<commit_before>/*
 Copyright (C) 2012 by Ivan Safrin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "PolycodeEditor.h"

extern PolycodeClipboard *globalClipboard;

PolycodeEditorFactory::PolycodeEditorFactory() {

}

PolycodeEditorFactory::~PolycodeEditorFactory() {

}

bool PolycodeEditorFactory::canHandleExtension(String extension) {
	for(int i=0; i < extensions.size(); i++) {
		if(extension == extensions[i])
		   return true;
	}
	return false;
}

void PolycodeEditor::setFilePath(String newPath) {
	filePath = newPath;
}

PolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {
	this->_isReadOnly = _isReadOnly;
	enableScissor = true;
	processInputEvents = true;
	_hasChanges = false;

	Core *core = CoreServices::getInstance()->getCore();

	core->addEventListener(this, Core::EVENT_COPY);
	core->addEventListener(this, Core::EVENT_PASTE);
}

void PolycodeEditor::setHasChanges(bool newVal) {
	if(_hasChanges != newVal) {
		_hasChanges = newVal;
		dispatchEvent(new Event(), Event::CHANGE_EVENT);
	}
}

void PolycodeEditor::handleEvent(Event *event) {
	if(event->getDispatcher() == CoreServices::getInstance()->getCore() && enabled) {
		switch(event->getEventCode()) {

			// Only copypaste of more complex IDE entities is handled here.
			// Pure text copy/paste is handled in:
			// Modules/Contents/UI/Source/PolyUITextInput.cpp
			case Core::EVENT_COPY:
			{
				void *data = NULL;
				String dataType = Copy(&data);
				if(data) {
					globalClipboard->setData(data, dataType, this);
				}
			}
			break;
			case Core::EVENT_PASTE:
			{
				if(globalClipboard->getData()) {
					Paste(globalClipboard->getData(), globalClipboard->getType());
				}
			}
			break;
		}
	}
}

void PolycodeEditor::Resize(int x, int y) {
	editorSize = Vector2(x,y);
	Vector2 pos = getScreenPosition();
	scissorBox.setRect(pos.x,pos.y, x, y);
}

PolycodeEditor::~PolycodeEditor() {

}

<commit_msg>Fixed copy/paste crashing the IDE because of unremoved event listeners<commit_after>/*
 Copyright (C) 2012 by Ivan Safrin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "PolycodeEditor.h"

extern PolycodeClipboard *globalClipboard;

PolycodeEditorFactory::PolycodeEditorFactory() {

}

PolycodeEditorFactory::~PolycodeEditorFactory() {

}

bool PolycodeEditorFactory::canHandleExtension(String extension) {
	for(int i=0; i < extensions.size(); i++) {
		if(extension == extensions[i])
		   return true;
	}
	return false;
}

void PolycodeEditor::setFilePath(String newPath) {
	filePath = newPath;
}

PolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {
	this->_isReadOnly = _isReadOnly;
	enableScissor = true;
	processInputEvents = true;
	_hasChanges = false;

	Core *core = CoreServices::getInstance()->getCore();

	core->addEventListener(this, Core::EVENT_COPY);
	core->addEventListener(this, Core::EVENT_PASTE);
}

void PolycodeEditor::setHasChanges(bool newVal) {
	if(_hasChanges != newVal) {
		_hasChanges = newVal;
		dispatchEvent(new Event(), Event::CHANGE_EVENT);
	}
}

void PolycodeEditor::handleEvent(Event *event) {
	if(event->getDispatcher() == CoreServices::getInstance()->getCore() && enabled) {
		switch(event->getEventCode()) {

			// Only copypaste of more complex IDE entities is handled here.
			// Pure text copy/paste is handled in:
			// Modules/Contents/UI/Source/PolyUITextInput.cpp
			case Core::EVENT_COPY:
			{
				void *data = NULL;
				String dataType = Copy(&data);
				if(data) {
					globalClipboard->setData(data, dataType, this);
				}
			}
			break;
			case Core::EVENT_PASTE:
			{
				if(globalClipboard->getData()) {
					Paste(globalClipboard->getData(), globalClipboard->getType());
				}
			}
			break;
		}
	}
}

void PolycodeEditor::Resize(int x, int y) {
	editorSize = Vector2(x,y);
	Vector2 pos = getScreenPosition();
	scissorBox.setRect(pos.x,pos.y, x, y);
}

PolycodeEditor::~PolycodeEditor() {
	Core *core = CoreServices::getInstance()->getCore();
	core->removeAllHandlersForListener(this);
}

<|endoftext|>


<commit_before><commit_msg>Example of classes, enum, interface, abstract class, inheritance, polymorphism, access modifiers, memory management.<commit_after>// Author: http://lemming.life
// Language: C++
// Purpose: Example of object oriented programming using classes.
// - C++ is C with classes.
// - Classes enable "encapsulation", meaning everything needed for x is in one package/class.
// - Has clases, enum, interface, abstract class, inheritance, polymorphism, access modifiers,

#include <iostream>
#include <string>
using namespace std;
//using std::string;

class Simple {
    public:
        int x;  // This is a public member variable
        void changeX(int newX) { x = newX; } // This is a public method
};

class Simple2 {
    private:
        int x; // Essential, a private member is one that only the class can access
    public:
        void changeX(int newX) { x = newX; } // changeX is a public method, which can access that x
};

// An enum is a type that has constant members.
enum Color { RED, GREEN, BLUE };

// A simple structure for x and y values.
struct Position {
    int x;
    int y;

    string toString() {
        return "x: " + to_string(x) + " y: " + to_string(y);
    }
};

// An interface is a constract
// - Those using the interface must implement the methods advertised.
class PositionInterface {
    virtual int getX() = 0;
    virtual int getY() = 0;
    virtual void changePosition(int, int) = 0;
};

// Shape is an abstract class
// - Abstract classes cannot be instantiated, but those inheriting from can be instantiated.
// - The setColor(Color aColor) = 0 makes this an "abstract class" in c++
class Shape : PositionInterface {
    private:
        Position position; // The shape has a position structure, it is private and thus only Shape can access
    protected:
        Color color; // Shape and child classes can access
    public:

        // This is a parameterized constructor
        Shape(int newX, int newY) {
            position.x = newX;
            position.y = newY;
        }

        // Implementation of the PositionInterface methods
        int getX() { return position.x; }
        int getY() { return position.y; }
        void changePosition(int newX, int newY) { position.x = newX; position.y = newY; }

        // Shape by itself doesn't have a color
        // but the inherited types may. So, we must
        // ensure that inherited classes implement.
        virtual Color getColor() { return color; }   // virtual method, it can be called but must be done so explictly
        virtual void setColor(Color aColor) = 0;    // A pure virtual method == the child must implement.

        virtual string toString() {
            string colorStr;

            // The getColor() method call will be the child one (Circle)
            // - Polymorphism is magic.
            switch(getColor()) {
                case RED: colorStr = "Red"; break;
                case GREEN: colorStr = "Green"; break;
                case BLUE: colorStr = "Blue"; break;
                default: colorStr = "None"; break;
            }
            return position.toString() + " Color: " + colorStr;
        }

        // Abstract classes must have virtual destructors
        virtual ~Shape() { }
};

// Circle inherits from Shape
// - This is a is-a relationship. Circle "is-a" shape.
class Circle : public Shape {
    private:
        int radius;
    public:
        // A parameterized constructor that calls Shape constructor for the x and y positions.
        Circle(int newX, int newY, int newRadius) : Shape(newX, newY) {
            radius = newRadius;
        }

        Color getColor() {
            return Shape::getColor(); // Explicitly calling the abstract class getColor();
        }

        void setColor(Color aColor) {
            color = aColor; // Circle can access protected and public members
        }

        string toString() {
            return Shape::toString() + " Radius: " + to_string(radius);
        }

        ~Circle() {
            // This is the Circle destructor
            // then ~Shape destructor is called
        }
};

class Square : public Shape {
    private:
        int width;
        int height;
    public:

        // Repeating ourselves is tedious...
        // Seeing repetition like this means that we should reconsider
        // how we have implemented. Perhaps it is the wrong approach.
        // One fix is to delegate this to Shape as a "has-a" relationship
        // in a similar way as we have done with a "has-a" position.
        Color getColor() { return color; }
        void setColor(Color aColor) { color = aColor; }

        string toString() {
            return Shape::toString() + " Width: " + to_string(width) + " Height: " + to_string(height);
        }

        Square(int newX, int newY, int newWidth, int newHeight) : Shape(newX, newY) {
            width = newWidth;
            height = newHeight;
        }
        ~Square() { }
};

int main() {

    Simple simple;
    simple.x = 5;
    cout << "Simple x is " << simple.x << '\n'; // 5
    simple.changeX(10);
    cout << "Simple x is " << simple.x << '\n'; // 10

    // Create an object.
    Circle* circle = new Circle(0, 0, 5);
    cout << circle->toString() << '\n'; // Color not yet assigned. So output is x: 0 y: 0 Color: None Radius: 5
    circle->setColor(RED);
    cout << circle->toString() << '\n'; // x: 0 y: 0 Color: Red Radius: 5
    delete circle; // Order of destructor call is from specific to base.

    // Imagine having a collection of Circles, then we have a collection of Squares.
    // Then we go through each collection, and call the toString() method of each element.
    // Wouldn't it be better if we had a single collection of Squares and Circles -- a collection of Shapes.
    // We can do this because Shape* is an abstract class and both Squares and Circles inherit from it.
    Shape* shapes[] = { new Circle(1, 2, 3), new Square(4, 5, 6, 7) }; // This may also be called "program to an interface"
    int length = 2;

    for(int i=0; i<length; ++i) {
        // Polymorphism: it knows which to call Circle::toString() or Square::toString()
        cout << shapes[i]->toString() << '\n';
        delete shapes[i]; // Delete the object. In C++ we must free memory manually.
    }

    return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cameo/runtime/app/cameo_main_delegate.h"
#include "content/public/app/content_main.h"

#if defined(OS_WIN)
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/sandbox_types.h"
#endif

#if defined(OS_WIN)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {
  sandbox::SandboxInterfaceInfo sandbox_info = {0};
  content::InitializeSandboxInfo(&sandbox_info);
  cameo::CameoMainDelegate delegate;
  return content::ContentMain(instance, &sandbox_info, &delegate);
}
#elif defined(OS_LINUX)
int main(int argc, const char** argv) {
  cameo::CameoMainDelegate delegate;
  return content::ContentMain(argc, argv, &delegate);
}
#else
#error "Unsupport platform."
#endif
<commit_msg>Fix wrongly changed include path when removing cameo/src dir<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cameo/runtime/app/cameo_main_delegate.h"
#include "content/public/app/content_main.h"

#if defined(OS_WIN)
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#endif

#if defined(OS_WIN)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {
  sandbox::SandboxInterfaceInfo sandbox_info = {0};
  content::InitializeSandboxInfo(&sandbox_info);
  cameo::CameoMainDelegate delegate;
  return content::ContentMain(instance, &sandbox_info, &delegate);
}
#elif defined(OS_LINUX)
int main(int argc, const char** argv) {
  cameo::CameoMainDelegate delegate;
  return content::ContentMain(argc, argv, &delegate);
}
#else
#error "Unsupport platform."
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebDevToolsMessageTransport;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

namespace {

class WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {
 public:
  void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {
    DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));
  }
};

}  // namespace

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  WebDevToolsMessageTransportImpl transport;
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      &transport,
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<commit_msg>Include WebDevToolsMessageTransport.h in devtools_agent_filter.cc<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageTransport.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebDevToolsMessageTransport;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

namespace {

class WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {
 public:
  void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {
    DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));
  }
};

}  // namespace

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  WebDevToolsMessageTransportImpl transport;
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      &transport,
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<|endoftext|>


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

#ifndef COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

#define ACCESSIBLE_SELECTION_CHILD_ALL  ((sal_Int32)-1)
#define ACCESSIBLE_SELECTION_CHILD_SELF ((sal_Int32)-2)

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= OCommonAccessibleSelection
    //=====================================================================
    /** base class encapsulating common functionality for the helper classes implementing
        the XAccessibleSelection
    */
    class COMPHELPER_DLLPUBLIC OCommonAccessibleSelection
    {
    protected:

        OCommonAccessibleSelection();

    protected:

        // access to context - still waiting to be overwritten
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
            implGetAccessibleContext()
            throw ( ::com::sun::star::uno::RuntimeException ) = 0;

        // return if the specified child is visible => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)
        virtual sal_Bool
            implIsSelected( sal_Int32 nAccessibleChildIndex )
            throw (::com::sun::star::uno::RuntimeException) = 0;

        // select the specified child => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)
        virtual void
            implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect )
            throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException) = 0;

    protected:

        /** non-virtual versions of the methods which can be implemented using <method>implIsSelected</method> and <method>implSelect</method>
        */
        void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        void SAL_CALL clearAccessibleSelection(  ) throw (::com::sun::star::uno::RuntimeException);
        void SAL_CALL selectAllAccessibleChildren(  ) throw (::com::sun::star::uno::RuntimeException);
        sal_Int32 SAL_CALL getSelectedAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    };

    //=====================================================================
    //= OAccessibleSelectionHelper
    //=====================================================================

    typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleSelection > OAccessibleSelectionHelper_Base;

    /** a helper class for implementing an AccessibleSelection which at the same time
        supports an XAccessibleSelection interface.
    */
    class COMPHELPER_DLLPUBLIC OAccessibleSelectionHelper : public OAccessibleComponentHelper,
                                       public OCommonAccessibleSelection,
                                       public OAccessibleSelectionHelper_Base
    {
    protected:

        OAccessibleSelectionHelper( );

        /// see the respective base class ctor for an extensive comment on this, please
        OAccessibleSelectionHelper( IMutex* _pExternalLock );

        // return ourself here by default
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException );

    public:

        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XAccessibleSelection - default implementations
        virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL clearAccessibleSelection(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL selectAllAccessibleChildren(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    };

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008/04/01 15:05:17 thb 1.7.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.7.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: accessibleselectionhelper.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX

#include <comphelper/uno3.hxx>
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#include <cppuhelper/implbase1.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#include "comphelper/comphelperdllapi.h"

#define ACCESSIBLE_SELECTION_CHILD_ALL  ((sal_Int32)-1)
#define ACCESSIBLE_SELECTION_CHILD_SELF ((sal_Int32)-2)

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= OCommonAccessibleSelection
    //=====================================================================
    /** base class encapsulating common functionality for the helper classes implementing
        the XAccessibleSelection
    */
    class COMPHELPER_DLLPUBLIC OCommonAccessibleSelection
    {
    protected:

        OCommonAccessibleSelection();

    protected:

        // access to context - still waiting to be overwritten
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
            implGetAccessibleContext()
            throw ( ::com::sun::star::uno::RuntimeException ) = 0;

        // return if the specified child is visible => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)
        virtual sal_Bool
            implIsSelected( sal_Int32 nAccessibleChildIndex )
            throw (::com::sun::star::uno::RuntimeException) = 0;

        // select the specified child => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)
        virtual void
            implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect )
            throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException) = 0;

    protected:

        /** non-virtual versions of the methods which can be implemented using <method>implIsSelected</method> and <method>implSelect</method>
        */
        void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        void SAL_CALL clearAccessibleSelection(  ) throw (::com::sun::star::uno::RuntimeException);
        void SAL_CALL selectAllAccessibleChildren(  ) throw (::com::sun::star::uno::RuntimeException);
        sal_Int32 SAL_CALL getSelectedAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    };

    //=====================================================================
    //= OAccessibleSelectionHelper
    //=====================================================================

    typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleSelection > OAccessibleSelectionHelper_Base;

    /** a helper class for implementing an AccessibleSelection which at the same time
        supports an XAccessibleSelection interface.
    */
    class COMPHELPER_DLLPUBLIC OAccessibleSelectionHelper : public OAccessibleComponentHelper,
                                       public OCommonAccessibleSelection,
                                       public OAccessibleSelectionHelper_Base
    {
    protected:

        OAccessibleSelectionHelper( );

        /// see the respective base class ctor for an extensive comment on this, please
        OAccessibleSelectionHelper( IMutex* _pExternalLock );

        // return ourself here by default
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException );

    public:

        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XAccessibleSelection - default implementations
        virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL clearAccessibleSelection(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL selectAllAccessibleChildren(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    };

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BorderHandler.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: os $ $Date: 2007-05-03 06:25:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_BORDERHANDLER_HXX
#include <BorderHandler.hxx>
#endif
#ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX
#include <PropertyMap.hxx>
#endif
#ifndef INCLUDED_RESOURCESIDS
#include <doctok/resourceids.hxx>
#endif
#ifndef INCLUDED_DMAPPER_CONVERSIONHELPER_HXX
#include <ConversionHelper.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif

namespace dmapper {

using namespace ::com::sun::star;
using namespace writerfilter;
//using namespace ::std;

/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
BorderHandler::BorderHandler() :
    m_nCurrentBorderPosition( BORDER_TOP ),
    m_nLineWidth(0),
    m_nLineType(0),
    m_nLineColor(0),
    m_nLineDistance(0)
{
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
BorderHandler::~BorderHandler()
{
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void BorderHandler::attribute(doctok::Id rName, doctok::Value & rVal)
{
    sal_Int32 nIntValue = rVal.getInt();
    switch( rName )
    {
        case NS_rtf::LN_rgbrc:
        {
            doctok::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            if( pProperties.get())
            {
                pProperties->resolve(*this);
                //
//                table::BorderLine* pToFill = 0;
//                switch(m_nCurrentBorderPosition)
//                {
//                    case BORDER_TOP:
//                        pToFill = &m_aTableBorder.TopLine;
//                        m_aTableBorder.IsTopLineValid = sal_True;
//                    break;
//                    case BORDER_LEFT:
//                        pToFill = &m_aTableBorder.LeftLine;
//                        m_aTableBorder.IsLeftLineValid = sal_True;
//                    break;
//                    case BORDER_BOTTOM:
//                        pToFill = &m_aTableBorder.BottomLine;
//                        m_aTableBorder.IsBottomLineValid = sal_True;;
//                    break;
//                    case BORDER_RIGHT:
//                        pToFill = &m_aTableBorder.RightLine;
//                        m_aTableBorder.IsRightLineValid = sal_True;
//                    break;
//                    case BORDER_HORIZONTAL:
//                        pToFill = &m_aTableBorder.HorizontalLine;
//                        m_aTableBorder.IsHorizontalLineValid = sal_True;;
//                    break;
//                    case BORDER_VERTICAL:
//                        m_aTableBorder.IsVerticalLineValid = sal_True;;
//                    default:
//                        pToFill = &m_aTableBorder.VerticalLine; break;
//                }
                ConversionHelper::MakeBorderLine( m_nLineWidth,   m_nLineType, m_nLineColor,
                                                                                m_aBorderLines[m_nCurrentBorderPosition] );
                OSL_ENSURE(m_nCurrentBorderPosition < BORDER_COUNT, "too many border values");
                ++m_nCurrentBorderPosition;
            }
        }
        break;
        case NS_rtf::LN_DPTLINEWIDTH: // 0x2871
            //  width of a single line in 1/8 pt, max of 32 pt -> twip * 5 / 2.
            m_nLineWidth = ConversionHelper::convertToMM100( nIntValue * 5 / 2 );
        break;
        case NS_rtf::LN_BRCTYPE:    // 0x2872
            m_nLineType = nIntValue;
        break;
        case NS_rtf::LN_ICO:        // 0x2873
            m_nLineColor = nIntValue;
        break;
        case NS_rtf::LN_DPTSPACE:   // 0x2874
            m_nLineDistance = nIntValue;
        break;
        case NS_rtf::LN_FSHADOW:    // 0x2875
            //if 1 then line has shadow - unsupported
        case NS_rtf::LN_FFRAME:     // 0x2876
        case NS_rtf::LN_UNUSED2_15: // 0x2877
            // ignored
        break;
        default:
            OSL_ASSERT("unknown attribute");
    }
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void BorderHandler::sprm(doctok::Sprm & rSprm)
{
    (void)rSprm;
}
/*-- 24.04.2007 09:09:01---------------------------------------------------

  -----------------------------------------------------------------------*/
PropertyMapPtr  BorderHandler::getProperties()
{
    static const PropertyIds aPropNames[BORDER_COUNT] =
    {
        PROP_TOP_BORDER,
        PROP_LEFT_BORDER,
        PROP_BOTTOM_BORDER,
        PROP_RIGHT_BORDER,
        META_PROP_HORIZONTAL_BORDER,
        META_PROP_VERTICAL_BORDER
    };
    PropertyMapPtr pPropertyMap(new PropertyMap);
    for( sal_Int32 nProp = 0; nProp < BORDER_COUNT; ++nProp)
        pPropertyMap->Insert( aPropNames[nProp], uno::makeAny( m_aBorderLines[nProp] ) );
    return pPropertyMap;
}
} //namespace dmapper
<commit_msg>don't apply default borders<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BorderHandler.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: os $ $Date: 2007-05-24 11:31:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_BORDERHANDLER_HXX
#include <BorderHandler.hxx>
#endif
#ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX
#include <PropertyMap.hxx>
#endif
#ifndef INCLUDED_RESOURCESIDS
#include <doctok/resourceids.hxx>
#endif
#ifndef INCLUDED_DMAPPER_CONVERSIONHELPER_HXX
#include <ConversionHelper.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif

namespace dmapper {

using namespace ::com::sun::star;
using namespace writerfilter;
//using namespace ::std;

/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
BorderHandler::BorderHandler() :
    m_nCurrentBorderPosition( BORDER_TOP ),
    m_nLineWidth(0),
    m_nLineType(0),
    m_nLineColor(0),
    m_nLineDistance(0)
{
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
BorderHandler::~BorderHandler()
{
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void BorderHandler::attribute(doctok::Id rName, doctok::Value & rVal)
{
    sal_Int32 nIntValue = rVal.getInt();
    switch( rName )
    {
        case NS_rtf::LN_rgbrc:
        {
            doctok::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();
            if( pProperties.get())
            {
                pProperties->resolve(*this);
                //
//                table::BorderLine* pToFill = 0;
//                switch(m_nCurrentBorderPosition)
//                {
//                    case BORDER_TOP:
//                        pToFill = &m_aTableBorder.TopLine;
//                        m_aTableBorder.IsTopLineValid = sal_True;
//                    break;
//                    case BORDER_LEFT:
//                        pToFill = &m_aTableBorder.LeftLine;
//                        m_aTableBorder.IsLeftLineValid = sal_True;
//                    break;
//                    case BORDER_BOTTOM:
//                        pToFill = &m_aTableBorder.BottomLine;
//                        m_aTableBorder.IsBottomLineValid = sal_True;;
//                    break;
//                    case BORDER_RIGHT:
//                        pToFill = &m_aTableBorder.RightLine;
//                        m_aTableBorder.IsRightLineValid = sal_True;
//                    break;
//                    case BORDER_HORIZONTAL:
//                        pToFill = &m_aTableBorder.HorizontalLine;
//                        m_aTableBorder.IsHorizontalLineValid = sal_True;;
//                    break;
//                    case BORDER_VERTICAL:
//                        m_aTableBorder.IsVerticalLineValid = sal_True;;
//                    default:
//                        pToFill = &m_aTableBorder.VerticalLine; break;
//                }
                ConversionHelper::MakeBorderLine( m_nLineWidth,   m_nLineType, m_nLineColor,
                                                                                m_aBorderLines[m_nCurrentBorderPosition] );
                OSL_ENSURE(m_nCurrentBorderPosition < BORDER_COUNT, "too many border values");
                ++m_nCurrentBorderPosition;
            }
        }
        break;
        case NS_rtf::LN_DPTLINEWIDTH: // 0x2871
            //  width of a single line in 1/8 pt, max of 32 pt -> twip * 5 / 2.
            m_nLineWidth = ConversionHelper::convertToMM100( nIntValue * 5 / 2 );
        break;
        case NS_rtf::LN_BRCTYPE:    // 0x2872
            m_nLineType = nIntValue;
        break;
        case NS_rtf::LN_ICO:        // 0x2873
            m_nLineColor = nIntValue;
        break;
        case NS_rtf::LN_DPTSPACE:   // 0x2874
            m_nLineDistance = nIntValue;
        break;
        case NS_rtf::LN_FSHADOW:    // 0x2875
            //if 1 then line has shadow - unsupported
        case NS_rtf::LN_FFRAME:     // 0x2876
        case NS_rtf::LN_UNUSED2_15: // 0x2877
            // ignored
        break;
        default:
            OSL_ASSERT("unknown attribute");
    }
}
/*-- 24.04.2007 09:06:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void BorderHandler::sprm(doctok::Sprm & rSprm)
{
    (void)rSprm;
}
/*-- 24.04.2007 09:09:01---------------------------------------------------

  -----------------------------------------------------------------------*/
PropertyMapPtr  BorderHandler::getProperties()
{
    static const PropertyIds aPropNames[BORDER_COUNT] =
    {
        PROP_TOP_BORDER,
        PROP_LEFT_BORDER,
        PROP_BOTTOM_BORDER,
        PROP_RIGHT_BORDER,
        META_PROP_HORIZONTAL_BORDER,
        META_PROP_VERTICAL_BORDER
    };
    PropertyMapPtr pPropertyMap(new PropertyMap);
    // don't fill in default properties
    if( m_nCurrentBorderPosition )
    {
        for( sal_Int32 nProp = 0; nProp < BORDER_COUNT; ++nProp)
            pPropertyMap->Insert( aPropNames[nProp], uno::makeAny( m_aBorderLines[nProp] ) );
    }
    return pPropertyMap;
}
} //namespace dmapper
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#define REQUIRESSL

#include "Modules.h"
#include "User.h"
#include "Listener.h"
#include "znc.h"

class CSSLClientCertMod : public CGlobalModule {
public:
	GLOBALMODCONSTRUCTOR(CSSLClientCertMod) {}
	virtual ~CSSLClientCertMod() {}

	virtual bool OnBoot() {
		const vector<CListener*>& vListeners = CZNC::Get().GetListeners();
		vector<CListener*>::const_iterator it;

		// We need the SSL_VERIFY_PEER flag on all listeners, or else
		// the client doesn't send a ssl cert
		for (it = vListeners.begin(); it != vListeners.end(); it++)
			(*it)->GetRealListener()->SetRequireClientCertFlags(SSL_VERIFY_PEER);

		MCString::iterator it1;
		for (it1 = BeginNV(); it1 != EndNV(); it1++) {
			VCString vsKeys;
			VCString::iterator it2;

			if (CZNC::Get().FindUser(it1->first) == NULL) {
				DEBUG("Unknown user in saved data [" + it1->first + "]");
				continue;
			}

			it1->second.Split(" ", vsKeys, false);
			for (it2 = vsKeys.begin(); it2 != vsKeys.end(); it2++) {
				m_PubKeys[it1->first].insert(*it2);
			}
		}

		return true;
	}

	virtual void OnPostRehash() {
		OnBoot();
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		OnBoot();

		return true;
	}

	bool Save() {
		MSCString::iterator it;

		ClearNV(false);
		for (it = m_PubKeys.begin(); it != m_PubKeys.end(); it++) {
			CString sVal;
			SCString::iterator it2;
			for (it2 = it->second.begin(); it2 != it->second.end(); it2++) {
				sVal += *it2 + " ";
			}

			if (!sVal.empty())
				SetNV(it->first, sVal, false);
		}

		return SaveRegistry();
	}

	virtual EModRet OnLoginAttempt(CSmartPtr<CAuthBase> Auth) {
		CString sUser = Auth->GetUsername();
		Csock *pSock = Auth->GetSocket();
		CUser *pUser = CZNC::Get().FindUser(sUser);

		if (pSock == NULL || pUser == NULL)
			return CONTINUE;

		CString sPubKey = GetKey(pSock);
		DEBUG("User: " << sUser << " Key: " << sPubKey);

		if (sPubKey.empty()) {
			DEBUG("Peer got no public key, ignoring");
			return CONTINUE;
		}

		MSCString::iterator it = m_PubKeys.find(sUser);
		if (it == m_PubKeys.end()) {
			DEBUG("No saved pubkeys for this client");
			return CONTINUE;
		}

		SCString::iterator it2 = it->second.find(sPubKey);
		if (it2 == it->second.end()) {
			DEBUG("Invalid pubkey");
			return CONTINUE;
		}

		// This client uses a valid pubkey for this user, let them in
		DEBUG("Accepted pubkey auth");
		Auth->AcceptLogin(*pUser);

		return HALT;
	}

	virtual void OnModCommand(const CString& sCommand) {
		CString sCmd = sCommand.Token(0);

		if (sCmd.Equals("show")) {
			CString sPubKey = GetKey(m_pClient);
			if (sPubKey.empty())
				PutModule("You are not connected with any valid public key");
			else
				PutModule("Your current public key is: " + sPubKey);
		} else if (sCmd.Equals("add")) {
			CString sPubKey = GetKey(m_pClient);
			if (sPubKey.empty())
				PutModule("You are not connected with any valid public key");
			else {
				pair<SCString::iterator, bool> res = m_PubKeys[m_pUser->GetUserName()].insert(sPubKey);
				if (res.second) {
					PutModule("Added your current public key to the list");
					Save();
				} else
					PutModule("Your key was already added");
			}
		} else if (sCmd.Equals("list")) {
			CTable Table;

			Table.AddColumn("Id");
			Table.AddColumn("Key");

			MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());
			if (it == m_PubKeys.end()) {
				PutModule("No keys set for your user");
				return;
			}

			SCString::iterator it2;
			unsigned int id = 1;
			for (it2 = it->second.begin(); it2 != it->second.end(); it2++) {
				Table.AddRow();
				Table.SetCell("Id", CString(id++));
				Table.SetCell("Key", *it2);
			}

			if (PutModule(Table) == 0)
				// This double check is necessary, because the
				// set could be empty.
				PutModule("No keys set for your user");
		} else if (sCmd.Equals("del") || sCmd.Equals("remove")) {
			unsigned int id = sCommand.Token(1, true).ToUInt();
			MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());

			if (it == m_PubKeys.end()) {
				PutModule("No keys set for your user");
				return;
			}

			if (id == 0 || id > it->second.size()) {
				PutModule("Invalid #, check \"list\"");
				return;
			}

			SCString::iterator it2 = it->second.begin();
			while (id > 1) {
				it2++;
				id--;
			}

			it->second.erase(it2);
			if (it->second.size() == 0)
				m_PubKeys.erase(it);
			PutModule("Removed");

			Save();
		} else {
			PutModule("Commands: show, list, add, del [no]");
		}
	}

	CString GetKey(Csock *pSock) {
		CString sRes;
		int res = pSock->GetPeerFingerprint(sRes);

		DEBUG("GetKey() returned status " << res << " with key " << sRes);

		// This is 'inspired' by charybdis' libratbox
		switch (res) {
		case X509_V_OK:
		case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
		case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
			return sRes;
		default:
			return "";
		}
	}

private:
	// Maps user names to a list of allowed pubkeys
	typedef map<CString, set<CString> > MSCString;
	MSCString                           m_PubKeys;
};

GLOBALMODULEDEFS(CSSLClientCertMod, "Allow users to authenticate via SSL client certificates")
<commit_msg>Make certauth use the CModCommand API<commit_after>/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#define REQUIRESSL

#include "Modules.h"
#include "User.h"
#include "Listener.h"
#include "znc.h"

class CSSLClientCertMod : public CGlobalModule {
public:
	GLOBALMODCONSTRUCTOR(CSSLClientCertMod) {
		AddHelpCommand();
		AddCommand("Add",  static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleAddCommand));
		AddCommand("Del",  static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleDelCommand),
			"id");
		AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleListCommand));
		AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleShowCommand),
			"", "Print your current key");
	}

	virtual ~CSSLClientCertMod() {}

	virtual bool OnBoot() {
		const vector<CListener*>& vListeners = CZNC::Get().GetListeners();
		vector<CListener*>::const_iterator it;

		// We need the SSL_VERIFY_PEER flag on all listeners, or else
		// the client doesn't send a ssl cert
		for (it = vListeners.begin(); it != vListeners.end(); it++)
			(*it)->GetRealListener()->SetRequireClientCertFlags(SSL_VERIFY_PEER);

		MCString::iterator it1;
		for (it1 = BeginNV(); it1 != EndNV(); it1++) {
			VCString vsKeys;
			VCString::iterator it2;

			if (CZNC::Get().FindUser(it1->first) == NULL) {
				DEBUG("Unknown user in saved data [" + it1->first + "]");
				continue;
			}

			it1->second.Split(" ", vsKeys, false);
			for (it2 = vsKeys.begin(); it2 != vsKeys.end(); it2++) {
				m_PubKeys[it1->first].insert(*it2);
			}
		}

		return true;
	}

	virtual void OnPostRehash() {
		OnBoot();
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		OnBoot();

		return true;
	}

	bool Save() {
		MSCString::iterator it;

		ClearNV(false);
		for (it = m_PubKeys.begin(); it != m_PubKeys.end(); it++) {
			CString sVal;
			SCString::iterator it2;
			for (it2 = it->second.begin(); it2 != it->second.end(); it2++) {
				sVal += *it2 + " ";
			}

			if (!sVal.empty())
				SetNV(it->first, sVal, false);
		}

		return SaveRegistry();
	}

	virtual EModRet OnLoginAttempt(CSmartPtr<CAuthBase> Auth) {
		CString sUser = Auth->GetUsername();
		Csock *pSock = Auth->GetSocket();
		CUser *pUser = CZNC::Get().FindUser(sUser);

		if (pSock == NULL || pUser == NULL)
			return CONTINUE;

		CString sPubKey = GetKey(pSock);
		DEBUG("User: " << sUser << " Key: " << sPubKey);

		if (sPubKey.empty()) {
			DEBUG("Peer got no public key, ignoring");
			return CONTINUE;
		}

		MSCString::iterator it = m_PubKeys.find(sUser);
		if (it == m_PubKeys.end()) {
			DEBUG("No saved pubkeys for this client");
			return CONTINUE;
		}

		SCString::iterator it2 = it->second.find(sPubKey);
		if (it2 == it->second.end()) {
			DEBUG("Invalid pubkey");
			return CONTINUE;
		}

		// This client uses a valid pubkey for this user, let them in
		DEBUG("Accepted pubkey auth");
		Auth->AcceptLogin(*pUser);

		return HALT;
	}

	void HandleShowCommand(const CString& sLine) {
		CString sPubKey = GetKey(m_pClient);

		if (sPubKey.empty()) {
			PutModule("You are not connected with any valid public key");
		} else {
			PutModule("Your current public key is: " + sPubKey);
		}
	}

	void HandleAddCommand(const CString& sLine) {
		CString sPubKey = GetKey(m_pClient);

		if (sPubKey.empty()) {
			PutModule("You are not connected with any valid public key");
		} else {
			pair<SCString::iterator, bool> res = m_PubKeys[m_pUser->GetUserName()].insert(sPubKey);
			if (res.second) {
				PutModule("Added your current public key to the list");
				Save();
			} else {
				PutModule("Your key was already added");
			}
		}
	}

	void HandleListCommand(const CString& sLine) {
		CTable Table;

		Table.AddColumn("Id");
		Table.AddColumn("Key");

		MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());
		if (it == m_PubKeys.end()) {
			PutModule("No keys set for your user");
			return;
		}

		SCString::iterator it2;
		unsigned int id = 1;
		for (it2 = it->second.begin(); it2 != it->second.end(); it2++) {
			Table.AddRow();
			Table.SetCell("Id", CString(id++));
			Table.SetCell("Key", *it2);
		}

		if (PutModule(Table) == 0) {
			// This double check is necessary, because the
			// set could be empty.
			PutModule("No keys set for your user");
		}
	}

	void HandleDelCommand(const CString& sLine) {
		unsigned int id = sLine.Token(1, true).ToUInt();
		MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());

		if (it == m_PubKeys.end()) {
			PutModule("No keys set for your user");
			return;
		}

		if (id == 0 || id > it->second.size()) {
			PutModule("Invalid #, check \"list\"");
			return;
		}

		SCString::iterator it2 = it->second.begin();
		while (id > 1) {
			it2++;
			id--;
		}

		it->second.erase(it2);
		if (it->second.size() == 0)
			m_PubKeys.erase(it);
		PutModule("Removed");

		Save();
	}

	CString GetKey(Csock *pSock) {
		CString sRes;
		int res = pSock->GetPeerFingerprint(sRes);

		DEBUG("GetKey() returned status " << res << " with key " << sRes);

		// This is 'inspired' by charybdis' libratbox
		switch (res) {
		case X509_V_OK:
		case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
		case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
			return sRes;
		default:
			return "";
		}
	}

private:
	// Maps user names to a list of allowed pubkeys
	typedef map<CString, set<CString> > MSCString;
	MSCString                           m_PubKeys;
};

GLOBALMODULEDEFS(CSSLClientCertMod, "Allow users to authenticate via SSL client certificates")
<|endoftext|>


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

#ifndef INCLUDED_RTL_CHARACTER_HXX
#define INCLUDED_RTL_CHARACTER_HXX

#include "sal/config.h"

#include "sal/types.h"

namespace rtl
{
/** Check for ASCII character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a ASCII character (0x00--0x7F).

    @since LibreOffice 4.1
 */
inline bool isAscii(sal_uInt32 nUtf32)
{
    return nUtf32 <= 0x7F;
}

/** Check for ASCII lower case character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a US-ASCII lower case alphabetic character
    (ASCII 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiLowerCase(sal_uInt32 nUtf32)
{
    return nUtf32 >= 'a' && nUtf32 <= 'z';
}

/** Check for US-ASCII upper case character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a US-ASCII upper case alphabetic character
    (US-ASCII 'A'--'Z').

    @since LibreOffice 4.1
 */
inline bool isAsciiUpperCase(sal_uInt32 nUtf32)
{
    return nUtf32 >= 'A' && nUtf32 <= 'Z';
}

/** Check for ASCII alphanumeric character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nUtf32 is a US-ASCII alphanumeric character
    (ASCII '0'--'9', 'A'--'Z' or 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiAlpha(sal_uInt32 nUtf32)
{
    return isAsciiLowerCase(nUtf32) || isAsciiUpperCase(nUtf32);
}

/** Check for ASCII digit character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a ASCII (decimal) digit character
    (ASCII '0'--'9').

    @since LibreOffice 4.1
 */
inline bool isAsciiDigit(sal_uInt32 nUtf32)
{
    return nUtf32 >= '0' && nUtf32 <= '9';
}

/** Check for US-ASCII alphanumeric character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a US-ASCII alphanumeric character (US-ASCII
    '0'--'9', 'A'--'Z' or 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiAlphanumeric(sal_uInt32 nUtf32)
{
    return isAsciiDigit(nUtf32) || isAsciiAlpha(nUtf32);
}

/** Check for US-ASCII canonic hexadecimal digit character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a US-ASCII canonic (i.e., upper case)
    hexadecimal digit character (US-ASCII '0'--'9' or 'A'--'F').

    @since LibreOffice 4.1
 */
inline bool isAsciiCanonicHexDigit(sal_uInt32 nUtf32)
{
    return isAsciiDigit(nUtf32) || (nUtf32 >= 'A' && nUtf32 <= 'F');
}

/** Check for US-ASCII hexadecimal digit character.

    @param nUtf32  Some UCS-4 character.

    @return  True if nChar is a US-ASCII hexadecimal digit character (US-
    ASCII '0'--'9', 'A'--'F', 'a'--'f').

    @since LibreOffice 4.1
 */
inline bool isAsciiHexDigit(sal_uInt32 nUtf32)
{
    return isAsciiCanonicHexDigit(nUtf32) || (nUtf32 >= 'a' && nUtf32 <= 'f');
}

}//rtl namespace

#endif

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

#ifndef INCLUDED_RTL_CHARACTER_HXX
#define INCLUDED_RTL_CHARACTER_HXX

#include "sal/config.h"

#include "sal/types.h"

namespace rtl
{
/** Check for ASCII character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a ASCII character (0x00--0x7F).

    @since LibreOffice 4.1
 */
inline bool isAscii(sal_uInt32 nUtf32)
{
    return nUtf32 <= 0x7F;
}

/** Check for ASCII lower case character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a US-ASCII lower case alphabetic character
    (ASCII 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiLowerCase(sal_uInt32 nUtf32)
{
    return nUtf32 >= 'a' && nUtf32 <= 'z';
}

/** Check for US-ASCII upper case character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a US-ASCII upper case alphabetic character
    (US-ASCII 'A'--'Z').

    @since LibreOffice 4.1
 */
inline bool isAsciiUpperCase(sal_uInt32 nUtf32)
{
    return nUtf32 >= 'A' && nUtf32 <= 'Z';
}

/** Check for ASCII alphanumeric character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nUtf32 is a US-ASCII alphanumeric character
    (ASCII '0'--'9', 'A'--'Z' or 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiAlpha(sal_uInt32 nUtf32)
{
    return isAsciiLowerCase(nUtf32) || isAsciiUpperCase(nUtf32);
}

/** Check for ASCII digit character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a ASCII (decimal) digit character
    (ASCII '0'--'9').

    @since LibreOffice 4.1
 */
inline bool isAsciiDigit(sal_uInt32 nUtf32)
{
    return nUtf32 >= '0' && nUtf32 <= '9';
}

/** Check for US-ASCII alphanumeric character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a US-ASCII alphanumeric character (US-ASCII
    '0'--'9', 'A'--'Z' or 'a'--'z').

    @since LibreOffice 4.1
 */
inline bool isAsciiAlphanumeric(sal_uInt32 nUtf32)
{
    return isAsciiDigit(nUtf32) || isAsciiAlpha(nUtf32);
}

/** Check for US-ASCII canonic hexadecimal digit character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a US-ASCII canonic (i.e., upper case)
    hexadecimal digit character (US-ASCII '0'--'9' or 'A'--'F').

    @since LibreOffice 4.1
 */
inline bool isAsciiCanonicHexDigit(sal_uInt32 nUtf32)
{
    return isAsciiDigit(nUtf32) || (nUtf32 >= 'A' && nUtf32 <= 'F');
}

/** Check for US-ASCII hexadecimal digit character.

    @param nUtf32  A Unicode scalar value (represented as a UTF-32 code unit).

    @return  True if nChar is a US-ASCII hexadecimal digit character (US-
    ASCII '0'--'9', 'A'--'F', 'a'--'f').

    @since LibreOffice 4.1
 */
inline bool isAsciiHexDigit(sal_uInt32 nUtf32)
{
    return isAsciiCanonicHexDigit(nUtf32) || (nUtf32 >= 'a' && nUtf32 <= 'f');
}

}//rtl namespace

#endif

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


<commit_before>// Copyright (c) 2014-2020 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <governance/governanceclasses.h>
#include <governance/governancevalidators.h>
#include <validation.h>
#include <rpc/server.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <rpc/blockchain.h>
#include <node/context.h>

UniValue VoteWithMasternodes(const std::map<uint256, CKey>& keys,
                             const uint256& hash, vote_signal_enum_t eVoteSignal,
                             vote_outcome_enum_t eVoteOutcome, CConnman& connman)
{
    {
        LOCK(governance.cs);
        CGovernanceObject *pGovObj = governance.FindGovernanceObject(hash);
        if (!pGovObj) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Governance object not found");
        }
    }

    int nSuccessful = 0;
    int nFailed = 0;
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);

    UniValue resultsObj(UniValue::VOBJ);

    for (const auto& p : keys) {
        const auto& proTxHash = p.first;
        const auto& key = p.second;

        UniValue statusObj(UniValue::VOBJ);

        auto dmn = mnList.GetValidMN(proTxHash);
        if (!dmn) {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", "Can't find masternode by proTxHash");
            resultsObj.pushKV(proTxHash.ToString(), statusObj);
            continue;
        }

        CGovernanceVote vote(dmn->collateralOutpoint, hash, eVoteSignal, eVoteOutcome);
        if (!vote.Sign(key, key.GetPubKey().GetID())) {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", "Failure to sign.");
            resultsObj.pushKV(proTxHash.ToString(), statusObj);
            continue;
        }

        CGovernanceException exception;
        if (governance.ProcessVoteAndRelay(vote, exception, connman)) {
            nSuccessful++;
            statusObj.pushKV("result", "success");
        } else {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", exception.GetMessage());
        }

        resultsObj.pushKV(proTxHash.ToString(), statusObj);
    }

    UniValue returnObj(UniValue::VOBJ);
    returnObj.pushKV("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", nSuccessful, nFailed));
    returnObj.pushKV("detail", resultsObj);

    return returnObj;
}

static RPCHelpMan gobject_prepare()
{
    return RPCHelpMan{"gobject_prepare",
        "\nPrepare governance object by signing and creating tx.\n",
        {
            {"parentHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the parent object, \"0\" is root."},
            {"revision", RPCArg::Type::NUM, RPCArg::Optional::NO, "Object revision in the system."},
            {"time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time this object was created."},
            {"dataHex", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Data in hex string form."},
            {"outputHash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The single output to submit the proposal fee from."},
            {"outputIndex", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The output index."},
        },
        RPCResult{RPCResult::Type::STR_HEX, "hash", "txid"},
        RPCExamples{
                HelpExampleCli("gobject_prepare", "")
            + HelpExampleRpc("gobject_prepare", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();
    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    EnsureWalletIsUnlocked(pwallet);

    // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS

    uint256 hashParent;

    // -- attach to root node (root node doesn't really exist, but has a hash of zero)
    if (request.params[0].get_str() == "0") {
        hashParent = uint256();
    } else {
        hashParent = ParseHashV(request.params[0], "feeTxid");
    }

    int nRevision = request.params[1].get_int();
    int64_t nTime = request.params[2].get_int64();
    std::string strDataHex = request.params[3].get_str();

    // CREATE A NEW COLLATERAL TRANSACTION FOR THIS SPECIFIC OBJECT

    CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);

    // This command is dangerous because it consumes 150 SYS irreversibly.
    // If params are lost, it's very hard to bruteforce them and yet
    // users ignore all instructions on syshub etc. and do not save them...
    // Let's log them here and hope users do not mess with debug.log
    LogPrintf("gobject_prepare -- params: %s %s %s %s, data: %s, hash: %s\n",
                request.params[0].get_str(), request.params[1].get_str(),
                request.params[2].get_str(), request.params[3].get_str(),
                govobj.GetDataAsPlainString(), govobj.GetHash().ToString());

    if (govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
        CProposalValidator validator(strDataHex, false);
        if (!validator.Validate()) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages());
        }
    }

    if (govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Trigger objects need not be prepared (however only masternodes can create them)");
    }

    LOCK(pwallet->cs_wallet);

    std::string strError = "";
    if (!govobj.IsValidLocally(strError, false))
        throw JSONRPCError(RPC_INTERNAL_ERROR, "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError);

    // If specified, spend this outpoint as the proposal fee
    COutPoint outpoint;
    outpoint.SetNull();
    if (!request.params[4].isNull() && !request.params[5].isNull()) {
        uint256 collateralHash = ParseHashV(request.params[4], "outputHash");
        int32_t collateralIndex = request.params[5].get_int();
        if (collateralHash.IsNull() || collateralIndex < 0) {
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("invalid hash or index: %s-%d", collateralHash.ToString(), collateralIndex));
        }
        outpoint = COutPoint(collateralHash, (uint32_t)collateralIndex);
    }

    CTransactionRef tx;
    if (!pwallet->GetBudgetSystemCollateralTX(tx, govobj.GetHash(), govobj.GetMinCollateralFee(), outpoint)) {
        std::string err = "Error making collateral transaction for governance object. Please check your wallet balance and make sure your wallet is unlocked.";
        if (!request.params[5].isNull() && !request.params[6].isNull()) {
            err += "Please verify your specified output is valid and is enough for the combined proposal fee and transaction fee.";
        }
        throw JSONRPCError(RPC_INTERNAL_ERROR, err);
    }

    // -- send the tx to the network
    mapValue_t mapValue;
    pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */);

    LogPrint(BCLog::GOBJECT, "gobject_prepare -- GetDataAsPlainString = %s, hash = %s, txid = %s\n",
                govobj.GetDataAsPlainString(), govobj.GetHash().ToString(), tx->GetHash().ToString());

    return tx->GetHash().ToString();
},
    };
}

static RPCHelpMan gobject_vote_many()
{
    return RPCHelpMan{"gobject_vote_many",
        "\nVote on a governance object by all masternodes for which the voting key is present in the local wallet.\n",
        {
            {"governanceHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the governance object."},
            {"vote", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote, possible values: [funding|valid|delete|endorsed]."},
            {"voteOutome", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote outcome, possible values: [yes|no|abstain]."},
        },
        RPCResult{RPCResult::Type::NONE, "", ""},
        RPCExamples{
                HelpExampleCli("gobject_vote_many", "")
            + HelpExampleRpc("gobject_vote_many", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    uint256 hash = ParseHashV(request.params[0], "Object hash");
    std::string strVoteSignal = request.params[1].get_str();
    std::string strVoteOutcome = request.params[2].get_str();

    vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);
    if (eVoteSignal == VOTE_SIGNAL_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER,
                           "Invalid vote signal. Please using one of the following: "
                           "(funding|valid|delete|endorsed)");
    }

    vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);
    if (eVoteOutcome == VOTE_OUTCOME_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'");
    }

    EnsureWalletIsUnlocked(pwallet);

    std::map<uint256, CKey> votingKeys;
    // Make sure the results are valid at least up to the most recent block
    // the user could have gotten from another RPC command prior to now
    pwallet->BlockUntilSyncedToCurrentChain();
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);
    mnList.ForEachMN(true, [&](const CDeterministicMNCPtr& dmn) {
        LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
        LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);

        EnsureWalletIsUnlocked(pwallet);

        CKey key;
        if (spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {
            votingKeys.emplace(dmn->proTxHash, key);
        }
    });

    return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);
},
    };
}

static RPCHelpMan gobject_vote_alias()
{
    return RPCHelpMan{"gobject_vote_alias",
        "\nVote on a governance object by masternode's voting key (if present in local wallet).\n",
        {
            {"governanceHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the governance object."},
            {"vote", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote, possible values: [funding|valid|delete|endorsed]."},
            {"voteOutome", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote outcome, possible values: [yes|no|abstain]."},
            {"protxHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Masternode's proTxHash."},
        },
        RPCResult{RPCResult::Type::NONE, "", ""},
        RPCExamples{
                HelpExampleCli("gobject_vote_alias", "")
            + HelpExampleRpc("gobject_vote_alias", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    uint256 hash = ParseHashV(request.params[0], "Object hash");
    std::string strVoteSignal = request.params[1].get_str();
    std::string strVoteOutcome = request.params[2].get_str();

    vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);
    if (eVoteSignal == VOTE_SIGNAL_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER,
                           "Invalid vote signal. Please using one of the following: "
                           "(funding|valid|delete|endorsed)");
    }

    vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);
    if (eVoteOutcome == VOTE_OUTCOME_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'");
    }

    EnsureWalletIsUnlocked(pwallet);

    uint256 proTxHash = ParseHashV(request.params[3], "protxHash");
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);
    auto dmn = mnList.GetValidMN(proTxHash);
    if (!dmn) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid or unknown proTxHash");
    }
    // Make sure the results are valid at least up to the most recent block
    // the user could have gotten from another RPC command prior to now
    pwallet->BlockUntilSyncedToCurrentChain();
    CKey key;
    {
        LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
        LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);

        if (!spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Private key for voting address %s not known by wallet", EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting))));
        }
    }

    std::map<uint256, CKey> votingKeys;
    votingKeys.emplace(proTxHash, key);

    return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);
},
    };
}

Span<const CRPCCommand> GetGovernanceWalletRPCCommands()
{
// clang-format off
static const CRPCCommand commands[] =
{ //  category              name                      actor (function)         argNames
//  --------------------- ------------------------  -----------------------  ----------
    { "governancewallet",               "gobject_vote_alias",     &gobject_vote_alias,      {"governanceHash","vote","voteOutome","protxHash"} },
    { "governancewallet",               "gobject_vote_many",      &gobject_vote_many,       {"governanceHash","vote","voteOutome"} },
    { "governancewallet",               "gobject_prepare",        &gobject_prepare,         {"parentHash","revision","time","dataHex","outputHash","outputIndex"} },

};
// clang-format on
    return MakeSpan(commands);
}
<commit_msg>fix gitian fail with govc exception<commit_after>// Copyright (c) 2014-2020 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <governance/governanceexceptions.h>
#include <governance/governanceclasses.h>
#include <governance/governancevalidators.h>
#include <validation.h>
#include <rpc/server.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <rpc/blockchain.h>
#include <node/context.h>

UniValue VoteWithMasternodes(const std::map<uint256, CKey>& keys,
                             const uint256& hash, vote_signal_enum_t eVoteSignal,
                             vote_outcome_enum_t eVoteOutcome, CConnman& connman)
{
    {
        LOCK(governance.cs);
        CGovernanceObject *pGovObj = governance.FindGovernanceObject(hash);
        if (!pGovObj) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Governance object not found");
        }
    }

    int nSuccessful = 0;
    int nFailed = 0;
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);

    UniValue resultsObj(UniValue::VOBJ);

    for (const auto& p : keys) {
        const auto& proTxHash = p.first;
        const auto& key = p.second;

        UniValue statusObj(UniValue::VOBJ);

        auto dmn = mnList.GetValidMN(proTxHash);
        if (!dmn) {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", "Can't find masternode by proTxHash");
            resultsObj.pushKV(proTxHash.ToString(), statusObj);
            continue;
        }

        CGovernanceVote vote(dmn->collateralOutpoint, hash, eVoteSignal, eVoteOutcome);
        if (!vote.Sign(key, key.GetPubKey().GetID())) {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", "Failure to sign.");
            resultsObj.pushKV(proTxHash.ToString(), statusObj);
            continue;
        }

        CGovernanceException exception;
        if (governance.ProcessVoteAndRelay(vote, exception, connman)) {
            nSuccessful++;
            statusObj.pushKV("result", "success");
        } else {
            nFailed++;
            statusObj.pushKV("result", "failed");
            statusObj.pushKV("errorMessage", exception.GetMessage());
        }

        resultsObj.pushKV(proTxHash.ToString(), statusObj);
    }

    UniValue returnObj(UniValue::VOBJ);
    returnObj.pushKV("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", nSuccessful, nFailed));
    returnObj.pushKV("detail", resultsObj);

    return returnObj;
}

static RPCHelpMan gobject_prepare()
{
    return RPCHelpMan{"gobject_prepare",
        "\nPrepare governance object by signing and creating tx.\n",
        {
            {"parentHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the parent object, \"0\" is root."},
            {"revision", RPCArg::Type::NUM, RPCArg::Optional::NO, "Object revision in the system."},
            {"time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time this object was created."},
            {"dataHex", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Data in hex string form."},
            {"outputHash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The single output to submit the proposal fee from."},
            {"outputIndex", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The output index."},
        },
        RPCResult{RPCResult::Type::STR_HEX, "hash", "txid"},
        RPCExamples{
                HelpExampleCli("gobject_prepare", "")
            + HelpExampleRpc("gobject_prepare", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();
    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    EnsureWalletIsUnlocked(pwallet);

    // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS

    uint256 hashParent;

    // -- attach to root node (root node doesn't really exist, but has a hash of zero)
    if (request.params[0].get_str() == "0") {
        hashParent = uint256();
    } else {
        hashParent = ParseHashV(request.params[0], "feeTxid");
    }

    int nRevision = request.params[1].get_int();
    int64_t nTime = request.params[2].get_int64();
    std::string strDataHex = request.params[3].get_str();

    // CREATE A NEW COLLATERAL TRANSACTION FOR THIS SPECIFIC OBJECT

    CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);

    // This command is dangerous because it consumes 150 SYS irreversibly.
    // If params are lost, it's very hard to bruteforce them and yet
    // users ignore all instructions on syshub etc. and do not save them...
    // Let's log them here and hope users do not mess with debug.log
    LogPrintf("gobject_prepare -- params: %s %s %s %s, data: %s, hash: %s\n",
                request.params[0].get_str(), request.params[1].get_str(),
                request.params[2].get_str(), request.params[3].get_str(),
                govobj.GetDataAsPlainString(), govobj.GetHash().ToString());

    if (govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
        CProposalValidator validator(strDataHex, false);
        if (!validator.Validate()) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages());
        }
    }

    if (govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Trigger objects need not be prepared (however only masternodes can create them)");
    }

    LOCK(pwallet->cs_wallet);

    std::string strError = "";
    if (!govobj.IsValidLocally(strError, false))
        throw JSONRPCError(RPC_INTERNAL_ERROR, "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError);

    // If specified, spend this outpoint as the proposal fee
    COutPoint outpoint;
    outpoint.SetNull();
    if (!request.params[4].isNull() && !request.params[5].isNull()) {
        uint256 collateralHash = ParseHashV(request.params[4], "outputHash");
        int32_t collateralIndex = request.params[5].get_int();
        if (collateralHash.IsNull() || collateralIndex < 0) {
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("invalid hash or index: %s-%d", collateralHash.ToString(), collateralIndex));
        }
        outpoint = COutPoint(collateralHash, (uint32_t)collateralIndex);
    }

    CTransactionRef tx;
    if (!pwallet->GetBudgetSystemCollateralTX(tx, govobj.GetHash(), govobj.GetMinCollateralFee(), outpoint)) {
        std::string err = "Error making collateral transaction for governance object. Please check your wallet balance and make sure your wallet is unlocked.";
        if (!request.params[5].isNull() && !request.params[6].isNull()) {
            err += "Please verify your specified output is valid and is enough for the combined proposal fee and transaction fee.";
        }
        throw JSONRPCError(RPC_INTERNAL_ERROR, err);
    }

    // -- send the tx to the network
    mapValue_t mapValue;
    pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */);

    LogPrint(BCLog::GOBJECT, "gobject_prepare -- GetDataAsPlainString = %s, hash = %s, txid = %s\n",
                govobj.GetDataAsPlainString(), govobj.GetHash().ToString(), tx->GetHash().ToString());

    return tx->GetHash().ToString();
},
    };
}

static RPCHelpMan gobject_vote_many()
{
    return RPCHelpMan{"gobject_vote_many",
        "\nVote on a governance object by all masternodes for which the voting key is present in the local wallet.\n",
        {
            {"governanceHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the governance object."},
            {"vote", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote, possible values: [funding|valid|delete|endorsed]."},
            {"voteOutome", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote outcome, possible values: [yes|no|abstain]."},
        },
        RPCResult{RPCResult::Type::NONE, "", ""},
        RPCExamples{
                HelpExampleCli("gobject_vote_many", "")
            + HelpExampleRpc("gobject_vote_many", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    uint256 hash = ParseHashV(request.params[0], "Object hash");
    std::string strVoteSignal = request.params[1].get_str();
    std::string strVoteOutcome = request.params[2].get_str();

    vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);
    if (eVoteSignal == VOTE_SIGNAL_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER,
                           "Invalid vote signal. Please using one of the following: "
                           "(funding|valid|delete|endorsed)");
    }

    vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);
    if (eVoteOutcome == VOTE_OUTCOME_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'");
    }

    EnsureWalletIsUnlocked(pwallet);

    std::map<uint256, CKey> votingKeys;
    // Make sure the results are valid at least up to the most recent block
    // the user could have gotten from another RPC command prior to now
    pwallet->BlockUntilSyncedToCurrentChain();
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);
    mnList.ForEachMN(true, [&](const CDeterministicMNCPtr& dmn) {
        LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
        LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);

        EnsureWalletIsUnlocked(pwallet);

        CKey key;
        if (spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {
            votingKeys.emplace(dmn->proTxHash, key);
        }
    });

    return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);
},
    };
}

static RPCHelpMan gobject_vote_alias()
{
    return RPCHelpMan{"gobject_vote_alias",
        "\nVote on a governance object by masternode's voting key (if present in local wallet).\n",
        {
            {"governanceHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Hash of the governance object."},
            {"vote", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote, possible values: [funding|valid|delete|endorsed]."},
            {"voteOutome", RPCArg::Type::STR, RPCArg::Optional::NO, "Vote outcome, possible values: [yes|no|abstain]."},
            {"protxHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Masternode's proTxHash."},
        },
        RPCResult{RPCResult::Type::NONE, "", ""},
        RPCExamples{
                HelpExampleCli("gobject_vote_alias", "")
            + HelpExampleRpc("gobject_vote_alias", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    NodeContext& node = EnsureNodeContext(request.context);
    if(!node.connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    uint256 hash = ParseHashV(request.params[0], "Object hash");
    std::string strVoteSignal = request.params[1].get_str();
    std::string strVoteOutcome = request.params[2].get_str();

    vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);
    if (eVoteSignal == VOTE_SIGNAL_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER,
                           "Invalid vote signal. Please using one of the following: "
                           "(funding|valid|delete|endorsed)");
    }

    vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);
    if (eVoteOutcome == VOTE_OUTCOME_NONE) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'");
    }

    EnsureWalletIsUnlocked(pwallet);

    uint256 proTxHash = ParseHashV(request.params[3], "protxHash");
    CDeterministicMNList mnList;
    deterministicMNManager->GetListAtChainTip(mnList);
    auto dmn = mnList.GetValidMN(proTxHash);
    if (!dmn) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid or unknown proTxHash");
    }
    // Make sure the results are valid at least up to the most recent block
    // the user could have gotten from another RPC command prior to now
    pwallet->BlockUntilSyncedToCurrentChain();
    CKey key;
    {
        LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
        LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);

        if (!spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Private key for voting address %s not known by wallet", EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting))));
        }
    }

    std::map<uint256, CKey> votingKeys;
    votingKeys.emplace(proTxHash, key);

    return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);
},
    };
}

Span<const CRPCCommand> GetGovernanceWalletRPCCommands()
{
// clang-format off
static const CRPCCommand commands[] =
{ //  category              name                      actor (function)         argNames
//  --------------------- ------------------------  -----------------------  ----------
    { "governancewallet",               "gobject_vote_alias",     &gobject_vote_alias,      {"governanceHash","vote","voteOutome","protxHash"} },
    { "governancewallet",               "gobject_vote_many",      &gobject_vote_many,       {"governanceHash","vote","voteOutome"} },
    { "governancewallet",               "gobject_prepare",        &gobject_prepare,         {"parentHash","revision","time","dataHex","outputHash","outputIndex"} },

};
// clang-format on
    return MakeSpan(commands);
}
<|endoftext|>