<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <basidesh.hrc>
#include <basidesh.hxx>
#include <basobj.hxx>

#include <basicbox.hxx>
#include <iderid.hxx>
#include <iderdll.hxx>
#include <bastypes.hxx>
#include "bastype2.hxx"
#include "basdoc.hxx"

#include "localizationmgr.hxx"
#include "managelang.hxx"
#include "dlgresid.hrc"
#include <editeng/unolingu.hxx>

#include <sfx2/dinfdlg.hxx>
#include <sfx2/dispatch.hxx>
#include <svtools/langtab.hxx>

namespace basctl
{

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;

SFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );

LibBoxControl::LibBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )
    : SfxToolBoxControl( nSlotId, nId, rTbx )
{
}

LibBoxControl::~LibBoxControl()
{
}

void LibBoxControl::StateChanged( sal_uInt16, SfxItemState eState, const SfxPoolItem* pState )
{
    LibBox* pBox = (LibBox*)GetToolBox().GetItemWindow(GetId());

    DBG_ASSERT( pBox, "Box not found" );
    if ( !pBox )
        return;

    if ( eState != SFX_ITEM_AVAILABLE )
        pBox->Disable();
    else
    {
        pBox->Enable();
        pBox->Update(dynamic_cast<SfxStringItem const*>(pState));
    }
}

Window* LibBoxControl::CreateItemWindow( Window *pParent )
{
    return new LibBox( pParent, m_xFrame );
}

//= DocListenerBox

DocListenerBox::DocListenerBox( Window* pParent )
    :ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) )
    ,m_aNotifier( *this )
{
}

DocListenerBox::~DocListenerBox()
{
    m_aNotifier.dispose();
}

void DocListenerBox::onDocumentCreated( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentOpened( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentSave( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveDone( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveAs( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveAsDone( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentClosed( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentTitleChanged( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentModeChanged( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

//= basctl::LibBox

LibBox::LibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :
    DocListenerBox( pParent ),
    m_xFrame( rFrame )
{
    FillBox();
    bIgnoreSelect = true;   // do not yet transfer select of 0
    bFillBox = true;
    SelectEntryPos( 0 );
    aCurText = GetEntry( 0 );
    SetSizePixel( Size( 250, 200 ) );
    bIgnoreSelect = false;
}

LibBox::~LibBox()
{
    ClearBox();
}

void LibBox::Update( const SfxStringItem* pItem )
{

//  if ( !pItem  || !pItem->GetValue().Len() )
        FillBox();

    if ( pItem )
    {
        aCurText = pItem->GetValue();
        if ( aCurText.isEmpty() )
            aCurText = OUString( IDEResId( RID_STR_ALL ) );
    }

    if ( GetSelectEntry() != aCurText )
        SelectEntry( aCurText );
}

void LibBox::ReleaseFocus()
{
    SfxViewShell* pCurSh = SfxViewShell::Current();
    DBG_ASSERT( pCurSh, "Current ViewShell not found!" );

    if ( pCurSh )
    {
        Window* pShellWin = pCurSh->GetWindow();
        if ( !pShellWin )
            pShellWin = Application::GetDefDialogParent();

        pShellWin->GrabFocus();
    }
}

void LibBox::FillBox()
{
    SetUpdateMode(false);
    bIgnoreSelect = true;

    aCurText = GetSelectEntry();

    SelectEntryPos( 0 );
    ClearBox();

    // create list box entries
    sal_Int32 nPos = InsertEntry( OUString( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );
    SetEntryData( nPos, new LibEntry( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_UNKNOWN, OUString() ) );
    InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_USER );
    InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_SHARE );

    ScriptDocuments aDocuments( ScriptDocument::getAllScriptDocuments( ScriptDocument::DocumentsSorted ) );
    for (   ScriptDocuments::const_iterator doc = aDocuments.begin();
            doc != aDocuments.end();
            ++doc
        )
    {
        InsertEntries( *doc, LIBRARY_LOCATION_DOCUMENT );
    }

    SetUpdateMode(true);

    SelectEntry( aCurText );
    if ( !GetSelectEntryCount() )
    {
        SelectEntryPos( GetEntryCount() );
        aCurText = GetSelectEntry();
    }
    bIgnoreSelect = false;
}

void LibBox::InsertEntries( const ScriptDocument& rDocument, LibraryLocation eLocation )
{
    // get a sorted list of library names
    Sequence< OUString > aLibNames = rDocument.getLibraryNames();
    sal_Int32 nLibCount = aLibNames.getLength();
    const OUString* pLibNames = aLibNames.getConstArray();

    for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )
    {
        OUString aLibName = pLibNames[ i ];
        if ( eLocation == rDocument.getLibraryLocation( aLibName ) )
        {
            OUString aName( rDocument.getTitle( eLocation ) );
            OUString aEntryText( CreateMgrAndLibStr( aName, aLibName ) );
            sal_Int32 nPos = InsertEntry( aEntryText, LISTBOX_APPEND );
            SetEntryData( nPos, new LibEntry( rDocument, eLocation, aLibName ) );
        }
    }
}

bool LibBox::PreNotify( NotifyEvent& rNEvt )
{
    bool nDone = false;
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();
        sal_uInt16 nKeyCode = aKeyEvt.GetKeyCode().GetCode();
        switch( nKeyCode )
        {
            case KEY_RETURN:
            {
                NotifyIDE();
                nDone = true;
            }
            break;

            case KEY_ESCAPE:
            {
                SelectEntry( aCurText );
                ReleaseFocus();
                nDone = true;
            }
            break;
        }
    }
    else if( rNEvt.GetType() == EVENT_GETFOCUS )
    {
        if ( bFillBox )
        {
            FillBox();
            bFillBox = false;
        }
    }
    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
    {
        if ( !HasChildPathFocus(true) )
        {
            bIgnoreSelect = true;
            bFillBox = true;
        }
    }

    return nDone || ListBox::PreNotify( rNEvt );
}

void LibBox::Select()
{
    if ( !IsTravelSelect() )
    {
        if ( !bIgnoreSelect )
            NotifyIDE();
        else
            SelectEntry( aCurText );    // since 306... (Select after Escape)
    }
}

void LibBox::NotifyIDE()
{
    sal_Int32 nSelPos = GetSelectEntryPos();
    if (LibEntry* pEntry = static_cast<LibEntry*>(GetEntryData(nSelPos)))
    {
        ScriptDocument aDocument( pEntry->GetDocument() );
        SfxUsrAnyItem aDocumentItem( SID_BASICIDE_ARG_DOCUMENT_MODEL, uno::makeAny( aDocument.getDocumentOrNull() ) );
        OUString aLibName = pEntry->GetLibName();
        SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );
        if (SfxDispatcher* pDispatcher = GetDispatcher())
            pDispatcher->Execute(
                SID_BASICIDE_LIBSELECTED,
                SFX_CALLMODE_SYNCHRON, &aDocumentItem, &aLibNameItem, 0L
            );
    }
    ReleaseFocus();
}

void LibBox::ClearBox()
{
    sal_Int32 nCount = GetEntryCount();
    for ( sal_Int32 i = 0; i < nCount; ++i )
    {
        LibEntry* pEntry = static_cast<LibEntry*>(GetEntryData( i ));
        delete pEntry;
    }
    ListBox::Clear();
}

// class LanguageBoxControl ----------------------------------------------

SFX_IMPL_TOOLBOX_CONTROL( LanguageBoxControl, SfxStringItem );

LanguageBoxControl::LanguageBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )
    : SfxToolBoxControl( nSlotId, nId, rTbx )
{
}

LanguageBoxControl::~LanguageBoxControl()
{
}

void LanguageBoxControl::StateChanged( sal_uInt16 nID, SfxItemState eState, const SfxPoolItem* pItem )
{
    (void)nID;
    if (LanguageBox* pBox = static_cast<LanguageBox*>(GetToolBox().GetItemWindow(GetId())))
    {
        if (eState != SFX_ITEM_AVAILABLE)
            pBox->Disable();
        else
        {
            pBox->Enable();
            pBox->Update(dynamic_cast<SfxStringItem const*>(pItem));
        }
    }
}

Window* LanguageBoxControl::CreateItemWindow( Window *pParent )
{
    return new LanguageBox( pParent );
}

// class basctl::LanguageBox -----------------------------------------------

LanguageBox::LanguageBox( Window* pParent ) :

    DocListenerBox( pParent ),

    m_sNotLocalizedStr( IDEResId( RID_STR_TRANSLATION_NOTLOCALIZED ) ),
    m_sDefaultLanguageStr( IDEResId( RID_STR_TRANSLATION_DEFAULT ) ),

    m_bIgnoreSelect( false )

{
    SetSizePixel( Size( 210, 200 ) );

    FillBox();
}

LanguageBox::~LanguageBox()
{
    ClearBox();
}

void LanguageBox::FillBox()
{
    SetUpdateMode(false);
    m_bIgnoreSelect = true;
    m_sCurrentText = GetSelectEntry();
    ClearBox();

    boost::shared_ptr<LocalizationMgr> pCurMgr(GetShell()->GetCurLocalizationMgr());
    if ( pCurMgr->isLibraryLocalized() )
    {
        Enable();
        SvtLanguageTable aLangTable;
        Locale aDefaultLocale = pCurMgr->getStringResourceManager()->getDefaultLocale();
        Locale aCurrentLocale = pCurMgr->getStringResourceManager()->getCurrentLocale();
        Sequence< Locale > aLocaleSeq = pCurMgr->getStringResourceManager()->getLocales();
        const Locale* pLocale = aLocaleSeq.getConstArray();
        sal_Int32 i, nCount = aLocaleSeq.getLength();
        sal_Int32 nSelPos = LISTBOX_ENTRY_NOTFOUND;
        for ( i = 0;  i < nCount;  ++i )
        {
            bool bIsDefault = localesAreEqual( aDefaultLocale, pLocale[i] );
            bool bIsCurrent = localesAreEqual( aCurrentLocale, pLocale[i] );
            LanguageType eLangType = LanguageTag::convertToLanguageType( pLocale[i] );
            OUString sLanguage = aLangTable.GetString( eLangType );
            if ( bIsDefault )
            {
                sLanguage += " ";
                sLanguage += m_sDefaultLanguageStr;
            }
            sal_Int32 nPos = InsertEntry( sLanguage );
            SetEntryData( nPos, new LanguageEntry( sLanguage, pLocale[i], bIsDefault ) );

            if ( bIsCurrent )
                nSelPos = nPos;
        }

        if ( nSelPos != LISTBOX_ENTRY_NOTFOUND )
        {
            SelectEntryPos( nSelPos );
            m_sCurrentText = GetSelectEntry();
        }
    }
    else
    {
        InsertEntry( m_sNotLocalizedStr );
        SelectEntryPos(0);
        Disable();
    }

    SetUpdateMode(true);
    m_bIgnoreSelect = false;
}

void LanguageBox::ClearBox()
{
    sal_Int32 nCount = GetEntryCount();
    for ( sal_Int32 i = 0; i < nCount; ++i )
    {
        LanguageEntry* pEntry = (LanguageEntry*)GetEntryData(i);
        delete pEntry;
    }
    ListBox::Clear();
}

void LanguageBox::SetLanguage()
{
    LanguageEntry* pEntry = (LanguageEntry*)GetEntryData( GetSelectEntryPos() );
    if ( pEntry )
        GetShell()->GetCurLocalizationMgr()->handleSetCurrentLocale( pEntry->m_aLocale );
}

void LanguageBox::Select()
{
    if ( !m_bIgnoreSelect )
        SetLanguage();
    else
        SelectEntry( m_sCurrentText );  // Select after Escape
}

bool LanguageBox::PreNotify( NotifyEvent& rNEvt )
{
    bool nDone = false;
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        sal_uInt16 nKeyCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
        switch( nKeyCode )
        {
            case KEY_RETURN:
            {
                SetLanguage();
                nDone = true;
            }
            break;

            case KEY_ESCAPE:
            {
                SelectEntry( m_sCurrentText );
                nDone = true;
            }
            break;
        }
    }
    else if( rNEvt.GetType() == EVENT_GETFOCUS )
    {
    }
    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
    {
    }

    return nDone || ListBox::PreNotify( rNEvt );
}

void LanguageBox::Update( const SfxStringItem* pItem )
{
    FillBox();

    if ( pItem && !pItem->GetValue().isEmpty() )
    {
        m_sCurrentText = pItem->GetValue();
        if ( GetSelectEntry() != m_sCurrentText )
            SelectEntry( m_sCurrentText );
    }
}

} // namespace basctl

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>no temporary instance of SvtLanguageTable necessary here<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <basidesh.hrc>
#include <basidesh.hxx>
#include <basobj.hxx>

#include <basicbox.hxx>
#include <iderid.hxx>
#include <iderdll.hxx>
#include <bastypes.hxx>
#include "bastype2.hxx"
#include "basdoc.hxx"

#include "localizationmgr.hxx"
#include "managelang.hxx"
#include "dlgresid.hrc"
#include <editeng/unolingu.hxx>

#include <sfx2/dinfdlg.hxx>
#include <sfx2/dispatch.hxx>
#include <svtools/langtab.hxx>

namespace basctl
{

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;

SFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );

LibBoxControl::LibBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )
    : SfxToolBoxControl( nSlotId, nId, rTbx )
{
}

LibBoxControl::~LibBoxControl()
{
}

void LibBoxControl::StateChanged( sal_uInt16, SfxItemState eState, const SfxPoolItem* pState )
{
    LibBox* pBox = (LibBox*)GetToolBox().GetItemWindow(GetId());

    DBG_ASSERT( pBox, "Box not found" );
    if ( !pBox )
        return;

    if ( eState != SFX_ITEM_AVAILABLE )
        pBox->Disable();
    else
    {
        pBox->Enable();
        pBox->Update(dynamic_cast<SfxStringItem const*>(pState));
    }
}

Window* LibBoxControl::CreateItemWindow( Window *pParent )
{
    return new LibBox( pParent, m_xFrame );
}

//= DocListenerBox

DocListenerBox::DocListenerBox( Window* pParent )
    :ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) )
    ,m_aNotifier( *this )
{
}

DocListenerBox::~DocListenerBox()
{
    m_aNotifier.dispose();
}

void DocListenerBox::onDocumentCreated( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentOpened( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentSave( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveDone( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveAs( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentSaveAsDone( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentClosed( const ScriptDocument& /*_rDocument*/ )
{
    FillBox();
}

void DocListenerBox::onDocumentTitleChanged( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

void DocListenerBox::onDocumentModeChanged( const ScriptDocument& /*_rDocument*/ )
{
    // not interested in
}

//= basctl::LibBox

LibBox::LibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :
    DocListenerBox( pParent ),
    m_xFrame( rFrame )
{
    FillBox();
    bIgnoreSelect = true;   // do not yet transfer select of 0
    bFillBox = true;
    SelectEntryPos( 0 );
    aCurText = GetEntry( 0 );
    SetSizePixel( Size( 250, 200 ) );
    bIgnoreSelect = false;
}

LibBox::~LibBox()
{
    ClearBox();
}

void LibBox::Update( const SfxStringItem* pItem )
{

//  if ( !pItem  || !pItem->GetValue().Len() )
        FillBox();

    if ( pItem )
    {
        aCurText = pItem->GetValue();
        if ( aCurText.isEmpty() )
            aCurText = OUString( IDEResId( RID_STR_ALL ) );
    }

    if ( GetSelectEntry() != aCurText )
        SelectEntry( aCurText );
}

void LibBox::ReleaseFocus()
{
    SfxViewShell* pCurSh = SfxViewShell::Current();
    DBG_ASSERT( pCurSh, "Current ViewShell not found!" );

    if ( pCurSh )
    {
        Window* pShellWin = pCurSh->GetWindow();
        if ( !pShellWin )
            pShellWin = Application::GetDefDialogParent();

        pShellWin->GrabFocus();
    }
}

void LibBox::FillBox()
{
    SetUpdateMode(false);
    bIgnoreSelect = true;

    aCurText = GetSelectEntry();

    SelectEntryPos( 0 );
    ClearBox();

    // create list box entries
    sal_Int32 nPos = InsertEntry( OUString( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );
    SetEntryData( nPos, new LibEntry( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_UNKNOWN, OUString() ) );
    InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_USER );
    InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_SHARE );

    ScriptDocuments aDocuments( ScriptDocument::getAllScriptDocuments( ScriptDocument::DocumentsSorted ) );
    for (   ScriptDocuments::const_iterator doc = aDocuments.begin();
            doc != aDocuments.end();
            ++doc
        )
    {
        InsertEntries( *doc, LIBRARY_LOCATION_DOCUMENT );
    }

    SetUpdateMode(true);

    SelectEntry( aCurText );
    if ( !GetSelectEntryCount() )
    {
        SelectEntryPos( GetEntryCount() );
        aCurText = GetSelectEntry();
    }
    bIgnoreSelect = false;
}

void LibBox::InsertEntries( const ScriptDocument& rDocument, LibraryLocation eLocation )
{
    // get a sorted list of library names
    Sequence< OUString > aLibNames = rDocument.getLibraryNames();
    sal_Int32 nLibCount = aLibNames.getLength();
    const OUString* pLibNames = aLibNames.getConstArray();

    for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )
    {
        OUString aLibName = pLibNames[ i ];
        if ( eLocation == rDocument.getLibraryLocation( aLibName ) )
        {
            OUString aName( rDocument.getTitle( eLocation ) );
            OUString aEntryText( CreateMgrAndLibStr( aName, aLibName ) );
            sal_Int32 nPos = InsertEntry( aEntryText, LISTBOX_APPEND );
            SetEntryData( nPos, new LibEntry( rDocument, eLocation, aLibName ) );
        }
    }
}

bool LibBox::PreNotify( NotifyEvent& rNEvt )
{
    bool nDone = false;
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();
        sal_uInt16 nKeyCode = aKeyEvt.GetKeyCode().GetCode();
        switch( nKeyCode )
        {
            case KEY_RETURN:
            {
                NotifyIDE();
                nDone = true;
            }
            break;

            case KEY_ESCAPE:
            {
                SelectEntry( aCurText );
                ReleaseFocus();
                nDone = true;
            }
            break;
        }
    }
    else if( rNEvt.GetType() == EVENT_GETFOCUS )
    {
        if ( bFillBox )
        {
            FillBox();
            bFillBox = false;
        }
    }
    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
    {
        if ( !HasChildPathFocus(true) )
        {
            bIgnoreSelect = true;
            bFillBox = true;
        }
    }

    return nDone || ListBox::PreNotify( rNEvt );
}

void LibBox::Select()
{
    if ( !IsTravelSelect() )
    {
        if ( !bIgnoreSelect )
            NotifyIDE();
        else
            SelectEntry( aCurText );    // since 306... (Select after Escape)
    }
}

void LibBox::NotifyIDE()
{
    sal_Int32 nSelPos = GetSelectEntryPos();
    if (LibEntry* pEntry = static_cast<LibEntry*>(GetEntryData(nSelPos)))
    {
        ScriptDocument aDocument( pEntry->GetDocument() );
        SfxUsrAnyItem aDocumentItem( SID_BASICIDE_ARG_DOCUMENT_MODEL, uno::makeAny( aDocument.getDocumentOrNull() ) );
        OUString aLibName = pEntry->GetLibName();
        SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );
        if (SfxDispatcher* pDispatcher = GetDispatcher())
            pDispatcher->Execute(
                SID_BASICIDE_LIBSELECTED,
                SFX_CALLMODE_SYNCHRON, &aDocumentItem, &aLibNameItem, 0L
            );
    }
    ReleaseFocus();
}

void LibBox::ClearBox()
{
    sal_Int32 nCount = GetEntryCount();
    for ( sal_Int32 i = 0; i < nCount; ++i )
    {
        LibEntry* pEntry = static_cast<LibEntry*>(GetEntryData( i ));
        delete pEntry;
    }
    ListBox::Clear();
}

// class LanguageBoxControl ----------------------------------------------

SFX_IMPL_TOOLBOX_CONTROL( LanguageBoxControl, SfxStringItem );

LanguageBoxControl::LanguageBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )
    : SfxToolBoxControl( nSlotId, nId, rTbx )
{
}

LanguageBoxControl::~LanguageBoxControl()
{
}

void LanguageBoxControl::StateChanged( sal_uInt16 nID, SfxItemState eState, const SfxPoolItem* pItem )
{
    (void)nID;
    if (LanguageBox* pBox = static_cast<LanguageBox*>(GetToolBox().GetItemWindow(GetId())))
    {
        if (eState != SFX_ITEM_AVAILABLE)
            pBox->Disable();
        else
        {
            pBox->Enable();
            pBox->Update(dynamic_cast<SfxStringItem const*>(pItem));
        }
    }
}

Window* LanguageBoxControl::CreateItemWindow( Window *pParent )
{
    return new LanguageBox( pParent );
}

// class basctl::LanguageBox -----------------------------------------------

LanguageBox::LanguageBox( Window* pParent ) :

    DocListenerBox( pParent ),

    m_sNotLocalizedStr( IDEResId( RID_STR_TRANSLATION_NOTLOCALIZED ) ),
    m_sDefaultLanguageStr( IDEResId( RID_STR_TRANSLATION_DEFAULT ) ),

    m_bIgnoreSelect( false )

{
    SetSizePixel( Size( 210, 200 ) );

    FillBox();
}

LanguageBox::~LanguageBox()
{
    ClearBox();
}

void LanguageBox::FillBox()
{
    SetUpdateMode(false);
    m_bIgnoreSelect = true;
    m_sCurrentText = GetSelectEntry();
    ClearBox();

    boost::shared_ptr<LocalizationMgr> pCurMgr(GetShell()->GetCurLocalizationMgr());
    if ( pCurMgr->isLibraryLocalized() )
    {
        Enable();
        Locale aDefaultLocale = pCurMgr->getStringResourceManager()->getDefaultLocale();
        Locale aCurrentLocale = pCurMgr->getStringResourceManager()->getCurrentLocale();
        Sequence< Locale > aLocaleSeq = pCurMgr->getStringResourceManager()->getLocales();
        const Locale* pLocale = aLocaleSeq.getConstArray();
        sal_Int32 i, nCount = aLocaleSeq.getLength();
        sal_Int32 nSelPos = LISTBOX_ENTRY_NOTFOUND;
        for ( i = 0;  i < nCount;  ++i )
        {
            bool bIsDefault = localesAreEqual( aDefaultLocale, pLocale[i] );
            bool bIsCurrent = localesAreEqual( aCurrentLocale, pLocale[i] );
            LanguageType eLangType = LanguageTag::convertToLanguageType( pLocale[i] );
            OUString sLanguage = SvtLanguageTable::GetLanguageString( eLangType );
            if ( bIsDefault )
            {
                sLanguage += " ";
                sLanguage += m_sDefaultLanguageStr;
            }
            sal_Int32 nPos = InsertEntry( sLanguage );
            SetEntryData( nPos, new LanguageEntry( sLanguage, pLocale[i], bIsDefault ) );

            if ( bIsCurrent )
                nSelPos = nPos;
        }

        if ( nSelPos != LISTBOX_ENTRY_NOTFOUND )
        {
            SelectEntryPos( nSelPos );
            m_sCurrentText = GetSelectEntry();
        }
    }
    else
    {
        InsertEntry( m_sNotLocalizedStr );
        SelectEntryPos(0);
        Disable();
    }

    SetUpdateMode(true);
    m_bIgnoreSelect = false;
}

void LanguageBox::ClearBox()
{
    sal_Int32 nCount = GetEntryCount();
    for ( sal_Int32 i = 0; i < nCount; ++i )
    {
        LanguageEntry* pEntry = (LanguageEntry*)GetEntryData(i);
        delete pEntry;
    }
    ListBox::Clear();
}

void LanguageBox::SetLanguage()
{
    LanguageEntry* pEntry = (LanguageEntry*)GetEntryData( GetSelectEntryPos() );
    if ( pEntry )
        GetShell()->GetCurLocalizationMgr()->handleSetCurrentLocale( pEntry->m_aLocale );
}

void LanguageBox::Select()
{
    if ( !m_bIgnoreSelect )
        SetLanguage();
    else
        SelectEntry( m_sCurrentText );  // Select after Escape
}

bool LanguageBox::PreNotify( NotifyEvent& rNEvt )
{
    bool nDone = false;
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        sal_uInt16 nKeyCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();
        switch( nKeyCode )
        {
            case KEY_RETURN:
            {
                SetLanguage();
                nDone = true;
            }
            break;

            case KEY_ESCAPE:
            {
                SelectEntry( m_sCurrentText );
                nDone = true;
            }
            break;
        }
    }
    else if( rNEvt.GetType() == EVENT_GETFOCUS )
    {
    }
    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
    {
    }

    return nDone || ListBox::PreNotify( rNEvt );
}

void LanguageBox::Update( const SfxStringItem* pItem )
{
    FillBox();

    if ( pItem && !pItem->GetValue().isEmpty() )
    {
        m_sCurrentText = pItem->GetValue();
        if ( GetSelectEntry() != m_sCurrentText )
            SelectEntry( m_sCurrentText );
    }
}

} // namespace basctl

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <gtkmm.h>

#include <gdk/gdk.h>
#include <gdkmm/general.h>
#include <gdk/gdkx.h>

class SFMLWidget : public Gtk::Widget, public sf::Window
{
    protected:
        sf::VideoMode m_vMode;

        virtual void on_size_request(Gtk::Requisition* requisition);
        virtual void on_size_allocate(Gtk::Allocation& allocation);
        virtual void on_map();
        virtual void on_unmap();
        virtual void on_realize();
        virtual void on_unrealize();
        virtual bool on_idle();
        virtual bool on_expose_event(GdkEventExpose* event);

        Glib::RefPtr<Gdk::Window> m_refGdkWindow;
    public:
        SFMLWidget(sf::VideoMode Mode);
        virtual ~SFMLWidget();
};

bool SFMLWidget::on_idle()
{
    if(m_refGdkWindow)
    {
        this->display();
    }

    return true;
}

SFMLWidget::SFMLWidget(sf::VideoMode Mode)
    : sf::Window(Mode, "")
{
    set_flags(Gtk::NO_WINDOW); //Makes this behave like an interal object rather then a parent window.
    Glib::signal_idle().connect( sigc::mem_fun(*this, &SFMLWidget::on_idle) );
}

SFMLWidget::~SFMLWidget()
{
}

void SFMLWidget::on_size_request(Gtk::Requisition* requisition)
{
    *requisition = Gtk::Requisition();

    sf::Vector2u v = this->getSize();

    requisition->width = v.x;
    requisition->height = v.y;
}

void SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)
{
    //Do something with the space that we have actually been given:
    //(We will not be given heights or widths less than we have requested, though
    //we might get more)

    this->set_allocation(allocation);

    if(m_refGdkWindow)
    {
        m_refGdkWindow->move_resize(allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height() );
        this->setSize(sf::Vector2u(allocation.get_width(), allocation.get_height()));
    }
}

void SFMLWidget::on_map()
{
    Gtk::Widget::on_map();
}

void SFMLWidget::on_unmap()
{
    Gtk::Widget::on_unmap();
}

void SFMLWidget::on_realize()
{
    Gtk::Widget::on_realize();

    if(!m_refGdkWindow)
    {
        //Create the GdkWindow:
        GdkWindowAttr attributes;
        memset(&attributes, 0, sizeof(attributes));

        Gtk::Allocation allocation = get_allocation();

        //Set initial position and size of the Gdk::Window:
        attributes.x = allocation.get_x();
        attributes.y = allocation.get_y();
        attributes.width = allocation.get_width();
        attributes.height = allocation.get_height();

        attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
        attributes.window_type = GDK_WINDOW_CHILD;
        attributes.wclass = GDK_INPUT_OUTPUT;

        m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,
                GDK_WA_X | GDK_WA_Y);
        unset_flags(Gtk::NO_WINDOW);
        set_window(m_refGdkWindow);

        //set colors
        modify_bg(Gtk::STATE_NORMAL , Gdk::Color("red"));
        modify_fg(Gtk::STATE_NORMAL , Gdk::Color("blue"));

        //make the widget receive expose events
        m_refGdkWindow->set_user_data(gobj());

        this->sf::Window::create((GDK_WINDOW_XID(m_refGdkWindow->gobj())));
    }
}

void SFMLWidget::on_unrealize()
{
  m_refGdkWindow.clear();

  //Call base class:
  Gtk::Widget::on_unrealize();
}

bool SFMLWidget::on_expose_event(GdkEventExpose* event)
{
    if(m_refGdkWindow)
    {
        glClearColor(0.25f, 0.25f, 0.25f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        this->display();
    }

    return true;
}

int main(int argc, char* argv[])
{
    Gtk::Main kit(argc, argv); //Initialize Gtk

    Gtk::Window window; //The GTK window will be our top level Window

    //Our RenderWindow will never be below  640x480 (unless we explicitly change it)
    //but it may be more then that
    SFMLWidget ourRenderWindow(sf::VideoMode(640, 480));

    // Doesn't draw the renderWindow but makes it so it will draw when we add it to the window
    ourRenderWindow.show();

    //VBox is a vertical box, we're going to pack our render window and a button in here
    Gtk::VBox ourVBox;

    Gtk::Button ourButton("Hello I do nothing"); //Just a clickable button, it won't be doing anything
    ourButton.show();

    ourVBox.pack_start(ourRenderWindow); //Add ourRenderWindow to the top of the VBox

    //PACK_SHRINK makes the VBox only allocate enough space to show the button and nothing more
    ourVBox.pack_start(ourButton, Gtk::PACK_SHRINK);
    ourVBox.show();

    window.add(ourVBox); //Adds ourVBox to the window so it (and it's children) can be drawn

    Gtk::Main::run(window); //Draw the window
    return 0;
}
<commit_msg>Add header comments<commit_after>// window.cpp
// Copyright 2013 Matthew Chandler
// windowing code. Using GTK to create the window, SFML to do openGL graphics.

#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <gtkmm.h>

#include <gdk/gdk.h>
#include <gdkmm/general.h>
#include <gdk/gdkx.h>

class SFMLWidget : public Gtk::Widget, public sf::Window
{
    protected:
        sf::VideoMode m_vMode;

        virtual void on_size_request(Gtk::Requisition* requisition);
        virtual void on_size_allocate(Gtk::Allocation& allocation);
        virtual void on_map();
        virtual void on_unmap();
        virtual void on_realize();
        virtual void on_unrealize();
        virtual bool on_idle();
        virtual bool on_expose_event(GdkEventExpose* event);

        Glib::RefPtr<Gdk::Window> m_refGdkWindow;
    public:
        SFMLWidget(sf::VideoMode Mode);
        virtual ~SFMLWidget();
};

bool SFMLWidget::on_idle()
{
    if(m_refGdkWindow)
    {
        this->display();
    }

    return true;
}

SFMLWidget::SFMLWidget(sf::VideoMode Mode)
    : sf::Window(Mode, "")
{
    set_flags(Gtk::NO_WINDOW); //Makes this behave like an interal object rather then a parent window.
    Glib::signal_idle().connect( sigc::mem_fun(*this, &SFMLWidget::on_idle) );
}

SFMLWidget::~SFMLWidget()
{
}

void SFMLWidget::on_size_request(Gtk::Requisition* requisition)
{
    *requisition = Gtk::Requisition();

    sf::Vector2u v = this->getSize();

    requisition->width = v.x;
    requisition->height = v.y;
}

void SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)
{
    //Do something with the space that we have actually been given:
    //(We will not be given heights or widths less than we have requested, though
    //we might get more)

    this->set_allocation(allocation);

    if(m_refGdkWindow)
    {
        m_refGdkWindow->move_resize(allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height() );
        this->setSize(sf::Vector2u(allocation.get_width(), allocation.get_height()));
    }
}

void SFMLWidget::on_map()
{
    Gtk::Widget::on_map();
}

void SFMLWidget::on_unmap()
{
    Gtk::Widget::on_unmap();
}

void SFMLWidget::on_realize()
{
    Gtk::Widget::on_realize();

    if(!m_refGdkWindow)
    {
        //Create the GdkWindow:
        GdkWindowAttr attributes;
        memset(&attributes, 0, sizeof(attributes));

        Gtk::Allocation allocation = get_allocation();

        //Set initial position and size of the Gdk::Window:
        attributes.x = allocation.get_x();
        attributes.y = allocation.get_y();
        attributes.width = allocation.get_width();
        attributes.height = allocation.get_height();

        attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
        attributes.window_type = GDK_WINDOW_CHILD;
        attributes.wclass = GDK_INPUT_OUTPUT;

        m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,
                GDK_WA_X | GDK_WA_Y);
        unset_flags(Gtk::NO_WINDOW);
        set_window(m_refGdkWindow);

        //set colors
        modify_bg(Gtk::STATE_NORMAL , Gdk::Color("red"));
        modify_fg(Gtk::STATE_NORMAL , Gdk::Color("blue"));

        //make the widget receive expose events
        m_refGdkWindow->set_user_data(gobj());

        this->sf::Window::create((GDK_WINDOW_XID(m_refGdkWindow->gobj())));
    }
}

void SFMLWidget::on_unrealize()
{
  m_refGdkWindow.clear();

  //Call base class:
  Gtk::Widget::on_unrealize();
}

bool SFMLWidget::on_expose_event(GdkEventExpose* event)
{
    if(m_refGdkWindow)
    {
        glClearColor(0.25f, 0.25f, 0.25f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        this->display();
    }

    return true;
}

int main(int argc, char* argv[])
{
    Gtk::Main kit(argc, argv); //Initialize Gtk

    Gtk::Window window; //The GTK window will be our top level Window

    //Our RenderWindow will never be below  640x480 (unless we explicitly change it)
    //but it may be more then that
    SFMLWidget ourRenderWindow(sf::VideoMode(640, 480));

    // Doesn't draw the renderWindow but makes it so it will draw when we add it to the window
    ourRenderWindow.show();

    //VBox is a vertical box, we're going to pack our render window and a button in here
    Gtk::VBox ourVBox;

    Gtk::Button ourButton("Hello I do nothing"); //Just a clickable button, it won't be doing anything
    ourButton.show();

    ourVBox.pack_start(ourRenderWindow); //Add ourRenderWindow to the top of the VBox

    //PACK_SHRINK makes the VBox only allocate enough space to show the button and nothing more
    ourVBox.pack_start(ourButton, Gtk::PACK_SHRINK);
    ourVBox.show();

    window.add(ourVBox); //Adds ourVBox to the window so it (and it's children) can be drawn

    Gtk::Main::run(window); //Draw the window
    return 0;
}
<|endoftext|>


<commit_before>#include "window.h"

Window::Window() {
  //gl.out("Created window.\n");
  SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
  if (win == NULL){
    std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
    SDL_Quit();
	}
}

Window::~Window() {
  //gl.out("Closing window.\n");
}
<commit_msg>Deleted window.cpp<commit_after><|endoftext|>


<commit_before>#define UNICODE

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <functional>
#include <tuple>
#include <clocale>
#include <windows.h>

#define MODKEY    VK_NONCONVERT
#define SUBMODKEY VK_LSHIFT

using stdfunc = std::function<void()>;
using wndtype = std::tuple<HWND>;

template <class T>
void print(T str) {
  std::wcout << str << std::endl;
}

/* function declarations */
HWND getHandle();
std::wstring getTitle();
bool start_hook(HINSTANCE, HWND);
bool stop_hook();
void show_taskbar();
void hide_taskbar();
void create_window(HINSTANCE);
void get_all_window();
stdfunc func_switcher(const stdfunc&, const stdfunc&);
stdfunc move_focus(const int);
stdfunc move_window(const int);
void maximize();
void close_window();
void quit();
void tile_layout();
void spiral_layout();

/* variables */
HHOOK hhk;
HWND clientWnd;
std::vector<wndtype> wndList;
std::vector<wndtype>::iterator focusWnd;
std::string layout = "TILE";
static std::map<std::string, void (*)()> arrange = {
  { "TILE",    tile_layout   },
  { "SPIRAL",  spiral_layout }
};
static std::map<std::string, bool> isPressed = {
  { "MOD",     false },
  { "SUBMOD",  false }
};
static std::map<unsigned int, stdfunc> callFunc = {
  { 'J',  func_switcher( move_focus(1),   move_window(2)  )},
  { 'K',  func_switcher( move_focus(-1),  move_window(-2) )},
  { 'M',                 maximize                          },
  { 'D',  func_switcher( []{},            close_window    )},
  { 'Q',                 quit                              }
};

/* function implementations */
HWND getHandle(wndtype wnd) {
  return std::get<0>(wnd);
}

stdfunc func_switcher(const stdfunc& func, const stdfunc& sub_func) {
  return [=] {
    !isPressed["SUBMOD"] ? func() : sub_func();
  };
};

stdfunc move_focus(const int value) {
  return [=] {
    print(value);
  };
};

stdfunc move_window(const int value) {
  return [=] {
    print("move_window");
    print(value);
  };
}

void maximize() {

}

void close_window() {

}

void quit() {
  PostQuitMessage(0);
}

void tile_layout() {

}

void spiral_layout() {

}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  switch (msg) {
    case WM_KEYDOWN: {
      callFunc[wParam]();
      break;
    }
    default:
      return DefWindowProc(hWnd, msg, wParam, lParam);
  }
  return 0;
}

LRESULT CALLBACK LLKeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
  if (code < 0)
    return CallNextHookEx(hhk, code, wParam, lParam);

  if (code == HC_ACTION) {
    KBDLLHOOKSTRUCT* tmp = (KBDLLHOOKSTRUCT*)lParam;
    DWORD vkCode = tmp->vkCode;
    bool isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);

    static auto switch_flag = [&](const std::string name) {
      isPressed[name] = isKeyDown;
      return CallNextHookEx(hhk, code, wParam, lParam);
    };

    if (vkCode == MODKEY)
      switch_flag("MOD");
    else if (vkCode == SUBMODKEY)
      switch_flag("SUBMOD");

    if (isPressed["MOD"] && isKeyDown && callFunc.count(vkCode) == 1)
      PostMessage(clientWnd, WM_KEYDOWN, vkCode, lParam);
  }

  return CallNextHookEx(hhk, code, wParam, lParam);
}

BOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM lParam) {
  if (IsWindowVisible(hWnd)) {
    static wchar_t buf[128];
    std::wstring str;

    GetWindowText(hWnd, buf, 128);
    str = buf;
    if (str == L"")
      return TRUE;

    std::wstring title = str;

    GetClassName(hWnd, buf, 128);
    str = buf;
    if (str == L"Progman" || str == L"MainWindowClass")
      return TRUE;

    print(title);
    print(hWnd);
    print("");

    wndList.push_back(std::make_tuple(hWnd));
  }

  return TRUE;
}

bool start_hook(HINSTANCE hInst) {
  hhk = SetWindowsHookEx(WH_KEYBOARD_LL, LLKeyboardProc, hInst, 0);

  if (hhk == nullptr) {
    MessageBox(nullptr, TEXT("Error in start_hook() : hhk is nullptr"), nullptr, MB_OK);
    return false;
  }

  return true;
}

bool stop_hook() {
  if (UnhookWindowsHookEx(hhk) == 0) {
    MessageBox(nullptr, TEXT("Error in stop_hook()"), nullptr, MB_OK);
    return false;
  }

  return true;
}

void show_taskbar() {
  HWND hTaskBar = FindWindow(TEXT("Shell_TrayWnd"), nullptr);
  HWND hStart = FindWindow(TEXT("Button"), nullptr);
  ShowWindow(hTaskBar, SW_SHOW);
  ShowWindow(hStart, SW_SHOW);
}

void hide_taskbar() {
  HWND hTaskBar = FindWindow(TEXT("Shell_TrayWnd"), nullptr);
  HWND hStart = FindWindow(TEXT("Button"), nullptr);
  ShowWindow(hTaskBar, SW_HIDE);
  ShowWindow(hStart, SW_HIDE);
}

void create_window(HINSTANCE hInstance) {
  WNDCLASSEX wcex;
  auto className = TEXT("WintileClass");

  wcex.cbSize = sizeof(WNDCLASSEX);
  wcex.style = 0;
  wcex.lpfnWndProc = WndProc;
  wcex.cbClsExtra = 0;
  wcex.cbWndExtra = 0;
  wcex.hInstance = hInstance;
  wcex.hIcon = nullptr;
  wcex.hCursor = nullptr;
  wcex.hbrBackground = nullptr;
  wcex.lpszMenuName = nullptr;
  wcex.lpszClassName = className;
  wcex.hIconSm = nullptr;

  if (RegisterClassEx(&wcex) == 0)
    return;

  clientWnd = CreateWindowEx(0, className, TEXT("wintile"), 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);

  if (clientWnd == nullptr)
    return;
}

void get_all_window() {
  EnumWindows(EnumWndProc, (LPARAM)nullptr);
  focusWnd = wndList.begin();
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  MSG msg;

  std::setlocale(LC_ALL, "");
  create_window(hInstance);
  hide_taskbar();
  get_all_window();
  arrange[layout];
  //MoveWindow(getHandle(wndList[2]), 0, 0, 1280, 800, TRUE);
  start_hook(hInstance);

  while (GetMessage(&msg, nullptr, 0, 0) > 0) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  stop_hook();
  show_taskbar();

  return msg.wParam;
}

<commit_msg>WINDOW_WIDTH, HEIGHT<commit_after>#define UNICODE

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <functional>
#include <tuple>
#include <clocale>
#include <windows.h>

#define MODKEY    VK_NONCONVERT
#define SUBMODKEY VK_LSHIFT

using stdfunc = std::function<void()>;
using wndtype = std::tuple<HWND>;

template <class T>
void print(T str) {
  std::wcout << str << std::endl;
}

/* function declarations */
HWND getHandle();
std::wstring getTitle();
bool start_hook(HINSTANCE, HWND);
bool stop_hook();
void show_taskbar();
void hide_taskbar();
void create_window(HINSTANCE);
void get_all_window();
stdfunc func_switcher(const stdfunc&, const stdfunc&);
stdfunc move_focus(const int);
stdfunc move_window(const int);
void maximize();
void close_window();
void quit();
void tile_layout();
void spiral_layout();

/* variables */
HHOOK hhk;
HWND clientWnd;
static const unsigned int WINDOW_WIDTH = GetSystemMetrics(SM_CXSCREEN);
static const unsigned int WINDOW_HEIGHT = GetSystemMetrics(SM_CYSCREEN);
std::vector<wndtype> wndList;
std::vector<wndtype>::iterator focusWnd;
std::string layout = "TILE";
static std::map<std::string, void (*)()> arrange = {
  { "TILE",    tile_layout   },
  { "SPIRAL",  spiral_layout }
};
static std::map<std::string, bool> isPressed = {
  { "MOD",     false },
  { "SUBMOD",  false }
};
static std::map<unsigned int, stdfunc> callFunc = {
  { 'J',  func_switcher( move_focus(1),   move_window(2)  )},
  { 'K',  func_switcher( move_focus(-1),  move_window(-2) )},
  { 'M',                 maximize                          },
  { 'D',  func_switcher( []{},            close_window    )},
  { 'Q',                 quit                              }
};

/* function implementations */
HWND getHandle(wndtype wnd) {
  return std::get<0>(wnd);
}

stdfunc func_switcher(const stdfunc& func, const stdfunc& sub_func) {
  return [=] {
    !isPressed["SUBMOD"] ? func() : sub_func();
  };
};

stdfunc move_focus(const int value) {
  return [=] {
    print(value);
  };
};

stdfunc move_window(const int value) {
  return [=] {
    print("move_window");
    print(value);
  };
}

void maximize() {

}

void close_window() {

}

void quit() {
  PostQuitMessage(0);
}

void tile_layout() {

}

void spiral_layout() {

}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  switch (msg) {
    case WM_KEYDOWN: {
      callFunc[wParam]();
      break;
    }
    default:
      return DefWindowProc(hWnd, msg, wParam, lParam);
  }
  return 0;
}

LRESULT CALLBACK LLKeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
  if (code < 0)
    return CallNextHookEx(hhk, code, wParam, lParam);

  if (code == HC_ACTION) {
    KBDLLHOOKSTRUCT* tmp = (KBDLLHOOKSTRUCT*)lParam;
    DWORD vkCode = tmp->vkCode;
    bool isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);

    static auto switch_flag = [&](const std::string name) {
      isPressed[name] = isKeyDown;
      return CallNextHookEx(hhk, code, wParam, lParam);
    };

    if (vkCode == MODKEY)
      switch_flag("MOD");
    else if (vkCode == SUBMODKEY)
      switch_flag("SUBMOD");

    if (isPressed["MOD"] && isKeyDown && callFunc.count(vkCode) == 1)
      PostMessage(clientWnd, WM_KEYDOWN, vkCode, lParam);
  }

  return CallNextHookEx(hhk, code, wParam, lParam);
}

BOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM lParam) {
  if (IsWindowVisible(hWnd)) {
    static wchar_t buf[128];
    std::wstring str;

    GetWindowText(hWnd, buf, 128);
    str = buf;
    if (str == L"")
      return TRUE;

    std::wstring title = str;

    GetClassName(hWnd, buf, 128);
    str = buf;
    if (str == L"Progman" || str == L"MainWindowClass")
      return TRUE;

    print(title);
    print(hWnd);
    print("");

    wndList.push_back(std::make_tuple(hWnd));
  }

  return TRUE;
}

bool start_hook(HINSTANCE hInst) {
  hhk = SetWindowsHookEx(WH_KEYBOARD_LL, LLKeyboardProc, hInst, 0);

  if (hhk == nullptr) {
    MessageBox(nullptr, TEXT("Error in start_hook() : hhk is nullptr"), nullptr, MB_OK);
    return false;
  }

  return true;
}

bool stop_hook() {
  if (UnhookWindowsHookEx(hhk) == 0) {
    MessageBox(nullptr, TEXT("Error in stop_hook()"), nullptr, MB_OK);
    return false;
  }

  return true;
}

void show_taskbar() {
  HWND hTaskBar = FindWindow(TEXT("Shell_TrayWnd"), nullptr);
  HWND hStart = FindWindow(TEXT("Button"), nullptr);
  ShowWindow(hTaskBar, SW_SHOW);
  ShowWindow(hStart, SW_SHOW);
}

void hide_taskbar() {
  HWND hTaskBar = FindWindow(TEXT("Shell_TrayWnd"), nullptr);
  HWND hStart = FindWindow(TEXT("Button"), nullptr);
  ShowWindow(hTaskBar, SW_HIDE);
  ShowWindow(hStart, SW_HIDE);
}

void create_window(HINSTANCE hInstance) {
  WNDCLASSEX wcex;
  auto className = TEXT("WintileClass");

  wcex.cbSize = sizeof(WNDCLASSEX);
  wcex.style = 0;
  wcex.lpfnWndProc = WndProc;
  wcex.cbClsExtra = 0;
  wcex.cbWndExtra = 0;
  wcex.hInstance = hInstance;
  wcex.hIcon = nullptr;
  wcex.hCursor = nullptr;
  wcex.hbrBackground = nullptr;
  wcex.lpszMenuName = nullptr;
  wcex.lpszClassName = className;
  wcex.hIconSm = nullptr;

  if (RegisterClassEx(&wcex) == 0)
    return;

  clientWnd = CreateWindowEx(0, className, TEXT("wintile"), 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);

  if (clientWnd == nullptr)
    return;
}

void get_all_window() {
  EnumWindows(EnumWndProc, (LPARAM)nullptr);
  focusWnd = wndList.begin();
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  MSG msg;

  std::setlocale(LC_ALL, "");
  create_window(hInstance);
  hide_taskbar();
  get_all_window();
  arrange[layout];
  //MoveWindow(getHandle(wndList[2]), 0, 0, 1280, 800, TRUE);
  start_hook(hInstance);

  while (GetMessage(&msg, nullptr, 0, 0) > 0) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  stop_hook();
  show_taskbar();

  return msg.wParam;
}

<|endoftext|>


<commit_before>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t count) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	unsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = buf[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad), PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t count) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char result[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char result[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char result[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<commit_msg>added heap stuff<commit_after>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t count) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	unsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = buf[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad), PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t count) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			delete[] mac;
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
		delete[] mac;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char result[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char result[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char* result = new char[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014, Alberto Corona <alberto@0x1a.us>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <dirent.h>
#include <fstream>
#include <yaml.h>
#include "parser.h"

Parser::Parser() {};
Parser::~Parser() {};

int Parser::OpenConfig(const char *build_file)
{
	if (AssertYML(build_file) == 1) {
		conf = fopen(build_file, "r");
		ParseConfig();
		ReadValues();
		CloseConfig();
		return 1;
	} else {
		return -1;
	}
	return 0;
}

int Parser::ParseConfig()
{
	if (conf != NULL) {
		yaml_parser_initialize(&parser);
		yaml_parser_set_input_file(&parser, conf);
		return 1;
	}
	return 0;
}

int Parser::CloseConfig()
{
	if ((&parser != NULL) && (conf != NULL)) {
		yaml_parser_delete(&parser);
		fclose(conf);
		return 1;
	} else {
		return -1;
	}
	return 0;
}

int Parser::AssertYML(const char *build_file)
{
	const char *ext;
	ext = strrchr(build_file, '.');
	if (opendir(build_file) != NULL) {
		printf("Error: %s is a directory\n", build_file);
		return -3;
	}
	if (!ext) {
		printf("Error: %s has no extension\n", build_file);
		return -1;
	}
	if ((strcmp(ext + 1, "yml") == 0) || (strcmp(ext + 1, "yaml") == 0) || (strcmp(ext + 1, "ybf") == 0)) {
		return 1;
	} else {
		printf("Error: %s is not a valid build file\n", build_file);
		return -2;
	}
	return 0;
}

int Parser::ReadValues()
{
	do {
		yaml_parser_scan(&parser, &token);
		switch (token.type) {
		case YAML_VERSION_DIRECTIVE_TOKEN:
			break;
		case YAML_NO_TOKEN:
			printf("No token\n");
			break;
		case YAML_STREAM_START_TOKEN:
			printf("Stream start\n");
			break;
		case YAML_STREAM_END_TOKEN:
			printf("Stream end\n");
			break;
		case YAML_KEY_TOKEN:
			printf("\tKey token: ");
			break;
		case YAML_VALUE_TOKEN:
			printf("\t\tValue token: ");
			break;
		case YAML_TAG_DIRECTIVE_TOKEN:
			printf("Tag directive: %s\n", token.data.scalar.value);
			break;
		case YAML_DOCUMENT_START_TOKEN:
			printf("Document start\n");
			break;
		case YAML_DOCUMENT_END_TOKEN:
			printf("Document end\n");
			break;
		case YAML_BLOCK_SEQUENCE_START_TOKEN:
			printf("Block sequence start\n");
			break;
		case YAML_BLOCK_END_TOKEN:
			printf("Block sequence end\n");
			break;
		case YAML_BLOCK_MAPPING_START_TOKEN:
			printf("Block Mapping start\n");
			break;
		case YAML_FLOW_SEQUENCE_START_TOKEN:
			printf("Sequence start\n");
			break;
		case YAML_FLOW_SEQUENCE_END_TOKEN:
			printf("Sequence end\n");
			break;
		case YAML_FLOW_MAPPING_START_TOKEN:
			printf("Mapping start\n");
			break;
		case YAML_FLOW_MAPPING_END_TOKEN:
			printf("Mapping end\n");
			break;
		case YAML_BLOCK_ENTRY_TOKEN:
			printf("Block entry\n");
			break;
		case YAML_FLOW_ENTRY_TOKEN:
			printf("Block entry token: %s\n", token.data.scalar.value);
			break;
		case YAML_ALIAS_TOKEN:
			printf("Alias token: %s\n", token.data.scalar.value);
			break;
		case YAML_ANCHOR_TOKEN:
			printf("Anchor token: %s\n", token.data.scalar.value);
			break;
		case YAML_TAG_TOKEN:
			printf("Tag token: %s\n", token.data.scalar.value);
			break;
		case YAML_SCALAR_TOKEN:
			printf("%s\n", token.data.scalar.value);
			break;
		}
	} while (token.type != YAML_STREAM_END_TOKEN);
	yaml_token_delete(&token);
	return 0;
}
<commit_msg>parser: fix opening a non-existing file<commit_after>/*
 * Copyright (c) 2013-2014, Alberto Corona <alberto@0x1a.us>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <dirent.h>
#include <fstream>
#include <yaml.h>
#include "parser.h"

Parser::Parser() {};
Parser::~Parser() {};

int Parser::OpenConfig(const char *build_file)
{
	if (AssertYML(build_file) == 1) {
		conf = fopen(build_file, "r");
		if (conf == NULL) {
			printf("Error: No file named %s\n", build_file);
			return -2;
		}
		ParseConfig();
		ReadValues();
		CloseConfig();
		return 1;
	} else {
		return -1;
	}
	return 0;
}

int Parser::ParseConfig()
{
	if (conf != NULL) {
		yaml_parser_initialize(&parser);
		yaml_parser_set_input_file(&parser, conf);
		return 1;
	}
	return 0;
}

int Parser::CloseConfig()
{
	if ((&parser != NULL) && (conf != NULL)) {
		yaml_parser_delete(&parser);
		fclose(conf);
		return 1;
	} else {
		return -1;
	}
	return 0;
}

int Parser::AssertYML(const char *build_file)
{
	const char *ext;
	ext = strrchr(build_file, '.');
	if (opendir(build_file) != NULL) {
		printf("Error: %s is a directory\n", build_file);
		return -3;
	}
	if (!ext) {
		printf("Error: %s has no extension\n", build_file);
		return -1;
	}
	if ((strcmp(ext + 1, "yml") == 0) || (strcmp(ext + 1, "yaml") == 0) || (strcmp(ext + 1, "ybf") == 0)) {
		return 1;
	} else {
		printf("Error: %s is not a valid build file\n", build_file);
		return -2;
	}
	return 0;
}

int Parser::ReadValues()
{
	do {
		yaml_parser_scan(&parser, &token);
		switch (token.type) {
		case YAML_VERSION_DIRECTIVE_TOKEN:
			break;
		case YAML_NO_TOKEN:
			printf("No token\n");
			break;
		case YAML_STREAM_START_TOKEN:
			printf("Stream start\n");
			break;
		case YAML_STREAM_END_TOKEN:
			printf("Stream end\n");
			break;
		case YAML_KEY_TOKEN:
			printf("\tKey token: ");
			break;
		case YAML_VALUE_TOKEN:
			printf("\t\tValue token: ");
			break;
		case YAML_TAG_DIRECTIVE_TOKEN:
			printf("Tag directive: %s\n", token.data.scalar.value);
			break;
		case YAML_DOCUMENT_START_TOKEN:
			printf("Document start\n");
			break;
		case YAML_DOCUMENT_END_TOKEN:
			printf("Document end\n");
			break;
		case YAML_BLOCK_SEQUENCE_START_TOKEN:
			printf("Block sequence start\n");
			break;
		case YAML_BLOCK_END_TOKEN:
			printf("Block sequence end\n");
			break;
		case YAML_BLOCK_MAPPING_START_TOKEN:
			printf("Block Mapping start\n");
			break;
		case YAML_FLOW_SEQUENCE_START_TOKEN:
			printf("Sequence start\n");
			break;
		case YAML_FLOW_SEQUENCE_END_TOKEN:
			printf("Sequence end\n");
			break;
		case YAML_FLOW_MAPPING_START_TOKEN:
			printf("Mapping start\n");
			break;
		case YAML_FLOW_MAPPING_END_TOKEN:
			printf("Mapping end\n");
			break;
		case YAML_BLOCK_ENTRY_TOKEN:
			printf("Block entry\n");
			break;
		case YAML_FLOW_ENTRY_TOKEN:
			printf("Block entry token: %s\n", token.data.scalar.value);
			break;
		case YAML_ALIAS_TOKEN:
			printf("Alias token: %s\n", token.data.scalar.value);
			break;
		case YAML_ANCHOR_TOKEN:
			printf("Anchor token: %s\n", token.data.scalar.value);
			break;
		case YAML_TAG_TOKEN:
			printf("Tag token: %s\n", token.data.scalar.value);
			break;
		case YAML_SCALAR_TOKEN:
			printf("%s\n", token.data.scalar.value);
			break;
		}
	} while (token.type != YAML_STREAM_END_TOKEN);
	yaml_token_delete(&token);
	return 0;
}
<|endoftext|>


<commit_before>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#include "PELConfig.h"

#include <boost/program_options.hpp>
#include <boost/tuple/tuple.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include <cstdlib>
#include "pelmap.h"
#include "logic/el_syntax.h"
#include "logic/folparser.h"
#include "logic/domain.h"
#include "log.h"
#include "logic/moves.h"
#include "logic/maxwalksat.h"
#include "logic/unit_prop.h"

// TODO: pelmap is the exe name?  probably should rename this.

int main(int argc, char* argv[]) {
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help", "produce help message")
	    ("version,v", "print version and exit")
	    ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
	    ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
	    ("evalModel,e", "simply print the model weight of the facts file")
	    ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
	    ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
	    ("output,o", po::value<std::string>(), "output model file")
	    ("unitProp,u", "perform unit propagation only and exit")
	;

	po::options_description hidden("Hidden options");
	hidden.add_options()
		("facts-file", po::value<std::string>(), "facts file")
		("formula-file", po::value<std::string>(), "formula file")
	;
	po::positional_options_description p;
	p.add("facts-file", 1);
	p.add("formula-file", 1);

	po::options_description cmdline_options;
	cmdline_options.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
	po::notify(vm);

	if (vm.count("version")) {
		std::cout << "pelmap version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl;
		return EXIT_SUCCESS;
	}

	if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
	    std::cout << "Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
		std::cout << desc << std::endl;
	    return EXIT_FAILURE;
	}

	// setup our logging facilities
	FILE* debugFile = fopen("debug.log", "w");
	if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
	else FilePolicy::stream() = debugFile;
	FileLog::globalLogLevel() = LOG_DEBUG;

	LOG(LOG_INFO) << "Opened log file for new session";

	// make sure we can open the output model file, if specified
	FILE* outputFile = NULL;
	if (vm.count("output")) {
		outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
		if (!outputFile) {
			std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
			return EXIT_FAILURE;
		}
	}

	boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
	if (vm.count("max") || vm.count("min")) {
		Interval maxInt = d->maxInterval();
		if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
		if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
		d->setMaxInterval(maxInt);
	}

	Model model = d->defaultModel();

	LOG_PRINT(LOG_INFO) << "model size: " << model.size();
	LOG(LOG_DEBUG) << "observation predicates: ";
	for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin();
			it != d->observedPredicates().end();
			it++) {
		LOG(LOG_DEBUG) << "\t" << it->first;
	}

	if (vm.count("evalModel")) {
		LOG(LOG_INFO) << "evaluating model...";
		unsigned long sum = 0;
		// evaluate the weight of each formula in the domain
		for(FormulaList::const_iterator it = d->formulas().begin(); it != d->formulas().end(); it++) {
			ELSentence formula = *it;
			SISet satisfied = d->satisfied(*(formula.sentence()), model);
			unsigned long weight = d->score(formula, model);
			sum += weight;
			LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
			LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
			LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
		}
		LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
	} else if (vm.count("unitProp")) {
	    doUnitProp(d);
	} else {
		double p = vm["prob"].as<double>();
		unsigned int iterations = vm["iterations"].as<unsigned int>();

		LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
		Model defModel = d->defaultModel();
		Model maxModel = maxWalkSat(*d, iterations, p, &defModel);
		LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
		LOG_PRINT(LOG_INFO) << maxModel.toString();
		if (vm.count("output")) {
			// log it to the output file as well
			fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
					vm["facts-file"].as<std::string>().c_str(),
					vm["formula-file"].as<std::string>().c_str());
			std::string timeStr;
			{
				time_t rawtime;
				struct tm * timeinfo;
				time (&rawtime);
				timeinfo = localtime (&rawtime);
				timeStr = asctime(timeinfo);
			}
			fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
			fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
					iterations,
					p);
			fputs(maxModel.toString().c_str(), outputFile);
		}
	}

	// Should be good and close files?
	return EXIT_SUCCESS;
}

namespace {
void doUnitProp(boost::shared_ptr<Domain>& d) {
    LOG(LOG_INFO) << "performing unit propagation...";
    QCNFClauseList clauses = convertToQCNFClauseList(d->formulas());
    if (!d->assumeClosedWorld()) {
        LOG(LOG_ERROR) << "doUnitProp(): cannot be called on a domain that is not a closed world - this code needs to be rewritten!";
        return;
    }
}
}
<commit_msg>some debugging code written for unit prop<commit_after>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#include "PELConfig.h"

#include <boost/program_options.hpp>
#include <boost/tuple/tuple.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include <cstdlib>
#include "pelmap.h"
#include "logic/el_syntax.h"
#include "logic/folparser.h"
#include "logic/domain.h"
#include "log.h"
#include "logic/moves.h"
#include "logic/maxwalksat.h"
#include "logic/unit_prop.h"

// TODO: pelmap is the exe name?  probably should rename this.

int main(int argc, char* argv[]) {
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help", "produce help message")
	    ("version,v", "print version and exit")
	    ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
	    ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
	    ("evalModel,e", "simply print the model weight of the facts file")
	    ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
	    ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
	    ("output,o", po::value<std::string>(), "output model file")
	    ("unitProp,u", "perform unit propagation only and exit")
	;

	po::options_description hidden("Hidden options");
	hidden.add_options()
		("facts-file", po::value<std::string>(), "facts file")
		("formula-file", po::value<std::string>(), "formula file")
	;
	po::positional_options_description p;
	p.add("facts-file", 1);
	p.add("formula-file", 1);

	po::options_description cmdline_options;
	cmdline_options.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
	po::notify(vm);

	if (vm.count("version")) {
		std::cout << "pelmap version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl;
		return EXIT_SUCCESS;
	}

	if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
	    std::cout << "Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
		std::cout << desc << std::endl;
	    return EXIT_FAILURE;
	}

	// setup our logging facilities
	FILE* debugFile = fopen("debug.log", "w");
	if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
	else FilePolicy::stream() = debugFile;
	FileLog::globalLogLevel() = LOG_DEBUG;

	LOG(LOG_INFO) << "Opened log file for new session";

	// make sure we can open the output model file, if specified
	FILE* outputFile = NULL;
	if (vm.count("output")) {
		outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
		if (!outputFile) {
			std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
			return EXIT_FAILURE;
		}
	}

	boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
	if (vm.count("max") || vm.count("min")) {
		Interval maxInt = d->maxInterval();
		if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
		if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
		d->setMaxInterval(maxInt);
	}

	Model model = d->defaultModel();

	LOG_PRINT(LOG_INFO) << "model size: " << model.size();
	LOG(LOG_DEBUG) << "observation predicates: ";
	for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin();
			it != d->observedPredicates().end();
			it++) {
		LOG(LOG_DEBUG) << "\t" << it->first;
	}

	if (vm.count("evalModel")) {
		LOG(LOG_INFO) << "evaluating model...";
		unsigned long sum = 0;
		// evaluate the weight of each formula in the domain
		for(FormulaList::const_iterator it = d->formulas().begin(); it != d->formulas().end(); it++) {
			ELSentence formula = *it;
			SISet satisfied = d->satisfied(*(formula.sentence()), model);
			unsigned long weight = d->score(formula, model);
			sum += weight;
			LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
			LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
			LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
		}
		LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
	} else if (vm.count("unitProp")) {
	    doUnitProp(d);
	} else {
		double p = vm["prob"].as<double>();
		unsigned int iterations = vm["iterations"].as<unsigned int>();

		LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
		Model defModel = d->defaultModel();
		Model maxModel = maxWalkSat(*d, iterations, p, &defModel);
		LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
		LOG_PRINT(LOG_INFO) << maxModel.toString();
		if (vm.count("output")) {
			// log it to the output file as well
			fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
					vm["facts-file"].as<std::string>().c_str(),
					vm["formula-file"].as<std::string>().c_str());
			std::string timeStr;
			{
				time_t rawtime;
				struct tm * timeinfo;
				time (&rawtime);
				timeinfo = localtime (&rawtime);
				timeStr = asctime(timeinfo);
			}
			fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
			fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
					iterations,
					p);
			fputs(maxModel.toString().c_str(), outputFile);
		}
	}

	// Should be good and close files?
	return EXIT_SUCCESS;
}

namespace {
void doUnitProp(boost::shared_ptr<Domain>& d) {
    LOG(LOG_INFO) << "performing unit propagation...";
    FormulaList formulas = d->formulas();

    // add quantification to any formulas that may be missing them
    for (FormulaList::iterator it = formulas.begin(); it != formulas.end(); it++) {
        if (!it->isQuantified()) {
            SISet everywhere(false, d->maxInterval());
            everywhere.add(d->maxSpanInterval());
            it->setQuantification(everywhere);
        }
    }
    QCNFClauseList clauses = convertToQCNFClauseList(formulas);

    if (!d->assumeClosedWorld()) {
        LOG(LOG_ERROR) << "doUnitProp(): cannot be called on a domain that is not a closed world - this code needs to be rewritten!";
        return;
    }
    // convert all the facts into unit clauses
    Model obs = d->defaultModel();
    std::set<Atom, atomcmp> atoms = obs.atoms();

    for (std::set<Atom>::const_iterator it = atoms.begin(); it != atoms.end(); it++) {
        SISet trueAt = obs.getAtom(*it);
        SISet falseAt = trueAt.compliment();

        // TODO: why make a copy?  we should have the original shared_ptr
        boost::shared_ptr<Sentence> atomTrue(new Atom(*it));
        boost::shared_ptr<Sentence> atomFalse(new Negation(atomTrue));
        CNFClause a, b;
        a.push_back(atomTrue);
        b.push_back(atomFalse);
        QCNFClause c, d;
        c.first = a;
        d.first = b;
        c.second = trueAt;
        d.second = falseAt;

        if (c.second.size() != 0) clauses.push_back(c);
        if (d.second.size() != 0) clauses.push_back(d);
    }

    for (QCNFClauseList::iterator it = clauses.begin(); it != clauses.end(); it++) {
        std::cout << "clause: ";
        for (CNFClause::iterator it2 = it->first.begin(); it2 != it->first.end(); it2++) {
            if (it2 != it->first.begin()) std::cout << ", ";
            std::cout << (*it2)->toString();
        }
        std::cout << " @ " << it->second.toString() << std::endl;
    }

    QUnitsFormulasPair reducedList = performUnitPropagation(clauses);
    std::cout << "unit prop performed, now we have:" << std::endl;
}
}
<|endoftext|>


<commit_before>#include "worker.h"
#include <QTextStream>
#include <QDebug>

Worker::Worker(QObject *parent) : QObject(parent){
    giFileSize = 0;
}

void Worker::worker_slot_loadFile(QFile *file)
{
    //qDebug() << "Begin worker_slot_loadFile, file: " << file->fileName();

    QString line = "";
    QString text = "";
    QTextStream in(file);
    while (!in.atEnd()) {
      line = in.readLine();
      text.append(line + "\n");
    }
    in.flush();
    file->close();
    text.remove(text.lastIndexOf("\n"),1);
    emit worker_signal_appendText(text);

    //qDebug() << "End worker_slot_loadFile";
}

void Worker::worker_slot_tailFile(QFile *file)
{
    if(file->size() > giFileSize) {
        int liDiff = file->size() - giFileSize;
        if(file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            if(file->seek(giFileSize)) {
                QString lsText = QString(file->read(liDiff));
                emit worker_signal_insertText(lsText);
                giFileSize = file->size();
            }
            file->close();
        }
    } else {
        giFileSize = file->size();
    }
}

void Worker::worker_slot_setCurrentFileSize(int aiFileSize)
{
    this->giFileSize = aiFileSize;
}

<commit_msg>Deleted comments<commit_after>#include "worker.h"
#include <QTextStream>
#include <QDebug>

Worker::Worker(QObject *parent) : QObject(parent){
    giFileSize = 0;
}

void Worker::worker_slot_loadFile(QFile *file)
{
    QString line = "";
    QString text = "";
    QTextStream in(file);
    while (!in.atEnd()) {
      line = in.readLine();
      text.append(line + "\n");
    }
    in.flush();
    file->close();
    text.remove(text.lastIndexOf("\n"),1);
    emit worker_signal_appendText(text);
}

void Worker::worker_slot_tailFile(QFile *file)
{
    if(file->size() > giFileSize) {
        int liDiff = file->size() - giFileSize;
        if(file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            if(file->seek(giFileSize)) {
                QString lsText = QString(file->read(liDiff));
                emit worker_signal_insertText(lsText);
                giFileSize = file->size();
            }
            file->close();
        }
    } else {
        giFileSize = file->size();
    }
}

void Worker::worker_slot_setCurrentFileSize(int aiFileSize)
{
    this->giFileSize = aiFileSize;
}

<|endoftext|>