<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlideSorterModule.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 15:54:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "SlideSorterModule.hxx"

#include "framework/FrameworkHelper.hxx"

#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XTABBAR_HPP_
#include <com/sun/star/drawing/framework/XTabBar.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_TABBARBUTTON_HPP_
#include <com/sun/star/drawing/framework/TabBarButton.hpp>
#endif

#include "strings.hrc"
#include "sdresid.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;

using ::rtl::OUString;
using ::sd::framework::FrameworkHelper;

namespace sd { namespace framework {

//===== SlideSorterModule ==================================================

SlideSorterModule::SlideSorterModule (
    const Reference<frame::XController>& rxController,
    const OUString& rsLeftPaneURL)
    : ResourceManager(rxController,
        FrameworkHelper::CreateResourceId(FrameworkHelper::msSlideSorterURL, rsLeftPaneURL)),
      mxViewTabBarId(FrameworkHelper::CreateResourceId(
          FrameworkHelper::msViewTabBarURL,
          FrameworkHelper::msCenterPaneURL)),
      mxControllerManager(rxController,UNO_QUERY)
{
    if (mxConfigurationController.is())
    {
        UpdateViewTabBar();

        AddActiveMainView(FrameworkHelper::msImpressViewURL);
        AddActiveMainView(FrameworkHelper::msOutlineViewURL);
        AddActiveMainView(FrameworkHelper::msNotesViewURL);

        AddActiveMainView(FrameworkHelper::msDrawViewURL);

        mxConfigurationController->addConfigurationChangeListener(
            this,
            FrameworkHelper::msResourceActivationEvent,
            Any());
    }
}

SlideSorterModule::~SlideSorterModule (void)
{
}

void SAL_CALL SlideSorterModule::notifyConfigurationChange (
    const ConfigurationChangeEvent& rEvent)
    throw (RuntimeException)
{
    if (rEvent.Type.equals(FrameworkHelper::msResourceActivationEvent))
    {
        if (rEvent.ResourceId->compareTo(mxViewTabBarId) == 0)
        {
            // Update the view tab bar because the view tab bar has just
            // become active.
            UpdateViewTabBar();
        }
        else if (rEvent.ResourceId->getResourceTypePrefix().equals(
            FrameworkHelper::msViewURLPrefix)
            && rEvent.ResourceId->isBoundTo(
                FrameworkHelper::CreateResourceId(FrameworkHelper::msCenterPaneURL),
                AnchorBindingMode_DIRECT))
        {
            // Update the view tab bar because the view in the center pane
            // has changed.
            UpdateViewTabBar();
        }
    }
    else
    {
        ResourceManager::notifyConfigurationChange(rEvent);
    }
}

void SlideSorterModule::UpdateViewTabBar (void)
{
    Reference<XToolBarController> xToolBarController;
    if (mxControllerManager.is())
        xToolBarController = mxControllerManager->getToolBarController();
    if (xToolBarController.is())
    {
        Reference<XTabBar> xBar (
            xToolBarController->getToolBar(mxViewTabBarId),
            UNO_QUERY);
        if (xBar.is())
        {
            TabBarButton aButtonA;
            aButtonA.ResourceId = FrameworkHelper::CreateResourceId(
                FrameworkHelper::msSlideSorterURL,
                FrameworkHelper::msCenterPaneURL);
            aButtonA.ButtonLabel = String(SdResId(STR_SLIDE_MODE));

            TabBarButton aButtonB;
            aButtonB.ResourceId = FrameworkHelper::CreateResourceId(
                FrameworkHelper::msHandoutViewURL,
                FrameworkHelper::msCenterPaneURL);

            if ( ! xBar->hasTabBarButton(aButtonA))
                xBar->addTabBarButtonAfter(aButtonA, aButtonB);
        }
    }
}

} } // end of namespace sd::framework
<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007/06/19 08:25:55 af 1.2.22.1: #i18486# Use the resource object provided by an event to improve behaviour during configuration update<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlideSorterModule.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 13:40:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "SlideSorterModule.hxx"

#include "framework/FrameworkHelper.hxx"

#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XTABBAR_HPP_
#include <com/sun/star/drawing/framework/XTabBar.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_TABBARBUTTON_HPP_
#include <com/sun/star/drawing/framework/TabBarButton.hpp>
#endif

#include "strings.hrc"
#include "sdresid.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;

using ::rtl::OUString;
using ::sd::framework::FrameworkHelper;

namespace sd { namespace framework {

//===== SlideSorterModule ==================================================

SlideSorterModule::SlideSorterModule (
    const Reference<frame::XController>& rxController,
    const OUString& rsLeftPaneURL)
    : ResourceManager(rxController,
        FrameworkHelper::CreateResourceId(FrameworkHelper::msSlideSorterURL, rsLeftPaneURL)),
      mxViewTabBarId(FrameworkHelper::CreateResourceId(
          FrameworkHelper::msViewTabBarURL,
          FrameworkHelper::msCenterPaneURL)),
      mxControllerManager(rxController,UNO_QUERY)
{
    if (mxConfigurationController.is())
    {
        UpdateViewTabBar(NULL);

        AddActiveMainView(FrameworkHelper::msImpressViewURL);
        AddActiveMainView(FrameworkHelper::msOutlineViewURL);
        AddActiveMainView(FrameworkHelper::msNotesViewURL);

        AddActiveMainView(FrameworkHelper::msDrawViewURL);

        mxConfigurationController->addConfigurationChangeListener(
            this,
            FrameworkHelper::msResourceActivationEvent,
            Any());
    }
}

SlideSorterModule::~SlideSorterModule (void)
{
}

void SAL_CALL SlideSorterModule::notifyConfigurationChange (
    const ConfigurationChangeEvent& rEvent)
    throw (RuntimeException)
{
    if (rEvent.Type.equals(FrameworkHelper::msResourceActivationEvent))
    {
        if (rEvent.ResourceId->compareTo(mxViewTabBarId) == 0)
        {
            // Update the view tab bar because the view tab bar has just
            // become active.
            UpdateViewTabBar(Reference<XTabBar>(rEvent.ResourceObject,UNO_QUERY));
        }
        else if (rEvent.ResourceId->getResourceTypePrefix().equals(
            FrameworkHelper::msViewURLPrefix)
            && rEvent.ResourceId->isBoundTo(
                FrameworkHelper::CreateResourceId(FrameworkHelper::msCenterPaneURL),
                AnchorBindingMode_DIRECT))
        {
            // Update the view tab bar because the view in the center pane
            // has changed.
            UpdateViewTabBar(NULL);
        }
    }
    else
    {
        ResourceManager::notifyConfigurationChange(rEvent);
    }
}

void SlideSorterModule::UpdateViewTabBar (const Reference<XTabBar>& rxTabBar)
{
    if ( ! mxControllerManager.is())
        return;

    Reference<XTabBar> xBar (rxTabBar);
    if ( ! xBar.is())
    {
        Reference<XConfigurationController> xCC (
            mxControllerManager->getConfigurationController());
        if (xCC.is())
            xBar = Reference<XTabBar>(xCC->getResource(mxViewTabBarId), UNO_QUERY);
    }

    if (xBar.is())
    {
        TabBarButton aButtonA;
        aButtonA.ResourceId = FrameworkHelper::CreateResourceId(
            FrameworkHelper::msSlideSorterURL,
            FrameworkHelper::msCenterPaneURL);
        aButtonA.ButtonLabel = String(SdResId(STR_SLIDE_MODE));

        TabBarButton aButtonB;
        aButtonB.ResourceId = FrameworkHelper::CreateResourceId(
            FrameworkHelper::msHandoutViewURL,
            FrameworkHelper::msCenterPaneURL);

        if ( ! xBar->hasTabBarButton(aButtonA))
            xBar->addTabBarButtonAfter(aButtonA, aButtonB);
    }
}

} } // end of namespace sd::framework
<|endoftext|>


<commit_before>// Keys.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2001 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//$Id$

#include "Keys.hh"

#include "FbTk/StringUtil.hh"
#include "FbTk/App.hh"
#include "FbTk/Command.hh"

#include "CommandParser.hh"
#include "FbTk/I18n.hh"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif	// HAVE_CTYPE_H

#ifdef HAVE_CSTDIO
  #include <cstdio>
#else
  #include <stdio.h>
#endif
#ifdef HAVE_CSTDLIB
  #include <cstdlib>
#else
  #include <stdlib.h>
#endif
#ifdef HAVE_CERRNO
  #include <cerrno>
#else
  #include <errno.h>
#endif
#ifdef HAVE_CSTRING
  #include <cstring>
#else
  #include <string.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif	// HAVE_SYS_TYPES_H

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif	// HAVE_SYS_WAIT_H

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif	// HAVE_UNISTD_H

#ifdef	HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif	// HAVE_SYS_STAT_H

#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>

#include <iostream>
#include <fstream>
#include <vector>
#ifdef HAVE_CASSERT
  #include <cassert>
#else
  #include <assert.h>
#endif
#include <memory>

using namespace std;

Keys::Keys(const char *filename):
    m_display(FbTk::App::instance()->display())
{

    if (filename != 0)
        load(filename);
}

Keys::~Keys() {

    FbTk::KeyUtil::ungrabKeys();
    deleteTree();
}

/// Destroys the keytree
void Keys::deleteTree() {
    while (!m_keylist.empty()) {
        if (m_keylist.back())
            delete m_keylist.back();
        m_keylist.pop_back();
    }
}

/**
    Load and grab keys
    TODO: error checking
    @return true on success else false
*/
bool Keys::load(const char *filename) {
    if (!filename)
        return false;

    //ungrab all keys
    FbTk::KeyUtil::ungrabKeys();

    //free memory of previous grabs
    deleteTree();

    FbTk::App::instance()->sync(false);

    //open the file
    ifstream infile(filename);
    if (!infile)
        return false; // faild to open file

    m_current_line = 0;//current line, so we can tell the user where the fault is

    while (!infile.eof()) {
        string linebuffer;

        getline(infile, linebuffer);

        m_current_line++;

        addBinding(linebuffer);
    } // end while eof

    m_current_line = 0;
    m_filename = filename;
    return true;
}

bool Keys::save(const char *filename) const {
    //!!
    //!! TODO: fix keybinding saving
    //!! (we probably need to save key actions
    //!! as strings instead of creating new Commands)

    // open file for writing
    //    ofstream outfile(filename);
    //    if (!outfile)
    return false;
    //    return true;
}

bool Keys::addBinding(const std::string &linebuffer) {

    vector<string> val;
    // Parse arguments
    FbTk::StringUtil::stringtok(val, linebuffer.c_str());

    // must have at least 1 argument
    if (val.size() <= 0)
        return true; // empty lines are valid.

    if (val[0][0] == '#' || val[0][0] == '!' ) //the line is commented
        return true; // still a valid line.

    unsigned int key = 0, mod = 0;
    char keyarg = 0;
    t_key *current_key=0, *last_key=0;

    _FB_USES_NLS;
    // for each argument
    for (size_t argc = 0; argc < val.size(); argc++) {

        if (val[argc][0] != ':') { // parse key(s)
            keyarg++;
            if (keyarg==1) //first arg is modifier
                mod = FbTk::KeyUtil::getModifier(val[argc].c_str());
            else if (keyarg > 1) {

                int tmpmod = FbTk::KeyUtil::getModifier(val[argc].c_str());
                if(tmpmod)
                    mod |= tmpmod; //If it's a modifier
                else {
                    // keycode covers the following three two-byte cases:
                    // 0x       - hex
                    // +[1-9]   - number between +1 and +9
                    // numbers 10 and above
                    //
                    if (val[argc].size() > 1 && (isdigit(val[argc][0]) &&
                                                 (isdigit(val[argc][1]) || val[argc][1] == 'x') ||
                                                 val[argc][0] == '+' && isdigit(val[argc][1])) ) {

                        key = strtoul(val[argc].c_str(), NULL, 0);

                        if (errno == EINVAL || errno == ERANGE)
                            key = 0;

                    } else // convert from string symbol
                        key = FbTk::KeyUtil::getKey(val[argc].c_str());

                    if (key == 0) {
                        cerr<<_FBTEXT(Keys, InvalidKeyMod,
                                      "Keys: Invalid key/modifier on line",
                                      "A bad key/modifier string was found on line (number following)")<<" "<<
                            m_current_line<<"): "<<linebuffer<<endl;
                        return false;
                    }
                    if (!current_key) {
                        current_key = new t_key(key, mod);
                        last_key = current_key;
                    } else {
                        t_key *temp_key = new t_key(key, mod);
                        last_key->keylist.push_back(temp_key);
                        last_key = temp_key;
                    }
                }
            }

        } else { // parse command line
            if (last_key == 0) {
                cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                cerr<<"> "<<linebuffer<<endl;
                return false;
            }
            bool ret_val = true;
            const char *str =
                FbTk::StringUtil::strcasestr(linebuffer.c_str(),
                                             val[argc].c_str() + 1); // +1 to skip ':'
            if (str == 0) {
                cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                cerr<<"> "<<linebuffer<<endl;
                ret_val = false;
            } else {

                last_key->m_command = CommandParser::instance().parseLine(str);

                if (*last_key->m_command == 0) {
                    cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                    cerr<<"> "<<linebuffer<<endl;
                } else {
                    // Add the keychain to list
                    if (!mergeTree(current_key)) {
                        cerr<<_FBTEXT(Keys, BadMerge, "Keys: Failed to merge keytree!", "relatively technical error message. Key bindings are stored in a tree structure")<<endl;
                        ret_val = false;
                    }
                }
            }
            delete current_key;
            current_key = 0;
            last_key = 0;

            return ret_val;

        }  // end if
    } // end for

    return false;
}

/**
 @return the KeyAction of the XKeyEvent
*/
void Keys::doAction(XKeyEvent &ke) {

    ke.state = FbTk::KeyUtil::instance().cleanMods(ke.state);

    static struct t_key* next_key = 0;

    if (!next_key) {

        for (size_t i = 0; i < m_keylist.size(); i++) {
            if (*m_keylist[i] == ke) {
                if (m_keylist[i]->keylist.size()) {
                    next_key = m_keylist[i];
                    break; //end for-loop
                } else {
                    if (*m_keylist[i]->m_command != 0)
                        m_keylist[i]->m_command->execute();
                }
            }
        }

    } else { //check the nextkey
            t_key *temp_key = next_key->find(ke);
        if (temp_key) {
            if (temp_key->keylist.size()) {
                next_key = temp_key;
            } else {
                next_key = 0;
                if (*temp_key->m_command != 0)
                    temp_key->m_command->execute();
            }
        }  else  {
            temp_key = next_key;
            next_key = 0;
            if (*temp_key->m_command != 0)
                temp_key->m_command->execute();

        }
    }
}

/**
 deletes the tree and load configuration
 returns true on success else false
*/
bool Keys::reconfigure(const char *filename) {
    deleteTree();
    return load(filename);
}

/**
 Merges two chains and binds new keys
 @return true on success else false.
*/
bool Keys::mergeTree(t_key *newtree, t_key *basetree) {
    size_t baselit_i = 0;
    if (basetree==0) {
        for (; baselist_i<m_keylist.size(); baselist_i++) {
            if (m_keylist[baselist_i]->mod == newtree->mod &&
                m_keylist[baselist_i]->key == newtree->key) {
                if (newtree->keylist.size() && *m_keylist[baselist_i]->m_command == 0) {
                    //assumes the newtree only have one branch
                    return mergeTree(newtree->keylist[0], m_keylist[baselist_i]);
                } else
                    break;
            }
        }

        if (baselist_i == m_keylist.size()) {
            FbTk::KeyUtil::grabKey(newtree->key, newtree->mod);
            m_keylist.push_back(new t_key(newtree));
            if (newtree->keylist.size())
                return mergeTree(newtree->keylist[0], m_keylist.back());
            return true;
        }

    } else {
        for (; baselist_i<basetree->keylist.size(); baselist_i++) {
            if (basetree->keylist[baselist_i]->mod == newtree->mod &&
                basetree->keylist[baselist_i]->key == newtree->key) {
                if (newtree->keylist.size()) {
                    //assumes the newtree only have on branch
                    return mergeTree(newtree->keylist[0], basetree->keylist[baselist_i]);
                } else
                    return false;
            }
        }
        //if it wasn't in the list grab the key and add it to the list
        if (baselist_i==basetree->keylist.size()) {
            FbTk::KeyUtil::grabKey(newtree->key, newtree->mod);
            basetree->keylist.push_back(new t_key(newtree));
            if (newtree->keylist.size())
                return mergeTree(newtree->keylist[0], basetree->keylist.back());
            return true;
        }
    }

    return false;
}

Keys::t_key::t_key(unsigned int key_, unsigned int mod_, FbTk::RefCount<FbTk::Command> command) {
    key = key_;
    mod = mod_;
    m_command = command;
}

Keys::t_key::t_key(t_key *k) {
    key = k->key;
    mod = k->mod;
    m_command = k->m_command;
}

Keys::t_key::~t_key() {
    while (!keylist.empty()) {
        t_key *k = keylist.back();
        if (k != 0) { // make sure we don't have a bad key pointer
            delete k;
            keylist.pop_back();
        }
    }

}
<commit_msg>typo broke build<commit_after>// Keys.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2001 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//$Id$

#include "Keys.hh"

#include "FbTk/StringUtil.hh"
#include "FbTk/App.hh"
#include "FbTk/Command.hh"

#include "CommandParser.hh"
#include "FbTk/I18n.hh"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif	// HAVE_CTYPE_H

#ifdef HAVE_CSTDIO
  #include <cstdio>
#else
  #include <stdio.h>
#endif
#ifdef HAVE_CSTDLIB
  #include <cstdlib>
#else
  #include <stdlib.h>
#endif
#ifdef HAVE_CERRNO
  #include <cerrno>
#else
  #include <errno.h>
#endif
#ifdef HAVE_CSTRING
  #include <cstring>
#else
  #include <string.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif	// HAVE_SYS_TYPES_H

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif	// HAVE_SYS_WAIT_H

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif	// HAVE_UNISTD_H

#ifdef	HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif	// HAVE_SYS_STAT_H

#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>

#include <iostream>
#include <fstream>
#include <vector>
#ifdef HAVE_CASSERT
  #include <cassert>
#else
  #include <assert.h>
#endif
#include <memory>

using namespace std;

Keys::Keys(const char *filename):
    m_display(FbTk::App::instance()->display())
{

    if (filename != 0)
        load(filename);
}

Keys::~Keys() {

    FbTk::KeyUtil::ungrabKeys();
    deleteTree();
}

/// Destroys the keytree
void Keys::deleteTree() {
    while (!m_keylist.empty()) {
        if (m_keylist.back())
            delete m_keylist.back();
        m_keylist.pop_back();
    }
}

/**
    Load and grab keys
    TODO: error checking
    @return true on success else false
*/
bool Keys::load(const char *filename) {
    if (!filename)
        return false;

    //ungrab all keys
    FbTk::KeyUtil::ungrabKeys();

    //free memory of previous grabs
    deleteTree();

    FbTk::App::instance()->sync(false);

    //open the file
    ifstream infile(filename);
    if (!infile)
        return false; // faild to open file

    m_current_line = 0;//current line, so we can tell the user where the fault is

    while (!infile.eof()) {
        string linebuffer;

        getline(infile, linebuffer);

        m_current_line++;

        addBinding(linebuffer);
    } // end while eof

    m_current_line = 0;
    m_filename = filename;
    return true;
}

bool Keys::save(const char *filename) const {
    //!!
    //!! TODO: fix keybinding saving
    //!! (we probably need to save key actions
    //!! as strings instead of creating new Commands)

    // open file for writing
    //    ofstream outfile(filename);
    //    if (!outfile)
    return false;
    //    return true;
}

bool Keys::addBinding(const std::string &linebuffer) {

    vector<string> val;
    // Parse arguments
    FbTk::StringUtil::stringtok(val, linebuffer.c_str());

    // must have at least 1 argument
    if (val.size() <= 0)
        return true; // empty lines are valid.

    if (val[0][0] == '#' || val[0][0] == '!' ) //the line is commented
        return true; // still a valid line.

    unsigned int key = 0, mod = 0;
    char keyarg = 0;
    t_key *current_key=0, *last_key=0;

    _FB_USES_NLS;
    // for each argument
    for (size_t argc = 0; argc < val.size(); argc++) {

        if (val[argc][0] != ':') { // parse key(s)
            keyarg++;
            if (keyarg==1) //first arg is modifier
                mod = FbTk::KeyUtil::getModifier(val[argc].c_str());
            else if (keyarg > 1) {

                int tmpmod = FbTk::KeyUtil::getModifier(val[argc].c_str());
                if(tmpmod)
                    mod |= tmpmod; //If it's a modifier
                else {
                    // keycode covers the following three two-byte cases:
                    // 0x       - hex
                    // +[1-9]   - number between +1 and +9
                    // numbers 10 and above
                    //
                    if (val[argc].size() > 1 && (isdigit(val[argc][0]) &&
                                                 (isdigit(val[argc][1]) || val[argc][1] == 'x') ||
                                                 val[argc][0] == '+' && isdigit(val[argc][1])) ) {

                        key = strtoul(val[argc].c_str(), NULL, 0);

                        if (errno == EINVAL || errno == ERANGE)
                            key = 0;

                    } else // convert from string symbol
                        key = FbTk::KeyUtil::getKey(val[argc].c_str());

                    if (key == 0) {
                        cerr<<_FBTEXT(Keys, InvalidKeyMod,
                                      "Keys: Invalid key/modifier on line",
                                      "A bad key/modifier string was found on line (number following)")<<" "<<
                            m_current_line<<"): "<<linebuffer<<endl;
                        return false;
                    }
                    if (!current_key) {
                        current_key = new t_key(key, mod);
                        last_key = current_key;
                    } else {
                        t_key *temp_key = new t_key(key, mod);
                        last_key->keylist.push_back(temp_key);
                        last_key = temp_key;
                    }
                }
            }

        } else { // parse command line
            if (last_key == 0) {
                cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                cerr<<"> "<<linebuffer<<endl;
                return false;
            }
            bool ret_val = true;
            const char *str =
                FbTk::StringUtil::strcasestr(linebuffer.c_str(),
                                             val[argc].c_str() + 1); // +1 to skip ':'
            if (str == 0) {
                cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                cerr<<"> "<<linebuffer<<endl;
                ret_val = false;
            } else {

                last_key->m_command = CommandParser::instance().parseLine(str);

                if (*last_key->m_command == 0) {
                    cerr<<_FBTEXT(Keys, BadLine, "Keys: Error on line", "Error on line (number following)")<<": "<<m_current_line<<endl;
                    cerr<<"> "<<linebuffer<<endl;
                } else {
                    // Add the keychain to list
                    if (!mergeTree(current_key)) {
                        cerr<<_FBTEXT(Keys, BadMerge, "Keys: Failed to merge keytree!", "relatively technical error message. Key bindings are stored in a tree structure")<<endl;
                        ret_val = false;
                    }
                }
            }
            delete current_key;
            current_key = 0;
            last_key = 0;

            return ret_val;

        }  // end if
    } // end for

    return false;
}

/**
 @return the KeyAction of the XKeyEvent
*/
void Keys::doAction(XKeyEvent &ke) {

    ke.state = FbTk::KeyUtil::instance().cleanMods(ke.state);

    static struct t_key* next_key = 0;

    if (!next_key) {

        for (size_t i = 0; i < m_keylist.size(); i++) {
            if (*m_keylist[i] == ke) {
                if (m_keylist[i]->keylist.size()) {
                    next_key = m_keylist[i];
                    break; //end for-loop
                } else {
                    if (*m_keylist[i]->m_command != 0)
                        m_keylist[i]->m_command->execute();
                }
            }
        }

    } else { //check the nextkey
            t_key *temp_key = next_key->find(ke);
        if (temp_key) {
            if (temp_key->keylist.size()) {
                next_key = temp_key;
            } else {
                next_key = 0;
                if (*temp_key->m_command != 0)
                    temp_key->m_command->execute();
            }
        }  else  {
            temp_key = next_key;
            next_key = 0;
            if (*temp_key->m_command != 0)
                temp_key->m_command->execute();

        }
    }
}

/**
 deletes the tree and load configuration
 returns true on success else false
*/
bool Keys::reconfigure(const char *filename) {
    deleteTree();
    return load(filename);
}

/**
 Merges two chains and binds new keys
 @return true on success else false.
*/
bool Keys::mergeTree(t_key *newtree, t_key *basetree) {
    size_t baselist_i = 0;
    if (basetree==0) {
        for (; baselist_i<m_keylist.size(); baselist_i++) {
            if (m_keylist[baselist_i]->mod == newtree->mod &&
                m_keylist[baselist_i]->key == newtree->key) {
                if (newtree->keylist.size() && *m_keylist[baselist_i]->m_command == 0) {
                    //assumes the newtree only have one branch
                    return mergeTree(newtree->keylist[0], m_keylist[baselist_i]);
                } else
                    break;
            }
        }

        if (baselist_i == m_keylist.size()) {
            FbTk::KeyUtil::grabKey(newtree->key, newtree->mod);
            m_keylist.push_back(new t_key(newtree));
            if (newtree->keylist.size())
                return mergeTree(newtree->keylist[0], m_keylist.back());
            return true;
        }

    } else {
        for (; baselist_i<basetree->keylist.size(); baselist_i++) {
            if (basetree->keylist[baselist_i]->mod == newtree->mod &&
                basetree->keylist[baselist_i]->key == newtree->key) {
                if (newtree->keylist.size()) {
                    //assumes the newtree only have on branch
                    return mergeTree(newtree->keylist[0], basetree->keylist[baselist_i]);
                } else
                    return false;
            }
        }
        //if it wasn't in the list grab the key and add it to the list
        if (baselist_i==basetree->keylist.size()) {
            FbTk::KeyUtil::grabKey(newtree->key, newtree->mod);
            basetree->keylist.push_back(new t_key(newtree));
            if (newtree->keylist.size())
                return mergeTree(newtree->keylist[0], basetree->keylist.back());
            return true;
        }
    }

    return false;
}

Keys::t_key::t_key(unsigned int key_, unsigned int mod_, FbTk::RefCount<FbTk::Command> command) {
    key = key_;
    mod = mod_;
    m_command = command;
}

Keys::t_key::t_key(t_key *k) {
    key = k->key;
    mod = k->mod;
    m_command = k->m_command;
}

Keys::t_key::~t_key() {
    while (!keylist.empty()) {
        t_key *k = keylist.back();
        if (k != 0) { // make sure we don't have a bad key pointer
            delete k;
            keylist.pop_back();
        }
    }

}
<|endoftext|>


<commit_before>
#pragma once

#include "testing_utilities/is_near.hpp"

#include <float.h>
#include <math.h>
#include <stdint.h>

#include <algorithm>
#include <limits>
#include <string>

#include "geometry/grassmann.hpp"
#include "geometry/r3_element.hpp"
#include "gmock/gmock.h"
#include "numerics/ulp_distance.hpp"
#include "testing_utilities/numerics.hpp"

namespace principia {
namespace testing_utilities {
namespace internal_is_near {

using quantities::DebugString;

template<typename T>
testing::PolymorphicMatcher<IsNearMatcher<T>> IsNear(
    T const& expected) {
  return testing::MakePolymorphicMatcher(
      IsNearMatcher<T>(expected, /*tolerance=*/1.1));
}

template<typename T>
testing::PolymorphicMatcher<IsNearMatcher<T>> IsNear(
    T const& expected,
    double const tolerance) {
  CHECK_LE(1.0, tolerance);
  return testing::MakePolymorphicMatcher(
      IsNearMatcher<T>(expected, tolerance));
}

template<typename T>
IsNearMatcher<T>::IsNearMatcher(T const& expected,
                                double const tolerance)
    : expected_(expected),
      low_(expected / std::sqrt(tolerance)),
      high_(expected * std::sqrt(tolerance)),
      tolerance_(tolerance) {}

template<typename T>
template<typename Dimensions>
bool IsNearMatcher<T>::MatchAndExplain(
    quantities::Quantity<Dimensions> const& actual,
    testing::MatchResultListener* listener) const {
  bool const match =  low_ <= actual && actual <= high_;
  if (!match) {
    *listener << "which is not in the range [" << low_ << ", " << high_
              << "] and is off by "
              << std::max(actual / expected_, expected_ / actual);
  }
  return match;
}

template<typename T>
bool IsNearMatcher<T>::MatchAndExplain(
    double const actual,
    testing::MatchResultListener* listener) const {
  bool const match =  low_ <= actual && actual <= high_;
  if (!match) {
    *listener << "which is not in the range [" << DebugString(low_)
              << ", " << DebugString(high_) << "] and is off by "
              << std::max(actual / expected_, expected_ / actual);
  }
  return match;
}

template<typename T>
void IsNearMatcher<T>::DescribeTo(std::ostream* out) const {
  *out << "is within ["<< low_
       << ", " << high_ << "], i.e., a factor " << tolerance_
       << " away from " << expected_;
}

template<typename T>
void IsNearMatcher<T>::DescribeNegationTo(std::ostream* out) const {
  *out << "is not within ["<< low_
       << ", " << high_ << "], i.e., a factor " << tolerance_
       << " away from " << expected_;
}

}  // namespace internal_almost_equals
}  // namespace testing_utilities
}  // namespace principia
<commit_msg>Lint.<commit_after>
#pragma once

#include "testing_utilities/is_near.hpp"

#include <float.h>
#include <math.h>
#include <stdint.h>

#include <algorithm>
#include <limits>
#include <string>

#include "geometry/grassmann.hpp"
#include "geometry/r3_element.hpp"
#include "gmock/gmock.h"
#include "numerics/ulp_distance.hpp"
#include "testing_utilities/numerics.hpp"

namespace principia {
namespace testing_utilities {
namespace internal_is_near {

using quantities::DebugString;

template<typename T>
testing::PolymorphicMatcher<IsNearMatcher<T>> IsNear(
    T const& expected) {
  return testing::MakePolymorphicMatcher(
      IsNearMatcher<T>(expected, /*tolerance=*/1.1));
}

template<typename T>
testing::PolymorphicMatcher<IsNearMatcher<T>> IsNear(
    T const& expected,
    double const tolerance) {
  CHECK_LE(1.0, tolerance);
  return testing::MakePolymorphicMatcher(
      IsNearMatcher<T>(expected, tolerance));
}

template<typename T>
IsNearMatcher<T>::IsNearMatcher(T const& expected,
                                double const tolerance)
    : expected_(expected),
      low_(expected / std::sqrt(tolerance)),
      high_(expected * std::sqrt(tolerance)),
      tolerance_(tolerance) {}

template<typename T>
template<typename Dimensions>
bool IsNearMatcher<T>::MatchAndExplain(
    quantities::Quantity<Dimensions> const& actual,
    testing::MatchResultListener* listener) const {
  bool const match =  low_ <= actual && actual <= high_;
  if (!match) {
    *listener << "which is not in the range [" << low_ << ", " << high_
              << "] and is off by "
              << std::max(actual / expected_, expected_ / actual);
  }
  return match;
}

template<typename T>
bool IsNearMatcher<T>::MatchAndExplain(
    double const actual,
    testing::MatchResultListener* listener) const {
  bool const match =  low_ <= actual && actual <= high_;
  if (!match) {
    *listener << "which is not in the range [" << DebugString(low_)
              << ", " << DebugString(high_) << "] and is off by "
              << std::max(actual / expected_, expected_ / actual);
  }
  return match;
}

template<typename T>
void IsNearMatcher<T>::DescribeTo(std::ostream* out) const {
  *out << "is within ["<< low_
       << ", " << high_ << "], i.e., a factor " << tolerance_
       << " away from " << expected_;
}

template<typename T>
void IsNearMatcher<T>::DescribeNegationTo(std::ostream* out) const {
  *out << "is not within ["<< low_
       << ", " << high_ << "], i.e., a factor " << tolerance_
       << " away from " << expected_;
}

}  // namespace internal_is_near
}  // namespace testing_utilities
}  // namespace principia
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/core/malloc_tracker_test.cpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/core/malloc_tracker.hpp>
#include <gtest/gtest.h>

using namespace c7a;

TEST(MallocTracker, Test1) {

    size_t curr = core::malloc_tracker_current();

    char* a = new char[1024];
    // dear compiler, please don't optimize away completely!
    a[0] = 0;

    size_t curr2 = core::malloc_tracker_current();
    ASSERT_GE(curr2, curr + 1024);

    delete[] a;

    ASSERT_LE(curr, curr2);
}

/******************************************************************************/
<commit_msg>*sigh*. it is hard to get the compiler to keep this in _this_ order!<commit_after>/*******************************************************************************
 * tests/core/malloc_tracker_test.cpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/core/malloc_tracker.hpp>
#include <gtest/gtest.h>

using namespace c7a;

TEST(MallocTracker, Test1) {

    size_t curr = core::malloc_tracker_current();
    ASSERT_GE(curr, 0);

    char* a = nullptr;
    {
        a = reinterpret_cast<char*>(malloc(1024));
        // dear compiler, please don't optimize away completely!
        a[0] = 0;
    }

    size_t curr2 = core::malloc_tracker_current();
    ASSERT_GE(curr2 + a[0], curr + 1024);

    free(a);

    ASSERT_LE(curr, curr2);
}

/******************************************************************************/
<|endoftext|>


<commit_before>/*
 Sifer Aseph
 TopCoder: ImageCompression
 SRM
 */

#include <iostream>
#include <string>
#include <vector>

class ImageCompression {
public:
    std::string isPossible(std::vector<std::string> image, int k) {
        size_t n = image.size();
        size_t m = image[0].length();
        if (k == image[0].length()) {
            return "Impossible";
        }

        if (n % k != 0 || m % k != 0) {
            return "Impossible";
        }

        std::string ideal1 = "";
        std::string ideal0 = "";
        for (int step = 0; step < k; ++step) {
            ideal1 += "1";
            ideal0 += "0";
        }

        //std::cout << ideal1 << " and " << ideal0 << std::endl;
        /*
        for (size_t i = 0; i < image.size(); i+=k) {
            if (image[i].substr(i, k) == ideal1 || image[i].substr(i, k) == ideal0) {
                return "Possible";
            } else if (image[i].substr(i, k) != ideal1 || image[i].substr(i, k) != ideal0) {
                return "Impossible";
            }
        }*/

        bool theTest = false;
        for (size_t i = 0; i < image.size(); i+=k) {
            if (image[i].substr(i, k) == ideal1 || image[i].substr(i, k) == ideal0) {
                theTest = true;
            } else if (image[i].substr(i, k) != ideal1 || image[i].substr(i, k) != ideal0) {
                theTest = false;
            }
        }

        if (theTest == true) {
            return "Possible";
        } else {
            return "Impossible";
        }

        // { string test = "example"; string a = test.substr(0, 2); cout << a; string b = test.substr(2, 2); cout << ' ' << b; }

        return "Maybe"; // If this is returned, it means I missed a case.
    }

};

int main() {
    ImageCompression test;

    std::cout << test.isPossible({ "0011", "0011", "1100", "1100", "0010", "0000" }, 2) << std::endl; // should be impossible
    std::cout << test.isPossible({ "111000111", "111000111", "111000111" }, 3) << std::endl; // possible
    std::cout << test.isPossible({ "001100", "001100", "110011", "110011", "001100", "001100" }, 6) << std::endl; // possible
    std::cout << test.isPossible({ "0011", "0011", "1100", "1100", "0000", "0000" }, 2) << std::endl; // impossible
    std::cout << test.isPossible({ "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111" }, 4) << std::endl; // possible

    return 0;
}
<commit_msg>Vincent Norah<commit_after>/*
 Sifer Aseph
 TopCoder: ImageCompression
 SRM
 */

#include <iostream>
#include <string>
#include <vector>

class ImageCompression {
public:
    std::string isPossible(std::vector<std::string> image, int k) {
        size_t n = image.size();
        size_t m = image[0].length();
        if (k == image[0].length()) {
            return "Impossible";
        }

        if (n % k != 0 || m % k != 0) {
            return "Impossible";
        }

        std::string ideal1 = "";
        std::string ideal0 = "";
        for (int step = 0; step < k; ++step) {
            ideal1 += "1";
            ideal0 += "0";
        }

        //std::cout << ideal1 << " and " << ideal0 << std::endl;
        /*
        for (size_t i = 0; i < image.size(); i+=k) {
            if (image[i].substr(i, k) == ideal1 || image[i].substr(i, k) == ideal0) {
                return "Possible";
            } else if (image[i].substr(i, k) != ideal1 || image[i].substr(i, k) != ideal0) {
                return "Impossible";
            }
        }*/

        bool theTest = false;
        for (size_t i = 0; i < image.size(); i+=k) {
            if (image[i].substr(i, k) == ideal1 || image[i].substr(i, k) == ideal0) {
                theTest = true;
            } else if (image[i].substr(i, k) != ideal1 || image[i].substr(i, k) != ideal0) {
                theTest = false;
            }
        }

        if (theTest == true) {
            return "Possible";
        } else {
            return "Impossible";
        }

        // { string test = "example"; string a = test.substr(0, 2); cout << a; string b = test.substr(2, 2); cout << ' ' << b; }

        return "Maybe"; // If this is returned, it means I missed a case.
    }

};

int main() {
    ImageCompression test;

    std::cout << test.isPossible({ "0011", "0011", "1100", "1100", "0010", "0000" }, 2) << std::endl; // should be impossible
    std::cout << test.isPossible({ "111000111", "111000111", "111000111" }, 3) << std::endl; // possible
    std::cout << test.isPossible({ "001100", "001100", "110011", "110011", "001100", "001100" }, 6) << std::endl; // impossible
    std::cout << test.isPossible({ "0011", "0011", "1100", "1100", "0000", "0000" }, 2) << std::endl; // impossible
    std::cout << test.isPossible({ "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111", "11111111" }, 4) << std::endl; // possible

    return 0;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include "dla.hpp"

Dla::Dla(int grid_width, int grid_height) {
    this->grid_width = grid_width;
    this->grid_height = grid_height;

    // Initialize all cells to zero
    this->anchors = (bool **) std::malloc(grid_height * sizeof(bool *));
    for (int i = 0; i < grid_height; i++)
        this->anchors[i] = (bool *) std::malloc(grid_width * sizeof(bool));
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width; j++)
            this->anchors[i][j] = false;
    }

    // Anchor a particle at the center
    this->center_x = grid_height / 2;
    this->center_y = grid_width / 2;
    this->anchors[this->center_x][this->center_y] = true;
    //std::cout << "New anchor at (" << center_x << "," << center_y << ")\n";
    this->r = 0.0;
    this->radius = 1;

    std::srand(std::time(NULL));
}

void Dla::print_grid() {
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width - 1; j++)
            std::cout << anchors[i][j] << " ";
        std::cout << anchors[i][grid_width - 1] << "\n";
    }
}

void Dla::write_grid_to_file(char *outfile) {
    std::FILE *p_outfile = std::fopen(outfile, "w");
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width - 1; j++)
            std::fprintf(p_outfile, "%d ", anchors[i][j]);
        std::fprintf(p_outfile, "%d\n", anchors[i][grid_width - 1]);
    }
    std::fclose(p_outfile);
}

int * Dla::get_points_on_square() {
    // Not sure yet if should be > or >=
    // This should be handled by the main loop
    if (radius > grid_width / 2 || radius > grid_height / 2)
        return NULL;

    int x, y;
    int i = 0;
    int *points = (int *) std::malloc(2 * (radius * 8) * sizeof(int));

    // Top edge
    x = center_x - radius;
    for (y = center_y - radius; y <= center_y + radius; y++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Bottom edge
    x = center_x + radius;
    for (y = center_y - radius; y <= center_y + radius; y++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Left edge
    y = center_y - radius;
    for (x = center_x - (radius - 1); x <= center_x + (radius - 1); x++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Right edge
    y = center_y + radius;
    for (x = center_x - (radius - 1); x <= center_x + (radius - 1); x++) {
        points[i++] = x;
        points[i++] = y;
    }

    return points;
}

double Dla::get_distance_from_center(int x, int y) {
    return std::sqrt(std::pow(x - center_x, 2) + std::pow(y - center_y, 2));
}

void Dla::update_square_radius() {
    //radius = 1 + (int) std::ceil(r);
    radius = (int) std::ceil(r + 1);
}

void Dla::anchor_second_particle() {
    int test = std::rand() % 4;
    if (test == 0) anchors[center_x - 1][center_y] = true;
    else if (test == 1) anchors[center_x + 1][center_y] = true;
    else if (test == 2) anchors[center_x][center_y - 1] = true;
    else anchors[center_x][center_y + 1] = true;
    r = 1.0;
    update_square_radius();
}

void Dla::walk_particle() {
    // Get all points on square of radius r + 1 around center
    int *points = get_points_on_square();
    // This should be handled by the main loop, remove later
    if (points == NULL) {
        // End program
        print_grid();
        exit(0);
    }

    // Choose random point to be starting position
    int n_points = radius * 8;
    int test = std::rand() % n_points;
    int start_x = points[test * 2];
    int start_y = points[test * 2 + 1];
    std::free(points);

    Walker walker = Walker(this, start_x, start_y);
    // Initialize to fake value
    double distance = 0.0;

    while (distance < 2.0 * r) {
        // Choose next move
        walker.choose_next_coords();
        while (point_not_in_grid(walker.next_x, walker.next_y))
            walker.choose_next_coords();
        walker.move_to_next();
        distance = get_distance_from_center(walker.x, walker.y);
        if (adjacent_to_anchor(walker.x, walker.y)) {
            // Anchor this particle
            //std::cout << "New anchor at (" << walker.x << "," << walker.y << ")\n";
            anchors[walker.x][walker.y] = true;
            // Update furthest distance from center if necessary
            if (r < distance) {
                r = distance;
                // Update square radius
                update_square_radius();
            }
            return;
        }
    }
}

bool Dla::adjacent_to_anchor(int x, int y) {
    if (!point_not_in_grid(x - 1, y) && anchors[x - 1][y]) return true;
    if (!point_not_in_grid(x + 1, y) && anchors[x + 1][y]) return true;
    if (!point_not_in_grid(x, y - 1) && anchors[x][y - 1]) return true;
    if (!point_not_in_grid(x, y + 1) && anchors[x][y + 1]) return true;
    return false;
}

// Faster than checking if point in grid since it short-circuits
bool Dla::point_not_in_grid(int x, int y) {
    return (x < 0 || x >= grid_height || y < 0 || y >= grid_width);
}

void Dla::sim() {
    // Anchor the second particle "manually" so that r becomes non-zero
    anchor_second_particle();

    // Experiment with this
    //while (r < grid_width / 2 && r < grid_height / 2) {
    while (radius < grid_width / 2 && radius < grid_height / 2) {
        walk_particle();
    }
}

Walker::Walker(Dla *parent, int x, int y) {
    this->parent = parent;
    this->x = x;
    this->y = y;
}

void Walker::move_to_next() {
    x = next_x;
    y = next_y;
}

void Walker::choose_next_coords() {
    int test;

    test = std::rand() % 4;
    if (test == 0) {
        next_x = x - 1;
        next_y = y;
    }
    else if (test == 1) {
        next_x = x + 1;
        next_y = y;
    }
    else if (test == 2) {
        next_x = x;
        next_y = y - 1;
    }
    else {
        next_x = x;
        next_y = y + 1;
    }
}
<commit_msg>Removed some redundant error checking<commit_after>#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include "dla.hpp"

Dla::Dla(int grid_width, int grid_height) {
    this->grid_width = grid_width;
    this->grid_height = grid_height;

    // Initialize all cells to zero
    this->anchors = (bool **) std::malloc(grid_height * sizeof(bool *));
    for (int i = 0; i < grid_height; i++)
        this->anchors[i] = (bool *) std::malloc(grid_width * sizeof(bool));
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width; j++)
            this->anchors[i][j] = false;
    }

    // Anchor a particle at the center
    this->center_x = grid_height / 2;
    this->center_y = grid_width / 2;
    this->anchors[this->center_x][this->center_y] = true;
    //std::cout << "New anchor at (" << center_x << "," << center_y << ")\n";
    this->r = 0.0;
    this->radius = 1;

    std::srand(std::time(NULL));
}

void Dla::print_grid() {
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width - 1; j++)
            std::cout << anchors[i][j] << " ";
        std::cout << anchors[i][grid_width - 1] << "\n";
    }
}

void Dla::write_grid_to_file(char *outfile) {
    std::FILE *p_outfile = std::fopen(outfile, "w");
    for (int i = 0; i < grid_height; i++) {
        for (int j = 0; j < grid_width - 1; j++)
            std::fprintf(p_outfile, "%d ", anchors[i][j]);
        std::fprintf(p_outfile, "%d\n", anchors[i][grid_width - 1]);
    }
    std::fclose(p_outfile);
}

int * Dla::get_points_on_square() {
    int x, y;
    int i = 0;
    int *points = (int *) std::malloc(2 * (radius * 8) * sizeof(int));

    // Top edge
    x = center_x - radius;
    for (y = center_y - radius; y <= center_y + radius; y++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Bottom edge
    x = center_x + radius;
    for (y = center_y - radius; y <= center_y + radius; y++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Left edge
    y = center_y - radius;
    for (x = center_x - (radius - 1); x <= center_x + (radius - 1); x++) {
        points[i++] = x;
        points[i++] = y;
    }
    // Right edge
    y = center_y + radius;
    for (x = center_x - (radius - 1); x <= center_x + (radius - 1); x++) {
        points[i++] = x;
        points[i++] = y;
    }

    return points;
}

double Dla::get_distance_from_center(int x, int y) {
    return std::sqrt(std::pow(x - center_x, 2) + std::pow(y - center_y, 2));
}

void Dla::update_square_radius() {
    radius = (int) std::ceil(r + 1);
}

void Dla::anchor_second_particle() {
    int test = std::rand() % 4;
    if (test == 0) anchors[center_x - 1][center_y] = true;
    else if (test == 1) anchors[center_x + 1][center_y] = true;
    else if (test == 2) anchors[center_x][center_y - 1] = true;
    else anchors[center_x][center_y + 1] = true;
    r = 1.0;
    update_square_radius();
}

void Dla::walk_particle() {
    // Get all points on square of radius r + 1 around center
    int *points = get_points_on_square();

    // Choose random point to be starting position
    int n_points = radius * 8;
    int test = std::rand() % n_points;
    int start_x = points[test * 2];
    int start_y = points[test * 2 + 1];
    std::free(points);

    Walker walker = Walker(this, start_x, start_y);
    // Initialize to fake value
    double distance = 0.0;

    while (distance < 2.0 * r) {
        // Choose next move
        walker.choose_next_coords();
        while (point_not_in_grid(walker.next_x, walker.next_y))
            walker.choose_next_coords();
        walker.move_to_next();
        distance = get_distance_from_center(walker.x, walker.y);
        if (adjacent_to_anchor(walker.x, walker.y)) {
            // Anchor this particle
            //std::cout << "New anchor at (" << walker.x << "," << walker.y << ")\n";
            anchors[walker.x][walker.y] = true;
            // Update furthest distance from center if necessary
            if (r < distance) {
                r = distance;
                // Update square radius
                update_square_radius();
            }
            return;
        }
    }
}

bool Dla::adjacent_to_anchor(int x, int y) {
    if (!point_not_in_grid(x - 1, y) && anchors[x - 1][y]) return true;
    if (!point_not_in_grid(x + 1, y) && anchors[x + 1][y]) return true;
    if (!point_not_in_grid(x, y - 1) && anchors[x][y - 1]) return true;
    if (!point_not_in_grid(x, y + 1) && anchors[x][y + 1]) return true;
    return false;
}

// Faster than checking if point in grid since it short-circuits
bool Dla::point_not_in_grid(int x, int y) {
    return (x < 0 || x >= grid_height || y < 0 || y >= grid_width);
}

void Dla::sim() {
    // Anchor the second particle "manually" so that r becomes non-zero
    anchor_second_particle();

    // Introduce new walkers until starting position reaches edge of grid
    while (radius < grid_width / 2 && radius < grid_height / 2) {
        walk_particle();
    }
}

Walker::Walker(Dla *parent, int x, int y) {
    this->x = x;
    this->y = y;
}

void Walker::move_to_next() {
    x = next_x;
    y = next_y;
}

void Walker::choose_next_coords() {
    int test;

    test = std::rand() % 4;
    if (test == 0) {
        next_x = x - 1;
        next_y = y;
    }
    else if (test == 1) {
        next_x = x + 1;
        next_y = y;
    }
    else if (test == 2) {
        next_x = x;
        next_y = y - 1;
    }
    else {
        next_x = x;
        next_y = y + 1;
    }
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2007 Till Adam <adam@kde.org>

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

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

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

#include "maildir.h"

#include <QDir>
#include <QFileInfo>
#include <QUuid>
#include <QDebug>

#include <klocale.h>
#include <kpimutils/kfileio.h>

using namespace KPIM;

class Maildir::Private
{
public:
    Private( const QString& p )
    :path(p)
    {
    }

    Private( const QString& p, bool isRoot )
    :path(p), isRoot(isRoot)
    {
    }

    Private( const Private& rhs )
    {
      path = rhs.path;
    }

    bool operator==( const Private& rhs ) const
    {
      return path == rhs.path;
    }
    bool accessIsPossible( QString& error ) const;
    bool canAccess( const QString& path ) const;

    QStringList subPaths() const
    {
      QStringList paths;
      paths << path + QString::fromLatin1("/cur");
      paths << path + QString::fromLatin1("/new");
      paths << path + QString::fromLatin1("/tmp");
      return paths;
    }

    QStringList listNew() const
    {
      QDir d( path + QString::fromLatin1("/new") );
      return d.entryList(QDir::Files);
    }

    QStringList listCurrent() const
    {
      QDir d( path + QString::fromLatin1("/cur") );
      return d.entryList(QDir::Files);
    }

    QString findRealKey( const QString& key ) const
    {
      QString realKey = path + QString::fromLatin1("/new/") + key;
      QFile f( realKey );
      if ( !f.exists() )
        realKey = path + QString::fromLatin1("/cur/") + key;
      QFile f2( realKey );
      if ( !f2.exists() )
        realKey = QString();
      return realKey;
    }

    QString subDirPath() const
    {
        QDir dir( path );
        return QString::fromLatin1(".%1.directory").arg( dir.dirName() );
    }

    QString path;
    bool isRoot;
};

Maildir::Maildir( const QString& path, bool isRoot )
:d( new Private(path, isRoot) )
{
}

void Maildir::swap( const Maildir &rhs )
{
    Private *p = d;
    d = new Private( *rhs.d );
    delete p;
}

Maildir::Maildir(const Maildir & rhs)
  :d( new Private(*rhs.d) )

{
}

Maildir& Maildir::operator= (const Maildir & rhs)
{
    // copy and swap, exception safe, and handles assignment to self
    Maildir temp(rhs);
    swap( temp );
    return *this;
}

bool Maildir::operator== (const Maildir & rhs) const
{
  return *d == *rhs.d;
}

Maildir::~Maildir()
{
    delete d;
}

bool Maildir::Private::canAccess( const QString& path ) const
{
  //return access(QFile::encodeName( path ), R_OK | W_OK | X_OK ) != 0;
  // FIXME X_OK?
  QFileInfo d(path);
  return d.isReadable() && d.isWritable();
}

bool Maildir::Private::accessIsPossible( QString& error ) const
{
  QStringList paths = subPaths();
  paths.prepend( path );

  Q_FOREACH( QString p, paths )
  {
    if ( !QFile::exists(p) ) {
      error = i18n("Error opening %1; this folder is missing.",p);
      return false;
    }
    if ( !canAccess( p ) ) {
      error = i18n("Error opening %1; either this is not a valid "
                "maildir folder, or you do not have sufficient access permissions." ,p);
      return false;
    }
  }
  return true;
}

bool Maildir::isValid() const
{
  QString error;
  return isValid( error );
}

bool Maildir::isValid( QString &error ) const
{
  if ( d->accessIsPossible( error ) ) {
    return true;
  }
  return false;
}

bool Maildir::create()
{
    // FIXME: in a failure case, this will leave partially created dirs around
    // we should clean them up, but only if they didn't previously existed...
  Q_FOREACH( QString p, d->subPaths() ) {
    QDir dir( p );
    if ( !dir.exists( p ) ) {
      if ( !dir.mkpath( p ) )
        return false;
    }
  }
  return true;
}

QString Maildir::path() const
{
  return d->path;
}

bool Maildir::addSubFolder( const QString& path )
{
    if ( !isValid() ) return false;
    // make the subdir dir
    QDir dir( d->path );
    if ( !d->isRoot ) {
      dir.cdUp();
      if (!dir.exists( d->subDirPath() ) )
          dir.mkdir( d->subDirPath() );
      dir.cd( d->subDirPath() );
    }

    const QString fullPath = dir.path() + '/' + path;
    Maildir subdir( fullPath );
    if ( subdir.create() )
        return true;
    return false;
}

bool Maildir::removeSubFolder( const QString& folderName )
{
    if ( !isValid() ) return false;
    QDir dir( d->path );
    if ( !d->isRoot ) {
      dir.cdUp();
      if ( !dir.exists( d->subDirPath() ) ) return false;
      dir.cd( d->subDirPath() );
    }
    if ( !dir.exists( folderName ) ) return false;

    // remove it recursively
    return KPIMUtils::removeDirAndContentsRecursively( dir.absolutePath() + '/' + folderName );
}

Maildir Maildir::subFolder( const QString& subFolder )
{
    if ( isValid() ) {
        // make the subdir dir
        QDir dir( d->path );
        if ( !d->isRoot ) {
          dir.cdUp();
          if ( dir.exists( d->subDirPath() ) ) {
              dir.cd( d->subDirPath() );
          }
        }
        return Maildir( dir.path() + '/' + subFolder );
    }
    return Maildir();
}

QStringList Maildir::entryList() const
{
  QStringList result;
  if ( isValid() ) {
    result += d->listNew();
    result += d->listCurrent();
  }
//  kDebug() <<"Maildir::entryList()" << result;
  return result;
}

QStringList Maildir::subFolderList() const
{
  QDir dir( d->path );

  // the root maildir has its subfolders directly beneath it
  if ( !d->isRoot ) {
    dir.cdUp();
    if (!dir.exists( d->subDirPath() ) ) return QStringList();
    dir.cd( d->subDirPath() );
  }
  dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot );
  QStringList entries = dir.entryList();
  entries.removeAll( "cur" );
  entries.removeAll( "new" );
  entries.removeAll( "tmp" );
  return entries;
}

QByteArray Maildir::readEntry( const QString& key ) const
{
  QByteArray result;

  QString realKey( d->findRealKey( key ) );
  if ( realKey.isEmpty() ) {
      // FIXME error handling?
      qWarning() << "Maildir::readEntry unable to find: " << key;
      return result;
  }

  QFile f( realKey );
  f.open( QIODevice::ReadOnly );

  // FIXME be safer than this
  result = f.readAll();

  return result;
}

QByteArray Maildir::readEntryHeaders( const QString& key ) const
{
  QByteArray result;

  QString realKey( d->findRealKey( key ) );
  if ( realKey.isEmpty() ) {
      // FIXME error handling?
      qWarning() << "Maildir::readEntry unable to find: " << key;
      return result;
  }

  QFile f( realKey );
  if ( !f.open( QIODevice::ReadOnly ) ) {
      // FIXME error handling?
      qWarning() << "Maildir::readEntry unable to find: " << key;
      return result;
  }
  forever {
      QByteArray line = f.readLine();
      if ( line.trimmed().isEmpty() )
          break;
      result.append( line );
  }
  return result;
}

static QString createUniqueFileName()
{
  return QUuid::createUuid().toString();
}

void Maildir::writeEntry( const QString& key, const QByteArray& data )
{
  QString realKey( d->findRealKey( key ) );
  if ( realKey.isEmpty() ) {
      // FIXME error handling?
      qWarning() << "Maildir::writeEntry unable to find: " << key;
      return;
  }
  QFile f( realKey );
  f.open( QIODevice::WriteOnly );
  f.write( data );
  f.close();
}

QString Maildir::addEntry( const QByteArray& data )
{
  QString uniqueKey( createUniqueFileName() );
  QString key( d->path + "/tmp/" + uniqueKey );
  QString finalKey( d->path + "/new/" + uniqueKey );
  QFile f( key );
  f.open( QIODevice::WriteOnly );
  f.write( data );
  f.close();
  /*
   * FIXME:
   *
   * THe whole point of the locking free maildir idea is that the moves between
   * the internal directories are atomic. Afaik QFile::rename does not guarantee
   * that, so this will need to be done properly. - ta
   */
  if (!f.rename( finalKey )) {
    qWarning() << "Maildir: Failed to add entry: " << finalKey  << "!";
  }
  return uniqueKey;
}

bool Maildir::removeEntry( const QString& key )
{
  QString realKey( d->findRealKey( key ) );
  if ( realKey.isEmpty() ) {
      // FIXME error handling?
      qWarning() << "Maildir::removeEntry unable to find: " << key;
      return false;
  }
  return QFile::remove(realKey);
}

<commit_msg>Make Thomas happy.<commit_after>/*
    Copyright (c) 2007 Till Adam <adam@kde.org>

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

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

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

#include "maildir.h"

#include <QDir>
#include <QFileInfo>
#include <QUuid>
#include <QDebug>

#include <klocale.h>
#include <kpimutils/kfileio.h>

using namespace KPIM;

class Maildir::Private
{
public:
    Private( const QString& p )
    :path(p)
    {
    }

    Private( const QString& p, bool isRoot )
        :path(p), isRoot(isRoot)
    {
    }

    Private( const Private& rhs )
    {
        path = rhs.path;
    }

    bool operator==( const Private& rhs ) const
    {
        return path == rhs.path;
    }
    bool accessIsPossible( QString& error ) const;
    bool canAccess( const QString& path ) const;

    QStringList subPaths() const
    {
        QStringList paths;
        paths << path + QString::fromLatin1("/cur");
        paths << path + QString::fromLatin1("/new");
        paths << path + QString::fromLatin1("/tmp");
        return paths;
    }

    QStringList listNew() const
    {
        QDir d( path + QString::fromLatin1("/new") );
        return d.entryList(QDir::Files);
    }

    QStringList listCurrent() const
    {
        QDir d( path + QString::fromLatin1("/cur") );
        return d.entryList(QDir::Files);
    }

    QString findRealKey( const QString& key ) const
    {
        QString realKey = path + QString::fromLatin1("/new/") + key;
        QFile f( realKey );
        if ( !f.exists() )
            realKey = path + QString::fromLatin1("/cur/") + key;
        QFile f2( realKey );
        if ( !f2.exists() )
            realKey = QString();
        return realKey;
    }

    QString subDirPath() const
    {
        QDir dir( path );
        return QString::fromLatin1(".%1.directory").arg( dir.dirName() );
    }

    QString path;
    bool isRoot;
};

Maildir::Maildir( const QString& path, bool isRoot )
:d( new Private(path, isRoot) )
{
}

void Maildir::swap( const Maildir &rhs )
{
    Private *p = d;
    d = new Private( *rhs.d );
    delete p;
}

Maildir::Maildir(const Maildir & rhs)
  :d( new Private(*rhs.d) )

{
}

Maildir& Maildir::operator= (const Maildir & rhs)
{
    // copy and swap, exception safe, and handles assignment to self
    Maildir temp(rhs);
    swap( temp );
    return *this;
}

bool Maildir::operator== (const Maildir & rhs) const
{
    return *d == *rhs.d;
}

Maildir::~Maildir()
{
    delete d;
}

bool Maildir::Private::canAccess( const QString& path ) const
{
    //return access(QFile::encodeName( path ), R_OK | W_OK | X_OK ) != 0;
    // FIXME X_OK?
    QFileInfo d(path);
    return d.isReadable() && d.isWritable();
}

bool Maildir::Private::accessIsPossible( QString& error ) const
{
    QStringList paths = subPaths();
    paths.prepend( path );

    Q_FOREACH( QString p, paths )
    {
        if ( !QFile::exists(p) ) {
            error = i18n("Error opening %1; this folder is missing.",p);
            return false;
        }
        if ( !canAccess( p ) ) {
            error = i18n("Error opening %1; either this is not a valid "
                    "maildir folder, or you do not have sufficient access permissions." ,p);
            return false;
        }
    }
    return true;
}

bool Maildir::isValid() const
{
    QString error;
    return isValid( error );
}

bool Maildir::isValid( QString &error ) const
{
    if ( d->accessIsPossible( error ) ) {
        return true;
    }
    return false;
}

bool Maildir::create()
{
    // FIXME: in a failure case, this will leave partially created dirs around
    // we should clean them up, but only if they didn't previously existed...
    Q_FOREACH( QString p, d->subPaths() ) {
        QDir dir( p );
        if ( !dir.exists( p ) ) {
            if ( !dir.mkpath( p ) )
                return false;
        }
    }
    return true;
}

QString Maildir::path() const
{
    return d->path;
}

bool Maildir::addSubFolder( const QString& path )
{
    if ( !isValid() ) return false;
    // make the subdir dir
    QDir dir( d->path );
    if ( !d->isRoot ) {
        dir.cdUp();
        if (!dir.exists( d->subDirPath() ) )
            dir.mkdir( d->subDirPath() );
        dir.cd( d->subDirPath() );
    }

    const QString fullPath = dir.path() + '/' + path;
    Maildir subdir( fullPath );
    if ( subdir.create() )
        return true;
    return false;
}

bool Maildir::removeSubFolder( const QString& folderName )
{
    if ( !isValid() ) return false;
    QDir dir( d->path );
    if ( !d->isRoot ) {
        dir.cdUp();
        if ( !dir.exists( d->subDirPath() ) ) return false;
        dir.cd( d->subDirPath() );
    }
    if ( !dir.exists( folderName ) ) return false;

    // remove it recursively
    return KPIMUtils::removeDirAndContentsRecursively( dir.absolutePath() + '/' + folderName );
}

Maildir Maildir::subFolder( const QString& subFolder )
{
    if ( isValid() ) {
        // make the subdir dir
        QDir dir( d->path );
        if ( !d->isRoot ) {
            dir.cdUp();
            if ( dir.exists( d->subDirPath() ) ) {
                dir.cd( d->subDirPath() );
            }
        }
        return Maildir( dir.path() + '/' + subFolder );
    }
    return Maildir();
}

QStringList Maildir::entryList() const
{
    QStringList result;
    if ( isValid() ) {
        result += d->listNew();
        result += d->listCurrent();
    }
    //  kDebug() <<"Maildir::entryList()" << result;
    return result;
}

QStringList Maildir::subFolderList() const
{
    QDir dir( d->path );

    // the root maildir has its subfolders directly beneath it
    if ( !d->isRoot ) {
        dir.cdUp();
        if (!dir.exists( d->subDirPath() ) ) return QStringList();
        dir.cd( d->subDirPath() );
    }
    dir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot );
    QStringList entries = dir.entryList();
    entries.removeAll( "cur" );
    entries.removeAll( "new" );
    entries.removeAll( "tmp" );
    return entries;
}

QByteArray Maildir::readEntry( const QString& key ) const
{
    QByteArray result;

    QString realKey( d->findRealKey( key ) );
    if ( realKey.isEmpty() ) {
        // FIXME error handling?
        qWarning() << "Maildir::readEntry unable to find: " << key;
        return result;
    }

    QFile f( realKey );
    f.open( QIODevice::ReadOnly );

    // FIXME be safer than this
    result = f.readAll();

    return result;
}

QByteArray Maildir::readEntryHeaders( const QString& key ) const
{
    QByteArray result;

    QString realKey( d->findRealKey( key ) );
    if ( realKey.isEmpty() ) {
        // FIXME error handling?
        qWarning() << "Maildir::readEntry unable to find: " << key;
        return result;
    }

    QFile f( realKey );
    if ( !f.open( QIODevice::ReadOnly ) ) {
        // FIXME error handling?
        qWarning() << "Maildir::readEntry unable to find: " << key;
        return result;
    }
    forever {
        QByteArray line = f.readLine();
        if ( line.trimmed().isEmpty() )
            break;
        result.append( line );
    }
    return result;
}

static QString createUniqueFileName()
{
    return QUuid::createUuid().toString();
}

void Maildir::writeEntry( const QString& key, const QByteArray& data )
{
    QString realKey( d->findRealKey( key ) );
    if ( realKey.isEmpty() ) {
        // FIXME error handling?
        qWarning() << "Maildir::writeEntry unable to find: " << key;
        return;
    }
    QFile f( realKey );
    f.open( QIODevice::WriteOnly );
    f.write( data );
    f.close();
}

QString Maildir::addEntry( const QByteArray& data )
{
    QString uniqueKey( createUniqueFileName() );
    QString key( d->path + "/tmp/" + uniqueKey );
    QString finalKey( d->path + "/new/" + uniqueKey );
    QFile f( key );
    f.open( QIODevice::WriteOnly );
    f.write( data );
    f.close();
    /*
     * FIXME:
     *
     * THe whole point of the locking free maildir idea is that the moves between
     * the internal directories are atomic. Afaik QFile::rename does not guarantee
     * that, so this will need to be done properly. - ta
     */
    if (!f.rename( finalKey )) {
        qWarning() << "Maildir: Failed to add entry: " << finalKey  << "!";
    }
    return uniqueKey;
}

bool Maildir::removeEntry( const QString& key )
{
    QString realKey( d->findRealKey( key ) );
    if ( realKey.isEmpty() ) {
        // FIXME error handling?
        qWarning() << "Maildir::removeEntry unable to find: " << key;
        return false;
    }
    return QFile::remove(realKey);
}

<|endoftext|>


<commit_before>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <Windows.h>
#include <tchar.h>

LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
  switch (msg) {
  case WM_CREATE:
    {
      RECT rc{};
      GetClientRect(hWnd, &rc);
      auto x = GetSystemMetrics(SM_CXSCREEN) / 2 - (rc.right - rc.left) / 2;
      auto y = GetSystemMetrics(SM_CYSCREEN) / 2 - (rc.bottom - rc.top) / 2;
      SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
    } break;
  case WM_KEYDOWN:
    switch (wp) {
    case VK_ESCAPE:
      MessageBox(hWnd, TEXT("ESC down"), TEXT("Keyboard"), MB_OK);
      PostMessage(hWnd, WM_CLOSE, 0, 0);
      break;
    }
    return 0;
  case WM_CLOSE:
    DestroyWindow(hWnd);
    return 0;
  case WM_RBUTTONDOWN:
    MessageBox(hWnd, TEXT("Right button down"), TEXT("Mouse"), MB_OK);
    return 0;
  case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
  }

  return DefWindowProc(hWnd, msg, wp, lp);
}

static BOOL initWindow(HINSTANCE hInst, int cmdShow) {
  WNDCLASS wc{};
  wc.lpfnWndProc = static_cast<WNDPROC>(wndProc);
  wc.hInstance = hInst;
  wc.hbrBackground = CreateSolidBrush(RGB(100, 0, 0));
  wc.lpszClassName = TEXT("Hello");
  RegisterClass(&wc);

  auto hWnd = CreateWindow(
      TEXT("Hello"), TEXT("Hello, world"),
      WS_POPUP | WS_MAXIMIZE, 0, 0,
      GetSystemMetrics(SM_CXSCREEN) / 2,
      GetSystemMetrics(SM_CYSCREEN) / 2,
      NULL, NULL, hInst, NULL);
  if (!hWnd)
    return FALSE;
  ShowWindow(hWnd, cmdShow);
  UpdateWindow(hWnd);
  return TRUE;
}

int CALLBACK _tWinMain(
    HINSTANCE hInst, HINSTANCE hPrev, LPTSTR cmdLine, int cmdShow) {
  if (!initWindow(hInst, cmdShow))
    return 0;

  MSG msg;
  for (;;) {
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT)
        break;
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }
  return static_cast<int>(msg.wParam);
}
<commit_msg>:construction: chore(wgame): add init ddraw for wgame<commit_after>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <Windows.h>
#include <tchar.h>
#include <ddraw.h>
#include "ddutils.h"

LPDIRECTDRAW7 lpdd; // DirectDraw pointer
LPDIRECTDRAWSURFACE7 lpddPrimary; // DirectDraw main surface
LPDIRECTDRAWSURFACE7 lpddBuffer; // DirectDraw background surface
LPDIRECTDRAWSURFACE7 lpddBack;

static LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) {
  switch (msg) {
  case WM_CREATE:
    {
      RECT rc{};
      GetClientRect(hWnd, &rc);
      auto x = GetSystemMetrics(SM_CXSCREEN) / 2 - (rc.right - rc.left) / 2;
      auto y = GetSystemMetrics(SM_CYSCREEN) / 2 - (rc.bottom - rc.top) / 2;
      SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
    } break;
  case WM_KEYDOWN:
    switch (wp) {
    case VK_ESCAPE:
      MessageBox(hWnd, TEXT("ESC down"), TEXT("Keyboard"), MB_OK);
      PostMessage(hWnd, WM_CLOSE, 0, 0);
      break;
    }
    return 0;
  case WM_CLOSE:
    DestroyWindow(hWnd);
    return 0;
  case WM_RBUTTONDOWN:
    MessageBox(hWnd, TEXT("Right button down"), TEXT("Mouse"), MB_OK);
    return 0;
  case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
  }

  return DefWindowProc(hWnd, msg, wp, lp);
}

static BOOL initWindow(HINSTANCE hInst, int cmdShow) {
  WNDCLASS wc{};
  wc.lpfnWndProc = static_cast<WNDPROC>(wndProc);
  wc.hInstance = hInst;
  wc.hbrBackground = CreateSolidBrush(RGB(100, 0, 0));
  wc.lpszClassName = TEXT("Hello");
  RegisterClass(&wc);

  auto hWnd = CreateWindow(
      TEXT("Hello"), TEXT("Hello, world"),
      WS_POPUP | WS_MAXIMIZE, 0, 0,
      GetSystemMetrics(SM_CXSCREEN) / 2,
      GetSystemMetrics(SM_CYSCREEN) / 2,
      NULL, NULL, hInst, NULL);
  if (!hWnd)
    return FALSE;
  ShowWindow(hWnd, cmdShow);
  UpdateWindow(hWnd);
  return TRUE;
}

static void initDDraw(HWND hWnd) {
  DirectDrawCreateEx(NULL, (void**)&lpdd, IID_IDirectDraw7, NULL);
  lpdd->SetCooperativeLevel(hWnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
  lpdd->SetDisplayMode(800, 600, 32, 0, DDSDM_STANDARDVGAMODE);

  DDSURFACEDESC2 ddsd{};
  ddsd.dwSize = sizeof(ddsd);
  ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
  ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX;
  ddsd.dwBackBufferCount = 1;
  lpdd->CreateSurface(&ddsd, &lpddPrimary, NULL);

  ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER;
  lpddPrimary->GetAttachedSurface(&ddsd.ddsCaps, &lpddBuffer);

  DDBLTFX bltfx{};
  bltfx.dwSize = sizeof(bltfx);
  bltfx.dwFillColor = RGB(0, 0, 0);
  lpddPrimary->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &bltfx);
  lpddBuffer->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &bltfx);

  ddsd.dwSize = sizeof(ddsd);
  ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
  ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
  ddsd.dwHeight = 16;
  ddsd.dwWidth = 16;
  lpdd->CreateSurface(&ddsd, &lpddBack, NULL);
  dd_reloadBitmap(lpddBack, TEXT("ball.bmp")); // need ball.bmp resource
  dd_setColorKey(lpddBack, RGB(255, 255, 255));
}

int CALLBACK _tWinMain(
    HINSTANCE hInst, HINSTANCE hPrev, LPTSTR cmdLine, int cmdShow) {
  if (!initWindow(hInst, cmdShow))
    return 0;

  MSG msg;
  for (;;) {
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT)
        break;
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }
  return static_cast<int>(msg.wParam);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ik_ce.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:14:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ARY_IDL_IK_CE_HXX
#define ARY_IDL_IK_CE_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/idl/i_language.hxx>
#include <ary/stdconstiter.hxx>

namespace ary
{
namespace info
{
     class Text;
}
namespace idl
{

namespace ifc_ce
{

typedef ::ary::Dyn_StdConstIterator<Ce_id>      Dyn_CeIterator;
typedef ::ary::Dyn_StdConstIterator<Type_id>    Dyn_TypeIterator;
typedef ::ary::info::Text                       DocText;

struct attr
{
    static Ce_id        CeId(
                            const CodeEntity &  i_ce );
    static const String &
                        LocalName(
                            const CodeEntity &  i_ce );
    static Ce_id        NameRoom(
                            const CodeEntity &  i_ce );
    static Rid          Owner(
                            const CodeEntity &  i_ce );
    static E_SightLevel SightLevel(
                            const CodeEntity &  i_ce );
    static bool         Search_Member(
                            const CodeEntity &  i_ce,
                            const String &      i_memberName )
                            { return true; }    // KORR_FUTURE
};

struct xref
{
};

struct doc
{
    static const DocText &
                        ShortInfo(          /// @return a short description of the CodeEntity
                            const CodeEntity &  i_ce );

    static const DocText &
                        TagAuthor(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagExample(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagDescr(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagGuarantees(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagKey(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagMissing(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagSee(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagShort(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagVersion(
                            const CodeEntity &  i_ce );

    void                Get_UnkownTags(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );

    bool                IsDeprecated(
                            const CodeEntity &  i_ce );
    bool                IsIncomplete(
                            const CodeEntity &  i_ce );
    bool                IsInternal(
                            const CodeEntity &  i_ce );
    bool                IsNodoc(
                            const CodeEntity &  i_ce );
    bool                IsOptional(
                            const CodeEntity &  i_ce );
    bool                IsSuspicious(
                            const CodeEntity &  i_ce );

};

}   // namespace ifc_ce

}   // namspace idl
}   // namspace ary

#endif

<commit_msg>INTEGRATION: CWS warnings01 (1.2.4); FILE MERGED 2005/10/18 08:35:40 np 1.2.4.1: #i53898#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ik_ce.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:48:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ARY_IDL_IK_CE_HXX
#define ARY_IDL_IK_CE_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/idl/i_language.hxx>
#include <ary/stdconstiter.hxx>

namespace ary
{
namespace info
{
     class Text;
}
namespace idl
{

namespace ifc_ce
{

typedef ::ary::Dyn_StdConstIterator<Ce_id>      Dyn_CeIterator;
typedef ::ary::Dyn_StdConstIterator<Type_id>    Dyn_TypeIterator;
typedef ::ary::info::Text                       DocText;

struct attr
{
    static Ce_id        CeId(
                            const CodeEntity &  i_ce );
    static const String &
                        LocalName(
                            const CodeEntity &  i_ce );
    static Ce_id        NameRoom(
                            const CodeEntity &  i_ce );
    static Rid          Owner(
                            const CodeEntity &  i_ce );
    static E_SightLevel SightLevel(
                            const CodeEntity &  i_ce );
    static bool         Search_Member(
                            const CodeEntity &  ,
                            const String &      )
                            { return true; }    // KORR_FUTURE
};

struct xref
{
};

struct doc
{
    static const DocText &
                        ShortInfo(          /// @return a short description of the CodeEntity
                            const CodeEntity &  i_ce );

    static const DocText &
                        TagAuthor(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagExample(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagDescr(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagGuarantees(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagKey(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagMissing(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagSee(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagShort(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagVersion(
                            const CodeEntity &  i_ce );

    void                Get_UnkownTags(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );

    bool                IsDeprecated(
                            const CodeEntity &  i_ce );
    bool                IsIncomplete(
                            const CodeEntity &  i_ce );
    bool                IsInternal(
                            const CodeEntity &  i_ce );
    bool                IsNodoc(
                            const CodeEntity &  i_ce );
    bool                IsOptional(
                            const CodeEntity &  i_ce );
    bool                IsSuspicious(
                            const CodeEntity &  i_ce );

};

}   // namespace ifc_ce

}   // namspace idl
}   // namspace ary

#endif

<|endoftext|>