<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * 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 "dbusmessagewriter.h"
#define DBUS_API_SUBJECT_TO_CHANGE
#include <dbus/dbus.h>
#include "textutils.h"
using namespace std;

DBusMessageWriter::DBusMessageWriter(DBusConnection* c, DBusMessage* msg)
        :conn(c), error(0) {
    reply = dbus_message_new_method_return(msg);
    dbus_message_iter_init_append(reply, &it);
}
DBusMessageWriter::~DBusMessageWriter() {
    DBusMessage* msg = (error) ?error :reply;
    dbus_uint32_t serial = 0;
    dbus_connection_send(conn, msg, &serial);
    dbus_connection_flush(conn);
    dbus_message_unref(reply);
    if (error) {
        dbus_message_unref(error);
    }
}
void
DBusMessageWriter::setError(const std::string &e) {
    error = dbus_message_new(DBUS_MESSAGE_TYPE_ERROR);
    dbus_message_set_error_name(error, e.c_str());
}
DBusMessageWriter&
DBusMessageWriter::operator<<(bool b) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_BOOLEAN, &b);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int32_t i) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_INT32, &i);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int64_t i) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_INT64, &i);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(double d) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_DOUBLE, &d);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::string& s) {
    const char* c = s.c_str();
    dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &c);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const set<string>& s) {
    DBusMessageIter sub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        DBUS_TYPE_STRING_AS_STRING, &sub);
    set<string>::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        const char* c = i->c_str();
        dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::map<std::string, std::string>& m) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "{ss}", &sub);
    map<string, string>::const_iterator i;
    for (i = m.begin(); i != m.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, 0, &ssub);
        const char* c = i->first.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::string>& s) {
    DBusMessageIter sub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        DBUS_TYPE_STRING_AS_STRING, &sub);
    vector<string>::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        const char* c = i->c_str();
        dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
/* yes this is ugly, i have to change the interface */
DBusMessageWriter&
DBusMessageWriter::operator<<(const ClientInterface::Hits& s) {
    DBusMessageIter sub;
    DBusMessageIter ssub;
    DBusMessageIter sssub;
    DBusMessageIter ssssub;
    DBusMessageIter sssssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        "(sdsssxxa{sas})", &sub);
    vector<jstreams::IndexedDocument>::const_iterator i;
    for (i=s.hits.begin(); i!=s.hits.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        const char* c = i->uri.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        double d = i->score;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_DOUBLE, &d);
        // quick bug fix on what is probably a clucene bug
        // the fragments as stored are sometimes not properly recoded back
        // from usc2 to utf8 which causes dbus to close the connection,
        // whereupon the strigidaemon quits
        if (jstreams::checkUtf8(i->fragment.c_str(), i->fragment.size())) {
            c = i->fragment.c_str();
        } else {
            c = "";
        }
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->mimetype.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->sha1.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        int64_t n = i->size;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
        n = i->mtime;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
        dbus_message_iter_open_container(&ssub, DBUS_TYPE_ARRAY, "{sas})",
            &sssub);
        multimap<string, string>::const_iterator j;
        for (j = i->properties.begin(); j != i->properties.end(); ++j) {
            dbus_message_iter_open_container(&sssub, DBUS_TYPE_DICT_ENTRY, 0,
                &ssssub);
            const char* c = j->first.c_str();
            dbus_message_iter_append_basic(&ssssub, DBUS_TYPE_STRING, &c);
            dbus_message_iter_open_container(&ssssub, DBUS_TYPE_ARRAY, "s",
                &sssssub);
            c = j->second.c_str();
            dbus_message_iter_append_basic(&sssssub, DBUS_TYPE_STRING, &c);
            dbus_message_iter_close_container(&ssssub, &sssssub);
            dbus_message_iter_close_container(&sssub, &ssssub);
        }
        dbus_message_iter_close_container(&ssub, &sssub);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
/** map multimap<int,string> to 'a(is)' **/
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::multimap<int, std::string>& m) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(is)", &sub);
    multimap<int,string>::const_iterator i;
    for (i = m.begin(); i != m.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        int32_t n = i->first;
        const char* s = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT32, &n);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<bool, std::string> >& s) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
    vector<pair<bool,string> >::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        dbus_bool_t n = i->first;
        const char* s = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_BOOLEAN, &n);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<std::string, uint32_t> >& s) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
    vector<pair<string,uint32_t> >::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        const char* s = i->first.c_str();
        dbus_uint32_t n = i->second;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_UINT32, &n);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);

    return *this;
}
<commit_msg>Fix dbus message signature.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * 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 "dbusmessagewriter.h"
#define DBUS_API_SUBJECT_TO_CHANGE
#include <dbus/dbus.h>
#include "textutils.h"
using namespace std;

DBusMessageWriter::DBusMessageWriter(DBusConnection* c, DBusMessage* msg)
        :conn(c), error(0) {
    reply = dbus_message_new_method_return(msg);
    dbus_message_iter_init_append(reply, &it);
}
DBusMessageWriter::~DBusMessageWriter() {
    DBusMessage* msg = (error) ?error :reply;
    dbus_uint32_t serial = 0;
    dbus_connection_send(conn, msg, &serial);
    dbus_connection_flush(conn);
    dbus_message_unref(reply);
    if (error) {
        dbus_message_unref(error);
    }
}
void
DBusMessageWriter::setError(const std::string &e) {
    error = dbus_message_new(DBUS_MESSAGE_TYPE_ERROR);
    dbus_message_set_error_name(error, e.c_str());
}
DBusMessageWriter&
DBusMessageWriter::operator<<(bool b) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_BOOLEAN, &b);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int32_t i) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_INT32, &i);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(int64_t i) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_INT64, &i);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(double d) {
    dbus_message_iter_append_basic(&it, DBUS_TYPE_DOUBLE, &d);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::string& s) {
    const char* c = s.c_str();
    dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &c);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const set<string>& s) {
    DBusMessageIter sub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        DBUS_TYPE_STRING_AS_STRING, &sub);
    set<string>::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        const char* c = i->c_str();
        dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::map<std::string, std::string>& m) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "{ss}", &sub);
    map<string, string>::const_iterator i;
    for (i = m.begin(); i != m.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, 0, &ssub);
        const char* c = i->first.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::string>& s) {
    DBusMessageIter sub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        DBUS_TYPE_STRING_AS_STRING, &sub);
    vector<string>::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        const char* c = i->c_str();
        dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &c);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
/* yes this is ugly, i have to change the interface */
DBusMessageWriter&
DBusMessageWriter::operator<<(const ClientInterface::Hits& s) {
    DBusMessageIter sub;
    DBusMessageIter ssub;
    DBusMessageIter sssub;
    DBusMessageIter ssssub;
    DBusMessageIter sssssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY,
        "(sdsssxxa{sas})", &sub);
    vector<jstreams::IndexedDocument>::const_iterator i;
    for (i=s.hits.begin(); i!=s.hits.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        const char* c = i->uri.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        double d = i->score;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_DOUBLE, &d);
        // quick bug fix on what is probably a clucene bug
        // the fragments as stored are sometimes not properly recoded back
        // from usc2 to utf8 which causes dbus to close the connection,
        // whereupon the strigidaemon quits
        if (jstreams::checkUtf8(i->fragment.c_str(), i->fragment.size())) {
            c = i->fragment.c_str();
        } else {
            c = "";
        }
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->mimetype.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        c = i->sha1.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &c);
        int64_t n = i->size;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
        n = i->mtime;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT64, &n);
        dbus_message_iter_open_container(&ssub, DBUS_TYPE_ARRAY, "{sas})",
            &sssub);
        multimap<string, string>::const_iterator j;
        for (j = i->properties.begin(); j != i->properties.end(); ++j) {
            dbus_message_iter_open_container(&sssub, DBUS_TYPE_DICT_ENTRY, 0,
                &ssssub);
            const char* c = j->first.c_str();
            dbus_message_iter_append_basic(&ssssub, DBUS_TYPE_STRING, &c);
            dbus_message_iter_open_container(&ssssub, DBUS_TYPE_ARRAY, "s",
                &sssssub);
            c = j->second.c_str();
            dbus_message_iter_append_basic(&sssssub, DBUS_TYPE_STRING, &c);
            dbus_message_iter_close_container(&ssssub, &sssssub);
            dbus_message_iter_close_container(&sssub, &ssssub);
        }
        dbus_message_iter_close_container(&ssub, &sssub);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
/** map multimap<int,string> to 'a(is)' **/
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::multimap<int, std::string>& m) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(is)", &sub);
    multimap<int,string>::const_iterator i;
    for (i = m.begin(); i != m.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        int32_t n = i->first;
        const char* s = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_INT32, &n);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<bool, std::string> >& s) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(bs)", &sub);
    vector<pair<bool,string> >::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        dbus_bool_t n = i->first;
        const char* s = i->second.c_str();
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_BOOLEAN, &n);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);
    return *this;
}
DBusMessageWriter&
DBusMessageWriter::operator<<(const std::vector<std::pair<std::string, uint32_t> >& s) {
    DBusMessageIter sub, ssub;
    dbus_message_iter_open_container(&it, DBUS_TYPE_ARRAY, "(su)", &sub);
    vector<pair<string,uint32_t> >::const_iterator i;
    for (i = s.begin(); i != s.end(); ++i) {
        dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, 0, &ssub);
        const char* s = i->first.c_str();
        dbus_uint32_t n = i->second;
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_STRING, &s);
        dbus_message_iter_append_basic(&ssub, DBUS_TYPE_UINT32, &n);
        dbus_message_iter_close_container(&sub, &ssub);
    }
    dbus_message_iter_close_container(&it, &sub);

    return *this;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <set>
#include "BinaryRegion.hpp"

int main(int argc, char** argv) {
	BinaryRegion binaryRegion(
		0x00400000,	/* Base address */
		0,			/* Entry point offset */
		"\x50\x8B\xD9\xEB\x01\xDE\x83\xF2\x43",
		9
	);

	return EXIT_SUCCESS;

}<commit_msg>furthering region split test<commit_after>#include <cstdlib>
#include <set>
#include <stack>
#include <libdasm.h>
#include <iostream>

#include "BinaryBlock.hpp"
#include "BinaryRegion.hpp"

bool is_address_within_blocks(const int64_t& address, std::set<BinaryBlock*>& binaryBlocks) {
	std::set<BinaryBlock*>::const_iterator it = binaryBlocks.begin();
	bool match = false;

	while(!match && it != binaryBlocks.end()) {
		if(address >= (*it)->address() && address <= (*it)->address() + (*it)->length()) {
			match = !match;
		}
		++it;
	}
}
void analyze_binary_region(const BinaryRegion& binaryRegion, std::set<BinaryBlock*>& binaryBlocks);

int main(int argc, char** argv) {
	BinaryRegion binaryRegion(
		0x00400000,	/* Base address */
		0,			/* Entry point offset */
		"\x50\x8B\xD9\xEB\x01\xDE\x83\xF2\x43",
		9
	);

	return EXIT_SUCCESS;

}

void analyze_binary_region(const BinaryRegion& binaryRegion, std::set<BinaryBlock*>& binaryBlocks) {
	int64_t current_memory_address = binaryRegion.baseAddress() + binaryRegion.entryPointOffset();

	// The current_memory_address should not be into any pre-existing binary block
	if(is_address_within_blocks(current_memory_address, binaryBlocks)) {
		return;
	}

}<|endoftext|>


<commit_before>/*
  This file is part of KAddressBook.
  Copyright (c) 2002 Mike Pilone <mpilone@slac.com>

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include <qapplication.h>
#include <qclipboard.h>

#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kprotocolinfo.h>
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>

#include "actionmanager.h"
#include "kaddressbook.h"
#include "viewmanager.h"
#include "undo.h"

ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget,
                             bool readWrite, QObject *parent)
    : QObject(parent)
{
    mGUIClient = client;
    mACollection = mGUIClient->actionCollection();

    mWidget = widget;
    connect( mWidget, SIGNAL( addresseeSelected( bool ) ),
             SLOT( addresseeSelected( bool ) ) );
    connect( mWidget, SIGNAL( modified( bool ) ),
             SLOT( modified( bool ) ) );

    mViewManager = mWidget->viewManager();
    connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ),
             SLOT( viewConfigChanged(const QString &) ) );

    connect( QApplication::clipboard(), SIGNAL( dataChanged() ),
             SLOT( clipboardDataChanged() ) );

    mReadWrite = readWrite;
    initReadOnlyActions();
    if (mReadWrite)
        initReadWriteActions();

    // Read our own config
    KConfig *config = kapp->config();
    config->setGroup("Views");
    mActiveViewName = config->readEntry("Active");
    config->setGroup("MainWindow");
    mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false));
    mActionFeatures->setCurrentItem(config->readNumEntry("Features", 0));
    mActionDetails->setChecked(config->readBoolEntry("Details", true));
    // Set the defaults
    addresseeSelected(false);
    modified(false);
    quickToolsAction();

    mActionViewList.setAutoDelete(true);

    // Connect to the signals from the undo/redo stacks so we can update the
    // edit menu
    connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
    connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
}

ActionManager::~ActionManager()
{
    // Write our own config
    KConfig *config = kapp->config();

    config->setGroup("Views");
    config->writeEntry("Active", mActiveViewName);

    config->setGroup("MainWindow");
    config->writeEntry("JumpBar", mActionJumpBar->isChecked());
    config->writeEntry("Features", mActionFeatures->currentItem());
    config->writeEntry("Details", mActionDetails->isChecked());

    config->sync();
}

void ActionManager::setReadWrite(bool rw)
{
    if (rw == mReadWrite)
        return;

    mReadWrite = rw;
    if (mReadWrite)
        initReadWriteActions();
    else
        destroyReadWriteActions();
}

void ActionManager::clipboardDataChanged()
{
    if (mReadWrite)
        mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}

void ActionManager::initReadOnlyActions()
{
    // File menu
    mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget,
                              SLOT(save()), mACollection,"file_sync");

    new KAction(i18n("&New Contact..."), "filenew", CTRL+Key_N, mWidget,
                SLOT(newAddressee()),mACollection,"file_new_contact");

    mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()),
                                   mACollection);
    mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0,
                                       mWidget, SLOT(editAddressee()),
                                       mACollection, "file_properties");

    KStdAction::print(mWidget, SLOT(print()), mACollection);

    new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget,
                SLOT(importKDE2()), mACollection, "file_import_kde2");

    new KAction(i18n("Import vCard..."), 0, mWidget, SLOT(importVCardSimple()),
                mACollection, "file_import_vcard");

    new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()),
                mACollection, "file_import_csv");

    new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()),
                mACollection, "file_export_csv");

    new KAction(i18n("&Export vCard 3.0..."), 0, mWidget, SLOT(exportVCard30()),
                mACollection, "file_export_vcard30");

    // Edit menu
    mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()),
                                   mACollection);

    KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection);

    mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete",
                                Key_Delete, mViewManager,
                                SLOT(deleteAddressee()), mACollection,
                                "edit_delete");

    mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection);
    mActionUndo->setEnabled(false);

    mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection);
    mActionRedo->setEnabled( false );

    // View menu
    new KAction(i18n("Modify View..."), "configure", 0, mViewManager,
                SLOT(modifyView()), mACollection,
                "view_modify");
    new KAction(i18n("Add View..."), "window_new", 0, mViewManager,
                SLOT(addView()), mACollection,
                "view_add");
    mActionDeleteView = new KAction(i18n("Delete View"), "view_remove", 0,
                                    mViewManager,
                                    SLOT(deleteView()), mACollection,
                                    "view_delete");
    new KAction(i18n("Refresh View"), "reload", 0, mViewManager,
                SLOT(refresh()), mACollection,
                "view_refresh");

    // Only enable LDAP lookup if we can handle the protocol
    if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) {
        // LDAP button on toolbar
        new KAction(i18n("&Lookup addresses in directory"),
                    "ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()),
                    mACollection,"ldap_lookup");
    }

    // Settings menu
    mActionFeatures = new KSelectAction( i18n("Show Features Bar"),
                                         0, mACollection,
                                         "options_show_features" );
    connect( mActionFeatures, SIGNAL( activated( int ) ),
             mViewManager, SLOT( showFeatures( int ) ) );
    QStringList features;
    features << i18n("None") << i18n("Contact Editor")
             << i18n("Distribution Lists");
    mActionFeatures->setItems( features );

    mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0,
                                       this, SLOT(quickToolsAction()),
                                       mACollection,
                                       "options_show_jump_bar");
    mActionDetails = new KToggleAction(i18n("Show Details"), 0,
                                       0, this, SLOT(quickToolsAction()),
                                       mACollection,
                                       "options_show_details");
    (void) new KAction(i18n("Edit &Filters..."), "filter",
                       0, mWidget, SLOT(configureFilters()),
                       mACollection, "options_edit_filters");
    mActionSelectFilter = new KSelectAction(i18n("Select Filter"), 0,
                                            0,
                                            this, SLOT(slotFilterActivated(int)),
                                            mACollection, "select_filter");
#if KDE_VERSION >= 309
    mActionSelectFilter->setMenuAccelsEnabled( false );
#endif

    connect(mActionSelectFilter, SIGNAL(activated(int)),
            SLOT(slotFilterActivated(int)));
    connect(this, SIGNAL(filterActivated(int)),
            mViewManager, SLOT(filterActivated(int)));
    connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)),
            SLOT(setFilterNames(const QStringList&)));
    connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)),
            SLOT(setCurrentFilterName(const QString&)));
    connect(mViewManager, SIGNAL(setCurrentFilter(int)),
            SLOT(setCurrentFilter(int)));
}

void ActionManager::initReadWriteActions()
{
    // Edit menu
    mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection);
    mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()),
                                     mACollection);
    clipboardDataChanged();
}

void ActionManager::destroyReadWriteActions()
{
    delete mActionCut;
    delete mActionPaste;
}

void ActionManager::updateEditMenu()
{
    UndoStack *undo = UndoStack::instance();
    RedoStack *redo = RedoStack::instance();

    if (undo->isEmpty())
        mActionUndo->setText( i18n( "Undo" ) );
    else
        mActionUndo->setText( i18n( "Undo %1" ).arg(undo->top()->name()) );
    mActionUndo->setEnabled( !undo->isEmpty() );

    if (!redo->top())
        mActionRedo->setText( i18n( "Redo" ) );
    else
        mActionRedo->setText( i18n( "Redo %1" ).arg(redo->top()->name()) );
    mActionRedo->setEnabled( !redo->isEmpty() );
}

void ActionManager::addresseeSelected(bool selected)
{
    if (mReadWrite)
    {
        mActionCut->setEnabled(selected);
    }

    mActionCopy->setEnabled(selected);
    mActionDelete->setEnabled(selected);
    mActionEditAddressee->setEnabled(selected);
    mActionMail->setEnabled(selected);
}

void ActionManager::modified(bool mod)
{
    mModified = mod;
    mActionSave->setEnabled(mod);
}

void ActionManager::initActionViewList()
{
    // Create the view actions, and set the active view
    // Find the last active view
    QStringList viewNameList = mViewManager->viewNames();
    KToggleAction *viewAction = 0;

    // Just incast there is no active view!
    if (mActiveViewName.isEmpty() ||
        (viewNameList.contains(mActiveViewName) == 0))
        mActiveViewName = *(viewNameList).at(0);

    // unplug the current ones
    mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews");

    // delete the current ones
    mActionViewList.clear();
    mActiveActionView = 0L;

    // Now find the active one, check the menu item, and raise it to the top
    QStringList::Iterator iter;
    QString viewName;
    for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter)
    {
        viewName = *iter;

        viewAction = new KToggleAction(viewName, QString::null, this,
                                       SLOT(selectViewAction()), mACollection,
                                       viewName.latin1());

        if (mActiveViewName == viewName)
        {
            mViewManager->setActiveView(viewName);

            viewAction->setChecked(true);
            mActiveActionView = viewAction;
        }

        mActionViewList.append(viewAction);
    }

    // Now append all the actions to the menu.
    mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews",
                                          mActionViewList);
}

void ActionManager::viewConfigChanged(const QString &newActive)
{
    if (!newActive.isEmpty())
    {
        mActiveViewName = newActive;
    }

    // we need to rebuild the actions
    initActionViewList();

    // Only enable delete if there is more than one view
    mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1);
}

void ActionManager::selectViewAction()
{
    // See if we can find the selected action
    KToggleAction *action = 0;

    QString activatedName = sender()->name();
    QPtrListIterator<KAction> iter(mActionViewList);
    for (iter.toFirst(); iter.current(); ++iter)
    {
        action = dynamic_cast<KToggleAction*>(*iter);

        if (action->name() != activatedName)
            action->setChecked(false);
        else
        {
            mActiveActionView = action;
            mActiveActionView->setChecked(true);
            mActiveViewName = mActiveActionView->name();

            // Last, tell the main widget to set the view.
            mViewManager->setActiveView(mActiveViewName);
        }
    }
}

void ActionManager::quickToolsAction()
{
    mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked());
    mViewManager->showFeatures(mActionFeatures->currentItem());
    mViewManager->setDetailsVisible(mActionDetails->isChecked());
}

void ActionManager::setFilterNames(const QStringList& list)
{
    QString current = mActionSelectFilter->currentText();

    QStringList items;
    items.append(i18n("None"));
    items+=list;
    mActionSelectFilter->setItems(items);

    setCurrentFilterName( current );
}

void ActionManager::slotFilterActivated(int index)
{
    emit filterActivated(index-1);
}

void ActionManager::setCurrentFilterName(const QString& name)
{
    QStringList items=mActionSelectFilter->items();
    int index=items.findIndex(name);
    if( index != -1 )
        setCurrentFilter(index);
}

void ActionManager::setCurrentFilter(int index)
{
    mActionSelectFilter->setCurrentItem(index);
    emit filterActivated(index-1);
}

bool ActionManager::isModified()
{
  return mModified;
}

#include "actionmanager.moc"
<commit_msg>Fix signal -> slot<commit_after>/*
  This file is part of KAddressBook.
  Copyright (c) 2002 Mike Pilone <mpilone@slac.com>

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include <qapplication.h>
#include <qclipboard.h>

#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kprotocolinfo.h>
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>

#include "actionmanager.h"
#include "kaddressbook.h"
#include "viewmanager.h"
#include "undo.h"

ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget,
                             bool readWrite, QObject *parent)
    : QObject(parent)
{
    mGUIClient = client;
    mACollection = mGUIClient->actionCollection();

    mWidget = widget;
    connect( mWidget, SIGNAL( addresseeSelected( bool ) ),
             SLOT( addresseeSelected( bool ) ) );
    connect( mWidget, SIGNAL( modified( bool ) ),
             SLOT( modified( bool ) ) );

    mViewManager = mWidget->viewManager();
    connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ),
             SLOT( viewConfigChanged(const QString &) ) );

    connect( QApplication::clipboard(), SIGNAL( dataChanged() ),
             SLOT( clipboardDataChanged() ) );

    mReadWrite = readWrite;
    initReadOnlyActions();
    if (mReadWrite)
        initReadWriteActions();

    // Read our own config
    KConfig *config = kapp->config();
    config->setGroup("Views");
    mActiveViewName = config->readEntry("Active");
    config->setGroup("MainWindow");
    mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false));
    mActionFeatures->setCurrentItem(config->readNumEntry("Features", 0));
    mActionDetails->setChecked(config->readBoolEntry("Details", true));
    // Set the defaults
    addresseeSelected(false);
    modified(false);
    quickToolsAction();

    mActionViewList.setAutoDelete(true);

    // Connect to the signals from the undo/redo stacks so we can update the
    // edit menu
    connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
    connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu()));
}

ActionManager::~ActionManager()
{
    // Write our own config
    KConfig *config = kapp->config();

    config->setGroup("Views");
    config->writeEntry("Active", mActiveViewName);

    config->setGroup("MainWindow");
    config->writeEntry("JumpBar", mActionJumpBar->isChecked());
    config->writeEntry("Features", mActionFeatures->currentItem());
    config->writeEntry("Details", mActionDetails->isChecked());

    config->sync();
}

void ActionManager::setReadWrite(bool rw)
{
    if (rw == mReadWrite)
        return;

    mReadWrite = rw;
    if (mReadWrite)
        initReadWriteActions();
    else
        destroyReadWriteActions();
}

void ActionManager::clipboardDataChanged()
{
    if (mReadWrite)
        mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() );
}

void ActionManager::initReadOnlyActions()
{
    // File menu
    mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget,
                              SLOT(save()), mACollection,"file_sync");

    new KAction(i18n("&New Contact..."), "filenew", CTRL+Key_N, mWidget,
                SLOT(newAddressee()),mACollection,"file_new_contact");

    mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()),
                                   mACollection);
    mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0,
                                       mWidget, SLOT(editAddressee()),
                                       mACollection, "file_properties");

    KStdAction::print(mWidget, SLOT(print()), mACollection);

    new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget,
                SLOT(importKDE2()), mACollection, "file_import_kde2");

    new KAction(i18n("Import vCard..."), 0, mWidget, SLOT(importVCardSimple()),
                mACollection, "file_import_vcard");

    new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()),
                mACollection, "file_import_csv");

    new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()),
                mACollection, "file_export_csv");

    new KAction(i18n("&Export vCard 3.0..."), 0, mWidget, SLOT(exportVCard30()),
                mACollection, "file_export_vcard30");

    // Edit menu
    mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()),
                                   mACollection);

    KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection);

    mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete",
                                Key_Delete, mViewManager,
                                SLOT(deleteAddressee()), mACollection,
                                "edit_delete");

    mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection);
    mActionUndo->setEnabled(false);

    mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection);
    mActionRedo->setEnabled( false );

    // View menu
    new KAction(i18n("Modify View..."), "configure", 0, mViewManager,
                SLOT(modifyView()), mACollection,
                "view_modify");
    new KAction(i18n("Add View..."), "window_new", 0, mViewManager,
                SLOT(addView()), mACollection,
                "view_add");
    mActionDeleteView = new KAction(i18n("Delete View"), "view_remove", 0,
                                    mViewManager,
                                    SLOT(deleteView()), mACollection,
                                    "view_delete");
    new KAction(i18n("Refresh View"), "reload", 0, mViewManager,
                SLOT(refresh()), mACollection,
                "view_refresh");

    // Only enable LDAP lookup if we can handle the protocol
    if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) {
        // LDAP button on toolbar
        new KAction(i18n("&Lookup addresses in directory"),
                    "ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()),
                    mACollection,"ldap_lookup");
    }

    // Settings menu
    mActionFeatures = new KSelectAction( i18n("Show Features Bar"),
                                         0, mACollection,
                                         "options_show_features" );
    connect( mActionFeatures, SIGNAL( activated( int ) ),
             mViewManager, SLOT( showFeatures( int ) ) );
    QStringList features;
    features << i18n("None") << i18n("Contact Editor")
             << i18n("Distribution Lists");
    mActionFeatures->setItems( features );

    mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0,
                                       this, SLOT(quickToolsAction()),
                                       mACollection,
                                       "options_show_jump_bar");
    mActionDetails = new KToggleAction(i18n("Show Details"), 0,
                                       0, this, SLOT(quickToolsAction()),
                                       mACollection,
                                       "options_show_details");
    (void) new KAction(i18n("Edit &Filters..."), "filter",
                       0, mWidget, SLOT(configureFilters()),
                       mACollection, "options_edit_filters");
    mActionSelectFilter = new KSelectAction(i18n("Select Filter"), 0,
                                            mACollection, "select_filter");
#if KDE_VERSION >= 309
    mActionSelectFilter->setMenuAccelsEnabled( false );
#endif

    connect(mActionSelectFilter, SIGNAL(activated(int)),
            SLOT(slotFilterActivated(int)));
    connect(this, SIGNAL(filterActivated(int)),
            mViewManager, SLOT(filterActivated(int)));
    connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)),
            SLOT(setFilterNames(const QStringList&)));
    connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)),
            SLOT(setCurrentFilterName(const QString&)));
    connect(mViewManager, SIGNAL(setCurrentFilter(int)),
            SLOT(setCurrentFilter(int)));
}

void ActionManager::initReadWriteActions()
{
    // Edit menu
    mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection);
    mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()),
                                     mACollection);
    clipboardDataChanged();
}

void ActionManager::destroyReadWriteActions()
{
    delete mActionCut;
    delete mActionPaste;
}

void ActionManager::updateEditMenu()
{
    UndoStack *undo = UndoStack::instance();
    RedoStack *redo = RedoStack::instance();

    if (undo->isEmpty())
        mActionUndo->setText( i18n( "Undo" ) );
    else
        mActionUndo->setText( i18n( "Undo %1" ).arg(undo->top()->name()) );
    mActionUndo->setEnabled( !undo->isEmpty() );

    if (!redo->top())
        mActionRedo->setText( i18n( "Redo" ) );
    else
        mActionRedo->setText( i18n( "Redo %1" ).arg(redo->top()->name()) );
    mActionRedo->setEnabled( !redo->isEmpty() );
}

void ActionManager::addresseeSelected(bool selected)
{
    if (mReadWrite)
    {
        mActionCut->setEnabled(selected);
    }

    mActionCopy->setEnabled(selected);
    mActionDelete->setEnabled(selected);
    mActionEditAddressee->setEnabled(selected);
    mActionMail->setEnabled(selected);
}

void ActionManager::modified(bool mod)
{
    mModified = mod;
    mActionSave->setEnabled(mod);
}

void ActionManager::initActionViewList()
{
    // Create the view actions, and set the active view
    // Find the last active view
    QStringList viewNameList = mViewManager->viewNames();
    KToggleAction *viewAction = 0;

    // Just incast there is no active view!
    if (mActiveViewName.isEmpty() ||
        (viewNameList.contains(mActiveViewName) == 0))
        mActiveViewName = *(viewNameList).at(0);

    // unplug the current ones
    mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews");

    // delete the current ones
    mActionViewList.clear();
    mActiveActionView = 0L;

    // Now find the active one, check the menu item, and raise it to the top
    QStringList::Iterator iter;
    QString viewName;
    for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter)
    {
        viewName = *iter;

        viewAction = new KToggleAction(viewName, QString::null, this,
                                       SLOT(selectViewAction()), mACollection,
                                       viewName.latin1());

        if (mActiveViewName == viewName)
        {
            mViewManager->setActiveView(viewName);

            viewAction->setChecked(true);
            mActiveActionView = viewAction;
        }

        mActionViewList.append(viewAction);
    }

    // Now append all the actions to the menu.
    mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews",
                                          mActionViewList);
}

void ActionManager::viewConfigChanged(const QString &newActive)
{
    if (!newActive.isEmpty())
    {
        mActiveViewName = newActive;
    }

    // we need to rebuild the actions
    initActionViewList();

    // Only enable delete if there is more than one view
    mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1);
}

void ActionManager::selectViewAction()
{
    // See if we can find the selected action
    KToggleAction *action = 0;

    QString activatedName = sender()->name();
    QPtrListIterator<KAction> iter(mActionViewList);
    for (iter.toFirst(); iter.current(); ++iter)
    {
        action = dynamic_cast<KToggleAction*>(*iter);

        if (action->name() != activatedName)
            action->setChecked(false);
        else
        {
            mActiveActionView = action;
            mActiveActionView->setChecked(true);
            mActiveViewName = mActiveActionView->name();

            // Last, tell the main widget to set the view.
            mViewManager->setActiveView(mActiveViewName);
        }
    }
}

void ActionManager::quickToolsAction()
{
    mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked());
    mViewManager->showFeatures(mActionFeatures->currentItem());
    mViewManager->setDetailsVisible(mActionDetails->isChecked());
}

void ActionManager::setFilterNames(const QStringList& list)
{
    QString current = mActionSelectFilter->currentText();

    QStringList items;
    items.append(i18n("None"));
    items+=list;
    mActionSelectFilter->setItems(items);

    setCurrentFilterName( current );
}

void ActionManager::slotFilterActivated(int index)
{
    emit filterActivated(index-1);
}

void ActionManager::setCurrentFilterName(const QString& name)
{
    QStringList items=mActionSelectFilter->items();
    int index=items.findIndex(name);
    if( index != -1 )
        setCurrentFilter(index);
}

void ActionManager::setCurrentFilter(int index)
{
    mActionSelectFilter->setCurrentItem(index);
    emit filterActivated(index-1);
}

bool ActionManager::isModified()
{
  return mModified;
}

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


<commit_before>// $Id: AutoDeleteable_test.C,v 1.1 2000/08/22 16:59:43 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/CONCEPT/autoDeletable.h>

///////////////////////////

using namespace BALL;

class A: public AutoDeletable
{
};

START_TEST(class_name, "$Id: AutoDeleteable_test.C,v 1.1 2000/08/22 16:59:43 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

A* a_ptr;
A* array_ptr;

CHECK(AutoDeletable::void* operator new(size_t size) throw())
	a_ptr = new A;
	array_ptr = new A[12];
RESULT

CHECK(AutoDeletable::void* operator new(size_t size, void* ptr) throw())
	// BAUSTELLE
RESULT

CHECK(AutoDeletable::void operator delete(void* ptr) throw())
	// BAUSTELLE
RESULT

A a;
a_ptr = new A;
A array[12];
array_ptr = new A[12];

CHECK(AutoDeletable::~AutoDeletable())
	delete a_ptr;
	delete array_ptr; // segfault ???
RESULT

a_ptr = new A;
array_ptr = new A[12];

CHECK(AutoDeletable::isAutoDeletable() const )
	TEST_EQUAL(a.isAutoDeletable(), false)
	TEST_EQUAL(a_ptr->isAutoDeletable(), true)
	TEST_EQUAL(array_ptr->isAutoDeletable(), false)
	TEST_EQUAL(array->isAutoDeletable(), false)
RESULT

CHECK(AutoDeletable::setAutoDeletable(bool enable))
  //BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed error in test for delete<commit_after>// $Id: AutoDeleteable_test.C,v 1.2 2000/08/23 01:02:07 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/CONCEPT/autoDeletable.h>

///////////////////////////

using namespace BALL;

class A: public AutoDeletable
{
};

START_TEST(class_name, "$Id: AutoDeleteable_test.C,v 1.2 2000/08/23 01:02:07 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

A* a_ptr;
A* array_ptr;

CHECK(AutoDeletable::void* operator new(size_t size) throw())
	a_ptr = new A;
	array_ptr = new A[12];
RESULT

CHECK(AutoDeletable::void* operator new(size_t size, void* ptr) throw())
	// BAUSTELLE
RESULT

CHECK(AutoDeletable::void operator delete(void* ptr) throw())
	// BAUSTELLE
RESULT

A a;
a_ptr = new A;
A array[12];
array_ptr = new A[12];

CHECK(AutoDeletable::~AutoDeletable())
	delete a_ptr;
	delete [] array_ptr;
RESULT

a_ptr = new A;
array_ptr = new A[12];

CHECK(AutoDeletable::isAutoDeletable() const )
	TEST_EQUAL(a.isAutoDeletable(), false)
	TEST_EQUAL(a_ptr->isAutoDeletable(), true)
	TEST_EQUAL(array_ptr->isAutoDeletable(), false)
	TEST_EQUAL(array->isAutoDeletable(), false)
RESULT

CHECK(AutoDeletable::setAutoDeletable(bool enable))
  //BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before><commit_msg>Gui: [skip ci] make Save logic of text document more intuitive<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
 * All rights reserved. Use of the code is allowed under the
 * Artistic License 2.0 terms, as specified in the LICENSE file
 * distributed with this code, or available from
 * http://www.opensource.org/licenses/artistic-license-2.0.php
 */
// ExpPWListDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ExpPWListDlg.h"
#include "DboxMain.h"
#include "corelib/MyString.h"
#include "corelib/Util.h"
#include "corelib/ItemData.h"
#include "resource2.h"  // Menu, Toolbar & Accelerator resources
#include "resource3.h"  // String resources

using namespace std;

ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime)
{
  group = ci.GetGroup();
  title = ci.GetTitle();
  user = ci.GetUser();
  // Expired or Warning / Normal or Base - see image list below
  type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0);
  expirylocdate = ci.GetLTimeL();
  expiryexpdate = ci.GetLTimeExp();
  expirytttdate = LTime;
}

// CExpPWListDlg dialog

CExpPWListDlg::CExpPWListDlg(CWnd* pParent,
                             const ExpiredList &expPWList,
                             const CString& a_filespec)
	: CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList)
{
	const int FILE_DISP_LEN = 75;

	if (a_filespec.GetLength() > FILE_DISP_LEN) {
    // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display
    // m_message.Insert(0, _T("..."));
		m_message =  a_filespec.Left(FILE_DISP_LEN/2-5) +
      _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2);
	} else {
		m_message = a_filespec;
	}

	m_iSortedColumn = -1;
	m_bSortAscending = TRUE;
}

CExpPWListDlg::~CExpPWListDlg()
{
}

void CExpPWListDlg::DoDataExchange(CDataExchange* pDX)
{
	CPWDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl);
	DDX_Text(pDX, IDC_MESSAGE, m_message);
}

BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog)
ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard)
ON_BN_CLICKED(IDOK, OnOK)
ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)
ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)
END_MESSAGE_MAP()

// CExpPWListDlg message handlers

BOOL
CExpPWListDlg::OnInitDialog()
{
	CPWDialog::OnInitDialog();

  //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES );

	CString cs_text;
  m_expPWListCtrl.InsertColumn(0, _T(""));
	cs_text.LoadString(IDS_GROUP);
	m_expPWListCtrl.InsertColumn(1, cs_text);
	cs_text.LoadString(IDS_TITLE);
	m_expPWListCtrl.InsertColumn(3, cs_text);
	cs_text.LoadString(IDS_USERNAME);
	m_expPWListCtrl.InsertColumn(3, cs_text);
	cs_text.LoadString(IDS_EXPIRYDATETIME);
	m_expPWListCtrl.InsertColumn(4, cs_text);

  m_pImageList = new CImageList();
  // Number (4) same as total of warn/expired images below
  BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0);
  ASSERT(status != 0);
  CBitmap bitmap;

  bitmap.LoadBitmap(IDB_LEAF_EXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL);
  m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL);

  int nPos = 0;
  ExpiredList::const_iterator itempos;

  for (itempos = m_expPWList.begin();
       itempos != m_expPWList.end();
       itempos++) {
		const ExpPWEntry exppwentry = *itempos;
		nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type);
    m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group);
		m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title);
		m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user);
		m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate);
    // original nPos == index in vector: save for Sort
		m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos));
	}

	m_expPWListCtrl.SetRedraw(FALSE);
	for (int i = 0; i < 5; i++) {
		m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);
		int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i);
		m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
		int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i);
		m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));
	}
	m_expPWListCtrl.SetRedraw(TRUE);

	return TRUE;
}

void
CExpPWListDlg::OnOK()
{
  delete m_pImageList;
	CPWDialog::OnOK();
}

void
CExpPWListDlg::OnBnClickedCopyExpToClipboard()
{
	CString data(MAKEINTRESOURCE(IDS_COPYTITLE));
	const CString CRLF = _T("\r\n");
	const CString TAB = _T('\t');

  ExpiredList::const_iterator itempos;

  for (itempos = m_expPWList.begin();
       itempos != m_expPWList.end();
       itempos++) {
		const ExpPWEntry exppwentry = *itempos;
		data = data +
			(CString)exppwentry.group + TAB +
			(CString)exppwentry.title + TAB +
			(CString)exppwentry.user + TAB +
			(CString)exppwentry.expiryexpdate + CRLF;
	}

  DboxMain *dbx = static_cast<DboxMain *>(GetParent());
  dbx->SetClipboardData(data);
}

void
CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
	HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

	if(phdn->iButton == 0) {
		// User clicked on header using left mouse button
		if(phdn->iItem == m_iSortedColumn)
			m_bSortAscending = !m_bSortAscending;
		else
			m_bSortAscending = TRUE;

		m_iSortedColumn = phdn->iItem;
		m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this);

		// Note: WINVER defines the minimum system level for which this is program compiled and
		// NOT the level of system it is running on!
		// In this case, these values are defined in Windows XP and later and supported
		// by V6 of comctl32.dll (supplied with Windows XP) and later.
		// They should be ignored by earlier levels of this dll or .....
		//     we can check the dll version (code available on request)!

#if (WINVER < 0x0501)	// These are already defined for WinXP and later
#define HDF_SORTUP 0x0400
#define HDF_SORTDOWN 0x0200
#endif
		HDITEM HeaderItem;
		HeaderItem.mask = HDI_FORMAT;
		m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);
		// Turn off all arrows
		HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);
		// Turn on the correct arrow
		HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);
		m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);
	}

	*pResult = 0;
}

int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2,
										LPARAM closure)
{
	CExpPWListDlg *self = (CExpPWListDlg*)closure;
	int nSortColumn = self->m_iSortedColumn;
	const ExpPWEntry pLHS = self->m_expPWList[lParam1];
	const ExpPWEntry pRHS = self->m_expPWList[lParam2];
	CMyString group1, title1, username1;
	CMyString group2, title2, username2;
    int type1, type2;
	time_t t1, t2;

	int iResult;
	switch(nSortColumn) {
		case 0:
			type1 = pLHS.type;
			type2 = pRHS.type;
			iResult = (type1 < type2) ? -1 : 1;
			break;
		case 1:
			group1 = pLHS.group;
			group2 = pRHS.group;
			iResult = ((CString)group1).CompareNoCase(group2);
			break;
		case 2:
			title1 = pLHS.title;
			title2 = pRHS.title;
			iResult = ((CString)title1).CompareNoCase(title2);
			break;
		case 3:
			username1 = pLHS.user;
			username2 = pRHS.user;
			iResult = ((CString)username1).CompareNoCase(username2);
			break;
		case 4:
			t1 = pLHS.expirytttdate;
			t2 = pRHS.expirytttdate;
			iResult = ((long) t1 < (long) t2) ? -1 : 1;
			break;
		default:
		    iResult = 0; // should never happen - just keep compiler happy
			ASSERT(FALSE);
	}

	if (!self->m_bSortAscending)
		iResult *= -1;

	return iResult;
}
<commit_msg>Correct column number in Expired Password dialog<commit_after>/*
 * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
 * All rights reserved. Use of the code is allowed under the
 * Artistic License 2.0 terms, as specified in the LICENSE file
 * distributed with this code, or available from
 * http://www.opensource.org/licenses/artistic-license-2.0.php
 */
// ExpPWListDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ExpPWListDlg.h"
#include "DboxMain.h"
#include "corelib/MyString.h"
#include "corelib/Util.h"
#include "corelib/ItemData.h"
#include "resource2.h"  // Menu, Toolbar & Accelerator resources
#include "resource3.h"  // String resources

using namespace std;

ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime)
{
  group = ci.GetGroup();
  title = ci.GetTitle();
  user = ci.GetUser();
  // Expired or Warning / Normal or Base - see image list below
  type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0);
  expirylocdate = ci.GetLTimeL();
  expiryexpdate = ci.GetLTimeExp();
  expirytttdate = LTime;
}

// CExpPWListDlg dialog

CExpPWListDlg::CExpPWListDlg(CWnd* pParent,
                             const ExpiredList &expPWList,
                             const CString& a_filespec)
	: CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList)
{
	const int FILE_DISP_LEN = 75;

	if (a_filespec.GetLength() > FILE_DISP_LEN) {
    // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display
    // m_message.Insert(0, _T("..."));
		m_message =  a_filespec.Left(FILE_DISP_LEN/2-5) +
      _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2);
	} else {
		m_message = a_filespec;
	}

	m_iSortedColumn = -1;
	m_bSortAscending = TRUE;
}

CExpPWListDlg::~CExpPWListDlg()
{
}

void CExpPWListDlg::DoDataExchange(CDataExchange* pDX)
{
	CPWDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl);
	DDX_Text(pDX, IDC_MESSAGE, m_message);
}

BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog)
ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard)
ON_BN_CLICKED(IDOK, OnOK)
ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)
ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)
END_MESSAGE_MAP()

// CExpPWListDlg message handlers

BOOL
CExpPWListDlg::OnInitDialog()
{
	CPWDialog::OnInitDialog();

  //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES );

	CString cs_text;
  m_expPWListCtrl.InsertColumn(0, _T(""));
	cs_text.LoadString(IDS_GROUP);
	m_expPWListCtrl.InsertColumn(1, cs_text);
	cs_text.LoadString(IDS_TITLE);
	m_expPWListCtrl.InsertColumn(2, cs_text);
	cs_text.LoadString(IDS_USERNAME);
	m_expPWListCtrl.InsertColumn(3, cs_text);
	cs_text.LoadString(IDS_EXPIRYDATETIME);
	m_expPWListCtrl.InsertColumn(4, cs_text);

  m_pImageList = new CImageList();
  // Number (4) same as total of warn/expired images below
  BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0);
  ASSERT(status != 0);
  CBitmap bitmap;

  bitmap.LoadBitmap(IDB_LEAF_EXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED);
  m_pImageList->Add(&bitmap, (COLORREF)0x0);
  bitmap.DeleteObject();
  m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL);
  m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL);

  int nPos = 0;
  ExpiredList::const_iterator itempos;

  for (itempos = m_expPWList.begin();
       itempos != m_expPWList.end();
       itempos++) {
		const ExpPWEntry exppwentry = *itempos;
		nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type);
    m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group);
		m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title);
		m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user);
		m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate);
    // original nPos == index in vector: save for Sort
		m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos));
	}

	m_expPWListCtrl.SetRedraw(FALSE);
	for (int i = 0; i < 5; i++) {
		m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);
		int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i);
		m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
		int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i);
		m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));
	}
	m_expPWListCtrl.SetRedraw(TRUE);

	return TRUE;
}

void
CExpPWListDlg::OnOK()
{
  delete m_pImageList;
	CPWDialog::OnOK();
}

void
CExpPWListDlg::OnBnClickedCopyExpToClipboard()
{
	CString data(MAKEINTRESOURCE(IDS_COPYTITLE));
	const CString CRLF = _T("\r\n");
	const CString TAB = _T('\t');

  ExpiredList::const_iterator itempos;

  for (itempos = m_expPWList.begin();
       itempos != m_expPWList.end();
       itempos++) {
		const ExpPWEntry exppwentry = *itempos;
		data = data +
			(CString)exppwentry.group + TAB +
			(CString)exppwentry.title + TAB +
			(CString)exppwentry.user + TAB +
			(CString)exppwentry.expiryexpdate + CRLF;
	}

  DboxMain *dbx = static_cast<DboxMain *>(GetParent());
  dbx->SetClipboardData(data);
}

void
CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
	HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

	if(phdn->iButton == 0) {
		// User clicked on header using left mouse button
		if(phdn->iItem == m_iSortedColumn)
			m_bSortAscending = !m_bSortAscending;
		else
			m_bSortAscending = TRUE;

		m_iSortedColumn = phdn->iItem;
		m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this);

		// Note: WINVER defines the minimum system level for which this is program compiled and
		// NOT the level of system it is running on!
		// In this case, these values are defined in Windows XP and later and supported
		// by V6 of comctl32.dll (supplied with Windows XP) and later.
		// They should be ignored by earlier levels of this dll or .....
		//     we can check the dll version (code available on request)!

#if (WINVER < 0x0501)	// These are already defined for WinXP and later
#define HDF_SORTUP 0x0400
#define HDF_SORTDOWN 0x0200
#endif
		HDITEM HeaderItem;
		HeaderItem.mask = HDI_FORMAT;
		m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);
		// Turn off all arrows
		HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);
		// Turn on the correct arrow
		HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);
		m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);
	}

	*pResult = 0;
}

int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2,
										LPARAM closure)
{
	CExpPWListDlg *self = (CExpPWListDlg*)closure;
	int nSortColumn = self->m_iSortedColumn;
	const ExpPWEntry pLHS = self->m_expPWList[lParam1];
	const ExpPWEntry pRHS = self->m_expPWList[lParam2];
	CMyString group1, title1, username1;
	CMyString group2, title2, username2;
    int type1, type2;
	time_t t1, t2;

	int iResult;
	switch(nSortColumn) {
		case 0:
			type1 = pLHS.type;
			type2 = pRHS.type;
			iResult = (type1 < type2) ? -1 : 1;
			break;
		case 1:
			group1 = pLHS.group;
			group2 = pRHS.group;
			iResult = ((CString)group1).CompareNoCase(group2);
			break;
		case 2:
			title1 = pLHS.title;
			title2 = pRHS.title;
			iResult = ((CString)title1).CompareNoCase(title2);
			break;
		case 3:
			username1 = pLHS.user;
			username2 = pRHS.user;
			iResult = ((CString)username1).CompareNoCase(username2);
			break;
		case 4:
			t1 = pLHS.expirytttdate;
			t2 = pRHS.expirytttdate;
			iResult = ((long) t1 < (long) t2) ? -1 : 1;
			break;
		default:
		    iResult = 0; // should never happen - just keep compiler happy
			ASSERT(FALSE);
	}

	if (!self->m_bSortAscending)
		iResult *= -1;

	return iResult;
}
<|endoftext|>


<commit_before>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include <climits>
#include <cstring>

#include "lldb/Host/FileSystem.h"
#include "lldb/Host/PosixApi.h"
#include "lldb/Target/PathMappingList.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Stream.h"
#include "lldb/lldb-private-enumerations.h"

using namespace lldb;
using namespace lldb_private;

namespace {
  // We must normalize our path pairs that we store because if we don't then
  // things won't always work. We found a case where if we did:
  // (lldb) settings set target.source-map . /tmp
  // We would store a path pairs of "." and "/tmp" as raw strings. If the debug
  // info contains "./foo/bar.c", the path will get normalized to "foo/bar.c".
  // When PathMappingList::RemapPath() is called, it expects the path to start
  // with the raw path pair, which doesn't work anymore because the paths have
  // been normalized when the debug info was loaded. So we need to store
  // nomalized path pairs to ensure things match up.
  ConstString NormalizePath(const ConstString &path) {
    // If we use "path" to construct a FileSpec, it will normalize the path for
    // us. We then grab the string and turn it back into a ConstString.
    return ConstString(FileSpec(path.GetStringRef()).GetPath());
  }
}
//----------------------------------------------------------------------
// PathMappingList constructor
//----------------------------------------------------------------------
PathMappingList::PathMappingList()
    : m_pairs(), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {}

PathMappingList::PathMappingList(ChangedCallback callback, void *callback_baton)
    : m_pairs(), m_callback(callback), m_callback_baton(callback_baton),
      m_mod_id(0) {}

PathMappingList::PathMappingList(const PathMappingList &rhs)
    : m_pairs(rhs.m_pairs), m_callback(nullptr), m_callback_baton(nullptr),
      m_mod_id(0) {}

const PathMappingList &PathMappingList::operator=(const PathMappingList &rhs) {
  if (this != &rhs) {
    m_pairs = rhs.m_pairs;
    m_callback = nullptr;
    m_callback_baton = nullptr;
    m_mod_id = rhs.m_mod_id;
  }
  return *this;
}

PathMappingList::~PathMappingList() = default;

void PathMappingList::Append(const ConstString &path,
                             const ConstString &replacement, bool notify) {
  ++m_mod_id;
  m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement)));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

void PathMappingList::Append(const PathMappingList &rhs, bool notify) {
  ++m_mod_id;
  if (!rhs.m_pairs.empty()) {
    const_iterator pos, end = rhs.m_pairs.end();
    for (pos = rhs.m_pairs.begin(); pos != end; ++pos)
      m_pairs.push_back(*pos);
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
  }
}

void PathMappingList::Insert(const ConstString &path,
                             const ConstString &replacement, uint32_t index,
                             bool notify) {
  ++m_mod_id;
  iterator insert_iter;
  if (index >= m_pairs.size())
    insert_iter = m_pairs.end();
  else
    insert_iter = m_pairs.begin() + index;
  m_pairs.emplace(insert_iter, pair(NormalizePath(path),
                                    NormalizePath(replacement)));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

bool PathMappingList::Replace(const ConstString &path,
                              const ConstString &replacement, uint32_t index,
                              bool notify) {
  if (index >= m_pairs.size())
    return false;
  ++m_mod_id;
  m_pairs[index] = pair(NormalizePath(path), NormalizePath(replacement));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
  return true;
}

bool PathMappingList::Remove(size_t index, bool notify) {
  if (index >= m_pairs.size())
    return false;

  ++m_mod_id;
  iterator iter = m_pairs.begin() + index;
  m_pairs.erase(iter);
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
  return true;
}

// For clients which do not need the pair index dumped, pass a pair_index >= 0
// to only dump the indicated pair.
void PathMappingList::Dump(Stream *s, int pair_index) {
  unsigned int numPairs = m_pairs.size();

  if (pair_index < 0) {
    unsigned int index;
    for (index = 0; index < numPairs; ++index)
      s->Printf("[%d] \"%s\" -> \"%s\"\n", index,
                m_pairs[index].first.GetCString(),
                m_pairs[index].second.GetCString());
  } else {
    if (static_cast<unsigned int>(pair_index) < numPairs)
      s->Printf("%s -> %s", m_pairs[pair_index].first.GetCString(),
                m_pairs[pair_index].second.GetCString());
  }
}

void PathMappingList::Clear(bool notify) {
  if (!m_pairs.empty())
    ++m_mod_id;
  m_pairs.clear();
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

bool PathMappingList::RemapPath(const ConstString &path,
                                ConstString &new_path) const {
  std::string remapped;
  if (RemapPath(path.GetStringRef(), remapped)) {
    new_path.SetString(remapped);
    return true;
  }
  return false;
}

bool PathMappingList::RemapPath(llvm::StringRef path,
                                std::string &new_path) const {
  if (m_pairs.empty() || path.empty())
    return false;
  LazyBool path_is_relative = eLazyBoolCalculate;
  for (const auto &it : m_pairs) {
    auto prefix = it.first.GetStringRef();
    if (!path.consume_front(prefix)) {
      // Relative paths won't have a leading "./" in them unless "." is the
      // only thing in the relative path so we need to work around "."
      // carefully.
      if (prefix != ".")
        continue;
      // We need to figure out if the "path" argument is relative. If it is,
      // then we should remap, else skip this entry.
      if (path_is_relative == eLazyBoolCalculate) {
        path_is_relative =
            FileSpec(path).IsRelative() ? eLazyBoolYes : eLazyBoolNo;
      }
      if (!path_is_relative)
        continue;
    }
    FileSpec remapped(it.second.GetStringRef());
    remapped.AppendPathComponent(path);
    new_path = remapped.GetPath();
    return true;
  }
  return false;
}

bool PathMappingList::ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const {
  std::string path = file.GetPath();
  llvm::StringRef path_ref(path);
  for (const auto &it : m_pairs) {
    if (!path_ref.consume_front(it.second.GetStringRef()))
      continue;
    fixed.SetFile(it.first.GetStringRef(), FileSpec::Style::native);
    fixed.AppendPathComponent(path_ref);
    return true;
  }
  return false;
}

bool PathMappingList::FindFile(const FileSpec &orig_spec,
                               FileSpec &new_spec) const {
  if (m_pairs.empty())
    return false;

  std::string orig_path = orig_spec.GetPath();

  if (orig_path.empty())
    return false;

  bool orig_is_relative = orig_spec.IsRelative();

  const_iterator pos, end = m_pairs.end();
  for (pos = m_pairs.begin(); pos != end; ++pos) {
    llvm::StringRef orig_ref(orig_path);
    llvm::StringRef prefix_ref = pos->first.GetStringRef();
    if (orig_ref.size() >= prefix_ref.size()) {
      // We consider a relative prefix or one of just "." to
      // mean "only apply to relative paths".
      bool prefix_is_relative = false;

      if (prefix_ref == ".") {
        prefix_is_relative = true;
        // Remove the "." since it will have been removed from the
        // FileSpec paths already.
        prefix_ref = prefix_ref.drop_front();
      } else {
        FileSpec prefix_spec(prefix_ref, FileSpec::Style::native);
        prefix_is_relative = prefix_spec.IsRelative();
      }
      if (prefix_is_relative != orig_is_relative)
        continue;

      if (orig_ref.consume_front(prefix_ref)) {
        new_spec.SetFile(pos->second.GetCString(), FileSpec::Style::native);
        new_spec.AppendPathComponent(orig_ref);
        if (FileSystem::Instance().Exists(new_spec))
          return true;
      }
    }
  }

  new_spec.Clear();
  return false;
}

bool PathMappingList::Replace(const ConstString &path,
                              const ConstString &new_path, bool notify) {
  uint32_t idx = FindIndexForPath(path);
  if (idx < m_pairs.size()) {
    ++m_mod_id;
    m_pairs[idx].second = new_path;
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
    return true;
  }
  return false;
}

bool PathMappingList::Remove(const ConstString &path, bool notify) {
  iterator pos = FindIteratorForPath(path);
  if (pos != m_pairs.end()) {
    ++m_mod_id;
    m_pairs.erase(pos);
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
    return true;
  }
  return false;
}

PathMappingList::const_iterator
PathMappingList::FindIteratorForPath(const ConstString &path) const {
  const_iterator pos;
  const_iterator begin = m_pairs.begin();
  const_iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      break;
  }
  return pos;
}

PathMappingList::iterator
PathMappingList::FindIteratorForPath(const ConstString &path) {
  iterator pos;
  iterator begin = m_pairs.begin();
  iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      break;
  }
  return pos;
}

bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path,
                                      ConstString &new_path) const {
  if (idx < m_pairs.size()) {
    path = m_pairs[idx].first;
    new_path = m_pairs[idx].second;
    return true;
  }
  return false;
}

uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const {
  const ConstString path = NormalizePath(orig_path);
  const_iterator pos;
  const_iterator begin = m_pairs.begin();
  const_iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      return std::distance(begin, pos);
  }
  return UINT32_MAX;
}
<commit_msg>Little more cleanup on https://reviews.llvm.org/D57552 Thanks Jonas...  One more early continue and using a range where we had an iterator.<commit_after>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include <climits>
#include <cstring>

#include "lldb/Host/FileSystem.h"
#include "lldb/Host/PosixApi.h"
#include "lldb/Target/PathMappingList.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Stream.h"
#include "lldb/lldb-private-enumerations.h"

using namespace lldb;
using namespace lldb_private;

namespace {
  // We must normalize our path pairs that we store because if we don't then
  // things won't always work. We found a case where if we did:
  // (lldb) settings set target.source-map . /tmp
  // We would store a path pairs of "." and "/tmp" as raw strings. If the debug
  // info contains "./foo/bar.c", the path will get normalized to "foo/bar.c".
  // When PathMappingList::RemapPath() is called, it expects the path to start
  // with the raw path pair, which doesn't work anymore because the paths have
  // been normalized when the debug info was loaded. So we need to store
  // nomalized path pairs to ensure things match up.
  ConstString NormalizePath(const ConstString &path) {
    // If we use "path" to construct a FileSpec, it will normalize the path for
    // us. We then grab the string and turn it back into a ConstString.
    return ConstString(FileSpec(path.GetStringRef()).GetPath());
  }
}
//----------------------------------------------------------------------
// PathMappingList constructor
//----------------------------------------------------------------------
PathMappingList::PathMappingList()
    : m_pairs(), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {}

PathMappingList::PathMappingList(ChangedCallback callback, void *callback_baton)
    : m_pairs(), m_callback(callback), m_callback_baton(callback_baton),
      m_mod_id(0) {}

PathMappingList::PathMappingList(const PathMappingList &rhs)
    : m_pairs(rhs.m_pairs), m_callback(nullptr), m_callback_baton(nullptr),
      m_mod_id(0) {}

const PathMappingList &PathMappingList::operator=(const PathMappingList &rhs) {
  if (this != &rhs) {
    m_pairs = rhs.m_pairs;
    m_callback = nullptr;
    m_callback_baton = nullptr;
    m_mod_id = rhs.m_mod_id;
  }
  return *this;
}

PathMappingList::~PathMappingList() = default;

void PathMappingList::Append(const ConstString &path,
                             const ConstString &replacement, bool notify) {
  ++m_mod_id;
  m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement)));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

void PathMappingList::Append(const PathMappingList &rhs, bool notify) {
  ++m_mod_id;
  if (!rhs.m_pairs.empty()) {
    const_iterator pos, end = rhs.m_pairs.end();
    for (pos = rhs.m_pairs.begin(); pos != end; ++pos)
      m_pairs.push_back(*pos);
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
  }
}

void PathMappingList::Insert(const ConstString &path,
                             const ConstString &replacement, uint32_t index,
                             bool notify) {
  ++m_mod_id;
  iterator insert_iter;
  if (index >= m_pairs.size())
    insert_iter = m_pairs.end();
  else
    insert_iter = m_pairs.begin() + index;
  m_pairs.emplace(insert_iter, pair(NormalizePath(path),
                                    NormalizePath(replacement)));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

bool PathMappingList::Replace(const ConstString &path,
                              const ConstString &replacement, uint32_t index,
                              bool notify) {
  if (index >= m_pairs.size())
    return false;
  ++m_mod_id;
  m_pairs[index] = pair(NormalizePath(path), NormalizePath(replacement));
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
  return true;
}

bool PathMappingList::Remove(size_t index, bool notify) {
  if (index >= m_pairs.size())
    return false;

  ++m_mod_id;
  iterator iter = m_pairs.begin() + index;
  m_pairs.erase(iter);
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
  return true;
}

// For clients which do not need the pair index dumped, pass a pair_index >= 0
// to only dump the indicated pair.
void PathMappingList::Dump(Stream *s, int pair_index) {
  unsigned int numPairs = m_pairs.size();

  if (pair_index < 0) {
    unsigned int index;
    for (index = 0; index < numPairs; ++index)
      s->Printf("[%d] \"%s\" -> \"%s\"\n", index,
                m_pairs[index].first.GetCString(),
                m_pairs[index].second.GetCString());
  } else {
    if (static_cast<unsigned int>(pair_index) < numPairs)
      s->Printf("%s -> %s", m_pairs[pair_index].first.GetCString(),
                m_pairs[pair_index].second.GetCString());
  }
}

void PathMappingList::Clear(bool notify) {
  if (!m_pairs.empty())
    ++m_mod_id;
  m_pairs.clear();
  if (notify && m_callback)
    m_callback(*this, m_callback_baton);
}

bool PathMappingList::RemapPath(const ConstString &path,
                                ConstString &new_path) const {
  std::string remapped;
  if (RemapPath(path.GetStringRef(), remapped)) {
    new_path.SetString(remapped);
    return true;
  }
  return false;
}

bool PathMappingList::RemapPath(llvm::StringRef path,
                                std::string &new_path) const {
  if (m_pairs.empty() || path.empty())
    return false;
  LazyBool path_is_relative = eLazyBoolCalculate;
  for (const auto &it : m_pairs) {
    auto prefix = it.first.GetStringRef();
    if (!path.consume_front(prefix)) {
      // Relative paths won't have a leading "./" in them unless "." is the
      // only thing in the relative path so we need to work around "."
      // carefully.
      if (prefix != ".")
        continue;
      // We need to figure out if the "path" argument is relative. If it is,
      // then we should remap, else skip this entry.
      if (path_is_relative == eLazyBoolCalculate) {
        path_is_relative =
            FileSpec(path).IsRelative() ? eLazyBoolYes : eLazyBoolNo;
      }
      if (!path_is_relative)
        continue;
    }
    FileSpec remapped(it.second.GetStringRef());
    remapped.AppendPathComponent(path);
    new_path = remapped.GetPath();
    return true;
  }
  return false;
}

bool PathMappingList::ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const {
  std::string path = file.GetPath();
  llvm::StringRef path_ref(path);
  for (const auto &it : m_pairs) {
    if (!path_ref.consume_front(it.second.GetStringRef()))
      continue;
    fixed.SetFile(it.first.GetStringRef(), FileSpec::Style::native);
    fixed.AppendPathComponent(path_ref);
    return true;
  }
  return false;
}

bool PathMappingList::FindFile(const FileSpec &orig_spec,
                               FileSpec &new_spec) const {
  if (m_pairs.empty())
    return false;

  std::string orig_path = orig_spec.GetPath();

  if (orig_path.empty())
    return false;

  bool orig_is_relative = orig_spec.IsRelative();

  for (auto entry : m_pairs) {
    llvm::StringRef orig_ref(orig_path);
    llvm::StringRef prefix_ref = entry.first.GetStringRef();
    if (orig_ref.size() < prefix_ref.size())
      continue;
    // We consider a relative prefix or one of just "." to
    // mean "only apply to relative paths".
    bool prefix_is_relative = false;

    if (prefix_ref == ".") {
      prefix_is_relative = true;
      // Remove the "." since it will have been removed from the
      // FileSpec paths already.
      prefix_ref = prefix_ref.drop_front();
    } else {
      FileSpec prefix_spec(prefix_ref, FileSpec::Style::native);
      prefix_is_relative = prefix_spec.IsRelative();
    }
    if (prefix_is_relative != orig_is_relative)
      continue;

    if (orig_ref.consume_front(prefix_ref)) {
      new_spec.SetFile(entry.second.GetCString(), FileSpec::Style::native);
      new_spec.AppendPathComponent(orig_ref);
      if (FileSystem::Instance().Exists(new_spec))
        return true;
    }
  }

  new_spec.Clear();
  return false;
}

bool PathMappingList::Replace(const ConstString &path,
                              const ConstString &new_path, bool notify) {
  uint32_t idx = FindIndexForPath(path);
  if (idx < m_pairs.size()) {
    ++m_mod_id;
    m_pairs[idx].second = new_path;
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
    return true;
  }
  return false;
}

bool PathMappingList::Remove(const ConstString &path, bool notify) {
  iterator pos = FindIteratorForPath(path);
  if (pos != m_pairs.end()) {
    ++m_mod_id;
    m_pairs.erase(pos);
    if (notify && m_callback)
      m_callback(*this, m_callback_baton);
    return true;
  }
  return false;
}

PathMappingList::const_iterator
PathMappingList::FindIteratorForPath(const ConstString &path) const {
  const_iterator pos;
  const_iterator begin = m_pairs.begin();
  const_iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      break;
  }
  return pos;
}

PathMappingList::iterator
PathMappingList::FindIteratorForPath(const ConstString &path) {
  iterator pos;
  iterator begin = m_pairs.begin();
  iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      break;
  }
  return pos;
}

bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path,
                                      ConstString &new_path) const {
  if (idx < m_pairs.size()) {
    path = m_pairs[idx].first;
    new_path = m_pairs[idx].second;
    return true;
  }
  return false;
}

uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const {
  const ConstString path = NormalizePath(orig_path);
  const_iterator pos;
  const_iterator begin = m_pairs.begin();
  const_iterator end = m_pairs.end();

  for (pos = begin; pos != end; ++pos) {
    if (pos->first == path)
      return std::distance(begin, pos);
  }
  return UINT32_MAX;
}
<|endoftext|>


<commit_before>#ifndef PK_BINARYINDEXEDTREE2D_HPP
#define PK_BINARYINDEXEDTREE2D_HPP

namespace pk
{
namespace detail
{

struct binary_indexed_tree_2d_entry
{
    binary_indexed_tree_2d_entry(const int x_, const int y_) : x(x_), y(y_) {}

    int x;
    int y;
};

struct binary_indexed_tree_2d_subrange
{
    binary_indexed_tree_2d_subrange(const int from_, const int to_) : from(from_), to(to_) {}

    int from;
    int to;
};

} // namespace detail

template<class ValueType, int Range1, int Range2>
class binary_indexed_tree_2d
{
public:
    typedef ValueType value_type;
    typedef detail::binary_indexed_tree_2d_entry entry;
    typedef detail::binary_indexed_tree_2d_subrange subrange;

    binary_indexed_tree_2d(const int real_range_1_, const int real_range_2_)
        : real_range_1(real_range_1_),
          real_range_2(real_range_2_)
    {
        for(int x = 0; x < real_range_1; ++x)
            for(int y = 0; y < real_range_2; ++y)
                data[x][y] = value_type();
    }

    void increase(entry e, const value_type& value)
    {
        while(e.x < real_range_1)
        {
            int y1 = e.y;
            while(y1 < real_range_2)
            {
                data[e.x][y1] += value;
                y1 |= y1 + 1;
            }

            e.x |= e.x + 1;
        }
    }

    void set(const entry& e, const value_type& value)
    {
        const value_type old_value = count_less_equal(e.x, e.y);
        increase(e, value - old_value);
    }

    int count_less_equal(int x, int y) const
    {
        value_type sum = value_type();

        while(x >= 0)
        {
            int y1 = y;
            while(y1 >= 0)
            {
                sum += data[x][y1];
                y1 &= y1 + 1;
                --y1;
            }

            x &= x + 1;
            --x;
        }

        return sum;
    }

    int count_in_range(const subrange& x_subrange, const subrange& y_subrange) const
    {
        return (count_less_equal(x_subrange.to, y_subrange.to)
                - count_less_equal(x_subrange.to, y_subrange.from - 1)
                - count_less_equal(x_subrange.from - 1, y_subrange.to)
                + count_less_equal(x_subrange.from - 1, y_subrange.from - 1));
    }

private:
    value_type data[Range1][Range2];

    const int real_range_1;
    const int real_range_2;
};

} // namespace pk

#endif // PK_BINARYINDEXEDTREE2D_HPP
<commit_msg>fix in binary_indexed_tree_2d::set()<commit_after>#ifndef PK_BINARYINDEXEDTREE2D_HPP
#define PK_BINARYINDEXEDTREE2D_HPP

namespace pk
{
namespace detail
{

struct binary_indexed_tree_2d_entry
{
    binary_indexed_tree_2d_entry(const int x_, const int y_) : x(x_), y(y_) {}

    int x;
    int y;
};

struct binary_indexed_tree_2d_subrange
{
    binary_indexed_tree_2d_subrange(const int from_, const int to_) : from(from_), to(to_) {}

    int from;
    int to;
};

} // namespace detail

template<class ValueType, int Range1, int Range2>
class binary_indexed_tree_2d
{
public:
    typedef ValueType value_type;
    typedef detail::binary_indexed_tree_2d_entry entry;
    typedef detail::binary_indexed_tree_2d_subrange subrange;

    binary_indexed_tree_2d(const int real_range_1_, const int real_range_2_)
        : real_range_1(real_range_1_),
          real_range_2(real_range_2_)
    {
        for(int x = 0; x < real_range_1; ++x)
            for(int y = 0; y < real_range_2; ++y)
                data[x][y] = value_type();
    }

    void increase(entry e, const value_type& value)
    {
        while(e.x < real_range_1)
        {
            int y1 = e.y;
            while(y1 < real_range_2)
            {
                data[e.x][y1] += value;
                y1 |= y1 + 1;
            }

            e.x |= e.x + 1;
        }
    }

    void set(const entry& e, const value_type& value)
    {
        const value_type old_value = count_in_range(subrange(e.x, e.x), subrange(e.y, e.y));
        increase(e, value - old_value);
    }

    int count_less_equal(int x, int y) const
    {
        value_type sum = value_type();

        while(x >= 0)
        {
            int y1 = y;
            while(y1 >= 0)
            {
                sum += data[x][y1];
                y1 &= y1 + 1;
                --y1;
            }

            x &= x + 1;
            --x;
        }

        return sum;
    }

    int count_in_range(const subrange& x_subrange, const subrange& y_subrange) const
    {
        return (count_less_equal(x_subrange.to, y_subrange.to)
                - count_less_equal(x_subrange.to, y_subrange.from - 1)
                - count_less_equal(x_subrange.from - 1, y_subrange.to)
                + count_less_equal(x_subrange.from - 1, y_subrange.from - 1));
    }

private:
    value_type data[Range1][Range2];

    const int real_range_1;
    const int real_range_2;
};

} // namespace pk

#endif // PK_BINARYINDEXEDTREE2D_HPP
<|endoftext|>


<commit_before><commit_msg>missing include limits<commit_after><|endoftext|>


<commit_before><commit_msg>Add newline to end of download_manager.cc<commit_after><|endoftext|>


<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */

#include <graph/power.hh>

using namespace parasols;

Graph parasols::power(const Graph & graph, int n)
{
    /* this is spectacularly dumb. we can do a lot better. */
    Graph result = graph;

    for (int p = 1 ; p < n ; ++p) {
        Graph prev_result = result;

        for (int i = 0 ; i < graph.size() ; ++i) {
            for (int j = 0 ; j < graph.size() ; ++j) {
                if (i == j)
                    continue;

                if (prev_result.adjacent(i, j)) {
                    for (int k = 0 ; k < graph.size() ; ++k) {
                        if (j == k)
                            continue;

                        if (graph.adjacent(i, k))
                            result.add_edge(j, k);
                    }
                }
            }
        }
    }

    return result;
}

<commit_msg>Better power code<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */

#include <graph/power.hh>
#include <limits>

using namespace parasols;

Graph parasols::power(const Graph & graph, int n)
{
    std::vector<std::vector<int> > distances((graph.size()));
    for (auto & d : distances)
        d.resize((graph.size()));

    /* d(m, n) = infinity */
    for (int i = 0 ; i < graph.size() ; ++i)
        for (int j = 0 ; j < graph.size() ; ++j)
            distances[i][j] = std::numeric_limits<int>::max();

    /* d(m, m) = 0 */
    for (int i = 0 ; i < graph.size() ; ++i)
        distances[i][i] = 0;

    /* d(m, n) = 1 if m, n in members and adjacent */
    for (int i = 0 ; i < graph.size() ; ++i)
        for (int j = 0 ; j < graph.size() ; ++j)
            if (i != j && graph.adjacent(i, j))
                distances[i][j] = 1;

    /* shorten */
    for (int i = 0 ; i < graph.size() ; ++i)
        for (int j = 0 ; j < graph.size() ; ++j)
            for (int k = 0 ; k < graph.size() ; ++k) {
                if (distances[i][k] != std::numeric_limits<int>::max() &&
                        distances[k][j] != std::numeric_limits<int>::max()) {
                    int d = distances[i][k] + distances[k][j];
                    if (distances[i][j] > d)
                        distances[i][j] = d;
                }
            }

    Graph result;
    result.resize(graph.size());

    for (int i = 0 ; i < graph.size() ; ++i) {
        for (int j = 0 ; j < graph.size() ; ++j) {
            if (i == j)
                continue;
            if (distances[i][j] <= n)
                result.add_edge(i, j);
        }
    }

    return result;
}

<|endoftext|>