<commit_before>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 1999-2007 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 *  $Id$
 *
 *  Application class
 *
 */

#include <wx/wxprec.h>

#include <wx/wx.h>
#include <wx/config.h>
#include <wx/fs_zip.h>
#include <wx/image.h>
#include <wx/cmdline.h>
#include <wx/log.h>
#include <wx/xrc/xmlres.h>
#include <wx/xrc/xh_all.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/sysopt.h>

#ifdef USE_SPARKLE
#include <Sparkle/SUCarbonAPI.h>
#endif // USE_SPARKLE

#if !wxUSE_UNICODE
    #error "Unicode build of wxWidgets is required by Poedit"
#endif

#include "edapp.h"
#include "edframe.h"
#include "manager.h"
#include "prefsdlg.h"
#include "parser.h"
#include "chooselang.h"
#include "icons.h"

IMPLEMENT_APP(PoeditApp);

wxString PoeditApp::GetAppPath() const
{
#if defined(__UNIX__)
    wxString home;
    if (!wxGetEnv(_T("POEDIT_PREFIX"), &home))
        home = wxString::FromAscii(POEDIT_PREFIX);
    return home;
#elif defined(__WXMSW__)
    wxString exedir;
    wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(),
                          &exedir, NULL, NULL);
    wxFileName fn = wxFileName::DirName(exedir);
    fn.RemoveLastDir();
    return fn.GetFullPath();
#else
#error "Unsupported platform!"
#endif
}

wxString PoeditApp::GetAppVersion() const
{
    wxString version(_T("1.3.9"));
    return version;
}

#ifndef __WXMAC__
static wxArrayString gs_filesToOpen;
#endif

extern void InitXmlResource();

bool PoeditApp::OnInit()
{
    if (!wxApp::OnInit())
        return false;

#ifdef __WXMAC__
    wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1);
#endif

#if defined(__UNIX__) && !defined(__WXMAC__)
    wxString home = wxGetHomeDir() + _T("/");

    // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config
    // (upgrade from older versions of Poedit which used ~/.poedit file)
    if (!wxDirExists(home + _T(".poedit")))
    {
        if (wxFileExists(home + _T(".poedit")))
            wxRenameFile(home + _T(".poedit"), home + _T(".poedit2"));
        wxMkdir(home + _T(".poedit"));
        if (wxFileExists(home + _T(".poedit2")))
            wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config"));
    }
#endif

    SetVendorName(_T("Vaclav Slavik"));
    SetAppName(_T("Poedit"));

#if defined(__WXMAC__)
    #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg"))
#elif defined(__UNIX__)
    #define CFG_FILE (home + _T(".poedit/config"))
#else
    #define CFG_FILE wxEmptyString
#endif

#ifdef __WXMAC__
    // upgrade from the old location of config file:
    wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg");
    if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE))
    {
        wxRenameFile(oldcfgfile, CFG_FILE);
    }
#endif

    wxConfigBase::Set(
        new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString,
                     wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE));
    wxConfigBase::Get()->SetExpandEnvVars(false);

    wxImage::AddHandler(new wxGIFHandler);
    wxImage::AddHandler(new wxPNGHandler);
    wxXmlResource::Get()->InitAllHandlers();
    InitXmlResource();

    SetDefaultCfg(wxConfig::Get());

#ifdef HAS_INSERT_PROVIDER
    wxArtProvider::Insert(new PoeditArtProvider);
#else
    wxArtProvider::PushProvider(new PoeditArtProvider);
#endif

#ifdef __WXMAC__
    wxLocale::AddCatalogLookupPathPrefix(
        wxStandardPaths::Get().GetResourcesDir() + _T("/locale"));
#else
    wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale"));
#endif

    m_locale.Init(GetUILanguage());

    m_locale.AddCatalog(_T("poedit"));

    if (wxConfig::Get()->Read(_T("translator_name"), _T("nothing")) == _T("nothing"))
    {
        wxMessageBox(_("This is first time you run Poedit.\nPlease fill in your name and e-mail address.\n(This information is used only in catalogs headers)"), _("Setup"),
                       wxOK | wxICON_INFORMATION);

        PreferencesDialog dlg;
        dlg.TransferTo(wxConfig::Get());
        if (dlg.ShowModal() == wxID_OK)
            dlg.TransferFrom(wxConfig::Get());
    }

    // opening files or creating empty window is handled differently on Macs,
    // using MacOpenFile() and MacNewFile(), so don't do it here:
#ifndef __WXMAC__
    if (gs_filesToOpen.GetCount() == 0)
    {
        OpenNewFile();
    }
    else
    {
        for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++)
            OpenFile(gs_filesToOpen[i]);
        gs_filesToOpen.clear();
    }
#endif // !__WXMAC__

#ifdef USE_SPARKLE
    SUSparkleInitializeForCarbon();
#endif // USE_SPARKLE

    return true;
}

void PoeditApp::OpenNewFile()
{
    if (wxConfig::Get()->Read(_T("manager_startup"), (long)false))
        ManagerFrame::Create()->Show(true);
    else
        PoeditFrame::Create(wxEmptyString);
}

void PoeditApp::OpenFile(const wxString& name)
{
    PoeditFrame::Create(name);
}

void PoeditApp::SetDefaultParsers(wxConfigBase *cfg)
{
    ParsersDB pdb;
    bool changed = false;
    wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"),
                                         _T("1.2.x"));
    pdb.Read(cfg);

    // Add parsers for languages supported by gettext itself (but only if the
    // user didn't already add language with this name himself):
    static struct
    {
        const wxChar *name;
        const wxChar *exts;
    } s_gettextLangs[] = {
        { _T("C/C++"),    _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") },
#ifndef __WINDOWS__
        // FIXME: not supported by 0.13.1 shipped with poedit on win32
        { _T("C#"),       _T("*.cs") },
#endif
        { _T("Java"),     _T("*.java") },
        { _T("Perl"),     _T("*.pl") },
        { _T("PHP"),      _T("*.php") },
        { _T("Python"),   _T("*.py") },
        { _T("TCL"),      _T("*.tcl") },
        { NULL, NULL }
    };

    for (size_t i = 0; s_gettextLangs[i].name != NULL; i++)
    {
        // if this lang is already registered, don't overwrite it:
        if (pdb.FindParser(s_gettextLangs[i].name) != -1)
            continue;

        // otherwise add new parser:
        Parser p;
        p.Name = s_gettextLangs[i].name;
        p.Extensions = s_gettextLangs[i].exts;
        p.Command = _T("xgettext --force-po -o %o %C %K %F");
        p.KeywordItem = _T("-k%k");
        p.FileItem = _T("%f");
        p.CharsetItem = _T("--from-code=%c");
        pdb.Add(p);
        changed = true;
    }

    // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi:
#ifdef __WINDOWS__
    if (defaultsVersion == _T("1.2.x"))
    {
        Parser p;
        p.Name = _T("Delphi (dxgettext)");
        p.Extensions = _T("*.pas;*.inc;*.dpr;*.xfm;*.dfm");
        p.Command = _T("dxgettext --so %o %F");
        p.KeywordItem = wxEmptyString;
        p.FileItem = _T("%f");
        pdb.Add(p);
        changed = true;
    }
#endif

    // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code:
    if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4"))
    {
        int cpp = pdb.FindParser(_T("C/C++"));
        if (cpp != -1)
        {
            if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F"))
            {
                pdb[cpp].Command = _T("xgettext --force-po -o %o %C %K %F");
                pdb[cpp].CharsetItem = _T("--from-code=%c");
                changed = true;
            }
        }
    }

    if (changed)
    {
        pdb.Write(cfg);
        cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion());
    }
}

void PoeditApp::SetDefaultCfg(wxConfigBase *cfg)
{
    SetDefaultParsers(cfg);

    if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return;

    if (cfg->Read(_T("TM/database_path"), wxEmptyString).empty())
    {
        wxString dbpath;
#if defined(__WXMAC__)
        dbpath = wxStandardPaths::Get().GetUserDataDir() + _T("/tm");
#elif defined(__UNIX__)
        dbpath = wxGetHomeDir() + _T("/.poedit/tm");
#elif defined(__WXMSW__)
        dbpath = wxGetHomeDir() + _T("\\poedit_tm");
#endif
        cfg->Write(_T("TM/database_path"), dbpath);
    }

    if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty())
    {
        wxString paths;
#if defined(__UNIX__)
        paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale");
#elif defined(__WXMSW__)
        paths = _T("C:");
#endif
        cfg->Write(_T("TM/search_paths"), paths);
    }

    cfg->Write(_T("version"), GetAppVersion());
}

void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    wxApp::OnInitCmdLine(parser);
    parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING,
                    wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
}

bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    if (!wxApp::OnCmdLineParsed(parser))
        return false;

#ifndef __WXMAC__
    for (size_t i = 0; i < parser.GetParamCount(); i++)
        gs_filesToOpen.Add(parser.GetParam(i));
#endif

    return true;
}
<commit_msg>compilation fix for OS X when building against wxMac < 2.8.5 (as comes with Leopard)<commit_after>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 1999-2007 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 *  $Id$
 *
 *  Application class
 *
 */

#include <wx/wxprec.h>

#include <wx/wx.h>
#include <wx/config.h>
#include <wx/fs_zip.h>
#include <wx/image.h>
#include <wx/cmdline.h>
#include <wx/log.h>
#include <wx/xrc/xmlres.h>
#include <wx/xrc/xh_all.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/sysopt.h>

#ifdef USE_SPARKLE
#include <Sparkle/SUCarbonAPI.h>
#endif // USE_SPARKLE

#if !wxUSE_UNICODE
    #error "Unicode build of wxWidgets is required by Poedit"
#endif

#include "edapp.h"
#include "edframe.h"
#include "manager.h"
#include "prefsdlg.h"
#include "parser.h"
#include "chooselang.h"
#include "icons.h"

IMPLEMENT_APP(PoeditApp);

wxString PoeditApp::GetAppPath() const
{
#if defined(__UNIX__)
    wxString home;
    if (!wxGetEnv(_T("POEDIT_PREFIX"), &home))
        home = wxString::FromAscii(POEDIT_PREFIX);
    return home;
#elif defined(__WXMSW__)
    wxString exedir;
    wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(),
                          &exedir, NULL, NULL);
    wxFileName fn = wxFileName::DirName(exedir);
    fn.RemoveLastDir();
    return fn.GetFullPath();
#else
#error "Unsupported platform!"
#endif
}

wxString PoeditApp::GetAppVersion() const
{
    wxString version(_T("1.3.9"));
    return version;
}

#ifndef __WXMAC__
static wxArrayString gs_filesToOpen;
#endif

extern void InitXmlResource();

bool PoeditApp::OnInit()
{
    if (!wxApp::OnInit())
        return false;

#if defined(__WXMAC__) && wxCHECK_VERSION(2,8,5)
    wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1);
#endif

#if defined(__UNIX__) && !defined(__WXMAC__)
    wxString home = wxGetHomeDir() + _T("/");

    // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config
    // (upgrade from older versions of Poedit which used ~/.poedit file)
    if (!wxDirExists(home + _T(".poedit")))
    {
        if (wxFileExists(home + _T(".poedit")))
            wxRenameFile(home + _T(".poedit"), home + _T(".poedit2"));
        wxMkdir(home + _T(".poedit"));
        if (wxFileExists(home + _T(".poedit2")))
            wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config"));
    }
#endif

    SetVendorName(_T("Vaclav Slavik"));
    SetAppName(_T("Poedit"));

#if defined(__WXMAC__)
    #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg"))
#elif defined(__UNIX__)
    #define CFG_FILE (home + _T(".poedit/config"))
#else
    #define CFG_FILE wxEmptyString
#endif

#ifdef __WXMAC__
    // upgrade from the old location of config file:
    wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg");
    if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE))
    {
        wxRenameFile(oldcfgfile, CFG_FILE);
    }
#endif

    wxConfigBase::Set(
        new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString,
                     wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE));
    wxConfigBase::Get()->SetExpandEnvVars(false);

    wxImage::AddHandler(new wxGIFHandler);
    wxImage::AddHandler(new wxPNGHandler);
    wxXmlResource::Get()->InitAllHandlers();
    InitXmlResource();

    SetDefaultCfg(wxConfig::Get());

#ifdef HAS_INSERT_PROVIDER
    wxArtProvider::Insert(new PoeditArtProvider);
#else
    wxArtProvider::PushProvider(new PoeditArtProvider);
#endif

#ifdef __WXMAC__
    wxLocale::AddCatalogLookupPathPrefix(
        wxStandardPaths::Get().GetResourcesDir() + _T("/locale"));
#else
    wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale"));
#endif

    m_locale.Init(GetUILanguage());

    m_locale.AddCatalog(_T("poedit"));

    if (wxConfig::Get()->Read(_T("translator_name"), _T("nothing")) == _T("nothing"))
    {
        wxMessageBox(_("This is first time you run Poedit.\nPlease fill in your name and e-mail address.\n(This information is used only in catalogs headers)"), _("Setup"),
                       wxOK | wxICON_INFORMATION);

        PreferencesDialog dlg;
        dlg.TransferTo(wxConfig::Get());
        if (dlg.ShowModal() == wxID_OK)
            dlg.TransferFrom(wxConfig::Get());
    }

    // opening files or creating empty window is handled differently on Macs,
    // using MacOpenFile() and MacNewFile(), so don't do it here:
#ifndef __WXMAC__
    if (gs_filesToOpen.GetCount() == 0)
    {
        OpenNewFile();
    }
    else
    {
        for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++)
            OpenFile(gs_filesToOpen[i]);
        gs_filesToOpen.clear();
    }
#endif // !__WXMAC__

#ifdef USE_SPARKLE
    SUSparkleInitializeForCarbon();
#endif // USE_SPARKLE

    return true;
}

void PoeditApp::OpenNewFile()
{
    if (wxConfig::Get()->Read(_T("manager_startup"), (long)false))
        ManagerFrame::Create()->Show(true);
    else
        PoeditFrame::Create(wxEmptyString);
}

void PoeditApp::OpenFile(const wxString& name)
{
    PoeditFrame::Create(name);
}

void PoeditApp::SetDefaultParsers(wxConfigBase *cfg)
{
    ParsersDB pdb;
    bool changed = false;
    wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"),
                                         _T("1.2.x"));
    pdb.Read(cfg);

    // Add parsers for languages supported by gettext itself (but only if the
    // user didn't already add language with this name himself):
    static struct
    {
        const wxChar *name;
        const wxChar *exts;
    } s_gettextLangs[] = {
        { _T("C/C++"),    _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") },
#ifndef __WINDOWS__
        // FIXME: not supported by 0.13.1 shipped with poedit on win32
        { _T("C#"),       _T("*.cs") },
#endif
        { _T("Java"),     _T("*.java") },
        { _T("Perl"),     _T("*.pl") },
        { _T("PHP"),      _T("*.php") },
        { _T("Python"),   _T("*.py") },
        { _T("TCL"),      _T("*.tcl") },
        { NULL, NULL }
    };

    for (size_t i = 0; s_gettextLangs[i].name != NULL; i++)
    {
        // if this lang is already registered, don't overwrite it:
        if (pdb.FindParser(s_gettextLangs[i].name) != -1)
            continue;

        // otherwise add new parser:
        Parser p;
        p.Name = s_gettextLangs[i].name;
        p.Extensions = s_gettextLangs[i].exts;
        p.Command = _T("xgettext --force-po -o %o %C %K %F");
        p.KeywordItem = _T("-k%k");
        p.FileItem = _T("%f");
        p.CharsetItem = _T("--from-code=%c");
        pdb.Add(p);
        changed = true;
    }

    // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi:
#ifdef __WINDOWS__
    if (defaultsVersion == _T("1.2.x"))
    {
        Parser p;
        p.Name = _T("Delphi (dxgettext)");
        p.Extensions = _T("*.pas;*.inc;*.dpr;*.xfm;*.dfm");
        p.Command = _T("dxgettext --so %o %F");
        p.KeywordItem = wxEmptyString;
        p.FileItem = _T("%f");
        pdb.Add(p);
        changed = true;
    }
#endif

    // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code:
    if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4"))
    {
        int cpp = pdb.FindParser(_T("C/C++"));
        if (cpp != -1)
        {
            if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F"))
            {
                pdb[cpp].Command = _T("xgettext --force-po -o %o %C %K %F");
                pdb[cpp].CharsetItem = _T("--from-code=%c");
                changed = true;
            }
        }
    }

    if (changed)
    {
        pdb.Write(cfg);
        cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion());
    }
}

void PoeditApp::SetDefaultCfg(wxConfigBase *cfg)
{
    SetDefaultParsers(cfg);

    if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return;

    if (cfg->Read(_T("TM/database_path"), wxEmptyString).empty())
    {
        wxString dbpath;
#if defined(__WXMAC__)
        dbpath = wxStandardPaths::Get().GetUserDataDir() + _T("/tm");
#elif defined(__UNIX__)
        dbpath = wxGetHomeDir() + _T("/.poedit/tm");
#elif defined(__WXMSW__)
        dbpath = wxGetHomeDir() + _T("\\poedit_tm");
#endif
        cfg->Write(_T("TM/database_path"), dbpath);
    }

    if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty())
    {
        wxString paths;
#if defined(__UNIX__)
        paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale");
#elif defined(__WXMSW__)
        paths = _T("C:");
#endif
        cfg->Write(_T("TM/search_paths"), paths);
    }

    cfg->Write(_T("version"), GetAppVersion());
}

void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    wxApp::OnInitCmdLine(parser);
    parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING,
                    wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
}

bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    if (!wxApp::OnCmdLineParsed(parser))
        return false;

#ifndef __WXMAC__
    for (size_t i = 0; i < parser.GetParamCount(); i++)
        gs_filesToOpen.Add(parser.GetParam(i));
#endif

    return true;
}
<|endoftext|>


<commit_before>#include <highgui.h>

#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>

#include "human_robot_collaboration_msgs/ArmState.h"

using namespace std;
using namespace human_robot_collaboration_msgs;

#define DEFAULT_DURATION 10.0  // [s]

class BaxterDisplay
{
private:
    ros::NodeHandle    nh;

    std::string name;

    ros::Subscriber l_sub;  // Subscriber for the left  arm state
    ros::Subscriber r_sub;  // Subscriber for the right arm state
    ros::Subscriber s_sub;  // Subscriber for the speech output

    ArmState l_state;
    ArmState r_state;

    std::string speech;             // Text to display
    ros::Timer  speech_timer;       // Timer remove the speech pop-up after specific duration
    double      speech_duration;    // Duration of the speech pop-up

    image_transport::ImageTransport     it;
    image_transport::Publisher      im_pub;

    int h;
    int w;

    int w_delim;

    cv::Scalar red;
    cv::Scalar green;
    cv::Scalar blue;

    void armStateCbL(const ArmState& msg)
    {
        armStateCb(msg, "left");
    };

    void armStateCbR(const ArmState& msg)
    {
        armStateCb(msg, "right");
    };

    void armStateCb(const ArmState& msg, std::string _limb)
    {
        ROS_DEBUG("Received callback! Arm %s", _limb.c_str());

        if      (_limb == "left")
        {
            l_state = msg;
        }
        else if (_limb == "right")
        {
            r_state = msg;
        }

        displayArmStates();
    };

    void displaySpeech(cv::Mat& in)
    {
        if (speech !="")
        {
            int thickness = 3;
            int baseline  = 0;
            int fontFace  = cv::FONT_HERSHEY_SIMPLEX;
            int fontScale = 2;

            int border = 20;

            int max_width = 700; // max width of a text line

            cv::Size textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
            int numLines = int(textSize.width/max_width)+1;

            if (numLines>5)
            {
                fontScale = 1.6;
                thickness =   2;
                textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
                numLines = int(textSize.width/max_width);
            }
            ROS_DEBUG("Size of the text %i %i numLines %i", textSize.height, textSize.width, numLines);

            std::vector<std::string> line;
            std::vector<cv::Size>    size;

            int interline  =         20;  // Number of pixels between a line and the next one
            int rec_height = -interline;  // Height of the rectangle container (line_heigth + interline)
            int rec_width  =          0;  // Width  of the rectangle container (max of the width of each of the lines)
            int line_length = int(speech.size()/numLines);

            for (int i = 0; i < numLines; ++i)
            {
                // The last line gets also the remainder of the splitting
                if (i==numLines-1)
                {
                    line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
                }
                else
                {
                    line.push_back(speech.substr(i*line_length,line_length));
                }

                size.push_back(cv::getTextSize( line.back(), fontFace, fontScale, thickness, &baseline));
                if (size.back().width>rec_width) rec_width=size.back().width;
                rec_height += interline + size.back().height;

                ROS_DEBUG("   Line %i: size: %i %i\ttext: %s", i, size.back().height, size.back().width, line.back().c_str());
            }
            rec_height += 2*border;
            rec_width  += 2*border;

            cv::Point rectOrg((in.cols - rec_width)/2, (in.rows - rec_height)/2);
            cv::Point rectEnd((in.cols + rec_width)/2, (in.rows + rec_height)/2);
            rectangle(in, rectOrg, rectEnd, blue, -1);

            int textOrgy = rectOrg.y + border;
            for (int i = 0; i < numLines; ++i)
            {
                textOrgy += size[i].height;
                cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
                putText(in, line[i], textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, CV_AA);
                textOrgy += interline;
            }

            printf("\n");
        }
    };

    cv::Mat createSubImage(std::string _limb)
    {
        ArmState state = _limb=="LEFT"?l_state:r_state;

        cv::Mat img(h,(w-w_delim)/2,CV_8UC3,cv::Scalar::all(255));
        cv::Scalar col       = cv::Scalar::all(60);
        cv::Scalar col_state = green;

        if (state.state == "ERROR"  || state.state == "RECOVER" ||
            state.state == "KILLED" || state.state == "DONE" ||
            state.state == "START" )
        {
            col = cv::Scalar::all(240);
            col_state = col;
            img.setTo(red);

            if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
            {
                img.setTo(green);
            }
        }

        int thickness = 3;
        int baseline  = 0;
        int fontFace  = cv::FONT_HERSHEY_SIMPLEX;
        int fontScale = 2;

        // Place a centered title on top
        string title = _limb + " ARM";
        cv::Size textSize = cv::getTextSize( title, fontFace, fontScale, thickness, &baseline);
        cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
        putText(img, title, textOrg, fontFace, fontScale, col, thickness, CV_AA);

        if (state.state !="")
        {
            putText(img, "state:", cv::Point(20,300), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.state, cv::Point(150,300), fontFace, fontScale, col_state, thickness, CV_AA);
        }
        if (state.action !="")
        {
            putText(img, "action:", cv::Point(20,400), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.action, cv::Point(150,400), fontFace, fontScale/1.25, col, thickness, CV_AA);
        }
        if (state.object !="")
        {
            putText(img, "object:", cv::Point(20,500), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.object, cv::Point(150,500), fontFace, fontScale/1.25, col, thickness, CV_AA);
        }

        return img;
    };

public:

    explicit BaxterDisplay(string _name) : name(_name), speech(""), it(nh)
    {
        im_pub = it.advertise("/robot/xdisplay", 1);

        l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
        r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);

        s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);

        h = 600;
        w = 1024;

        w_delim = 8;

        l_state.state  = "START";
        l_state.action =     "";
        l_state.object =     "";

        r_state.state  = "START";
        r_state.action =     "";
        r_state.object =     "";

        red   = cv::Scalar(  44,  48, 201);  // BGR color code
        green = cv::Scalar(  60, 160,  60);
        blue  = cv::Scalar( 200, 162,  77);

        nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);

        displayArmStates();
    };

    void setSpeech(const std::string &s)
    {
        speech = s;
    }

    void speechCb(const std_msgs::String& msg)
    {
        setSpeech(msg.data);

        speech_timer = nh.createTimer(ros::Duration(speech_duration),
                                      &BaxterDisplay::deleteSpeechCb, this, true);

        displayArmStates();
    };

    void deleteSpeechCb(const ros::TimerEvent&)
    {
        setSpeech("");
        displayArmStates();
    };

    bool displayArmStates()
    {
        cv::Mat l = createSubImage("LEFT");
        cv::Mat r = createSubImage("RIGHT");
        cv::Mat d(h,w_delim,CV_8UC3,cv::Scalar::all(80));

        cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));

        // Move right boundary to the left.
        res.adjustROI(0,0,0,-(w+w_delim)/2);
        r.copyTo(res);

        // Move the left boundary to the right, right boundary to the right.
        res.adjustROI(0, 0, -(w-w_delim)/2, w_delim);
        d.copyTo(res);

        // Move the left boundary to the right, right boundary to the right.
        res.adjustROI(0, 0, -w_delim, (w-w_delim)/2);
        l.copyTo(res);

        res.adjustROI(0, 0, (w+w_delim)/2, 0);

        displaySpeech(res);

        cv_bridge::CvImage msg;
        msg.encoding = sensor_msgs::image_encodings::BGR8;
        msg.image    = res;

        im_pub.publish(msg.toImageMsg());

        // cv::imshow("res", res);
        // cv::waitKey(20);

        return true;
    };

};

int main(int argc, char ** argv)
{
    ros::init(argc, argv, "baxter_display");

    BaxterDisplay bd("baxter_display");

    ros::Duration(0.2).sleep();
    bd.displayArmStates();

    ros::spin();
    return 0;
}

<commit_msg>Removes object name from display.<commit_after>#include <highgui.h>

#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>

#include "human_robot_collaboration_msgs/ArmState.h"

using namespace std;
using namespace human_robot_collaboration_msgs;

#define DEFAULT_DURATION 10.0  // [s]

class BaxterDisplay
{
private:
    ros::NodeHandle    nh;

    std::string name;

    ros::Subscriber l_sub;  // Subscriber for the left  arm state
    ros::Subscriber r_sub;  // Subscriber for the right arm state
    ros::Subscriber s_sub;  // Subscriber for the speech output

    ArmState l_state;
    ArmState r_state;

    std::string speech;             // Text to display
    ros::Timer  speech_timer;       // Timer remove the speech pop-up after specific duration
    double      speech_duration;    // Duration of the speech pop-up

    image_transport::ImageTransport     it;
    image_transport::Publisher      im_pub;

    int h;
    int w;

    int w_delim;

    cv::Scalar red;
    cv::Scalar green;
    cv::Scalar blue;

    void armStateCbL(const ArmState& msg)
    {
        armStateCb(msg, "left");
    };

    void armStateCbR(const ArmState& msg)
    {
        armStateCb(msg, "right");
    };

    void armStateCb(const ArmState& msg, std::string _limb)
    {
        ROS_DEBUG("Received callback! Arm %s", _limb.c_str());

        if      (_limb == "left")
        {
            l_state = msg;
        }
        else if (_limb == "right")
        {
            r_state = msg;
        }

        displayArmStates();
    };

    void displaySpeech(cv::Mat& in)
    {
        if (speech !="")
        {
            int thickness = 3;
            int baseline  = 0;
            int fontFace  = cv::FONT_HERSHEY_SIMPLEX;
            int fontScale = 2;

            int border = 20;

            int max_width = 700; // max width of a text line

            cv::Size textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
            int numLines = int(textSize.width/max_width)+1;

            if (numLines>5)
            {
                fontScale = 1.6;
                thickness =   2;
                textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
                numLines = int(textSize.width/max_width);
            }
            ROS_DEBUG("Size of the text %i %i numLines %i", textSize.height, textSize.width, numLines);

            std::vector<std::string> line;
            std::vector<cv::Size>    size;

            int interline  =         20;  // Number of pixels between a line and the next one
            int rec_height = -interline;  // Height of the rectangle container (line_heigth + interline)
            int rec_width  =          0;  // Width  of the rectangle container (max of the width of each of the lines)
            int line_length = int(speech.size()/numLines);

            for (int i = 0; i < numLines; ++i)
            {
                // The last line gets also the remainder of the splitting
                if (i==numLines-1)
                {
                    line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
                }
                else
                {
                    line.push_back(speech.substr(i*line_length,line_length));
                }

                size.push_back(cv::getTextSize( line.back(), fontFace, fontScale, thickness, &baseline));
                if (size.back().width>rec_width) rec_width=size.back().width;
                rec_height += interline + size.back().height;

                ROS_DEBUG("   Line %i: size: %i %i\ttext: %s", i, size.back().height, size.back().width, line.back().c_str());
            }
            rec_height += 2*border;
            rec_width  += 2*border;

            cv::Point rectOrg((in.cols - rec_width)/2, (in.rows - rec_height)/2);
            cv::Point rectEnd((in.cols + rec_width)/2, (in.rows + rec_height)/2);
            rectangle(in, rectOrg, rectEnd, blue, -1);

            int textOrgy = rectOrg.y + border;
            for (int i = 0; i < numLines; ++i)
            {
                textOrgy += size[i].height;
                cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
                putText(in, line[i], textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, CV_AA);
                textOrgy += interline;
            }

            printf("\n");
        }
    };

    cv::Mat createSubImage(std::string _limb)
    {
        ArmState state = _limb=="LEFT"?l_state:r_state;

        cv::Mat img(h,(w-w_delim)/2,CV_8UC3,cv::Scalar::all(255));
        cv::Scalar col       = cv::Scalar::all(60);
        cv::Scalar col_state = green;

        if (state.state == "ERROR"  || state.state == "RECOVER" ||
            state.state == "KILLED" || state.state == "DONE" ||
            state.state == "START" )
        {
            col = cv::Scalar::all(240);
            col_state = col;
            img.setTo(red);

            if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
            {
                img.setTo(green);
            }
        }

        int thickness = 3;
        int baseline  = 0;
        int fontFace  = cv::FONT_HERSHEY_SIMPLEX;
        int fontScale = 2;

        // Place a centered title on top
        string title = _limb + " ARM";
        cv::Size textSize = cv::getTextSize( title, fontFace, fontScale, thickness, &baseline);
        cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
        putText(img, title, textOrg, fontFace, fontScale, col, thickness, CV_AA);

        if (state.state !="")
        {
            putText(img, "state:", cv::Point(20,300), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.state, cv::Point(150,300), fontFace, fontScale, col_state, thickness, CV_AA);
        }
        if (state.action !="")
        {
            putText(img, "action:", cv::Point(20,400), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.action, cv::Point(150,400), fontFace, fontScale/1.25, col, thickness, CV_AA);
        }
        if (false)
        {
            putText(img, "object:", cv::Point(20,500), fontFace, fontScale/2, col, 2, 8);
            putText(img, state.object, cv::Point(150,500), fontFace, fontScale/1.25, col, thickness, CV_AA);
        }

        return img;
    };

public:

    explicit BaxterDisplay(string _name) : name(_name), speech(""), it(nh)
    {
        im_pub = it.advertise("/robot/xdisplay", 1);

        l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
        r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);

        s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);

        h = 600;
        w = 1024;

        w_delim = 8;

        l_state.state  = "START";
        l_state.action =     "";
        l_state.object =     "";

        r_state.state  = "START";
        r_state.action =     "";
        r_state.object =     "";

        red   = cv::Scalar(  44,  48, 201);  // BGR color code
        green = cv::Scalar(  60, 160,  60);
        blue  = cv::Scalar( 200, 162,  77);

        nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);

        displayArmStates();
    };

    void setSpeech(const std::string &s)
    {
        speech = s;
    }

    void speechCb(const std_msgs::String& msg)
    {
        setSpeech(msg.data);

        speech_timer = nh.createTimer(ros::Duration(speech_duration),
                                      &BaxterDisplay::deleteSpeechCb, this, true);

        displayArmStates();
    };

    void deleteSpeechCb(const ros::TimerEvent&)
    {
        setSpeech("");
        displayArmStates();
    };

    bool displayArmStates()
    {
        cv::Mat l = createSubImage("LEFT");
        cv::Mat r = createSubImage("RIGHT");
        cv::Mat d(h,w_delim,CV_8UC3,cv::Scalar::all(80));

        cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));

        // Move right boundary to the left.
        res.adjustROI(0,0,0,-(w+w_delim)/2);
        r.copyTo(res);

        // Move the left boundary to the right, right boundary to the right.
        res.adjustROI(0, 0, -(w-w_delim)/2, w_delim);
        d.copyTo(res);

        // Move the left boundary to the right, right boundary to the right.
        res.adjustROI(0, 0, -w_delim, (w-w_delim)/2);
        l.copyTo(res);

        res.adjustROI(0, 0, (w+w_delim)/2, 0);

        displaySpeech(res);

        cv_bridge::CvImage msg;
        msg.encoding = sensor_msgs::image_encodings::BGR8;
        msg.image    = res;

        im_pub.publish(msg.toImageMsg());

        // cv::imshow("res", res);
        // cv::waitKey(20);

        return true;
    };

};

int main(int argc, char ** argv)
{
    ros::init(argc, argv, "baxter_display");

    BaxterDisplay bd("baxter_display");

    ros::Duration(0.2).sleep();
    bd.displayArmStates();

    ros::spin();
    return 0;
}

<|endoftext|>


<commit_before>/*
    This file is part of KDE WSCL Parser

    Copyright (c) 2005 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
 */

#include <qdom.h>

#include "parser.h"

using namespace WSCL;

Parser::Parser()
{
}

Parser::~Parser()
{
}

void Parser::parse( const QString &xml )
{
  QDomDocument doc( "kwscl" );
  QString errorMsg;
  int errorLine, errorColumn;
  bool ok = doc.setContent( xml, true, &errorMsg, &errorLine, &errorColumn );
  if ( !ok ) {
    qDebug( "Error parsing wscl (%d:%d) %s", errorLine, errorColumn, errorMsg.toLatin1() );
    return;
  }

  QDomNodeList nodes = doc.elementsByTagName( "Conversation" );
  if ( nodes.count() <= 0 ) {
    qDebug( "No conversation tag found in wscl data" );
    return;
  }

  QDomElement conversationElement = nodes.item( 0 ).toElement();

  mConversation.setName( conversationElement.attribute( "name" ) );
  mConversation.setVersion( conversationElement.attribute( "version" ) );
  mConversation.setDescription( conversationElement.attribute( "description" ) );
  mConversation.setNameSpace( conversationElement.attribute( "targetNamespace" ) );
  mConversation.setSchema( conversationElement.attribute( "hrefSchema" ) );
  mConversation.setInitialInteraction( conversationElement.attribute( "initialInteraction" ) );
  mConversation.setFinalInteraction( conversationElement.attribute( "finalInteraction" ) );

  QDomNode node = conversationElement.firstChild();
  while ( !node.isNull() ) {
    QDomElement element = node.toElement();
    if ( !element.isNull() ) {
      if ( element.tagName() == "ConversationInteractions" ) {
        Interaction::List interactions;

        QDomNode interactionNode = element.firstChild();
        while ( !interactionNode.isNull() ) {
          QDomElement interactionElement = interactionNode.toElement();
          if ( !interactionElement.isNull() ) {
            if ( interactionElement.tagName() != "Interaction" ) {
              qDebug( "Expected tag name 'Interaction', got '%s'", interactionElement.tagName().toLatin1() );
              continue;
            }

            Interaction interaction;
            interaction.setId( interactionElement.attribute( "id" ) );
            const QString type = interactionElement.attribute( "interactionType" );
            if ( type == "ReceiveSend" )
              interaction.setType( Interaction::ReceiveSend );
            else if ( type == "SendReceive" )
              interaction.setType( Interaction::SendReceive );
            else if ( type == "Receive" )
              interaction.setType( Interaction::Receive );
            else if ( type == "Send" )
              interaction.setType( Interaction::Send );
            else if ( type == "Empty" )
              interaction.setType( Interaction::Empty );
            else
              qDebug( "Unknown interaction type '%s'", type.toLatin1() );

            XMLDocument::List inputDocuments;
            XMLDocument::List outputDocuments;
            XMLDocument inputDocument;
            XMLDocument outputDocument;

            QDomNode contentNode = interactionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "InboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  inputDocuments.append( document );
                  inputDocument = document;
                } else if ( tagName == "OutboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  outputDocuments.append( document );
                  outputDocument = document;
                }
              }

              contentNode = contentNode.nextSibling();
            }

            switch ( interaction.type() ) {
              case Interaction::ReceiveSend:
                {
                  ReceiveSendDocument document;
                  document.setInputDocument( inputDocument );
                  document.setOutputDocuments( outputDocuments );
                  interaction.setReceiveSendDocument( document );
                }
                break;
              case Interaction::SendReceive:
                {
                  SendReceiveDocument document;
                  document.setInputDocuments( inputDocuments );
                  document.setOutputDocument( outputDocument );
                  interaction.setSendReceiveDocument( document );
                }
                break;
              case Interaction::Receive:
                {
                  ReceiveDocument document;
                  document.setInputDocument( inputDocument );
                  interaction.setReceiveDocument( document );
                }
                break;
              case Interaction::Send:
                {
                  SendDocument document;
                  document.setOutputDocument( outputDocument );
                  interaction.setSendDocument( document );
                }
                break;
              case Interaction::Empty:
              default:
                break;
            }

            interactions.append( interaction );
          }

          interactionNode = interactionNode.nextSibling();
        }

        mConversation.setInteractions( interactions );

      } else if ( element.tagName() == "ConversationTransitions" ) {
        Transition::List transitions;

        QDomNode transitionNode = element.firstChild();
        while ( !transitionNode.isNull() ) {
          QDomElement transitionElement = transitionNode.toElement();
          if ( !transitionElement.isNull() ) {
            if ( transitionElement.tagName() != "Transition" ) {
              qDebug( "Expected tag name 'Transition', got '%s'", transitionElement.tagName().toLatin1() );
              continue;
            }

            Transition transition;

            QDomNode contentNode = transitionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "SourceInteraction" )
                  transition.setSourceInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "DestinationInteraction" )
                  transition.setDestinationInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "SourceInteractionCondition" )
                  transition.setSourceInteractionCondition( contentElement.attribute( "href" ) );
                else
                  qDebug( "Unknown transition element %s", tagName.toLatin1() );
              }

              contentNode = contentNode.nextSibling();
            }

            transitions.append( transition );
          }

          transitionNode = transitionNode.nextSibling();
        }

        mConversation.setTransitions( transitions );
      }
    }

    node = node.nextSibling();
  }
}

void Parser::reset()
{
  mConversation = Conversation();
}

Conversation Parser::conversation() const
{
  return mConversation;
}
<commit_msg>qDebug( toLatin1() ) -> qDebug( qPrintable() );<commit_after>/*
    This file is part of KDE WSCL Parser

    Copyright (c) 2005 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
 */

#include <qdom.h>

#include "parser.h"

using namespace WSCL;

Parser::Parser()
{
}

Parser::~Parser()
{
}

void Parser::parse( const QString &xml )
{
  QDomDocument doc( "kwscl" );
  QString errorMsg;
  int errorLine, errorColumn;
  bool ok = doc.setContent( xml, true, &errorMsg, &errorLine, &errorColumn );
  if ( !ok ) {
    qDebug( "Error parsing wscl (%d:%d) %s", errorLine, errorColumn, qPrintable( errorMsg ) );
    return;
  }

  QDomNodeList nodes = doc.elementsByTagName( "Conversation" );
  if ( nodes.count() <= 0 ) {
    qDebug( "No conversation tag found in wscl data" );
    return;
  }

  QDomElement conversationElement = nodes.item( 0 ).toElement();

  mConversation.setName( conversationElement.attribute( "name" ) );
  mConversation.setVersion( conversationElement.attribute( "version" ) );
  mConversation.setDescription( conversationElement.attribute( "description" ) );
  mConversation.setNameSpace( conversationElement.attribute( "targetNamespace" ) );
  mConversation.setSchema( conversationElement.attribute( "hrefSchema" ) );
  mConversation.setInitialInteraction( conversationElement.attribute( "initialInteraction" ) );
  mConversation.setFinalInteraction( conversationElement.attribute( "finalInteraction" ) );

  QDomNode node = conversationElement.firstChild();
  while ( !node.isNull() ) {
    QDomElement element = node.toElement();
    if ( !element.isNull() ) {
      if ( element.tagName() == "ConversationInteractions" ) {
        Interaction::List interactions;

        QDomNode interactionNode = element.firstChild();
        while ( !interactionNode.isNull() ) {
          QDomElement interactionElement = interactionNode.toElement();
          if ( !interactionElement.isNull() ) {
            if ( interactionElement.tagName() != "Interaction" ) {
              qDebug( "Expected tag name 'Interaction', got '%s'", qPrintable( interactionElement.tagName() ) );
              continue;
            }

            Interaction interaction;
            interaction.setId( interactionElement.attribute( "id" ) );
            const QString type = interactionElement.attribute( "interactionType" );
            if ( type == "ReceiveSend" )
              interaction.setType( Interaction::ReceiveSend );
            else if ( type == "SendReceive" )
              interaction.setType( Interaction::SendReceive );
            else if ( type == "Receive" )
              interaction.setType( Interaction::Receive );
            else if ( type == "Send" )
              interaction.setType( Interaction::Send );
            else if ( type == "Empty" )
              interaction.setType( Interaction::Empty );
            else
              qDebug( "Unknown interaction type '%s'", qPrintable( type ) );

            XMLDocument::List inputDocuments;
            XMLDocument::List outputDocuments;
            XMLDocument inputDocument;
            XMLDocument outputDocument;

            QDomNode contentNode = interactionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "InboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  inputDocuments.append( document );
                  inputDocument = document;
                } else if ( tagName == "OutboundXMLDocument" ) {
                  XMLDocument document;
                  document.setId( contentElement.attribute( "id" ) );
                  document.setSchema( contentElement.attribute( "hrefSchema" ) );

                  outputDocuments.append( document );
                  outputDocument = document;
                }
              }

              contentNode = contentNode.nextSibling();
            }

            switch ( interaction.type() ) {
              case Interaction::ReceiveSend:
                {
                  ReceiveSendDocument document;
                  document.setInputDocument( inputDocument );
                  document.setOutputDocuments( outputDocuments );
                  interaction.setReceiveSendDocument( document );
                }
                break;
              case Interaction::SendReceive:
                {
                  SendReceiveDocument document;
                  document.setInputDocuments( inputDocuments );
                  document.setOutputDocument( outputDocument );
                  interaction.setSendReceiveDocument( document );
                }
                break;
              case Interaction::Receive:
                {
                  ReceiveDocument document;
                  document.setInputDocument( inputDocument );
                  interaction.setReceiveDocument( document );
                }
                break;
              case Interaction::Send:
                {
                  SendDocument document;
                  document.setOutputDocument( outputDocument );
                  interaction.setSendDocument( document );
                }
                break;
              case Interaction::Empty:
              default:
                break;
            }

            interactions.append( interaction );
          }

          interactionNode = interactionNode.nextSibling();
        }

        mConversation.setInteractions( interactions );

      } else if ( element.tagName() == "ConversationTransitions" ) {
        Transition::List transitions;

        QDomNode transitionNode = element.firstChild();
        while ( !transitionNode.isNull() ) {
          QDomElement transitionElement = transitionNode.toElement();
          if ( !transitionElement.isNull() ) {
            if ( transitionElement.tagName() != "Transition" ) {
              qDebug( "Expected tag name 'Transition', got '%s'", qPrintable( transitionElement.tagName() ) );
              continue;
            }

            Transition transition;

            QDomNode contentNode = transitionElement.firstChild();
            while ( !contentNode.isNull() ) {
              QDomElement contentElement = contentNode.toElement();
              if ( !contentElement.isNull() ) {
                const QString tagName = contentElement.tagName();
                if ( tagName == "SourceInteraction" )
                  transition.setSourceInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "DestinationInteraction" )
                  transition.setDestinationInteraction( contentElement.attribute( "href" ) );
                else if ( tagName == "SourceInteractionCondition" )
                  transition.setSourceInteractionCondition( contentElement.attribute( "href" ) );
                else
                  qDebug( "Unknown transition element %s", qPrintable( tagName ) );
              }

              contentNode = contentNode.nextSibling();
            }

            transitions.append( transition );
          }

          transitionNode = transitionNode.nextSibling();
        }

        mConversation.setTransitions( transitions );
      }
    }

    node = node.nextSibling();
  }
}

void Parser::reset()
{
  mConversation = Conversation();
}

Conversation Parser::conversation() const
{
  return mConversation;
}
<|endoftext|>


<commit_before>#include <itkImageRegionConstIterator.h>

#include "rtkTestConfiguration.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkJosephBackProjectionImageFilter.h"

#ifdef USE_CUDA
  #include "rtkCudaBackProjectionImageFilter.h"
  #include "rtkCudaSARTConeBeamReconstructionFilter.h"
  #include "itkCudaImage.h"
#else
  #include "rtkSARTConeBeamReconstructionFilter.h"
#endif

template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();
    TestError += vcl_abs(RefVal - TestVal);
    EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (2.0-ErrorPerPixel)/2.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 0.032)
  {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 0.032" << std::endl;
    exit( EXIT_FAILURE);
  }
  if (PSNR < 28.6)
  {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 28.6" << std::endl;
    exit( EXIT_FAILURE);
  }
}
#endif

/**
 * \file rtksarttest.cxx
 *
 * \brief Functional test for SART reconstruction
 *
 * This test generates the projections of an ellipsoid and reconstructs the CT
 * image using the SART algorithm with different backprojectors (Voxel-Based,
 * Joseph and CUDA Voxel-Based). The generated results are compared to the
 * expected results (analytical calculation).
 *
 * \author Simon Rit and Marc Vila
 */

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 180;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -255.;
  origin[1] = -255.;
  origin[2] = -255.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 504.;
  spacing[1] = 504.;
  spacing[2] = 504.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages);

  // Create ellipsoid PROJECTIONS
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  REIType::Pointer rei;

  rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(90.);
  center.Fill(0.);
  rei->SetAngle(0.);
  rei->SetDensity(1.);

  rei->SetInput( projectionsSource->GetOutput() );
  rei->SetGeometry( geometry );

  //Update
  rei->Update();

  // Create REFERENCE object (3D ellipsoid).
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer dsl = DEType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // SART reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaSARTConeBeamReconstructionFilter                SARTType;
#else
  typedef rtk::SARTConeBeamReconstructionFilter< OutputImageType > SARTType;
#endif
  SARTType::Pointer sart = SARTType::New();
  sart->SetInput( tomographySource->GetOutput() );
  sart->SetInput(1, rei->GetOutput());
  sart->SetGeometry( geometry );
  sart->SetNumberOfIterations( 1 );
  sart->SetLambda( 0.5 );

  std::cout << "\n\n****** Case 1: Voxel-Based Backprojector ******" << std::endl;

  rtk::BackProjectionImageFilter<OutputImageType, OutputImageType>::Pointer bp;
  bp = rtk::BackProjectionImageFilter<OutputImageType, OutputImageType>::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 2: Joseph Backprojector ******" << std::endl;

  bp = rtk::JosephBackProjectionImageFilter<OutputImageType, OutputImageType>::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

#ifdef USE_CUDA
  std::cout << "\n\n****** Case 3: CUDA Voxel-Based Backprojector ******" << std::endl;

  bp = rtk::CudaBackProjectionImageFilter::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;
#endif

  return EXIT_SUCCESS;
}
<commit_msg>BUG: added missing initialization of projection parameters<commit_after>#include <itkImageRegionConstIterator.h>

#include "rtkTestConfiguration.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkJosephBackProjectionImageFilter.h"

#ifdef USE_CUDA
  #include "rtkCudaBackProjectionImageFilter.h"
  #include "rtkCudaSARTConeBeamReconstructionFilter.h"
  #include "itkCudaImage.h"
#else
  #include "rtkSARTConeBeamReconstructionFilter.h"
#endif

template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();
    TestError += vcl_abs(RefVal - TestVal);
    EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (2.0-ErrorPerPixel)/2.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 0.032)
  {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 0.032" << std::endl;
    exit( EXIT_FAILURE);
  }
  if (PSNR < 28.6)
  {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 28.6" << std::endl;
    exit( EXIT_FAILURE);
  }
}
#endif

/**
 * \file rtksarttest.cxx
 *
 * \brief Functional test for SART reconstruction
 *
 * This test generates the projections of an ellipsoid and reconstructs the CT
 * image using the SART algorithm with different backprojectors (Voxel-Based,
 * Joseph and CUDA Voxel-Based). The generated results are compared to the
 * expected results (analytical calculation).
 *
 * \author Simon Rit and Marc Vila
 */

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 180;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -255.;
  origin[1] = -255.;
  origin[2] = -255.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 504.;
  spacing[1] = 504.;
  spacing[2] = 504.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages);

  // Create ellipsoid PROJECTIONS
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  REIType::Pointer rei;

  rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(90.);
  center.Fill(0.);
  rei->SetAngle(0.);
  rei->SetDensity(1.);
  rei->SetCenter(center);
  rei->SetAxis(semiprincipalaxis);

  rei->SetInput( projectionsSource->GetOutput() );
  rei->SetGeometry( geometry );

  //Update
  TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() );

  // Create REFERENCE object (3D ellipsoid).
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer dsl = DEType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // SART reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaSARTConeBeamReconstructionFilter                SARTType;
#else
  typedef rtk::SARTConeBeamReconstructionFilter< OutputImageType > SARTType;
#endif
  SARTType::Pointer sart = SARTType::New();
  sart->SetInput( tomographySource->GetOutput() );
  sart->SetInput(1, rei->GetOutput());
  sart->SetGeometry( geometry );
  sart->SetNumberOfIterations( 1 );
  sart->SetLambda( 0.5 );

  std::cout << "\n\n****** Case 1: Voxel-Based Backprojector ******" << std::endl;

  rtk::BackProjectionImageFilter<OutputImageType, OutputImageType>::Pointer bp;
  bp = rtk::BackProjectionImageFilter<OutputImageType, OutputImageType>::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 2: Joseph Backprojector ******" << std::endl;

  bp = rtk::JosephBackProjectionImageFilter<OutputImageType, OutputImageType>::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

#ifdef USE_CUDA
  std::cout << "\n\n****** Case 3: CUDA Voxel-Based Backprojector ******" << std::endl;

  bp = rtk::CudaBackProjectionImageFilter::New();
  sart->SetBackProjectionFilter( bp );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( sart->Update() );

  CheckImageQuality<OutputImageType>(sart->GetOutput(), dsl->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;
#endif

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2002 - 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   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                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <tfile.h>
#include <tstring.h>

#include "fileref.h"
#include "asffile.h"
#include "mpegfile.h"
#include "vorbisfile.h"
#include "flacfile.h"
#include "oggflacfile.h"
#include "mpcfile.h"
#include "mp4file.h"
#include "wavpackfile.h"
#include "speexfile.h"
#include "trueaudiofile.h"
#include "aifffile.h"
#include "wavfile.h"

using namespace TagLib;

class FileRef::FileRefPrivate : public RefCounter
{
public:
  FileRefPrivate(File *f) : RefCounter(), file(f) {}
  ~FileRefPrivate() {
    delete file;
  }

  File *file;
  static List<const FileTypeResolver *> fileTypeResolvers;
};

List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers;

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

FileRef::FileRef()
{
  d = new FileRefPrivate(0);
}

FileRef::FileRef(FileName fileName, bool readAudioProperties,
                 AudioProperties::ReadStyle audioPropertiesStyle)
{
  d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle));
}

FileRef::FileRef(File *file)
{
  d = new FileRefPrivate(file);
}

FileRef::FileRef(const FileRef &ref) : d(ref.d)
{
  d->ref();
}

FileRef::~FileRef()
{
  if(d->deref())
    delete d;
}

Tag *FileRef::tag() const
{
  return d->file->tag();
}

AudioProperties *FileRef::audioProperties() const
{
  return d->file->audioProperties();
}

File *FileRef::file() const
{
  return d->file;
}

bool FileRef::save()
{
  return d->file->save();
}

const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static
{
  FileRefPrivate::fileTypeResolvers.prepend(resolver);
  return resolver;
}

StringList FileRef::defaultFileExtensions()
{
  StringList l;

  l.append("ogg");
  l.append("flac");
  l.append("oga");
  l.append("mp3");
  l.append("mpc");
  l.append("wv");
  l.append("spx");
  l.append("tta");
#ifdef WITH_MP4
  l.append("m4a");
  l.append("m4b");
  l.append("m4p");
  l.append("3g2");
#endif
#ifdef WITH_ASF
  l.append("wma");
#endif
  l.append("aif");
  l.append("aiff");
  l.append("wav");

  return l;
}

bool FileRef::isNull() const
{
  return !d->file || !d->file->isValid();
}

FileRef &FileRef::operator=(const FileRef &ref)
{
  if(&ref == this)
    return *this;

  if(d->deref())
    delete d;

  d = ref.d;
  d->ref();

  return *this;
}

bool FileRef::operator==(const FileRef &ref) const
{
  return ref.d->file == d->file;
}

bool FileRef::operator!=(const FileRef &ref) const
{
  return ref.d->file != d->file;
}

File *FileRef::create(FileName fileName, bool readAudioProperties,
                      AudioProperties::ReadStyle audioPropertiesStyle) // static
{

  List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin();

  for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) {
    File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle);
    if(file)
      return file;
  }

  // Ok, this is really dumb for now, but it works for testing.

  String s;

#ifdef _WIN32
  s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName);
#else
  s = fileName;
#endif

  // If this list is updated, the method defaultFileExtensions() should also be
  // updated.  However at some point that list should be created at the same time
  // that a default file type resolver is created.

  if(s.size() > 4) {
    if(s.substr(s.size() - 4, 4).upper() == ".OGG")
      return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MP3")
      return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".OGA")
      return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 5, 5).upper() == ".FLAC")
      return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MPC")
      return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 3, 3).upper() == ".WV")
      return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".SPX")
      return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".TTA")
      return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle);
#ifdef WITH_MP4
    if(s.substr(s.size() - 4, 4).upper() == ".M4A" ||
       s.substr(s.size() - 4, 4).upper() == ".M4B" ||
       s.substr(s.size() - 4, 4).upper() == ".M4P" ||
       s.substr(s.size() - 4, 4).upper() == ".3G2")
      return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
#ifdef WITH_ASF
    if(s.substr(s.size() - 4, 4).upper() == ".WMA")
      return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
    if(s.substr(s.size() - 4, 4).upper() == ".AIF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".WAV")
      return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle);
  }
  if(s.size() > 5) {
    if(s.substr(s.size() - 5, 5).upper() == ".AIFF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
  }

  return 0;
}
<commit_msg>Several of us have seen .asf WMA files in the wild.<commit_after>/***************************************************************************
    copyright            : (C) 2002 - 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   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                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <tfile.h>
#include <tstring.h>

#include "fileref.h"
#include "asffile.h"
#include "mpegfile.h"
#include "vorbisfile.h"
#include "flacfile.h"
#include "oggflacfile.h"
#include "mpcfile.h"
#include "mp4file.h"
#include "wavpackfile.h"
#include "speexfile.h"
#include "trueaudiofile.h"
#include "aifffile.h"
#include "wavfile.h"

using namespace TagLib;

class FileRef::FileRefPrivate : public RefCounter
{
public:
  FileRefPrivate(File *f) : RefCounter(), file(f) {}
  ~FileRefPrivate() {
    delete file;
  }

  File *file;
  static List<const FileTypeResolver *> fileTypeResolvers;
};

List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers;

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

FileRef::FileRef()
{
  d = new FileRefPrivate(0);
}

FileRef::FileRef(FileName fileName, bool readAudioProperties,
                 AudioProperties::ReadStyle audioPropertiesStyle)
{
  d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle));
}

FileRef::FileRef(File *file)
{
  d = new FileRefPrivate(file);
}

FileRef::FileRef(const FileRef &ref) : d(ref.d)
{
  d->ref();
}

FileRef::~FileRef()
{
  if(d->deref())
    delete d;
}

Tag *FileRef::tag() const
{
  return d->file->tag();
}

AudioProperties *FileRef::audioProperties() const
{
  return d->file->audioProperties();
}

File *FileRef::file() const
{
  return d->file;
}

bool FileRef::save()
{
  return d->file->save();
}

const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static
{
  FileRefPrivate::fileTypeResolvers.prepend(resolver);
  return resolver;
}

StringList FileRef::defaultFileExtensions()
{
  StringList l;

  l.append("ogg");
  l.append("flac");
  l.append("oga");
  l.append("mp3");
  l.append("mpc");
  l.append("wv");
  l.append("spx");
  l.append("tta");
#ifdef WITH_MP4
  l.append("m4a");
  l.append("m4b");
  l.append("m4p");
  l.append("3g2");
#endif
#ifdef WITH_ASF
  l.append("wma");
  l.append("asf");
#endif
  l.append("aif");
  l.append("aiff");
  l.append("wav");

  return l;
}

bool FileRef::isNull() const
{
  return !d->file || !d->file->isValid();
}

FileRef &FileRef::operator=(const FileRef &ref)
{
  if(&ref == this)
    return *this;

  if(d->deref())
    delete d;

  d = ref.d;
  d->ref();

  return *this;
}

bool FileRef::operator==(const FileRef &ref) const
{
  return ref.d->file == d->file;
}

bool FileRef::operator!=(const FileRef &ref) const
{
  return ref.d->file != d->file;
}

File *FileRef::create(FileName fileName, bool readAudioProperties,
                      AudioProperties::ReadStyle audioPropertiesStyle) // static
{

  List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin();

  for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) {
    File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle);
    if(file)
      return file;
  }

  // Ok, this is really dumb for now, but it works for testing.

  String s;

#ifdef _WIN32
  s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName);
#else
  s = fileName;
#endif

  // If this list is updated, the method defaultFileExtensions() should also be
  // updated.  However at some point that list should be created at the same time
  // that a default file type resolver is created.

  if(s.size() > 4) {
    if(s.substr(s.size() - 4, 4).upper() == ".OGG")
      return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MP3")
      return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".OGA")
      return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 5, 5).upper() == ".FLAC")
      return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MPC")
      return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 3, 3).upper() == ".WV")
      return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".SPX")
      return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".TTA")
      return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle);
#ifdef WITH_MP4
    if(s.substr(s.size() - 4, 4).upper() == ".M4A" ||
       s.substr(s.size() - 4, 4).upper() == ".M4B" ||
       s.substr(s.size() - 4, 4).upper() == ".M4P" ||
       s.substr(s.size() - 4, 4).upper() == ".3G2")
      return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
#ifdef WITH_ASF
    if(s.substr(s.size() - 4, 4).upper() == ".WMA")
      return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
    if(s.substr(s.size() - 4, 4).upper() == ".AIF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".WAV")
      return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle);
  }
  if(s.size() > 5) {
    if(s.substr(s.size() - 5, 5).upper() == ".AIFF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
  }

  return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *****************************************************************************/

#include "gamewindowmanager.h"

#include "input/inputmanager.h"

#include "engine/scene.h"

#include <QtCore/QTimer>
#include <QtCore/QDebug>
#include <QtGui/QApplication>

using namespace GluonQMLPlayer;

class GameWindowManager::GameWindowManagerPrivate
{
    public:
        GameWindowManagerPrivate() {}

        GluonGraphics::RenderWidget* widget;

        QString title;
        QString fileName;

        int msecElapsed;
        int frameCount;
};

GameWindowManager::GameWindowManager(const QString& /* filename */)
    : QObject()
    , d( new GameWindowManagerPrivate )
    , m_project( new GluonEngine::GameProject )
{
}

GameWindowManager::GameWindowManager(GluonGraphics::RenderWidget* renderWidget, QGraphicsView* view,
                                    GluonPlayer::GameItemsModel* gameItemsModel, const QString& /* filename */ )
    : QObject()
    , d( new GameWindowManagerPrivate )
    , m_project( new GluonEngine::GameProject )
    , m_view(view)
    , m_gameItemsModel(gameItemsModel)
{
    d->widget = renderWidget;
}

GameWindowManager::~GameWindowManager ( )
{
}

bool GameWindowManager::isViewportGLWidget( )
{
    return qobject_cast<QGLWidget*>(m_view);
}

void GameWindowManager::startGame( )
{
    GluonCore::GluonObjectFactory::instance()->loadPlugins();

    m_project->loadFromFile( m_gameFileName );

    GluonEngine::Game::instance()->setGameProject( m_project );
    GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() );

    GluonEngine::Game::instance()->runGame();
    QApplication::instance()->exit();
}

void GameWindowManager::pauseGame()
{
    GluonEngine::Game::instance()->setPause( true );
    // stateChanged( "paused" );
}

void GameWindowManager::stopGame()
{
    GluonEngine::Game::instance()->stopGame();
}

void GameWindowManager::setProject( int index )
{
    m_gameFileName = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
    openProject();
}

int GameWindowManager::availableGamesCount( ) const
{
    return m_gameItemsModel->rowCount();
}

void GameWindowManager::buildCommentsModel( int index )
{
    QString gameID = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString();
    if( gameID.isEmpty() )
    {
        return;
    }

    m_commentItemsModel = new GluonPlayer::CommentItemsModel( gameID );
}

void GameWindowManager::setProject( const QModelIndex& index )
{
    m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
    openProject();
}

void GameWindowManager::openProject()
{
    if( m_gameFileName.isEmpty() )
    {
        return;
    }

    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
    connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );

    GluonInput::InputManager::instance()->setFilteredObject(d->widget);
    QTimer::singleShot( 1000, this, SLOT( startGame() ) );
}

void GameWindowManager::activated( QModelIndex index )
{
    if( index.isValid() )
    {
    }
}

void GameWindowManager::updateTitle( int msec )
{
    d->msecElapsed += msec;

    static int fps = 0;
    if( d->msecElapsed > 1000 )
    {
        fps = d->frameCount;
        d->frameCount = 0;
        d->msecElapsed = 0;
    }
}

void GameWindowManager::countFrames( int /* time */ )
{
    d->frameCount++;
}

GluonPlayer::GameItemsModel* GameWindowManager::gameItemsModel() const
{
    return m_gameItemsModel;
}

void GameWindowManager::setGameItemsModel(GluonPlayer::GameItemsModel* gameItemsModel)
{
    m_gameItemsModel = gameItemsModel;
}

GluonPlayer::CommentItemsModel* GameWindowManager::commentItemsModel() const
{
    return m_commentItemsModel;
}

void GameWindowManager::setCommentItemsModel(GluonPlayer::CommentItemsModel* commentItemsModel)
{
    m_commentItemsModel = commentItemsModel;
}

#include "gamewindowmanager.moc"
<commit_msg>Fix the QML Player crash on N900.<commit_after>/*****************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *****************************************************************************/

#include "gamewindowmanager.h"

#include "input/inputmanager.h"

#include "engine/scene.h"

#include <QtCore/QTimer>
#include <QtCore/QDebug>
#include <QtGui/QApplication>

using namespace GluonQMLPlayer;

class GameWindowManager::GameWindowManagerPrivate
{
    public:
        GameWindowManagerPrivate() {}

        GluonGraphics::RenderWidget* widget;

        QString title;
        QString fileName;

        int msecElapsed;
        int frameCount;
};

GameWindowManager::GameWindowManager(const QString& /* filename */)
    : QObject()
    , d( new GameWindowManagerPrivate )
{
}

GameWindowManager::GameWindowManager(GluonGraphics::RenderWidget* renderWidget, QGraphicsView* view,
                                    GluonPlayer::GameItemsModel* gameItemsModel, const QString& /* filename */ )
    : QObject()
    , d( new GameWindowManagerPrivate )
    , m_view(view)
    , m_gameItemsModel(gameItemsModel)
{
    d->widget = renderWidget;
}

GameWindowManager::~GameWindowManager ( )
{
}

bool GameWindowManager::isViewportGLWidget( )
{
    return qobject_cast<QGLWidget*>(m_view);
}

void GameWindowManager::startGame( )
{
    GluonCore::GluonObjectFactory::instance()->loadPlugins();

    m_project = new GluonEngine::GameProject();
    m_project->loadFromFile( m_gameFileName );

    GluonEngine::Game::instance()->setGameProject( m_project );
    GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() );

    GluonEngine::Game::instance()->runGame();
    QApplication::instance()->exit();
}

void GameWindowManager::pauseGame()
{
    GluonEngine::Game::instance()->setPause( true );
    // stateChanged( "paused" );
}

void GameWindowManager::stopGame()
{
    GluonEngine::Game::instance()->stopGame();
}

void GameWindowManager::setProject( int index )
{
    m_gameFileName = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
    openProject();
}

int GameWindowManager::availableGamesCount( ) const
{
    return m_gameItemsModel->rowCount();
}

void GameWindowManager::buildCommentsModel( int index )
{
    QString gameID = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString();
    if( gameID.isEmpty() )
    {
        return;
    }

    m_commentItemsModel = new GluonPlayer::CommentItemsModel( gameID );
}

void GameWindowManager::setProject( const QModelIndex& index )
{
    m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString();
    openProject();
}

void GameWindowManager::openProject()
{
    if( m_gameFileName.isEmpty() )
    {
        return;
    }

    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
    connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );

    GluonInput::InputManager::instance()->setFilteredObject(d->widget);
    QTimer::singleShot( 1000, this, SLOT( startGame() ) );
}

void GameWindowManager::activated( QModelIndex index )
{
    if( index.isValid() )
    {
    }
}

void GameWindowManager::updateTitle( int msec )
{
    d->msecElapsed += msec;

    static int fps = 0;
    if( d->msecElapsed > 1000 )
    {
        fps = d->frameCount;
        d->frameCount = 0;
        d->msecElapsed = 0;
    }
}

void GameWindowManager::countFrames( int /* time */ )
{
    d->frameCount++;
}

GluonPlayer::GameItemsModel* GameWindowManager::gameItemsModel() const
{
    return m_gameItemsModel;
}

void GameWindowManager::setGameItemsModel(GluonPlayer::GameItemsModel* gameItemsModel)
{
    m_gameItemsModel = gameItemsModel;
}

GluonPlayer::CommentItemsModel* GameWindowManager::commentItemsModel() const
{
    return m_commentItemsModel;
}

void GameWindowManager::setCommentItemsModel(GluonPlayer::CommentItemsModel* commentItemsModel)
{
    m_commentItemsModel = commentItemsModel;
}

#include "gamewindowmanager.moc"
<|endoftext|>