<commit_before>/*
 *  qihdr.cpp
 *
 *  Created by Tobias Wood on 11/06/2015.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  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/.
 *
 */

#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>

#include "Types.h"
#include "Util.h"

using namespace std;

//******************************************************************************
// Arguments / Usage
//******************************************************************************
int print_all = true;
int print_size = false, print_spacing = false, print_origin = false, print_direction = false;

const string usage {
"Usage is: qihdr [options] input[s] \n\
\n\
By default, a summary of the header is printed. If options below are specified,\n\
only those parts of the header will be printed. Multiple files can be input,\n\
in which case the header info is written for each in order.\n\
\n\
Options:\n\
    --help, -h  : Print this message.\n\
    --size      : Print the image dimensions.\n\
    --spacing   : Print the image spacing.\n\
    --origin    : Print the origin.\n\
    --direction : Print the image direction.\n"
};

const struct option long_options[] = {
    {"help", no_argument, 0, 'h'},
    {"size", no_argument, 0, 's'},
    {"spacing", no_argument, 0, 'p'},
    {"origin", no_argument, 0, 'o'},
    {"direction", no_argument, 0, 'd'},
    {0, 0, 0, 0}
};
const char *short_options = "h";

//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
    int indexptr = 0, c;
    while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
        switch (c) {
            case 'h':
                cout << usage << endl;
                return EXIT_SUCCESS;
            case 's': print_size = true; print_all = false; break;
            case 'p': print_spacing = true; print_all = false; break;
            case 'o': print_origin = true; print_all = false; break;
            case 'd': print_direction = true; print_all = false; break;
            case '?': // getopt will print an error message
                return EXIT_FAILURE;
            default:
                cout << "Unhandled option " << string(1, c) << endl;
                return EXIT_FAILURE;
        }
    }

    while (optind < argc) {
        QI::ReadImageF::Pointer thisImg = QI::ReadImageF::New();
        if (print_all) cout << "Header for: " << string(argv[optind]) << endl;
        thisImg->SetFileName(argv[optind++]);
        thisImg->Update();
        if (print_all) cout << "Size:      "; if (print_all || print_size)      cout << thisImg->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
        if (print_all) cout << "Spacing:   "; if (print_all || print_spacing)   cout << thisImg->GetOutput()->GetSpacing() << endl;
        if (print_all) cout << "Origin:    "; if (print_all || print_origin)    cout << thisImg->GetOutput()->GetOrigin() << endl;
        if (print_all) cout << "Direction: "; if (print_all || print_direction) cout << thisImg->GetOutput()->GetDirection() << endl;
    }
    return EXIT_SUCCESS;
}
<commit_msg>Added a missing newline to make the direction legible.<commit_after>/*
 *  qihdr.cpp
 *
 *  Created by Tobias Wood on 11/06/2015.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  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/.
 *
 */

#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>

#include "Types.h"
#include "Util.h"

using namespace std;

//******************************************************************************
// Arguments / Usage
//******************************************************************************
int print_all = true;
int print_size = false, print_spacing = false, print_origin = false, print_direction = false;

const string usage {
"Usage is: qihdr [options] input[s] \n\
\n\
By default, a summary of the header is printed. If options below are specified,\n\
only those parts of the header will be printed. Multiple files can be input,\n\
in which case the header info is written for each in order.\n\
\n\
Options:\n\
    --help, -h  : Print this message.\n\
    --size      : Print the image dimensions.\n\
    --spacing   : Print the image spacing.\n\
    --origin    : Print the origin.\n\
    --direction : Print the image direction.\n"
};

const struct option long_options[] = {
    {"help", no_argument, 0, 'h'},
    {"size", no_argument, 0, 's'},
    {"spacing", no_argument, 0, 'p'},
    {"origin", no_argument, 0, 'o'},
    {"direction", no_argument, 0, 'd'},
    {0, 0, 0, 0}
};
const char *short_options = "h";

//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
    int indexptr = 0, c;
    while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
        switch (c) {
            case 'h':
                cout << usage << endl;
                return EXIT_SUCCESS;
            case 's': print_size = true; print_all = false; break;
            case 'p': print_spacing = true; print_all = false; break;
            case 'o': print_origin = true; print_all = false; break;
            case 'd': print_direction = true; print_all = false; break;
            case '?': // getopt will print an error message
                return EXIT_FAILURE;
            default:
                cout << "Unhandled option " << string(1, c) << endl;
                return EXIT_FAILURE;
        }
    }

    while (optind < argc) {
        QI::ReadImageF::Pointer thisImg = QI::ReadImageF::New();
        if (print_all) cout << "Header for: " << string(argv[optind]) << endl;
        thisImg->SetFileName(argv[optind++]);
        thisImg->Update();
        if (print_all) cout << "Size:      "; if (print_all || print_size)      cout << thisImg->GetOutput()->GetLargestPossibleRegion().GetSize() << endl;
        if (print_all) cout << "Spacing:   "; if (print_all || print_spacing)   cout << thisImg->GetOutput()->GetSpacing() << endl;
        if (print_all) cout << "Origin:    "; if (print_all || print_origin)    cout << thisImg->GetOutput()->GetOrigin() << endl;
        if (print_all) cout << "Direction: " << endl; if (print_all || print_direction) cout << thisImg->GetOutput()->GetDirection() << endl;
    }
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// Copyright (c) 1996-2013, Live Networks, Inc.  All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif

#include "liveMedia.hh"
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"

//RTPSink* videoSink;
UsageEnvironment* env;

// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;

// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;

static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
			   char const* streamName); // fwd

static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
  demux = newDemux;
  newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();

void startRTSP(int port){
//    pthread_t thread;
//    return pthread_create(&thread,NULL,eventLoop, NULL);
    boost::thread thread1(boost::bind(&eventLoop, port));
}

ServerMediaSession* sms;

EventTriggerId addFaceSubstreamTriggerId;

concurrent_queue<CubemapFace*> faceBuffer;

void addFaceSubstream0(void*) {

	CubemapFace* face;

	while (faceBuffer.try_pop(face))
	{
		H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);
		sms->addSubsession(subsession);
		std::cout << "added face " << face->index << std::endl;
	}
}

std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;

void addFaceSubstream()
{
	std::list<int> addedFaces;

	while (true)
	{
		boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
		//
		for (int i = 0; i < cubemap->count(); i++)
		{
			if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
			{
				faceBuffer.push(cubemap->getFace(i).get());
				addedFaces.push_back(cubemap->getFace(i)->index);
			}
		}
		if (!faceBuffer.empty())
		{
			env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
		}
		cubemap->newFaceCondition.wait(lock);
	}
}

void eventLoop(int port) {
  // Begin by setting up our usage environment:
  TaskScheduler* scheduler = BasicTaskScheduler::createNew();
  env = BasicUsageEnvironment::createNew(*scheduler);

  UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
  // To implement client access control to the RTSP server, do the following:
  authDB = new UserAuthenticationDatabase;
  authDB->addUserRecord("username1", "password1"); // replace these with real strings
  // Repeat the above with each <username>, <password> that you wish to allow
  // access to the server.
#endif

  // Create the RTSP server:
  RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
  if (rtspServer == NULL) {
    *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
    exit(1);
  }

  char const* descriptionString
    = "Session streamed by \"testOnDemandRTSPServer\"";

  // Set up each of the possible streams that can be served by the
  // RTSP server.  Each such stream is implemented using a
  // "ServerMediaSession" object, plus one or more
  // "ServerMediaSubsession" objects for each audio/video substream.

  OutPacketBuffer::maxSize = 4000000;

  // A H.264 video elementary stream:
  {
    char const* streamName = "h264ESVideoTest";

    sms = ServerMediaSession::createNew(*env, streamName, streamName,
				      descriptionString);

    //H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");

    //videoSink = subsession->createNewRTPSink(groupSock, 96);

    //sms->addSubsession(subsession1);

    rtspServer->addServerMediaSession(sms);

    announceStream(rtspServer, sms, streamName);
  }

  // Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
  // Try first with the default HTTP port (80), and then with the alternative HTTP
  // port numbers (8000 and 8080).

  /*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
    *env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
  } else {
    *env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
  }*/

    /*
    // Start the streaming:
    *env << "Beginning streaming...\n";
    startPlay();
    //play(NULL);
    usleep(5000000);
    printf("done play\n");
    */
  addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);

  boost::thread thread2(&addFaceSubstream);

  env->taskScheduler().doEventLoop(); // does not return

 // return 0; // only to prevent compiler warning
}

static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
			   char const* streamName) {
  char* url = rtspServer->rtspURL(sms);
  UsageEnvironment& env = rtspServer->envir();
  env << "Play this stream using the URL \"" << url << "\"\n";
  delete[] url;
}
<commit_msg>Multicast support for AlloServer. Still crashes.<commit_after>/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// Copyright (c) 1996-2013, Live Networks, Inc.  All rights reserved
// A test program that demonstrates how to stream - via unicast RTP
// - various kinds of file on demand, using a built-in RTSP server.
// main program
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif

#include "liveMedia.hh"
#include <GroupsockHelper.hh>
#define EventTime server_EventTime
#include "BasicUsageEnvironment.hh"
#undef EventTime
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "H264VideoOnDemandServerMediaSubsession.h"
#include "shared.h"
#include "config.h"
#include "RandomFramedSource.h"
#include "AlloShared/CubemapFace.h"
#include "AlloServer.h"
#include "concurrent_queue.h"
#include "CubemapFaceSource.h"

//RTPSink* videoSink;
UsageEnvironment* env;

// To make the second and subsequent client for each stream reuse the same
// input stream as the first client (rather than playing the file from the
// start for each client), change the following "False" to "True":
Boolean reuseFirstSource = True;

// To stream *only* MPEG-1 or 2 video "I" frames
// (e.g., to reduce network bandwidth),
// change the following "False" to "True":
Boolean iFramesOnly = False;

static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
			   char const* streamName); // fwd

static char newMatroskaDemuxWatchVariable;
static MatroskaFileServerDemux* demux;
static void onMatroskaDemuxCreation(MatroskaFileServerDemux* newDemux, void* /*clientData*/) {
  demux = newDemux;
  newMatroskaDemuxWatchVariable = 1;
}
void eventLoop(int port);
void addFaceSubstream();

void startRTSP(int port){
//    pthread_t thread;
//    return pthread_create(&thread,NULL,eventLoop, NULL);
    boost::thread thread1(boost::bind(&eventLoop, port));
}

ServerMediaSession* sms;

EventTriggerId addFaceSubstreamTriggerId;

concurrent_queue<CubemapFace*> faceBuffer;

struct in_addr destinationAddress;

static struct FaceStreamState
{
    RTPSink* sink;
    CubemapFace* face;
    FramedSource* source;
};

void afterPlaying(void* clientData)
{
    FaceStreamState* state = (FaceStreamState*)clientData;

    *env << "stopped streaming face " << state->face->index << "\n";

    state->sink->stopPlaying();
    Medium::close(state->source);
    // Note that this also closes the input file that this source read from.

    delete state;
}

const unsigned short rtpPortNum = 18888;
const unsigned char ttl = 255;

void addFaceSubstream0(void*) {

	CubemapFace* face;

	while (faceBuffer.try_pop(face))
	{
        FaceStreamState* state = new FaceStreamState;
        state->face = face;

        Port rtpPort(rtpPortNum + face->index);
        Groupsock rtpGroupsock(*env, destinationAddress, rtpPort, ttl);
        rtpGroupsock.multicastSendOnly(); // we're a SSM source

        // Create a 'H264 Video RTP' sink from the RTP 'groupsock':
        OutPacketBuffer::maxSize = 100000;
        state->sink = H264VideoRTPSink::createNew(*env, &rtpGroupsock, 96);

        ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink);

		//H264VideoOnDemandServerMediaSubsession *subsession = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, face);

        sms->addSubsession(subsession);

        state->source =  H264VideoStreamDiscreteFramer::createNew(*env, CubemapFaceSource::createNew(*env, face));
        state->sink->startPlaying(*state->source, afterPlaying, state);

		std::cout << "added face " << face->index << std::endl;
	}
}

std::vector<H264VideoOnDemandServerMediaSubsession*> faceSubstreams;

void addFaceSubstream()
{
	std::list<int> addedFaces;

	while (true)
	{
		boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(cubemap->mutex);
		//
		for (int i = 0; i < cubemap->count(); i++)
		{
			if (std::find(addedFaces.begin(), addedFaces.end(), cubemap->getFace(i)->index) == addedFaces.end())
			{
				faceBuffer.push(cubemap->getFace(i).get());
				addedFaces.push_back(cubemap->getFace(i)->index);
			}
		}
		if (!faceBuffer.empty())
		{
			env->taskScheduler().triggerEvent(addFaceSubstreamTriggerId, NULL);
		}
		cubemap->newFaceCondition.wait(lock);
	}
}

void eventLoop(int port) {
  // Begin by setting up our usage environment:
  TaskScheduler* scheduler = BasicTaskScheduler::createNew();
  env = BasicUsageEnvironment::createNew(*scheduler);

    // Create 'groupsocks' for RTP and RTCP:

    destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
    // Note: This is a multicast address.  If you wish instead to stream
    // using unicast, then you should use the "testOnDemandRTSPServer"
    // test program - not this test program - as a model.

    char str[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(destinationAddress.s_addr), str, INET_ADDRSTRLEN);
    printf("Multicast address: %s\n", str);

  UserAuthenticationDatabase* authDB = NULL;
#ifdef ACCESS_CONTROL
  // To implement client access control to the RTSP server, do the following:
  authDB = new UserAuthenticationDatabase;
  authDB->addUserRecord("username1", "password1"); // replace these with real strings
  // Repeat the above with each <username>, <password> that you wish to allow
  // access to the server.
#endif

  // Create the RTSP server:
  RTSPServer* rtspServer = RTSPServer::createNew(*env, port, authDB);
//RTSPServer* rtspServer = RTSPServer::createNew(*env, 8555, authDB);
  if (rtspServer == NULL) {
    *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
    exit(1);
  }

  char const* descriptionString
    = "Session streamed by \"testOnDemandRTSPServer\"";

  // Set up each of the possible streams that can be served by the
  // RTSP server.  Each such stream is implemented using a
  // "ServerMediaSession" object, plus one or more
  // "ServerMediaSubsession" objects for each audio/video substream.

  OutPacketBuffer::maxSize = 4000000;

  // A H.264 video elementary stream:
  {
    char const* streamName = "h264ESVideoTest";

    sms = ServerMediaSession::createNew(*env, streamName, streamName,
				      descriptionString, True);

    //H264VideoOnDemandServerMediaSubsession *subsession2 = H264VideoOnDemandServerMediaSubsession::createNew(*env, reuseFirstSource, "two");

    //videoSink = subsession->createNewRTPSink(groupSock, 96);

    //sms->addSubsession(subsession1);

    rtspServer->addServerMediaSession(sms);

    announceStream(rtspServer, sms, streamName);
  }

  // Also, attempt to create a HTTP server for RTSP-over-HTTP tunneling.
  // Try first with the default HTTP port (80), and then with the alternative HTTP
  // port numbers (8000 and 8080).

  /*if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) {
    *env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n";
  } else {
    *env << "\n(RTSP-over-HTTP tunneling is not available.)\n";
  }*/

    /*
    // Start the streaming:
    *env << "Beginning streaming...\n";
    startPlay();
    //play(NULL);
    usleep(5000000);
    printf("done play\n");
    */
  addFaceSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstream0);

  boost::thread thread2(&addFaceSubstream);

  env->taskScheduler().doEventLoop(); // does not return

 // return 0; // only to prevent compiler warning
}

static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
			   char const* streamName) {
  char* url = rtspServer->rtspURL(sms);
  UsageEnvironment& env = rtspServer->envir();
  env << "Play this stream using the URL \"" << url << "\"\n";
  delete[] url;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppapi_webplugin_impl.h"

#include <cmath>

#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/plugins/ppapi/message_channel.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_loader_impl.h"
#include "webkit/plugins/ppapi/var.h"

using WebKit::WebCanvas;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;
using WebKit::WebView;

namespace webkit {
namespace ppapi {

struct WebPluginImpl::InitData {
  scoped_refptr<PluginModule> module;
  base::WeakPtr<PluginDelegate> delegate;
  std::vector<std::string> arg_names;
  std::vector<std::string> arg_values;
  GURL url;
};

WebPluginImpl::WebPluginImpl(
    PluginModule* plugin_module,
    const WebPluginParams& params,
    const base::WeakPtr<PluginDelegate>& plugin_delegate)
    : init_data_(new InitData()),
      full_frame_(params.loadManually) {
  DCHECK(plugin_module);
  init_data_->module = plugin_module;
  init_data_->delegate = plugin_delegate;
  for (size_t i = 0; i < params.attributeNames.size(); ++i) {
    init_data_->arg_names.push_back(params.attributeNames[i].utf8());
    init_data_->arg_values.push_back(params.attributeValues[i].utf8());
  }
  init_data_->url = params.url;
}

WebPluginImpl::~WebPluginImpl() {
}

bool WebPluginImpl::initialize(WebPluginContainer* container) {
  // The plugin delegate may have gone away.
  if (!init_data_->delegate)
    return false;

  instance_ = init_data_->module->CreateInstance(init_data_->delegate);
  if (!instance_)
    return false;

  bool success = instance_->Initialize(container,
                                       init_data_->arg_names,
                                       init_data_->arg_values,
                                       init_data_->url,
                                       full_frame_);
  if (!success) {
    instance_->Delete();
    instance_ = NULL;
    return false;
  }

  init_data_.reset();
  return true;
}

void WebPluginImpl::destroy() {
  if (instance_) {
    instance_->Delete();
    instance_ = NULL;
  }

  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

NPObject* WebPluginImpl::scriptableObject() {
  scoped_refptr<ObjectVar> object(
      ObjectVar::FromPPVar(instance_->GetInstanceObject()));
  // If there's an InstanceObject, tell the Instance's MessageChannel to pass
  // any non-postMessage calls to it.
  if (object) {
    instance_->message_channel().SetPassthroughObject(object->np_object());
  }
  NPObject* message_channel_np_object(instance_->message_channel().np_object());
  // The object is expected to be retained before it is returned.
  WebKit::WebBindings::retainObject(message_channel_np_object);
  return message_channel_np_object;
}

bool WebPluginImpl::getFormValue(WebString* value) {
  return false;
}

void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& rect) {
  if (!instance_->IsFullscreenOrPending())
    instance_->Paint(canvas, plugin_rect_, rect);
}

void WebPluginImpl::updateGeometry(
    const WebRect& window_rect,
    const WebRect& clip_rect,
    const WebVector<WebRect>& cut_outs_rects,
    bool is_visible) {
  plugin_rect_ = window_rect;
  if (!instance_->IsFullscreenOrPending())
    instance_->ViewChanged(plugin_rect_, clip_rect);
}

void WebPluginImpl::updateFocus(bool focused) {
  instance_->SetWebKitFocus(focused);
}

void WebPluginImpl::updateVisibility(bool visible) {
}

bool WebPluginImpl::acceptsInputEvents() {
  return true;
}

bool WebPluginImpl::handleInputEvent(const WebKit::WebInputEvent& event,
                                     WebKit::WebCursorInfo& cursor_info) {
  if (instance_->IsFullscreenOrPending())
    return false;
  return instance_->HandleInputEvent(event, &cursor_info);
}

void WebPluginImpl::didReceiveResponse(
    const WebKit::WebURLResponse& response) {
  DCHECK(!document_loader_);

  document_loader_ = new PPB_URLLoader_Impl(instance_, true);
  document_loader_->didReceiveResponse(NULL, response);

  if (!instance_->HandleDocumentLoad(document_loader_))
    document_loader_ = NULL;
}

void WebPluginImpl::didReceiveData(const char* data, int data_length) {
  if (document_loader_)
    document_loader_->didReceiveData(NULL, data, data_length, data_length);
}

void WebPluginImpl::didFinishLoading() {
  if (document_loader_) {
    document_loader_->didFinishLoading(NULL, 0);
    document_loader_ = NULL;
  }
}

void WebPluginImpl::didFailLoading(const WebKit::WebURLError& error) {
  if (document_loader_) {
    document_loader_->didFail(NULL, error);
    document_loader_ = NULL;
  }
}

void WebPluginImpl::didFinishLoadingFrameRequest(const WebKit::WebURL& url,
                                                 void* notify_data) {
}

void WebPluginImpl::didFailLoadingFrameRequest(
    const WebKit::WebURL& url,
    void* notify_data,
    const WebKit::WebURLError& error) {
}

bool WebPluginImpl::hasSelection() const {
  return !selectionAsText().isEmpty();
}

WebString WebPluginImpl::selectionAsText() const {
  return instance_->GetSelectedText(false);
}

WebString WebPluginImpl::selectionAsMarkup() const {
  return instance_->GetSelectedText(true);
}

WebURL WebPluginImpl::linkAtPosition(const WebPoint& position) const {
  return GURL(instance_->GetLinkAtPosition(position));
}

void WebPluginImpl::setZoomLevel(double level, bool text_only) {
  instance_->Zoom(WebView::zoomLevelToZoomFactor(level), text_only);
}

bool WebPluginImpl::startFind(const WebKit::WebString& search_text,
                              bool case_sensitive,
                              int identifier) {
  return instance_->StartFind(search_text, case_sensitive, identifier);
}

void WebPluginImpl::selectFindResult(bool forward) {
  instance_->SelectFindResult(forward);
}

void WebPluginImpl::stopFind() {
  instance_->StopFind();
}

bool WebPluginImpl::supportsPaginatedPrint() {
  return instance_->SupportsPrintInterface();
}

int WebPluginImpl::printBegin(const WebKit::WebRect& printable_area,
                              int printer_dpi) {
  return instance_->PrintBegin(printable_area, printer_dpi);
}

bool WebPluginImpl::printPage(int page_number,
                              WebKit::WebCanvas* canvas) {
  return instance_->PrintPage(page_number, canvas);
}

void WebPluginImpl::printEnd() {
  return instance_->PrintEnd();
}

}  // namespace ppapi
}  // namespace webkit
<commit_msg>Fix re-entrancy case in WebPluginImpl::scriptableObject.<commit_after>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppapi_webplugin_impl.h"

#include <cmath>

#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBindings.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/plugins/ppapi/message_channel.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_url_loader_impl.h"
#include "webkit/plugins/ppapi/var.h"

using WebKit::WebCanvas;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebVector;
using WebKit::WebView;

namespace webkit {
namespace ppapi {

struct WebPluginImpl::InitData {
  scoped_refptr<PluginModule> module;
  base::WeakPtr<PluginDelegate> delegate;
  std::vector<std::string> arg_names;
  std::vector<std::string> arg_values;
  GURL url;
};

WebPluginImpl::WebPluginImpl(
    PluginModule* plugin_module,
    const WebPluginParams& params,
    const base::WeakPtr<PluginDelegate>& plugin_delegate)
    : init_data_(new InitData()),
      full_frame_(params.loadManually) {
  DCHECK(plugin_module);
  init_data_->module = plugin_module;
  init_data_->delegate = plugin_delegate;
  for (size_t i = 0; i < params.attributeNames.size(); ++i) {
    init_data_->arg_names.push_back(params.attributeNames[i].utf8());
    init_data_->arg_values.push_back(params.attributeValues[i].utf8());
  }
  init_data_->url = params.url;
}

WebPluginImpl::~WebPluginImpl() {
}

bool WebPluginImpl::initialize(WebPluginContainer* container) {
  // The plugin delegate may have gone away.
  if (!init_data_->delegate)
    return false;

  instance_ = init_data_->module->CreateInstance(init_data_->delegate);
  if (!instance_)
    return false;

  bool success = instance_->Initialize(container,
                                       init_data_->arg_names,
                                       init_data_->arg_values,
                                       init_data_->url,
                                       full_frame_);
  if (!success) {
    instance_->Delete();
    instance_ = NULL;
    return false;
  }

  init_data_.reset();
  return true;
}

void WebPluginImpl::destroy() {
  if (instance_) {
    instance_->Delete();
    instance_ = NULL;
  }

  MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

NPObject* WebPluginImpl::scriptableObject() {
  scoped_refptr<ObjectVar> object(
      ObjectVar::FromPPVar(instance_->GetInstanceObject()));
  // GetInstanceObject talked to the plugin which may have removed the instance
  // from the DOM, in which case instance_ would be NULL now.
  if (!instance_)
    return NULL;

  // If there's an InstanceObject, tell the Instance's MessageChannel to pass
  // any non-postMessage calls to it.
  if (object) {
    instance_->message_channel().SetPassthroughObject(object->np_object());
  }
  NPObject* message_channel_np_object(instance_->message_channel().np_object());
  // The object is expected to be retained before it is returned.
  WebKit::WebBindings::retainObject(message_channel_np_object);
  return message_channel_np_object;
}

bool WebPluginImpl::getFormValue(WebString* value) {
  return false;
}

void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& rect) {
  if (!instance_->IsFullscreenOrPending())
    instance_->Paint(canvas, plugin_rect_, rect);
}

void WebPluginImpl::updateGeometry(
    const WebRect& window_rect,
    const WebRect& clip_rect,
    const WebVector<WebRect>& cut_outs_rects,
    bool is_visible) {
  plugin_rect_ = window_rect;
  if (!instance_->IsFullscreenOrPending())
    instance_->ViewChanged(plugin_rect_, clip_rect);
}

void WebPluginImpl::updateFocus(bool focused) {
  instance_->SetWebKitFocus(focused);
}

void WebPluginImpl::updateVisibility(bool visible) {
}

bool WebPluginImpl::acceptsInputEvents() {
  return true;
}

bool WebPluginImpl::handleInputEvent(const WebKit::WebInputEvent& event,
                                     WebKit::WebCursorInfo& cursor_info) {
  if (instance_->IsFullscreenOrPending())
    return false;
  return instance_->HandleInputEvent(event, &cursor_info);
}

void WebPluginImpl::didReceiveResponse(
    const WebKit::WebURLResponse& response) {
  DCHECK(!document_loader_);

  document_loader_ = new PPB_URLLoader_Impl(instance_, true);
  document_loader_->didReceiveResponse(NULL, response);

  if (!instance_->HandleDocumentLoad(document_loader_))
    document_loader_ = NULL;
}

void WebPluginImpl::didReceiveData(const char* data, int data_length) {
  if (document_loader_)
    document_loader_->didReceiveData(NULL, data, data_length, data_length);
}

void WebPluginImpl::didFinishLoading() {
  if (document_loader_) {
    document_loader_->didFinishLoading(NULL, 0);
    document_loader_ = NULL;
  }
}

void WebPluginImpl::didFailLoading(const WebKit::WebURLError& error) {
  if (document_loader_) {
    document_loader_->didFail(NULL, error);
    document_loader_ = NULL;
  }
}

void WebPluginImpl::didFinishLoadingFrameRequest(const WebKit::WebURL& url,
                                                 void* notify_data) {
}

void WebPluginImpl::didFailLoadingFrameRequest(
    const WebKit::WebURL& url,
    void* notify_data,
    const WebKit::WebURLError& error) {
}

bool WebPluginImpl::hasSelection() const {
  return !selectionAsText().isEmpty();
}

WebString WebPluginImpl::selectionAsText() const {
  return instance_->GetSelectedText(false);
}

WebString WebPluginImpl::selectionAsMarkup() const {
  return instance_->GetSelectedText(true);
}

WebURL WebPluginImpl::linkAtPosition(const WebPoint& position) const {
  return GURL(instance_->GetLinkAtPosition(position));
}

void WebPluginImpl::setZoomLevel(double level, bool text_only) {
  instance_->Zoom(WebView::zoomLevelToZoomFactor(level), text_only);
}

bool WebPluginImpl::startFind(const WebKit::WebString& search_text,
                              bool case_sensitive,
                              int identifier) {
  return instance_->StartFind(search_text, case_sensitive, identifier);
}

void WebPluginImpl::selectFindResult(bool forward) {
  instance_->SelectFindResult(forward);
}

void WebPluginImpl::stopFind() {
  instance_->StopFind();
}

bool WebPluginImpl::supportsPaginatedPrint() {
  return instance_->SupportsPrintInterface();
}

int WebPluginImpl::printBegin(const WebKit::WebRect& printable_area,
                              int printer_dpi) {
  return instance_->PrintBegin(printable_area, printer_dpi);
}

bool WebPluginImpl::printPage(int page_number,
                              WebKit::WebCanvas* canvas) {
  return instance_->PrintPage(page_number, canvas);
}

void WebPluginImpl::printEnd() {
  return instance_->PrintEnd();
}

}  // namespace ppapi
}  // namespace webkit
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *  ---
 *
 *  The Verilog frontend.
 *
 *  This frontend is using the AST frontend library (see frontends/ast/).
 *  Thus this frontend does not generate RTLIL code directly but creates an
 *  AST directly from the Verilog parse tree and then passes this AST to
 *  the AST frontend library.
 *
 */

#include "verilog_frontend.h"
#include "kernel/register.h"
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include <sstream>
#include <stdarg.h>
#include <assert.h>

using namespace VERILOG_FRONTEND;

// use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL

static std::vector<std::string> verilog_defaults;
static std::list<std::vector<std::string>> verilog_defaults_stack;

struct VerilogFrontend : public Frontend {
	VerilogFrontend() : Frontend("verilog", "read modules from verilog file") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    read_verilog [filename]\n");
		log("\n");
		log("Load modules from a verilog file to the current design. A large subset of\n");
		log("Verilog-2005 is supported.\n");
		log("\n");
		log("    -dump_ast1\n");
		log("        dump abstract syntax tree (before simplification)\n");
		log("\n");
		log("    -dump_ast2\n");
		log("        dump abstract syntax tree (after simplification)\n");
		log("\n");
		log("    -dump_vlog\n");
		log("        dump ast as verilog code (after simplification)\n");
		log("\n");
		log("    -yydebug\n");
		log("        enable parser debug output\n");
		log("\n");
		log("    -nolatches\n");
		log("        usually latches are synthesized into logic loops\n");
		log("        this option prohibits this and sets the output to 'x'\n");
		log("        in what would be the latches hold condition\n");
		log("\n");
		log("        this behavior can also be achieved by setting the\n");
		log("        'nolatches' attribute on the respective module or\n");
		log("        always block.\n");
		log("\n");
		log("    -nomem2reg\n");
		log("        under certain conditions memories are converted to registers\n");
		log("        early during simplification to ensure correct handling of\n");
		log("        complex corner cases. this option disables this behavior.\n");
		log("\n");
		log("        this can also be achieved by setting the 'nomem2reg'\n");
		log("        attribute on the respective module or register.\n");
		log("\n");
		log("    -mem2reg\n");
		log("        always convert memories to registers. this can also be\n");
		log("        achieved by setting the 'mem2reg' attribute on the respective\n");
		log("        module or register.\n");
		log("\n");
		log("    -ppdump\n");
		log("        dump verilog code after pre-processor\n");
		log("\n");
		log("    -nopp\n");
		log("        do not run the pre-processor\n");
		log("\n");
		log("    -lib\n");
		log("        only create empty blackbox modules\n");
		log("\n");
		log("    -noopt\n");
		log("        don't perform basic optimizations (such as const folding) in the\n");
		log("        high-level front-end.\n");
		log("\n");
		log("    -icells\n");
		log("        interpret cell types starting with '$' as internal cell types\n");
		log("\n");
		log("    -ignore_redef\n");
		log("        ignore re-definitions of modules. (the default behavior is to\n");
		log("        create an error message.)\n");
		log("\n");
		log("    -Dname[=definition]\n");
		log("        define the preprocessor symbol 'name' and set its optional value\n");
		log("        'definition'\n");
		log("\n");
		log("    -Idir\n");
		log("        add 'dir' to the directories which are used when searching include\n");
		log("        files\n");
		log("\n");
		log("The command 'verilog_defaults' can be used to register default options for\n");
		log("subsequent calls to 'read_verilog'.\n");
		log("\n");
	}
	virtual void execute(FILE *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
	{
		bool flag_dump_ast1 = false;
		bool flag_dump_ast2 = false;
		bool flag_dump_vlog = false;
		bool flag_nolatches = false;
		bool flag_nomem2reg = false;
		bool flag_mem2reg = false;
		bool flag_ppdump = false;
		bool flag_nopp = false;
		bool flag_lib = false;
		bool flag_noopt = false;
		bool flag_icells = false;
		bool flag_ignore_redef = false;
		std::map<std::string, std::string> defines_map;
		std::list<std::string> include_dirs;
		frontend_verilog_yydebug = false;

		log_header("Executing Verilog-2005 frontend.\n");

		args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end());

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			std::string arg = args[argidx];
			if (arg == "-dump_ast1") {
				flag_dump_ast1 = true;
				continue;
			}
			if (arg == "-dump_ast2") {
				flag_dump_ast2 = true;
				continue;
			}
			if (arg == "-dump_vlog") {
				flag_dump_vlog = true;
				continue;
			}
			if (arg == "-yydebug") {
				frontend_verilog_yydebug = true;
				continue;
			}
			if (arg == "-nolatches") {
				flag_nolatches = true;
				continue;
			}
			if (arg == "-nomem2reg") {
				flag_nomem2reg = true;
				continue;
			}
			if (arg == "-mem2reg") {
				flag_mem2reg = true;
				continue;
			}
			if (arg == "-ppdump") {
				flag_ppdump = true;
				continue;
			}
			if (arg == "-nopp") {
				flag_nopp = true;
				continue;
			}
			if (arg == "-lib") {
				flag_lib = true;
				continue;
			}
			if (arg == "-noopt") {
				flag_noopt = true;
				continue;
			}
			if (arg == "-icells") {
				flag_icells = true;
				continue;
			}
			if (arg == "-ignore_redef") {
				flag_ignore_redef = true;
				continue;
			}
			if (arg == "-D" && argidx+1 < args.size()) {
				std::string name = args[++argidx], value;
				size_t equal = name.find('=', 2);
				if (equal != std::string::npos) {
					value = arg.substr(equal+1);
					name = arg.substr(0, equal);
				}
				defines_map[name] = value;
				continue;
			}
			if (arg.compare(0, 2, "-D") == 0) {
				size_t equal = arg.find('=', 2);
				std::string name = arg.substr(2, equal-2);
				std::string value;
				if (equal != std::string::npos)
					value = arg.substr(equal+1);
				defines_map[name] = value;
				continue;
			}
			if (arg == "-I" && argidx+1 < args.size()) {
				include_dirs.push_back(args[++argidx]);
				continue;
			}
			if (arg.compare(0, 2, "-I") == 0) {
				include_dirs.push_back(arg.substr(2));
				continue;
			}
			break;
		}
		extra_args(f, filename, args, argidx);

		log("Parsing Verilog input from `%s' to AST representation.\n", filename.c_str());

		AST::current_filename = filename;
		AST::set_line_num = &frontend_verilog_yyset_lineno;
		AST::get_line_num = &frontend_verilog_yyget_lineno;

		current_ast = new AST::AstNode(AST::AST_DESIGN);

		FILE *fp = f;
		std::string code_after_preproc;

		if (!flag_nopp) {
			code_after_preproc = frontend_verilog_preproc(f, filename, defines_map, include_dirs);
			if (flag_ppdump)
				log("-- Verilog code after preprocessor --\n%s-- END OF DUMP --\n", code_after_preproc.c_str());
			fp = fmemopen((void*)code_after_preproc.c_str(), code_after_preproc.size(), "r");
		}

		frontend_verilog_yyset_lineno(1);
		frontend_verilog_yyrestart(fp);
		frontend_verilog_yyparse();
		frontend_verilog_yylex_destroy();

		AST::process(design, current_ast, flag_dump_ast1, flag_dump_ast2, flag_dump_vlog, flag_nolatches, flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_ignore_redef);

		if (!flag_nopp)
			fclose(fp);

		delete current_ast;
		current_ast = NULL;

		log("Successfully finished Verilog frontend.\n");
	}
} VerilogFrontend;

// the yyerror function used by bison to report parser errors
void frontend_verilog_yyerror(char const *fmt, ...)
{
	va_list ap;
	char buffer[1024];
	char *p = buffer;
	p += snprintf(p, buffer + sizeof(buffer) - p, "Parser error in line %s:%d: ",
			AST::current_filename.c_str(), frontend_verilog_yyget_lineno());
	va_start(ap, fmt);
	p += vsnprintf(p, buffer + sizeof(buffer) - p, fmt, ap);
	va_end(ap);
	p += snprintf(p, buffer + sizeof(buffer) - p, "\n");
	log_error("%s", buffer);
	exit(1);
}

struct VerilogDefaults : public Pass {
	VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    verilog_defaults -add [options]\n");
		log("\n");
		log("Add the sepcified options to the list of default options to read_verilog.\n");
		log("\n");
		log("\n");
		log("    verilog_defaults -clear");
		log("\n");
		log("Clear the list of verilog default options.\n");
		log("\n");
		log("\n");
		log("    verilog_defaults -push");
		log("    verilog_defaults -pop");
		log("\n");
		log("Push or pop the list of default options to a stack. Note that -push does\n");
		log("not imply -clear.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design*)
	{
		if (args.size() == 0)
			cmd_error(args, 1, "Missing argument.");

		if (args[1] == "-add") {
			verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end());
			return;
		}

		if (args.size() != 2)
			cmd_error(args, 2, "Extra argument.");

		if (args[1] == "-clear") {
			verilog_defaults.clear();
			return;
		}

		if (args[1] == "-push") {
			verilog_defaults_stack.push_back(verilog_defaults);
			return;
		}

		if (args[1] == "-pop") {
			if (verilog_defaults_stack.empty()) {
				verilog_defaults.clear();
			} else {
				verilog_defaults.swap(verilog_defaults_stack.back());
				verilog_defaults_stack.pop_back();
			}
			return;
		}
	}
} VerilogDefaults;

<commit_msg>Added read_verilog -setattr<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *  ---
 *
 *  The Verilog frontend.
 *
 *  This frontend is using the AST frontend library (see frontends/ast/).
 *  Thus this frontend does not generate RTLIL code directly but creates an
 *  AST directly from the Verilog parse tree and then passes this AST to
 *  the AST frontend library.
 *
 */

#include "verilog_frontend.h"
#include "kernel/register.h"
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include <sstream>
#include <stdarg.h>
#include <assert.h>

using namespace VERILOG_FRONTEND;

// use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL

static std::vector<std::string> verilog_defaults;
static std::list<std::vector<std::string>> verilog_defaults_stack;

struct VerilogFrontend : public Frontend {
	VerilogFrontend() : Frontend("verilog", "read modules from verilog file") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    read_verilog [filename]\n");
		log("\n");
		log("Load modules from a verilog file to the current design. A large subset of\n");
		log("Verilog-2005 is supported.\n");
		log("\n");
		log("    -dump_ast1\n");
		log("        dump abstract syntax tree (before simplification)\n");
		log("\n");
		log("    -dump_ast2\n");
		log("        dump abstract syntax tree (after simplification)\n");
		log("\n");
		log("    -dump_vlog\n");
		log("        dump ast as verilog code (after simplification)\n");
		log("\n");
		log("    -yydebug\n");
		log("        enable parser debug output\n");
		log("\n");
		log("    -nolatches\n");
		log("        usually latches are synthesized into logic loops\n");
		log("        this option prohibits this and sets the output to 'x'\n");
		log("        in what would be the latches hold condition\n");
		log("\n");
		log("        this behavior can also be achieved by setting the\n");
		log("        'nolatches' attribute on the respective module or\n");
		log("        always block.\n");
		log("\n");
		log("    -nomem2reg\n");
		log("        under certain conditions memories are converted to registers\n");
		log("        early during simplification to ensure correct handling of\n");
		log("        complex corner cases. this option disables this behavior.\n");
		log("\n");
		log("        this can also be achieved by setting the 'nomem2reg'\n");
		log("        attribute on the respective module or register.\n");
		log("\n");
		log("    -mem2reg\n");
		log("        always convert memories to registers. this can also be\n");
		log("        achieved by setting the 'mem2reg' attribute on the respective\n");
		log("        module or register.\n");
		log("\n");
		log("    -ppdump\n");
		log("        dump verilog code after pre-processor\n");
		log("\n");
		log("    -nopp\n");
		log("        do not run the pre-processor\n");
		log("\n");
		log("    -lib\n");
		log("        only create empty blackbox modules\n");
		log("\n");
		log("    -noopt\n");
		log("        don't perform basic optimizations (such as const folding) in the\n");
		log("        high-level front-end.\n");
		log("\n");
		log("    -icells\n");
		log("        interpret cell types starting with '$' as internal cell types\n");
		log("\n");
		log("    -ignore_redef\n");
		log("        ignore re-definitions of modules. (the default behavior is to\n");
		log("        create an error message.)\n");
		log("\n");
		log("    -setattr <attribute_name>\n");
		log("        set the specified attribute (to the value 1) on all loaded modules\n");
		log("\n");
		log("    -Dname[=definition]\n");
		log("        define the preprocessor symbol 'name' and set its optional value\n");
		log("        'definition'\n");
		log("\n");
		log("    -Idir\n");
		log("        add 'dir' to the directories which are used when searching include\n");
		log("        files\n");
		log("\n");
		log("The command 'verilog_defaults' can be used to register default options for\n");
		log("subsequent calls to 'read_verilog'.\n");
		log("\n");
	}
	virtual void execute(FILE *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
	{
		bool flag_dump_ast1 = false;
		bool flag_dump_ast2 = false;
		bool flag_dump_vlog = false;
		bool flag_nolatches = false;
		bool flag_nomem2reg = false;
		bool flag_mem2reg = false;
		bool flag_ppdump = false;
		bool flag_nopp = false;
		bool flag_lib = false;
		bool flag_noopt = false;
		bool flag_icells = false;
		bool flag_ignore_redef = false;
		std::map<std::string, std::string> defines_map;
		std::list<std::string> include_dirs;
		std::list<std::string> attributes;
		frontend_verilog_yydebug = false;

		log_header("Executing Verilog-2005 frontend.\n");

		args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end());

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			std::string arg = args[argidx];
			if (arg == "-dump_ast1") {
				flag_dump_ast1 = true;
				continue;
			}
			if (arg == "-dump_ast2") {
				flag_dump_ast2 = true;
				continue;
			}
			if (arg == "-dump_vlog") {
				flag_dump_vlog = true;
				continue;
			}
			if (arg == "-yydebug") {
				frontend_verilog_yydebug = true;
				continue;
			}
			if (arg == "-nolatches") {
				flag_nolatches = true;
				continue;
			}
			if (arg == "-nomem2reg") {
				flag_nomem2reg = true;
				continue;
			}
			if (arg == "-mem2reg") {
				flag_mem2reg = true;
				continue;
			}
			if (arg == "-ppdump") {
				flag_ppdump = true;
				continue;
			}
			if (arg == "-nopp") {
				flag_nopp = true;
				continue;
			}
			if (arg == "-lib") {
				flag_lib = true;
				continue;
			}
			if (arg == "-noopt") {
				flag_noopt = true;
				continue;
			}
			if (arg == "-icells") {
				flag_icells = true;
				continue;
			}
			if (arg == "-ignore_redef") {
				flag_ignore_redef = true;
				continue;
			}
			if (arg == "-setattr" && argidx+1 < args.size()) {
				attributes.push_back(RTLIL::escape_id(args[++argidx]));
				continue;
			}
			if (arg == "-D" && argidx+1 < args.size()) {
				std::string name = args[++argidx], value;
				size_t equal = name.find('=', 2);
				if (equal != std::string::npos) {
					value = arg.substr(equal+1);
					name = arg.substr(0, equal);
				}
				defines_map[name] = value;
				continue;
			}
			if (arg.compare(0, 2, "-D") == 0) {
				size_t equal = arg.find('=', 2);
				std::string name = arg.substr(2, equal-2);
				std::string value;
				if (equal != std::string::npos)
					value = arg.substr(equal+1);
				defines_map[name] = value;
				continue;
			}
			if (arg == "-I" && argidx+1 < args.size()) {
				include_dirs.push_back(args[++argidx]);
				continue;
			}
			if (arg.compare(0, 2, "-I") == 0) {
				include_dirs.push_back(arg.substr(2));
				continue;
			}
			break;
		}
		extra_args(f, filename, args, argidx);

		log("Parsing Verilog input from `%s' to AST representation.\n", filename.c_str());

		AST::current_filename = filename;
		AST::set_line_num = &frontend_verilog_yyset_lineno;
		AST::get_line_num = &frontend_verilog_yyget_lineno;

		current_ast = new AST::AstNode(AST::AST_DESIGN);

		FILE *fp = f;
		std::string code_after_preproc;

		if (!flag_nopp) {
			code_after_preproc = frontend_verilog_preproc(f, filename, defines_map, include_dirs);
			if (flag_ppdump)
				log("-- Verilog code after preprocessor --\n%s-- END OF DUMP --\n", code_after_preproc.c_str());
			fp = fmemopen((void*)code_after_preproc.c_str(), code_after_preproc.size(), "r");
		}

		frontend_verilog_yyset_lineno(1);
		frontend_verilog_yyrestart(fp);
		frontend_verilog_yyparse();
		frontend_verilog_yylex_destroy();

		for (auto &child : current_ast->children) {
			log_assert(child->type == AST::AST_MODULE);
			for (auto &attr : attributes)
				if (child->attributes.count(attr) == 0)
					child->attributes[attr] = AST::AstNode::mkconst_int(1, false);
		}

		AST::process(design, current_ast, flag_dump_ast1, flag_dump_ast2, flag_dump_vlog, flag_nolatches, flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_ignore_redef);

		if (!flag_nopp)
			fclose(fp);

		delete current_ast;
		current_ast = NULL;

		log("Successfully finished Verilog frontend.\n");
	}
} VerilogFrontend;

// the yyerror function used by bison to report parser errors
void frontend_verilog_yyerror(char const *fmt, ...)
{
	va_list ap;
	char buffer[1024];
	char *p = buffer;
	p += snprintf(p, buffer + sizeof(buffer) - p, "Parser error in line %s:%d: ",
			AST::current_filename.c_str(), frontend_verilog_yyget_lineno());
	va_start(ap, fmt);
	p += vsnprintf(p, buffer + sizeof(buffer) - p, fmt, ap);
	va_end(ap);
	p += snprintf(p, buffer + sizeof(buffer) - p, "\n");
	log_error("%s", buffer);
	exit(1);
}

struct VerilogDefaults : public Pass {
	VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    verilog_defaults -add [options]\n");
		log("\n");
		log("Add the sepcified options to the list of default options to read_verilog.\n");
		log("\n");
		log("\n");
		log("    verilog_defaults -clear");
		log("\n");
		log("Clear the list of verilog default options.\n");
		log("\n");
		log("\n");
		log("    verilog_defaults -push");
		log("    verilog_defaults -pop");
		log("\n");
		log("Push or pop the list of default options to a stack. Note that -push does\n");
		log("not imply -clear.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design*)
	{
		if (args.size() == 0)
			cmd_error(args, 1, "Missing argument.");

		if (args[1] == "-add") {
			verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end());
			return;
		}

		if (args.size() != 2)
			cmd_error(args, 2, "Extra argument.");

		if (args[1] == "-clear") {
			verilog_defaults.clear();
			return;
		}

		if (args[1] == "-push") {
			verilog_defaults_stack.push_back(verilog_defaults);
			return;
		}

		if (args[1] == "-pop") {
			if (verilog_defaults_stack.empty()) {
				verilog_defaults.clear();
			} else {
				verilog_defaults.swap(verilog_defaults_stack.back());
				verilog_defaults_stack.pop_back();
			}
			return;
		}
	}
} VerilogDefaults;

<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

struct Numero {
	int cifras[30];
	int ncifras;
};

int main() {
	int tam;
	string s;
	Numero N;
	cin >> s;
	int tam = s.size();
	for (int i = 0; i < tam; ++i) {
		char digito = s[i];
	}
}<commit_msg>the structure of proyect is completed<commit_after>#include <iostream>

using namespace std;

struct Numero {
	int cifras[30];
	int ncifras;
};

void escribir_numero(const Numero& N) {
	for (int i = N.ncifras - 1; i >= 0; --i) {
		cout << N.cifras[i];
	}
}

void leer_numero(Numero& N) {
	int tam;
	string s;
	cin >> s;
	int tam = s.size();
	for (int i = 0; i < tam; ++i) {
		char digito = s[i];
		N.cifras[tam - 1 - i] = int(digito) - int('0');
	}
	N.ncifras = tam;
}

int main() {
	Numero N;
	leer_numero(N);
	escribir_numero(N);
	cout << endl;
}<|endoftext|>


<commit_before>
#include <Onsang/utility.hpp>
#include <Onsang/detail/gr_ceformat.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/asio.hpp>
#include <Onsang/Net/CmdStreamer.hpp>

#include <Hord/Error.hpp>
#include <Hord/ErrorCode.hpp>

#include <duct/IO/arithmetic.hpp>

#include <cassert>
#include <mutex>
#include <iomanip>
#include <iostream>

namespace Onsang {
namespace Net {

// class CmdStreamer implementation

#define ONSANG_SCOPE_CLASS Net::CmdStreamer

namespace {

enum : unsigned {
	// uint32 size
	// uint32 type
	msg_header_size = 8u,

	// stage : 8
	// cmd   : 24
	mask_type_stage	= 0x000000FF,
	mask_type_cmd	= 0xFFFFFF00
};

static constexpr ceformat::Format const
	s_err_command_type_invalid{
		": command type %#08x is invalid\n"
	},
	s_err_stage_type_invalid{
		": stage type %#02x is invalid for command type %#08x\n"
	}
;

} // anonymous namespace

#define ONSANG_SCOPE_FUNC read_header
bool
CmdStreamer::read_header() {
	std::istream stream{&m_streambuf_in};
	std::size_t const size
	= duct::IO::read_arithmetic<uint32_t>(
		stream,
		duct::Endian::little
	);

	uint32_t const type
	= duct::IO::read_arithmetic<uint32_t>(
		stream,
		duct::Endian::little
	);

	if (stream.fail()) {
		return false;
	} else {
		m_incoming_size = size;
		m_incoming_type = type;
		return true;
	}
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC read_stage
bool
CmdStreamer::read_stage() {
	auto const command_type = static_cast<Hord::Cmd::Type>(
		m_incoming_type & mask_type_cmd
	);
	auto const stage_type = static_cast<Hord::Cmd::StageType>(
		m_incoming_type & mask_type_stage
	);

	Hord::Cmd::StageUPtr stage_uptr;
	Hord::Cmd::type_info const* const
	type_info = m_driver.get_command_type_info(
		command_type
	);
	if (!type_info) {
		Log::acquire(Log::error)
			<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
			<< ceformat::write_sentinel<
				s_err_command_type_invalid
			>(
				enum_cast(command_type)
			)
		;
		return false;
	}

	try {
		stage_uptr.reset(type_info->construct_stage(stage_type));
		std::istream stream{&m_streambuf_in};
		stage_uptr->deserialize(stream);
	} catch (Hord::Error& ex) {
		stage_uptr.reset();
		switch (ex.get_code()) {
		case Hord::ErrorCode::cmd_construct_stage_type_invalid:
			Log::acquire(Log::error)
				<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
				<< ceformat::write_sentinel<s_err_stage_type_invalid>(
					enum_cast(stage_type),
					enum_cast(command_type)
				)
			;
			return false;

		// IO error or malformed data
		default:
			return false;
		}
	} catch (...) {
		throw;
	}

	std::size_t const remaining = m_streambuf_in.get_remaining();
	if (0u < remaining) {
		Log::acquire(Log::debug)
			<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
			<< ": "
			<< remaining
			<< " bytes left in buffer after stage deserialization\n"
		;
	}

	{
		std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
		m_stage_buffer.emplace_back(std::move(stage_uptr));
		m_sig_have_stages.store(true);
	}

	return true;
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_read_header
void
CmdStreamer::chain_read_header() {
	m_incoming_size = 0u;
	assert(m_streambuf_in.reset(msg_header_size));
	asio::async_read(
		m_socket,
		asio::buffer(
			m_streambuf_in.get_buffer().data(),
			msg_header_size
		),
		asio::transfer_exactly(msg_header_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			if (!ec) {
				m_streambuf_in.commit_direct(msg_header_size);
				read_header();
				chain_read_stage();
			} else {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_read_stage
void
CmdStreamer::chain_read_stage() {
	assert(0u <  m_incoming_size);
	assert(0u != m_incoming_type);

	assert(m_streambuf_in.reset(m_incoming_size));
	asio::async_read(
		m_socket,
		asio::buffer(
			m_streambuf_in.get_buffer().data(),
			m_incoming_size
		),
		asio::transfer_exactly(m_incoming_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			if (!ec) {
				m_streambuf_in.commit_direct(m_incoming_size);
				read_stage();
				chain_read_header();
			} else {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_flush_output
void
CmdStreamer::chain_flush_output() {
	assert(0u < m_outgoing_size);

	asio::async_write(
		m_socket,
		asio::buffer(
			make_const(m_streambuf_out).get_buffer().data(),
			m_outgoing_size
		),
		asio::transfer_exactly(m_incoming_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			m_sig_pending_output.store(false);
			m_outgoing_size = 0u;
			if (ec) {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

// operations

void
CmdStreamer::halt() noexcept {
	m_socket.get_io_service().stop();
}

#define ONSANG_SCOPE_FUNC run
void
CmdStreamer::run() {
	auto& io_service = m_socket.get_io_service();
	try {
		while (!io_service.stopped()) {
			chain_read_header();
			io_service.run();
		}
	} catch (std::exception& ex) {
		Log::acquire(Log::error)
			<< Log::Pre::current << ONSANG_SCOPE_FQN_STR_LIT
			<< ": caught exception from io_service::run(): "
			<< ex.what()
			<< "\n"
		;
		throw;
	}
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC context_input
bool
CmdStreamer::context_input(
	Hord::System::Context& context
) {
	if (!m_sig_have_stages.load()) {
		return false;
	}

	{
		std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
		for (auto& stage_uptr : m_stage_buffer) {
			context.push_input(stage_uptr);
		}
		m_stage_buffer.clear();
		m_sig_have_stages.store(false);
	}

	return true;
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC context_output
bool
CmdStreamer::context_output(
	Hord::System::Context& context
) {
	if (
		0 == context.get_output().size() ||
		m_sig_pending_output.load()
	) {
		return false;
	}

	m_streambuf_out.reset(
		msg_header_size + (m_streambuf_out.get_max_size() >> 2)
	);
	std::ostream stream{&m_streambuf_out};

	// Seek past header to reserve it; we need the size of the
	// stage payload
	stream.seekp(msg_header_size);

	// data
	auto& stage = *context.get_output().front();
	stage.serialize(
		stream
	);

	// Can't use buffer.size() later because it might've grown
	// beyond our write amount
	m_outgoing_size = m_streambuf_out.get_sequence_size();

	// header
	stream.seekp(0);
	std::size_t const h_size = m_outgoing_size - msg_header_size;
	duct::IO::write_arithmetic<uint32_t>(
		stream,
		static_cast<uint32_t>(h_size),
		duct::Endian::little
	);

	uint32_t const h_type
		= enum_cast(stage.get_stage_type())
		| enum_cast(stage.get_command_type())
	;
	duct::IO::write_arithmetic<uint32_t>(
		stream,
		h_type,
		duct::Endian::little
	);

	if (stream.fail()) {
		return false;
	}
	m_streambuf_out.commit();

	context.get_output().pop_front();
	m_sig_pending_output.store(true);

	m_socket.get_io_service().post(
		[this]() {
			chain_flush_output();
		}
	);

	return true;
}
#undef ONSANG_SCOPE_FUNC

#undef ONSANG_SCOPE_CLASS // Onsang::Net::CmdStreamer

} // namespace Net
} // namespace Onsang
<commit_msg>Net/CmdStreamer: corrected Log::acquire() calls.¹<commit_after>
#include <Onsang/utility.hpp>
#include <Onsang/detail/gr_ceformat.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/asio.hpp>
#include <Onsang/Net/CmdStreamer.hpp>

#include <Hord/Error.hpp>
#include <Hord/ErrorCode.hpp>

#include <duct/IO/arithmetic.hpp>

#include <cassert>
#include <mutex>
#include <iomanip>
#include <iostream>

namespace Onsang {
namespace Net {

// class CmdStreamer implementation

#define ONSANG_SCOPE_CLASS Net::CmdStreamer

namespace {

enum : unsigned {
	// uint32 size
	// uint32 type
	msg_header_size = 8u,

	// stage : 8
	// cmd   : 24
	mask_type_stage	= 0x000000FF,
	mask_type_cmd	= 0xFFFFFF00
};

static constexpr ceformat::Format const
	s_err_command_type_invalid{
		": command type %#08x is invalid\n"
	},
	s_err_stage_type_invalid{
		": stage type %#02x is invalid for command type %#08x\n"
	}
;

} // anonymous namespace

#define ONSANG_SCOPE_FUNC read_header
bool
CmdStreamer::read_header() {
	std::istream stream{&m_streambuf_in};
	std::size_t const size
	= duct::IO::read_arithmetic<uint32_t>(
		stream,
		duct::Endian::little
	);

	uint32_t const type
	= duct::IO::read_arithmetic<uint32_t>(
		stream,
		duct::Endian::little
	);

	if (stream.fail()) {
		return false;
	} else {
		m_incoming_size = size;
		m_incoming_type = type;
		return true;
	}
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC read_stage
bool
CmdStreamer::read_stage() {
	auto const command_type = static_cast<Hord::Cmd::Type>(
		m_incoming_type & mask_type_cmd
	);
	auto const stage_type = static_cast<Hord::Cmd::StageType>(
		m_incoming_type & mask_type_stage
	);

	Hord::Cmd::StageUPtr stage_uptr;
	Hord::Cmd::type_info const* const
	type_info = m_driver.get_command_type_info(
		command_type
	);
	if (!type_info) {
		Log::acquire(Log::error)
			<< ONSANG_SCOPE_FQN_STR_LIT
			<< ceformat::write_sentinel<
				s_err_command_type_invalid
			>(
				enum_cast(command_type)
			)
		;
		return false;
	}

	try {
		stage_uptr.reset(type_info->construct_stage(stage_type));
		std::istream stream{&m_streambuf_in};
		stage_uptr->deserialize(stream);
	} catch (Hord::Error& ex) {
		stage_uptr.reset();
		switch (ex.get_code()) {
		case Hord::ErrorCode::cmd_construct_stage_type_invalid:
			Log::acquire(Log::error)
				<< ONSANG_SCOPE_FQN_STR_LIT
				<< ceformat::write_sentinel<s_err_stage_type_invalid>(
					enum_cast(stage_type),
					enum_cast(command_type)
				)
			;
			return false;

		// IO error or malformed data
		default:
			return false;
		}
	} catch (...) {
		throw;
	}

	std::size_t const remaining = m_streambuf_in.get_remaining();
	if (0u < remaining) {
		Log::acquire(Log::debug)
			<< ONSANG_SCOPE_FQN_STR_LIT
			<< ": "
			<< remaining
			<< " bytes left in buffer after stage deserialization\n"
		;
	}

	{
		std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
		m_stage_buffer.emplace_back(std::move(stage_uptr));
		m_sig_have_stages.store(true);
	}

	return true;
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_read_header
void
CmdStreamer::chain_read_header() {
	m_incoming_size = 0u;
	assert(m_streambuf_in.reset(msg_header_size));
	asio::async_read(
		m_socket,
		asio::buffer(
			m_streambuf_in.get_buffer().data(),
			msg_header_size
		),
		asio::transfer_exactly(msg_header_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			if (!ec) {
				m_streambuf_in.commit_direct(msg_header_size);
				read_header();
				chain_read_stage();
			} else {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_read_stage
void
CmdStreamer::chain_read_stage() {
	assert(0u <  m_incoming_size);
	assert(0u != m_incoming_type);

	assert(m_streambuf_in.reset(m_incoming_size));
	asio::async_read(
		m_socket,
		asio::buffer(
			m_streambuf_in.get_buffer().data(),
			m_incoming_size
		),
		asio::transfer_exactly(m_incoming_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			if (!ec) {
				m_streambuf_in.commit_direct(m_incoming_size);
				read_stage();
				chain_read_header();
			} else {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC chain_flush_output
void
CmdStreamer::chain_flush_output() {
	assert(0u < m_outgoing_size);

	asio::async_write(
		m_socket,
		asio::buffer(
			make_const(m_streambuf_out).get_buffer().data(),
			m_outgoing_size
		),
		asio::transfer_exactly(m_incoming_size),
		[this](
			boost::system::error_code const ec,
			std::size_t /*length*/
		) {
			m_sig_pending_output.store(false);
			m_outgoing_size = 0u;
			if (ec) {
				halt();
			}
		}
	);
}
#undef ONSANG_SCOPE_FUNC

// operations

void
CmdStreamer::halt() noexcept {
	m_socket.get_io_service().stop();
}

#define ONSANG_SCOPE_FUNC run
void
CmdStreamer::run() {
	auto& io_service = m_socket.get_io_service();
	try {
		while (!io_service.stopped()) {
			chain_read_header();
			io_service.run();
		}
	} catch (std::exception& ex) {
		Log::acquire(Log::error)
			<< ONSANG_SCOPE_FQN_STR_LIT
			<< ": caught exception from io_service::run(): "
			<< ex.what()
			<< "\n"
		;
		throw;
	}
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC context_input
bool
CmdStreamer::context_input(
	Hord::System::Context& context
) {
	if (!m_sig_have_stages.load()) {
		return false;
	}

	{
		std::lock_guard<std::mutex> m_lock{m_stage_buffer_mutex};
		for (auto& stage_uptr : m_stage_buffer) {
			context.push_input(stage_uptr);
		}
		m_stage_buffer.clear();
		m_sig_have_stages.store(false);
	}

	return true;
}
#undef ONSANG_SCOPE_FUNC

#define ONSANG_SCOPE_FUNC context_output
bool
CmdStreamer::context_output(
	Hord::System::Context& context
) {
	if (
		0 == context.get_output().size() ||
		m_sig_pending_output.load()
	) {
		return false;
	}

	m_streambuf_out.reset(
		msg_header_size + (m_streambuf_out.get_max_size() >> 2)
	);
	std::ostream stream{&m_streambuf_out};

	// Seek past header to reserve it; we need the size of the
	// stage payload
	stream.seekp(msg_header_size);

	// data
	auto& stage = *context.get_output().front();
	stage.serialize(
		stream
	);

	// Can't use buffer.size() later because it might've grown
	// beyond our write amount
	m_outgoing_size = m_streambuf_out.get_sequence_size();

	// header
	stream.seekp(0);
	std::size_t const h_size = m_outgoing_size - msg_header_size;
	duct::IO::write_arithmetic<uint32_t>(
		stream,
		static_cast<uint32_t>(h_size),
		duct::Endian::little
	);

	uint32_t const h_type
		= enum_cast(stage.get_stage_type())
		| enum_cast(stage.get_command_type())
	;
	duct::IO::write_arithmetic<uint32_t>(
		stream,
		h_type,
		duct::Endian::little
	);

	if (stream.fail()) {
		return false;
	}
	m_streambuf_out.commit();

	context.get_output().pop_front();
	m_sig_pending_output.store(true);

	m_socket.get_io_service().post(
		[this]() {
			chain_flush_output();
		}
	);

	return true;
}
#undef ONSANG_SCOPE_FUNC

#undef ONSANG_SCOPE_CLASS // Onsang::Net::CmdStreamer

} // namespace Net
} // namespace Onsang
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NamedBoolPropertyHdl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:25:30 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

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

///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//

XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
    // Nothing to do
}

sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const
{
    if( rStrImpValue == maTrueStr )
    {
        rValue = ::cppu::bool2any( sal_True );
        return sal_True;
    }

    if( rStrImpValue == maFalseStr )
    {
        rValue = ::cppu::bool2any( sal_False );
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const
{
    if( ::cppu::any2bool( rValue ) )
    {
        rStrExpValue = maTrueStr;
    }
    else
    {
        rStrExpValue = maFalseStr;
    }

    return sal_True;
}

<commit_msg>INTEGRATION: CWS impresstables2 (1.5.80); FILE MERGED 2007/08/01 14:23:46 cl 1.5.80.2: RESYNC: (1.5-1.6); FILE MERGED 2007/07/27 09:09:53 cl 1.5.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NamedBoolPropertyHdl.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:43:22 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <xmloff/NamedBoolPropertyHdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

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

///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//

XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
    // Nothing to do
}

sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const
{
    if( rStrImpValue == maTrueStr )
    {
        rValue = ::cppu::bool2any( sal_True );
        return sal_True;
    }

    if( rStrImpValue == maFalseStr )
    {
        rValue = ::cppu::bool2any( sal_False );
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const
{
    if( ::cppu::any2bool( rValue ) )
    {
        rStrExpValue = maTrueStr;
    }
    else
    {
        rStrExpValue = maFalseStr;
    }

    return sal_True;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropMapper.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:28:18 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif

#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif

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

//______________________________________________________________________________

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
    XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
        const XMLPropertyMapEntry* pEntries,
        const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
    XMLPropertySetMapper( pEntries, rFactory )
{
}

XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}

<commit_msg>INTEGRATION: CWS changefileheader (1.13.162); FILE MERGED 2008/04/01 13:04:58 thb 1.13.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:19 rt 1.13.162.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: PageMasterPropMapper.cxx,v $
 * $Revision: 1.14 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif

#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#include "PageMasterPropHdlFactory.hxx"

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

//______________________________________________________________________________

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
    XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
        const XMLPropertyMapEntry* pEntries,
        const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
    XMLPropertySetMapper( pEntries, rFactory )
{
}

XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}

<|endoftext|>


<commit_before>/*
    kcodecaction.cpp

    Copyright (c) 2003 by Jason Keirstead        <jason@keirstead.org>
    Kopete    (c) 2003 by the Kopete developers  <kopete-devel@kde.org>

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

#include "kcodecaction.h"

KCodecAction::KCodecAction( const QString &text, const KShortcut &cut,
		QObject *parent, const char *name ) : KSelectAction( text, "", cut, parent, name )
{
	QObject::connect( this, SIGNAL( activated( int ) ),
		this, SLOT(slotActivated( int )) );

	QTextCodec *codec;
	QStringList items;

	for (uint i = 0; ( codec = QTextCodec::codecForIndex(i) ); ++i)
	{
        	items.append( codec->name() );
		codecMap.insert( i, codec );
	}

	setItems( items );
}

void KCodecAction::slotActivated( int index )
{
	emit activated( codecMap[ index ] );
}

void KCodecAction::setCodec( const QTextCodec *codec )
{
	for( QIntDictIterator<QTextCodec> it( codecMap ); it.current(); ++it )
	{
		if( it.current() == codec )
			setCurrentItem( it.currentKey() );
	}
}

#include "kcodecaction.moc"
<commit_msg>Fix a small bug when changing the encoding for a channel or private chat  via IRC->Encoding menu item: The encoding changes, but the menu is not  updated to reflect that change, the 'tick' just stays in the default  selection.<commit_after>/*
    kcodecaction.cpp

    Copyright (c) 2003 by Jason Keirstead        <jason@keirstead.org>
    Kopete    (c) 2003 by the Kopete developers  <kopete-devel@kde.org>

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

#include "kcodecaction.h"

KCodecAction::KCodecAction( const QString &text, const KShortcut &cut,
		QObject *parent, const char *name ) : KSelectAction( text, "", cut, parent, name )
{
	QObject::connect( this, SIGNAL( activated( int ) ),
		this, SLOT(slotActivated( int )) );

	QTextCodec *codec;
	QStringList items;

	for (uint i = 0; ( codec = QTextCodec::codecForIndex(i) ); ++i)
	{
        	items.append( codec->name() );
		codecMap.insert( i, codec );
	}

	setItems( items );
}

void KCodecAction::slotActivated( int index )
{
	setCurrentItem( index );
	emit activated( codecMap[ index ] );
}

void KCodecAction::setCodec( const QTextCodec *codec )
{
	for( QIntDictIterator<QTextCodec> it( codecMap ); it.current(); ++it )
	{
		if( it.current() == codec )
			setCurrentItem( it.currentKey() );
	}
}

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