<commit_before>#include <algorithm>

#include <UnitTest++/UnitTest++.h>

#include "Article.h"
#include "WalkerException.h"
#include "WikimediaJsonToArticleConverter.h"

SUITE(WikimediaJsonToArticleConverterTests)
{
  using namespace WikiWalker;
  using namespace WikiWalker::CollectionUtils;

  TEST(JsonDataWithOneLinkedArticle)
  {
    std::string testdata =
        R"({"batchcomplete":"","servedby":"mw1197","query":{"pages":[{"pageid":36669940,"ns":0,"title":"3PTT","links":[{"ns":0,"title":"Switch"}]}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto cont = conv.convert(testdata, ac);
    CHECK(WikimediaJsonToArticleConverter::ContinuationStatus::
              ConversionCompleted == cont);
    CHECK_EQUAL("", conv.continuationData()["plcontinue"]);
    auto getArticle = CollectionUtils::get(ac, "3PTT");
    CHECK(getArticle != nullptr);
    CHECK_EQUAL(1, getArticle->countLinks());
    CHECK_EQUAL(2, ac.size());
  }

  TEST(JsonDataWithInvalidArticle_Throws)
  {
    std::string testdata =
        R"({"batchcomplete":"","servedby":"mw1208","query":{"pages":[{"ns":0,"title":"FoObAr","missing":""}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto ret = conv.convert(testdata, ac);
    CHECK(ret == WikiWalker::WikimediaJsonToArticleConverter::
                     ContinuationStatus::ConversionCompleted);
    auto art = CollectionUtils::get(ac, "FoObAr");
    CHECK(art != nullptr);
    CHECK(art->marked());
  }

  TEST(JsonData_MoreLinks_HasContinueData)
  {
    std::string testdata =
        R"({"continue":{"plcontinue":"34419161|0|Jharkhand","continue":"||"},"servedby":"mw1283","query":{"pages":[{"pageid":34419161,"ns":0,"title":"Satar, Deoghar","links":[{"ns":0,"title":"Deoghar district"}]}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto cont = conv.convert(testdata, ac);
    CHECK(cont == WikimediaJsonToArticleConverter::ContinuationStatus::
                      ConversionNeedsMoreData);
    CHECK_EQUAL("34419161|0|Jharkhand", conv.continuationData()["plcontinue"]);
    auto getArticle = CollectionUtils::get(ac, "Satar, Deoghar");
    CHECK(getArticle != nullptr);
    CHECK_EQUAL(1, getArticle->countLinks());
    CHECK_EQUAL(2, ac.size());
  }

  TEST(JsonData_ContainsMultipleArticles)
  {
    std::string testdata =
        R"#({"batchcomplete": true,"query": {"normalized": [{"fromencoded": false,"from": "Zanfina_Ismajli","to": "Zanfina Ismajli"},{"fromencoded": false,"from": "Kleite_(Tochter_des_Danaos)","to": "Kleite (Tochter des Danaos)"}],"pages": [{"pageid": 2834303,"ns": 0,"title": "Zanfina Ismajli","links": [{"ns": 0,"title": "10. Mai"},{"ns": 0,"title": "1985"}]},{"pageid": 8086803,"ns": 0,"title": "Kleite (Tochter des Danaos)","links": [{"ns": 0,"title": "Aigyptos"},{"ns": 0,"title": "Altgriechische Sprache"}]}]},"limits": {"links": 500}})#";
    WikimediaJsonToArticleConverter conv;
    ArticleCollection ac;
    auto cont = conv.convert(testdata, ac);
    CHECK(WikimediaJsonToArticleConverter::ContinuationStatus::
              ConversionCompleted == cont);

    CHECK_EQUAL(2, CollectionUtils::countAnalyzedArticles(ac));
    auto ptr = CollectionUtils::get(ac, "Zanfina Ismajli");
    CHECK(ptr != nullptr);
    ptr = CollectionUtils::get(ac, "Kleite (Tochter des Danaos)");
    CHECK(ptr != nullptr);
    CHECK_EQUAL(6, ac.size());
  }
}
<commit_msg>add tests for backwards links / linkshere<commit_after>#include <algorithm>

#include <UnitTest++/UnitTest++.h>

#include "Article.h"
#include "WalkerException.h"
#include "WikimediaJsonToArticleConverter.h"

SUITE(WikimediaJsonToArticleConverterTests)
{
  using namespace WikiWalker;
  using namespace WikiWalker::CollectionUtils;

  TEST(JsonDataWithOneLinkedArticle)
  {
    std::string testdata =
        R"({"batchcomplete":"","servedby":"mw1197","query":{"pages":[{"pageid":36669940,"ns":0,"title":"3PTT","links":[{"ns":0,"title":"Switch"}]}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto cont = conv.convert(testdata, ac);
    CHECK(WikimediaJsonToArticleConverter::ContinuationStatus::
              ConversionCompleted == cont);
    CHECK_EQUAL("", conv.continuationData()["plcontinue"]);
    auto getArticle = CollectionUtils::get(ac, "3PTT");
    CHECK(getArticle != nullptr);
    CHECK_EQUAL(1, getArticle->countLinks());
    CHECK_EQUAL(2, ac.size());
  }

  TEST(JsonDataWithInvalidArticle_Throws)
  {
    std::string testdata =
        R"({"batchcomplete":"","servedby":"mw1208","query":{"pages":[{"ns":0,"title":"FoObAr","missing":""}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto ret = conv.convert(testdata, ac);
    CHECK(ret == WikiWalker::WikimediaJsonToArticleConverter::
                     ContinuationStatus::ConversionCompleted);
    auto art = CollectionUtils::get(ac, "FoObAr");
    CHECK(art != nullptr);
    CHECK(art->marked());
  }

  TEST(JsonData_MoreLinks_HasContinueData)
  {
    std::string testdata =
        R"({"continue":{"plcontinue":"34419161|0|Jharkhand","continue":"||"},"servedby":"mw1283","query":{"pages":[{"pageid":34419161,"ns":0,"title":"Satar, Deoghar","links":[{"ns":0,"title":"Deoghar district"}]}]}})";

    ArticleCollection ac;
    WikimediaJsonToArticleConverter conv;
    auto cont = conv.convert(testdata, ac);
    CHECK(cont == WikimediaJsonToArticleConverter::ContinuationStatus::
                      ConversionNeedsMoreData);
    CHECK_EQUAL("34419161|0|Jharkhand", conv.continuationData()["plcontinue"]);
    auto getArticle = CollectionUtils::get(ac, "Satar, Deoghar");
    CHECK(getArticle != nullptr);
    CHECK_EQUAL(1, getArticle->countLinks());
    CHECK_EQUAL(2, ac.size());
  }

  TEST(JsonData_ContainsMultipleArticles)
  {
    std::string testdata =
        R"#({"batchcomplete": true,"query": {"normalized": [{"fromencoded": false,"from": "Zanfina_Ismajli","to": "Zanfina Ismajli"},{"fromencoded": false,"from": "Kleite_(Tochter_des_Danaos)","to": "Kleite (Tochter des Danaos)"}],"pages": [{"pageid": 2834303,"ns": 0,"title": "Zanfina Ismajli","links": [{"ns": 0,"title": "10. Mai"},{"ns": 0,"title": "1985"}]},{"pageid": 8086803,"ns": 0,"title": "Kleite (Tochter des Danaos)","links": [{"ns": 0,"title": "Aigyptos"},{"ns": 0,"title": "Altgriechische Sprache"}]}]},"limits": {"links": 500}})#";
    WikimediaJsonToArticleConverter conv;
    ArticleCollection ac;
    auto cont = conv.convert(testdata, ac);
    CHECK(WikimediaJsonToArticleConverter::ContinuationStatus::
              ConversionCompleted == cont);

    CHECK_EQUAL(2, CollectionUtils::countAnalyzedArticles(ac));
    auto ptr = CollectionUtils::get(ac, "Zanfina Ismajli");
    CHECK(ptr != nullptr);
    ptr = CollectionUtils::get(ac, "Kleite (Tochter des Danaos)");
    CHECK(ptr != nullptr);
    CHECK_EQUAL(6, ac.size());
  }

  TEST(JsonData_ConvertLinkshere)
  {
    std::string testdata =
        R"#({"batchcomplete":true,"query":{"pages":[{"pageid":2,"ns":0,"title":"Eins","linkshere":[{"ns":0,"title":"Zw\u00f6lf"},{"ns":0,"title":"Dreizehn"},{"ns":0,"title":"Ens"}]}]},"limits":{"linkshere":500}})#";
    WikimediaJsonToArticleConverter conv;
    ArticleCollection ac;
    auto cont = conv.convert(testdata, ac);

    // exp: zwölf, dreizehn, ens --> eins
    CHECK(WikimediaJsonToArticleConverter::ContinuationStatus::
              ConversionCompleted == cont);
    CHECK_EQUAL(3, CollectionUtils::countAnalyzedArticles(ac));
    CHECK_EQUAL(4, ac.size());

    auto ptr = CollectionUtils::get(ac, "Ens");
    REQUIRE CHECK(ptr != nullptr);
    CHECK(ptr->analyzed());
    ptr = CollectionUtils::get(ac, "Dreizehn");
    REQUIRE CHECK(ptr != nullptr);
    CHECK(ptr->analyzed());
    // better be save than sorry
    ptr = CollectionUtils::get(ac, "Zw\u00f6lf");
    REQUIRE CHECK(ptr != nullptr);
    CHECK(ptr->analyzed());
    ptr = CollectionUtils::get(ac, "Eins");
    REQUIRE CHECK(ptr != nullptr);
    CHECK(!ptr->analyzed());
  }
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "OptionsGroup.h"

namespace sofa
{

namespace helper
{

class OptionsGroup;
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
OptionsGroup::OptionsGroup() : textItems()
{
    selectedItem=0;
}
///////////////////////////////////////
OptionsGroup::OptionsGroup(int nbofRadioButton,...)
{
    textItems.resize(nbofRadioButton);
    va_list vl;
    va_start(vl,nbofRadioButton);
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        const char * tempochar=va_arg(vl,char *);
        std::string  tempostring(tempochar);
        textItems[i]=tempostring;
    }
    va_end(vl);
    selectedItem=0;
}
///////////////////////////////////////
OptionsGroup::OptionsGroup(const OptionsGroup & m_radiotrick) : textItems(m_radiotrick.textItems)
{
    selectedItem=m_radiotrick.getSelectedId();
}
///////////////////////////////////////
OptionsGroup & OptionsGroup::operator=(const OptionsGroup & m_radiotrick)
{
    textItems.resize(m_radiotrick.textItems.size());
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        textItems[i]=m_radiotrick.textItems[i];
    }
    selectedItem=m_radiotrick.selectedItem;
    return *this;
}
///////////////////////////////////////
void OptionsGroup::setNames(int nbofRadioButton,...)
{
    textItems.resize(nbofRadioButton);
    va_list vl;
    va_start(vl,nbofRadioButton);
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        const char * tempochar=va_arg(vl,char *);
        std::string  tempostring(tempochar);
        textItems[i]=tempostring;
    }
    va_end(vl);
    selectedItem=0;
}
///////////////////////////////////////
int OptionsGroup::isInButtonList(const std::string & tempostring) const
{
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        if (textItems[i]==tempostring) return i;
    }
    return -1;
}
///////////////////////////////////////
void OptionsGroup::setSelectedItem(unsigned int id_item)
{
    if (id_item<textItems.size())
        selectedItem=id_item;
    //std::cout<<"OptionsGroup:: ==============================setted :"<< this->selectedItem << std::endl;
}
///////////////////////////////////////
void OptionsGroup::setSelectedItem(const std::string & m_string)
{
    int id_stringinButtonList = isInButtonList(m_string);
    if (id_stringinButtonList == -1)
    {
        std::cout<<"WARNING(OptionsGroup) : \""<< m_string <<"\" is not a parameter in button list :\" "<<(*this)<<"\""<< std::endl;
    }
    else
    {
        setSelectedItem(id_stringinButtonList);
    }
}
///////////////////////////////////////
unsigned int OptionsGroup::getSelectedId() const
{
    return selectedItem;
}
///////////////////////////////////////
std::string  OptionsGroup::getSelectedItem() const
{
    std::string checkedString;
    checkedString = textItems.operator[](selectedItem);
    return checkedString;
}
///////////////////////////////////////
void OptionsGroup::readFromStream(std::istream & stream)
{
    std::string tempostring;
    stream >> tempostring;
    int id_stringinButtonList = isInButtonList(tempostring);
    if (id_stringinButtonList == -1)
    {
        std::cout<<"WARNING(OptionsGroup) : \""<< tempostring <<"\" is not a parameter in button list :\" "<<(*this)<<"\""<< std::endl;
    }
    else
    {
        setSelectedItem(id_stringinButtonList);
    }
}
///////////////////////////////////////
void OptionsGroup::writeToStream(std::ostream & stream) const
{

    for(unsigned int i=0; i<textItems.size()-1; i++)
    {
        std::string tempostring= textItems.operator[](i);
        stream<< tempostring << " ";
    }
}
///////////////////////////////////////
void OptionsGroup::TestOptionsGroup() const
{
    sofa::helper::OptionsGroup m_radiotrick; m_radiotrick.setNames(3,"hello1","hello2","hello3");
    std::cout<<"Radio button :"<<m_radiotrick<<"    selectedId :"<<m_radiotrick.getSelectedId()<<"   getSelectedItem() :"<<m_radiotrick.getSelectedItem()<<std::endl;
    std::cin>>m_radiotrick;
    std::cout<<"Radio button :"<<m_radiotrick<<"    selectedId :"<<m_radiotrick.getSelectedId()<<"   getSelectedItem() :"<<m_radiotrick.getSelectedItem()<<std::endl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////

} // namespace helper

} // namespace sofa
<commit_msg>r7394/sofa-dev : FIX: bug with OptionGroup: writeToStream method was not correct<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "OptionsGroup.h"

namespace sofa
{

namespace helper
{

class OptionsGroup;
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
OptionsGroup::OptionsGroup() : textItems()
{
    selectedItem=0;
}
///////////////////////////////////////
OptionsGroup::OptionsGroup(int nbofRadioButton,...)
{
    textItems.resize(nbofRadioButton);
    va_list vl;
    va_start(vl,nbofRadioButton);
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        const char * tempochar=va_arg(vl,char *);
        std::string  tempostring(tempochar);
        textItems[i]=tempostring;
    }
    va_end(vl);
    selectedItem=0;
}
///////////////////////////////////////
OptionsGroup::OptionsGroup(const OptionsGroup & m_radiotrick) : textItems(m_radiotrick.textItems)
{
    selectedItem=m_radiotrick.getSelectedId();
}
///////////////////////////////////////
OptionsGroup & OptionsGroup::operator=(const OptionsGroup & m_radiotrick)
{
    textItems.resize(m_radiotrick.textItems.size());
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        textItems[i]=m_radiotrick.textItems[i];
    }
    selectedItem=m_radiotrick.selectedItem;
    return *this;
}
///////////////////////////////////////
void OptionsGroup::setNames(int nbofRadioButton,...)
{
    textItems.resize(nbofRadioButton);
    va_list vl;
    va_start(vl,nbofRadioButton);
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        const char * tempochar=va_arg(vl,char *);
        std::string  tempostring(tempochar);
        textItems[i]=tempostring;
    }
    va_end(vl);
    selectedItem=0;
}
///////////////////////////////////////
int OptionsGroup::isInButtonList(const std::string & tempostring) const
{
    for(unsigned int i=0; i<textItems.size(); i++)
    {
        if (textItems[i]==tempostring) return i;
    }
    return -1;
}
///////////////////////////////////////
void OptionsGroup::setSelectedItem(unsigned int id_item)
{
    if (id_item<textItems.size())
        selectedItem=id_item;
    //std::cout<<"OptionsGroup:: ==============================setted :"<< this->selectedItem << std::endl;
}
///////////////////////////////////////
void OptionsGroup::setSelectedItem(const std::string & m_string)
{
    int id_stringinButtonList = isInButtonList(m_string);
    if (id_stringinButtonList == -1)
    {
        std::cout<<"WARNING(OptionsGroup) : \""<< m_string <<"\" is not a parameter in button list :\" "<<(*this)<<"\""<< std::endl;
    }
    else
    {
        setSelectedItem(id_stringinButtonList);
    }
}
///////////////////////////////////////
unsigned int OptionsGroup::getSelectedId() const
{
    return selectedItem;
}
///////////////////////////////////////
std::string  OptionsGroup::getSelectedItem() const
{
    std::string checkedString;
    checkedString = textItems.operator[](selectedItem);
    return checkedString;
}
///////////////////////////////////////
void OptionsGroup::readFromStream(std::istream & stream)
{
    std::string tempostring;
    stream >> tempostring;
    int id_stringinButtonList = isInButtonList(tempostring);
    if (id_stringinButtonList == -1)
    {
        std::cout<<"WARNING(OptionsGroup) : \""<< tempostring <<"\" is not a parameter in button list :\" "<<(*this)<<"\""<< std::endl;
    }
    else
    {
        setSelectedItem(id_stringinButtonList);
    }
}
///////////////////////////////////////
void OptionsGroup::writeToStream(std::ostream & stream) const
{
    stream << getSelectedItem();
//	for(unsigned int i=0;i<textItems.size()-1;i++)
//	{
//		std::string tempostring= textItems.operator[](i);
//		stream<< tempostring << " ";
//	}
}
///////////////////////////////////////
void OptionsGroup::TestOptionsGroup() const
{
    sofa::helper::OptionsGroup m_radiotrick; m_radiotrick.setNames(3,"hello1","hello2","hello3");
    std::cout<<"Radio button :"<<m_radiotrick<<"    selectedId :"<<m_radiotrick.getSelectedId()<<"   getSelectedItem() :"<<m_radiotrick.getSelectedItem()<<std::endl;
    std::cin>>m_radiotrick;
    std::cout<<"Radio button :"<<m_radiotrick<<"    selectedId :"<<m_radiotrick.getSelectedId()<<"   getSelectedItem() :"<<m_radiotrick.getSelectedItem()<<std::endl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////

} // namespace helper

} // namespace sofa
<|endoftext|>


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

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_LOGINDIALOG_HXX_
#include <services/logindialog.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_SERVICEMANAGER_HXX_
#include <classes/servicemanager.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XDIALOG_HPP_
#include <com/sun/star/awt/XDialog.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif

#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#include <stdio.h>

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

#define TEMPFILE_ENCODING           RTL_TEXTENCODING_UTF8           // encoding of written temp. ascii file
#define ARGUMENTFOUND               0                               // OUString::compareTo returns 0 if searched string match given one
#define SEPERATOR                   (sal_Unicode)';'                // seperator for temp. file values
#define ENCODESIGN                  (sal_Unicode)'\\'               // special character to encode SEPERATOR. These sign must be encoded too!!!

#define ARGUMENT_TEMPFILE           DECLARE_ASCII("-f=")            // we support "-f=c:\temp\test.txt" as argument
#define ARGUMENTLENGTH_TEMPFILE     3                               // length of ARGUMENT_TEMPFILE to find it in argumentlist

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl                       ;
using namespace ::vos                       ;
using namespace ::comphelper                ;
using namespace ::framework                 ;
using namespace ::com::sun::star::uno       ;
using namespace ::com::sun::star::lang      ;
using namespace ::com::sun::star::awt       ;
using namespace ::com::sun::star::beans     ;

//_________________________________________________________________________________________________________________
//  defines
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short      implement command application to show login dialog and save his information in temp. file!
    @descr      We need this temp. file to share informations between our dialog and different processes, which
                can't use vcl directly. Caller of this executable give us the file name as an argument - we save
                all informations in it - caller can read it and MUST delete temp. file.
                This is neccessary for example; to hide the password!

    @implements -

    @base       Application
*//*-*************************************************************************************************************/
class LoginApplication : public Application
{
    //*************************************************************************************************************
    //  public methods
    //*************************************************************************************************************
    public:
        void Main();

    //*************************************************************************************************************
    //  private methods
    //*************************************************************************************************************
    private:
        void        impl_parseCommandline   (                           );      // search supported arguments on command line
        OUString    impl_encodeString       ( const OUString& sValue    );      // encode SEPERATOR and "\" with an additional "\"! zB "\" => "\\"

    //*************************************************************************************************************
    //  private variables
    //*************************************************************************************************************
    private:
        OString m_sTempFile ;   // name of temp. file in system notation

};  //  class LoginApplication

//_________________________________________________________________________________________________________________
//  global variables
//_________________________________________________________________________________________________________________

LoginApplication    gLoginApplication;

//_________________________________________________________________________________________________________________
//  main
//_________________________________________________________________________________________________________________

void LoginApplication::Main()
{
    // Init global uno servicemanager.
    ServiceManager aManager;
    Reference< XMultiServiceFactory > xServiceManager = aManager.getSharedUNOServiceManager( DECLARE_ASCII("login.rdb") );
    LOG_ASSERT( !(xServiceManager.is()==sal_False), "LoginApplication::Main()\nCould not create uno service manager!\n" )

    // Parse command line and set found arguments on application member.
    impl_parseCommandline();
    LOG_ASSERT( !(m_sTempFile.getLength()<1), "LoginApplication::Main()\nWrong or missing argument for temp. file detected!\n" )

    // Try to get neccessary dialog service.
    // By the way - cast it to interface XPropertySet too - we need it later.
    // (define SERVICENAME... comes from defines.hxx!)
    Reference< XDialog >        xLoginDialog( xServiceManager->createInstance( SERVICENAME_LOGINDIALOG ), UNO_QUERY );
    Reference< XPropertySet >   xPropertySet( xLoginDialog                                              , UNO_QUERY );

    // Work with valid ressources only!
    // Otherwise do nothing ...
    if  (
            ( xLoginDialog.is()         ==  sal_True    )   &&
            ( xPropertySet.is()         ==  sal_True    )   &&
            ( m_sTempFile.getLength()   >   0           )
        )
    {
        // User can't set used connection type in dialog directly!
        // And if our setup has written wrong value for it ...
        // we must set right type before to get right value after showing dialog!!!
        Any aConnectionType;
        aConnectionType <<= PROPERTYNAME_COMPRESSEDSECURE;
        xPropertySet->setPropertyValue( PROPERTYNAME_CONNECTIONTYPE, aConnectionType );

        // Show login dialog and get decision of user.
        sal_Bool bDecision = (sal_Bool)(xLoginDialog->execute());

        OUString    sUserName       ;
        OUString    sPassword       ;
        OUString    sServer         ;
        OUString    sConnectionType ;
        sal_Int32   nPort=0         ;   // We need this default if follow "if"-statement "failed"!
                                        // Strings before has "" as default.

        // If user say "OK" ... get values from dialog.
        // If user say "NO" ... leave it. Then we save empty informations later ...
        if( bDecision == sal_True )
        {
            // defines PROPERTYNAME... comes from logindialog.hxx!
            xPropertySet->getPropertyValue( PROPERTYNAME_USERNAME       ) >>= sUserName         ;
            xPropertySet->getPropertyValue( PROPERTYNAME_PASSWORD       ) >>= sPassword         ;
            xPropertySet->getPropertyValue( PROPERTYNAME_SERVER         ) >>= sServer           ;
            xPropertySet->getPropertyValue( PROPERTYNAME_CONNECTIONTYPE ) >>= sConnectionType   ;
            if( sConnectionType.getLength() > 0 )
            {
                xPropertySet->getPropertyValue( sConnectionType ) >>= nPort;
            }
        }

        // Build string for output.
        // At this point it doesnt matter if information exist or not!
        // Format of output: "<decision[0|1]>;<username[string]>;<password[string]>;<servername[string]>;<port[int]>"
        OUStringBuffer sBuffer( 1000 );

        if( bDecision == sal_True )
        {
            sBuffer.appendAscii( "1" );
        }
        else
        {
            sBuffer.appendAscii( "0" );
        }
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.append      ( impl_encodeString(sUserName)      );
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.append      ( impl_encodeString(sPassword)      );
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.append      ( impl_encodeString(sServer)        );
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.append      ( impl_encodeString(sConnectionType));
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.append      ( nPort                             );
        sBuffer.append      ( SEPERATOR                         );
        sBuffer.appendAscii ( "\n"                              );

        // Write informations in temp. file.
        // If given file name isnt valid ... caller will have a problem!!!
        // If fil already exist (That's out of specification!!!) we overwrite it everytime.
        FILE* pFile = fopen( m_sTempFile.getStr(), "w" );
        LOG_ASSERT( !(pFile==NULL), "LoginApplication::Main()\nCould not open file!\n" );
        if( pFile != NULL )
        {
            OString sEncodedOut = U2B_ENC( sBuffer.makeStringAndClear(), TEMPFILE_ENCODING );
            fprintf( pFile, sEncodedOut.getStr()    );
            fclose ( pFile                          );
        }
    }
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
void LoginApplication::impl_parseCommandline()
{
    // Use vos::OStartupInfo for access to command line.
    // Step over all arguments, search for supported ones and try to get his values.
    // Set it on our member. Caller of this method must control setted values.
    OStartupInfo aInfo;

    sal_uInt32  nCount      =   aInfo.getCommandArgCount()  ;
    sal_uInt32  nArgument   =   0                           ;
    OUString    sArgument                                   ;

    // Warn programmer if argument count isnt ok!
    LOG_ASSERT( !(nCount!=1), "LoginApplication::impl_parseCommandline()\nWrong argument count detected!\n" )

    // Step over all arguments ...
    for( nArgument=0; nArgument<nCount; ++nArgument )
    {
        // .. but work with valid ones only!
        // Don't check values here. Caller of this method must decide between wrong and allowed values!
        aInfo.getCommandArg( nArgument, sArgument );

        //_____________________________________________________________________________________________________
        // Look for "-f<temp. file name>
        if( sArgument.compareTo( ARGUMENT_TEMPFILE, ARGUMENTLENGTH_TEMPFILE ) == ARGUMENTFOUND )
        {
            m_sTempFile = U2B(sArgument.copy( ARGUMENTLENGTH_TEMPFILE ));
        }
    }
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
OUString LoginApplication::impl_encodeString( const OUString& sValue )
{
    // Read all signs from source buffer into destination buffer
    // and change all ";" and "\" to "\;" and "\\"!

    sal_Int32       nCount      = sValue.getLength();
    OUStringBuffer  sSource     ( sValue    )       ;
    OUStringBuffer  sDestination( nCount*2  )       ;   // Reserve destination buffer with enough free space for changes! Sometimes we must add signs ...
    sal_Unicode     cLetter                         ;

    for( sal_Int32 nLetter=0; nLetter<nCount; ++nLetter )
    {
        cLetter = sSource.charAt(nLetter);
        // If sign a special one ...
        // add escape letter before ...
        // and special one then!
        // Otherwise letter will copied normaly.
        if  (
                ( cLetter   ==  SEPERATOR   )   ||
                ( cLetter   ==  ENCODESIGN  )
            )
        {
            sDestination.append( ENCODESIGN );
        }
        sDestination.append( cLetter );
    }

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

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_LOGINDIALOG_LOGINDIALOG_HXX_
#include <logindialog.hxx>
#endif

#ifndef __FRAMEWORK_CLASSES_SERVICEMANAGER_HXX_
#include <classes/servicemanager.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_DEFINES_HXX_
#include <defines.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XDIALOG_HPP_
#include <com/sun/star/awt/XDialog.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif

#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#include <stdio.h>

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

#define TEMPFILE_ENCODING           RTL_TEXTENCODING_UTF8           // encoding of written temp. ascii file
#define LOGIN_RDB                   DECLARE_ASCII("login.rdb")      // name of our own registry file - neccessary to create own servicemanager
#define SEPERATOR                   "\n"                            // used to seperate parts in temp. file

#define MINARGUMENTCOUNT            1                               // count of min. required arguments
#define ARGUMENTFOUND               0                               // OUString::compareTo returns 0 if searched string match given one
#define ARGUMENTLENGTH              3                               // length of fixed part of any argument to detect it easier!

#define ARGUMENT_TEMPFILE           DECLARE_ASCII("-f=")            // we support "-f=c:\temp\test.txt" to write dialog data in temp. file
#define ARGUMENT_DIALOGPARENT       DECLARE_ASCII("-p=")            // we support "-p=36748322" as window handle of parent for vcl dialog

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

using namespace ::rtl                       ;
using namespace ::vos                       ;
using namespace ::comphelper                ;
using namespace ::framework                 ;
using namespace ::com::sun::star::uno       ;
using namespace ::com::sun::star::lang      ;
using namespace ::com::sun::star::awt       ;
using namespace ::com::sun::star::beans     ;

//_________________________________________________________________________________________________________________
//  defines
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short      implement command application to show login dialog and save his information in temp. file!
    @descr      We need this temp. file to share informations between our dialog and different processes, which
                can't use vcl directly. Caller of this executable give us the file name as an argument - we save
                all informations in it - caller can read it and MUST delete temp. file.
                This is neccessary for example; to hide the password!

    @implements -

    @base       Application
*//*-*************************************************************************************************************/
class LoginApplication : public Application
{
    //*************************************************************************************************************
    //  public methods
    //*************************************************************************************************************
    public:
        void Main();

    //*************************************************************************************************************
    //  private methods
    //*************************************************************************************************************
    private:
        void impl_parseCommandline();       // search supported arguments on command line

    //*************************************************************************************************************
    //  private variables
    //*************************************************************************************************************
    private:
        OString     m_sTempFile     ;   // name of temp. file in system notation
        sal_Int32   m_nParentHandle ;   // a parent window handle for used vcl dialog

};  //  class LoginApplication

//_________________________________________________________________________________________________________________
//  global variables
//_________________________________________________________________________________________________________________

LoginApplication    gLoginApplication;

//_________________________________________________________________________________________________________________
//  main
//_________________________________________________________________________________________________________________

void LoginApplication::Main()
{
    // Init global uno servicemanager.
    ServiceManager aManager;
    Reference< XMultiServiceFactory > xServiceManager = aManager.getManager( LOGIN_RDB );
    LOG_ASSERT( !(xServiceManager.is()==sal_False), "LoginApplication::Main()\nCould not create uno service manager!\n" )

    // Parse command line and set found arguments on application member.
    impl_parseCommandline();
    LOG_ASSERT( !(m_sTempFile.getLength()<1), "LoginApplication::Main()\nWrong or missing argument for temp. file detected!\n" )

    // Try to get neccessary dialog service.
    // By the way - cast it to interface XPropertySet too - we need it later.
    // (define SERVICENAME... comes from defines.hxx!)
    Reference< XDialog >        xLoginDialog( xServiceManager->createInstance( SERVICENAME_LOGINDIALOG ), UNO_QUERY );
    Reference< XPropertySet >   xPropertySet( xLoginDialog                                              , UNO_QUERY );

    // Work with valid ressources only!
    // Otherwise do nothing ...
    if  (
            ( xLoginDialog.is()         ==  sal_True    )   &&
            ( xPropertySet.is()         ==  sal_True    )   &&
            ( m_sTempFile.getLength()   >   0           )
        )
    {
        // Exist a parent window? YES => set right property.
        if( m_nParentHandle != 0 )
        {
            Any aParentWindow;
            aParentWindow <<= m_nParentHandle;
            xPropertySet->setPropertyValue( PROPERTYNAME_PARENTWINDOW, aParentWindow );
        }

        Any aConnectionType;
        aConnectionType <<= PROPERTYNAME_COMPRESSEDSECURE;
        xPropertySet->setPropertyValue( PROPERTYNAME_CONNECTIONTYPE, aConnectionType );

        // Show login dialog and get decision of user.
        sal_Bool bDecision = (sal_Bool)(xLoginDialog->execute());

        OUString    sUserName       ;
        OUString    sPassword       ;
        OUString    sServer         ;
        OUString    sConnectionType ;
        sal_Int32   nPort=0         ;   // We need this default if follow "if"-statement "failed"!

        // If user say "OK" ... get values from dialog.
        // If user say "NO" ... leave it. Then we save empty informations later ...
        if( bDecision == sal_True )
        {
            // defines PROPERTYNAME... comes from logindialog.hxx!
            xPropertySet->getPropertyValue( PROPERTYNAME_USERNAME       ) >>= sUserName         ;
            xPropertySet->getPropertyValue( PROPERTYNAME_PASSWORD       ) >>= sPassword         ;
            xPropertySet->getPropertyValue( PROPERTYNAME_SERVER         ) >>= sServer           ;
            xPropertySet->getPropertyValue( PROPERTYNAME_CONNECTIONTYPE ) >>= sConnectionType   ;
            if( sConnectionType.getLength() > 0 )
            {
                xPropertySet->getPropertyValue( sConnectionType ) >>= nPort;
            }
        }

        // Build string for output.
        // At this point it doesnt matter if information exist or not!
        // Format of output: "<decision>    [0|1]       SEPERATOR
        //                    <username>    [string]    SEPERATOR
        //                    <password>    [string]    SEPERATOR
        //                    <servername>  [string]    SEPERATOR
        //                    <port>        [int]       SEPERATOR"
        OUStringBuffer sBuffer( 1000 );

        if( bDecision == sal_True )
        {
            sBuffer.appendAscii( "1" );
        }
        else
        {
            sBuffer.appendAscii( "0" );
        }
        sBuffer.appendAscii ( SEPERATOR         );
        sBuffer.append      ( sUserName         );
        sBuffer.appendAscii ( SEPERATOR         );
        sBuffer.append      ( sPassword         );
        sBuffer.appendAscii ( SEPERATOR         );
        sBuffer.append      ( sServer           );
        sBuffer.appendAscii ( SEPERATOR         );
        sBuffer.append      ( sConnectionType   );
        sBuffer.appendAscii ( SEPERATOR         );
        sBuffer.append      ( nPort             );
        sBuffer.appendAscii ( SEPERATOR         );

        // Write informations in temp. file.
        // If given file name isnt valid ... caller will have a problem!!!
        // If fil already exist (That's out of specification!!!) we overwrite it everytime.
        FILE* pFile = fopen( m_sTempFile.getStr(), "w" );
        LOG_ASSERT( !(pFile==NULL), "LoginApplication::Main()\nCould not open file!\n" );
        if( pFile != NULL )
        {
            OString sEncodedOut = U2B_ENC( sBuffer.makeStringAndClear(), TEMPFILE_ENCODING );
            fprintf( pFile, sEncodedOut.getStr()    );
            fclose ( pFile                          );
        }
    }
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
void LoginApplication::impl_parseCommandline()
{
    // Use vos::OStartupInfo for access to command line.
    // Step over all arguments, search for supported ones and try to get his values.
    // Set it on our member. Caller of this method must control setted values.
    OStartupInfo aInfo;

    sal_uInt32  nCount      =   aInfo.getCommandArgCount()  ;
    sal_uInt32  nArgument   =   0                           ;
    OUString    sArgument                                   ;
    OUString    sValue                                      ;

    // Warn programmer if argument count isnt ok!
    LOG_ASSERT( !(nCount!=MINARGUMENTCOUNT), "LoginApplication::impl_parseCommandline()\nWrong argument count detected!\n" )

    // Reset all possible argument variables to defaults if someone is missing.
    m_sTempFile     = OString();
    m_nParentHandle = 0        ;

    // Step over all arguments ...
    for( nArgument=0; nArgument<nCount; ++nArgument )
    {
        // .. but work with valid ones only!
        // Don't check values here. Caller of this method must decide between wrong and allowed values!
        aInfo.getCommandArg( nArgument, sArgument );

        //_____________________________________________________________________________________________________
        // Look for "-f=<temp. file name>"
        if( sArgument.compareTo( ARGUMENT_TEMPFILE, ARGUMENTLENGTH ) == ARGUMENTFOUND )
        {
            sValue      = sArgument.copy( ARGUMENTLENGTH );
            m_sTempFile = U2B(sValue);
        }
        else
        //_____________________________________________________________________________________________________
        // Look for "-p=<parent window handle>"
        if( sArgument.compareTo( ARGUMENT_DIALOGPARENT, ARGUMENTLENGTH ) == ARGUMENTFOUND )
        {
            sValue          = sArgument.copy( ARGUMENTLENGTH );
            m_nParentHandle = sValue.toInt32();
        }
    }

    // Parent window handle is an optional argument ... but should be used mostly!
    // Warn programmer.
    LOG_ASSERT( !(m_nParentHandle==0), "Login.exe\nYou should give me a parent window handle!\n" )
}
<|endoftext|>


<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <sstream>

#include "udpipe_service.h"

namespace ufal {
namespace udpipe {

// Init the UDPipe service -- load the models
bool udpipe_service::init(const vector<model_description>& model_descriptions) {
  if (model_descriptions.empty()) return false;

  // Load models
  models.clear();
  rest_models_map.clear();
  for (auto& model_description : model_descriptions) {
    Model* model = Model::load(model_description.file.c_str());
    if (!model) return false;

    // Store the model
    models.emplace_back(model_description.rest_id, model_description.acknowledgements, model);
  }

  // Fill rest_models_map with model name and aliases
  for (auto& model : models) {
    // Fail if this model id is aready in use.
    if (!rest_models_map.emplace(model.rest_id, &model).second) return false;

    // Create (but not overwrite) id without version.
    for (unsigned i = 0; i+1+6 < model.rest_id.size(); i++)
      if (model.rest_id[i] == '-') {
        bool is_version = true;
        for (unsigned j = i+1; j < i+1+6; j++)
          is_version = is_version && model.rest_id[j] >= '0' && model.rest_id[j] <= '9';
        if (is_version)
          rest_models_map.emplace(model.rest_id.substr(0, i) + model.rest_id.substr(i+1+6), &model);
      }

    // Create (but not overwrite) hyphen-separated prefixes.
    for (unsigned i = 0; i < model.rest_id.size(); i++)
      if (model.rest_id[i] == '-')
        rest_models_map.emplace(model.rest_id.substr(0, i), &model);
  }
  // Default model
  rest_models_map.emplace(string(), &models.front());

  // Init REST service
  json_models.clear().object().indent().key("models").indent().object();
  for (auto& model : models) {
    json_models.indent().key(model.rest_id).indent().array();
    if (model.can_tokenize) json_models.value("tokenizer");
    if (model.can_tag) json_models.value("tagger");
    if (model.can_parse) json_models.value("parser");
    json_models.close();
  }
  json_models.indent().close().indent().key("default_model").indent().value(model_descriptions.front().rest_id).finish(true);

  return true;
}

// Handlers with their URLs
unordered_map<string, bool (udpipe_service::*)(microrestd::rest_request&)> udpipe_service::handlers = {
  // REST service
  {"/models", &udpipe_service::handle_rest_models},
  {"/process", &udpipe_service::handle_rest_process},
};

// Handle a request using the specified URL/handler map
bool udpipe_service::handle(microrestd::rest_request& req) {
  auto handler_it = handlers.find(req.url);
  return handler_it == handlers.end() ? req.respond_not_found() : (this->*handler_it->second)(req);
}

// Load selected model
const udpipe_service::model_info* udpipe_service::load_rest_model(const string& rest_id, string& error) {
  auto model_it = rest_models_map.find(rest_id);
  if (model_it == rest_models_map.end())
    return error.assign("Requested model '").append(rest_id).append("' does not exist.\n"), nullptr;

  return model_it->second;
}

// REST service
inline microrestd::string_piece sp(string_piece str) { return microrestd::string_piece(str.str, str.len); }
inline microrestd::string_piece sp(const char* str, size_t len) { return microrestd::string_piece(str, len); }

udpipe_service::rest_response_generator::rest_response_generator(const model_info* model) : model(model) {
  json.object();
  json.indent().key("model").indent().value(model->rest_id);
  json.indent().key("acknowledgements").indent().array();
  json.indent().value("http://ufal.mff.cuni.cz/udpipe#udpipe_acknowledgements");
  if (!model->acknowledgements.empty()) json.indent().value(model->acknowledgements);
  json.indent().close().indent().key("result").indent().value("");
}

// REST service handlers

bool udpipe_service::handle_rest_models(microrestd::rest_request& req) {
  return req.respond(rest_response_generator::mime, json_models);
}

bool udpipe_service::handle_rest_process(microrestd::rest_request& req) {
  string error;
  auto rest_id = get_rest_model_id(req);
  auto model = load_rest_model(rest_id, error);
  if (!model) return req.respond_error(error);

  auto& data = get_data(req, error); if (!error.empty()) return req.respond_error(error);
  bool tokenizer = false;
  unique_ptr<input_format> input(get_input_format(req, model, tokenizer, error)); if (!input) return req.respond_error(error);
  auto& tagger = get_tagger(req, model, error); if (!error.empty()) return req.respond_error(error);
  auto& parser = get_parser(req, model, error); if (!error.empty()) return req.respond_error(error);
  unique_ptr<output_format> output(get_output_format(req, error)); if (!output) return req.respond_error(error);

  // Try loading the input if tokenizer is not used
  if (!tokenizer) {
    input->set_text(data);
    sentence s;
    while (input->next_sentence(s, error)) {}
    if (!error.empty())
      return req.respond_error(error.insert(0, "Cannot read input data: ").append("\n"));
  }

  input->set_text(data);
  class generator : public rest_response_generator {
   public:
    generator(const model_info* model, input_format* input, const string& tagger, const string& parser, output_format* output)
        : rest_response_generator(model), input(input), tagger(tagger), parser(parser), output(output) {}

    bool generate() {
      if (!input->next_sentence(s, error)) {
        output->finish_document(os);
        json.value(os.str(), true);
        os.str(string());

        json.finish(true);

        return false;
      }

      if (tagger != "none")
        model->model->tag(s, tagger, error);
      if (parser != "none")
        model->model->parse(s, parser, error);

      output->write_sentence(s, os);
      json.value(os.str(), true);
      os.str(string());

      return true;
    }

   private:
    sentence s;
    string error;
    ostringstream os;
    unique_ptr<input_format> input;
    const string& tagger;
    const string& parser;
    unique_ptr<output_format> output;
  };
  return req.respond(generator::mime, new generator(model, input.release(), tagger, parser, output.release()));
}

// REST service helpers

const string& udpipe_service::get_rest_model_id(microrestd::rest_request& req) {
  static string empty;

  auto model_it = req.params.find("model");
  return model_it == req.params.end() ? empty : model_it->second;
}

const string& udpipe_service::get_data(microrestd::rest_request& req, string& error) {
  auto data_it = req.params.find("data");
  if (data_it == req.params.end()) return error.assign("Required argument 'data' is missing.\n"), empty;

  return data_it->second;
}

input_format* udpipe_service::get_input_format(microrestd::rest_request& req, const model_info* model, bool& is_tokenizer, string& error) {
  auto tokenizer_it = req.params.find("tokenizer");
  if (tokenizer_it != req.params.end()) {
    if (!model->can_tokenize) return error.assign("The required model does not contain a tokenizer!"), nullptr;
    input_format* tokenizer = model->model->new_tokenizer(Model::DEFAULT);
    if (!tokenizer) return error.assign("Cannot construct a tokenizer instance!"), nullptr;
    return is_tokenizer = true, tokenizer;
  }

  auto& input = req.params.emplace("input", "conllu").first->second;
  auto input_format = input_format::new_input_format(input);
  if (!input_format) return error.assign("Unknown input format '").append(input).append("'.\n"), nullptr;
  return is_tokenizer = false, input_format;
}

const string& udpipe_service::get_tagger(microrestd::rest_request& req, const model_info* model, string& error) {
  auto& tagger = req.params.emplace("tagger", "none").first->second;
  if (tagger != "none" && !model->can_tag) return error.assign("The required model does not contain a tagger!"), empty;
  return tagger;
}

const string& udpipe_service::get_parser(microrestd::rest_request& req, const model_info* model, string& error) {
  auto& parser = req.params.emplace("parser", "none").first->second;
  if (parser != "none" && !model->can_parse) return error.assign("The required model does not contain a parser!"), empty;
  return parser;
}

output_format* udpipe_service::get_output_format(microrestd::rest_request& req, string& error) {
  auto& output = req.params.emplace("output", "conllu").first->second;
  auto output_format = output_format::new_output_format(output);
  if (!output_format) return error.assign("Unknown output format '").append(output).append("'.\n"), nullptr;
  return output_format;
}

const string udpipe_service::empty;

} // namespace udpipe
} // namespace ufal
<commit_msg>Pass tokenizer options to tokenizer in the REST server.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <sstream>

#include "udpipe_service.h"

namespace ufal {
namespace udpipe {

// Init the UDPipe service -- load the models
bool udpipe_service::init(const vector<model_description>& model_descriptions) {
  if (model_descriptions.empty()) return false;

  // Load models
  models.clear();
  rest_models_map.clear();
  for (auto& model_description : model_descriptions) {
    Model* model = Model::load(model_description.file.c_str());
    if (!model) return false;

    // Store the model
    models.emplace_back(model_description.rest_id, model_description.acknowledgements, model);
  }

  // Fill rest_models_map with model name and aliases
  for (auto& model : models) {
    // Fail if this model id is aready in use.
    if (!rest_models_map.emplace(model.rest_id, &model).second) return false;

    // Create (but not overwrite) id without version.
    for (unsigned i = 0; i+1+6 < model.rest_id.size(); i++)
      if (model.rest_id[i] == '-') {
        bool is_version = true;
        for (unsigned j = i+1; j < i+1+6; j++)
          is_version = is_version && model.rest_id[j] >= '0' && model.rest_id[j] <= '9';
        if (is_version)
          rest_models_map.emplace(model.rest_id.substr(0, i) + model.rest_id.substr(i+1+6), &model);
      }

    // Create (but not overwrite) hyphen-separated prefixes.
    for (unsigned i = 0; i < model.rest_id.size(); i++)
      if (model.rest_id[i] == '-')
        rest_models_map.emplace(model.rest_id.substr(0, i), &model);
  }
  // Default model
  rest_models_map.emplace(string(), &models.front());

  // Init REST service
  json_models.clear().object().indent().key("models").indent().object();
  for (auto& model : models) {
    json_models.indent().key(model.rest_id).indent().array();
    if (model.can_tokenize) json_models.value("tokenizer");
    if (model.can_tag) json_models.value("tagger");
    if (model.can_parse) json_models.value("parser");
    json_models.close();
  }
  json_models.indent().close().indent().key("default_model").indent().value(model_descriptions.front().rest_id).finish(true);

  return true;
}

// Handlers with their URLs
unordered_map<string, bool (udpipe_service::*)(microrestd::rest_request&)> udpipe_service::handlers = {
  // REST service
  {"/models", &udpipe_service::handle_rest_models},
  {"/process", &udpipe_service::handle_rest_process},
};

// Handle a request using the specified URL/handler map
bool udpipe_service::handle(microrestd::rest_request& req) {
  auto handler_it = handlers.find(req.url);
  return handler_it == handlers.end() ? req.respond_not_found() : (this->*handler_it->second)(req);
}

// Load selected model
const udpipe_service::model_info* udpipe_service::load_rest_model(const string& rest_id, string& error) {
  auto model_it = rest_models_map.find(rest_id);
  if (model_it == rest_models_map.end())
    return error.assign("Requested model '").append(rest_id).append("' does not exist.\n"), nullptr;

  return model_it->second;
}

// REST service
inline microrestd::string_piece sp(string_piece str) { return microrestd::string_piece(str.str, str.len); }
inline microrestd::string_piece sp(const char* str, size_t len) { return microrestd::string_piece(str, len); }

udpipe_service::rest_response_generator::rest_response_generator(const model_info* model) : model(model) {
  json.object();
  json.indent().key("model").indent().value(model->rest_id);
  json.indent().key("acknowledgements").indent().array();
  json.indent().value("http://ufal.mff.cuni.cz/udpipe#udpipe_acknowledgements");
  if (!model->acknowledgements.empty()) json.indent().value(model->acknowledgements);
  json.indent().close().indent().key("result").indent().value("");
}

// REST service handlers

bool udpipe_service::handle_rest_models(microrestd::rest_request& req) {
  return req.respond(rest_response_generator::mime, json_models);
}

bool udpipe_service::handle_rest_process(microrestd::rest_request& req) {
  string error;
  auto rest_id = get_rest_model_id(req);
  auto model = load_rest_model(rest_id, error);
  if (!model) return req.respond_error(error);

  auto& data = get_data(req, error); if (!error.empty()) return req.respond_error(error);
  bool tokenizer = false;
  unique_ptr<input_format> input(get_input_format(req, model, tokenizer, error)); if (!input) return req.respond_error(error);
  auto& tagger = get_tagger(req, model, error); if (!error.empty()) return req.respond_error(error);
  auto& parser = get_parser(req, model, error); if (!error.empty()) return req.respond_error(error);
  unique_ptr<output_format> output(get_output_format(req, error)); if (!output) return req.respond_error(error);

  // Try loading the input if tokenizer is not used
  if (!tokenizer) {
    input->set_text(data);
    sentence s;
    while (input->next_sentence(s, error)) {}
    if (!error.empty())
      return req.respond_error(error.insert(0, "Cannot read input data: ").append("\n"));
  }

  input->set_text(data);
  class generator : public rest_response_generator {
   public:
    generator(const model_info* model, input_format* input, const string& tagger, const string& parser, output_format* output)
        : rest_response_generator(model), input(input), tagger(tagger), parser(parser), output(output) {}

    bool generate() {
      if (!input->next_sentence(s, error)) {
        output->finish_document(os);
        json.value(os.str(), true);
        os.str(string());

        json.finish(true);

        return false;
      }

      if (tagger != "none")
        model->model->tag(s, tagger, error);
      if (parser != "none")
        model->model->parse(s, parser, error);

      output->write_sentence(s, os);
      json.value(os.str(), true);
      os.str(string());

      return true;
    }

   private:
    sentence s;
    string error;
    ostringstream os;
    unique_ptr<input_format> input;
    const string& tagger;
    const string& parser;
    unique_ptr<output_format> output;
  };
  return req.respond(generator::mime, new generator(model, input.release(), tagger, parser, output.release()));
}

// REST service helpers

const string& udpipe_service::get_rest_model_id(microrestd::rest_request& req) {
  static string empty;

  auto model_it = req.params.find("model");
  return model_it == req.params.end() ? empty : model_it->second;
}

const string& udpipe_service::get_data(microrestd::rest_request& req, string& error) {
  auto data_it = req.params.find("data");
  if (data_it == req.params.end()) return error.assign("Required argument 'data' is missing.\n"), empty;

  return data_it->second;
}

input_format* udpipe_service::get_input_format(microrestd::rest_request& req, const model_info* model, bool& is_tokenizer, string& error) {
  auto tokenizer_it = req.params.find("tokenizer");
  if (tokenizer_it != req.params.end()) {
    if (!model->can_tokenize) return error.assign("The required model does not contain a tokenizer!"), nullptr;
    input_format* tokenizer = model->model->new_tokenizer(tokenizer_it->second);
    if (!tokenizer) return error.assign("Cannot construct a tokenizer instance!"), nullptr;
    return is_tokenizer = true, tokenizer;
  }

  auto& input = req.params.emplace("input", "conllu").first->second;
  auto input_format = input_format::new_input_format(input);
  if (!input_format) return error.assign("Unknown input format '").append(input).append("'.\n"), nullptr;
  return is_tokenizer = false, input_format;
}

const string& udpipe_service::get_tagger(microrestd::rest_request& req, const model_info* model, string& error) {
  auto& tagger = req.params.emplace("tagger", "none").first->second;
  if (tagger != "none" && !model->can_tag) return error.assign("The required model does not contain a tagger!"), empty;
  return tagger;
}

const string& udpipe_service::get_parser(microrestd::rest_request& req, const model_info* model, string& error) {
  auto& parser = req.params.emplace("parser", "none").first->second;
  if (parser != "none" && !model->can_parse) return error.assign("The required model does not contain a parser!"), empty;
  return parser;
}

output_format* udpipe_service::get_output_format(microrestd::rest_request& req, string& error) {
  auto& output = req.params.emplace("output", "conllu").first->second;
  auto output_format = output_format::new_output_format(output);
  if (!output_format) return error.assign("Unknown output format '").append(output).append("'.\n"), nullptr;
  return output_format;
}

const string udpipe_service::empty;

} // namespace udpipe
} // namespace ufal
<|endoftext|>


<commit_before>#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <string>
#include <libgen.h>

int main(int argc, char *argv[]) {
  if(argc != 3) { printf("USAGE: %s imagefile outputdir", argv[0]); }

  std::string input_filename = std::string(argv[1]);
  std::string input_basename = std::string(basename(argv[1]));

  std::string output_dir = std::string(argv[2]);

  Pix *image = pixRead(input_filename.c_str());
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, NULL, NULL);
  printf("Found %d textline image components.\n", boxes->n);

  int lastindex = input_basename.find_last_of(".");
  std::string basename = input_basename.substr(0, lastindex).c_str();
  std::string extension = input_basename.substr(lastindex + 1).c_str();
  std::string outdir = output_dir.c_str();
  int linedirLen = outdir.length()+1+basename.length()+strlen("-line_extract_")+extension.length()+1;
  char* linedir = (char*)malloc(linedirLen*sizeof(char));
  sprintf(linedir, "%s/%s-line_extract_%s", output_dir.c_str(), basename.c_str(), extension.c_str());
  printf("Writing to directory [%s].  If this fails, try:\n    mkdir -p %s\n\n\n", linedir, linedir);

  for (int i = 0; i < boxes->n; i++) {
    BOX* box = boxaGetBox(boxes, i, L_CLONE);
    PIX* pixd= pixClipRectangle(image, box, NULL);

    char* linefilename = (char*)malloc((linedirLen+strlen("/line00.")+extension.length()+1)*sizeof(char));
    sprintf(linefilename, "%s/line%02d.%s", linedir, i, extension.c_str());
    printf("  Writing %s\n", linefilename);
    pixWrite(linefilename, pixd, IFF_DEFAULT);
    pixDestroy(&pixd);
    boxDestroy(&box);
    free(linefilename);
  }
  return 0;
}
<commit_msg>binarize output<commit_after>//#include <tesseract/baseapi.h>
//#include <leptonica/allheaders.h>
#include "baseapi.h"
#include "allheaders.h"
#include <string>
#include <libgen.h>

int main(int argc, char *argv[]) {
  if(argc != 3) { printf("USAGE: %s imagefile outputdir", argv[0]); }

  std::string input_filename = std::string(argv[1]);
  std::string input_basename = std::string(basename(argv[1]));

  std::string output_dir = std::string(argv[2]);

  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  Pix *image0 = pixRead(input_filename.c_str());
  api->SetImage(image0);
  Pix* image = api->GetThresholdedImage();
  api->SetImage(image);
  Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, false, 0, NULL, NULL, NULL);
  printf("204c\n");

  printf("Found %d textline image components.\n", boxes->n);

  int lastindex = input_basename.find_last_of(".");
  std::string basename = input_basename.substr(0, lastindex).c_str();
  std::string extension = input_basename.substr(lastindex + 1).c_str();

  std::string outdir = output_dir.c_str();
  int linedirLen = outdir.length()+1+basename.length()+strlen("-line_extract_")+extension.length();
  char* linedir = (char*)malloc((linedirLen+1)*sizeof(char));
  sprintf(linedir, "%s/%s-line_extract_%s", output_dir.c_str(), basename.c_str(), extension.c_str());
  printf("Writing to directory [%s].  If this fails, try:\n    mkdir -p %s\n\n\n", linedir, linedir);

  for (int i = 0; i < boxes->n; i++) {
    BOX* box = boxaGetBox(boxes, i, L_CLONE);
    PIX* pixd= pixClipRectangle(image, box, NULL);

    char* linefilename = (char*)malloc((linedirLen+strlen("/line00.")+extension.length()+1)*sizeof(char));
    sprintf(linefilename, "%s/line%02d.%s", linedir, i, extension.c_str());
    printf("  Writing %s\n", linefilename);
    pixWrite(linefilename, pixd, IFF_DEFAULT);
    pixDestroy(&pixd);
    boxDestroy(&box);
    free(linefilename);
  }

  free(linedir);
  return 0;
}
<|endoftext|>


<commit_before>#include "UnrealEnginePythonPrivatePCH.h"

#if WITH_EDITOR
#include "LevelEditor.h"
#include "Editor/LevelEditor/Public/ILevelViewport.h"
#include "Editor/UnrealEd/Public/LevelEditorViewport.h"
#endif

PyObject *py_unreal_engine_get_game_viewport_client(PyObject * self, PyObject * args) {

	UGameViewportClient *viewport_client = GEngine->GameViewport;
	if (!viewport_client) {
		return PyErr_Format(PyExc_Exception, "no engine GameViewport found");
	}
	ue_PyUObject *ret = ue_get_python_wrapper(GEngine->GameViewport);
	if (!ret)
		return PyErr_Format(PyExc_Exception, "uobject is in invalid state");
	Py_INCREF(ret);
	return (PyObject *)ret;
}

#if WITH_EDITOR
PyObject *py_unreal_engine_get_editor_pie_game_viewport_client(PyObject * self, PyObject * args) {

	UGameViewportClient *viewport_client = GEditor->GameViewport;
	if (!viewport_client) {
		return PyErr_Format(PyExc_Exception, "no editor GameViewport found");
	}
	ue_PyUObject *ret = ue_get_python_wrapper(viewport_client);
	if (!ret)
		return PyErr_Format(PyExc_Exception, "uobject is in invalid state");
	Py_INCREF(ret);
	return (PyObject *)ret;
}

PyObject *py_unreal_engine_editor_set_view_mode(PyObject * self, PyObject * args) {

	int mode;

	if (!PyArg_ParseTuple(args, "i:editor_set_view_mode", &mode)) {
		return NULL;
	}

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewMode((EViewModeIndex)mode);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_camera_speed(PyObject * self, PyObject * args) {

	int speed;

	if (!PyArg_ParseTuple(args, "f:editor_set_camera_speed", &speed)) {
		return NULL;
	}

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetCameraSpeedSetting(speed);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_view_location(PyObject * self, PyObject * args) {

	PyObject *py_vector;

	if (!PyArg_ParseTuple(args, "O:editor_set_view_location", &py_vector)) {
		return NULL;
	}

	ue_PyFVector *vector = py_ue_is_fvector(py_vector);
	if (!vector)
		return PyErr_Format(PyExc_Exception, "argument is not a FVector");

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewLocation(vector->vec);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_view_rotation(PyObject * self, PyObject * args) {

	PyObject *py_rotator;

	if (!PyArg_ParseTuple(args, "O:editor_set_view_rotation", &py_rotator)) {
		return NULL;
	}

	ue_PyFRotator *rotator = py_ue_is_frotator(py_rotator);
	if (!rotator)
		return PyErr_Format(PyExc_Exception, "argument is not a FRotator");

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewRotation(rotator->rot);

	Py_RETURN_NONE;
}

#endif

PyObject *py_ue_add_viewport_widget_content(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	PyObject *py_widget;
	int z_order = 0;

	if (!PyArg_ParseTuple(args, "O|i:add_viewport_widget_content", &py_widget, &z_order)) {
		return NULL;
	}

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport)
		return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient");

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_widget);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	// TODO: decrement reference when destroying parent
	Py_INCREF(py_swidget);

	viewport->AddViewportWidgetContent(py_swidget->s_widget, z_order);

	Py_INCREF(Py_None);
	return Py_None;
}

PyObject *py_ue_remove_viewport_widget_content(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	PyObject *py_widget;

	if (!PyArg_ParseTuple(args, "O:remove_viewport_widget_content", &py_widget)) {
		return NULL;
	}

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport)
		return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient");

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_widget);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	Py_DECREF(py_swidget);

	viewport->RemoveViewportWidgetContent(py_swidget->s_widget);

	Py_INCREF(Py_None);
	return Py_None;
}

PyObject *py_ue_remove_all_viewport_widgets(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport)
		return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient");

	viewport->RemoveAllViewportWidgets();

	Py_INCREF(Py_None);
	return Py_None;
}

<commit_msg>allows attaching slate widgets to running worlds<commit_after>#include "UnrealEnginePythonPrivatePCH.h"

#if WITH_EDITOR
#include "LevelEditor.h"
#include "Editor/LevelEditor/Public/ILevelViewport.h"
#include "Editor/UnrealEd/Public/LevelEditorViewport.h"
#endif

PyObject *py_unreal_engine_get_game_viewport_client(PyObject * self, PyObject * args) {

	UGameViewportClient *viewport_client = GEngine->GameViewport;
	if (!viewport_client) {
		return PyErr_Format(PyExc_Exception, "no engine GameViewport found");
	}
	ue_PyUObject *ret = ue_get_python_wrapper(GEngine->GameViewport);
	if (!ret)
		return PyErr_Format(PyExc_Exception, "uobject is in invalid state");
	Py_INCREF(ret);
	return (PyObject *)ret;
}

#if WITH_EDITOR
PyObject *py_unreal_engine_get_editor_pie_game_viewport_client(PyObject * self, PyObject * args) {

	UGameViewportClient *viewport_client = GEditor->GameViewport;
	if (!viewport_client) {
		return PyErr_Format(PyExc_Exception, "no editor GameViewport found");
	}
	ue_PyUObject *ret = ue_get_python_wrapper(viewport_client);
	if (!ret)
		return PyErr_Format(PyExc_Exception, "uobject is in invalid state");
	Py_INCREF(ret);
	return (PyObject *)ret;
}

PyObject *py_unreal_engine_editor_set_view_mode(PyObject * self, PyObject * args) {

	int mode;

	if (!PyArg_ParseTuple(args, "i:editor_set_view_mode", &mode)) {
		return NULL;
	}

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewMode((EViewModeIndex)mode);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_camera_speed(PyObject * self, PyObject * args) {

	int speed;

	if (!PyArg_ParseTuple(args, "f:editor_set_camera_speed", &speed)) {
		return NULL;
	}

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetCameraSpeedSetting(speed);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_view_location(PyObject * self, PyObject * args) {

	PyObject *py_vector;

	if (!PyArg_ParseTuple(args, "O:editor_set_view_location", &py_vector)) {
		return NULL;
	}

	ue_PyFVector *vector = py_ue_is_fvector(py_vector);
	if (!vector)
		return PyErr_Format(PyExc_Exception, "argument is not a FVector");

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewLocation(vector->vec);

	Py_RETURN_NONE;
}

PyObject *py_unreal_engine_editor_set_view_rotation(PyObject * self, PyObject * args) {

	PyObject *py_rotator;

	if (!PyArg_ParseTuple(args, "O:editor_set_view_rotation", &py_rotator)) {
		return NULL;
	}

	ue_PyFRotator *rotator = py_ue_is_frotator(py_rotator);
	if (!rotator)
		return PyErr_Format(PyExc_Exception, "argument is not a FRotator");

	FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");

	if (!EditorModule.GetFirstActiveViewport().IsValid())
		return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport");

	FLevelEditorViewportClient &viewport_client = EditorModule.GetFirstActiveViewport()->GetLevelViewportClient();

	viewport_client.SetViewRotation(rotator->rot);

	Py_RETURN_NONE;
}

#endif

PyObject *py_ue_add_viewport_widget_content(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	PyObject *py_widget;
	int z_order = 0;

	if (!PyArg_ParseTuple(args, "O|i:add_viewport_widget_content", &py_widget, &z_order)) {
		return NULL;
	}

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport) {
		UWorld *world = ue_py_check_type<UWorld>(self);
		if (!world)
			return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient or a UWorld");
		viewport = world->GetGameViewport();
		if (!viewport)
			return PyErr_Format(PyExc_Exception, "cannot retrieve GameViewportClient from UWorld");
	}

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_widget);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	// Do not increment reference count as it is assumed this function is used in a PyComponent/PyActor/ that can holds reference to
	// it in various ways
	// Py_INCREF(py_swidget);

	viewport->AddViewportWidgetContent(py_swidget->s_widget, z_order);

	Py_INCREF(Py_None);
	return Py_None;
}

PyObject *py_ue_remove_viewport_widget_content(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	PyObject *py_widget;

	if (!PyArg_ParseTuple(args, "O:remove_viewport_widget_content", &py_widget)) {
		return NULL;
	}

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport)
		return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient");

	ue_PySWidget *py_swidget = py_ue_is_swidget(py_widget);
	if (!py_swidget) {
		return PyErr_Format(PyExc_Exception, "argument is not a SWidget");
	}
	Py_DECREF(py_swidget);

	viewport->RemoveViewportWidgetContent(py_swidget->s_widget);

	Py_INCREF(Py_None);
	return Py_None;
}

PyObject *py_ue_remove_all_viewport_widgets(ue_PyUObject *self, PyObject * args) {

	ue_py_check(self);

	UGameViewportClient *viewport = ue_py_check_type<UGameViewportClient>(self);
	if (!viewport)
		return PyErr_Format(PyExc_Exception, "object is not a GameViewportClient");

	viewport->RemoveAllViewportWidgets();

	Py_INCREF(Py_None);
	return Py_None;
}

<|endoftext|>