<commit_before>/*************************************************************************
 *
 *  $RCSfile: edtwin3.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: os $ $Date: 2002-06-12 08:46: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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <hintids.hxx>
#include "uiparam.hxx"
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif

#ifndef _VIEWOPT_HXX //autogen
#include <viewopt.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "pview.hxx"
#include "mdiexp.hxx"
#include "edtwin.hxx"
#include "swmodule.hxx"
#include "modcfg.hxx"
#include "swtable.hxx"
#include "docsh.hxx"
#include "pagedesc.hxx"     // Aktuelles Seitenformat
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_FRMDIRITEM_HXX
#include <svx/frmdiritem.hxx>
#endif

/*--------------------------------------------------------------------
    Beschreibung:   Core-Notify
 --------------------------------------------------------------------*/

void ScrollMDI( ViewShell* pVwSh, const SwRect &rRect,
                USHORT nRangeX, USHORT nRangeY)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA(SwView))
        ((SwView *)pSfxVwSh)->Scroll( rRect.SVRect(), nRangeX, nRangeY );
}

/*--------------------------------------------------------------------
    Beschreibung:   Docmdi - verschiebbar
 --------------------------------------------------------------------*/

BOOL IsScrollMDI( ViewShell* pVwSh, const SwRect &rRect )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA(SwView))
        return (((SwView *)pSfxVwSh)->IsScroll(rRect.SVRect()));
    return FALSE;
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Groessen-Aenderung
 --------------------------------------------------------------------*/

void SizeNotify(ViewShell* pVwSh, const Size &rSize)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh)
    {
        if (pSfxVwSh->ISA(SwView))
            ((SwView *)pSfxVwSh)->DocSzChgd(rSize);
        else if (pSfxVwSh->ISA(SwPagePreView))
            ((SwPagePreView *)pSfxVwSh)->DocSzChgd( rSize );
    }
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Seitenzahl-Update
 --------------------------------------------------------------------*/

void PageNumNotify( ViewShell* pVwSh, USHORT nPhyNum, USHORT nVirtNum,
                                                    const String& rPgStr)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if ( pSfxVwSh && pSfxVwSh->ISA(SwView) &&
         ((SwView*)pSfxVwSh)->GetCurShell() )
            ((SwView *)pSfxVwSh)->UpdatePageNums(nPhyNum, nVirtNum, rPgStr);
}

/******************************************************************************
 *  Methode     :   void FrameNotify( DocMDIBase *pWin, FlyMode eMode )
 *  Beschreibung:
 *  Erstellt    :   OK 08.02.94 13:49
 *  Aenderung   :
 ******************************************************************************/

void FrameNotify( ViewShell* pVwSh, FlyMode eMode )
{
    if ( pVwSh->ISA(SwCrsrShell) )
        SwBaseShell::SetFrmMode( eMode, (SwWrtShell*)pVwSh );
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Seitenzahl-Update
 --------------------------------------------------------------------*/
BOOL SwEditWin::RulerColumnDrag( SwView& rView , const MouseEvent& rMEvt, BOOL bVerticalMode)
{
    SvxRuler& rRuler = bVerticalMode ?  rView.GetVLineal() : rView.GetHLineal();
    return (!rRuler.StartDocDrag( rMEvt, RULER_TYPE_BORDER ) &&
            !rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN1) &&
            !rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN2));
}

Dialog* GetSearchDialog()
{
    return SwView::GetSearchDialog();
}

void JavaScriptScrollMDI( SfxFrame* pFrame, INT32 nX, INT32 nY )
{
    SfxViewShell *pSfxVwSh = pFrame->GetCurrentViewFrame()->GetViewShell();
    if( pSfxVwSh && pSfxVwSh->ISA( SwView ))
    {
        SwView* pView = (SwView *)pSfxVwSh;

        Size aSz( nX, nY );
        aSz = pView->GetEditWin().PixelToLogic( aSz );

        Point aTopLeft( aSz.Width(), aSz.Height() );
        if( aTopLeft.X() < DOCUMENTBORDER ) aTopLeft.X() = DOCUMENTBORDER;
        if( aTopLeft.Y() < DOCUMENTBORDER ) aTopLeft.Y() = DOCUMENTBORDER;

        const Size& rVisSize = pView->GetVisArea().GetSize();
        Size aDocSize( pView->GetDocSz() );
        aDocSize.Width() += DOCUMENTBORDER;
        aDocSize.Height() += DOCUMENTBORDER;

        if( aTopLeft.X() + rVisSize.Width() > aDocSize.Width() )
            aTopLeft.X() = rVisSize.Width() > aDocSize.Width()
                                ? DOCUMENTBORDER
                                : aDocSize.Width() - rVisSize.Width();

        if( aTopLeft.Y() + rVisSize.Height() > aDocSize.Height() )
            aTopLeft.Y() = rVisSize.Height() > aDocSize.Height()
                                ? DOCUMENTBORDER
                                : aDocSize.Height() - rVisSize.Height();

        pView->SetVisArea( aTopLeft );
    }
}

USHORT GetTblChgDefaultMode()
{
    SwModuleOptions* pOpt = SW_MOD()->GetModuleConfig();
    return pOpt ? pOpt->GetTblMode() : TBLVAR_CHGABS;
}

void RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA( SwPagePreView ))
        ((SwPagePreView *)pSfxVwSh)->RepaintCoreRect( rRect );
}

BOOL JumpToSwMark( ViewShell* pVwSh, const String& rMark )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if( pSfxVwSh && pSfxVwSh->ISA( SwView ) )
        return ((SwView *)pSfxVwSh)->JumpToSwMark( rMark );
    return FALSE;
}

void SwEditWin::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );

    SwWrtShell* pSh = GetView().GetWrtShellPtr();
    //#99906#   DataChanged() is sometimes called prior to creating
    //          the SwWrtShell
    if(!pSh)
        return;
    BOOL bViewWasLocked = pSh->IsViewLocked(), bUnlockPaint = FALSE;
    pSh->LockView( TRUE );
    switch( rDCEvt.GetType() )
    {
    case DATACHANGED_SETTINGS:
        // ScrollBars neu anordnen bzw. Resize ausloesen, da sich
        // ScrollBar-Groesse geaendert haben kann. Dazu muss dann im
        // Resize-Handler aber auch die Groesse der ScrollBars aus
        // den Settings abgefragt werden.
        if( rDCEvt.GetFlags() & SETTINGS_STYLE )
        {
            pSh->LockPaint();
            bUnlockPaint = TRUE;
            GetView().InvalidateBorder();               //Scrollbarbreiten
        }
        break;

    case DATACHANGED_PRINTER:
    case DATACHANGED_DISPLAY:
    case DATACHANGED_FONTS:
    case DATACHANGED_FONTSUBSTITUTION:
        pSh->LockPaint();
        bUnlockPaint = TRUE;
        GetView().GetDocShell()->UpdateFontList();  //z.B. Druckerwechsel
        break;
    }
    pSh->LockView( bViewWasLocked );
    if( bUnlockPaint )
        pSh->UnlockPaint();
}

<commit_msg>INTEGRATION: CWS os8 (1.5.146); FILE MERGED 2003/04/03 07:14:01 os 1.5.146.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
 *
 *  $RCSfile: edtwin3.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:23:31 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <hintids.hxx>
#include "uiparam.hxx"
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif

#ifndef _VIEWOPT_HXX //autogen
#include <viewopt.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "pview.hxx"
#include "mdiexp.hxx"
#include "edtwin.hxx"
#include "swmodule.hxx"
#include "modcfg.hxx"
#include "swtable.hxx"
#include "docsh.hxx"
#include "pagedesc.hxx"     // Aktuelles Seitenformat
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_FRMDIRITEM_HXX
#include <svx/frmdiritem.hxx>
#endif

/*--------------------------------------------------------------------
    Beschreibung:   Core-Notify
 --------------------------------------------------------------------*/

void ScrollMDI( ViewShell* pVwSh, const SwRect &rRect,
                USHORT nRangeX, USHORT nRangeY)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA(SwView))
        ((SwView *)pSfxVwSh)->Scroll( rRect.SVRect(), nRangeX, nRangeY );
}

/*--------------------------------------------------------------------
    Beschreibung:   Docmdi - verschiebbar
 --------------------------------------------------------------------*/

BOOL IsScrollMDI( ViewShell* pVwSh, const SwRect &rRect )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA(SwView))
        return (((SwView *)pSfxVwSh)->IsScroll(rRect.SVRect()));
    return FALSE;
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Groessen-Aenderung
 --------------------------------------------------------------------*/

void SizeNotify(ViewShell* pVwSh, const Size &rSize)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh)
    {
        if (pSfxVwSh->ISA(SwView))
            ((SwView *)pSfxVwSh)->DocSzChgd(rSize);
        else if (pSfxVwSh->ISA(SwPagePreView))
            ((SwPagePreView *)pSfxVwSh)->DocSzChgd( rSize );
    }
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Seitenzahl-Update
 --------------------------------------------------------------------*/

void PageNumNotify( ViewShell* pVwSh, USHORT nPhyNum, USHORT nVirtNum,
                                                    const String& rPgStr)
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if ( pSfxVwSh && pSfxVwSh->ISA(SwView) &&
         ((SwView*)pSfxVwSh)->GetCurShell() )
            ((SwView *)pSfxVwSh)->UpdatePageNums(nPhyNum, nVirtNum, rPgStr);
}

/******************************************************************************
 *  Methode     :   void FrameNotify( DocMDIBase *pWin, FlyMode eMode )
 *  Beschreibung:
 *  Erstellt    :   OK 08.02.94 13:49
 *  Aenderung   :
 ******************************************************************************/

void FrameNotify( ViewShell* pVwSh, FlyMode eMode )
{
    if ( pVwSh->ISA(SwCrsrShell) )
        SwBaseShell::SetFrmMode( eMode, (SwWrtShell*)pVwSh );
}

/*--------------------------------------------------------------------
    Beschreibung:   Notify fuer Seitenzahl-Update
 --------------------------------------------------------------------*/
BOOL SwEditWin::RulerColumnDrag( SwView& rView , const MouseEvent& rMEvt, BOOL bVerticalMode)
{
    SvxRuler& rRuler = bVerticalMode ?  rView.GetVLineal() : rView.GetHLineal();
    return (!rRuler.StartDocDrag( rMEvt, RULER_TYPE_BORDER ) &&
            !rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN1) &&
            !rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN2));
}

Dialog* GetSearchDialog()
{
    return SwView::GetSearchDialog();
}

void JavaScriptScrollMDI( SfxFrame* pFrame, INT32 nX, INT32 nY )
{
    SfxViewShell *pSfxVwSh = pFrame->GetCurrentViewFrame()->GetViewShell();
    if( pSfxVwSh && pSfxVwSh->ISA( SwView ))
    {
        SwView* pView = (SwView *)pSfxVwSh;

        Size aSz( nX, nY );
        aSz = pView->GetEditWin().PixelToLogic( aSz );

        Point aTopLeft( aSz.Width(), aSz.Height() );
        if( aTopLeft.X() < DOCUMENTBORDER ) aTopLeft.X() = DOCUMENTBORDER;
        if( aTopLeft.Y() < DOCUMENTBORDER ) aTopLeft.Y() = DOCUMENTBORDER;

        const Size& rVisSize = pView->GetVisArea().GetSize();
        Size aDocSize( pView->GetDocSz() );
        aDocSize.Width() += DOCUMENTBORDER;
        aDocSize.Height() += DOCUMENTBORDER;

        if( aTopLeft.X() + rVisSize.Width() > aDocSize.Width() )
            aTopLeft.X() = rVisSize.Width() > aDocSize.Width()
                                ? DOCUMENTBORDER
                                : aDocSize.Width() - rVisSize.Width();

        if( aTopLeft.Y() + rVisSize.Height() > aDocSize.Height() )
            aTopLeft.Y() = rVisSize.Height() > aDocSize.Height()
                                ? DOCUMENTBORDER
                                : aDocSize.Height() - rVisSize.Height();

        pView->SetVisArea( aTopLeft );
    }
}

USHORT GetTblChgDefaultMode()
{
    SwModuleOptions* pOpt = SW_MOD()->GetModuleConfig();
    return pOpt ? pOpt->GetTblMode() : TBLVAR_CHGABS;
}

void RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if (pSfxVwSh && pSfxVwSh->ISA( SwPagePreView ))
        ((SwPagePreView *)pSfxVwSh)->RepaintCoreRect( rRect );
}

BOOL JumpToSwMark( ViewShell* pVwSh, const String& rMark )
{
    SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
    if( pSfxVwSh && pSfxVwSh->ISA( SwView ) )
        return ((SwView *)pSfxVwSh)->JumpToSwMark( rMark );
    return FALSE;
}

void SwEditWin::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );

    SwWrtShell* pSh = GetView().GetWrtShellPtr();
    //#99906#   DataChanged() is sometimes called prior to creating
    //          the SwWrtShell
    if(!pSh)
        return;
    BOOL bViewWasLocked = pSh->IsViewLocked(), bUnlockPaint = FALSE;
    pSh->LockView( TRUE );
    switch( rDCEvt.GetType() )
    {
    case DATACHANGED_SETTINGS:
        // ScrollBars neu anordnen bzw. Resize ausloesen, da sich
        // ScrollBar-Groesse geaendert haben kann. Dazu muss dann im
        // Resize-Handler aber auch die Groesse der ScrollBars aus
        // den Settings abgefragt werden.
        if( rDCEvt.GetFlags() & SETTINGS_STYLE )
        {
            pSh->LockPaint();
            bUnlockPaint = TRUE;
            GetView().InvalidateBorder();               //Scrollbarbreiten
        }
        break;

    case DATACHANGED_PRINTER:
    case DATACHANGED_DISPLAY:
    case DATACHANGED_FONTS:
    case DATACHANGED_FONTSUBSTITUTION:
        pSh->LockPaint();
        bUnlockPaint = TRUE;
        GetView().GetDocShell()->UpdateFontList();  //z.B. Druckerwechsel
        break;
    }
    pSh->LockView( bViewWasLocked );
    if( bUnlockPaint )
        pSh->UnlockPaint();
}

<|endoftext|>


<commit_before>/******************************************************************************\
* File:          support.cpp
* Purpose:       Implementation of support classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2008 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/stockitem.h> // for wxGetStockLabel
#ifndef __WXMSW__
#include "appl.xpm"
#endif
#include "support.h"
#include "defs.h"

Frame::Frame(const wxString& project_wildcard)
  : ftFrame(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppName(), //title
      NUMBER_RECENT_FILES, //maxFiles
      4,    // maxProjects
      project_wildcard)
{
  SetIcon(wxICON(appl));

  std::vector<exPane> panes;
  panes.push_back(exPane("PaneText", -3));
  panes.push_back(exPane("PaneFileType", 50, _("File Type")));
  panes.push_back(exPane("PaneLines", 100, _("Lines")));

  // Add the lexer pane only if we have lexers.
  if (!exApp::GetLexers()->Get().empty())
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif
    panes.push_back(exPane("PaneLexer", lexer_size, _("Lexer")));
  }

  panes.push_back(exPane("PaneItems", 65, _("Items")));
  SetupStatusBar(panes);

  wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
  SetMenuBar(menubar);

  exMenu *menuFile = new exMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
  menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->Append(ID_ALL_STC_PRINT, exEllipsed(_("Print A&ll")), wxEmptyString, wxITEM_NORMAL, NULL, wxART_PRINT);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  exMenu *menuEdit = new exMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND);
  menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
  menuEdit->Append(wxID_REPLACE);
  menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, exEllipsed(_("Find &In Files")));
  menuEdit->AppendSeparator();
  menuEdit->AppendTools(ID_STC_TOOL_MENU);
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_GOTO, exEllipsed(_("&Goto"), "Ctrl+G"));
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_CONTROL_CHAR, exEllipsed(_("&Control Char"), "Ctrl+H"));
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
  menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));

  exMenu *menuView = new exMenu;
  menuView->Append(ID_VIEW_STATUSBAR, _("&Statusbar"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_TOOLBAR, _("&Toolbar"), wxEmptyString, wxITEM_CHECK);
  menuView->AppendSeparator();
  menuView->Append(ID_VIEW_FILES, _("&Files"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_PROJECTS, _("&Projects"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_DIRCTRL, _("&Explorer"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_OUTPUT, _("&Output"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_ASCII_TABLE, _("&Ascii Table"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_HISTORY, _("&History"), wxEmptyString, wxITEM_CHECK);
#ifdef __WXMSW__
  ///  \todo Listctrl under GTK and X11 behave differently, items become non-existing by the OnIdle.
  wxMenu *menuListView = new wxMenu;
  menuListView->Append(wxID_VIEW_LIST, _("&List"), wxEmptyString, wxITEM_CHECK);
  menuListView->Append(wxID_VIEW_DETAILS, _("&Detail"), wxEmptyString, wxITEM_CHECK);
  menuListView->Append(wxID_VIEW_SMALLICONS, _("&Small Icon"), wxEmptyString, wxITEM_CHECK);
  menuView->AppendSeparator();
  menuView->Append(ID_VIEW_MENU, _("&Lists"), wxEmptyString, wxITEM_NORMAL, menuListView);
#endif

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, exEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(ID_PROCESS_RUN, _("&Run"));
  menuProcess->Append(wxID_STOP);

  exMenu *menuProject = new exMenu();
  menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxITEM_NORMAL, NULL, wxART_NEW);
  menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
  menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
  menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->Append(ID_SORT_SYNC, _("&Auto Sort"), wxEmptyString, wxITEM_CHECK);

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(ID_OPTION_COMPARATOR, exEllipsed(_("Set &Comparator")));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_LIST_COLOUR, exEllipsed(_("Set &List Colour")));
  menuOptions->Append(ID_OPTION_LIST_FONT, exEllipsed(_("Set &List Font")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->Append(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"), wxEmptyString, wxITEM_CHECK);
  menuListSort->Append(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"), wxEmptyString, wxITEM_CHECK);
  menuListSort->Append(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"), wxEmptyString, wxITEM_CHECK);
  menuOptions->Append(ID_OPTION_LIST_SORT_MENU, _("Set &List Sort Method"), menuListSort);
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, exEllipsed(_("Set &Editor Options")));
  wxMenu *menuHelp = new wxMenu();
  // Both wxART_HELP_BOOK, and wxART_HELP_PAGE do not fit nicely on menu item.
  menuHelp->Append(wxID_HELP_CONTENTS, _("&Contents"));
  menuHelp->AppendSeparator();
  menuHelp->Append(wxID_ABOUT);
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuEdit, _("&Edit"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  m_ToolBar = new exToolBar(this,
    wxID_ANY,
    wxDefaultPosition,
    wxDefaultSize,
    wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);

  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);
  m_ToolBar->AddTool(wxID_PRINT);
  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXMSW__
  const wxSize tbz(150, 20);
#else
  const wxSize tbz(150, -1);
#endif
  m_ToolBar->AddControl(new ftFind(m_ToolBar, this, ID_FIND_TEXT, wxDefaultPosition, tbz));

  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(
    ID_PROJECT_OPEN,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Open project..."));
  m_ToolBar->AddTool(
    ID_PROJECT_SAVE,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Save project"));
#ifdef __WXMSW__
  ///  \todo See comment above.
  m_ToolBar->AddCheckTool(
    wxID_VIEW_LIST,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in list mode"));
  m_ToolBar->AddCheckTool(
    wxID_VIEW_DETAILS, wxEmptyString,
    wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in detail mode"));

#endif
#if wxUSE_CHECKBOX
  m_ToolBar->AddSeparator();
#ifndef __WXMSW__
  wxSize size(55, 25);
#else
  wxSize size = wxDefaultSize;
#endif

  m_ToolBar->AddControl(
    m_HexModeCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_EDIT_HEX_MODE,
      "Hex",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_ToolBar->AddControl(
    m_SyncCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_SYNC_MODE,
      "Sync",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
  m_HexModeCheckBox->SetValue(exApp::GetConfigBool("HexMode"));
  m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif // wxUSE_CHECKBOX

  m_ToolBar->Realize();
}

bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
  if (ftListView::ProcessIsRunning())
    return false;
  else if (id == NOTEBOOK_EDITORS)
    return ((ftSTC*)page)->Continue();
  else if (id == NOTEBOOK_PROJECTS)
    return ((ftListView*)page)->Continue();
  else
    return ftFrame::AllowClose(id, page);
}

void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
  if (id == NOTEBOOK_EDITORS)
  {
    ((ftSTC*)page)->PropertiesMessage();
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    SetTitle(wxEmptyString, ((ftListView*)page)->GetFileName().GetName());
    exStatusText(((ftListView*)page)->GetFileName());
  }
}
<commit_msg>commit depends on local rcs<commit_after>/******************************************************************************\
* File:          support.cpp
* Purpose:       Implementation of support classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2008 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/stockitem.h> // for wxGetStockLabel
#ifndef __WXMSW__
#include "appl.xpm"
#endif
#include "support.h"
#include "defs.h"

Frame::Frame(const wxString& project_wildcard)
  : ftFrame(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppName(), //title
      NUMBER_RECENT_FILES, //maxFiles
      4,    // maxProjects
      project_wildcard)
{
  SetIcon(wxICON(appl));

  std::vector<exPane> panes;
  panes.push_back(exPane("PaneText", -3));
  panes.push_back(exPane("PaneFileType", 50, _("File Type")));
  panes.push_back(exPane("PaneLines", 100, _("Lines")));

  // Add the lexer pane only if we have lexers.
  if (!exApp::GetLexers()->Get().empty())
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif
    panes.push_back(exPane("PaneLexer", lexer_size, _("Lexer")));
  }

  panes.push_back(exPane("PaneItems", 65, _("Items")));
  SetupStatusBar(panes);

  wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
  SetMenuBar(menubar);

  exMenu *menuFile = new exMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
  menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->Append(ID_ALL_STC_PRINT, exEllipsed(_("Print A&ll")), wxEmptyString, wxITEM_NORMAL, NULL, wxART_PRINT);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  exMenu *menuEdit = new exMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND);
  menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
  menuEdit->Append(wxID_REPLACE);
  menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, exEllipsed(_("Find &In Files")));
  menuEdit->AppendSeparator();
  menuEdit->AppendTools(ID_STC_TOOL_MENU);
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_GOTO, exEllipsed(_("&Goto"), "Ctrl+G"));
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_CONTROL_CHAR, exEllipsed(_("&Control Char"), "Ctrl+H"));
  menuEdit->AppendSeparator();
#ifndef LOCAL_RCS
  menuEdit->Append(ID_COMMIT, _(C&ommit"));
  menuEdit->AppendSeparator();
#endif
  menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
  menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));

  exMenu *menuView = new exMenu;
  menuView->Append(ID_VIEW_STATUSBAR, _("&Statusbar"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_TOOLBAR, _("&Toolbar"), wxEmptyString, wxITEM_CHECK);
  menuView->AppendSeparator();
  menuView->Append(ID_VIEW_FILES, _("&Files"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_PROJECTS, _("&Projects"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_DIRCTRL, _("&Explorer"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_OUTPUT, _("&Output"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_ASCII_TABLE, _("&Ascii Table"), wxEmptyString, wxITEM_CHECK);
  menuView->Append(ID_VIEW_HISTORY, _("&History"), wxEmptyString, wxITEM_CHECK);
#ifdef __WXMSW__
  ///  \todo Listctrl under GTK and X11 behave differently, items become non-existing by the OnIdle.
  wxMenu *menuListView = new wxMenu;
  menuListView->Append(wxID_VIEW_LIST, _("&List"), wxEmptyString, wxITEM_CHECK);
  menuListView->Append(wxID_VIEW_DETAILS, _("&Detail"), wxEmptyString, wxITEM_CHECK);
  menuListView->Append(wxID_VIEW_SMALLICONS, _("&Small Icon"), wxEmptyString, wxITEM_CHECK);
  menuView->AppendSeparator();
  menuView->Append(ID_VIEW_MENU, _("&Lists"), wxEmptyString, wxITEM_NORMAL, menuListView);
#endif

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, exEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(ID_PROCESS_RUN, _("&Run"));
  menuProcess->Append(wxID_STOP);

  exMenu *menuProject = new exMenu();
  menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxITEM_NORMAL, NULL, wxART_NEW);
  menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
  menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
  menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->Append(ID_SORT_SYNC, _("&Auto Sort"), wxEmptyString, wxITEM_CHECK);

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(ID_OPTION_COMPARATOR, exEllipsed(_("Set &Comparator")));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_LIST_COLOUR, exEllipsed(_("Set &List Colour")));
  menuOptions->Append(ID_OPTION_LIST_FONT, exEllipsed(_("Set &List Font")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->Append(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"), wxEmptyString, wxITEM_CHECK);
  menuListSort->Append(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"), wxEmptyString, wxITEM_CHECK);
  menuListSort->Append(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"), wxEmptyString, wxITEM_CHECK);
  menuOptions->Append(ID_OPTION_LIST_SORT_MENU, _("Set &List Sort Method"), menuListSort);
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, exEllipsed(_("Set &Editor Options")));
  wxMenu *menuHelp = new wxMenu();
  // Both wxART_HELP_BOOK, and wxART_HELP_PAGE do not fit nicely on menu item.
  menuHelp->Append(wxID_HELP_CONTENTS, _("&Contents"));
  menuHelp->AppendSeparator();
  menuHelp->Append(wxID_ABOUT);
  menubar->Append(menuFile, _("&File"));
  menubar->Append(menuEdit, _("&Edit"));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  m_ToolBar = new exToolBar(this,
    wxID_ANY,
    wxDefaultPosition,
    wxDefaultSize,
    wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);

  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);
  m_ToolBar->AddTool(wxID_PRINT);
  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXMSW__
  const wxSize tbz(150, 20);
#else
  const wxSize tbz(150, -1);
#endif
  m_ToolBar->AddControl(new ftFind(m_ToolBar, this, ID_FIND_TEXT, wxDefaultPosition, tbz));

  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(
    ID_PROJECT_OPEN,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Open project..."));
  m_ToolBar->AddTool(
    ID_PROJECT_SAVE,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Save project"));
#ifdef __WXMSW__
  ///  \todo See comment above.
  m_ToolBar->AddCheckTool(
    wxID_VIEW_LIST,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in list mode"));
  m_ToolBar->AddCheckTool(
    wxID_VIEW_DETAILS, wxEmptyString,
    wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in detail mode"));

#endif
#if wxUSE_CHECKBOX
  m_ToolBar->AddSeparator();
#ifndef __WXMSW__
  wxSize size(55, 25);
#else
  wxSize size = wxDefaultSize;
#endif

  m_ToolBar->AddControl(
    m_HexModeCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_EDIT_HEX_MODE,
      "Hex",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_ToolBar->AddControl(
    m_SyncCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_SYNC_MODE,
      "Sync",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
  m_HexModeCheckBox->SetValue(exApp::GetConfigBool("HexMode"));
  m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif // wxUSE_CHECKBOX

  m_ToolBar->Realize();
}

bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
  if (ftListView::ProcessIsRunning())
    return false;
  else if (id == NOTEBOOK_EDITORS)
    return ((ftSTC*)page)->Continue();
  else if (id == NOTEBOOK_PROJECTS)
    return ((ftListView*)page)->Continue();
  else
    return ftFrame::AllowClose(id, page);
}

void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
  if (id == NOTEBOOK_EDITORS)
  {
    ((ftSTC*)page)->PropertiesMessage();
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    SetTitle(wxEmptyString, ((ftListView*)page)->GetFileName().GetName());
    exStatusText(((ftListView*)page)->GetFileName());
  }
}
<|endoftext|>


<commit_before>// Includes
#include "NDataManager.h"

namespace NDataManager
{
	// Default initialize all data
	TNavData			m_navData = {};
	TEnvironmentData	m_environmentData = {};
	TCapeData			m_capeData = {};
	TThrusterData		m_thrusterData = {};
	TCameraMountData	m_cameraMountData = {};
	TControllerData		m_controllerData = {};

	CTimer				m_timer_1hz;
	CTimer				m_timer_10hz;

	uint32_t			m_loopsPerSec = 0;

	// Called during Setup() to initialize any DataManager members to specific values
	void Initialize()
	{
		Serial.println( "Systems.DataManager.Status:INIT;" );

		Serial.println( "Systems.DataManager.Status:READY;" );
	}

	void OutputNavData()
	{
		// Print Nav Data on the serial line
		Serial.print( F( "hdgd:" ) );
		Serial.print( m_navData.HDGD );
		Serial.print( ';' );
		Serial.print( F( "deap:" ) );
		Serial.print( m_navData.DEEP );
		Serial.print( ';' );
		Serial.print( F( "pitc:" ) );
		Serial.print( m_navData.PITC );
		Serial.print( ';' );
		Serial.print( F( "roll:" ) );
		Serial.print( m_navData.ROLL );
		Serial.print( ';' );
		Serial.print( F( "yaw:" ) );
		Serial.print( m_navData.YAW );
		Serial.print( ';' );
		Serial.print( F( "fthr:" ) );
		Serial.print( m_navData.FTHR );
		Serial.println( ';' );
	}

	void OutputSharedData()
	{
		// Print all other shared data on the serial line

		// Thruster Data
		Serial.print( F( "motorAttached:" ) );
		Serial.print( m_thrusterData.MATC );
		Serial.println( ';' );

		// Camera Mount Data
		Serial.print( F( "servo:" ) );
		Serial.print( m_cameraMountData.CMNT );
		Serial.print( ';' );
		Serial.print( F( "starg:" ) );
		Serial.print( m_cameraMountData.CMTG );
		Serial.println( ';' );

		// Cape Data
		Serial.print( F( "fmem:" ) );
		Serial.print( m_capeData.FMEM );
		Serial.print( ';' );
		Serial.print( F( "vout:" ) );
		Serial.print( m_capeData.VOUT );
		Serial.print( ';' );
		Serial.print( F( "iout:" ) );
		Serial.print( m_capeData.IOUT );
		Serial.print( ';' );
		Serial.print( F( "btti:" ) );
		Serial.print( m_capeData.BTTI );
		Serial.print( ';' );
		Serial.print( F( "atmp:" ) );
		Serial.print( m_capeData.ATMP );
		Serial.print( ';' );
		Serial.print( F( "ver:" ) );
		Serial.print( F( "CUSTOM_BUILD" ) );
		Serial.print( ';' );
		Serial.print( F( "cmpd:" ) );
		Serial.print( F( __DATE__ ) );
		Serial.print( F( ", " ) );
		Serial.print( F( __TIME__ ) );
		Serial.print( F( ", " ) );
		Serial.print( F( __VERSION__ ) );
		Serial.print( ';' );
		Serial.print( F( "time:" ) );
		Serial.print( m_capeData.UTIM );
		Serial.println( ';' );

		// Environment Data
		Serial.print( F( "pres:" ) );
		Serial.print( m_environmentData.PRES );
		Serial.print( ';' );
		Serial.print( F( "temp:" ) );
		Serial.print( m_environmentData.TEMP );
		Serial.println( ';' );

		// Module loop timers in milliseconds
		// Serial.print( F( "modtime:" ) );

		// for( int i = 0; i < NModuleManager::m_moduleCount; ++i )
		// {
		// 	Serial.print( NModuleManager::m_pModules[ i ]->m_name );
		// 	Serial.print( '|' );
		// 	Serial.print( NModuleManager::m_pModules[ i ]->m_executionTime );
		// 	Serial.print( '|' );
		// }

		// Serial.println( ';' );

		//
	}

	void HandleOutputLoops()
	{
		++m_loopsPerSec;

		// 1Hz update loop
		if( m_timer_1hz.HasElapsed( 1000 ) )
		{
			// Send shared data to beaglebone
			OutputSharedData();

			// Loops per sec
			Serial.print( F( "alps:" ) );
			Serial.print( m_loopsPerSec );
			Serial.println( ';' );

			// Reset loop counter
			m_loopsPerSec = 0;
		}

		// 10Hz Update loop
		if( m_timer_10hz.HasElapsed( 100 ) )
		{
			// Send nav data to beaglebone
			OutputNavData();
		}
	}
}<commit_msg>Fixed depth navdata output label<commit_after>// Includes
#include "NDataManager.h"

namespace NDataManager
{
	// Default initialize all data
	TNavData			m_navData = {};
	TEnvironmentData	m_environmentData = {};
	TCapeData			m_capeData = {};
	TThrusterData		m_thrusterData = {};
	TCameraMountData	m_cameraMountData = {};
	TControllerData		m_controllerData = {};

	CTimer				m_timer_1hz;
	CTimer				m_timer_10hz;

	uint32_t			m_loopsPerSec = 0;

	// Called during Setup() to initialize any DataManager members to specific values
	void Initialize()
	{
		Serial.println( "Systems.DataManager.Status:INIT;" );

		Serial.println( "Systems.DataManager.Status:READY;" );
	}

	void OutputNavData()
	{
		// Print Nav Data on the serial line
		Serial.print( F( "hdgd:" ) );
		Serial.print( m_navData.HDGD );
		Serial.print( ';' );
		Serial.print( F( "deep:" ) );
		Serial.print( m_navData.DEEP );
		Serial.print( ';' );
		Serial.print( F( "pitc:" ) );
		Serial.print( m_navData.PITC );
		Serial.print( ';' );
		Serial.print( F( "roll:" ) );
		Serial.print( m_navData.ROLL );
		Serial.print( ';' );
		Serial.print( F( "yaw:" ) );
		Serial.print( m_navData.YAW );
		Serial.print( ';' );
		Serial.print( F( "fthr:" ) );
		Serial.print( m_navData.FTHR );
		Serial.println( ';' );
	}

	void OutputSharedData()
	{
		// Print all other shared data on the serial line

		// Thruster Data
		Serial.print( F( "motorAttached:" ) );
		Serial.print( m_thrusterData.MATC );
		Serial.println( ';' );

		// Camera Mount Data
		Serial.print( F( "servo:" ) );
		Serial.print( m_cameraMountData.CMNT );
		Serial.print( ';' );
		Serial.print( F( "starg:" ) );
		Serial.print( m_cameraMountData.CMTG );
		Serial.println( ';' );

		// Cape Data
		Serial.print( F( "fmem:" ) );
		Serial.print( m_capeData.FMEM );
		Serial.print( ';' );
		Serial.print( F( "vout:" ) );
		Serial.print( m_capeData.VOUT );
		Serial.print( ';' );
		Serial.print( F( "iout:" ) );
		Serial.print( m_capeData.IOUT );
		Serial.print( ';' );
		Serial.print( F( "btti:" ) );
		Serial.print( m_capeData.BTTI );
		Serial.print( ';' );
		Serial.print( F( "atmp:" ) );
		Serial.print( m_capeData.ATMP );
		Serial.print( ';' );
		Serial.print( F( "ver:" ) );
		Serial.print( F( "CUSTOM_BUILD" ) );
		Serial.print( ';' );
		Serial.print( F( "cmpd:" ) );
		Serial.print( F( __DATE__ ) );
		Serial.print( F( ", " ) );
		Serial.print( F( __TIME__ ) );
		Serial.print( F( ", " ) );
		Serial.print( F( __VERSION__ ) );
		Serial.print( ';' );
		Serial.print( F( "time:" ) );
		Serial.print( m_capeData.UTIM );
		Serial.println( ';' );

		// Environment Data
		Serial.print( F( "pres:" ) );
		Serial.print( m_environmentData.PRES );
		Serial.print( ';' );
		Serial.print( F( "temp:" ) );
		Serial.print( m_environmentData.TEMP );
		Serial.println( ';' );

		// Module loop timers in milliseconds
		// Serial.print( F( "modtime:" ) );

		// for( int i = 0; i < NModuleManager::m_moduleCount; ++i )
		// {
		// 	Serial.print( NModuleManager::m_pModules[ i ]->m_name );
		// 	Serial.print( '|' );
		// 	Serial.print( NModuleManager::m_pModules[ i ]->m_executionTime );
		// 	Serial.print( '|' );
		// }

		// Serial.println( ';' );

		//
	}

	void HandleOutputLoops()
	{
		++m_loopsPerSec;

		// 1Hz update loop
		if( m_timer_1hz.HasElapsed( 1000 ) )
		{
			// Send shared data to beaglebone
			OutputSharedData();

			// Loops per sec
			Serial.print( F( "alps:" ) );
			Serial.print( m_loopsPerSec );
			Serial.println( ';' );

			// Reset loop counter
			m_loopsPerSec = 0;
		}

		// 10Hz Update loop
		if( m_timer_10hz.HasElapsed( 100 ) )
		{
			// Send nav data to beaglebone
			OutputNavData();
		}
	}
}<|endoftext|>


<commit_before>#include <sm/logging/LoggingGlobals.hpp>
#include <sm/logging/StdOutLogger.hpp>

namespace sm {
    namespace logging {

        LoggingGlobals g_logging_globals;

        LoggingGlobals::LoggingGlobals()
        {
            _logger.reset( new StdOutLogger() );
            _level = levels::Info;
            enableNamedStream(SMCONSOLE_DEFAULT_NAME);
            _globalCharBuffer.resize(4096);
        }

        LoggingGlobals::~LoggingGlobals()
        {

        }

        void LoggingGlobals::shutdown()
        {
            _shutting_down = true;
        }

        /**
         * \brief Registers a logging location with the system.
         *
         * This is used for the case where a logger's verbosity level changes, and we need to reset the enabled status of
         * all the logging statements.
         * @param loc The location to add
         */
        void LoggingGlobals::registerLogLocation(LogLocation* loc) {
            boost::mutex::scoped_lock lock(_locations_mutex);
            _log_locations.push_back(loc);
        }

        void LoggingGlobals::checkLogLocationEnabledNoLock(LogLocation* loc) {
            loc->_loggerEnabled = loc->_level >= _level && (loc->_streamName.size() == 0 || isNamedStreamEnabled(loc->_streamName));
        }

        void LoggingGlobals::initializeLogLocation(LogLocation* loc, const std::string& name, Level level){
            boost::mutex::scoped_lock lock(_locations_mutex);

            if (loc->_initialized)
            {
                return;
            }

            loc->_streamName = name;
            loc->_level = level;

            _log_locations.push_back(loc);

            checkLogLocationEnabledNoLock(loc);

            loc->_initialized = true;
        }

        void LoggingGlobals::setLogLocationLevel(LogLocation* loc, Level level)
        {
            boost::mutex::scoped_lock lock(_locations_mutex);
            loc->_level = level;
        }

        void LoggingGlobals::checkLogLocationEnabled(LogLocation* loc)
        {
            boost::mutex::scoped_lock lock(_locations_mutex);
            checkLogLocationEnabledNoLock(loc);
        }

        /**
         * \brief Tells the system that a logger's level has changed
         *
         * This must be called if a log4cxx::Logger's level has been changed in the middle of an application run.
         * Because of the way the static guard for enablement works, if a logger's level is changed and this
         * function is not called, only logging statements which are first hit *after* the change will be correct wrt
         * that logger.
         */
        void LoggingGlobals::notifyLoggerLevelsChanged()
        {
            boost::mutex::scoped_lock lock(_locations_mutex);

            V_LogLocation::iterator it = _log_locations.begin();
            V_LogLocation::iterator end = _log_locations.end();
            for ( ; it != end; ++it )
            {
                LogLocation* loc = *it;
                checkLogLocationEnabledNoLock(loc);
            }
        }

        bool LoggingGlobals::isNamedStreamEnabled( const std::string & name ){
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
            return it != _namedStreamsEnabled.end();

        }

        void LoggingGlobals::enableNamedStream( const std::string & name ) {
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            _namedStreamsEnabled.insert(name);
            notifyLoggerLevelsChanged();
        }

        void LoggingGlobals::disableNamedStream( const std::string & name ) {
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
            if(it != _namedStreamsEnabled.end())
            {
                _namedStreamsEnabled.erase(it);
                notifyLoggerLevelsChanged();
            }
        }

        void LoggingGlobals::vformatToBuffer(const char* fmt, va_list args)
        {
#ifdef _MSC_VER
            va_list arg_copy = args; // dangerous?
#else
            va_list arg_copy;
            va_copy(arg_copy, args);
#endif

#ifdef _MSC_VER
            size_t total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, args);
#else
            size_t total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, args);
#endif
            if (total >= _globalCharBuffer.size())
            {
                _globalCharBuffer.resize(total + 2);
#ifdef _MSC_VER
                total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, arg_copy);
#else
                total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, arg_copy);
#endif

            }
            va_end(arg_copy);

        }

        void LoggingGlobals::formatToBuffer(const char* fmt, ...)
        {
            va_list args;
            va_start(args, fmt);

            vformatToBuffer(fmt, args);

            va_end(args);
        }

        void LoggingGlobals::print(const char * streamName, Level level, const char* file, int line, const char* function, const char* fmt, ...)
        {
            if (_shutting_down)
                return;

            if (_printing_thread_id == boost::this_thread::get_id())
            {
                fprintf(stderr, "Warning: recursive print statement has occurred.  Throwing out recursive print.\n");
                return;
            }

            boost::mutex::scoped_lock lock(_print_mutex);

            _printing_thread_id = boost::this_thread::get_id();

            va_list args;
            va_start(args, fmt);

            vformatToBuffer(fmt, args);

            va_end(args);

            try
            {
                _logger->log( LoggingEvent( streamName, level, file, line, function, &_globalCharBuffer[0], _logger->currentTimeString() ) );
            }
            catch (std::exception& e)
            {
                fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
            }

            _printing_thread_id = boost::thread::id();
        }

        void LoggingGlobals::print(const char * streamName,  Level level,
                                   vectorstream & ss, const char* file, int line, const char* function)
        {
            if (_shutting_down)
                return;

            if (_printing_thread_id == boost::this_thread::get_id())
            {
                fprintf(stderr, "Warning: recursive print statement has occurred.  Throwing out recursive print.\n");
                return;
            }

            std::vector<char> str;
            ss.swap_vector(str);

            boost::mutex::scoped_lock lock(_print_mutex);

            _printing_thread_id = boost::this_thread::get_id();
            try
            {
                _logger->log( LoggingEvent( streamName, level, file, line, function, &str[0], _logger->currentTimeString() ) );
            }
            catch (std::exception& e)
            {
                fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
            }

            _printing_thread_id = boost::thread::id();
        }

        sm::logging::levels::Level LoggingGlobals::getLevel()
        {
            // \todo is this thread safe?
            return _level;
        }

        void LoggingGlobals::setLevel( sm::logging::levels::Level level )
        {
            // \todo is this thread safe?
            if(level != _level)
            {
                _level = level;
                notifyLoggerLevelsChanged();
            }
        }

        void LoggingGlobals::setLogger( boost::shared_ptr<Logger> logger )
        {
            if(logger.get())
            {
                _logger = logger;
            }
        }
        boost::shared_ptr<Logger> LoggingGlobals::getLogger()
        {
            return _logger;
        }

        sm::logging::levels::Level getLevel()
        {
            return g_logging_globals.getLevel();
        }
        void setLevel( sm::logging::levels::Level level )
        {
            g_logging_globals.setLevel(level);
        }
        void setLogger( boost::shared_ptr<Logger> logger )
        {
            g_logging_globals.setLogger(logger);
        }
        boost::shared_ptr<Logger> getLogger()
        {
            return g_logging_globals.getLogger();
        }
        bool isNamedStreamEnabled( const std::string & name )
        {
            return g_logging_globals.isNamedStreamEnabled( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }
        void enableNamedStream( const std::string & name )
        {
            g_logging_globals.enableNamedStream( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }
        void disableNamedStream( const std::string & name )
        {
            g_logging_globals.disableNamedStream(std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }

    } // namespace logging
} // namespace sm
<commit_msg>Hopefully got rid of the extra characters in the logging when using streams<commit_after>#include <sm/logging/LoggingGlobals.hpp>
#include <sm/logging/StdOutLogger.hpp>

namespace sm {
    namespace logging {

        LoggingGlobals g_logging_globals;

        LoggingGlobals::LoggingGlobals()
        {
            _logger.reset( new StdOutLogger() );
            _level = levels::Info;
            enableNamedStream(SMCONSOLE_DEFAULT_NAME);
            _globalCharBuffer.resize(4096);
        }

        LoggingGlobals::~LoggingGlobals()
        {

        }

        void LoggingGlobals::shutdown()
        {
            _shutting_down = true;
        }

        /**
         * \brief Registers a logging location with the system.
         *
         * This is used for the case where a logger's verbosity level changes, and we need to reset the enabled status of
         * all the logging statements.
         * @param loc The location to add
         */
        void LoggingGlobals::registerLogLocation(LogLocation* loc) {
            boost::mutex::scoped_lock lock(_locations_mutex);
            _log_locations.push_back(loc);
        }

        void LoggingGlobals::checkLogLocationEnabledNoLock(LogLocation* loc) {
            loc->_loggerEnabled = loc->_level >= _level && (loc->_streamName.size() == 0 || isNamedStreamEnabled(loc->_streamName));
        }

        void LoggingGlobals::initializeLogLocation(LogLocation* loc, const std::string& name, Level level){
            boost::mutex::scoped_lock lock(_locations_mutex);

            if (loc->_initialized)
            {
                return;
            }

            loc->_streamName = name;
            loc->_level = level;

            _log_locations.push_back(loc);

            checkLogLocationEnabledNoLock(loc);

            loc->_initialized = true;
        }

        void LoggingGlobals::setLogLocationLevel(LogLocation* loc, Level level)
        {
            boost::mutex::scoped_lock lock(_locations_mutex);
            loc->_level = level;
        }

        void LoggingGlobals::checkLogLocationEnabled(LogLocation* loc)
        {
            boost::mutex::scoped_lock lock(_locations_mutex);
            checkLogLocationEnabledNoLock(loc);
        }

        /**
         * \brief Tells the system that a logger's level has changed
         *
         * This must be called if a log4cxx::Logger's level has been changed in the middle of an application run.
         * Because of the way the static guard for enablement works, if a logger's level is changed and this
         * function is not called, only logging statements which are first hit *after* the change will be correct wrt
         * that logger.
         */
        void LoggingGlobals::notifyLoggerLevelsChanged()
        {
            boost::mutex::scoped_lock lock(_locations_mutex);

            V_LogLocation::iterator it = _log_locations.begin();
            V_LogLocation::iterator end = _log_locations.end();
            for ( ; it != end; ++it )
            {
                LogLocation* loc = *it;
                checkLogLocationEnabledNoLock(loc);
            }
        }

        bool LoggingGlobals::isNamedStreamEnabled( const std::string & name ){
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
            return it != _namedStreamsEnabled.end();

        }

        void LoggingGlobals::enableNamedStream( const std::string & name ) {
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            _namedStreamsEnabled.insert(name);
            notifyLoggerLevelsChanged();
        }

        void LoggingGlobals::disableNamedStream( const std::string & name ) {
            boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
            std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
            if(it != _namedStreamsEnabled.end())
            {
                _namedStreamsEnabled.erase(it);
                notifyLoggerLevelsChanged();
            }
        }

        void LoggingGlobals::vformatToBuffer(const char* fmt, va_list args)
        {
#ifdef _MSC_VER
            va_list arg_copy = args; // dangerous?
#else
            va_list arg_copy;
            va_copy(arg_copy, args);
#endif

#ifdef _MSC_VER
            size_t total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, args);
#else
            size_t total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, args);
#endif
            if (total >= _globalCharBuffer.size())
            {
                _globalCharBuffer.resize(total + 2);
#ifdef _MSC_VER
                total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, arg_copy);
#else
                total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, arg_copy);
#endif

            }
            va_end(arg_copy);

        }

        void LoggingGlobals::formatToBuffer(const char* fmt, ...)
        {
            va_list args;
            va_start(args, fmt);

            vformatToBuffer(fmt, args);

            va_end(args);
        }

        void LoggingGlobals::print(const char * streamName, Level level, const char* file, int line, const char* function, const char* fmt, ...)
        {
            if (_shutting_down)
                return;

            if (_printing_thread_id == boost::this_thread::get_id())
            {
                fprintf(stderr, "Warning: recursive print statement has occurred.  Throwing out recursive print.\n");
                return;
            }

            boost::mutex::scoped_lock lock(_print_mutex);

            _printing_thread_id = boost::this_thread::get_id();

            va_list args;
            va_start(args, fmt);

            vformatToBuffer(fmt, args);

            va_end(args);

            try
            {
                _logger->log( LoggingEvent( streamName, level, file, line, function, &_globalCharBuffer[0], _logger->currentTimeString() ) );
            }
            catch (std::exception& e)
            {
                fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
            }

            _printing_thread_id = boost::thread::id();
        }

        void LoggingGlobals::print(const char * streamName,  Level level,
                                   vectorstream & ss, const char* file, int line, const char* function)
        {
            if (_shutting_down)
                return;

            if (_printing_thread_id == boost::this_thread::get_id())
            {
                fprintf(stderr, "Warning: recursive print statement has occurred.  Throwing out recursive print.\n");
                return;
            }

            std::vector<char> str;
            ss.swap_vector(str);
            // make sure the string is null terminated.
            str.push_back('\0');

            boost::mutex::scoped_lock lock(_print_mutex);

            _printing_thread_id = boost::this_thread::get_id();
            try
            {
                _logger->log( LoggingEvent( streamName, level, file, line, function, &str[0], _logger->currentTimeString() ) );
            }
            catch (std::exception& e)
            {
                fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
            }

            _printing_thread_id = boost::thread::id();
        }

        sm::logging::levels::Level LoggingGlobals::getLevel()
        {
            // \todo is this thread safe?
            return _level;
        }

        void LoggingGlobals::setLevel( sm::logging::levels::Level level )
        {
            // \todo is this thread safe?
            if(level != _level)
            {
                _level = level;
                notifyLoggerLevelsChanged();
            }
        }

        void LoggingGlobals::setLogger( boost::shared_ptr<Logger> logger )
        {
            if(logger.get())
            {
                _logger = logger;
            }
        }
        boost::shared_ptr<Logger> LoggingGlobals::getLogger()
        {
            return _logger;
        }

        sm::logging::levels::Level getLevel()
        {
            return g_logging_globals.getLevel();
        }
        void setLevel( sm::logging::levels::Level level )
        {
            g_logging_globals.setLevel(level);
        }
        void setLogger( boost::shared_ptr<Logger> logger )
        {
            g_logging_globals.setLogger(logger);
        }
        boost::shared_ptr<Logger> getLogger()
        {
            return g_logging_globals.getLogger();
        }
        bool isNamedStreamEnabled( const std::string & name )
        {
            return g_logging_globals.isNamedStreamEnabled( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }
        void enableNamedStream( const std::string & name )
        {
            g_logging_globals.enableNamedStream( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }
        void disableNamedStream( const std::string & name )
        {
            g_logging_globals.disableNamedStream(std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
        }

    } // namespace logging
} // namespace sm
<|endoftext|>


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

#include "trikJavaScriptRunner.h"

#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>

#include "src/scriptEngineWorker.h"
#include "src/scriptExecutionControl.h"

#include <QsLog.h>

using namespace trikScriptRunner;

TrikJavaScriptRunner::TrikJavaScriptRunner(trikControl::BrickInterface &brick
										   , trikNetwork::MailboxInterface * const mailbox
										   )
	: mScriptController(new ScriptExecutionControl())
	, mScriptEngineWorker(new ScriptEngineWorker(brick, mailbox, *mScriptController))
	, mMaxScriptId(0)
	, mVariablesServer(new TrikVariablesServer())
{
	connect(&mWorkerThread, &QThread::finished, &mWorkerThread, &QThread::deleteLater);

	mScriptEngineWorker->moveToThread(&mWorkerThread);

	connect(&mWorkerThread, &QThread::finished, mScriptEngineWorker, &QThread::deleteLater);
	connect(mScriptEngineWorker, &ScriptEngineWorker::completed, this, &TrikJavaScriptRunner::completed);
	connect(mScriptEngineWorker, &ScriptEngineWorker::startedScript, this, &TrikJavaScriptRunner::onScriptStart);

	connect(mScriptController.data(), &ScriptExecutionControl::textInStdOut, this, &TrikJavaScriptRunner::textInStdOut);

	connect(mVariablesServer.data(), &TrikVariablesServer::getVariables, mScriptEngineWorker, &ScriptEngineWorker::getVariables);
	connect(mScriptEngineWorker, &ScriptEngineWorker::variablesReady
		, mVariablesServer.data(), &TrikVariablesServer::sendHTTPResponse);

	QLOG_INFO() << "Starting TrikJavaScriptRunner worker thread" << &mWorkerThread;

	mWorkerThread.start();
}

TrikJavaScriptRunner::~TrikJavaScriptRunner()
{
	mScriptEngineWorker->stopScript();
	QMetaObject::invokeMethod(&mWorkerThread, "quit");
	mWorkerThread.wait(1000);
}

void TrikJavaScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function)
{
	mScriptEngineWorker->registerUserFunction(name, function);
}

void TrikJavaScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step)
{
	mScriptEngineWorker->addCustomEngineInitStep(step);
}

void TrikJavaScriptRunner::brickBeep()
{
	QMetaObject::invokeMethod(mScriptEngineWorker, "brickBeep");
}

void TrikJavaScriptRunner::run(const QString &script, const QString &fileName)
{
	const int scriptId = mMaxScriptId++;
	QLOG_INFO() << "TrikJavaScriptRunner: new script" << scriptId << "from file" << fileName;
	mScriptEngineWorker->stopScript();

	if (!fileName.isEmpty()) {
		mScriptFileNames[scriptId] = fileName;
	}

	mScriptEngineWorker->run(script, (fileName.isEmpty() ? -1 : scriptId));
}

void TrikJavaScriptRunner::runDirectCommand(const QString &command)
{
	QLOG_INFO() << "TrikJavaScriptRunner: new direct command" << command;
	mScriptEngineWorker->runDirect(command, mMaxScriptId++);
}

void TrikJavaScriptRunner::abort()
{
	mScriptEngineWorker->stopScript();
	mScriptEngineWorker->resetBrick();
}

void TrikJavaScriptRunner::onScriptStart(int scriptId)
{
	if (scriptId != -1 && mScriptFileNames.contains(scriptId)) {
		emit startedScript(mScriptFileNames[scriptId], scriptId);
	} else {
		emit startedDirectScript(scriptId);
	}
}

QStringList TrikJavaScriptRunner::knownMethodNames() const
{
	return mScriptEngineWorker->knownMethodNames();
}

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

#include "trikJavaScriptRunner.h"

#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>

#include "src/scriptEngineWorker.h"
#include "src/scriptExecutionControl.h"

#include <QsLog.h>

using namespace trikScriptRunner;

TrikJavaScriptRunner::TrikJavaScriptRunner(trikControl::BrickInterface &brick
										   , trikNetwork::MailboxInterface * const mailbox
										   )
	: mScriptController(new ScriptExecutionControl())
	, mScriptEngineWorker(new ScriptEngineWorker(brick, mailbox, *mScriptController))
	, mMaxScriptId(0)
	, mVariablesServer(new TrikVariablesServer())
{
	connect(&mWorkerThread, &QThread::finished, &mWorkerThread, &QThread::deleteLater);

	mScriptEngineWorker->moveToThread(&mWorkerThread);

	connect(&mWorkerThread, &QThread::finished, mScriptEngineWorker, &QThread::deleteLater);
	connect(mScriptEngineWorker, &ScriptEngineWorker::completed, this, &TrikJavaScriptRunner::completed);
	connect(mScriptEngineWorker, &ScriptEngineWorker::startedScript, this, &TrikJavaScriptRunner::onScriptStart);

	connect(mScriptController.data(), &ScriptExecutionControl::textInStdOut,
		this, &TrikJavaScriptRunner::textInStdOut);

	connect(mVariablesServer.data(), &TrikVariablesServer::getVariables
		, mScriptEngineWorker, &ScriptEngineWorker::getVariables);
	connect(mScriptEngineWorker, &ScriptEngineWorker::variablesReady
		, mVariablesServer.data(), &TrikVariablesServer::sendHTTPResponse);

	QLOG_INFO() << "Starting TrikJavaScriptRunner worker thread" << &mWorkerThread;

	mWorkerThread.start();
}

TrikJavaScriptRunner::~TrikJavaScriptRunner()
{
	mScriptEngineWorker->stopScript();
	QMetaObject::invokeMethod(&mWorkerThread, "quit");
	mWorkerThread.wait(1000);
}

void TrikJavaScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function)
{
	mScriptEngineWorker->registerUserFunction(name, function);
}

void TrikJavaScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step)
{
	mScriptEngineWorker->addCustomEngineInitStep(step);
}

void TrikJavaScriptRunner::brickBeep()
{
	QMetaObject::invokeMethod(mScriptEngineWorker, "brickBeep");
}

void TrikJavaScriptRunner::run(const QString &script, const QString &fileName)
{
	const int scriptId = mMaxScriptId++;
	QLOG_INFO() << "TrikJavaScriptRunner: new script" << scriptId << "from file" << fileName;
	mScriptEngineWorker->stopScript();

	if (!fileName.isEmpty()) {
		mScriptFileNames[scriptId] = fileName;
	}

	mScriptEngineWorker->run(script, (fileName.isEmpty() ? -1 : scriptId));
}

void TrikJavaScriptRunner::runDirectCommand(const QString &command)
{
	QLOG_INFO() << "TrikJavaScriptRunner: new direct command" << command;
	mScriptEngineWorker->runDirect(command, mMaxScriptId++);
}

void TrikJavaScriptRunner::abort()
{
	mScriptEngineWorker->stopScript();
	mScriptEngineWorker->resetBrick();
}

void TrikJavaScriptRunner::onScriptStart(int scriptId)
{
	if (scriptId != -1 && mScriptFileNames.contains(scriptId)) {
		emit startedScript(mScriptFileNames[scriptId], scriptId);
	} else {
		emit startedDirectScript(scriptId);
	}
}

QStringList TrikJavaScriptRunner::knownMethodNames() const
{
	return mScriptEngineWorker->knownMethodNames();
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// Generic version of the x86 CPU extension detection routine.
///
/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp'
/// for the Microsoft compiler version.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <stdexcept>
#include <string>
#include "cpu_detect.h"
#include "STTypes.h"

using namespace std;

#include <stdio.h>

//////////////////////////////////////////////////////////////////////////////
//
// processor instructions extension detection routines
//
//////////////////////////////////////////////////////////////////////////////

// Flag variable indicating whick ISA extensions are disabled (for debugging)
static uint _dwDisabledISA = 0x00;      // 0xffffffff; //<- use this to disable all extensions

// Disables given set of instruction extensions. See SUPPORT_... defines.
void disableExtensions(uint dwDisableMask)
{
    _dwDisabledISA = dwDisableMask;
}

/// Checks which instruction set extensions are supported by the CPU.
uint detectCPUextensions(void)
{
#if (!(ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__))

    return 0; // always disable extensions on non-x86 platforms.

#else
    uint res = 0;

    if (_dwDisabledISA == 0xffffffff) return 0;

    asm volatile(
#ifndef __x86_64__
        // Check if 'cpuid' instructions is available by toggling eflags bit 21.
        // Skip this for x86-64 as they always have cpuid while stack manipulation
        // differs from 16/32bit ISA.
        "\n\txor     %%esi, %%esi"       // clear %%esi = result register

        "\n\tpushf"                      // save eflags to stack
        "\n\tmovl    (%%esp), %%eax"     // load eax from stack (with eflags)
        "\n\tmovl    %%eax, %%ecx"       // save the original eflags values to ecx
        "\n\txor     $0x00200000, %%eax" // toggle bit 21
        "\n\tmovl    %%eax, (%%esp)"     // store toggled eflags to stack
        "\n\tpopf"                       // load eflags from stack
        "\n\tpushf"                      // save updated eflags to stack
        "\n\tmovl    (%%esp), %%eax"     // load eax from stack
        "\n\tpopf"                       // pop stack to restore esp
        "\n\txor     %%edx, %%edx"       // clear edx for defaulting no mmx
        "\n\tcmp     %%ecx, %%eax"       // compare to original eflags values
        "\n\tjz      end"                // jumps to 'end' if cpuid not present
#endif // __x86_64__

        // cpuid instruction available, test for presence of mmx instructions

        "\n\tmovl    $1, %%eax"
        "\n\tcpuid"
        "\n\ttest    $0x00800000, %%edx"
        "\n\tjz      end"                // branch if MMX not available

        "\n\tor      $0x01, %%esi"       // otherwise add MMX support bit

        "\n\ttest    $0x02000000, %%edx"
        "\n\tjz      test3DNow"          // branch if SSE not available

        "\n\tor      $0x08, %%esi"       // otherwise add SSE support bit

    "\n\ttest3DNow:"
        // test for precense of AMD extensions
        "\n\tmov     $0x80000000, %%eax"
        "\n\tcpuid"
        "\n\tcmp     $0x80000000, %%eax"
        "\n\tjbe     end"                 // branch if no AMD extensions detected

        // test for precense of 3DNow! extension
        "\n\tmov     $0x80000001, %%eax"
        "\n\tcpuid"
        "\n\ttest    $0x80000000, %%edx"
        "\n\tjz      end"                  // branch if 3DNow! not detected

        "\n\tor      $0x02, %%esi"         // otherwise add 3DNow support bit

    "\n\tend:"

        "\n\tmov     %%esi, %0"

      : "=r" (res)
      : /* no inputs */
      : "%edx", "%eax", "%ecx", "%esi" );

    return res & ~_dwDisabledISA;
#endif
}
<commit_msg>Fixed #ifdefs<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// Generic version of the x86 CPU extension detection routine.
///
/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp'
/// for the Microsoft compiler version.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <stdexcept>
#include <string>
#include "cpu_detect.h"
#include "STTypes.h"

using namespace std;

#include <stdio.h>

//////////////////////////////////////////////////////////////////////////////
//
// processor instructions extension detection routines
//
//////////////////////////////////////////////////////////////////////////////

// Flag variable indicating whick ISA extensions are disabled (for debugging)
static uint _dwDisabledISA = 0x00;      // 0xffffffff; //<- use this to disable all extensions

// Disables given set of instruction extensions. See SUPPORT_... defines.
void disableExtensions(uint dwDisableMask)
{
    _dwDisabledISA = dwDisableMask;
}

/// Checks which instruction set extensions are supported by the CPU.
uint detectCPUextensions(void)
{
#if (!(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__))

    return 0; // always disable extensions on non-x86 platforms.

#else
    uint res = 0;

    if (_dwDisabledISA == 0xffffffff) return 0;

    asm volatile(
#ifndef __x86_64__
        // Check if 'cpuid' instructions is available by toggling eflags bit 21.
        // Skip this for x86-64 as they always have cpuid while stack manipulation
        // differs from 16/32bit ISA.
        "\n\txor     %%esi, %%esi"       // clear %%esi = result register

        "\n\tpushf"                      // save eflags to stack
        "\n\tmovl    (%%esp), %%eax"     // load eax from stack (with eflags)
        "\n\tmovl    %%eax, %%ecx"       // save the original eflags values to ecx
        "\n\txor     $0x00200000, %%eax" // toggle bit 21
        "\n\tmovl    %%eax, (%%esp)"     // store toggled eflags to stack
        "\n\tpopf"                       // load eflags from stack
        "\n\tpushf"                      // save updated eflags to stack
        "\n\tmovl    (%%esp), %%eax"     // load eax from stack
        "\n\tpopf"                       // pop stack to restore esp
        "\n\txor     %%edx, %%edx"       // clear edx for defaulting no mmx
        "\n\tcmp     %%ecx, %%eax"       // compare to original eflags values
        "\n\tjz      end"                // jumps to 'end' if cpuid not present
#endif // __x86_64__

        // cpuid instruction available, test for presence of mmx instructions

        "\n\tmovl    $1, %%eax"
        "\n\tcpuid"
        "\n\ttest    $0x00800000, %%edx"
        "\n\tjz      end"                // branch if MMX not available

        "\n\tor      $0x01, %%esi"       // otherwise add MMX support bit

        "\n\ttest    $0x02000000, %%edx"
        "\n\tjz      test3DNow"          // branch if SSE not available

        "\n\tor      $0x08, %%esi"       // otherwise add SSE support bit

    "\n\ttest3DNow:"
        // test for precense of AMD extensions
        "\n\tmov     $0x80000000, %%eax"
        "\n\tcpuid"
        "\n\tcmp     $0x80000000, %%eax"
        "\n\tjbe     end"                 // branch if no AMD extensions detected

        // test for precense of 3DNow! extension
        "\n\tmov     $0x80000001, %%eax"
        "\n\tcpuid"
        "\n\ttest    $0x80000000, %%edx"
        "\n\tjz      end"                  // branch if 3DNow! not detected

        "\n\tor      $0x02, %%esi"         // otherwise add 3DNow support bit

    "\n\tend:"

        "\n\tmov     %%esi, %0"

      : "=r" (res)
      : /* no inputs */
      : "%edx", "%eax", "%ecx", "%esi" );

    return res & ~_dwDisabledISA;
#endif
}
<|endoftext|>


<commit_before>// $Id: residueChecker.C,v 1.13 2000/10/30 00:19:59 amoll Exp $

#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/DATATYPE/hashSet.h>

using namespace std;

namespace BALL
{

	ResidueChecker::ResidueChecker()
		:	fragment_db_(0),
			status_(true)
	{
	}

	ResidueChecker::ResidueChecker(FragmentDB& fragment_db)
		:	fragment_db_(&fragment_db),
			status_(true)
	{
	}

	ResidueChecker::ResidueChecker(const ResidueChecker& residue_checker , bool /* deep */)
		:	UnaryProcessor<Residue>(),
			fragment_db_(residue_checker.fragment_db_),
			status_(residue_checker.status_)
	{
	}

	ResidueChecker::~ResidueChecker()
	{
	}

	bool ResidueChecker::getStatus() const
	{
		return status_;
	}

	bool ResidueChecker::start()
	{
		status_ = true;
		return true;
	}

	bool ResidueChecker::finish()
	{
		return true;
	}

	Processor::Result ResidueChecker::operator () (Residue& residue)
	{
		String res_name;
		if ((residue.getChain() != 0) && (residue.getChain()->getName() != BALL_CHAIN_DEFAULT_NAME))
		{
			res_name = residue.getChain()->getName() + ":";
		}
		res_name += residue.getName() + ":" + residue.getID();

		// checking charge: charge should be integral and -2 <= charge <= 2
		float total_charge = 0.0;
		AtomIterator atom_it = residue.beginAtom();
		for (; +atom_it; ++atom_it)
		{
			total_charge += atom_it->getCharge();
		}

		// check for very large absolute charges
		if (total_charge < -2.0)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
								 << total_charge << " is too negative." << endl;
			status_ = false;
		}

		if (total_charge > 2.0)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
								 << total_charge << " is too positive." << endl;
			status_ = false;
		}

		// check for integrality of charges
		float tmp = fabs(fabs(total_charge) - (float)((int)(fabs(total_charge) + 0.5)));
		if (tmp > 0.05)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": residue total charge of "
								 << total_charge << " is not integral." << endl;
			status_ = false;
		}

		// if a fragment data base is defined, check for completeness
		// of the residue
		if (fragment_db_ != 0)
		{
			const Residue* reference = dynamic_cast<const Residue*>(fragment_db_->getReferenceFragment(residue));
			if (reference == 0)
			{
				Log.warn() << "ResidueChecker: didn't find a reference fragment for " << res_name << endl;
				status_ = false;
			}
			else
			{
				// first, check for completeness
				HashSet<String> reference_names;
				for (atom_it = reference->beginAtom(); +atom_it; ++atom_it)
				{
					reference_names.insert(atom_it->getName());
				}

				for (atom_it = residue.beginAtom(); +atom_it; ++atom_it)
				{
					if (reference_names.has(atom_it->getName()))
					{
						reference_names.erase(atom_it->getName());
					}
					else
					{
						Log.warn() << "ResidueChecker: did not find atom " << atom_it->getName() << " of "
											 << res_name  << " in the reference residue " << reference->getName() << endl;
						status_ = false;
					}
				}
				if (reference_names.size() > 0)
				{
					Log.warn() << "ResidueChecker: did not find the following atoms in " << res_name << " : ";
					HashSet<String>::Iterator set_it = reference_names.begin();
					for (; set_it != reference_names.end(); ++set_it)
					{
						Log.warn() << *set_it << " ";
					}
					Log.warn() << endl;
					status_ = false;
				}

				// check bond lengths (should be within +/- 15% of reference values)
				Atom::BondIterator bond_it;
				AtomIterator bond_atom_it;
				Residue res(*reference);
				BALL_FOREACH_BOND(res, bond_atom_it, bond_it)
				{
					Atom* first = 0;
					Atom* second = 0;
					for (atom_it = residue.beginAtom(); +atom_it && (first == 0 || second == 0); ++atom_it)
					{
						if (atom_it->getName() == bond_it->getFirstAtom()->getName())
						{
							first = &*atom_it;
						}
						if (atom_it->getName() == bond_it->getSecondAtom()->getName())
						{
							second = &*atom_it;
						}
					}

					// if we found the bond atoms in residue, check the atom distance
					if ((first != 0) && (second != 0))
					{
						float distance = first->getPosition().getDistance(second->getPosition());
						float deviation = fabs(distance - bond_it->getLength()) / bond_it->getLength();
						if (deviation > 0.15)
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom distance "
												 << "between " << first->getName() << " and " << second->getName() << " suspect: "
												 << distance << " A instead of " << bond_it->getLength() << " A" << endl;
							status_ = false;
						}

						// check for the element type of each atom
						if (first->getElement() != bond_it->getFirstAtom()->getElement())
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
												 << first->getName() << " is "
												 << first->getElement().getSymbol() << " should be "
												 << bond_it->getFirstAtom()->getElement().getSymbol() << endl;
							status_ = false;
						}
						if (second->getElement() != bond_it->getSecondAtom()->getElement())
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
												 << second->getName() << " is "
												 << second->getElement().getSymbol() << " should be "
												 << bond_it->getSecondAtom()->getElement().getSymbol() << endl;
							status_ = false;
						}
					}
				}
			}
		}

		return Processor::CONTINUE;
	}

} // namespace BALL
<commit_msg>added: additional information is printed for missing atoms (template name)<commit_after>// $Id: residueChecker.C,v 1.14 2000/11/14 12:38:31 oliver Exp $

#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/DATATYPE/hashSet.h>

using namespace std;

namespace BALL
{

	ResidueChecker::ResidueChecker()
		:	fragment_db_(0),
			status_(true)
	{
	}

	ResidueChecker::ResidueChecker(FragmentDB& fragment_db)
		:	fragment_db_(&fragment_db),
			status_(true)
	{
	}

	ResidueChecker::ResidueChecker(const ResidueChecker& residue_checker , bool /* deep */)
		:	UnaryProcessor<Residue>(),
			fragment_db_(residue_checker.fragment_db_),
			status_(residue_checker.status_)
	{
	}

	ResidueChecker::~ResidueChecker()
	{
	}

	bool ResidueChecker::getStatus() const
	{
		return status_;
	}

	bool ResidueChecker::start()
	{
		status_ = true;
		return true;
	}

	bool ResidueChecker::finish()
	{
		return true;
	}

	Processor::Result ResidueChecker::operator () (Residue& residue)
	{
		String res_name;
		if ((residue.getChain() != 0) && (residue.getChain()->getName() != BALL_CHAIN_DEFAULT_NAME))
		{
			res_name = residue.getChain()->getName() + ":";
		}
		res_name += residue.getName() + ":" + residue.getID();

		// checking charge: charge should be integral and -2 <= charge <= 2
		float total_charge = 0.0;
		AtomIterator atom_it = residue.beginAtom();
		for (; +atom_it; ++atom_it)
		{
			total_charge += atom_it->getCharge();
		}

		// check for very large absolute charges
		if (total_charge < -2.0)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
								 << total_charge << " is too negative." << endl;
			status_ = false;
		}

		if (total_charge > 2.0)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
								 << total_charge << " is too positive." << endl;
			status_ = false;
		}

		// check for integrality of charges
		float tmp = fabs(fabs(total_charge) - (float)((int)(fabs(total_charge) + 0.5)));
		if (tmp > 0.05)
		{
			Log.warn() << "ResidueChecker: in residue " << res_name << ": residue total charge of "
								 << total_charge << " is not integral." << endl;
			status_ = false;
		}

		// if a fragment data base is defined, check for completeness
		// of the residue
		if (fragment_db_ != 0)
		{
			const Residue* reference = dynamic_cast<const Residue*>(fragment_db_->getReferenceFragment(residue));
			if (reference == 0)
			{
				Log.warn() << "ResidueChecker: didn't find a reference fragment for " << res_name << endl;
				status_ = false;
			}
			else
			{
				// first, check for completeness
				HashSet<String> reference_names;
				for (atom_it = reference->beginAtom(); +atom_it; ++atom_it)
				{
					reference_names.insert(atom_it->getName());
				}

				for (atom_it = residue.beginAtom(); +atom_it; ++atom_it)
				{
					if (reference_names.has(atom_it->getName()))
					{
						reference_names.erase(atom_it->getName());
					}
					else
					{
						Log.warn() << "ResidueChecker: did not find atom " << atom_it->getName() << " of "
											 << res_name  << " in the reference residue " << reference->getName() << endl;
						status_ = false;
					}
				}
				if (reference_names.size() > 0)
				{
					Log.warn() << "ResidueChecker: did not find the following atoms in " << res_name << " : ";
					HashSet<String>::Iterator set_it = reference_names.begin();
					for (; set_it != reference_names.end(); ++set_it)
					{
						Log.warn() << *set_it << " ";
					}
					Log.warn() << " (template was " << reference->getName() << ")" << endl;
					status_ = false;
				}

				// check bond lengths (should be within +/- 15% of reference values)
				Atom::BondIterator bond_it;
				AtomIterator bond_atom_it;
				Residue res(*reference);
				BALL_FOREACH_BOND(res, bond_atom_it, bond_it)
				{
					Atom* first = 0;
					Atom* second = 0;
					for (atom_it = residue.beginAtom(); +atom_it && (first == 0 || second == 0); ++atom_it)
					{
						if (atom_it->getName() == bond_it->getFirstAtom()->getName())
						{
							first = &*atom_it;
						}
						if (atom_it->getName() == bond_it->getSecondAtom()->getName())
						{
							second = &*atom_it;
						}
					}

					// if we found the bond atoms in residue, check the atom distance
					if ((first != 0) && (second != 0))
					{
						float distance = first->getPosition().getDistance(second->getPosition());
						float deviation = fabs(distance - bond_it->getLength()) / bond_it->getLength();
						if (deviation > 0.15)
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom distance "
												 << "between " << first->getName() << " and " << second->getName() << " suspect: "
												 << distance << " A instead of " << bond_it->getLength() << " A" << endl;
							status_ = false;
						}

						// check for the element type of each atom
						if (first->getElement() != bond_it->getFirstAtom()->getElement())
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
												 << first->getName() << " is "
												 << first->getElement().getSymbol() << " should be "
												 << bond_it->getFirstAtom()->getElement().getSymbol() << endl;
							status_ = false;
						}
						if (second->getElement() != bond_it->getSecondAtom()->getElement())
						{
							Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
												 << second->getName() << " is "
												 << second->getElement().getSymbol() << " should be "
												 << bond_it->getSecondAtom()->getElement().getSymbol() << endl;
							status_ = false;
						}
					}
				}
			}
		}

		return Processor::CONTINUE;
	}

} // namespace BALL
<|endoftext|>