<commit_before>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  this->setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  QTreeView::keyPressEvent(e);
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    deleteItem(currentIndex());
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = this->indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    if (dataSource->type() == DataSource::Volume) {
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  QAction* deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  QAction* selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 1) {
    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();
      if (tomviz::convert<pqSpreadSheetView*>(view)) {
        vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
        controller->Show(result->producerProxy(), 0, view);
      }
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(current);
  auto module = pipelineModel->module(current);
  if (dataSource) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (module) {
    ActiveObjects::instance().setActiveModule(module);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<commit_msg>When double clicking a table, open a spreadsheet if not available<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  this->setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  QTreeView::keyPressEvent(e);
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    deleteItem(currentIndex());
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = this->indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    if (dataSource->type() == DataSource::Volume) {
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  QAction* deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  QAction* selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 1) {
    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();
      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
      controller->ShowInPreferredView(result->producerProxy(), 0, view);
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(current);
  auto module = pipelineModel->module(current);
  if (dataSource) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (module) {
    ActiveObjects::instance().setActiveModule(module);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_filter.hxx"

#include "svgfilter.hxx"
#include "rtl/ref.hxx"
#include "jvmaccess/virtualmachine.hxx"
// -------------
// - SVGFilter -
// -------------

sal_Bool SVGFilter::implImport( const Sequence< PropertyValue >& rDescriptor )
    throw (RuntimeException)
{
    Reference< XMultiServiceFactory >   xServiceFactory( ::comphelper::getProcessServiceFactory() ) ;
    rtl::OUString                           aTmpFileName;
    String                              aFileName;
    sal_Int32                           nLength = rDescriptor.getLength();
    const PropertyValue*                pValue = rDescriptor.getConstArray();
    sal_Bool                            bRet = sal_False;

    for( sal_Int32 i = 0 ; ( i < nLength ) && !aTmpFileName.getLength(); i++)
        if( pValue[ i ].Name.equalsAscii( "FileName" ) )
            pValue[ i ].Value >>= aTmpFileName;

    if( aTmpFileName.getLength() && xServiceFactory.is() )
    {

        Reference< XJavaVM >    xJavaVM( xServiceFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), UNO_QUERY );
        Sequence< sal_Int8 >    aProcessID( 17 );
        String                  aLocalFile;

        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTmpFileName, aLocalFile ) && aLocalFile.Len() )
        {
            rtl_getGlobalProcessId( (sal_uInt8 *) aProcessID.getArray() );
            aProcessID[16] = 0;

            OSL_ENSURE(sizeof (sal_Int64)
                       >= sizeof (jvmaccess::VirtualMachine *),
                       "Pointer cannot be represented as sal_Int64");
            sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(
                static_cast< jvmaccess::VirtualMachine * >(0));
            xJavaVM->getJavaVM(aProcessID) >>= nPointer;
            rtl::Reference<jvmaccess::VirtualMachine> _virtualMachine =
                reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);
            if (!_virtualMachine.is())
                return bRet;

            jobjectArray    aArgs;
            jclass          aClass;
            jmethodID       aMId;
            jstring         aJStr;

            try
            {
                jvmaccess::VirtualMachine::AttachGuard vmGuard(_virtualMachine);

                JNIEnv * pEnv = vmGuard.getEnvironment();

                aClass = pEnv->FindClass( "SOTranscoder" );

                if( aClass )
                {
                    aMId = pEnv->GetStaticMethodID( aClass, "main", "([Ljava/lang/String;)V" );
                    if ( aMId )
                    {

                        ::utl::TempFile aTempFile;
                        String          aOutputURL( aTempFile.GetURL() );
                        String          aOutputFile;

                        aTempFile.EnableKillingFile();

                        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aOutputURL, aOutputFile ) && aOutputFile.Len() )
                        {
                            aJStr = pEnv->NewStringUTF( ByteString( aLocalFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );
                            aArgs = static_cast<jobjectArray>(pEnv->NewObjectArray( 2, pEnv->FindClass( "java/lang/String" ), aJStr ));
                            aJStr = pEnv->NewStringUTF( ByteString( aOutputFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );
                            pEnv->SetObjectArrayElement( aArgs, 1, aJStr );
                            pEnv->CallStaticVoidMethod( aClass, aMId, aArgs );

                            Graphic     aGraphic;
                            SvStream*   pIStm = ::utl::UcbStreamHelper::CreateStream( aOutputURL, STREAM_READ );

                            if( pIStm )
                            {
                                GraphicConverter::Import( *pIStm, aGraphic );
                                delete pIStm;
                            }

                            Reference< XDrawPagesSupplier > xDrawPagesSupplier( mxDstDoc, UNO_QUERY );

                            if( xDrawPagesSupplier.is() && ( aGraphic.GetType() != GRAPHIC_NONE ) )
                            {
                                Reference< XDrawPages > xDrawPages( xDrawPagesSupplier->getDrawPages() );

                                if( xDrawPages.is() && xDrawPages->getCount() )
                                {
                                    Reference< XDrawPage >  xDrawPage;

                                    if( xDrawPages->getByIndex( 0 ) >>= xDrawPage )
                                    {
                                        Reference< XShapes >        xShapes( xDrawPage, UNO_QUERY );
                                        Reference< XPropertySet>    xPagePropSet( xDrawPage, UNO_QUERY );
                                        Reference< XShape >         xShape( Reference< XMultiServiceFactory >( mxDstDoc, UNO_QUERY )->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.GraphicObjectShape" ) ) ), UNO_QUERY );

                                        if( xPagePropSet.is() && xShapes.is() && xShape.is() )
                                        {
                                            Reference< XPropertySet >   xPropSet( xShape, UNO_QUERY );
                                            sal_Int32                   nPageWidth = 0, nPageHeight = 0;

                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Width" ) ) ) >>= nPageWidth;
                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Height" ) ) ) >>= nPageHeight;

                                            if( xPropSet.is() && nPageWidth && nPageHeight )
                                            {
                                                xShapes->add( xShape );

                                                ::com::sun::star::awt::Point    aPos;
                                                ::com::sun::star::awt::Size     aSize;
                                                GraphicObject                   aGraphObj( aGraphic );
                                                String                          aGraphURL( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.GraphicObject:" ) );
                                                Any                             aValue;
                                                Size                            aGraphicSize;
                                                const MapMode                   aTargetMapMode( MAP_100TH_MM );

                                                if( aGraphObj.GetPrefMapMode().GetMapUnit() == MAP_PIXEL )
                                                    aGraphicSize = Application::GetDefaultDevice()->PixelToLogic( aGraphObj.GetPrefSize(), aTargetMapMode );
                                                else
                                                    aGraphicSize = OutputDevice::LogicToLogic( aGraphObj.GetPrefSize(), aGraphObj.GetPrefMapMode(), aTargetMapMode );

                                                aGraphURL += String( aGraphObj.GetUniqueID(), RTL_TEXTENCODING_ASCII_US );
                                                aValue <<= rtl::OUString( aGraphURL );
                                                xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GraphicURL" ) ), aValue );

                                                aPos.X = ( nPageWidth - aGraphicSize.Width() ) >> 1;
                                                aPos.Y = ( nPageHeight - aGraphicSize.Height() ) >> 1;

                                                aSize.Width = aGraphicSize.Width();
                                                aSize.Height = aGraphicSize.Height();

                                                xShape->setPosition( aPos );
                                                xShape->setSize( aSize );

                                                bRet = sal_True;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
            {
            }
        }
    }
    return bRet;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.8.216); FILE MERGED 2008/03/28 15:31:30 rt 1.8.216.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: svgimport.cxx,v $
 * $Revision: 1.9 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_filter.hxx"

#include "svgfilter.hxx"
#include "rtl/ref.hxx"
#include "jvmaccess/virtualmachine.hxx"
// -------------
// - SVGFilter -
// -------------

sal_Bool SVGFilter::implImport( const Sequence< PropertyValue >& rDescriptor )
    throw (RuntimeException)
{
    Reference< XMultiServiceFactory >   xServiceFactory( ::comphelper::getProcessServiceFactory() ) ;
    rtl::OUString                           aTmpFileName;
    String                              aFileName;
    sal_Int32                           nLength = rDescriptor.getLength();
    const PropertyValue*                pValue = rDescriptor.getConstArray();
    sal_Bool                            bRet = sal_False;

    for( sal_Int32 i = 0 ; ( i < nLength ) && !aTmpFileName.getLength(); i++)
        if( pValue[ i ].Name.equalsAscii( "FileName" ) )
            pValue[ i ].Value >>= aTmpFileName;

    if( aTmpFileName.getLength() && xServiceFactory.is() )
    {

        Reference< XJavaVM >    xJavaVM( xServiceFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), UNO_QUERY );
        Sequence< sal_Int8 >    aProcessID( 17 );
        String                  aLocalFile;

        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTmpFileName, aLocalFile ) && aLocalFile.Len() )
        {
            rtl_getGlobalProcessId( (sal_uInt8 *) aProcessID.getArray() );
            aProcessID[16] = 0;

            OSL_ENSURE(sizeof (sal_Int64)
                       >= sizeof (jvmaccess::VirtualMachine *),
                       "Pointer cannot be represented as sal_Int64");
            sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(
                static_cast< jvmaccess::VirtualMachine * >(0));
            xJavaVM->getJavaVM(aProcessID) >>= nPointer;
            rtl::Reference<jvmaccess::VirtualMachine> _virtualMachine =
                reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);
            if (!_virtualMachine.is())
                return bRet;

            jobjectArray    aArgs;
            jclass          aClass;
            jmethodID       aMId;
            jstring         aJStr;

            try
            {
                jvmaccess::VirtualMachine::AttachGuard vmGuard(_virtualMachine);

                JNIEnv * pEnv = vmGuard.getEnvironment();

                aClass = pEnv->FindClass( "SOTranscoder" );

                if( aClass )
                {
                    aMId = pEnv->GetStaticMethodID( aClass, "main", "([Ljava/lang/String;)V" );
                    if ( aMId )
                    {

                        ::utl::TempFile aTempFile;
                        String          aOutputURL( aTempFile.GetURL() );
                        String          aOutputFile;

                        aTempFile.EnableKillingFile();

                        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aOutputURL, aOutputFile ) && aOutputFile.Len() )
                        {
                            aJStr = pEnv->NewStringUTF( ByteString( aLocalFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );
                            aArgs = static_cast<jobjectArray>(pEnv->NewObjectArray( 2, pEnv->FindClass( "java/lang/String" ), aJStr ));
                            aJStr = pEnv->NewStringUTF( ByteString( aOutputFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );
                            pEnv->SetObjectArrayElement( aArgs, 1, aJStr );
                            pEnv->CallStaticVoidMethod( aClass, aMId, aArgs );

                            Graphic     aGraphic;
                            SvStream*   pIStm = ::utl::UcbStreamHelper::CreateStream( aOutputURL, STREAM_READ );

                            if( pIStm )
                            {
                                GraphicConverter::Import( *pIStm, aGraphic );
                                delete pIStm;
                            }

                            Reference< XDrawPagesSupplier > xDrawPagesSupplier( mxDstDoc, UNO_QUERY );

                            if( xDrawPagesSupplier.is() && ( aGraphic.GetType() != GRAPHIC_NONE ) )
                            {
                                Reference< XDrawPages > xDrawPages( xDrawPagesSupplier->getDrawPages() );

                                if( xDrawPages.is() && xDrawPages->getCount() )
                                {
                                    Reference< XDrawPage >  xDrawPage;

                                    if( xDrawPages->getByIndex( 0 ) >>= xDrawPage )
                                    {
                                        Reference< XShapes >        xShapes( xDrawPage, UNO_QUERY );
                                        Reference< XPropertySet>    xPagePropSet( xDrawPage, UNO_QUERY );
                                        Reference< XShape >         xShape( Reference< XMultiServiceFactory >( mxDstDoc, UNO_QUERY )->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.GraphicObjectShape" ) ) ), UNO_QUERY );

                                        if( xPagePropSet.is() && xShapes.is() && xShape.is() )
                                        {
                                            Reference< XPropertySet >   xPropSet( xShape, UNO_QUERY );
                                            sal_Int32                   nPageWidth = 0, nPageHeight = 0;

                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Width" ) ) ) >>= nPageWidth;
                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Height" ) ) ) >>= nPageHeight;

                                            if( xPropSet.is() && nPageWidth && nPageHeight )
                                            {
                                                xShapes->add( xShape );

                                                ::com::sun::star::awt::Point    aPos;
                                                ::com::sun::star::awt::Size     aSize;
                                                GraphicObject                   aGraphObj( aGraphic );
                                                String                          aGraphURL( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.GraphicObject:" ) );
                                                Any                             aValue;
                                                Size                            aGraphicSize;
                                                const MapMode                   aTargetMapMode( MAP_100TH_MM );

                                                if( aGraphObj.GetPrefMapMode().GetMapUnit() == MAP_PIXEL )
                                                    aGraphicSize = Application::GetDefaultDevice()->PixelToLogic( aGraphObj.GetPrefSize(), aTargetMapMode );
                                                else
                                                    aGraphicSize = OutputDevice::LogicToLogic( aGraphObj.GetPrefSize(), aGraphObj.GetPrefMapMode(), aTargetMapMode );

                                                aGraphURL += String( aGraphObj.GetUniqueID(), RTL_TEXTENCODING_ASCII_US );
                                                aValue <<= rtl::OUString( aGraphURL );
                                                xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GraphicURL" ) ), aValue );

                                                aPos.X = ( nPageWidth - aGraphicSize.Width() ) >> 1;
                                                aPos.Y = ( nPageHeight - aGraphicSize.Height() ) >> 1;

                                                aSize.Width = aGraphicSize.Width();
                                                aSize.Height = aGraphicSize.Height();

                                                xShape->setPosition( aPos );
                                                xShape->setSize( aSize );

                                                bRet = sal_True;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
            {
            }
        }
    }
    return bRet;
}

<|endoftext|>


<commit_before><commit_msg>- comment out references to bx_callback, which is no longer used<commit_after><|endoftext|>


<commit_before>#include "time-watch.h"

#include <taiju/line-reader.h>
#include <taiju/trie-builder.h>
#include <taiju/trie.h>
#include <taiju/trie-converter-factory.h>
#include <taiju/trie-factory.h>

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <exception>
#include <fstream>
#include <iostream>
#include <memory>
#include <set>
#include <sstream>
#include <vector>

static taiju::BuilderConfig taiju_config;

void read_keys(std::istream *in, std::vector<std::string> *keys)
{
	std::cerr << "reading keys..." << std::endl;
	taiju::TimeWatch watch;

	taiju::LineReader reader;
	reader.open(in);

	const char *key;
	std::size_t length;
	while (reader.read(&key, &length))
	{
		if (length > 0)
			keys->push_back(key);

		if (keys->size() % 100000 == 0)
		{
			std::cerr << "\rkeys: " << keys->size()
				<< ", time: " << watch.elapsed() << "s  ";
		}
	}
	std::cerr << "\rkeys: " << keys->size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;
}

void sort_keys(std::vector<std::string> *keys)
{
	std::cerr << "sorting keys..." << std::endl;
	taiju::TimeWatch watch;

	std::sort(keys->begin(), keys->end());
	keys->erase(std::unique(keys->begin(), keys->end()), keys->end());

	std::cerr << "keys: " << keys->size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;
}

void randomize_keys(const std::vector<std::string> &keys,
	std::vector<std::string> *rand_keys)
{
	std::cerr << "randomizing keys..." << std::endl;
	taiju::TimeWatch watch;

	std::vector<std::string>(keys).swap(*rand_keys);
	std::random_shuffle(rand_keys->begin(), rand_keys->end());

	std::cerr << "time: " << watch.elapsed() << 's' << std::endl;
}

void build_trie(const std::vector<std::string> &keys, taiju::Trie *trie)
{
	std::cerr << "building a trie..." << std::endl;
	taiju::TimeWatch watch;

	taiju::TrieBuilder builder;
	builder.open(taiju_config);
	for (std::size_t i = 0; i < keys.size(); ++i)
	{
		builder.append(keys[i].c_str(), keys[i].length());
		if (builder.num_keys() % 100000 == 0)
		{
			std::cerr << "\rkeys: " << builder.num_keys()
				<< ", nodes: " << builder.num_nodes()
				<< ", bytes: " << builder.size()
				<< ", time: " << watch.elapsed() << "s  ";
			if (builder.num_keys() % 10000000 == 0)
				std::cerr << '\n';
		}
	}
	builder.finish();
	std::cerr << "\rkeys: " << builder.num_keys()
		<< ", nodes: " << builder.num_nodes()
		<< ", bytes: " << builder.size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;

	std::stringstream stream;
	builder.write(&stream);
	builder.clear();
	trie->read(&stream);
}

std::auto_ptr<taiju::TrieBase> convert_trie(const taiju::Trie &src_trie,
	const std::vector<std::string> &keys)
{
	taiju::TimeWatch watch;

	std::auto_ptr<taiju::TrieConverterBase> converter(
		taiju::TrieConverterFactory::Create(taiju_config));
	std::printf(" %10s", converter->type_name());

	converter->convert(src_trie);

	// Note that the size of BP_TRIE or DFUDS_TRIE will be fixed in
	// the member function write().
	std::stringstream stream;
	converter->write(&stream);
	converter->clear();

	std::auto_ptr<taiju::TrieBase> dest_trie(
		taiju::TrieFactory::read(&stream));

	std::printf(" %7llukb %8.2fus", dest_trie->size() / 1000,
		1e+6 * watch.elapsed() / keys.size());

	return dest_trie;
}

void find_keys(const taiju::TrieBase &trie,
	const std::vector<std::string> &keys)
{
	taiju::TimeWatch watch;

	for (std::size_t i = 0; i < keys.size(); ++i)
	{
//		taiju::UInt64 key_id;
//		if (!trie.find(keys[i].c_str(), keys[i].length(), &key_id))
		if (!trie.find(keys[i].c_str(), keys[i].length()))
		{
			std::cerr << "error: failed to find a key: "
				<< keys[i] << std::endl;
			return;
		}
	}

	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / keys.size());
}

void benchmark_trie(taiju::TrieType trie_type, const taiju::Trie &src_trie,
	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	taiju_config.set_trie_type(trie_type);
	std::auto_ptr<taiju::TrieBase> dest_trie(convert_trie(src_trie, keys));

	find_keys(*dest_trie, keys);
	find_keys(*dest_trie, rand_keys);

	std::printf("\n");
}

void benchmark_baseline(	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	taiju::TimeWatch watch;

	std::printf(" %10s %9s", "std::set", "");
	std::set<std::string> set(rand_keys.begin(), rand_keys.end());
	std::printf(" %8.2fus", 1e+6 * watch.elapsed() / set.size());

	watch.reset();
	for (std::size_t i = 0; i < keys.size(); ++i)
		set.find(keys[i]);
	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / keys.size());

	watch.reset();
	for (std::size_t i = 0; i < rand_keys.size(); ++i)
		set.find(rand_keys[i]);
	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / rand_keys.size());

	std::printf("\n");
}

void benchmark_tries(const taiju::Trie &trie,
	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	std::printf("+----------+---------+----------+-------------------+\n");
	std::printf(" %10s %9s %10s %19s\n",
		"", "", "conversion", "lookup time");
	std::printf(" %10s %9s %10s %9s %9s\n",
		"type", "size", "time", "sorted", "random");
	std::printf("+----------+---------+----------+-------------------+\n");

	benchmark_baseline(keys, rand_keys);
	benchmark_trie(taiju::PODS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::LOB_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::LOUDS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::PLOUDS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::BP_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::DFUDS_TRIE, trie, keys, rand_keys);

	std::printf("+----------+---------+----------+-------------------+\n");
}

int main(int argc, char *argv[])
{
	try
	{
		taiju_config.parse(argc, argv, &argc);
	}
	catch (...)
	{
		std::cerr << taiju::BuilderConfig::help() << std::endl;
		return 1;
	}

	try
	{
		std::vector<std::string> keys;
		if (argc > 1 && std::strcmp(argv[1], "-") != 0)
		{
			std::ifstream file(argv[1], std::ios::binary);
			if (!file)
				TAIJU_THROW("failed to open input file");
			read_keys(&file, &keys);
		}
		else
			read_keys(&std::cin, &keys);

		sort_keys(&keys);

		std::vector<std::string> rand_keys;
		randomize_keys(keys, &rand_keys);

		taiju::Trie trie;
		build_trie(keys, &trie);

		benchmark_tries(trie, keys, rand_keys);
	}
	catch (const std::exception &ex)
	{
		std::cerr << ex.what() << std::endl;
		return 2;
	}

	return 0;
}
<commit_msg>The new taiju-benchmark shows the performance of the original PODS if the node order is not the default (ASCENDING_LABEL_ORDER or LABEL_ORDER).<commit_after>#include "time-watch.h"

#include <taiju/line-reader.h>
#include <taiju/trie-builder.h>
#include <taiju/trie.h>
#include <taiju/trie-converter-factory.h>
#include <taiju/trie-factory.h>

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <exception>
#include <fstream>
#include <iostream>
#include <memory>
#include <set>
#include <sstream>
#include <vector>

static taiju::BuilderConfig taiju_config;

void read_keys(std::istream *in, std::vector<std::string> *keys)
{
	std::cerr << "reading keys..." << std::endl;
	taiju::TimeWatch watch;

	taiju::LineReader reader;
	reader.open(in);

	const char *key;
	std::size_t length;
	while (reader.read(&key, &length))
	{
		if (length > 0)
			keys->push_back(key);

		if (keys->size() % 100000 == 0)
		{
			std::cerr << "\rkeys: " << keys->size()
				<< ", time: " << watch.elapsed() << "s  ";
		}
	}
	std::cerr << "\rkeys: " << keys->size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;
}

void sort_keys(std::vector<std::string> *keys)
{
	std::cerr << "sorting keys..." << std::endl;
	taiju::TimeWatch watch;

	std::sort(keys->begin(), keys->end());
	keys->erase(std::unique(keys->begin(), keys->end()), keys->end());

	std::cerr << "keys: " << keys->size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;
}

void randomize_keys(const std::vector<std::string> &keys,
	std::vector<std::string> *rand_keys)
{
	std::cerr << "randomizing keys..." << std::endl;
	taiju::TimeWatch watch;

	std::vector<std::string>(keys).swap(*rand_keys);
	std::random_shuffle(rand_keys->begin(), rand_keys->end());

	std::cerr << "time: " << watch.elapsed() << 's' << std::endl;
}

void build_trie(const std::vector<std::string> &keys, taiju::Trie *trie)
{
	std::cerr << "building a trie..." << std::endl;
	taiju::TimeWatch watch;

	taiju::TrieBuilder builder;
	builder.open(taiju_config);
	for (std::size_t i = 0; i < keys.size(); ++i)
	{
		builder.append(keys[i].c_str(), keys[i].length());
		if (builder.num_keys() % 100000 == 0)
		{
			std::cerr << "\rkeys: " << builder.num_keys()
				<< ", nodes: " << builder.num_nodes()
				<< ", bytes: " << builder.size()
				<< ", time: " << watch.elapsed() << "s  ";
			if (builder.num_keys() % 10000000 == 0)
				std::cerr << '\n';
		}
	}
	builder.finish();
	std::cerr << "\rkeys: " << builder.num_keys()
		<< ", nodes: " << builder.num_nodes()
		<< ", bytes: " << builder.size()
		<< ", time: " << watch.elapsed() << 's' << std::endl;

	std::stringstream stream;
	builder.write(&stream);
	builder.clear();
	trie->read(&stream);
}

std::auto_ptr<taiju::TrieBase> convert_trie(const taiju::Trie &src_trie,
	const std::vector<std::string> &keys)
{
	taiju::TimeWatch watch;

	std::auto_ptr<taiju::TrieConverterBase> converter(
		taiju::TrieConverterFactory::Create(taiju_config));
	std::printf(" %10s", converter->type_name());

	converter->convert(src_trie);

	// Note that the size of BP_TRIE or DFUDS_TRIE will be fixed in
	// the member function write().
	std::stringstream stream;
	converter->write(&stream);
	converter->clear();

	std::auto_ptr<taiju::TrieBase> dest_trie(
		taiju::TrieFactory::read(&stream));

	std::printf(" %7llukb %8.2fus", dest_trie->size() / 1000,
		1e+6 * watch.elapsed() / keys.size());

	return dest_trie;
}

void find_keys(const taiju::TrieBase &trie,
	const std::vector<std::string> &keys)
{
	taiju::TimeWatch watch;

	for (std::size_t i = 0; i < keys.size(); ++i)
	{
//		taiju::UInt64 key_id;
//		if (!trie.find(keys[i].c_str(), keys[i].length(), &key_id))
		if (!trie.find(keys[i].c_str(), keys[i].length()))
		{
			std::cerr << "error: failed to find a key: "
				<< keys[i] << std::endl;
			return;
		}
	}

	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / keys.size());
}

void benchmark_trie(taiju::TrieType trie_type, const taiju::Trie &src_trie,
	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	taiju_config.set_trie_type(trie_type);
	std::auto_ptr<taiju::TrieBase> dest_trie(convert_trie(src_trie, keys));

	find_keys(*dest_trie, keys);
	find_keys(*dest_trie, rand_keys);

	std::printf("\n");
}

void benchmark_baseline(	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	taiju::TimeWatch watch;

	std::printf(" %10s %9s", "std::set", "");
	std::set<std::string> set(rand_keys.begin(), rand_keys.end());
	std::printf(" %8.2fus", 1e+6 * watch.elapsed() / set.size());

	watch.reset();
	for (std::size_t i = 0; i < keys.size(); ++i)
		set.find(keys[i]);
	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / keys.size());

	watch.reset();
	for (std::size_t i = 0; i < rand_keys.size(); ++i)
		set.find(rand_keys[i]);
	std::printf(" %7.2fus", 1e+6 * watch.elapsed() / rand_keys.size());

	std::printf("\n");
}

void benchmark_tries(const taiju::Trie &trie,
	const std::vector<std::string> &keys,
	const std::vector<std::string> &rand_keys)
{
	std::printf("+----------+---------+----------+-------------------+\n");
	std::printf(" %10s %9s %10s %19s\n",
		"", "", "conversion", "lookup time");
	std::printf(" %10s %9s %10s %9s %9s\n",
		"type", "size", "time", "sorted", "random");
	std::printf("+----------+---------+----------+-------------------+\n");

	benchmark_baseline(keys, rand_keys);

	if (taiju_config.node_order() != taiju::LABEL_ORDER)
	{
		std::printf(" %10s", trie.type_name());
		std::printf(" %7llukb %8sus", trie.size() / 1000, "- ");
		find_keys(trie, keys);
		find_keys(trie, rand_keys);
		std::printf("\n");
	}

	benchmark_trie(taiju::PODS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::LOB_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::LOUDS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::PLOUDS_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::BP_TRIE, trie, keys, rand_keys);
	benchmark_trie(taiju::DFUDS_TRIE, trie, keys, rand_keys);

	std::printf("+----------+---------+----------+-------------------+\n");
}

int main(int argc, char *argv[])
{
	try
	{
		taiju_config.parse(argc, argv, &argc);
	}
	catch (...)
	{
		std::cerr << taiju::BuilderConfig::help() << std::endl;
		return 1;
	}

	try
	{
		std::vector<std::string> keys;
		if (argc > 1 && std::strcmp(argv[1], "-") != 0)
		{
			std::ifstream file(argv[1], std::ios::binary);
			if (!file)
				TAIJU_THROW("failed to open input file");
			read_keys(&file, &keys);
		}
		else
			read_keys(&std::cin, &keys);

		sort_keys(&keys);

		std::vector<std::string> rand_keys;
		randomize_keys(keys, &rand_keys);

		taiju::Trie trie;
		build_trie(keys, &trie);

		benchmark_tries(trie, keys, rand_keys);
	}
	catch (const std::exception &ex)
	{
		std::cerr << ex.what() << std::endl;
		return 2;
	}

	return 0;
}
<|endoftext|>


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

#include "common/error.h"
#include "common/io.h"

#ifndef SHADERS_DIR
#define SHADERS_DIR "./shaders/"
#endif

const float vertices[] = {
     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, // vertex 1: Red
     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, // vertex 2: Green
    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  // vertex 3: Blue
};

enum class ShaderType {vertex, fragment};

/**
 * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.
 */
GLuint compileShader(const std::string& filename, ShaderType type) {
    auto source = readFile(SHADERS_DIR + filename).c_str();
    auto gl_type = GL_VERTEX_SHADER;
    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;

    GLuint shader = glCreateShader(gl_type);
    glShaderSource(shader, 1, &source, NULL);
    glCompileShader(shader);
    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    if (status != GL_TRUE) {
        std::cerr << "Failed to compile shader:\n";
        std::cerr << source << std::endl;
        std::cerr << "************************************\n";
        char buffer[512];
        glGetShaderInfoLog(shader, 512, NULL, buffer);
        std::cerr << buffer;
        throw Exception();
    }
    printGlErrors();
    return shader;
}

void initGlew() {
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    printGlErrors();
    if(err != GLEW_OK) {
        throw Exception("glewInit failed");
    }
}

/**
 * Return ID of the linked and activated shader.
 */
GLuint initShaders() {
    auto vshader = compileShader("vshader.glsl", ShaderType::vertex);
    auto fshader = compileShader("fshader.glsl", ShaderType::fragment);
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vshader);
    glAttachShader(shaderProgram, fshader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
    printGlErrors();
    return shaderProgram;
}

SDL_GLContext initContext(SDL_Window *window) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GLContext context = SDL_GL_CreateContext(window);
    printGlErrors();
    return context;
}

/**
 * Copy buffers to memory, set shader attributes, bind to VAO.
 * Return bound VAO ID.
 */
GLuint initBuffers(GLuint shaderProgram) {
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), 0);

    GLint colorAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colorAttrib);
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), (void*)(2*sizeof(float)));

    GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
    printGlErrors();
    return vao;
}

void paint() {
    glDrawArrays(GL_TRIANGLES, 0, 3);
    printGlErrors();
}

int main(int argc, char *argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                           100, 100, 800, 600,
                                           SDL_WINDOW_OPENGL);
    auto context = initContext(window);
    initGlew();
    auto program = initShaders();
    initBuffers(program);

    paint();

    SDL_Event event;
    while (true) {
        if (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) break;
            if (event.type == SDL_KEYDOWN) break;
        }
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
<commit_msg>tutorial: fix odd problem with shader not loading<commit_after>/* Copyright 2015 Martina Kollarova
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <iostream>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_opengl.h>

#include "common/error.h"
#include "common/io.h"

#ifndef SHADERS_DIR
#define SHADERS_DIR "./shaders/"
#endif

const float vertices[] = {
     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, // vertex 1: Red
     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, // vertex 2: Green
    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  // vertex 3: Blue
};

enum class ShaderType {vertex, fragment};

/**
 * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.
 */
GLuint compileShader(const std::string& filename, ShaderType type) {
    std::string source = readFile(SHADERS_DIR + filename);
    if (source.length() == 0)
      throw Exception("empty shader file");
    auto gl_type = GL_VERTEX_SHADER;
    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;

    GLuint shader = glCreateShader(gl_type);
    const char* source_c = source.c_str();
    glShaderSource(shader, 1, &source_c, NULL);
    glCompileShader(shader);
    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    if (status != GL_TRUE) {
        std::cerr << "Failed to compile shader:\n";
        std::cerr << source << std::endl;
        std::cerr << "************************************\n";
        char buffer[512];
        glGetShaderInfoLog(shader, 512, NULL, buffer);
        std::cerr << buffer;
        throw Exception();
    }
    printGlErrors();
    return shader;
}

void initGlew() {
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    printGlErrors();
    if(err != GLEW_OK) {
        throw Exception("glewInit failed");
    }
}

/**
 * Return ID of the linked and activated shader.
 */
GLuint initShaders() {
    auto vshader = compileShader("vshader.glsl", ShaderType::vertex);
    auto fshader = compileShader("fshader.glsl", ShaderType::fragment);
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vshader);
    glAttachShader(shaderProgram, fshader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
    printGlErrors();
    return shaderProgram;
}

SDL_GLContext initContext(SDL_Window *window) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GLContext context = SDL_GL_CreateContext(window);
    printGlErrors();
    return context;
}

/**
 * Copy buffers to memory, set shader attributes, bind to VAO.
 * Return bound VAO ID.
 */
GLuint initBuffers(GLuint shaderProgram) {
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), 0);

    GLint colorAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colorAttrib);
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), (void*)(2*sizeof(float)));

    GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
    printGlErrors();
    return vao;
}

void paint() {
    glDrawArrays(GL_TRIANGLES, 0, 3);
    printGlErrors();
}

int main(int argc, char *argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                           100, 100, 800, 600,
                                           SDL_WINDOW_OPENGL);
    auto context = initContext(window);
    initGlew();
    auto program = initShaders();
    initBuffers(program);

    paint();

    SDL_Event event;
    while (true) {
        if (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) break;
            if (event.type == SDL_KEYDOWN) break;
        }
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
<|endoftext|>


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

#include <misc/files.h>
#include <misc/opt.hpp>

#include "server.h"

using namespace ydsh;
using namespace lsp;

#define EACH_OPT(OP)                                                                               \
  OP(LOG, "--log", opt::HAS_ARG,                                                                   \
     "specify log level (info, warning, error, fatal, none). default is `info'")                   \
  OP(HELP, "--help", opt::NO_ARG, "show this help message")                                        \
  OP(LSP, "--language-server", opt::NO_ARG, "enable language server features (default)")

enum class OptionKind {
#define GEN_ENUM(E, S, F, D) E,
  EACH_OPT(GEN_ENUM)
#undef GEN_ENUM
};

struct Options {
  LogLevel level{LogLevel::INFO};
  bool lsp{true};
};

static LogLevel parseLogLevel(const char *value, LogLevel v) {
  LogLevel levels[] = {LogLevel::INFO, LogLevel::WARNING, LogLevel::ERROR, LogLevel::FATAL,
                       LogLevel::NONE};
  for (auto &l : levels) {
    const char *ls = toString(l);
    if (strcasecmp(ls, value) == 0) {
      return l;
    }
  }
  return v;
}

static Options parseOptions(int argc, char **argv) {
  opt::Parser<OptionKind> optParser = {
#define GEN_OPT(E, S, F, D) {OptionKind::E, S, F, D},
      EACH_OPT(GEN_OPT)
#undef GEN_OPT
  };
  auto begin = argv + (argc > 0 ? 1 : 0);
  auto end = argv + argc;
  opt::Result<OptionKind> result;
  Options options;
  while ((result = optParser(begin, end))) {
    switch (result.value()) {
    case OptionKind::LOG:
      options.level = parseLogLevel(result.arg(), LogLevel::INFO);
      break;
    case OptionKind::HELP:
      optParser.printOption(stdout);
      exit(0);
    case OptionKind::LSP:
      options.lsp = true;
      break;
    }
  }
  if (result.error() != opt::END) {
    fprintf(stderr, "%s\n", result.formatError().c_str());
    optParser.printOption(stderr);
    exit(1);
  }
  return options;
}

static void showInfo(LSPLogger &logger) {
  fprintf(stderr, "start ydsh code analyzer\n");
  fflush(stderr);
  logger(LogLevel::INFO, "working directory: %s", getCWD().get());
}

int main(int argc, char **argv) {
  auto options = parseOptions(argc, argv);
  LSPLogger logger;
  logger.setSeverity(options.level);
  logger.setAppender(FilePtr(stderr));
  showInfo(logger);
  LSPServer server(logger, FilePtr(stdin), FilePtr(stdout));
  server.run();
}
<commit_msg>show command line options after startup<commit_after>/*
 * Copyright (C) 2018 Nagisa Sekiguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <misc/files.h>
#include <misc/opt.hpp>

#include "server.h"

using namespace ydsh;
using namespace lsp;

#define EACH_OPT(OP)                                                                               \
  OP(LOG, "--log", opt::HAS_ARG,                                                                   \
     "specify log level (info, warning, error, fatal, none). default is `info'")                   \
  OP(HELP, "--help", opt::NO_ARG, "show this help message")                                        \
  OP(LSP, "--language-server", opt::NO_ARG, "enable language server features (default)")

enum class OptionKind {
#define GEN_ENUM(E, S, F, D) E,
  EACH_OPT(GEN_ENUM)
#undef GEN_ENUM
};

struct Options {
  LogLevel level{LogLevel::INFO};
  bool lsp{true};
};

static LogLevel parseLogLevel(const char *value, LogLevel v) {
  LogLevel levels[] = {LogLevel::INFO, LogLevel::WARNING, LogLevel::ERROR, LogLevel::FATAL,
                       LogLevel::NONE};
  for (auto &l : levels) {
    const char *ls = toString(l);
    if (strcasecmp(ls, value) == 0) {
      return l;
    }
  }
  return v;
}

static Options parseOptions(int argc, char **argv) {
  opt::Parser<OptionKind> optParser = {
#define GEN_OPT(E, S, F, D) {OptionKind::E, S, F, D},
      EACH_OPT(GEN_OPT)
#undef GEN_OPT
  };
  auto begin = argv + (argc > 0 ? 1 : 0);
  auto end = argv + argc;
  opt::Result<OptionKind> result;
  Options options;
  while ((result = optParser(begin, end))) {
    switch (result.value()) {
    case OptionKind::LOG:
      options.level = parseLogLevel(result.arg(), LogLevel::INFO);
      break;
    case OptionKind::HELP:
      optParser.printOption(stdout);
      exit(0);
    case OptionKind::LSP:
      options.lsp = true;
      break;
    }
  }
  if (result.error() != opt::END) {
    fprintf(stderr, "%s\n", result.formatError().c_str());
    optParser.printOption(stderr);
    exit(1);
  }
  return options;
}

static void showInfo(char **const argv, LSPLogger &logger) {
  std::string cmdline;
  for(unsigned int i = 0; argv[i]; i++) {
    if(!cmdline.empty()) {
      cmdline += ' ';
    }
    cmdline += argv[i];
  }
  fprintf(stderr, "start ydsh code analyzer with the following options\n");
  fprintf(stderr, "    %s\n", cmdline.c_str());
  fflush(stderr);
  logger(LogLevel::INFO, "working directory: %s", getCWD().get());
}

int main(int argc, char **argv) {
  auto options = parseOptions(argc, argv);
  LSPLogger logger;
  logger.setSeverity(options.level);
  logger.setAppender(FilePtr(stderr));
  showInfo(argv, logger);
  LSPServer server(logger, FilePtr(stdin), FilePtr(stdout));
  server.run();
}
<|endoftext|>


<commit_before>//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang driver; it is a thin wrapper
// for functionality in the Driver clang library.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Option.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/config.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace clang::driver;

class DriverDiagnosticPrinter : public DiagnosticClient {
  std::string ProgName;
  llvm::raw_ostream &OS;

public:
  DriverDiagnosticPrinter(const std::string _ProgName,
                          llvm::raw_ostream &_OS)
    : ProgName(_ProgName),
      OS(_OS) {}

  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
                                const DiagnosticInfo &Info);
};

void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
                                               const DiagnosticInfo &Info) {
  OS << ProgName << ": ";

  switch (Level) {
  case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
  case Diagnostic::Note:    OS << "note: "; break;
  case Diagnostic::Warning: OS << "warning: "; break;
  case Diagnostic::Error:   OS << "error: "; break;
  case Diagnostic::Fatal:   OS << "fatal error: "; break;
  }

  llvm::SmallString<100> OutStr;
  Info.FormatDiagnostic(OutStr);
  OS.write(OutStr.begin(), OutStr.size());
  OS << '\n';
}

llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
  if (!CanonicalPrefixes)
    return llvm::sys::Path(Argv0);

  // This just needs to be some symbol in the binary; C++ doesn't
  // allow taking the address of ::main however.
  void *P = (void*) (intptr_t) GetExecutablePath;
  return llvm::sys::Path::GetMainExecutable(Argv0, P);
}

static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
                                   const std::string &S) {
  return SavedStrings.insert(S).first->c_str();
}

/// ApplyQAOverride - Apply a list of edits to the input argument lists.
///
/// The input string is a space separate list of edits to perform,
/// they are applied in order to the input argument lists. Edits
/// should be one of the following forms:
///
///  '#': Silence information about the changes to the command line arguments.
///
///  '^': Add FOO as a new argument at the beginning of the command line.
///
///  '+': Add FOO as a new argument at the end of the command line.
///
///  's/XXX/YYY/': Replace the literal argument XXX by YYY in the
///  command line.
///
///  'xOPTION': Removes all instances of the literal argument OPTION.
///
///  'XOPTION': Removes all instances of the literal argument OPTION,
///  and the following argument.
///
///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
///  at the end of the command line.
///
/// \param OS - The stream to write edit information to.
/// \param Args - The vector of command line arguments.
/// \param Edit - The override command to perform.
/// \param SavedStrings - Set to use for storing string representations.
void ApplyOneQAOverride(llvm::raw_ostream &OS,
                        std::vector<const char*> &Args,
                        const std::string &Edit,
                        std::set<std::string> &SavedStrings) {
  // This does not need to be efficient.

  if (Edit[0] == '^') {
    const char *Str =
      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
    OS << "### Adding argument " << Str << " at beginning\n";
    Args.insert(Args.begin() + 1, Str);
  } else if (Edit[0] == '+') {
    const char *Str =
      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
    OS << "### Adding argument " << Str << " at end\n";
    Args.push_back(Str);
  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
    std::string Option = Edit.substr(1, std::string::npos);
    for (unsigned i = 1; i < Args.size();) {
      if (Option == Args[i]) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
        if (Edit[0] == 'X') {
          if (i < Args.size()) {
            OS << "### Deleting argument " << Args[i] << '\n';
            Args.erase(Args.begin() + i);
          } else
            OS << "### Invalid X edit, end of command line!\n";
        }
      } else
        ++i;
    }
  } else if (Edit[0] == 'O') {
    for (unsigned i = 1; i < Args.size();) {
      const char *A = Args[i];
      if (A[0] == '-' && A[1] == 'O' &&
          (A[2] == '\0' ||
           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
                             ('0' <= A[2] && A[2] <= '9'))))) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
      } else
        ++i;
    }
    OS << "### Adding argument " << Edit << " at end\n";
    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));
  } else {
    OS << "### Unrecognized edit: " << Edit << "\n";
  }
}

/// ApplyQAOverride - Apply a comma separate list of edits to the
/// input argument lists. See ApplyOneQAOverride.
void ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,
                     std::set<std::string> &SavedStrings) {
  llvm::raw_ostream *OS = &llvm::errs();

  if (OverrideStr[0] == '#') {
    ++OverrideStr;
    OS = &llvm::nulls();
  }

  *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";

  // This does not need to be efficient.

  const char *S = OverrideStr;
  while (*S) {
    const char *End = ::strchr(S, ' ');
    if (!End)
      End = S + strlen(S);
    if (End != S)
      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
    S = End;
    if (*S != '\0')
      ++S;
  }
}

extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
                    const char *Argv0, void *MainAddr);

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);

  // Dispatch to cc1_main if appropriate.
  if (argc > 1 && llvm::StringRef(argv[1]) == "-cc1")
    return cc1_main(argv+2, argv+argc, argv[0],
                    (void*) (intptr_t) GetExecutablePath);

  bool CanonicalPrefixes = true;
  for (int i = 1; i < argc; ++i) {
    if (llvm::StringRef(argv[i]) == "-no-canonical-prefixes") {
      CanonicalPrefixes = false;
      break;
    }
  }

  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);

  DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());

  Diagnostic Diags(&DiagClient);

#ifdef CLANG_IS_PRODUCTION
  bool IsProduction = true;
#else
  bool IsProduction = false;
#endif
  Driver TheDriver(Path.getBasename(), Path.getDirname(),
                   llvm::sys::getHostTriple(),
                   "a.out", IsProduction, Diags);

  // Check for ".*++" or ".*++-[^-]*" to determine if we are a C++
  // compiler. This matches things like "c++", "clang++", and "clang++-1.1".
  //
  // Note that we intentionally want to use argv[0] here, to support "clang++"
  // being a symlink.
  //
  // We use *argv instead of argv[0] to work around a bogus g++ warning.
  std::string ProgName(llvm::sys::Path(*argv).getBasename());
  if (llvm::StringRef(ProgName).endswith("++") ||
      llvm::StringRef(ProgName).rsplit('-').first.endswith("++"))
    TheDriver.CCCIsCXX = true;

  llvm::OwningPtr<Compilation> C;

  // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
  // command line behind the scenes.
  std::set<std::string> SavedStrings;
  if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
    // FIXME: Driver shouldn't take extra initial argument.
    std::vector<const char*> StringPointers(argv, argv + argc);

    ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);

    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
                                       &StringPointers[0]));
  } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
    std::vector<const char*> StringPointers;

    // FIXME: Driver shouldn't take extra initial argument.
    StringPointers.push_back(argv[0]);

    for (;;) {
      const char *Next = strchr(Cur, ',');

      if (Next) {
        StringPointers.push_back(SaveStringInSet(SavedStrings,
                                                 std::string(Cur, Next)));
        Cur = Next + 1;
      } else {
        if (*Cur != '\0')
          StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));
        break;
      }
    }

    StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);

    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
                                       &StringPointers[0]));
  } else
    C.reset(TheDriver.BuildCompilation(argc, argv));

  int Res = 0;
  if (C.get())
    Res = TheDriver.ExecuteCompilation(*C);

  llvm::llvm_shutdown();

  return Res;
}
<commit_msg>Driver: Use "g++" as generic gcc name when running in C++ mode, for platforms that lack real tool definitions.<commit_after>//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang driver; it is a thin wrapper
// for functionality in the Driver clang library.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Option.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/config.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace clang::driver;

class DriverDiagnosticPrinter : public DiagnosticClient {
  std::string ProgName;
  llvm::raw_ostream &OS;

public:
  DriverDiagnosticPrinter(const std::string _ProgName,
                          llvm::raw_ostream &_OS)
    : ProgName(_ProgName),
      OS(_OS) {}

  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
                                const DiagnosticInfo &Info);
};

void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
                                               const DiagnosticInfo &Info) {
  OS << ProgName << ": ";

  switch (Level) {
  case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
  case Diagnostic::Note:    OS << "note: "; break;
  case Diagnostic::Warning: OS << "warning: "; break;
  case Diagnostic::Error:   OS << "error: "; break;
  case Diagnostic::Fatal:   OS << "fatal error: "; break;
  }

  llvm::SmallString<100> OutStr;
  Info.FormatDiagnostic(OutStr);
  OS.write(OutStr.begin(), OutStr.size());
  OS << '\n';
}

llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
  if (!CanonicalPrefixes)
    return llvm::sys::Path(Argv0);

  // This just needs to be some symbol in the binary; C++ doesn't
  // allow taking the address of ::main however.
  void *P = (void*) (intptr_t) GetExecutablePath;
  return llvm::sys::Path::GetMainExecutable(Argv0, P);
}

static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
                                   const std::string &S) {
  return SavedStrings.insert(S).first->c_str();
}

/// ApplyQAOverride - Apply a list of edits to the input argument lists.
///
/// The input string is a space separate list of edits to perform,
/// they are applied in order to the input argument lists. Edits
/// should be one of the following forms:
///
///  '#': Silence information about the changes to the command line arguments.
///
///  '^': Add FOO as a new argument at the beginning of the command line.
///
///  '+': Add FOO as a new argument at the end of the command line.
///
///  's/XXX/YYY/': Replace the literal argument XXX by YYY in the
///  command line.
///
///  'xOPTION': Removes all instances of the literal argument OPTION.
///
///  'XOPTION': Removes all instances of the literal argument OPTION,
///  and the following argument.
///
///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
///  at the end of the command line.
///
/// \param OS - The stream to write edit information to.
/// \param Args - The vector of command line arguments.
/// \param Edit - The override command to perform.
/// \param SavedStrings - Set to use for storing string representations.
void ApplyOneQAOverride(llvm::raw_ostream &OS,
                        std::vector<const char*> &Args,
                        const std::string &Edit,
                        std::set<std::string> &SavedStrings) {
  // This does not need to be efficient.

  if (Edit[0] == '^') {
    const char *Str =
      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
    OS << "### Adding argument " << Str << " at beginning\n";
    Args.insert(Args.begin() + 1, Str);
  } else if (Edit[0] == '+') {
    const char *Str =
      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
    OS << "### Adding argument " << Str << " at end\n";
    Args.push_back(Str);
  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
    std::string Option = Edit.substr(1, std::string::npos);
    for (unsigned i = 1; i < Args.size();) {
      if (Option == Args[i]) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
        if (Edit[0] == 'X') {
          if (i < Args.size()) {
            OS << "### Deleting argument " << Args[i] << '\n';
            Args.erase(Args.begin() + i);
          } else
            OS << "### Invalid X edit, end of command line!\n";
        }
      } else
        ++i;
    }
  } else if (Edit[0] == 'O') {
    for (unsigned i = 1; i < Args.size();) {
      const char *A = Args[i];
      if (A[0] == '-' && A[1] == 'O' &&
          (A[2] == '\0' ||
           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
                             ('0' <= A[2] && A[2] <= '9'))))) {
        OS << "### Deleting argument " << Args[i] << '\n';
        Args.erase(Args.begin() + i);
      } else
        ++i;
    }
    OS << "### Adding argument " << Edit << " at end\n";
    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));
  } else {
    OS << "### Unrecognized edit: " << Edit << "\n";
  }
}

/// ApplyQAOverride - Apply a comma separate list of edits to the
/// input argument lists. See ApplyOneQAOverride.
void ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,
                     std::set<std::string> &SavedStrings) {
  llvm::raw_ostream *OS = &llvm::errs();

  if (OverrideStr[0] == '#') {
    ++OverrideStr;
    OS = &llvm::nulls();
  }

  *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";

  // This does not need to be efficient.

  const char *S = OverrideStr;
  while (*S) {
    const char *End = ::strchr(S, ' ');
    if (!End)
      End = S + strlen(S);
    if (End != S)
      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
    S = End;
    if (*S != '\0')
      ++S;
  }
}

extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
                    const char *Argv0, void *MainAddr);

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);

  // Dispatch to cc1_main if appropriate.
  if (argc > 1 && llvm::StringRef(argv[1]) == "-cc1")
    return cc1_main(argv+2, argv+argc, argv[0],
                    (void*) (intptr_t) GetExecutablePath);

  bool CanonicalPrefixes = true;
  for (int i = 1; i < argc; ++i) {
    if (llvm::StringRef(argv[i]) == "-no-canonical-prefixes") {
      CanonicalPrefixes = false;
      break;
    }
  }

  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);

  DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());

  Diagnostic Diags(&DiagClient);

#ifdef CLANG_IS_PRODUCTION
  bool IsProduction = true;
#else
  bool IsProduction = false;
#endif
  Driver TheDriver(Path.getBasename(), Path.getDirname(),
                   llvm::sys::getHostTriple(),
                   "a.out", IsProduction, Diags);

  // Check for ".*++" or ".*++-[^-]*" to determine if we are a C++
  // compiler. This matches things like "c++", "clang++", and "clang++-1.1".
  //
  // Note that we intentionally want to use argv[0] here, to support "clang++"
  // being a symlink.
  //
  // We use *argv instead of argv[0] to work around a bogus g++ warning.
  std::string ProgName(llvm::sys::Path(*argv).getBasename());
  if (llvm::StringRef(ProgName).endswith("++") ||
      llvm::StringRef(ProgName).rsplit('-').first.endswith("++")) {
    TheDriver.CCCIsCXX = true;
    TheDriver.CCCGenericGCCName = "g++";
  }

  llvm::OwningPtr<Compilation> C;

  // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
  // command line behind the scenes.
  std::set<std::string> SavedStrings;
  if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
    // FIXME: Driver shouldn't take extra initial argument.
    std::vector<const char*> StringPointers(argv, argv + argc);

    ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);

    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
                                       &StringPointers[0]));
  } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
    std::vector<const char*> StringPointers;

    // FIXME: Driver shouldn't take extra initial argument.
    StringPointers.push_back(argv[0]);

    for (;;) {
      const char *Next = strchr(Cur, ',');

      if (Next) {
        StringPointers.push_back(SaveStringInSet(SavedStrings,
                                                 std::string(Cur, Next)));
        Cur = Next + 1;
      } else {
        if (*Cur != '\0')
          StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));
        break;
      }
    }

    StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);

    C.reset(TheDriver.BuildCompilation(StringPointers.size(),
                                       &StringPointers[0]));
  } else
    C.reset(TheDriver.BuildCompilation(argc, argv));

  int Res = 0;
  if (C.get())
    Res = TheDriver.ExecuteCompilation(*C);

  llvm::llvm_shutdown();

  return Res;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include <stdint.h>
#include <unistd.h>

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>

#ifndef WIN32
#define _FILE_OFFSET_BITS 64
#define MYSEEK64 fseek
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#undef BLOCK_SIZE
#else
#define MYSEEK64 _fseeki64
#endif

/********************  SETTINGS  ********************/
// SDIO Settings
#define BLOCK_SIZE              512ULL   /* SD card block size in Bytes (512 for a normal SD card) */

// Logger settings
#define RX_BUFFER_NUM_BLOCKS    20ULL /* 20 blocks * 512 = 10 KB RAM required per buffer*/
/**************   END OF SETTINGS   *****************/

#define BUFF_SIZE  (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)

// max card size supported is 8MB
uint64_t disk_size = 8ULL*1024ULL*1024ULL*1024ULL;

void format_disk_raw(char* volume_name)
{
    FILE *volume;
    int k = 0;
    char buf[BUFF_SIZE] = {0, 0, 0, 0, 0};

	int i;

	printf("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nWe will block-format drive '%s' \nAre you absolutely sure? Then type 1324: ",volume_name);
	std::cin >> i;
	if (i != 1324)
	{
		printf("\n...\nAborting...\n");
		return;
	}

#ifdef WIN32
	uint64_t sd = disk_size;
	sd /= 1024ULL * 1024ULL;
	printf("\nExpecting an SD-card of %llu MB.\n",sd);
#else
	int fd = open(volume_name, O_RDONLY);

	uint64_t sdcard_disk_size;
	ioctl(fd, BLKGETSIZE64, &sdcard_disk_size);
	close(fd);
	uint64_t sd = sdcard_disk_size / 1024ULL / 1024ULL;

	if (sd != 0)
	{
		disk_size = sdcard_disk_size;
		printf("Found an SG card of %llu MB %llu\n",sd, disk_size);
	} else {
		sd = disk_size / (1024ULL * 1024ULL);
		printf("\nExpecting an SD-card of %llu MB.\n",sd);
	}
#endif

    volume = fopen(volume_name, "w+b");
    if(!volume)
    {
        printf("Cant open Drive '%s'\n", volume_name);
        return;
    }
    setbuf(volume, NULL);       // Disable buffering

	printf("\nFormatting entire SDCard '%s': \n...\r",volume_name);
	sleep(3);

	uint64_t addr = 0;

	addr= 0x2000 * BLOCK_SIZE;

	if(MYSEEK64(volume, addr, SEEK_SET) != 0)
	{
		printf("Can't move to sector\n");
		fclose(volume);
		return;
	}

	fwrite(buf, 5, 1, volume);

	addr = 0;
    // read what is in sector and put in buf //
	while (addr < disk_size)
	{
		printf(".");

		if(MYSEEK64(volume, addr, SEEK_SET) != 0)
		{
			printf("Can't move to sector\n");
			break;
		}

		fwrite(buf, 1, 1, volume);

		int f = feof(volume);
		int e = ferror(volume);

		if (f!=0)
		{
			printf("End of file system found at addr %lluX: \n",addr);
			break;
		}
		printf("Format success until %llu: \n",addr);

		addr += BUFF_SIZE;
	}

    fclose(volume);

    return;
}

int main(int argc, char** argv)
{
	char outfilename[2048] = "";

    printf("FORMAT SDCARD:\n-------------\n");

	if (argc >= 2)
	{
		if (argc == 2)
		{
			format_disk_raw(argv[1]);
			exit(0);
		}
	}
	else
	{
		printf("Please provide the disk drive you would like to format.\n");
		printf("highspeedloggerbinaryformat <DRIVE>     : eg. '/dev/sdb' or '\\\\.\\G:'  \n");
		exit(0);
	}

	exit(-1);

}

<commit_msg>Make output of pprz_format more informative (#3)<commit_after>#include <stdio.h>
#include <stdlib.h>

#include <stdint.h>
#include <unistd.h>

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <time.h>
#include <math.h>

#ifndef WIN32
#define _FILE_OFFSET_BITS 64
#define MYSEEK64 fseek
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#undef BLOCK_SIZE
#else
#define MYSEEK64 _fseeki64
#endif

/********************  SETTINGS  ********************/
// SDIO Settings
#define BLOCK_SIZE              512ULL   /* SD card block size in Bytes (512 for a normal SD card) */

// Logger settings
#define RX_BUFFER_NUM_BLOCKS    20ULL /* 20 blocks * 512 = 10 KB RAM required per buffer*/
/**************   END OF SETTINGS   *****************/

#define BUFF_SIZE  (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)

// max card size supported is 8MB
uint64_t disk_size = 8ULL*1024ULL*1024ULL*1024ULL;

void format_disk_raw(char* volume_name)
{
    FILE *volume;
    int k = 0;
    char buf[BUFF_SIZE] = {0, 0, 0, 0, 0};

	int i;

	printf("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nWe will block-format drive '%s' \nAre you absolutely sure? Then type 1324: ",volume_name);
	std::cin >> i;
	if (i != 1324)
	{
		printf("\n...\nAborting...\n");
		return;
	}

#ifdef WIN32
	uint64_t sd = disk_size;
	sd /= 1024ULL * 1024ULL;
	printf("\nExpecting an SD-card of %llu MB.\n",sd);
#else
	int fd = open(volume_name, O_RDONLY);

	uint64_t sdcard_disk_size;
	ioctl(fd, BLKGETSIZE64, &sdcard_disk_size);
	close(fd);
	uint64_t sd = sdcard_disk_size / 1024ULL / 1024ULL;

	if (sd != 0)
	{
		disk_size = sdcard_disk_size;
		printf("Found an SG card of %llu MB %llu\n",sd, disk_size);
	} else {
		sd = disk_size / (1024ULL * 1024ULL);
		printf("\nExpecting an SD-card of %llu MB.\n",sd);
	}
#endif

    volume = fopen(volume_name, "w+b");
    if(!volume)
    {
        printf("Cant open Drive '%s'\n", volume_name);
        return;
    }
    setbuf(volume, NULL);       // Disable buffering

	printf("\nFormatting entire SDCard '%s': \n...\r",volume_name);
	sleep(3);

	uint64_t addr = 0;

	addr= 0x2000 * BLOCK_SIZE;

	if(MYSEEK64(volume, addr, SEEK_SET) != 0)
	{
		printf("Can't move to sector\n");
		fclose(volume);
		return;
	}

	fwrite(buf, 5, 1, volume);

	addr = 0;
    // read what is in sector and put in buf //

	time_t time_start = time(0);
	float remaining = 0;
	while (addr < disk_size)
	{
		printf(".");

		if(MYSEEK64(volume, addr, SEEK_SET) != 0)
		{
			printf("Can't move to sector\n");
			break;
		}

		fwrite(buf, 1, 1, volume);

		int f = feof(volume);
		int e = ferror(volume);

		if (addr > 0)
			remaining = (time(0) - time_start) * ((float) disk_size / addr - 1);

		if (f!=0)
		{
			printf("End of file system found at addr %lluX: \n",addr);
			break;
		}
		printf("Format success until %llu (%lluMB), Done: %llu%%, Time left: %02.0f:%02.0f:%02.0f\r", addr, addr/1000000, 100*addr/disk_size, remaining / 3600, fmod(remaining, 3600) / 60, fmod(remaining, 60.));

		addr += BUFF_SIZE;
	}
	printf("\nDone\n");
    fclose(volume);

    return;
}

int main(int argc, char** argv)
{
	char outfilename[2048] = "";

    printf("FORMAT SDCARD:\n-------------\n");

	if (argc >= 2)
	{
		if (argc == 2)
		{
			format_disk_raw(argv[1]);
			exit(0);
		}
	}
	else
	{
		printf("Please provide the disk drive you would like to format.\n");
		printf("highspeedloggerbinaryformat <DRIVE>     : eg. '/dev/sdb' or '\\\\.\\G:'  \n");
		exit(0);
	}

	exit(-1);

}

<|endoftext|>


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

#include "ui/gfx/win/dpi.h"

#include <windows.h>
#include "base/command_line.h"
#include "base/win/scoped_hdc.h"
#include "base/win/windows_version.h"
#include "base/win/registry.h"
#include "ui/gfx/display.h"
#include "ui/gfx/switches.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/size_conversions.h"

namespace {

int kDefaultDPIX = 96;
int kDefaultDPIY = 96;

BOOL IsProcessDPIAwareWrapper() {
  typedef BOOL(WINAPI *IsProcessDPIAwarePtr)(VOID);
  IsProcessDPIAwarePtr is_process_dpi_aware_func =
      reinterpret_cast<IsProcessDPIAwarePtr>(
          GetProcAddress(GetModuleHandleA("user32.dll"), "IsProcessDPIAware"));
  if (is_process_dpi_aware_func)
    return is_process_dpi_aware_func();
  return FALSE;
}

float g_device_scale_factor = 0.0f;

float GetUnforcedDeviceScaleFactor() {
  return static_cast<float>(gfx::GetDPI().width()) /
      static_cast<float>(kDefaultDPIX);
}

float GetModernUIScaleWrapper() {
  float result = 1.0f;
  typedef float(WINAPI *GetModernUIScalePtr)(VOID);
  HMODULE lib = LoadLibraryA("metro_driver.dll");
  if (lib) {
    GetModernUIScalePtr func =
        reinterpret_cast<GetModernUIScalePtr>(
        GetProcAddress(lib, "GetModernUIScale"));
    if (func)
      result = func();
    FreeLibrary(lib);
  }
  return result;
}

}  // namespace

namespace gfx {

float GetModernUIScale() {
  return GetModernUIScaleWrapper();
}

void InitDeviceScaleFactor(float scale) {
  DCHECK_NE(0.0f, scale);
  g_device_scale_factor = scale;
}

Size GetDPI() {
  static int dpi_x = 0;
  static int dpi_y = 0;
  static bool should_initialize = true;

  if (should_initialize) {
    should_initialize = false;
    base::win::ScopedGetDC screen_dc(NULL);
    // This value is safe to cache for the life time of the app since the
    // user must logout to change the DPI setting. This value also applies
    // to all screens.
    dpi_x = GetDeviceCaps(screen_dc, LOGPIXELSX);
    dpi_y = GetDeviceCaps(screen_dc, LOGPIXELSY);
  }
  return Size(dpi_x, dpi_y);
}

float GetDPIScale() {
  if (IsHighDPIEnabled()) {
    return gfx::Display::HasForceDeviceScaleFactor() ?
        gfx::Display::GetForcedDeviceScaleFactor() :
        GetUnforcedDeviceScaleFactor();
  }
  return 1.0;
}

bool IsHighDPIEnabled() {
  // Default is disabled.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHighDPISupport)) {
    return CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
        switches::kHighDPISupport).compare("1") == 0;
  }
  return false;
}

bool IsInHighDPIMode() {
  return GetDPIScale() > 1.0;
}

void EnableHighDPISupport() {
  if (IsHighDPIEnabled()) {
    typedef BOOL(WINAPI *SetProcessDPIAwarePtr)(VOID);
    SetProcessDPIAwarePtr set_process_dpi_aware_func =
        reinterpret_cast<SetProcessDPIAwarePtr>(
            GetProcAddress(GetModuleHandleA("user32.dll"),
                           "SetProcessDPIAware"));
    if (set_process_dpi_aware_func)
      set_process_dpi_aware_func();
  }
}

namespace win {

float GetDeviceScaleFactor() {
  DCHECK_NE(0.0f, g_device_scale_factor);
  return g_device_scale_factor;
}

Point ScreenToDIPPoint(const Point& pixel_point) {
  static float scaling_factor =
      GetDeviceScaleFactor() > GetUnforcedDeviceScaleFactor() ?
      1.0f / GetDeviceScaleFactor() :
      1.0f;
  return ToFlooredPoint(ScalePoint(pixel_point,
      scaling_factor));
}

Point DIPToScreenPoint(const Point& dip_point) {
  return ToFlooredPoint(ScalePoint(dip_point, GetDeviceScaleFactor()));
}

Rect ScreenToDIPRect(const Rect& pixel_bounds) {
  // TODO(kevers): Switch to non-deprecated method for float to int conversions.
  return ToFlooredRectDeprecated(
      ScaleRect(pixel_bounds, 1.0f / GetDeviceScaleFactor()));
}

Rect DIPToScreenRect(const Rect& dip_bounds) {
  // TODO(kevers): Switch to non-deprecated method for float to int conversions.
  return ToFlooredRectDeprecated(
      ScaleRect(dip_bounds, GetDeviceScaleFactor()));
}

Size ScreenToDIPSize(const Size& size_in_pixels) {
  return ToFlooredSize(
      ScaleSize(size_in_pixels, 1.0f / GetDeviceScaleFactor()));
}

Size DIPToScreenSize(const Size& dip_size) {
  return ToFlooredSize(ScaleSize(dip_size, GetDeviceScaleFactor()));
}

int GetSystemMetricsInDIP(int metric) {
  return static_cast<int>(GetSystemMetrics(metric) /
      GetDeviceScaleFactor() + 0.5);
}

double GetUndocumentedDPIScale() {
  // TODO(girard): Remove this code when chrome is DPIAware.
  static double scale = -1.0;
  if (scale == -1.0) {
    scale = 1.0;
    if (!IsProcessDPIAwareWrapper()) {
      base::win::RegKey key(HKEY_CURRENT_USER,
                            L"Control Panel\\Desktop\\WindowMetrics",
                            KEY_QUERY_VALUE);
      if (key.Valid()) {
        DWORD value = 0;
        if (key.ReadValueDW(L"AppliedDPI", &value) == ERROR_SUCCESS) {
          scale = static_cast<double>(value) / kDefaultDPIX;
        }
      }
    }
  }
  return scale;
}

double GetUndocumentedDPITouchScale() {
  static double scale =
      (base::win::GetVersion() < base::win::VERSION_WIN8_1) ?
      GetUndocumentedDPIScale() : 1.0;
  return scale;
}

}  // namespace win
}  // namespace gfx
<commit_msg>Disable calls to SetProcessDPIAware under Win8.1 (Rebase)<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/win/dpi.h"

#include <windows.h>
#include "base/command_line.h"
#include "base/win/scoped_hdc.h"
#include "base/win/windows_version.h"
#include "base/win/registry.h"
#include "ui/gfx/display.h"
#include "ui/gfx/switches.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/size_conversions.h"

namespace {

int kDefaultDPIX = 96;
int kDefaultDPIY = 96;

BOOL IsProcessDPIAwareWrapper() {
  typedef BOOL(WINAPI *IsProcessDPIAwarePtr)(VOID);
  IsProcessDPIAwarePtr is_process_dpi_aware_func =
      reinterpret_cast<IsProcessDPIAwarePtr>(
          GetProcAddress(GetModuleHandleA("user32.dll"), "IsProcessDPIAware"));
  if (is_process_dpi_aware_func)
    return is_process_dpi_aware_func();
  return FALSE;
}

float g_device_scale_factor = 0.0f;

float GetUnforcedDeviceScaleFactor() {
  return static_cast<float>(gfx::GetDPI().width()) /
      static_cast<float>(kDefaultDPIX);
}

float GetModernUIScaleWrapper() {
  float result = 1.0f;
  typedef float(WINAPI *GetModernUIScalePtr)(VOID);
  HMODULE lib = LoadLibraryA("metro_driver.dll");
  if (lib) {
    GetModernUIScalePtr func =
        reinterpret_cast<GetModernUIScalePtr>(
        GetProcAddress(lib, "GetModernUIScale"));
    if (func)
      result = func();
    FreeLibrary(lib);
  }
  return result;
}

}  // namespace

namespace gfx {

float GetModernUIScale() {
  return GetModernUIScaleWrapper();
}

void InitDeviceScaleFactor(float scale) {
  DCHECK_NE(0.0f, scale);
  g_device_scale_factor = scale;
}

Size GetDPI() {
  static int dpi_x = 0;
  static int dpi_y = 0;
  static bool should_initialize = true;

  if (should_initialize) {
    should_initialize = false;
    base::win::ScopedGetDC screen_dc(NULL);
    // This value is safe to cache for the life time of the app since the
    // user must logout to change the DPI setting. This value also applies
    // to all screens.
    dpi_x = GetDeviceCaps(screen_dc, LOGPIXELSX);
    dpi_y = GetDeviceCaps(screen_dc, LOGPIXELSY);
  }
  return Size(dpi_x, dpi_y);
}

float GetDPIScale() {
  if (IsHighDPIEnabled()) {
    return gfx::Display::HasForceDeviceScaleFactor() ?
        gfx::Display::GetForcedDeviceScaleFactor() :
        GetUnforcedDeviceScaleFactor();
  }
  return 1.0;
}

bool IsHighDPIEnabled() {
  // Default is disabled.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kHighDPISupport)) {
    return CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
        switches::kHighDPISupport).compare("1") == 0;
  }
  return false;
}

bool IsInHighDPIMode() {
  return GetDPIScale() > 1.0;
}

void EnableHighDPISupport() {
  if (IsHighDPIEnabled() &&
      (base::win::GetVersion() < base::win::VERSION_WIN8_1)) {
    typedef BOOL(WINAPI *SetProcessDPIAwarePtr)(VOID);
    SetProcessDPIAwarePtr set_process_dpi_aware_func =
        reinterpret_cast<SetProcessDPIAwarePtr>(
            GetProcAddress(GetModuleHandleA("user32.dll"),
                           "SetProcessDPIAware"));
    if (set_process_dpi_aware_func)
      set_process_dpi_aware_func();
  }
}

namespace win {

float GetDeviceScaleFactor() {
  DCHECK_NE(0.0f, g_device_scale_factor);
  return g_device_scale_factor;
}

Point ScreenToDIPPoint(const Point& pixel_point) {
  static float scaling_factor =
      GetDeviceScaleFactor() > GetUnforcedDeviceScaleFactor() ?
      1.0f / GetDeviceScaleFactor() :
      1.0f;
  return ToFlooredPoint(ScalePoint(pixel_point,
      scaling_factor));
}

Point DIPToScreenPoint(const Point& dip_point) {
  return ToFlooredPoint(ScalePoint(dip_point, GetDeviceScaleFactor()));
}

Rect ScreenToDIPRect(const Rect& pixel_bounds) {
  // TODO(kevers): Switch to non-deprecated method for float to int conversions.
  return ToFlooredRectDeprecated(
      ScaleRect(pixel_bounds, 1.0f / GetDeviceScaleFactor()));
}

Rect DIPToScreenRect(const Rect& dip_bounds) {
  // TODO(kevers): Switch to non-deprecated method for float to int conversions.
  return ToFlooredRectDeprecated(
      ScaleRect(dip_bounds, GetDeviceScaleFactor()));
}

Size ScreenToDIPSize(const Size& size_in_pixels) {
  return ToFlooredSize(
      ScaleSize(size_in_pixels, 1.0f / GetDeviceScaleFactor()));
}

Size DIPToScreenSize(const Size& dip_size) {
  return ToFlooredSize(ScaleSize(dip_size, GetDeviceScaleFactor()));
}

int GetSystemMetricsInDIP(int metric) {
  return static_cast<int>(GetSystemMetrics(metric) /
      GetDeviceScaleFactor() + 0.5);
}

double GetUndocumentedDPIScale() {
  // TODO(girard): Remove this code when chrome is DPIAware.
  static double scale = -1.0;
  if (scale == -1.0) {
    scale = 1.0;
    if (!IsProcessDPIAwareWrapper()) {
      base::win::RegKey key(HKEY_CURRENT_USER,
                            L"Control Panel\\Desktop\\WindowMetrics",
                            KEY_QUERY_VALUE);
      if (key.Valid()) {
        DWORD value = 0;
        if (key.ReadValueDW(L"AppliedDPI", &value) == ERROR_SUCCESS) {
          scale = static_cast<double>(value) / kDefaultDPIX;
        }
      }
    }
  }
  return scale;
}

double GetUndocumentedDPITouchScale() {
  static double scale =
      (base::win::GetVersion() < base::win::VERSION_WIN8_1) ?
      GetUndocumentedDPIScale() : 1.0;
  return scale;
}

}  // namespace win
}  // namespace gfx
<|endoftext|>