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

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

#include "versionhelper.hxx"

#include <rtl/ustring.hxx>
#include <iostream>

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    static char* optionSet[] = {
        "-time,      display time only",
        "-date,      display date only",
        "-upd,       display UPD only",
        "-minor,     display minor only",
        "-build,     display build only",
        "-inpath,    display inpath only",
        "-verbose,   be verbose",
        "-h:s,       display help or help on option",
        "-help:s,    see -h",
        NULL
    };

    GetOpt opt( argv, optionSet );

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        exit(0);
    }

    if (opt.getParams().empty())
    {
        // std::cerr << "error: At least a library should given." << std::endl;
        fprintf(stderr, "error: At least a library should given.\n");
        opt.showUsage();
        exit(0);
    }

    rtl::OUString suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), RTL_TEXTENCODING_ASCII_US );
    VersionHelper aHelper(suLibraryName, opt);

    if (! aHelper.isOk() )
    {
        fprintf(stderr, "error: No version info found.\n");
        exit(1);
    }

    if (opt.hasOpt("-time"))
    {
        fprintf(stdout, "%s\n", aHelper.getTime().getStr());
    }
    else if (opt.hasOpt("-date"))
    {
        fprintf(stdout, "%s\n", aHelper.getDate().getStr());
    }
    else if (opt.hasOpt("-upd"))
    {
        fprintf(stdout, "%s\n", aHelper.getUpd().getStr());
    }
    else if (opt.hasOpt("-minor"))
    {
        fprintf(stdout, "%s\n", aHelper.getMinor().getStr());
    }
    else if (opt.hasOpt("-build"))
    {
        fprintf(stdout, "%s\n", aHelper.getBuild().getStr());
    }
    else if (opt.hasOpt("-inpath"))
    {
        fprintf(stdout, "%s\n", aHelper.getInpath().getStr());
    }
    else
    {
        // std::cout << aHelper << std::endl;
        aHelper.printall(stdout);
    }

    return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.70); FILE MERGED 2005/09/05 17:28:45 rt 1.5.70.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: versioner.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:08:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "versionhelper.hxx"

#include <rtl/ustring.hxx>
#include <iostream>

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    static char* optionSet[] = {
        "-time,      display time only",
        "-date,      display date only",
        "-upd,       display UPD only",
        "-minor,     display minor only",
        "-build,     display build only",
        "-inpath,    display inpath only",
        "-verbose,   be verbose",
        "-h:s,       display help or help on option",
        "-help:s,    see -h",
        NULL
    };

    GetOpt opt( argv, optionSet );

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        exit(0);
    }

    if (opt.getParams().empty())
    {
        // std::cerr << "error: At least a library should given." << std::endl;
        fprintf(stderr, "error: At least a library should given.\n");
        opt.showUsage();
        exit(0);
    }

    rtl::OUString suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), RTL_TEXTENCODING_ASCII_US );
    VersionHelper aHelper(suLibraryName, opt);

    if (! aHelper.isOk() )
    {
        fprintf(stderr, "error: No version info found.\n");
        exit(1);
    }

    if (opt.hasOpt("-time"))
    {
        fprintf(stdout, "%s\n", aHelper.getTime().getStr());
    }
    else if (opt.hasOpt("-date"))
    {
        fprintf(stdout, "%s\n", aHelper.getDate().getStr());
    }
    else if (opt.hasOpt("-upd"))
    {
        fprintf(stdout, "%s\n", aHelper.getUpd().getStr());
    }
    else if (opt.hasOpt("-minor"))
    {
        fprintf(stdout, "%s\n", aHelper.getMinor().getStr());
    }
    else if (opt.hasOpt("-build"))
    {
        fprintf(stdout, "%s\n", aHelper.getBuild().getStr());
    }
    else if (opt.hasOpt("-inpath"))
    {
        fprintf(stdout, "%s\n", aHelper.getInpath().getStr());
    }
    else
    {
        // std::cout << aHelper << std::endl;
        aHelper.printall(stdout);
    }

    return 0;
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
    using std::strlen;
#endif

#include <osg/Notify>

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
	    return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<fileName<<")"<<std::endl;

    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<new_fileName<<")"<<std::endl;

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    std::string ext = osgDB::getFileExtension(filename);
    for(std::string::iterator itr=ext.begin();
        itr!=ext.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return ext;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for http://
    if (filename.size()<7) return false;
    if (filename.compare(0,7,"http://")==0) return true;
    return false;
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(7,pos_slash-7);
        }
        else
        {
            return filename.substr(7,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
//     std::string test("/here/we/are.exe");
//     std::string test2("\\there\\you\\go.dll");
//     std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
//     std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
//     std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
//     std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
//     std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
//     std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<commit_msg>Removed debugging messages<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
    using std::strlen;
#endif

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
	    return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    std::string ext = osgDB::getFileExtension(filename);
    for(std::string::iterator itr=ext.begin();
        itr!=ext.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return ext;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for http://
    if (filename.size()<7) return false;
    if (filename.compare(0,7,"http://")==0) return true;
    return false;
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(7,pos_slash-7);
        }
        else
        {
            return filename.substr(7,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
//     std::string test("/here/we/are.exe");
//     std::string test2("\\there\\you\\go.dll");
//     std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
//     std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
//     std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
//     std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
//     std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
//     std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<|endoftext|>


<commit_before>/**********************************************************************
 *
 *    FILE:            Text.cpp
 *
 *    DESCRIPTION:    Read/Write osgText::Text in binary format to disk.
 *
 *    CREATED BY:        Auto generated by iveGenerator
 *                    and later modified by Rune Schmidt Jensen.
 *
 *    HISTORY:        Created 27.3.2003
 *
 *    Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "Text.h"
#include "Drawable.h"
#include "Object.h"

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osg/Notify>

using namespace ive;

void Text::write(DataOutputStream* out){
    // Write Text's identification.
    out->writeInt(IVETEXT);
    // If the osg class is inherited by any other class we should also write this to file.
    osg::Object*  obj = dynamic_cast<osg::Object*>(this);
    if(obj){
        ((ive::Drawable*)(obj))->write(out);
    }
    else
        throw Exception("Text::write(): Could not cast this osgText::Text to an osg::Drawable.");
    // Write Text's properties.
    if( getFont() )
    {
        std::string fname = getFont()->getFileName();

        if(!fname.empty())
        {
            if(out->getUseOriginalExternalReferences())
            {
                out->writeString(fname); //Saving file name with local directory
            }
            else
            {
                out->writeString(osgDB::getSimpleFileName(fname)); //Saving original file name
            }
        }
        else
            out->writeString(""); //Blank string
    }
    else
        out->writeString(""); //Blank string

    out->writeUInt(getFontWidth());
    out->writeUInt(getFontHeight());
    out->writeFloat(getCharacterHeight());
    out->writeFloat(getCharacterAspectRatio());
    out->writeUInt(getCharacterSizeMode());
    out->writeFloat(getMaximumWidth());
    out->writeFloat(getMaximumHeight());
    out->writeUInt(getAlignment());

    out->writeQuat(getRotation()); //FIXME: controllare che ci sia

    out->writeBool(getAutoRotateToScreen());
    out->writeUInt(getLayout());
    out->writeVec3(getPosition());
    out->writeVec4(getColor());
    out->writeUInt(getDrawMode());

    // text :: Modified from osgPlugins::osg
    const osgText::String& textstring = getText();
    bool isACString = true;
    osgText::String::const_iterator itr;
    for(itr=textstring.begin();
        itr!=textstring.end() && isACString;
        ++itr)
    {
        if (*itr==0 || *itr>256) isACString=false;
    }

    if (isACString)
    {
        std::string str;

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            str += (char)(*itr);
        }

        //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));

        out->writeBool(true);
        out->writeString(str);
    }
    else
    {
        // do it the hardway...output each character as an int
        osg::ref_ptr<osg::UByteArray> strarr = new osg::UByteArray(textstring.size());

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            strarr->push_back((char)(*itr));
        }

        out->writeBool(false);
        out->writeUByteArray(strarr.get());
    }
}

void Text::read(DataInputStream* in){
    // Peek on Text's identification.
    int id = in->peekInt();
    if(id == IVETEXT){
        // Read Text's identification.
        id = in->readInt();
        // If the osg class is inherited by any other class we should also read this from file.
        osg::Object*  obj = dynamic_cast<osg::Object*>(this);
        if(obj){
            ((ive::Drawable*)(obj))->read(in);
        }
        else
            throw Exception("Text::read(): Could not cast this osgText::Text to an osg::Drawable.");
        // Read Text's properties

    unsigned int width, height;
    float c_height, aspectRatio;

    setFont(in->readString());

    width = in->readUInt();
    height = in->readUInt();

    setFontResolution(width,height);

    c_height = in->readFloat();
    aspectRatio = in->readFloat();

    setCharacterSize(height,aspectRatio);

    setCharacterSizeMode((osgText::Text::CharacterSizeMode) in->readUInt());

    setMaximumWidth(in->readFloat());
    setMaximumHeight(in->readFloat());

    setAlignment((osgText::Text::AlignmentType) in->readUInt());

    //Nothing to do...
    //setAxisAlignment((osgText::Text::AxisAlignment) in->readUint());

    setRotation(in->readQuat());
    setAutoRotateToScreen(in->readBool());
    setLayout((osgText::Text::Layout) in->readUInt());

    setPosition(in->readVec3());
    setColor(in->readVec4());
    setDrawMode(in->readUInt());

    if(in->readBool())
        setText(in->readString());
    else
    {
        std::string textstr;

        osg::ref_ptr<osg::UByteArray> arr = in->readUByteArray();

        for(unsigned int i = 0; i < arr->getNumElements(); i++)
        {
            textstr += (char) arr->at(i);
        }

        setText(textstr);
    }

    }
    else{
        throw Exception("ShadeModel::read(): Expected ShadeModel identification.");
    }
}
<commit_msg>From Carlo Camporesi, fixed .ive handling of character height and aspect ratio.<commit_after>/**********************************************************************
 *
 *    FILE:            Text.cpp
 *
 *    DESCRIPTION:    Read/Write osgText::Text in binary format to disk.
 *
 *    CREATED BY:        Auto generated by iveGenerator
 *                    and later modified by Rune Schmidt Jensen.
 *
 *    HISTORY:        Created 27.3.2003
 *
 *    Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "Text.h"
#include "Drawable.h"
#include "Object.h"

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osg/Notify>

using namespace ive;

void Text::write(DataOutputStream* out){
    // Write Text's identification.
    out->writeInt(IVETEXT);
    // If the osg class is inherited by any other class we should also write this to file.
    osg::Object*  obj = dynamic_cast<osg::Object*>(this);
    if(obj){
        ((ive::Drawable*)(obj))->write(out);
    }
    else
        throw Exception("Text::write(): Could not cast this osgText::Text to an osg::Drawable.");
    // Write Text's properties.
    if( getFont() )
    {
        std::string fname = getFont()->getFileName();

        if(!fname.empty())
        {
            if(out->getUseOriginalExternalReferences())
            {
                out->writeString(fname); //Saving file name with local directory
            }
            else
            {
                out->writeString(osgDB::getSimpleFileName(fname)); //Saving original file name
            }
        }
        else
            out->writeString(""); //Blank string
    }
    else
        out->writeString(""); //Blank string

    out->writeUInt(getFontWidth());
    out->writeUInt(getFontHeight());
    out->writeFloat(getCharacterHeight());
    out->writeFloat(getCharacterAspectRatio());
    out->writeUInt(getCharacterSizeMode());
    out->writeFloat(getMaximumWidth());
    out->writeFloat(getMaximumHeight());
    out->writeUInt(getAlignment());

    out->writeQuat(getRotation()); //FIXME: controllare che ci sia

    out->writeBool(getAutoRotateToScreen());
    out->writeUInt(getLayout());
    out->writeVec3(getPosition());
    out->writeVec4(getColor());
    out->writeUInt(getDrawMode());

    // text :: Modified from osgPlugins::osg
    const osgText::String& textstring = getText();
    bool isACString = true;
    osgText::String::const_iterator itr;
    for(itr=textstring.begin();
        itr!=textstring.end() && isACString;
        ++itr)
    {
        if (*itr==0 || *itr>256) isACString=false;
    }

    if (isACString)
    {
        std::string str;

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            str += (char)(*itr);
        }

        //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));

        out->writeBool(true);
        out->writeString(str);
    }
    else
    {
        // do it the hardway...output each character as an int
        osg::ref_ptr<osg::UByteArray> strarr = new osg::UByteArray(textstring.size());

        for(itr=textstring.begin();
            itr!=textstring.end();
            ++itr)
        {
            strarr->push_back((char)(*itr));
        }

        out->writeBool(false);
        out->writeUByteArray(strarr.get());
    }
}

void Text::read(DataInputStream* in){
    // Peek on Text's identification.
    int id = in->peekInt();
    if(id == IVETEXT){
        // Read Text's identification.
        id = in->readInt();
        // If the osg class is inherited by any other class we should also read this from file.
        osg::Object*  obj = dynamic_cast<osg::Object*>(this);
        if(obj){
            ((ive::Drawable*)(obj))->read(in);
        }
        else
            throw Exception("Text::read(): Could not cast this osgText::Text to an osg::Drawable.");
        // Read Text's properties

    unsigned int width, height;
    float c_height, aspectRatio;

    setFont(in->readString());

    width = in->readUInt();
    height = in->readUInt();

    setFontResolution(width,height);

    c_height = in->readFloat();
    aspectRatio = in->readFloat();

    setCharacterSize(c_height,aspectRatio);

    setCharacterSizeMode((osgText::Text::CharacterSizeMode) in->readUInt());

    setMaximumWidth(in->readFloat());
    setMaximumHeight(in->readFloat());

    setAlignment((osgText::Text::AlignmentType) in->readUInt());

    //Nothing to do...
    //setAxisAlignment((osgText::Text::AxisAlignment) in->readUint());

    setRotation(in->readQuat());
    setAutoRotateToScreen(in->readBool());
    setLayout((osgText::Text::Layout) in->readUInt());

    setPosition(in->readVec3());
    setColor(in->readVec4());
    setDrawMode(in->readUInt());

    if(in->readBool())
        setText(in->readString());
    else
    {
        std::string textstr;

        osg::ref_ptr<osg::UByteArray> arr = in->readUByteArray();

        for(unsigned int i = 0; i < arr->getNumElements(); i++)
        {
            textstr += (char) arr->at(i);
        }

        setText(textstr);
    }

    }
    else{
        throw Exception("ShadeModel::read(): Expected ShadeModel identification.");
    }
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
// oxygenwindowmanager.cpp
// pass some window mouse press/release/move event actions to window manager
// -------------------
//
// Copyright (c) 2010 Cédric Bellegarde <gnumdk@gmail.com>
//
// Largely inspired from Qtcurve style
// Copyright (C) Craig Drummond, 2003 - 2010 craig.p.drummond@gmail.com
//
// 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.
//////////////////////////////////////////////////////////////////////////////

#include <string>

#include "oxygenwindowmanager.h"
#include "oxygenstyle.h"

#define GE_IS_CONTAINER(object) ((object)  && objectIsA((GObject*)(object), "GtkContainer"))
#define GE_IS_WIDGET(object) ((object)  && objectIsA((GObject*)(object), "GtkWidget"))
#define GE_IS_MENUITEM(object) ((object)  && objectIsA((GObject*)(object), "GtkMenuItem"))
#define GE_IS_SCROLL(object) ((object)  && objectIsA((GObject*)(object), "GtkScrolledWindow"))
#define GE_IS_NOTEBOOK(object) ((object)  && objectIsA((GObject*)(object), "GtkNotebook"))

namespace Oxygen
{
    namespace Gtk
    {
        static bool drag = FALSE;

        // check object type
        static bool objectIsA( const GObject * object, const gchar * type_name )
        {
            if( ( object ) )
            {
                GType tmp = g_type_from_name( type_name );

                if( tmp )
                    return g_type_check_instance_is_a( ( GTypeInstance * ) object, tmp );
            }
            return false;
        }

        //_________________________________________________
        WindowManager::WindowManager( GtkWidget *widget )
        {
            // setup window management
            if( !g_object_get_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET" ) )
            {

                // Force widget to listen to events
                gtk_widget_add_events( widget, GDK_BUTTON_RELEASE_MASK |
                                               GDK_BUTTON_PRESS_MASK   |
                                               GDK_LEAVE_NOTIFY_MASK   |
                                               GDK_BUTTON1_MOTION_MASK );

                g_object_set_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET", ( gpointer )1 );

                _leaveId.connect( G_OBJECT( widget ), "leave-notify-event", G_CALLBACK( wmButtonRelease ), NULL );
                _destroyId.connect( G_OBJECT( widget ), "destroy-event", G_CALLBACK( wmDestroy ), this );
                _styleId.connect( G_OBJECT( widget ), "style-set", G_CALLBACK( wmStyleSet ), this );
                _pressId.connect( G_OBJECT( widget ), "button-press-event", G_CALLBACK( wmButtonPress ), widget );
                _releaseId.connect( G_OBJECT( widget ), "button-release-event", G_CALLBACK( wmButtonRelease ), widget );
                _motionId.connect( G_OBJECT( widget ), "motion-notify-event", G_CALLBACK( wmMotion ), NULL );
                _widget = widget;
            }
            else
                _widget = NULL;
        }

        //_________________________________________________
        WindowManager::~WindowManager()
        {
            if( _widget )
            {
                _leaveId.disconnect();
                _destroyId.disconnect();
                _styleId.disconnect();
                _pressId.disconnect();
                _releaseId.disconnect();
                g_object_steal_data( G_OBJECT( _widget ), "OXYGEN_WM_MOVE_HACK_SET" );
            }
        }

        //_________________________________________________
        bool WindowManager::isValid()
        {
            return _widget != NULL;
        }

        //_________________________________________________
        bool WindowManager::isWindowDragWidget( GtkWidget *widget, GdkEventButton *event )
        {
            return withinWidget(widget, event )  && useEvent( widget, event );
        }

        //_________________________________________________
        bool WindowManager::withinWidget( GtkWidget *widget, GdkEventButton *event )
        {
            GtkAllocation alloc;
            GdkWindow *window = gtk_widget_get_parent_window( widget );
            int nx = 0,
                ny = 0;

            if( !window )
                return true;

            /* Need to get absolute co-ordinates... */
#if GTK_CHECK_VERSION(2, 18, 0)
            gtk_widget_get_allocation( widget, &alloc );
#else
            alloc = widget->allocation;
#endif
            gdk_window_get_origin(window, &nx, &ny );
            alloc.x += nx;
            alloc.y += ny;

            return alloc.x <= event->x_root && alloc.y <= event->y_root &&
                (alloc.x + alloc.width) > event->x_root && (alloc.y + alloc.height) > event->y_root;
        }

        //_________________________________________________
        bool WindowManager::useEvent( GtkWidget *widget, GdkEventButton *event )
        {
            bool usable = true;

            // check if there is an hovered tab
            if( GE_IS_NOTEBOOK( widget ) )
            {
                if( Style::instance().animations().tabWidgetEngine().hoveredTab( widget ) != -1 )
                {
                    usable = false;
                }
            }
            // need to check all children that may be listening to event
            else if(GE_IS_CONTAINER( widget ) )
            {
                GList *containers = NULL;
                containers = g_list_prepend( containers, widget );

                while( g_list_length( containers ) )
                {
                    GtkContainer *c = GTK_CONTAINER( g_list_nth_data(containers, 0) );
                    GList *children = gtk_container_get_children( GTK_CONTAINER( c ) );
                    for( GList *child = g_list_first( children ); child && usable ; child = g_list_next( child ) )
                    {
                        if( child->data )
                        {
                            if( GE_IS_CONTAINER( child->data ) )
                            {
                                containers = g_list_prepend( containers, child->data );
                            }

                            // if widget is prelight, we don't need to check where event happen,
                            // any prelight widget indicate we can't do a move
                            if( GTK_WIDGET_STATE( GTK_WIDGET( child->data ) ) == GTK_STATE_PRELIGHT )
                            {
                                usable = false;
                            }
                            // if event happen in widget
                            else if( GE_IS_WIDGET( child->data ) && event && withinWidget( GTK_WIDGET( child->data ), event ) )
                            {
                                // widget listening to press event
                                if( gtk_widget_get_events ( GTK_WIDGET( child->data ) ) & GDK_BUTTON_PRESS_MASK )
                                {
                                    // here deal with notebook: widget may be not visible
                                    GdkWindow *window = gtk_widget_get_window( GTK_WIDGET ( child->data ) );
                                    if( window && gdk_window_is_visible ( window ) )
                                    {
                                        usable = false;
                                    }
                                }
                                // deal with menu item, GtkMenuItem only listen to
                                // GDK_BUTTON_PRESS_MASK when state == GTK_STATE_PRELIGHT
                                // so previous check are invalids :(
                                //
                                // same for ScrolledWindow, they do not send motion events
                                // to parents so not usable
                                else if( GE_IS_MENUITEM( G_OBJECT( child->data ) ) ||
                                         GE_IS_SCROLL( G_OBJECT( child->data ) ) )
                                {
                                    usable = false;
                                }
                            }
                        }
                    }
                    if( children )
                        g_list_free( children );
                    containers = g_list_remove( containers, c );
                }
            }
            return usable;
        }

        //_________________________________________________
        bool WindowManager::wmMove( GtkWidget *widget, int x, int y )
        {
            XEvent     xev;
            GtkWindow  *topLevel = GTK_WINDOW( gtk_widget_get_toplevel( widget ) );
            GdkWindow  *window = gtk_widget_get_window( GTK_WIDGET( topLevel ) );
            GdkDisplay *display = gtk_widget_get_display( GTK_WIDGET( topLevel ) );
            GdkWindow  *root = gdk_screen_get_root_window( gtk_window_get_screen( topLevel ) );

            xev.xclient.type = ClientMessage;
            xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_MOVERESIZE");
            xev.xclient.display = GDK_DISPLAY_XDISPLAY(display);
            xev.xclient.window = GDK_WINDOW_XID(window);
            xev.xclient.format = 32;
            xev.xclient.data.l[0] = x;
            xev.xclient.data.l[1] = y;
            xev.xclient.data.l[2] = 8; // NET::Move
            xev.xclient.data.l[3] = Button1;
            xev.xclient.data.l[4] = 0;
            XUngrabPointer(GDK_DISPLAY_XDISPLAY(display), CurrentTime);

            XSendEvent(GDK_DISPLAY_XDISPLAY(display), GDK_WINDOW_XID(root), False,
                    SubstructureRedirectMask | SubstructureNotifyMask, &xev);

            // force a release as some widgets miss it...
            wmButtonRelease( widget, NULL, NULL );

            return true;
        }

        //_________________________________________________
        bool WindowManager::wmMotion( GtkWidget *widget, GdkEventMotion *event, gpointer user_data )
        {
            if( drag )
            {
                wmMove( widget, event->x_root, event->y_root );
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmButtonPress(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
        {
            if( event->type == GDK_BUTTON_PRESS && event->button == 1  &&
                isWindowDragWidget( widget, event ) )
            {
                drag = true;
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmButtonRelease(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
        {
            if( drag )
            {
                gtk_grab_remove(widget);
                gdk_pointer_ungrab( CurrentTime );
                drag = false;
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmStyleSet( GtkWidget *widget, GtkStyle *style, gpointer user_data )
        {
            delete static_cast<WindowManager*>(user_data);
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmDestroy( GtkWidget *widget, GtkStyle *style, gpointer user_data )
        {
            delete static_cast<WindowManager*>(user_data);
            return false;
        }
    }
}
<commit_msg>Fix regression due to notebook support<commit_after>//////////////////////////////////////////////////////////////////////////////
// oxygenwindowmanager.cpp
// pass some window mouse press/release/move event actions to window manager
// -------------------
//
// Copyright (c) 2010 Cédric Bellegarde <gnumdk@gmail.com>
//
// Largely inspired from Qtcurve style
// Copyright (C) Craig Drummond, 2003 - 2010 craig.p.drummond@gmail.com
//
// 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.
//////////////////////////////////////////////////////////////////////////////

#include <string>

#include "oxygenwindowmanager.h"
#include "oxygenstyle.h"

#define GE_IS_CONTAINER(object) ((object)  && objectIsA((GObject*)(object), "GtkContainer"))
#define GE_IS_WIDGET(object) ((object)  && objectIsA((GObject*)(object), "GtkWidget"))
#define GE_IS_MENUITEM(object) ((object)  && objectIsA((GObject*)(object), "GtkMenuItem"))
#define GE_IS_SCROLL(object) ((object)  && objectIsA((GObject*)(object), "GtkScrolledWindow"))
#define GE_IS_NOTEBOOK(object) ((object)  && objectIsA((GObject*)(object), "GtkNotebook"))

namespace Oxygen
{
    namespace Gtk
    {
        static bool drag = FALSE;

        // check object type
        static bool objectIsA( const GObject * object, const gchar * type_name )
        {
            if( ( object ) )
            {
                GType tmp = g_type_from_name( type_name );

                if( tmp )
                    return g_type_check_instance_is_a( ( GTypeInstance * ) object, tmp );
            }
            return false;
        }

        //_________________________________________________
        WindowManager::WindowManager( GtkWidget *widget )
        {
            // setup window management
            if( !g_object_get_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET" ) )
            {

                // Force widget to listen to events
                gtk_widget_add_events( widget, GDK_BUTTON_RELEASE_MASK |
                                               GDK_BUTTON_PRESS_MASK   |
                                               GDK_LEAVE_NOTIFY_MASK   |
                                               GDK_BUTTON1_MOTION_MASK );

                g_object_set_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET", ( gpointer )1 );

                _leaveId.connect( G_OBJECT( widget ), "leave-notify-event", G_CALLBACK( wmButtonRelease ), NULL );
                _destroyId.connect( G_OBJECT( widget ), "destroy-event", G_CALLBACK( wmDestroy ), this );
                _styleId.connect( G_OBJECT( widget ), "style-set", G_CALLBACK( wmStyleSet ), this );
                _pressId.connect( G_OBJECT( widget ), "button-press-event", G_CALLBACK( wmButtonPress ), widget );
                _releaseId.connect( G_OBJECT( widget ), "button-release-event", G_CALLBACK( wmButtonRelease ), widget );
                _motionId.connect( G_OBJECT( widget ), "motion-notify-event", G_CALLBACK( wmMotion ), NULL );
                _widget = widget;
            }
            else
                _widget = NULL;
        }

        //_________________________________________________
        WindowManager::~WindowManager()
        {
            if( _widget )
            {
                _leaveId.disconnect();
                _destroyId.disconnect();
                _styleId.disconnect();
                _pressId.disconnect();
                _releaseId.disconnect();
                g_object_steal_data( G_OBJECT( _widget ), "OXYGEN_WM_MOVE_HACK_SET" );
            }
        }

        //_________________________________________________
        bool WindowManager::isValid()
        {
            return _widget != NULL;
        }

        //_________________________________________________
        bool WindowManager::isWindowDragWidget( GtkWidget *widget, GdkEventButton *event )
        {
            return withinWidget(widget, event )  && useEvent( widget, event );
        }

        //_________________________________________________
        bool WindowManager::withinWidget( GtkWidget *widget, GdkEventButton *event )
        {
            GtkAllocation alloc;
            GdkWindow *window = gtk_widget_get_parent_window( widget );
            int nx = 0,
                ny = 0;

            if( !window )
                return true;

            /* Need to get absolute co-ordinates... */
#if GTK_CHECK_VERSION(2, 18, 0)
            gtk_widget_get_allocation( widget, &alloc );
#else
            alloc = widget->allocation;
#endif
            gdk_window_get_origin(window, &nx, &ny );
            alloc.x += nx;
            alloc.y += ny;

            return alloc.x <= event->x_root && alloc.y <= event->y_root &&
                (alloc.x + alloc.width) > event->x_root && (alloc.y + alloc.height) > event->y_root;
        }

        //_________________________________________________
        bool WindowManager::useEvent( GtkWidget *widget, GdkEventButton *event )
        {
            bool usable = true;

            // check if there is an hovered tab
            if( GE_IS_NOTEBOOK( widget ) )
            {
                if( Style::instance().animations().tabWidgetEngine().hoveredTab( widget ) != -1 )
                {
                    usable = false;
                }
            }
            // need to check all children that may be listening to event
            else if(GE_IS_CONTAINER( widget ) )
            {
                GList *containers = NULL;
                containers = g_list_prepend( containers, widget );

                while( g_list_length( containers ) )
                {
                    GtkContainer *c = GTK_CONTAINER( g_list_nth_data(containers, 0) );
                    GList *children = gtk_container_get_children( GTK_CONTAINER( c ) );
                    for( GList *child = g_list_first( children ); child && usable ; child = g_list_next( child ) )
                    {
                        if( child->data )
                        {
                            if( GE_IS_CONTAINER( child->data ) )
                            {
                                containers = g_list_prepend( containers, child->data );
                            }

                            // if widget is prelight, we don't need to check where event happen,
                            // any prelight widget indicate we can't do a move
                            if( GTK_WIDGET_STATE( GTK_WIDGET( child->data ) ) == GTK_STATE_PRELIGHT )
                            {
                                usable = false;
                            }
                            // if event happen in widget
                            // check not a notebook: event in but notebook don't get it...
                            else if( GE_IS_WIDGET( child->data ) && !GE_IS_NOTEBOOK ( child->data ) &&
                                     event && withinWidget( GTK_WIDGET( child->data ), event ) )
                            {
                                // here deal with notebook: widget may be not visible
                                GdkWindow *window = gtk_widget_get_window( GTK_WIDGET ( child->data ) );
                                if( window && gdk_window_is_visible ( window ) )
                                {
                                    // widget listening to press event
                                    if( gtk_widget_get_events ( GTK_WIDGET( child->data ) ) & GDK_BUTTON_PRESS_MASK )
                                    {
                                        usable = false;
                                    }
                                    // deal with menu item, GtkMenuItem only listen to
                                    // GDK_BUTTON_PRESS_MASK when state == GTK_STATE_PRELIGHT
                                    // so previous check are invalids :(
                                    //
                                    // same for ScrolledWindow, they do not send motion events
                                    // to parents so not usable
                                    else if( GE_IS_MENUITEM( G_OBJECT( child->data ) ) ||
                                             GE_IS_SCROLL( G_OBJECT( child->data ) ) )
                                    {
                                        usable = false;
                                    }
                                }
                            }
                        }
                    }
                    if( children )
                        g_list_free( children );
                    containers = g_list_remove( containers, c );
                }
            }
            return usable;
        }

        //_________________________________________________
        bool WindowManager::wmMove( GtkWidget *widget, int x, int y )
        {
            XEvent     xev;
            GtkWindow  *topLevel = GTK_WINDOW( gtk_widget_get_toplevel( widget ) );
            GdkWindow  *window = gtk_widget_get_window( GTK_WIDGET( topLevel ) );
            GdkDisplay *display = gtk_widget_get_display( GTK_WIDGET( topLevel ) );
            GdkWindow  *root = gdk_screen_get_root_window( gtk_window_get_screen( topLevel ) );

            xev.xclient.type = ClientMessage;
            xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_MOVERESIZE");
            xev.xclient.display = GDK_DISPLAY_XDISPLAY(display);
            xev.xclient.window = GDK_WINDOW_XID(window);
            xev.xclient.format = 32;
            xev.xclient.data.l[0] = x;
            xev.xclient.data.l[1] = y;
            xev.xclient.data.l[2] = 8; // NET::Move
            xev.xclient.data.l[3] = Button1;
            xev.xclient.data.l[4] = 0;
            XUngrabPointer(GDK_DISPLAY_XDISPLAY(display), CurrentTime);

            XSendEvent(GDK_DISPLAY_XDISPLAY(display), GDK_WINDOW_XID(root), False,
                    SubstructureRedirectMask | SubstructureNotifyMask, &xev);

            // force a release as some widgets miss it...
            wmButtonRelease( widget, NULL, NULL );

            return true;
        }

        //_________________________________________________
        bool WindowManager::wmMotion( GtkWidget *widget, GdkEventMotion *event, gpointer user_data )
        {
            if( drag )
            {
                wmMove( widget, event->x_root, event->y_root );
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmButtonPress(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
        {
            if( event->type == GDK_BUTTON_PRESS && event->button == 1  &&
                isWindowDragWidget( widget, event ) )
            {
                drag = true;
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmButtonRelease(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
        {
            if( drag )
            {
                gtk_grab_remove(widget);
                gdk_pointer_ungrab( CurrentTime );
                drag = false;
                return true;
            }
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmStyleSet( GtkWidget *widget, GtkStyle *style, gpointer user_data )
        {
            delete static_cast<WindowManager*>(user_data);
            return false;
        }

        //_________________________________________________
        bool WindowManager::wmDestroy( GtkWidget *widget, GtkStyle *style, gpointer user_data )
        {
            delete static_cast<WindowManager*>(user_data);
            return false;
        }
    }
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <fstream>
#include <thread>

#include <QWidget>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QLayout>
#include <QDateTime>

#include "common/params.h"

#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"

#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00

OffroadHome::OffroadHome(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout();
  main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);

  // top header
  QHBoxLayout *header_layout = new QHBoxLayout();

  date = new QLabel();
  date->setStyleSheet(R"(font-size: 55px;)");
  header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);

  QLabel *version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
  version->setStyleSheet(R"(font-size: 45px;)");
  header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);

  main_layout->addLayout(header_layout);

  alert_notification = new QPushButton();
  QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
  main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);

  // main content
  main_layout->addSpacing(25);
  center_layout = new QStackedLayout();

  DriveStats *drive = new DriveStats;
  drive->setFixedSize(1000, 800);
  center_layout->addWidget(drive);

  alerts_widget = new OffroadAlert();
  QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
  center_layout->addWidget(alerts_widget);
  center_layout->setAlignment(alerts_widget, Qt::AlignCenter);

  main_layout->addLayout(center_layout, 1);

  // set up refresh timer
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
  refresh();
  timer->start(10 * 1000);

  setLayout(main_layout);
  setStyleSheet(R"(background-color: none;)");
}

void OffroadHome::openAlerts() {
  center_layout->setCurrentIndex(1);
}

void OffroadHome::closeAlerts() {
  center_layout->setCurrentIndex(0);
}

void OffroadHome::refresh() {
  bool first_refresh = !date->text().size();
  if (!isVisible() && !first_refresh) {
    return;
  }

  date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));

  // update alerts

  alerts_widget->refresh();
  if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
    alert_notification->setVisible(false);
    return;
  }

  if (alerts_widget->updateAvailable) {
    // There is a new release
    alert_notification->setText("UPDATE");
  } else {
    int alerts = alerts_widget->alerts.size();
    alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
  }

  alert_notification->setVisible(true);

  // Red background for alerts, blue for update available
  QString style = QString(R"(
    padding: 15px;
    padding-left: 30px;
    padding-right: 30px;
    border: 1px solid;
    border-radius: 5px;
    font-size: 40px;
    font-weight: bold;
    background-color: #E22C2C;
  )");
  if (alerts_widget->updateAvailable){
    style.replace("#E22C2C", "#364DEF");
  }
  alert_notification->setStyleSheet(style);
}

HomeWindow::HomeWindow(QWidget *parent) : QWidget(parent) {
  layout = new QGridLayout;
  layout->setMargin(0);

  // onroad UI
  glWindow = new GLWindow(this);
  layout->addWidget(glWindow, 0, 0);

  // draw offroad UI on top of onroad UI
  home = new OffroadHome();
  layout->addWidget(home, 0, 0);
  QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
  QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
  setLayout(layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
  )");
}

void HomeWindow::setVisibility(bool offroad) {
  home->setVisible(offroad);
}

void HomeWindow::mousePressEvent(QMouseEvent *e) {
  UIState *ui_state = glWindow->ui_state;

  glWindow->wake();

  // Settings button click
  if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
    emit openSettings();
  }

  // Vision click
  if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
    ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
  }
}

static void handle_display_state(UIState *s, int dt, bool user_input) {
  static int awake_timeout = 0;
  awake_timeout = std::max(awake_timeout-dt, 0);

  if (user_input || s->ignition || s->started) {
    s->awake = true;
    awake_timeout = 30*UI_FREQ;
  } else if (awake_timeout == 0) {
    s->awake = false;
  }
}

static void set_backlight(int brightness) {
  std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
  if (brightness_control.is_open()) {
    brightness_control << brightness << "\n";
    brightness_control.close();
  }
}

GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));

  backlight_timer = new QTimer(this);
  QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));

  int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
  result += read_param(&brightness_m, "BRIGHTNESS_M", true);
  if (result != 0) {
    brightness_b = 200.0;
    brightness_m = 10.0;
  }
  smooth_brightness = 512;
}

GLWindow::~GLWindow() {
  makeCurrent();
  doneCurrent();
}

void GLWindow::initializeGL() {
  initializeOpenGLFunctions();
  std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
  std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
  std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
  std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;

  ui_state = new UIState();
  ui_state->sound = &sound;
  ui_init(ui_state);

  wake();

  timer->start(0);
  backlight_timer->start(BACKLIGHT_DT * 1000);
}

void GLWindow::backlightUpdate() {
  // Update brightness
  float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);

  float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
  smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
  int brightness = smooth_brightness;

  if (!ui_state->awake) {
    brightness = 0;
  }

  std::thread{set_backlight, brightness}.detach();
}

void GLWindow::timerUpdate() {
  if (ui_state->started != onroad) {
    onroad = ui_state->started;
    emit offroadTransition(!onroad);
#ifdef QCOM2
    timer->setInterval(onroad ? 0 : 1000);
#endif
  }

  // Fix awake timeout if running 1 Hz when offroad
  int dt = timer->interval() == 0 ? 1 : 20;
  handle_display_state(ui_state, dt, false);

  ui_update(ui_state);
  repaint();
}

void GLWindow::resizeGL(int w, int h) {
  std::cout << "resize " << w << "x" << h << std::endl;
}

void GLWindow::paintGL() {
  ui_draw(ui_state);
}

void GLWindow::wake() {
  // UI state might not be initialized yet
  if (ui_state != nullptr) {
    handle_display_state(ui_state, 1, true);
  }
}

FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
                                   int *out_w, int *out_h) {
  *out_w = vwp_w;
  *out_h = vwp_h;
  return (FramebufferState*)1; // not null
}
<commit_msg>Remove spaces (#19779)<commit_after>#include <cmath>
#include <iostream>
#include <fstream>
#include <thread>

#include <QWidget>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QLayout>
#include <QDateTime>

#include "common/params.h"

#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"

#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00

OffroadHome::OffroadHome(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout();
  main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);

  // top header
  QHBoxLayout *header_layout = new QHBoxLayout();

  date = new QLabel();
  date->setStyleSheet(R"(font-size: 55px;)");
  header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);

  QLabel *version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
  version->setStyleSheet(R"(font-size: 45px;)");
  header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);

  main_layout->addLayout(header_layout);

  alert_notification = new QPushButton();
  QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
  main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);

  // main content
  main_layout->addSpacing(25);
  center_layout = new QStackedLayout();

  DriveStats *drive = new DriveStats;
  drive->setFixedSize(1000, 800);
  center_layout->addWidget(drive);

  alerts_widget = new OffroadAlert();
  QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
  center_layout->addWidget(alerts_widget);
  center_layout->setAlignment(alerts_widget, Qt::AlignCenter);

  main_layout->addLayout(center_layout, 1);

  // set up refresh timer
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
  refresh();
  timer->start(10 * 1000);

  setLayout(main_layout);
  setStyleSheet(R"(background-color: none;)");
}

void OffroadHome::openAlerts() {
  center_layout->setCurrentIndex(1);
}

void OffroadHome::closeAlerts() {
  center_layout->setCurrentIndex(0);
}

void OffroadHome::refresh() {
  bool first_refresh = !date->text().size();
  if (!isVisible() && !first_refresh) {
    return;
  }

  date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));

  // update alerts

  alerts_widget->refresh();
  if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
    alert_notification->setVisible(false);
    return;
  }

  if (alerts_widget->updateAvailable) {
    // There is a new release
    alert_notification->setText("UPDATE");
  } else {
    int alerts = alerts_widget->alerts.size();
    alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
  }

  alert_notification->setVisible(true);

  // Red background for alerts, blue for update available
  QString style = QString(R"(
    padding: 15px;
    padding-left: 30px;
    padding-right: 30px;
    border: 1px solid;
    border-radius: 5px;
    font-size: 40px;
    font-weight: bold;
    background-color: #E22C2C;
  )");
  if (alerts_widget->updateAvailable){
    style.replace("#E22C2C", "#364DEF");
  }
  alert_notification->setStyleSheet(style);
}

HomeWindow::HomeWindow(QWidget *parent) : QWidget(parent) {
  layout = new QGridLayout;
  layout->setMargin(0);

  // onroad UI
  glWindow = new GLWindow(this);
  layout->addWidget(glWindow, 0, 0);

  // draw offroad UI on top of onroad UI
  home = new OffroadHome();
  layout->addWidget(home, 0, 0);
  QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
  QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
  setLayout(layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
  )");
}

void HomeWindow::setVisibility(bool offroad) {
  home->setVisible(offroad);
}

void HomeWindow::mousePressEvent(QMouseEvent *e) {
  UIState *ui_state = glWindow->ui_state;

  glWindow->wake();

  // Settings button click
  if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
    emit openSettings();
  }

  // Vision click
  if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
    ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
  }
}

static void handle_display_state(UIState *s, int dt, bool user_input) {
  static int awake_timeout = 0;
  awake_timeout = std::max(awake_timeout-dt, 0);

  if (user_input || s->ignition || s->started) {
    s->awake = true;
    awake_timeout = 30*UI_FREQ;
  } else if (awake_timeout == 0) {
    s->awake = false;
  }
}

static void set_backlight(int brightness) {
  std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
  if (brightness_control.is_open()) {
    brightness_control << brightness << "\n";
    brightness_control.close();
  }
}

GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));

  backlight_timer = new QTimer(this);
  QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));

  int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
  result += read_param(&brightness_m, "BRIGHTNESS_M", true);
  if (result != 0) {
    brightness_b = 200.0;
    brightness_m = 10.0;
  }
  smooth_brightness = 512;
}

GLWindow::~GLWindow() {
  makeCurrent();
  doneCurrent();
}

void GLWindow::initializeGL() {
  initializeOpenGLFunctions();
  std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
  std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
  std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
  std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;

  ui_state = new UIState();
  ui_state->sound = &sound;
  ui_init(ui_state);

  wake();

  timer->start(0);
  backlight_timer->start(BACKLIGHT_DT * 1000);
}

void GLWindow::backlightUpdate() {
  // Update brightness
  float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);

  float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
  smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
  int brightness = smooth_brightness;

  if (!ui_state->awake) {
    brightness = 0;
  }

  std::thread{set_backlight, brightness}.detach();
}

void GLWindow::timerUpdate() {
  if (ui_state->started != onroad) {
    onroad = ui_state->started;
    emit offroadTransition(!onroad);
#ifdef QCOM2
    timer->setInterval(onroad ? 0 : 1000);
#endif
  }

  // Fix awake timeout if running 1 Hz when offroad
  int dt = timer->interval() == 0 ? 1 : 20;
  handle_display_state(ui_state, dt, false);

  ui_update(ui_state);
  repaint();
}

void GLWindow::resizeGL(int w, int h) {
  std::cout << "resize " << w << "x" << h << std::endl;
}

void GLWindow::paintGL() {
  ui_draw(ui_state);
}

void GLWindow::wake() {
  // UI state might not be initialized yet
  if (ui_state != nullptr) {
    handle_display_state(ui_state, 1, true);
  }
}

FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
                                   int *out_w, int *out_h) {
  *out_w = vwp_w;
  *out_h = vwp_h;
  return (FramebufferState*)1; // not null
}
<|endoftext|>


<commit_before>#include <cmath>
#include <fstream>
#include <iostream>
#include <thread>

#include <QDateTime>
#include <QHBoxLayout>
#include <QLayout>
#include <QMouseEvent>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <QWidget>

#include "common/params.h"

#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#include "widgets/setup.hpp"

#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00

OffroadHome::OffroadHome(QWidget* parent) : QWidget(parent) {
  QVBoxLayout* main_layout = new QVBoxLayout();
  main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);

  // top header
  QHBoxLayout* header_layout = new QHBoxLayout();

  date = new QLabel();
  date->setStyleSheet(R"(font-size: 55px;)");
  header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);

  QLabel* version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
  version->setStyleSheet(R"(font-size: 45px;)");
  header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);

  main_layout->addLayout(header_layout);

  alert_notification = new QPushButton();
  QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
  main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);

  // main content
  main_layout->addSpacing(25);
  center_layout = new QStackedLayout();

  QHBoxLayout* statsAndSetup = new QHBoxLayout();

  DriveStats* drive = new DriveStats;
  drive->setFixedSize(1000, 800);
  statsAndSetup->addWidget(drive);

  SetupWidget* setup = new SetupWidget;
  statsAndSetup->addWidget(setup);

  QWidget* statsAndSetupWidget = new QWidget();
  statsAndSetupWidget->setLayout(statsAndSetup);

  center_layout->addWidget(statsAndSetupWidget);

  alerts_widget = new OffroadAlert();
  QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
  center_layout->addWidget(alerts_widget);
  center_layout->setAlignment(alerts_widget, Qt::AlignCenter);

  main_layout->addLayout(center_layout, 1);

  // set up refresh timer
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
  refresh();
  timer->start(10 * 1000);

  setLayout(main_layout);
  setStyleSheet(R"(background-color: none;)");
}

void OffroadHome::openAlerts() {
  center_layout->setCurrentIndex(1);
}

void OffroadHome::closeAlerts() {
  center_layout->setCurrentIndex(0);
}

void OffroadHome::refresh() {
  bool first_refresh = !date->text().size();
  if (!isVisible() && !first_refresh) {
    return;
  }

  date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));

  // update alerts

  alerts_widget->refresh();
  if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
    alert_notification->setVisible(false);
    return;
  }

  if (alerts_widget->updateAvailable) {
    // There is a new release
    alert_notification->setText("UPDATE");
  } else {
    int alerts = alerts_widget->alerts.size();
    alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
  }

  alert_notification->setVisible(true);

  // Red background for alerts, blue for update available
  QString style = QString(R"(
    padding: 15px;
    padding-left: 30px;
    padding-right: 30px;
    border: 1px solid;
    border-radius: 5px;
    font-size: 40px;
    font-weight: bold;
    background-color: #E22C2C;
  )");
  if (alerts_widget->updateAvailable) {
    style.replace("#E22C2C", "#364DEF");
  }
  alert_notification->setStyleSheet(style);
}

HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) {
  layout = new QGridLayout;
  layout->setMargin(0);

  // onroad UI
  glWindow = new GLWindow(this);
  layout->addWidget(glWindow, 0, 0);

  // draw offroad UI on top of onroad UI
  home = new OffroadHome();
  layout->addWidget(home, 0, 0);
  QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
  QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
  setLayout(layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
  )");
}

void HomeWindow::setVisibility(bool offroad) {
  home->setVisible(offroad);
}

void HomeWindow::mousePressEvent(QMouseEvent* e) {
  UIState* ui_state = &glWindow->ui_state;

  glWindow->wake();

  // Settings button click
  if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
    emit openSettings();
  }

  // Vision click
  if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
    ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
  }
}

static void handle_display_state(UIState* s, bool user_input) {
  static int awake_timeout = 0; // Somehow this only gets called on program start
  awake_timeout = std::max(awake_timeout - 1, 0);

  if (user_input || s->ignition || s->started) {
    s->awake = true;
    awake_timeout = 30 * UI_FREQ;
  } else if (awake_timeout == 0) {
    s->awake = false;
  }
}

static void set_backlight(int brightness) {
  std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
  if (brightness_control.is_open()) {
    brightness_control << brightness << "\n";
    brightness_control.close();
  }
}

GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent) {
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));

  backlight_timer = new QTimer(this);
  QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));

  int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
  result += read_param(&brightness_m, "BRIGHTNESS_M", true);
  if (result != 0) {
    brightness_b = 200.0;
    brightness_m = 10.0;
  }
  smooth_brightness = 512;
}

GLWindow::~GLWindow() {
  makeCurrent();
  doneCurrent();
}

void GLWindow::initializeGL() {
  initializeOpenGLFunctions();
  std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
  std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
  std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
  std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;

  ui_state.sound = &sound;
  ui_init(&ui_state);

  wake();

  timer->start(1000 / UI_FREQ);
  backlight_timer->start(BACKLIGHT_DT * 1000);
}

void GLWindow::backlightUpdate() {
  // Update brightness
  float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);

  float clipped_brightness = std::min(1023.0f, (ui_state.light_sensor * brightness_m) + brightness_b);
  smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
  int brightness = smooth_brightness;

  if (!ui_state.awake) {
    brightness = 0;
  }

  std::thread{set_backlight, brightness}.detach();
}

void GLWindow::timerUpdate() {
  // Connecting to visionIPC requires opengl to be current
  if (!ui_state.vipc_client->connected){
    makeCurrent();
  }

  if (ui_state.started != onroad) {
    onroad = ui_state.started;
    emit offroadTransition(!onroad);
  }

  handle_display_state(&ui_state, false);

  ui_update(&ui_state);
  repaint();
}

void GLWindow::resizeGL(int w, int h) {
  std::cout << "resize " << w << "x" << h << std::endl;
}

void GLWindow::paintGL() {
  if(GLWindow::ui_state.awake){
    ui_draw(&ui_state);
  }
}

void GLWindow::wake() {
  handle_display_state(&ui_state, true);
}

FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
                                   int *out_w, int *out_h) {
  *out_w = vwp_w;
  *out_h = vwp_h;
  return (FramebufferState*)1; // not null
}
<commit_msg>qt ui: sync fps with camera<commit_after>#include <cmath>
#include <fstream>
#include <iostream>
#include <thread>

#include <QDateTime>
#include <QHBoxLayout>
#include <QLayout>
#include <QMouseEvent>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <QWidget>

#include "common/params.h"

#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#include "widgets/setup.hpp"

#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00

OffroadHome::OffroadHome(QWidget* parent) : QWidget(parent) {
  QVBoxLayout* main_layout = new QVBoxLayout();
  main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);

  // top header
  QHBoxLayout* header_layout = new QHBoxLayout();

  date = new QLabel();
  date->setStyleSheet(R"(font-size: 55px;)");
  header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);

  QLabel* version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
  version->setStyleSheet(R"(font-size: 45px;)");
  header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);

  main_layout->addLayout(header_layout);

  alert_notification = new QPushButton();
  QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
  main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);

  // main content
  main_layout->addSpacing(25);
  center_layout = new QStackedLayout();

  QHBoxLayout* statsAndSetup = new QHBoxLayout();

  DriveStats* drive = new DriveStats;
  drive->setFixedSize(1000, 800);
  statsAndSetup->addWidget(drive);

  SetupWidget* setup = new SetupWidget;
  statsAndSetup->addWidget(setup);

  QWidget* statsAndSetupWidget = new QWidget();
  statsAndSetupWidget->setLayout(statsAndSetup);

  center_layout->addWidget(statsAndSetupWidget);

  alerts_widget = new OffroadAlert();
  QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
  center_layout->addWidget(alerts_widget);
  center_layout->setAlignment(alerts_widget, Qt::AlignCenter);

  main_layout->addLayout(center_layout, 1);

  // set up refresh timer
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
  refresh();
  timer->start(10 * 1000);

  setLayout(main_layout);
  setStyleSheet(R"(background-color: none;)");
}

void OffroadHome::openAlerts() {
  center_layout->setCurrentIndex(1);
}

void OffroadHome::closeAlerts() {
  center_layout->setCurrentIndex(0);
}

void OffroadHome::refresh() {
  bool first_refresh = !date->text().size();
  if (!isVisible() && !first_refresh) {
    return;
  }

  date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));

  // update alerts

  alerts_widget->refresh();
  if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
    alert_notification->setVisible(false);
    return;
  }

  if (alerts_widget->updateAvailable) {
    // There is a new release
    alert_notification->setText("UPDATE");
  } else {
    int alerts = alerts_widget->alerts.size();
    alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
  }

  alert_notification->setVisible(true);

  // Red background for alerts, blue for update available
  QString style = QString(R"(
    padding: 15px;
    padding-left: 30px;
    padding-right: 30px;
    border: 1px solid;
    border-radius: 5px;
    font-size: 40px;
    font-weight: bold;
    background-color: #E22C2C;
  )");
  if (alerts_widget->updateAvailable) {
    style.replace("#E22C2C", "#364DEF");
  }
  alert_notification->setStyleSheet(style);
}

HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) {
  layout = new QGridLayout;
  layout->setMargin(0);

  // onroad UI
  glWindow = new GLWindow(this);
  layout->addWidget(glWindow, 0, 0);

  // draw offroad UI on top of onroad UI
  home = new OffroadHome();
  layout->addWidget(home, 0, 0);
  QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
  QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
  setLayout(layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
  )");
}

void HomeWindow::setVisibility(bool offroad) {
  home->setVisible(offroad);
}

void HomeWindow::mousePressEvent(QMouseEvent* e) {
  UIState* ui_state = &glWindow->ui_state;

  glWindow->wake();

  // Settings button click
  if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
    emit openSettings();
  }

  // Vision click
  if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
    ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
  }
}

static void handle_display_state(UIState* s, bool user_input) {
  static int awake_timeout = 0; // Somehow this only gets called on program start
  awake_timeout = std::max(awake_timeout - 1, 0);

  if (user_input || s->ignition || s->started) {
    s->awake = true;
    awake_timeout = 30 * UI_FREQ;
  } else if (awake_timeout == 0) {
    s->awake = false;
  }
}

static void set_backlight(int brightness) {
  std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
  if (brightness_control.is_open()) {
    brightness_control << brightness << "\n";
    brightness_control.close();
  }
}

GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent) {
  timer = new QTimer(this);
  QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));

  backlight_timer = new QTimer(this);
  QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));

  int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
  result += read_param(&brightness_m, "BRIGHTNESS_M", true);
  if (result != 0) {
    brightness_b = 200.0;
    brightness_m = 10.0;
  }
  smooth_brightness = 512;
}

GLWindow::~GLWindow() {
  makeCurrent();
  doneCurrent();
}

void GLWindow::initializeGL() {
  initializeOpenGLFunctions();
  std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
  std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
  std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
  std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;

  ui_state.sound = &sound;
  ui_init(&ui_state);

  wake();

  timer->start(1000 / UI_FREQ);
  backlight_timer->start(BACKLIGHT_DT * 1000);
}

void GLWindow::backlightUpdate() {
  // Update brightness
  float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);

  float clipped_brightness = std::min(1023.0f, (ui_state.light_sensor * brightness_m) + brightness_b);
  smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
  int brightness = smooth_brightness;

  if (!ui_state.awake) {
    brightness = 0;
  }

  std::thread{set_backlight, brightness}.detach();
}

void GLWindow::timerUpdate() {
  // Connecting to visionIPC requires opengl to be current
  if (!ui_state.vipc_client->connected){
    makeCurrent();
  }

  if (ui_state.started != onroad) {
    onroad = ui_state.started;
    emit offroadTransition(!onroad);

    // Change timeout to 0 when onroad, this will call timerUpdate continously.
    // This puts visionIPC in charge of update frequency, reducing video latency
    timer->start(onroad ? 0 : 1000 / UI_FREQ);
  }

  handle_display_state(&ui_state, false);

  ui_update(&ui_state);
  repaint();
}

void GLWindow::resizeGL(int w, int h) {
  std::cout << "resize " << w << "x" << h << std::endl;
}

void GLWindow::paintGL() {
  if(GLWindow::ui_state.awake){
    ui_draw(&ui_state);
  }
}

void GLWindow::wake() {
  handle_display_state(&ui_state, true);
}

FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
                                   int *out_w, int *out_h) {
  *out_w = vwp_w;
  *out_h = vwp_h;
  return (FramebufferState*)1; // not null
}
<|endoftext|>


<commit_before>#include "test_macros.hpp"

#include <matrix/math.hpp>

using namespace matrix;

int main()
{
    float data1[] = {1,2,3,4,5};
    float data2[] = {6,7,8,9,10};
    Vector<float, 5> v1(data1);
    TEST(isEqualF(v1.norm(), 7.416198487095663f));
    TEST(isEqualF(v1.norm(), v1.length()));
    Vector<float, 5> v2(data2);
    TEST(isEqualF(v1.dot(v2), 130.0f));
    v2.normalize();
    Vector<float, 5> v3(v2);
    TEST(isEqual(v2, v3));
    float data1_sq[] = {1,4,9,16,25};
    Vector<float, 5> v4(data1_sq);
    TEST(isEqual(v1, v4.pow(0.5)));

    // dot product operator
    v1 = Vector<float, 5>(data1);
    v2 = Vector<float, 5>(data2);
    float dprod = v1 * v2;
    TEST(isEqualF(dprod, 130.0f));
    return 0;
}

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Test vector: structured & commented, added normalize and unit_or_zero tests, removed duplicate data preparation<commit_after>#include "test_macros.hpp"

#include <matrix/math.hpp>

using namespace matrix;

int main()
{
    // test data
    float data1[] = {1,2,3,4,5};
    float data2[] = {6,7,8,9,10};
    Vector<float, 5> v1(data1);
    Vector<float, 5> v2(data2);

    // copy constructor
    Vector<float, 5> v3(v2);
    TEST(isEqual(v2, v3));

    // norm, dot product
    TEST(isEqualF(v1.norm(), 7.416198487095663f));
    TEST(isEqualF(v1.norm(), v1.length()));
    TEST(isEqualF(v1.dot(v2), 130.0f));
    TEST(isEqualF(v1.dot(v2), v1 * v2));

    // unit, unit_zero, normalize
    TEST(isEqualF(v2.unit().norm(), 1.f));
    TEST(isEqualF(v2.unit_or_zero().norm(), 1.f));
    TEST(isEqualF(Vector<float, 5>().unit_or_zero().norm(), 0.f));
    v2.normalize();
    TEST(isEqualF(v2.norm(), 1.f));

    // power
    float data1_sq[] = {1,4,9,16,25};
    Vector<float, 5> v4(data1_sq);
    TEST(isEqual(v1, v4.pow(0.5)));

    return 0;
}

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|>