<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Nico Blodow (blodow@cs.tum.edu)
 *         Radu Bogdan Rusu (rusu@willowgarage.com)
 *         Suat Gedikli (gedikli@willowgarage.com)
 *         Ethan Rublee (rublee@willowgarage.com)
 */

#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <vector>

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    if (++count == 100) \
    { \
      double now = pcl::getTime (); \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

template <typename PointType>
class SimpleOpenNIViewer
{
public:
  typedef pcl::PointCloud<PointType> Cloud;
  typedef typename Cloud::ConstPtr CloudConstPtr;

  SimpleOpenNIViewer(pcl::OpenNIGrabber& grabber)
    : viewer("PCL OpenNI Viewer")
    , grabber_(grabber)
  {
  }

  /**
   * @brief Callback method for the grabber interface
   * @param cloud The new point cloud from Grabber
   */
  void
  cloud_cb_ (const CloudConstPtr& cloud)
  {
    FPS_CALC ("callback");
    boost::mutex::scoped_lock lock (mtx_);
    cloud_ = cloud;
  }

  /**
   * @brief swaps the pointer to the point cloud with Null pointer and returns the cloud pointer
   * @return boost shared pointer to point cloud
   */
  CloudConstPtr
  getLatestCloud ()
  {
    //lock while we swap our cloud and reset it.
    boost::mutex::scoped_lock lock(mtx_);
    CloudConstPtr temp_cloud;
    temp_cloud.swap (cloud_); //here we set cloud_ to null, so that
    //it is safe to set it again from our
    //callback
    return (temp_cloud);
  }

  /**
   * @brief starts the main loop
   */
  void
  run()
  {
    //pcl::Grabber* interface = new pcl::OpenNIGrabber(device_id_, pcl::OpenNIGrabber::OpenNI_QQVGA_30Hz, pcl::OpenNIGrabber::OpenNI_VGA_30Hz);

    boost::function<void (const CloudConstPtr&) > f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

    boost::signals2::connection c = grabber_.registerCallback (f);

    grabber_.start();

    while (!viewer.wasStopped ())
    {
      if (cloud_)
      {
        FPS_CALC ("drawing");
        //the call to get() sets the cloud_ to null;
        viewer.showCloud (getLatestCloud ());
      }
    }

    grabber_.stop();
  }

  pcl::visualization::CloudViewer viewer;
  pcl::OpenNIGrabber& grabber_;
  boost::mutex mtx_;
  CloudConstPtr cloud_;
};

void
usage(char ** argv)
{
  cout << "usage: " << argv[0] << " [<device_id> [<depth-mode> [<image-mode>] ] ] | [path-to-oni-file]\n";
  cout << argv[0] << " -h | --help : shows this help" << endl;
  cout << argv[0] << " -l : list all available devices" << endl;
  cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;

  cout << "                 device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
       << " or" << endl
       << "                 bus@address for the device connected to a specific usb-bus / address combination or" << endl
       << "                 <serial-number>"
#endif
       << endl;
  cout << endl;
  cout << "examples:" << endl;
  cout << argv[0] << " \"#1\"" << endl;
  cout << "    uses the first device." << endl;
  cout << argv[0] << " \"./temp/test.oni\"" << endl;
  cout << "    uses the oni-player device to play back oni file given by path." << endl;
  cout << argv[0] << " -l" << endl;
  cout << "    lists all available devices." << endl;
  cout << argv[0] << " -l \"#2\"" << endl;
  cout << "    lists all available modes for the second device" << endl;
  #ifndef _WIN32
  cout << argv[0] << " A00361800903049A" << endl;
  cout << "    uses the device with the serial number \'A00361800903049A\'." << endl;
  cout << argv[0] << " 1@16" << endl;
  cout << "    uses the device on address 16 at usb bus 1." << endl;
  #endif
  return;
}

int
main(int argc, char ** argv)
{
  std::string arg("");
  pcl::OpenNIGrabber::Mode depth_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
  pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;

  if (argc >= 2)
  {
    arg = argv[1];

    if (arg == "--help" || arg == "-h")
    {
      usage(argv);
      return 1;
    }
    else if (arg == "-l")
    {
      if (argc >= 3)
      {
        pcl::OpenNIGrabber grabber(argv[2]);
        const openni_wrapper::OpenNIDevice& device = grabber.getDevice();
        cout << "Supported depth modes for device: " << device.getVendorName() << " , " << device.getProductName() << endl;
        std::vector<std::pair<int, XnMapOutputMode > > modes = grabber.getAvailableDepthModes();
        for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
        {
          cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
        }

        cout << endl << "Supported image modes for device: " << device.getVendorName() << " , " << device.getProductName() << endl;
        modes = grabber.getAvailableImageModes();
        for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
        {
          cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
        }
        return 0;
      }
      else
      {
        openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
        if (driver.getNumberDevices() > 0)
        {
          for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices(); ++deviceIdx)
          {
            cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName(deviceIdx) << ", product: " << driver.getProductName(deviceIdx)
              << ", connected: " << (int) driver.getBus(deviceIdx) << " @ " << (int) driver.getAddress(deviceIdx) << ", serial number: \'" << driver.getSerialNumber(deviceIdx) << "\'" << endl;
          }

        }
        else
          cout << "No devices connected." << endl;

        cout <<"Virtual Devices available: ONI player" << endl;
        return 0;
      }
    }

    if (argc >= 3)
    {
      depth_mode = (pcl::OpenNIGrabber::Mode) atoi(argv[2]);
      if (argc == 4)
      {
        image_mode = (pcl::OpenNIGrabber::Mode) atoi(argv[3]);
      }
    }
  }
  else
  {
    openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
    if (driver.getNumberDevices() > 0)
      cout << "Device Id not set, using first device." << endl;
  }

  pcl::OpenNIGrabber grabber(arg, depth_mode, image_mode);
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb > ())
  {
    SimpleOpenNIViewer<pcl::PointXYZRGB> v(grabber);
    v.run();
  }
  else
  {
    SimpleOpenNIViewer<pcl::PointXYZI> v(grabber);
    v.run();
  }

  return (0);
}
<commit_msg>more rest :)<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Nico Blodow (blodow@cs.tum.edu)
 *         Radu Bogdan Rusu (rusu@willowgarage.com)
 *         Suat Gedikli (gedikli@willowgarage.com)
 *         Ethan Rublee (rublee@willowgarage.com)
 */

#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <vector>

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    if (++count == 100) \
    { \
      double now = pcl::getTime (); \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

template <typename PointType>
class SimpleOpenNIViewer
{
public:
  typedef pcl::PointCloud<PointType> Cloud;
  typedef typename Cloud::ConstPtr CloudConstPtr;

  SimpleOpenNIViewer(pcl::OpenNIGrabber& grabber)
    : viewer("PCL OpenNI Viewer")
    , grabber_(grabber)
  {
  }

  /**
   * @brief Callback method for the grabber interface
   * @param cloud The new point cloud from Grabber
   */
  void
  cloud_cb_ (const CloudConstPtr& cloud)
  {
    FPS_CALC ("callback");
    boost::mutex::scoped_lock lock (mtx_);
    cloud_ = cloud;
  }

  /**
   * @brief swaps the pointer to the point cloud with Null pointer and returns the cloud pointer
   * @return boost shared pointer to point cloud
   */
  CloudConstPtr
  getLatestCloud ()
  {
    //lock while we swap our cloud and reset it.
    boost::mutex::scoped_lock lock(mtx_);
    CloudConstPtr temp_cloud;
    temp_cloud.swap (cloud_); //here we set cloud_ to null, so that
    //it is safe to set it again from our
    //callback
    return (temp_cloud);
  }

  /**
   * @brief starts the main loop
   */
  void
  run()
  {
    //pcl::Grabber* interface = new pcl::OpenNIGrabber(device_id_, pcl::OpenNIGrabber::OpenNI_QQVGA_30Hz, pcl::OpenNIGrabber::OpenNI_VGA_30Hz);

    boost::function<void (const CloudConstPtr&) > f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

    boost::signals2::connection c = grabber_.registerCallback (f);

    grabber_.start();

    while (!viewer.wasStopped ())
    {
      if (cloud_)
      {
        FPS_CALC ("drawing");
        //the call to get() sets the cloud_ to null;
        viewer.showCloud (getLatestCloud ());
      }
    }

    grabber_.stop();
  }

  pcl::visualization::CloudViewer viewer;
  pcl::OpenNIGrabber& grabber_;
  boost::mutex mtx_;
  CloudConstPtr cloud_;
};

void
usage(char ** argv)
{
  cout << "usage: " << argv[0] << " [<device_id> [<depth-mode> [<image-mode>] ] ] | [path-to-oni-file]\n";
  cout << argv[0] << " -h | --help : shows this help" << endl;
  cout << argv[0] << " -l : list all available devices" << endl;
  cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;

  cout << "                 device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
       << " or" << endl
       << "                 bus@address for the device connected to a specific usb-bus / address combination or" << endl
       << "                 <serial-number>"
#endif
       << endl;
  cout << endl;
  cout << "examples:" << endl;
  cout << argv[0] << " \"#1\"" << endl;
  cout << "    uses the first device." << endl;
  cout << argv[0] << " \"./temp/test.oni\"" << endl;
  cout << "    uses the oni-player device to play back oni file given by path." << endl;
  cout << argv[0] << " -l" << endl;
  cout << "    lists all available devices." << endl;
  cout << argv[0] << " -l \"#2\"" << endl;
  cout << "    lists all available modes for the second device" << endl;
  #ifndef _WIN32
  cout << argv[0] << " A00361800903049A" << endl;
  cout << "    uses the device with the serial number \'A00361800903049A\'." << endl;
  cout << argv[0] << " 1@16" << endl;
  cout << "    uses the device on address 16 at usb bus 1." << endl;
  #endif
  return;
}

int
main(int argc, char ** argv)
{
  std::string arg("");
  pcl::OpenNIGrabber::Mode depth_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
  pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;

  if (argc >= 2)
  {
    arg = argv[1];

    if (arg == "--help" || arg == "-h")
    {
      usage(argv);
      return 1;
    }
    else if (arg == "-l")
    {
      if (argc >= 3)
      {
        pcl::OpenNIGrabber grabber(argv[2]);
        boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice();
        cout << "Supported depth modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl;
        std::vector<std::pair<int, XnMapOutputMode > > modes = grabber.getAvailableDepthModes();
        for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
        {
          cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
        }

        cout << endl << "Supported image modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl;
        modes = grabber.getAvailableImageModes();
        for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
        {
          cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
        }
        return 0;
      }
      else
      {
        openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
        if (driver.getNumberDevices() > 0)
        {
          for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices(); ++deviceIdx)
          {
            cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName(deviceIdx) << ", product: " << driver.getProductName(deviceIdx)
              << ", connected: " << (int) driver.getBus(deviceIdx) << " @ " << (int) driver.getAddress(deviceIdx) << ", serial number: \'" << driver.getSerialNumber(deviceIdx) << "\'" << endl;
          }

        }
        else
          cout << "No devices connected." << endl;

        cout <<"Virtual Devices available: ONI player" << endl;
        return 0;
      }
    }

    if (argc >= 3)
    {
      depth_mode = (pcl::OpenNIGrabber::Mode) atoi(argv[2]);
      if (argc == 4)
      {
        image_mode = (pcl::OpenNIGrabber::Mode) atoi(argv[3]);
      }
    }
  }
  else
  {
    openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
    if (driver.getNumberDevices() > 0)
      cout << "Device Id not set, using first device." << endl;
  }

  pcl::OpenNIGrabber grabber(arg, depth_mode, image_mode);
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb > ())
  {
    SimpleOpenNIViewer<pcl::PointXYZRGB> v(grabber);
    v.run();
  }
  else
  {
    SimpleOpenNIViewer<pcl::PointXYZI> v(grabber);
    v.run();
  }

  return (0);
}
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2008 - 2010 IBM Corporation and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    David Ungar, IBM Research - Initial Implementation
 *    Sam Adams, IBM Research - Initial Implementation
 *    Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
 ******************************************************************************/

#include "headers.h"

# include <fcntl.h>
# include <unistd.h>

void Squeak_Image_Reader::read(char* fileName, Memory_System* ms, Squeak_Interpreter* i) {
  Squeak_Image_Reader* sir = new Squeak_Image_Reader(fileName, ms, i);
  sir->read_image();
  dittoing_stdout_printer->printf("finished reading %s\n", fileName);
}

void Squeak_Image_Reader::fake_read(char* fileName, Memory_System* ms, Squeak_Interpreter* i) {
  Squeak_Image_Reader* sir = new Squeak_Image_Reader(fileName, ms, i);
  sir->read_header();

  //mimic reader
  Memory_Semantics::shared_malloc(sir->dataSize);
  malloc(sir->dataSize);

  i->restore_all_from_checkpoint(sir->dataSize, sir->lastHash, sir->savedWindowSize, sir->fullScreenFlag);
  imageNamePut_on_all_cores(sir->file_name, strlen(sir->file_name));
}

Squeak_Image_Reader::Squeak_Image_Reader(char* fn, Memory_System* ms, Squeak_Interpreter* i) {
  dittoing_stdout_printer->printf("Reading %s\n", fn);
  memory_system = ms;
  interpreter = i;

  file_name = fn;
  image_file = fopen(file_name, "r");
  swap_bytes = false;
  if (image_file == NULL) {
    char buf[BUFSIZ];
    snprintf(buf, sizeof(buf), "Could not open image file %s", file_name);
    perror(buf);
    abort();
  }
}

void Squeak_Image_Reader::read_image() {
/*

readImageFromFile: f HeapSize: desiredHeapSize StartingAt: imageOffset
   "Read an image from the given file stream, allocating the given amount of
    memory to its object heap. Fail if the image has an unknown format or
    requires more than the given amount of memory."

   "Details: This method detects when the image was stored on a machine with
    the opposite byte ordering from this machine and swaps the bytes
    automatically. Furthermore, it allows the header information to start 512
    bytes into the file, since some file transfer programs for the Macintosh
    apparently prepend a Mac-specific header of this size. Note that this same
    512 bytes of prefix area could also be used to store an exec command on
    Unix systems, allowing one to launch Smalltalk by invoking the image name
    as a command."

   "This code is based on C code by Ian Piumarta and Smalltalk code by Tim
    Rowledge. Many thanks to both of you!!"
*/

  Object::verify_constants();

  read_header();

  fprintf(stdout, "allocating memory for snapshot\n");

  // "allocate a contiguous block of memory for the Squeak heap"
  memory = (char*)Memory_Semantics::shared_malloc(dataSize);
  assert_always(memory != NULL);

  /*
	memStart := self startOfMemory.
	memoryLimit := (memStart + heapSize) - 24.  "decrease memoryLimit a tad for safety"
	endOfMemory := memStart + dataSize.
  */

  // "position file after the header"
  fprintf(stdout, "reading objects in snapshot\n");
  if ( fseek(image_file, headerStart + headerSize, SEEK_SET))
    perror("seek"), fatal();

  // "read in the image in bulk, then swap the bytes if necessary"
  xfread(memory, 1, dataSize, image_file);

  // "First, byte-swap every word in the image. This fixes objects headers."
  if (swap_bytes) reverseBytes((int32*)&memory[0], (int32*)&memory[dataSize]);

  // "Second, return the bytes of bytes-type objects to their orginal order."
  if (swap_bytes) byteSwapByteObjects();

  Safepoint_Ability sa(false); // for distributing objects and putting image name
  distribute_objects();
  imageNamePut_on_all_cores(file_name, strlen(file_name));

  // we need to reoder floats if the image was a Cog image
  if (is_cog_image_with_reodered_floats()) {
    normalize_float_ordering_in_image();
  }
}

/** Inspired by:
 !Interpreter methodsFor: 'image save/restore' stamp: 'dtl 10/5/2010 23:54'!
 normalizeFloatOrderingInImage

 "Float objects were saved in platform word ordering. Reorder them into the
 traditional object format."
*/
void Squeak_Image_Reader::normalize_float_ordering_in_image() {
  Squeak_Interpreter* const interp = The_Squeak_Interpreter();
  Memory_System* const mem_sys = The_Memory_System();

  Oop cls = interp->splObj(Special_Indices::ClassFloat);
  for (Oop floatInstance = mem_sys->initialInstanceOf(cls);
       floatInstance != interp->roots.nilObj;
       floatInstance  = mem_sys->nextInstanceAfter(floatInstance) ) {
    /* Swap words within Float objects, taking them out of native platform ordering */
    floatInstance.as_object()->swapFloatParts_for_cog_compatibility();
  }
}

void Squeak_Image_Reader::imageNamePut_on_all_cores(char* bytes, unsigned int len) {
  // Use a shared buffer to reduce the size of the message to optimize the
  // footprint of message buffer allocation -- dmu & sm
  char* shared_buffer = (char*)Memory_Semantics::shared_malloc(len);
  bcopy(bytes, shared_buffer, len);
  imageNamePutMessage_class m(shared_buffer, len);
  if (On_Tilera) m.send_to_all_cores();
  else           m.handle_me();
  free(shared_buffer);
}

void Squeak_Image_Reader::read_header() {
  fprintf(stdout, "reading snapshot header\n");
  check_image_version();
  // headerStart := (self sqImageFilePosition: f) - bytesPerWord.  "record header start position"
  headerStart = ftell(image_file) - bytesPerWord;
  headerSize         = get_long();
  dataSize           = get_long();
  oldBaseAddr        = (char*)get_long();
  specialObjectsOop = Oop::from_bits(get_long());

  lastHash = get_long();
  if (lastHash == 0) lastHash = 999;

  savedWindowSize    = get_long();
  fullScreenFlag     = get_long();

  extraVMMemory      = get_long();
}

void Squeak_Image_Reader::check_image_version() {
    int32 first_version = get_long();
    interpreter->image_version = first_version;
    if ( readable_format(interpreter->image_version) ) return;
    swap_bytes = true;
    if (fseek(image_file, -sizeof(int32), SEEK_CUR) != 0) {
      perror("seek failed"); fatal();
    }
    interpreter->image_version = get_long();
    if ( readable_format(interpreter->image_version) ) return;

    fatal("cannot read file");

}

int32 Squeak_Image_Reader::get_long() {
  int32 x;
  xfread(&x, sizeof(x), 1, image_file);
  if (swap_bytes) swap_bytes_long(&x);
  return x;
}

bool Squeak_Image_Reader::readable_format(int32 version) {
  /* Check against a magic constant that changes when the image format
     changes. Since the image reading code uses this to detect byte ordering,
     one must avoid version numbers that are invariant under byte reversal. */
  return   version == Pre_Closure_32_Bit_Image_Version
       ||  version == Post_Closure_32_Bit_Image_Version
       ||  version == Post_Closure_With_Reordered_Floats_32_Bit_Image_Version;
}

bool Squeak_Image_Reader::is_cog_image_with_reodered_floats() {
  return interpreter->image_version == Post_Closure_With_Reordered_Floats_32_Bit_Image_Version;
}

void Squeak_Image_Reader::byteSwapByteObjects() {
  fprintf(stdout, "swapping bytes back in byte objects\n");
  for (Chunk* c = (Chunk*)memory;
       (char*)c <  &memory[dataSize]; ) {
    Object* obj = c->object_from_chunk_without_preheader();
    obj->byteSwapIfByteObject();
    c = obj->nextChunk();
  }
  fprintf(stdout, "done swapping bytes back in byte objects\n");
}

class Convert_Closure: public Oop_Closure {
  Squeak_Image_Reader* reader;
public:
  Convert_Closure(Squeak_Image_Reader* r)  : Oop_Closure() { reader = r; }
  void value(Oop* p, Object_p) {
    if (p->is_mem()) {
      *p = reader->oop_for_oop(*p);
    }
  }
  virtual const char* class_name(char*) { return "Convert_Closure"; }
};

# if !Use_Object_Table
class UpdateOop_Closure: public Oop_Closure {
  Multicore_Object_Table* object_table;
public:
  UpdateOop_Closure(Multicore_Object_Table* ot)  : Oop_Closure() { object_table = ot; }
  void value(Oop* p, Object_p) {
    if (p->is_mem()) {
      Object* obj = object_table->object_for(*p);
      *p = obj->as_oop();
      assert_always(p->as_object() == obj);
    }
  }
  virtual const char* class_name(char*) { return "UpdateOop_Closure"; }
};
# endif

void Squeak_Image_Reader::distribute_objects() {
  fprintf(stdout, "distributing objects\n");
  u_int64 start = OS_Interface::get_cycle_count();
  char* base = memory;
  u_int32 total_bytes = dataSize;

  object_oops = (Oop*)malloc(total_bytes);
  bzero(object_oops, total_bytes);
  Convert_Closure cc(this);

  memory_system->initialize_from_snapshot(dataSize, savedWindowSize, fullScreenFlag, lastHash);

  for (Chunk *c = (Chunk*)base, *nextChunk = NULL;
       (char*)c <  &base[total_bytes];
       c = nextChunk) {
    Object* obj = c->object_from_chunk_without_preheader(); // chunks in memory don't have a preheader
    if (check_many_assertions &&  (char*)obj - memory == (char*)specialObjectsOop.bits() - oldBaseAddr)
      lprintf("about to do specialObjectsOop");
    nextChunk = obj->nextChunk();
    if (!obj->isFreeObject()) {
      obj->do_all_oops_of_object_for_reading_snapshot(this);
      memory_system->ask_cpu_core_to_add_object_from_snapshot_allocating_chunk(oop_for_addr(obj), obj, object_table);
    }
  }

  cc.value(&specialObjectsOop, (Object_p)NULL);

  /* RMOT: Extra pass for updating the pointers && deallocate the object table */
  UpdateOop_Closure uoc(object_table);
  FOR_ALL_RANKS(r) {
    for (int hi = 0; hi<Memory_System::max_num_mutabilities; hi++) {
      Multicore_Object_Heap* heap = memory_system->heaps[r][hi];
      FOR_EACH_OBJECT_IN_HEAP(heap, obj) {
        if (!obj->isFreeObject()) {
          obj->set_backpointer(obj->as_oop());
          obj->do_all_oops_of_object(&uoc,false);
          if(((Oop*)obj->extra_preheader_word())->is_mem())
            fatal("shouldnt occur");
        }
      }
    }
  }
  specialObjectsOop = object_table->object_for(specialObjectsOop)->as_oop();

  object_table->cleanup();
  delete object_table;

  memory_system->finished_adding_objects_from_snapshot();
  free(object_oops);
  fprintf(stdout, "done distributing objects, %lld cycles\n",
    OS_Interface::get_cycle_count() - start);

  interpreter->initialize(specialObjectsOop, false);
}

Oop Squeak_Image_Reader::oop_for_oop(Oop x) {
  return oop_for_relative_addr(x.bits() - (int)oldBaseAddr);
}

Oop Squeak_Image_Reader::oop_for_addr(Object* obj) {
  return oop_for_relative_addr(int(obj) - int(memory));
}

Oop Squeak_Image_Reader::oop_for_relative_addr(int relative_addr) {
  assert(u_int32(relative_addr) < dataSize);
  Oop* addr_in_table = &object_oops[relative_addr / sizeof(Oop)];
  Object* obj = (Object*) &memory[relative_addr];
  if (addr_in_table->bits() == 0) {
    Object_Table* const ot = memory_system->object_table;
    *addr_in_table = ot->allocate_OTE_for_object_in_snapshot(obj);
  }
  return *addr_in_table;
}

<commit_msg>Remove Convert_Closure since it is not used in anyway useful.<commit_after>/******************************************************************************
 *  Copyright (c) 2008 - 2010 IBM Corporation and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    David Ungar, IBM Research - Initial Implementation
 *    Sam Adams, IBM Research - Initial Implementation
 *    Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems
 ******************************************************************************/

#include "headers.h"

# include <fcntl.h>
# include <unistd.h>

void Squeak_Image_Reader::read(char* fileName, Memory_System* ms, Squeak_Interpreter* i) {
  Squeak_Image_Reader* sir = new Squeak_Image_Reader(fileName, ms, i);
  sir->read_image();
  dittoing_stdout_printer->printf("finished reading %s\n", fileName);
}

void Squeak_Image_Reader::fake_read(char* fileName, Memory_System* ms, Squeak_Interpreter* i) {
  Squeak_Image_Reader* sir = new Squeak_Image_Reader(fileName, ms, i);
  sir->read_header();

  //mimic reader
  Memory_Semantics::shared_malloc(sir->dataSize);
  malloc(sir->dataSize);

  i->restore_all_from_checkpoint(sir->dataSize, sir->lastHash, sir->savedWindowSize, sir->fullScreenFlag);
  imageNamePut_on_all_cores(sir->file_name, strlen(sir->file_name));
}

Squeak_Image_Reader::Squeak_Image_Reader(char* fn, Memory_System* ms, Squeak_Interpreter* i) {
  dittoing_stdout_printer->printf("Reading %s\n", fn);
  memory_system = ms;
  interpreter = i;

  file_name = fn;
  image_file = fopen(file_name, "r");
  swap_bytes = false;
  if (image_file == NULL) {
    char buf[BUFSIZ];
    snprintf(buf, sizeof(buf), "Could not open image file %s", file_name);
    perror(buf);
    abort();
  }
}

void Squeak_Image_Reader::read_image() {
/*

readImageFromFile: f HeapSize: desiredHeapSize StartingAt: imageOffset
   "Read an image from the given file stream, allocating the given amount of
    memory to its object heap. Fail if the image has an unknown format or
    requires more than the given amount of memory."

   "Details: This method detects when the image was stored on a machine with
    the opposite byte ordering from this machine and swaps the bytes
    automatically. Furthermore, it allows the header information to start 512
    bytes into the file, since some file transfer programs for the Macintosh
    apparently prepend a Mac-specific header of this size. Note that this same
    512 bytes of prefix area could also be used to store an exec command on
    Unix systems, allowing one to launch Smalltalk by invoking the image name
    as a command."

   "This code is based on C code by Ian Piumarta and Smalltalk code by Tim
    Rowledge. Many thanks to both of you!!"
*/

  Object::verify_constants();

  read_header();

  fprintf(stdout, "allocating memory for snapshot\n");

  // "allocate a contiguous block of memory for the Squeak heap"
  memory = (char*)Memory_Semantics::shared_malloc(dataSize);
  assert_always(memory != NULL);

  /*
	memStart := self startOfMemory.
	memoryLimit := (memStart + heapSize) - 24.  "decrease memoryLimit a tad for safety"
	endOfMemory := memStart + dataSize.
  */

  // "position file after the header"
  fprintf(stdout, "reading objects in snapshot\n");
  if ( fseek(image_file, headerStart + headerSize, SEEK_SET))
    perror("seek"), fatal();

  // "read in the image in bulk, then swap the bytes if necessary"
  xfread(memory, 1, dataSize, image_file);

  // "First, byte-swap every word in the image. This fixes objects headers."
  if (swap_bytes) reverseBytes((int32*)&memory[0], (int32*)&memory[dataSize]);

  // "Second, return the bytes of bytes-type objects to their orginal order."
  if (swap_bytes) byteSwapByteObjects();

  Safepoint_Ability sa(false); // for distributing objects and putting image name
  distribute_objects();
  imageNamePut_on_all_cores(file_name, strlen(file_name));

  // we need to reoder floats if the image was a Cog image
  if (is_cog_image_with_reodered_floats()) {
    normalize_float_ordering_in_image();
  }
}

/** Inspired by:
 !Interpreter methodsFor: 'image save/restore' stamp: 'dtl 10/5/2010 23:54'!
 normalizeFloatOrderingInImage

 "Float objects were saved in platform word ordering. Reorder them into the
 traditional object format."
*/
void Squeak_Image_Reader::normalize_float_ordering_in_image() {
  Squeak_Interpreter* const interp = The_Squeak_Interpreter();
  Memory_System* const mem_sys = The_Memory_System();

  Oop cls = interp->splObj(Special_Indices::ClassFloat);
  for (Oop floatInstance = mem_sys->initialInstanceOf(cls);
       floatInstance != interp->roots.nilObj;
       floatInstance  = mem_sys->nextInstanceAfter(floatInstance) ) {
    /* Swap words within Float objects, taking them out of native platform ordering */
    floatInstance.as_object()->swapFloatParts_for_cog_compatibility();
  }
}

void Squeak_Image_Reader::imageNamePut_on_all_cores(char* bytes, unsigned int len) {
  // Use a shared buffer to reduce the size of the message to optimize the
  // footprint of message buffer allocation -- dmu & sm
  char* shared_buffer = (char*)Memory_Semantics::shared_malloc(len);
  bcopy(bytes, shared_buffer, len);
  imageNamePutMessage_class m(shared_buffer, len);
  if (On_Tilera) m.send_to_all_cores();
  else           m.handle_me();
  free(shared_buffer);
}

void Squeak_Image_Reader::read_header() {
  fprintf(stdout, "reading snapshot header\n");
  check_image_version();
  // headerStart := (self sqImageFilePosition: f) - bytesPerWord.  "record header start position"
  headerStart = ftell(image_file) - bytesPerWord;
  headerSize         = get_long();
  dataSize           = get_long();
  oldBaseAddr        = (char*)get_long();
  specialObjectsOop = Oop::from_bits(get_long());

  lastHash = get_long();
  if (lastHash == 0) lastHash = 999;

  savedWindowSize    = get_long();
  fullScreenFlag     = get_long();

  extraVMMemory      = get_long();
}

void Squeak_Image_Reader::check_image_version() {
    int32 first_version = get_long();
    interpreter->image_version = first_version;
    if ( readable_format(interpreter->image_version) ) return;
    swap_bytes = true;
    if (fseek(image_file, -sizeof(int32), SEEK_CUR) != 0) {
      perror("seek failed"); fatal();
    }
    interpreter->image_version = get_long();
    if ( readable_format(interpreter->image_version) ) return;

    fatal("cannot read file");

}

int32 Squeak_Image_Reader::get_long() {
  int32 x;
  xfread(&x, sizeof(x), 1, image_file);
  if (swap_bytes) swap_bytes_long(&x);
  return x;
}

bool Squeak_Image_Reader::readable_format(int32 version) {
  /* Check against a magic constant that changes when the image format
     changes. Since the image reading code uses this to detect byte ordering,
     one must avoid version numbers that are invariant under byte reversal. */
  return   version == Pre_Closure_32_Bit_Image_Version
       ||  version == Post_Closure_32_Bit_Image_Version
       ||  version == Post_Closure_With_Reordered_Floats_32_Bit_Image_Version;
}

bool Squeak_Image_Reader::is_cog_image_with_reodered_floats() {
  return interpreter->image_version == Post_Closure_With_Reordered_Floats_32_Bit_Image_Version;
}

void Squeak_Image_Reader::byteSwapByteObjects() {
  fprintf(stdout, "swapping bytes back in byte objects\n");
  for (Chunk* c = (Chunk*)memory;
       (char*)c <  &memory[dataSize]; ) {
    Object* obj = c->object_from_chunk_without_preheader();
    obj->byteSwapIfByteObject();
    c = obj->nextChunk();
  }
  fprintf(stdout, "done swapping bytes back in byte objects\n");
}

# if !Use_Object_Table
class UpdateOop_Closure: public Oop_Closure {
  Multicore_Object_Table* object_table;
public:
  UpdateOop_Closure(Multicore_Object_Table* ot)  : Oop_Closure() { object_table = ot; }
  void value(Oop* p, Object_p) {
    if (p->is_mem()) {
      Object* obj = object_table->object_for(*p);
      *p = obj->as_oop();
      assert_always(p->as_object() == obj);
    }
  }
  virtual const char* class_name(char*) { return "UpdateOop_Closure"; }
};
# endif

void Squeak_Image_Reader::distribute_objects() {
  fprintf(stdout, "distributing objects\n");
  u_int64 start = OS_Interface::get_cycle_count();
  char* base = memory;
  u_int32 total_bytes = dataSize;

  object_oops = (Oop*)malloc(total_bytes);
  bzero(object_oops, total_bytes);

  memory_system->initialize_from_snapshot(dataSize, savedWindowSize, fullScreenFlag, lastHash);

  for (Chunk *c = (Chunk*)base, *nextChunk = NULL;
       (char*)c <  &base[total_bytes];
       c = nextChunk) {
    Object* obj = c->object_from_chunk_without_preheader(); // chunks in memory don't have a preheader
    if (check_many_assertions &&  (char*)obj - memory == (char*)specialObjectsOop.bits() - oldBaseAddr)
      lprintf("about to do specialObjectsOop");
    nextChunk = obj->nextChunk();
    if (!obj->isFreeObject()) {
      obj->do_all_oops_of_object_for_reading_snapshot(this);
      memory_system->ask_cpu_core_to_add_object_from_snapshot_allocating_chunk(oop_for_addr(obj), obj, object_table);
    }
  }

  // Remap specialObjectsOop
  specialObjectsOop = oop_for_oop(specialObjectsOop);

  /* RMOT: Extra pass for updating the pointers && deallocate the object table */
  UpdateOop_Closure uoc(object_table);
  FOR_ALL_RANKS(r) {
    for (int hi = 0; hi<Memory_System::max_num_mutabilities; hi++) {
      Multicore_Object_Heap* heap = memory_system->heaps[r][hi];
      FOR_EACH_OBJECT_IN_HEAP(heap, obj) {
        if (!obj->isFreeObject()) {
          obj->set_backpointer(obj->as_oop());
          obj->do_all_oops_of_object(&uoc,false);
          if(((Oop*)obj->extra_preheader_word())->is_mem())
            fatal("shouldnt occur");
        }
      }
    }
  }
  specialObjectsOop = object_table->object_for(specialObjectsOop)->as_oop();

  object_table->cleanup();
  delete object_table;

  memory_system->finished_adding_objects_from_snapshot();
  free(object_oops);
  fprintf(stdout, "done distributing objects, %lld cycles\n",
    OS_Interface::get_cycle_count() - start);

  interpreter->initialize(specialObjectsOop, false);
}

Oop Squeak_Image_Reader::oop_for_oop(Oop x) {
  return oop_for_relative_addr(x.bits() - (int)oldBaseAddr);
}

Oop Squeak_Image_Reader::oop_for_addr(Object* obj) {
  return oop_for_relative_addr(int(obj) - int(memory));
}

Oop Squeak_Image_Reader::oop_for_relative_addr(int relative_addr) {
  assert(u_int32(relative_addr) < dataSize);
  Oop* addr_in_table = &object_oops[relative_addr / sizeof(Oop)];
  Object* obj = (Object*) &memory[relative_addr];
  if (addr_in_table->bits() == 0) {
    Object_Table* const ot = memory_system->object_table;
    *addr_in_table = ot->allocate_OTE_for_object_in_snapshot(obj);
  }
  return *addr_in_table;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: recfloat.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 16:49:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// includes *******************************************************************

#pragma hdrstop

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDERSUPPLIER_HPP_
#include <com/sun/star/frame/XDispatchRecorderSupplier.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <drafts/com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include <svtools/eitem.hxx>
#include <svtools/generictoolboxcontroller.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>

#include "recfloat.hxx"
#include "dialog.hrc"
#include "sfxresid.hxx"
#include "app.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "viewsh.hxx"
#include "imagemgr.hxx"

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

static rtl::OUString GetLabelFromCommandURL( const rtl::OUString& rCommandURL, const uno::Reference< frame::XFrame >& xFrame )
{
    rtl::OUString aLabel;
    rtl::OUString aModuleIdentifier;
    uno::Reference< container::XNameAccess > xUICommandLabels;
    uno::Reference< lang::XMultiServiceFactory > xServiceManager;
    uno::Reference< container::XNameAccess > xUICommandDescription;
    uno::Reference< drafts::com::sun::star::frame::XModuleManager > xModuleManager;

    static uno::WeakReference< lang::XMultiServiceFactory > xTmpServiceManager;
    static uno::WeakReference< container::XNameAccess >     xTmpNameAccess;
    static uno::WeakReference< drafts::com::sun::star::frame::XModuleManager > xTmpModuleMgr;

    xServiceManager = xTmpServiceManager;
    if ( !xServiceManager.is() )
    {
        xServiceManager = ::comphelper::getProcessServiceFactory();
        xTmpServiceManager = xServiceManager;
    }

    xUICommandDescription = xTmpNameAccess;
    if ( !xUICommandDescription.is() )
    {
        xUICommandDescription = uno::Reference< container::XNameAccess >(
                                    xServiceManager->createInstance(
                                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                            "drafts.com.sun.star.frame.UICommandDescription" ))),
                                    uno::UNO_QUERY );
        xTmpNameAccess = xUICommandDescription;
    }

    xModuleManager = xTmpModuleMgr;
    if ( !xModuleManager.is() )
    {
        xModuleManager = uno::Reference< drafts::com::sun::star::frame::XModuleManager >(
            xServiceManager->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                    "drafts.com.sun.star.frame.ModuleManager" ))),
            uno::UNO_QUERY_THROW );
        xTmpModuleMgr = xModuleManager;
    }

    // Retrieve label from UI command description service
    try
    {
        try
        {
            aModuleIdentifier = xModuleManager->identify( xFrame );
        }
        catch( uno::Exception& )
        {
        }

        if ( xUICommandDescription.is() )
        {
            uno::Any a = xUICommandDescription->getByName( aModuleIdentifier );
            uno::Reference< container::XNameAccess > xUICommands;
            a >>= xUICommandLabels;
        }
    }
    catch ( uno::Exception& )
    {
    }

    if ( xUICommandLabels.is() )
    {
        try
        {
            if ( rCommandURL.getLength() > 0 )
            {
                uno::Sequence< beans::PropertyValue > aPropSeq;
                uno::Any a( xUICommandLabels->getByName( rCommandURL ));
                if ( a >>= aPropSeq )
                {
                    for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ )
                    {
                        if ( aPropSeq[i].Name.equalsAscii( "Label" ))
                        {
                            aPropSeq[i].Value >>= aLabel;
                            break;
                        }
                    }
                }
            }
        }
        catch (uno::Exception& )
        {
        }
    }

    return aLabel;
}

SFX_IMPL_FLOATINGWINDOW( SfxRecordingFloatWrapper_Impl, SID_RECORDING_FLOATWINDOW );

SfxRecordingFloatWrapper_Impl::SfxRecordingFloatWrapper_Impl( Window* pParent ,
                                                USHORT nId ,
                                                SfxBindings* pBind ,
                                                SfxChildWinInfo* pInfo )
                    : SfxChildWindow( pParent , nId )
                    , pBindings( pBind )
{
    pWindow = new SfxRecordingFloat_Impl( pBindings, this, pParent );
    SetWantsFocus( FALSE );
    eChildAlignment = SFX_ALIGN_NOALIGNMENT;
    ( ( SfxFloatingWindow* ) pWindow )->Initialize( pInfo );
}

SfxRecordingFloatWrapper_Impl::~SfxRecordingFloatWrapper_Impl()
{
    SfxBoolItem aItem( FN_PARAM_1, TRUE );
    com::sun::star::uno::Reference< com::sun::star::frame::XDispatchRecorder > xRecorder = pBindings->GetRecorder();
    if ( xRecorder.is() )
        pBindings->GetDispatcher()->Execute( SID_STOP_RECORDING, SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}

sal_Bool SfxRecordingFloatWrapper_Impl::QueryClose()
{
    // asking for recorded macro should be replaced if index access is available!
    BOOL bRet = TRUE;
    com::sun::star::uno::Reference< com::sun::star::frame::XDispatchRecorder > xRecorder = pBindings->GetRecorder();
    if ( xRecorder.is() && xRecorder->getRecordedMacro().getLength() )
    {
        QueryBox aBox( GetWindow(), WB_YES_NO | WB_DEF_NO , String( SfxResId( STR_MACRO_LOSS ) ) );
        aBox.SetText( String( SfxResId(STR_CANCEL_RECORDING) ) );
        bRet = ( aBox.Execute() == RET_YES );
    }

    return bRet;
}

SfxRecordingFloat_Impl::SfxRecordingFloat_Impl(
    SfxBindings* pBindings ,
    SfxChildWindow* pChildWin ,
    Window* pParent )
    : SfxFloatingWindow( pBindings ,
                         pChildWin ,
                         pParent ,
                         SfxResId( SID_RECORDING_FLOATWINDOW ) )
    , pWrapper( pChildWin )
    , aTbx( this, SfxResId(SID_RECORDING_FLOATWINDOW) )
{
    // Retrieve label from helper function
    uno::Reference< frame::XFrame > xFrame = GetBindings().GetActiveFrame();
    rtl::OUString aCommandStr( RTL_CONSTASCII_USTRINGPARAM( ".uno:StopRecording" ));
    aTbx.SetItemText( SID_STOP_RECORDING, GetLabelFromCommandURL( aCommandStr, xFrame ));

    // Determine size of toolbar
    Size aSize = aTbx.CalcWindowSizePixel();
    aTbx.SetPosSizePixel( Point(), aSize );
    SetOutputSizePixel( aSize );

    // create a generic toolbox controller for our internal toolbox
    svt::GenericToolboxController* pController = new svt::GenericToolboxController(
                                                    ::comphelper::getProcessServiceFactory(),
                                                    xFrame,
                                                    &aTbx,
                                                    SID_STOP_RECORDING,
                                                    aCommandStr );
    xStopRecTbxCtrl = uno::Reference< frame::XToolbarController >(
                            static_cast< cppu::OWeakObject* >( pController ),
                        uno::UNO_QUERY );
    uno::Reference< util::XUpdatable > xUpdate( xStopRecTbxCtrl, uno::UNO_QUERY );
    if ( xUpdate.is() )
        xUpdate->update();

    aTbx.SetSelectHdl( LINK( this, SfxRecordingFloat_Impl, Select ) );

    // start recording
    SfxBoolItem aItem( SID_RECORDMACRO, TRUE );
    GetBindings().GetDispatcher()->Execute( SID_RECORDMACRO, SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}

SfxRecordingFloat_Impl::~SfxRecordingFloat_Impl()
{
    try
    {
        if ( xStopRecTbxCtrl.is() )
        {
            uno::Reference< lang::XComponent > xComp( xStopRecTbxCtrl, uno::UNO_QUERY );
            xComp->dispose();
        }
    }
    catch ( uno::Exception& )
    {
    }
}

BOOL SfxRecordingFloat_Impl::Close()
{
    BOOL bRet = SfxFloatingWindow::Close();
    return bRet;
}

void SfxRecordingFloat_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
    SfxFloatingWindow::FillInfo( rInfo );
    rInfo.bVisible = sal_False;
}

void SfxRecordingFloat_Impl::StateChanged( StateChangedType nStateChange )
{
    if ( nStateChange == STATE_CHANGE_INITSHOW )
    {
        SfxViewFrame *pFrame = GetBindings().GetDispatcher_Impl()->GetFrame();
        Window* pEditWin = pFrame->GetViewShell()->GetWindow();

        Point aPoint = pEditWin->OutputToScreenPixel( pEditWin->GetPosPixel() );
        aPoint = GetParent()->ScreenToOutputPixel( aPoint );
        aPoint.X() += 20;
        aPoint.Y() += 10;
        SetPosPixel( aPoint );
    }

    SfxFloatingWindow::StateChanged( nStateChange );
}

IMPL_LINK( SfxRecordingFloat_Impl, Select, ToolBox*, pToolBar )
{
    sal_Int16   nKeyModifier( (sal_Int16)aTbx.GetModifier() );
    if ( xStopRecTbxCtrl.is() )
        xStopRecTbxCtrl->execute( nKeyModifier );

    return 1;
}
<commit_msg>INTEGRATION: CWS removedrafts (1.7.236); FILE MERGED 2005/02/17 14:02:13 cd 1.7.236.1: #i42557# Move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: recfloat.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:59:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// includes *******************************************************************

#pragma hdrstop

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDERSUPPLIER_HPP_
#include <com/sun/star/frame/XDispatchRecorderSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include <svtools/eitem.hxx>
#include <svtools/generictoolboxcontroller.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>

#include "recfloat.hxx"
#include "dialog.hrc"
#include "sfxresid.hxx"
#include "app.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "viewsh.hxx"
#include "imagemgr.hxx"

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

static rtl::OUString GetLabelFromCommandURL( const rtl::OUString& rCommandURL, const uno::Reference< frame::XFrame >& xFrame )
{
    rtl::OUString aLabel;
    rtl::OUString aModuleIdentifier;
    uno::Reference< container::XNameAccess > xUICommandLabels;
    uno::Reference< lang::XMultiServiceFactory > xServiceManager;
    uno::Reference< container::XNameAccess > xUICommandDescription;
    uno::Reference< ::com::sun::star::frame::XModuleManager > xModuleManager;

    static uno::WeakReference< lang::XMultiServiceFactory > xTmpServiceManager;
    static uno::WeakReference< container::XNameAccess >     xTmpNameAccess;
    static uno::WeakReference< ::com::sun::star::frame::XModuleManager > xTmpModuleMgr;

    xServiceManager = xTmpServiceManager;
    if ( !xServiceManager.is() )
    {
        xServiceManager = ::comphelper::getProcessServiceFactory();
        xTmpServiceManager = xServiceManager;
    }

    xUICommandDescription = xTmpNameAccess;
    if ( !xUICommandDescription.is() )
    {
        xUICommandDescription = uno::Reference< container::XNameAccess >(
                                    xServiceManager->createInstance(
                                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                            "com.sun.star.frame.UICommandDescription" ))),
                                    uno::UNO_QUERY );
        xTmpNameAccess = xUICommandDescription;
    }

    xModuleManager = xTmpModuleMgr;
    if ( !xModuleManager.is() )
    {
        xModuleManager = uno::Reference< ::com::sun::star::frame::XModuleManager >(
            xServiceManager->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                    "com.sun.star.frame.ModuleManager" ))),
            uno::UNO_QUERY_THROW );
        xTmpModuleMgr = xModuleManager;
    }

    // Retrieve label from UI command description service
    try
    {
        try
        {
            aModuleIdentifier = xModuleManager->identify( xFrame );
        }
        catch( uno::Exception& )
        {
        }

        if ( xUICommandDescription.is() )
        {
            uno::Any a = xUICommandDescription->getByName( aModuleIdentifier );
            uno::Reference< container::XNameAccess > xUICommands;
            a >>= xUICommandLabels;
        }
    }
    catch ( uno::Exception& )
    {
    }

    if ( xUICommandLabels.is() )
    {
        try
        {
            if ( rCommandURL.getLength() > 0 )
            {
                uno::Sequence< beans::PropertyValue > aPropSeq;
                uno::Any a( xUICommandLabels->getByName( rCommandURL ));
                if ( a >>= aPropSeq )
                {
                    for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ )
                    {
                        if ( aPropSeq[i].Name.equalsAscii( "Label" ))
                        {
                            aPropSeq[i].Value >>= aLabel;
                            break;
                        }
                    }
                }
            }
        }
        catch (uno::Exception& )
        {
        }
    }

    return aLabel;
}

SFX_IMPL_FLOATINGWINDOW( SfxRecordingFloatWrapper_Impl, SID_RECORDING_FLOATWINDOW );

SfxRecordingFloatWrapper_Impl::SfxRecordingFloatWrapper_Impl( Window* pParent ,
                                                USHORT nId ,
                                                SfxBindings* pBind ,
                                                SfxChildWinInfo* pInfo )
                    : SfxChildWindow( pParent , nId )
                    , pBindings( pBind )
{
    pWindow = new SfxRecordingFloat_Impl( pBindings, this, pParent );
    SetWantsFocus( FALSE );
    eChildAlignment = SFX_ALIGN_NOALIGNMENT;
    ( ( SfxFloatingWindow* ) pWindow )->Initialize( pInfo );
}

SfxRecordingFloatWrapper_Impl::~SfxRecordingFloatWrapper_Impl()
{
    SfxBoolItem aItem( FN_PARAM_1, TRUE );
    com::sun::star::uno::Reference< com::sun::star::frame::XDispatchRecorder > xRecorder = pBindings->GetRecorder();
    if ( xRecorder.is() )
        pBindings->GetDispatcher()->Execute( SID_STOP_RECORDING, SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}

sal_Bool SfxRecordingFloatWrapper_Impl::QueryClose()
{
    // asking for recorded macro should be replaced if index access is available!
    BOOL bRet = TRUE;
    com::sun::star::uno::Reference< com::sun::star::frame::XDispatchRecorder > xRecorder = pBindings->GetRecorder();
    if ( xRecorder.is() && xRecorder->getRecordedMacro().getLength() )
    {
        QueryBox aBox( GetWindow(), WB_YES_NO | WB_DEF_NO , String( SfxResId( STR_MACRO_LOSS ) ) );
        aBox.SetText( String( SfxResId(STR_CANCEL_RECORDING) ) );
        bRet = ( aBox.Execute() == RET_YES );
    }

    return bRet;
}

SfxRecordingFloat_Impl::SfxRecordingFloat_Impl(
    SfxBindings* pBindings ,
    SfxChildWindow* pChildWin ,
    Window* pParent )
    : SfxFloatingWindow( pBindings ,
                         pChildWin ,
                         pParent ,
                         SfxResId( SID_RECORDING_FLOATWINDOW ) )
    , pWrapper( pChildWin )
    , aTbx( this, SfxResId(SID_RECORDING_FLOATWINDOW) )
{
    // Retrieve label from helper function
    uno::Reference< frame::XFrame > xFrame = GetBindings().GetActiveFrame();
    rtl::OUString aCommandStr( RTL_CONSTASCII_USTRINGPARAM( ".uno:StopRecording" ));
    aTbx.SetItemText( SID_STOP_RECORDING, GetLabelFromCommandURL( aCommandStr, xFrame ));

    // Determine size of toolbar
    Size aSize = aTbx.CalcWindowSizePixel();
    aTbx.SetPosSizePixel( Point(), aSize );
    SetOutputSizePixel( aSize );

    // create a generic toolbox controller for our internal toolbox
    svt::GenericToolboxController* pController = new svt::GenericToolboxController(
                                                    ::comphelper::getProcessServiceFactory(),
                                                    xFrame,
                                                    &aTbx,
                                                    SID_STOP_RECORDING,
                                                    aCommandStr );
    xStopRecTbxCtrl = uno::Reference< frame::XToolbarController >(
                            static_cast< cppu::OWeakObject* >( pController ),
                        uno::UNO_QUERY );
    uno::Reference< util::XUpdatable > xUpdate( xStopRecTbxCtrl, uno::UNO_QUERY );
    if ( xUpdate.is() )
        xUpdate->update();

    aTbx.SetSelectHdl( LINK( this, SfxRecordingFloat_Impl, Select ) );

    // start recording
    SfxBoolItem aItem( SID_RECORDMACRO, TRUE );
    GetBindings().GetDispatcher()->Execute( SID_RECORDMACRO, SFX_CALLMODE_SYNCHRON, &aItem, 0L );
}

SfxRecordingFloat_Impl::~SfxRecordingFloat_Impl()
{
    try
    {
        if ( xStopRecTbxCtrl.is() )
        {
            uno::Reference< lang::XComponent > xComp( xStopRecTbxCtrl, uno::UNO_QUERY );
            xComp->dispose();
        }
    }
    catch ( uno::Exception& )
    {
    }
}

BOOL SfxRecordingFloat_Impl::Close()
{
    BOOL bRet = SfxFloatingWindow::Close();
    return bRet;
}

void SfxRecordingFloat_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
    SfxFloatingWindow::FillInfo( rInfo );
    rInfo.bVisible = sal_False;
}

void SfxRecordingFloat_Impl::StateChanged( StateChangedType nStateChange )
{
    if ( nStateChange == STATE_CHANGE_INITSHOW )
    {
        SfxViewFrame *pFrame = GetBindings().GetDispatcher_Impl()->GetFrame();
        Window* pEditWin = pFrame->GetViewShell()->GetWindow();

        Point aPoint = pEditWin->OutputToScreenPixel( pEditWin->GetPosPixel() );
        aPoint = GetParent()->ScreenToOutputPixel( aPoint );
        aPoint.X() += 20;
        aPoint.Y() += 10;
        SetPosPixel( aPoint );
    }

    SfxFloatingWindow::StateChanged( nStateChange );
}

IMPL_LINK( SfxRecordingFloat_Impl, Select, ToolBox*, pToolBar )
{
    sal_Int16   nKeyModifier( (sal_Int16)aTbx.GetModifier() );
    if ( xStopRecTbxCtrl.is() )
        xStopRecTbxCtrl->execute( nKeyModifier );

    return 1;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_desktop.hxx"

#include "sal/config.h"

#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/xml/dom/XElement.hpp"
#include "com/sun/star/xml/dom/XNode.hpp"
#include "com/sun/star/xml/dom/XNodeList.hpp"
#include "rtl/bootstrap.hxx"
#include "rtl/string.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "tools/string.hxx"

#include "deployment.hrc"
#include "dp_resource.h"

#include "dp_dependencies.hxx"
#include "dp_descriptioninfoset.hxx"
#include "dp_version.hxx"

namespace {

namespace css = ::com::sun::star;

static char const xmlNamespace[] =
    "http://openoffice.org/extensions/description/2006";

bool satisfiesMinimalVersion(::rtl::OUString const & version) {
    ::rtl::OUString v(
        RTL_CONSTASCII_USTRINGPARAM(
            "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("version")
            ":Version:OOOPackageVersion}"));
    ::rtl::Bootstrap::expandMacros(v);
    return ::dp_misc::compareVersions(v, version) != ::dp_misc::LESS;
}

}

namespace dp_misc {

namespace Dependencies {

css::uno::Sequence< css::uno::Reference< css::xml::dom::XElement > >
check(::dp_misc::DescriptionInfoset const & infoset) {
    css::uno::Reference< css::xml::dom::XNodeList > deps(
        infoset.getDependencies());
    ::sal_Int32 n = deps->getLength();
    css::uno::Sequence< css::uno::Reference< css::xml::dom::XElement > >
        unsatisfied(n);
    ::sal_Int32 unsat = 0;
    for (::sal_Int32 i = 0; i < n; ++i) {
        static char const minimalVersion[] = "OpenOffice.org-minimal-version";
        css::uno::Reference< css::xml::dom::XElement > e(
            deps->item(i), css::uno::UNO_QUERY_THROW);
        bool sat = false;
        if (e->getNamespaceURI().equalsAsciiL(
                RTL_CONSTASCII_STRINGPARAM(xmlNamespace))
            && e->getTagName().equalsAsciiL(
                RTL_CONSTASCII_STRINGPARAM(minimalVersion)))
        {
            sat = satisfiesMinimalVersion(
                e->getAttribute(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value"))));
        } else if (e->getNamespaceURI().equalsAsciiL(
                       RTL_CONSTASCII_STRINGPARAM(xmlNamespace))
                   && e->getTagName().equalsAsciiL(
                       RTL_CONSTASCII_STRINGPARAM(
                           "OpenOffice.org-maximal-version")))
        {
            ::rtl::OUString v(
                RTL_CONSTASCII_USTRINGPARAM(
                    "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("version")
                    ":Version:OOOBaseVersion}"));
            ::rtl::Bootstrap::expandMacros(v);
            sat =
                ::dp_misc::compareVersions(
                    v,
                    e->getAttribute(
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value"))))
                != ::dp_misc::GREATER;
        } else if (e->hasAttributeNS(
                       ::rtl::OUString(
                           RTL_CONSTASCII_USTRINGPARAM(xmlNamespace)),
                       ::rtl::OUString(
                           RTL_CONSTASCII_USTRINGPARAM(minimalVersion))))
        {
            sat = satisfiesMinimalVersion(
                e->getAttributeNS(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(xmlNamespace)),
                    ::rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM(minimalVersion))));
        }
        if (!sat) {
            unsatisfied[unsat++] = e;
        }
    }
    unsatisfied.realloc(unsat);
    return unsatisfied;
}

::rtl::OUString getErrorText( css::uno::Reference< css::xml::dom::XElement > const & dependency )
{
    ::rtl::OUString sReason;
    ::rtl::OUString sValue;
    ::rtl::OUString sVersion(RTL_CONSTASCII_USTRINGPARAM("%VERSION"));

    if ( dependency->getNamespaceURI().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( xmlNamespace ) )
         && dependency->getTagName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "OpenOffice.org-minimal-version" ) ) )
    {
        sValue = dependency->getAttribute( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "value" ) ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MIN)) );
    }
    else if ( dependency->getNamespaceURI().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( xmlNamespace ) )
              && dependency->getTagName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "OpenOffice.org-maximal-version" ) ) )
    {
        sValue = dependency->getAttribute( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value") ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MAX)) );
    }
    else if ( dependency->hasAttributeNS( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( xmlNamespace ) ),
                                          ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OpenOffice.org-minimal-version" ))))
    {
        sValue = dependency->getAttributeNS( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( xmlNamespace ) ),
                                             ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OpenOffice.org-minimal-version" ) ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MIN)) );
    }
    else
        return ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_UNKNOWN)) );

    if ( sValue.getLength() == 0 )
        sValue = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_UNKNOWN)) );

    sal_Int32 nPos = sReason.indexOf( sVersion );
    if ( nPos >= 0 )
        sReason = sReason.replaceAt( nPos, sVersion.getLength(), sValue );
    return sReason;
}

}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>refactor to remove some redundancy<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_desktop.hxx"

#include "sal/config.h"

#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/xml/dom/XElement.hpp"
#include "com/sun/star/xml/dom/XNode.hpp"
#include "com/sun/star/xml/dom/XNodeList.hpp"
#include "rtl/bootstrap.hxx"
#include "rtl/string.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "tools/string.hxx"

#include "deployment.hrc"
#include "dp_resource.h"

#include "dp_dependencies.hxx"
#include "dp_descriptioninfoset.hxx"
#include "dp_version.hxx"

namespace {

namespace css = ::com::sun::star;

static char const xmlNamespace[] =
    "http://openoffice.org/extensions/description/2006";

bool
lcl_versionIsNot(dp_misc::Order i_eOrder, ::rtl::OUString const& i_rVersion)
{
    ::rtl::OUString aVersion(
        RTL_CONSTASCII_USTRINGPARAM(
            "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("version")
            ":Version:OOOPackageVersion}"));
    ::rtl::Bootstrap::expandMacros(aVersion);
    return ::dp_misc::compareVersions(aVersion, i_rVersion) != i_eOrder;
}

bool satisfiesMinimalVersion(::rtl::OUString const& i_rVersion)
{
    return lcl_versionIsNot(dp_misc::LESS, i_rVersion);
}

bool satisfiesMaximalVersion(::rtl::OUString const& i_rVersion)
{
    return lcl_versionIsNot(dp_misc::GREATER, i_rVersion);
}

}

namespace dp_misc {

namespace Dependencies {

css::uno::Sequence< css::uno::Reference< css::xml::dom::XElement > >
check(::dp_misc::DescriptionInfoset const & infoset) {
    css::uno::Reference< css::xml::dom::XNodeList > deps(
        infoset.getDependencies());
    ::sal_Int32 n = deps->getLength();
    css::uno::Sequence< css::uno::Reference< css::xml::dom::XElement > >
        unsatisfied(n);
    ::sal_Int32 unsat = 0;
    for (::sal_Int32 i = 0; i < n; ++i) {
        static rtl::OUString const minimalVersion(
                RTL_CONSTASCII_USTRINGPARAM("OpenOffice.org-minimal-version"));
        css::uno::Reference< css::xml::dom::XElement > e(
            deps->item(i), css::uno::UNO_QUERY_THROW);
        bool sat = false;
        if (e->getNamespaceURI().equalsAsciiL(
                RTL_CONSTASCII_STRINGPARAM(xmlNamespace))
            && (e->getTagName() == minimalVersion))
        {
            sat = satisfiesMinimalVersion(
                e->getAttribute(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value"))));
        } else if (e->getNamespaceURI().equalsAsciiL(
                       RTL_CONSTASCII_STRINGPARAM(xmlNamespace))
                   && e->getTagName().equalsAsciiL(
                       RTL_CONSTASCII_STRINGPARAM(
                           "OpenOffice.org-maximal-version")))
        {
            sat = satisfiesMaximalVersion(
                    e->getAttribute(
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value"))));
        } else if (e->hasAttributeNS(
                       ::rtl::OUString(
                           RTL_CONSTASCII_USTRINGPARAM(xmlNamespace)),
                        minimalVersion))
        {
            sat = satisfiesMinimalVersion(
                e->getAttributeNS(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(xmlNamespace)),
                    minimalVersion));
        }
        if (!sat) {
            unsatisfied[unsat++] = e;
        }
    }
    unsatisfied.realloc(unsat);
    return unsatisfied;
}

::rtl::OUString getErrorText( css::uno::Reference< css::xml::dom::XElement > const & dependency )
{
    ::rtl::OUString sReason;
    ::rtl::OUString sValue;
    ::rtl::OUString sVersion(RTL_CONSTASCII_USTRINGPARAM("%VERSION"));

    if ( dependency->getNamespaceURI().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( xmlNamespace ) )
         && dependency->getTagName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "OpenOffice.org-minimal-version" ) ) )
    {
        sValue = dependency->getAttribute( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "value" ) ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MIN)) );
    }
    else if ( dependency->getNamespaceURI().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( xmlNamespace ) )
              && dependency->getTagName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "OpenOffice.org-maximal-version" ) ) )
    {
        sValue = dependency->getAttribute( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value") ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MAX)) );
    }
    else if ( dependency->hasAttributeNS( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( xmlNamespace ) ),
                                          ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OpenOffice.org-minimal-version" ))))
    {
        sValue = dependency->getAttributeNS( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( xmlNamespace ) ),
                                             ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OpenOffice.org-minimal-version" ) ) );
        sReason = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_MIN)) );
    }
    else
        return ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_UNKNOWN)) );

    if ( sValue.getLength() == 0 )
        sValue = ::rtl::OUString( ::String(::dp_misc::getResId(RID_DEPLYOMENT_DEPENDENCIES_UNKNOWN)) );

    sal_Int32 nPos = sReason.indexOf( sVersion );
    if ( nPos >= 0 )
        sReason = sReason.replaceAt( nPos, sVersion.getLength(), sValue );
    return sReason;
}

}

}

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


<commit_before>//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like traditional Unix "nm",
// that is, it prints out the names of symbols in a bytecode file,
// along with some information about each symbol.
//
// This "nm" does not print symbols' addresses. It supports many of
// the features of GNU "nm", including its different output formats.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/Bytecode/Reader.h"
#include "Support/CommandLine.h"
#include <cctype>

using namespace llvm;

namespace {
  enum OutputFormatTy { bsd, sysv, posix };
  cl::opt<OutputFormatTy>
  OutputFormat("format",
       cl::desc("Specify output format"),
         cl::values(clEnumVal(bsd,   "BSD format"),
                    clEnumVal(sysv,  "System V format"),
                    clEnumVal(posix, "POSIX.2 format"), 0), cl::init(bsd));
  cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
                          cl::aliasopt(OutputFormat));

  cl::list<std::string>
  InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
                 cl::ZeroOrMore);

  cl::opt<bool> UndefinedOnly("undefined-only",
                              cl::desc("Show only undefined symbols"));
  cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
                           cl::aliasopt(UndefinedOnly));

  cl::opt<bool> DefinedOnly("defined-only",
                            cl::desc("Show only defined symbols"));

  cl::opt<bool> ExternalOnly("extern-only",
                             cl::desc("Show only external symbols"));
  cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
                          cl::aliasopt(ExternalOnly));

  cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
  cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));

  bool MultipleFiles = false;

  std::string ToolName;
};

char TypeCharForSymbol (GlobalValue &GV) {
  if (GV.isExternal ())                                     return 'U';
  if (GV.hasLinkOnceLinkage ())                             return 'C';
  if (GV.hasWeakLinkage ())                                 return 'W';
  if (isa<Function> (GV) && GV.hasInternalLinkage ())       return 't';
  if (isa<Function> (GV))                                   return 'T';
  if (isa<GlobalVariable> (GV) && GV.hasInternalLinkage ()) return 'd';
  if (isa<GlobalVariable> (GV))                             return 'D';
                                                            return '?';
}

void DumpSymbolNameForGlobalValue (GlobalValue &GV) {
  const std::string SymbolAddrStr = "        "; // Not used yet...
  char TypeChar = TypeCharForSymbol (GV);
  if ((TypeChar != 'U') && UndefinedOnly)
    return;
  if ((TypeChar == 'U') && DefinedOnly)
    return;
  if (GV.hasInternalLinkage () && ExternalOnly)
    return;
  if (OutputFormat == posix) {
    std::cout << GV.getName () << " " << TypeCharForSymbol (GV) << " "
              << SymbolAddrStr << "\n";
  } else if (OutputFormat == bsd) {
    std::cout << SymbolAddrStr << " " << TypeCharForSymbol (GV) << " "
              << GV.getName () << "\n";
  } else if (OutputFormat == sysv) {
    std::string PaddedName (GV.getName ());
    while (PaddedName.length () < 20)
      PaddedName += " ";
    std::cout << PaddedName << "|" << SymbolAddrStr << "|   "
              << TypeCharForSymbol (GV)
              << "  |                  |      |     |\n";
  }
}

void DumpSymbolNamesFromModule (Module *M) {
  std::for_each (M->begin (), M->end (), DumpSymbolNameForGlobalValue);
  std::for_each (M->gbegin (), M->gend (), DumpSymbolNameForGlobalValue);
}

void DumpSymbolNamesFromFile (std::string &Filename) {
  std::string ErrorMessage;
  Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
  if (Result) {
    if (OutputFormat == posix && MultipleFiles) {
      std::cout << Filename << ":\n";
    } else if (OutputFormat == bsd && MultipleFiles) {
      std::cout << "\n" << Filename << ":\n";
    } else if (OutputFormat == sysv) {
      std::cout << "\n\nSymbols from " << Filename << ":\n\n"
                << "Name                  Value   Class        Type"
                << "         Size   Line  Section\n";
    }
    DumpSymbolNamesFromModule (Result);
  } else {
    std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
  }
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm symbol table dumper\n");
  ToolName = argv[0];
  if (BSDFormat) OutputFormat = bsd;
  if (POSIXFormat) OutputFormat = posix;

  switch (InputFilenames.size()) {
  case 0: InputFilenames.push_back("-");
  case 1: break;
  default: MultipleFiles = true;
  }

  std::for_each (InputFilenames.begin (), InputFilenames.end (),
                 DumpSymbolNamesFromFile);
  return 0;
}
<commit_msg>Include Support/FileUtilities.h. Print module identifier in DumpSymbolNamesFromModule(). In DumpSymbolNamesFromFile(), check whether it is an archive or a bytecode  file, and call the corresponding reader function (ParseBytecodeFile or  ReadArchiveFile). Unconditionally set MultipleFiles for archives. Fixes PR117.<commit_after>//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like traditional Unix "nm",
// that is, it prints out the names of symbols in a bytecode file,
// along with some information about each symbol.
//
// This "nm" does not print symbols' addresses. It supports many of
// the features of GNU "nm", including its different output formats.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/Bytecode/Reader.h"
#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include <cctype>

using namespace llvm;

namespace {
  enum OutputFormatTy { bsd, sysv, posix };
  cl::opt<OutputFormatTy>
  OutputFormat("format",
       cl::desc("Specify output format"),
         cl::values(clEnumVal(bsd,   "BSD format"),
                    clEnumVal(sysv,  "System V format"),
                    clEnumVal(posix, "POSIX.2 format"), 0), cl::init(bsd));
  cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
                          cl::aliasopt(OutputFormat));

  cl::list<std::string>
  InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
                 cl::ZeroOrMore);

  cl::opt<bool> UndefinedOnly("undefined-only",
                              cl::desc("Show only undefined symbols"));
  cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
                           cl::aliasopt(UndefinedOnly));

  cl::opt<bool> DefinedOnly("defined-only",
                            cl::desc("Show only defined symbols"));

  cl::opt<bool> ExternalOnly("extern-only",
                             cl::desc("Show only external symbols"));
  cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"),
                          cl::aliasopt(ExternalOnly));

  cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd"));
  cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix"));

  bool MultipleFiles = false;

  std::string ToolName;
};

char TypeCharForSymbol (GlobalValue &GV) {
  if (GV.isExternal ())                                     return 'U';
  if (GV.hasLinkOnceLinkage ())                             return 'C';
  if (GV.hasWeakLinkage ())                                 return 'W';
  if (isa<Function> (GV) && GV.hasInternalLinkage ())       return 't';
  if (isa<Function> (GV))                                   return 'T';
  if (isa<GlobalVariable> (GV) && GV.hasInternalLinkage ()) return 'd';
  if (isa<GlobalVariable> (GV))                             return 'D';
                                                            return '?';
}

void DumpSymbolNameForGlobalValue (GlobalValue &GV) {
  const std::string SymbolAddrStr = "        "; // Not used yet...
  char TypeChar = TypeCharForSymbol (GV);
  if ((TypeChar != 'U') && UndefinedOnly)
    return;
  if ((TypeChar == 'U') && DefinedOnly)
    return;
  if (GV.hasInternalLinkage () && ExternalOnly)
    return;
  if (OutputFormat == posix) {
    std::cout << GV.getName () << " " << TypeCharForSymbol (GV) << " "
              << SymbolAddrStr << "\n";
  } else if (OutputFormat == bsd) {
    std::cout << SymbolAddrStr << " " << TypeCharForSymbol (GV) << " "
              << GV.getName () << "\n";
  } else if (OutputFormat == sysv) {
    std::string PaddedName (GV.getName ());
    while (PaddedName.length () < 20)
      PaddedName += " ";
    std::cout << PaddedName << "|" << SymbolAddrStr << "|   "
              << TypeCharForSymbol (GV)
              << "  |                  |      |     |\n";
  }
}

void DumpSymbolNamesFromModule (Module *M) {
  const std::string &Filename = M->getModuleIdentifier ();
  if (OutputFormat == posix && MultipleFiles) {
    std::cout << Filename << ":\n";
  } else if (OutputFormat == bsd && MultipleFiles) {
    std::cout << "\n" << Filename << ":\n";
  } else if (OutputFormat == sysv) {
    std::cout << "\n\nSymbols from " << Filename << ":\n\n"
              << "Name                  Value   Class        Type"
              << "         Size   Line  Section\n";
  }
  std::for_each (M->begin (), M->end (), DumpSymbolNameForGlobalValue);
  std::for_each (M->gbegin (), M->gend (), DumpSymbolNameForGlobalValue);
}

void DumpSymbolNamesFromFile (std::string &Filename) {
  std::string ErrorMessage;
  if (IsBytecode (Filename)) {
    Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
    if (Result) {
      DumpSymbolNamesFromModule (Result);
    } else {
      std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
    }
  } else if (IsArchive (Filename)) {
    std::vector<Module *> Modules;
    if (ReadArchiveFile (Filename, Modules, &ErrorMessage))
      std::cerr << ToolName << ": " << Filename << ": "
                << ErrorMessage << "\n";
    MultipleFiles = true;
    std::for_each (Modules.begin (), Modules.end (), DumpSymbolNamesFromModule);
  }
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm symbol table dumper\n");
  ToolName = argv[0];
  if (BSDFormat) OutputFormat = bsd;
  if (POSIXFormat) OutputFormat = posix;

  switch (InputFilenames.size()) {
  case 0: InputFilenames.push_back("-");
  case 1: break;
  default: MultipleFiles = true;
  }

  std::for_each (InputFilenames.begin (), InputFilenames.end (),
                 DumpSymbolNamesFromFile);
  return 0;
}
<|endoftext|>