<commit_before>#include "device.h"
#include "udevnotifier.h"
#include "udevnotifier_p.h"

#include <libudev.h>
#include <monitor.h>
#include <poll.h>
#include"webcam.h"
#include <QtCore/QDebug>

namespace UdevNotifier {

UdevNotifier::UdevNotifier(const QStringList &groups, QObject *parent)
    : QThread(parent)
    , d(new UdevNotifierPrivate)
{
    // register types needed for signals and slots
    qRegisterMetaType<UdevNotifier::Action>("UdevNotifier::Action");
    qRegisterMetaType<Device>("Device");

    d->groups = groups;
    d->udev = udev_new();

    if (!d->udev) {
        printf("Can't create udev\n");
        exit(1);
    }

    // TODO group monitoring goes here
    d->udevMonitor = udev_monitor_new_from_netlink(d->udev, "udev");

    if (d->udevMonitor) {
        // start receiving events
        udev_monitor_enable_receiving(d->udevMonitor);
    } else {
        qDebug("FAILED UDEv MONITOR");
    }

    d->display = XOpenDisplay(NULL);
    d->window = RootWindow(d->display, DefaultScreen(d->display));
    d->screenRes = XRRGetScreenResources(d->display, d->window);

    int errorBaseIgnored = 0;
    XRRQueryExtension(d->display, &d->xrandrEventBase, &errorBaseIgnored);

    XRRSelectInput(d->display, DefaultRootWindow(d->display), RROutputChangeNotifyMask);
}

UdevNotifier::~UdevNotifier()
{
    XRRFreeScreenResources(d->screenRes);
    XCloseDisplay(d->display);
    delete d;
}

UdevNotifier::Action UdevNotifier::actionFromString(const QString &actionStr)
{
    qDebug("[UdevNotifier::actionFromString]");
    qDebug() << actionStr;

    if (actionStr == QLatin1String("add")) {
        return ADD;
    } else if (actionStr == QLatin1String("remove")) {
        return REMOVE;
    } else {
        // not handled at the moment
        return NONE;
    }
}

void UdevNotifier::scan()
{
    struct udev *udev = d->udev;
    struct udev_enumerate *enumerate = udev_enumerate_new(udev);

    // XXX --- old udev display detection code
    // udev_enumerate_add_match_subsystem(enumerate, "drm");
    // udev_enumerate_add_match_sysname(enumerate, "card[0-9]-*");
    // udev_enumerate_scan_devices(enumerate);

    // struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
    // struct udev_list_entry *dev_list_entry;
    // struct udev_device *dev;

    // udev_list_entry_foreach(dev_list_entry, devices) {
    //     const char *path;

    //     path = udev_list_entry_get_name(dev_list_entry);
    //     dev = udev_device_new_from_syspath(udev, path);

    //     if (!dev) {
    //         continue;
    //     }

    //     qDebug("[UdevNotifier::scan] Found display: %s", udev_device_get_sysname(dev));
    //     qDebug("[UdevNotifier::scan] enabled? %s", udev_device_get_sysattr_value(dev, "enabled"));

    //     if (QString(udev_device_get_sysattr_value(dev, "enabled")) == QLatin1String("enabled")) {
    //         Q_EMIT udevEvent(ADD, new Monitor(dev));
    //     }

    //     udev_device_unref(dev);
    // }

    // udev_enumerate_unref(enumerate);

    // enumerate = udev_enumerate_new(udev);
    // XXX --- old udev display detection code

    udev_enumerate_add_match_subsystem(enumerate, "video4linux");
    udev_enumerate_scan_devices(enumerate);

    struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
    struct udev_list_entry *dev_list_entry;
    struct udev_device *dev;

    udev_list_entry_foreach(dev_list_entry, devices) {
        const char *path;

        path = udev_list_entry_get_name(dev_list_entry);
        dev = udev_device_new_from_syspath(udev, path);

        if (!dev) {
            continue;
        }

        qDebug("[UdevNotifier::scan] Found webcam: %s", udev_device_get_sysattr_value(dev, "name"));
        qDebug("[UdevNotifier::scan] node %s", udev_device_get_devnode(dev));

        Q_EMIT udevEvent(ADD, new Webcam(dev));

        udev_device_unref(dev);
    }

    for (int i = 0; i < d->screenRes->noutput; ++i) {
        XRROutputInfo *outputInfo = XRRGetOutputInfo(d->display, d->screenRes, d->screenRes->outputs[i]);

        qDebug() << "[UdevNotifier::scan] found output: " << outputInfo->name;
        if (outputInfo->connection == 0) {
            qDebug() << "[UdevNotifier::scan] output connected, sending signal...";
            Q_EMIT udevEvent(ADD, new Monitor(outputInfo->name));
        }

        XRRFreeOutputInfo(outputInfo);
    }

    udev_enumerate_unref(enumerate);
}

void UdevNotifier::run()
{
    qDebug("[UdevNotifier::run]");
    d->exit = false;

    while (!d->exit) {
       // create the poll item
        pollfd items[1];
        items[0].fd = udev_monitor_get_fd(d->udevMonitor);
        items[0].events = POLLIN;
        items[0].revents = 0;

        // while there are hotplug events to process
        while (poll(items, 1, 50) > 0) {
            // XXX
          //  qDebug() << "hotplug[ " << items[0].revents << " ]";

            // receive the relevant device
            udev_device* dev = udev_monitor_receive_device(d->udevMonitor);
            if (!dev) {
                // error receiving device, skip it
                qDebug("error rcv device. Skip");
                continue;
            }

            //qDebug() << "hotplug[" << udev_device_get_action(dev) << "] " << udev_device_get_devnode(dev) << "," << udev_device_get_subsystem(dev) << "," << udev_device_get_devtype(dev);
            // emit the found device
            // if (udev_device_get_devtype(dev) == QLatin1String("drm_minor")) {
            //     Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Monitor(dev));
            // }

            if (udev_device_get_subsystem(dev) == QLatin1String("video4linux")) {
                Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Webcam(dev));
            }
            // XXX
         //   qDebug("-> done");

            // clear the revents
            items[0].revents = 0;
        }

        while (XPending(d->display)) {
            XEvent e;
            XNextEvent(d->display, &e);

            if (e.type - d->xrandrEventBase == RRNotify) {
                qDebug() << "[UdevNotifier] output change event";

                XRROutputChangeNotifyEvent *ev = (XRROutputChangeNotifyEvent*)&e;
                XRROutputInfo *outputInfo = XRRGetOutputInfo(d->display, d->screenRes, ev->output);
                if (outputInfo) {
                    qDebug() << "[UdevNotifier] output:" << outputInfo->name;
                    qDebug() << "[UdevNotifier] output status:" << (outputInfo->connection == 0 ? "connected"
                                                                                : outputInfo->connection == 1 ? "disconnected"
                                                                                : "unknown");

                    UdevNotifier::Action action = outputInfo->connection == 0 ? ADD : REMOVE;
                    Q_EMIT udevEvent(action, new Monitor(outputInfo->name));

                    XRRFreeOutputInfo(outputInfo);
                }
            }
        }
    }

  //  qDebug("-> OUT");
}

void UdevNotifier::stop()
{
    d->exit = true;
}

}
<commit_msg>Don't delete the udev device when creating the UdevNotifier::Webcam object<commit_after>#include "device.h"
#include "udevnotifier.h"
#include "udevnotifier_p.h"

#include <libudev.h>
#include <monitor.h>
#include <poll.h>
#include"webcam.h"
#include <QtCore/QDebug>

namespace UdevNotifier {

UdevNotifier::UdevNotifier(const QStringList &groups, QObject *parent)
    : QThread(parent)
    , d(new UdevNotifierPrivate)
{
    // register types needed for signals and slots
    qRegisterMetaType<UdevNotifier::Action>("UdevNotifier::Action");
    qRegisterMetaType<Device>("Device");

    d->groups = groups;
    d->udev = udev_new();

    if (!d->udev) {
        printf("Can't create udev\n");
        exit(1);
    }

    // TODO group monitoring goes here
    d->udevMonitor = udev_monitor_new_from_netlink(d->udev, "udev");

    if (d->udevMonitor) {
        // start receiving events
        udev_monitor_enable_receiving(d->udevMonitor);
    } else {
        qDebug("FAILED UDEv MONITOR");
    }

    d->display = XOpenDisplay(NULL);
    d->window = RootWindow(d->display, DefaultScreen(d->display));
    d->screenRes = XRRGetScreenResources(d->display, d->window);

    int errorBaseIgnored = 0;
    XRRQueryExtension(d->display, &d->xrandrEventBase, &errorBaseIgnored);

    XRRSelectInput(d->display, DefaultRootWindow(d->display), RROutputChangeNotifyMask);
}

UdevNotifier::~UdevNotifier()
{
    XRRFreeScreenResources(d->screenRes);
    XCloseDisplay(d->display);
    delete d;
}

UdevNotifier::Action UdevNotifier::actionFromString(const QString &actionStr)
{
    qDebug("[UdevNotifier::actionFromString]");
    qDebug() << actionStr;

    if (actionStr == QLatin1String("add")) {
        return ADD;
    } else if (actionStr == QLatin1String("remove")) {
        return REMOVE;
    } else {
        // not handled at the moment
        return NONE;
    }
}

void UdevNotifier::scan()
{
    struct udev *udev = d->udev;
    struct udev_enumerate *enumerate = udev_enumerate_new(udev);

    // XXX --- old udev display detection code
    // udev_enumerate_add_match_subsystem(enumerate, "drm");
    // udev_enumerate_add_match_sysname(enumerate, "card[0-9]-*");
    // udev_enumerate_scan_devices(enumerate);

    // struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
    // struct udev_list_entry *dev_list_entry;
    // struct udev_device *dev;

    // udev_list_entry_foreach(dev_list_entry, devices) {
    //     const char *path;

    //     path = udev_list_entry_get_name(dev_list_entry);
    //     dev = udev_device_new_from_syspath(udev, path);

    //     if (!dev) {
    //         continue;
    //     }

    //     qDebug("[UdevNotifier::scan] Found display: %s", udev_device_get_sysname(dev));
    //     qDebug("[UdevNotifier::scan] enabled? %s", udev_device_get_sysattr_value(dev, "enabled"));

    //     if (QString(udev_device_get_sysattr_value(dev, "enabled")) == QLatin1String("enabled")) {
    //         Q_EMIT udevEvent(ADD, new Monitor(dev));
    //     }

    //     udev_device_unref(dev);
    // }

    // udev_enumerate_unref(enumerate);

    // enumerate = udev_enumerate_new(udev);
    // XXX --- old udev display detection code

    udev_enumerate_add_match_subsystem(enumerate, "video4linux");
    udev_enumerate_scan_devices(enumerate);

    struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
    struct udev_list_entry *dev_list_entry;
    struct udev_device *dev;

    udev_list_entry_foreach(dev_list_entry, devices) {
        const char *path;

        path = udev_list_entry_get_name(dev_list_entry);
        dev = udev_device_new_from_syspath(udev, path);

        if (!dev) {
            continue;
        }

        qDebug("[UdevNotifier::scan] Found webcam: %s", udev_device_get_sysattr_value(dev, "name"));
        qDebug("[UdevNotifier::scan] node %s", udev_device_get_devnode(dev));

        Q_EMIT udevEvent(ADD, new Webcam(dev));

        // removed the unref of the 'udev_device' struct as the Webcam object handles it's deletion
//        udev_device_unref(dev);
    }

    for (int i = 0; i < d->screenRes->noutput; ++i) {
        XRROutputInfo *outputInfo = XRRGetOutputInfo(d->display, d->screenRes, d->screenRes->outputs[i]);

        qDebug() << "[UdevNotifier::scan] found output: " << outputInfo->name;
        if (outputInfo->connection == 0) {
            qDebug() << "[UdevNotifier::scan] output connected, sending signal...";
            Q_EMIT udevEvent(ADD, new Monitor(outputInfo->name));
        }

        XRRFreeOutputInfo(outputInfo);
    }

    udev_enumerate_unref(enumerate);
}

void UdevNotifier::run()
{
    qDebug("[UdevNotifier::run]");
    d->exit = false;

    while (!d->exit) {
       // create the poll item
        pollfd items[1];
        items[0].fd = udev_monitor_get_fd(d->udevMonitor);
        items[0].events = POLLIN;
        items[0].revents = 0;

        // while there are hotplug events to process
        while (poll(items, 1, 50) > 0) {
            // XXX
          //  qDebug() << "hotplug[ " << items[0].revents << " ]";

            // receive the relevant device
            udev_device* dev = udev_monitor_receive_device(d->udevMonitor);
            if (!dev) {
                // error receiving device, skip it
                qDebug("error rcv device. Skip");
                continue;
            }

            //qDebug() << "hotplug[" << udev_device_get_action(dev) << "] " << udev_device_get_devnode(dev) << "," << udev_device_get_subsystem(dev) << "," << udev_device_get_devtype(dev);
            // emit the found device
            // if (udev_device_get_devtype(dev) == QLatin1String("drm_minor")) {
            //     Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Monitor(dev));
            // }

            if (udev_device_get_subsystem(dev) == QLatin1String("video4linux")) {
                Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Webcam(dev));
            }
            // XXX
         //   qDebug("-> done");

            // clear the revents
            items[0].revents = 0;
        }

        while (XPending(d->display)) {
            XEvent e;
            XNextEvent(d->display, &e);

            if (e.type - d->xrandrEventBase == RRNotify) {
                qDebug() << "[UdevNotifier] output change event";

                XRROutputChangeNotifyEvent *ev = (XRROutputChangeNotifyEvent*)&e;
                XRROutputInfo *outputInfo = XRRGetOutputInfo(d->display, d->screenRes, ev->output);
                if (outputInfo) {
                    qDebug() << "[UdevNotifier] output:" << outputInfo->name;
                    qDebug() << "[UdevNotifier] output status:" << (outputInfo->connection == 0 ? "connected"
                                                                                : outputInfo->connection == 1 ? "disconnected"
                                                                                : "unknown");

                    UdevNotifier::Action action = outputInfo->connection == 0 ? ADD : REMOVE;
                    Q_EMIT udevEvent(action, new Monitor(outputInfo->name));

                    XRRFreeOutputInfo(outputInfo);
                }
            }
        }
    }

  //  qDebug("-> OUT");
}

void UdevNotifier::stop()
{
    d->exit = true;
}

}
<|endoftext|>


<commit_before>/* RLTK (RogueLike Tool Kit) 1.00
 * Copyright (c) 2016-Present, Bracket Productions.
 * Licensed under the LGPL - see LICENSE file.
 *
 * Provides support for complicated GUIs.
 */

#pragma once

#include <SFML/Graphics.hpp>
#include <functional>
#include <unordered_map>
#include <memory>
#include <vector>

#include "virtual_terminal.hpp"

namespace rltk {

/*
 * Base type for retained-mode GUI controls.
 */
struct gui_control_t {
	virtual void render(virtual_terminal * console)=0;
};

/*
 * A renderable layer. You won't use this type directly.
 */
struct layer_t {
	/* This specialization is for generic consoles */
	layer_t(const int X, const int Y, const int W, const int H, std::string font_name, std::function<void(layer_t *,int,int)> resize_fun, bool render_background=true) :
		x(X), y(Y), w(W), h(H), font(font_name), resize_func(resize_fun), has_background(render_background)
	{
		console = std::make_unique<virtual_terminal>(font_name, x, y, has_background);
	    console->resize_pixels(w, h);
	}

	/* This specialization is for owner-draw panels */
	layer_t(const int X, const int Y, const int W, const int H, std::function<void(layer_t *,int,int)> resize_fun, std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_fun) :
		x(X), y(Y), w(W), h(H), resize_func(resize_fun), owner_draw_func(owner_draw_fun)
	{
	}

	int x;
	int y;
	int w;
	int h;
	std::string font;

	std::function<void(layer_t *,int,int)> resize_func;
	std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_func;
	std::unique_ptr<virtual_terminal> console;
	bool has_background;
	std::vector<gui_control_t> controls;
	std::unique_ptr<sf::RenderTexture> backing; // Used for owner-draw layers

	void make_owner_draw_backing();
	void on_resize(const int width, const int height);
	void render(sf::RenderWindow &window);
};

/*
 * The overall GUI - holds layers and handles render calls. Access via rltk::gui
 */
struct gui_t {
public:
	gui_t(const int w, const int h) : screen_width(w), screen_height(h) {}
	void on_resize(const int w, const int h);
	void render(sf::RenderWindow &window);

	// Specialization for adding console layers
	void add_layer(const int handle, const int X, const int Y, const int W, const int H, std::string font_name, std::function<void(layer_t *,int,int)> resize_fun, bool has_background=true, int order=-1);

	// Specialization for adding owner-draw layers
	void add_owner_layer(const int handle, const int X, const int Y, const int W, const int H, std::function<void(layer_t *,int,int)> resize_fun, std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_fun, int order=-1);
	void delete_layer(const int handle);
	layer_t * get_layer(const int handle);

private:
	int screen_width;
	int screen_height;
	int render_order = 0;

	std::unordered_map<int, layer_t> layers;
};

}<commit_msg>More commenting.<commit_after>/* RLTK (RogueLike Tool Kit) 1.00
 * Copyright (c) 2016-Present, Bracket Productions.
 * Licensed under the LGPL - see LICENSE file.
 *
 * Provides support for complicated GUIs.
 */

#pragma once

#include <SFML/Graphics.hpp>
#include <functional>
#include <unordered_map>
#include <memory>
#include <vector>

#include "virtual_terminal.hpp"

namespace rltk {

/*
 * Base type for retained-mode GUI controls.
 */
struct gui_control_t {
	virtual void render(virtual_terminal * console)=0;
};

/*
 * A renderable layer. You won't use this type directly.
 */
struct layer_t {
	/* This specialization is for generic consoles */
	layer_t(const int X, const int Y, const int W, const int H, std::string font_name, std::function<void(layer_t *,int,int)> resize_fun, bool render_background=true) :
		x(X), y(Y), w(W), h(H), font(font_name), resize_func(resize_fun), has_background(render_background)
	{
		console = std::make_unique<virtual_terminal>(font_name, x, y, has_background);
	    console->resize_pixels(w, h);
	}

	/* This specialization is for owner-draw panels */
	layer_t(const int X, const int Y, const int W, const int H, std::function<void(layer_t *,int,int)> resize_fun, std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_fun) :
		x(X), y(Y), w(W), h(H), resize_func(resize_fun), owner_draw_func(owner_draw_fun)
	{
	}

	// The bounding box of the layer
	int x;
	int y;
	int w;
	int h;

	// Font tag - used only if there is a console
	std::string font;

	// Callbacks:
	// resize_func is called when the window changes size. It receives the WINDOW dimensions - it's up to you to
	// determine how to lay things out.
	std::function<void(layer_t *,int,int)> resize_func;

	// Passed through to virtual console; if false then no background will be rendered (helpful for text overlays)
	bool has_background;

	// owner_draw_func is used only for owner draw layers, and is called at render time.
	std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_func;

	// If a console is present, this is it.
	std::unique_ptr<virtual_terminal> console;

	// If retained-mode controls are present, they are in here.
	std::vector<gui_control_t> controls;

	// Used for owner-draw layers. We need to render to texture and then compose to:
	// a) permit threading, should you so wish (so there is a single composite run)
	// b) allow the future "effects" engine to run.
	std::unique_ptr<sf::RenderTexture> backing;

	// Used by the owner-draw code to ensure that a texture is available for use
	void make_owner_draw_backing();

	// Called by GUI when a resize event occurs.
	void on_resize(const int width, const int height);

	// Called by GUI when a render event occurs.
	void render(sf::RenderWindow &window);
};

/*
 * The overall GUI - holds layers and handles render calls. Access via rltk::gui
 */
struct gui_t {
public:
	gui_t(const int w, const int h) : screen_width(w), screen_height(h) {}
	void on_resize(const int w, const int h);
	void render(sf::RenderWindow &window);

	// Specialization for adding console layers
	void add_layer(const int handle, const int X, const int Y, const int W, const int H, std::string font_name, std::function<void(layer_t *,int,int)> resize_fun, bool has_background=true, int order=-1);

	// Specialization for adding owner-draw layers
	void add_owner_layer(const int handle, const int X, const int Y, const int W, const int H, std::function<void(layer_t *,int,int)> resize_fun, std::function<void(layer_t *, sf::RenderTexture &)> owner_draw_fun, int order=-1);
	void delete_layer(const int handle);
	layer_t * get_layer(const int handle);

private:
	int screen_width;
	int screen_height;
	int render_order = 0;

	std::unordered_map<int, layer_t> layers;
};

}<|endoftext|>


<commit_before><commit_msg>Simplifies SbMatrix::multLeft() and SbMatrix::multRight().<commit_after><|endoftext|>


<commit_before>/*

Copyright (c) 2015, Project OSRM contributors
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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ROUND_TRIP_HPP
#define ROUND_TRIP_HPP

#include "plugin_base.hpp"

#include "../algorithms/object_encoder.hpp"
#include "../data_structures/query_edge.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/json_descriptor.hpp"
#include "../util/json_renderer.hpp"
#include "../util/make_unique.hpp"
#include "../util/string_util.hpp"
#include "../util/timing_util.hpp"
#include "../util/simple_logger.hpp"

#include <osrm/json_container.hpp>

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>
#include <limits>

template <class DataFacadeT> class RoundTripPlugin final : public BasePlugin
{
  private:
    std::string descriptor_string;
    DataFacadeT *facade;
    std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

  public:
    explicit RoundTripPlugin(DataFacadeT *facade)
        : descriptor_string("trip"), facade(facade)
    {
        search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
    }

    const std::string GetDescriptor() const override final { return descriptor_string; }

    int HandleRequest(const RouteParameters &route_parameters,
                      osrm::json::Object &json_result) override final
    {
        // check if all inputs are coordinates
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            return 400;
        }
        const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());

        // find phantom nodes for all input coords
        PhantomNodeArray phantom_node_vector(route_parameters.coordinates.size());
        for (const auto i : osrm::irange<std::size_t>(0, route_parameters.coordinates.size()))
        {
            // if client hints are helpful, encode hints
            if (checksum_OK && i < route_parameters.hints.size() &&
                !route_parameters.hints[i].empty())
            {
                PhantomNode current_phantom_node;
                ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
                if (current_phantom_node.is_valid(facade->GetNumberOfNodes()))
                {
                    phantom_node_vector[i].emplace_back(std::move(current_phantom_node));
                    continue;
                }
            }
            facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
                                                            phantom_node_vector[i], 1);
            if (phantom_node_vector[i].size() > 1)
            {
                phantom_node_vector[i].pop_back();
            }

            BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
            // SimpleLogger().Write() << "In loop 1";
        }

        // compute the distance table of all phantom nodes
        std::shared_ptr<std::vector<EdgeWeight>> result_table =
            search_engine_ptr->distance_table(phantom_node_vector);

        if (!result_table)
        {
            return 400;
        }

        // SimpleLogger().Write() << "Distance Table Computed";

        //////////////////////////////////////////////////////////////////////////////////////////////////
        // START GREEDY NEAREST NEIGHBOUR HERE
        // 1. grab a random location and mark as starting point
        // 2. find the nearest unvisited neighbour, set it as the current location and mark as visited
        // 3. repeat 2 until there is no unvisited location
        // 4. return route back to starting point
        // 5. compute route
        // 6. DONE!
        //////////////////////////////////////////////////////////////////////////////////////////////////

        const auto number_of_locations = phantom_node_vector.size();
        InternalRouteResult raw_route;
        // 1. START WITH LOCATION 0 AS START POINT
        int curr_node = 0;
        std::vector<int> loc_permutation(number_of_locations, -1);
        loc_permutation[0] = 0;
        std::vector<bool> visited(number_of_locations, false);
        visited[0] = true;

        // SimpleLogger().Write() << "Added an initial via";
        // SimpleLogger().Write() << "Started from location 0";
        // SimpleLogger().Write() << "Number of locs: " << number_of_locations;

        PhantomNodes subroute;
        // 3. REPEAT FOR EVERY UNVISITED NODE
        for(int stopover = 1; stopover < number_of_locations; ++stopover)
        {
            auto row_begin_iterator = result_table->begin() + (curr_node * number_of_locations);
            auto row_end_iterator = result_table->begin() + ((curr_node + 1) * number_of_locations);
            int min_dist = std::numeric_limits<int>::max();
            int min_id = -1;

            // 2. FIND NEAREST NEIGHBOUR
            for (auto it = row_begin_iterator; it != row_end_iterator; ++it) {
                auto index = std::distance(row_begin_iterator, it);

                if (!visited[index] && *it < min_dist)
                {
                    min_dist = *it;
                    min_id = index;
                }

                // SimpleLogger().Write() << "In loop 2";
            }
            // SimpleLogger().Write() << "After loop 2";

            // SimpleLogger().Write() << "visited size is " << visited.size();

            if (min_id == -1)
            {
                SimpleLogger().Write() << "ALARM: NO ROUTE!";
                break;
            }
            else
            {
                loc_permutation[min_id] = stopover;
                visited[min_id] = true;
                subroute = PhantomNodes{phantom_node_vector[curr_node][0], phantom_node_vector[min_id][0]};
                raw_route.segment_end_coordinates.emplace_back(subroute);

                // SimpleLogger().Write() << "Found location " << curr_node;
                // SimpleLogger().Write() << "Added a looped via" << curr_node << " " << min_id;

                curr_node = min_id;

                // SimpleLogger().Write() << "In loop 3";
            }
        }

        // 4. ROUTE BACK TO STARTING POINT
        // SimpleLogger().Write() << "Added a final via";
        subroute = PhantomNodes{raw_route.segment_end_coordinates.back().target_phantom, phantom_node_vector[0][0]};
        raw_route.segment_end_coordinates.emplace_back(subroute);

        // 5. COMPUTE ROUTE
        search_engine_ptr->shortest_path(raw_route.segment_end_coordinates,
                                             route_parameters.uturns, raw_route);

        // return result to json
        std::unique_ptr<BaseDescriptor<DataFacadeT>> descriptor;
        descriptor = osrm::make_unique<JSONDescriptor<DataFacadeT>>(facade);

        descriptor->SetConfig(route_parameters);
        descriptor->Run(raw_route, json_result);

        osrm::json::Array json_loc_permutation;
        json_loc_permutation.values.insert(json_loc_permutation.values.end(), loc_permutation.begin(), loc_permutation.end());
        json_result.values["loc_permutation"] = json_loc_permutation;

        return 200;
    }

};

#endif // ROUND_TRIP_HPP
<commit_msg>fix bugs and add comments<commit_after>/*

Copyright (c) 2015, Project OSRM contributors
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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ROUND_TRIP_HPP
#define ROUND_TRIP_HPP

#include "plugin_base.hpp"

#include "../algorithms/object_encoder.hpp"
#include "../data_structures/query_edge.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/json_descriptor.hpp"
#include "../util/json_renderer.hpp"
#include "../util/make_unique.hpp"
#include "../util/string_util.hpp"
#include "../util/timing_util.hpp"
#include "../util/simple_logger.hpp"

#include <osrm/json_container.hpp>

#include <cstdlib>

#include <algorithm>
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>
#include <limits>

template <class DataFacadeT> class RoundTripPlugin final : public BasePlugin
{
  private:
    std::string descriptor_string;
    DataFacadeT *facade;
    std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;

  public:
    explicit RoundTripPlugin(DataFacadeT *facade)
        : descriptor_string("trip"), facade(facade)
    {
        search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
    }

    const std::string GetDescriptor() const override final { return descriptor_string; }

    int HandleRequest(const RouteParameters &route_parameters,
                      osrm::json::Object &json_result) override final
    {
        // check if all inputs are coordinates
        if (!check_all_coordinates(route_parameters.coordinates))
        {
            return 400;
        }
        const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());

        // find phantom nodes for all input coords
        PhantomNodeArray phantom_node_vector(route_parameters.coordinates.size());
        for (const auto i : osrm::irange<std::size_t>(0, route_parameters.coordinates.size()))
        {
            // if client hints are helpful, encode hints
            if (checksum_OK && i < route_parameters.hints.size() &&
                !route_parameters.hints[i].empty())
            {
                PhantomNode current_phantom_node;
                ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
                if (current_phantom_node.is_valid(facade->GetNumberOfNodes()))
                {
                    phantom_node_vector[i].emplace_back(std::move(current_phantom_node));
                    continue;
                }
            }
            facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
                                                            phantom_node_vector[i], 1);
            if (phantom_node_vector[i].size() > 1)
            {
                phantom_node_vector[i].erase(phantom_node_vector[i].begin());
            }
            BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
        }

        // compute the distance table of all phantom nodes
        std::shared_ptr<std::vector<EdgeWeight>> result_table =
            search_engine_ptr->distance_table(phantom_node_vector);

        if (!result_table)
        {
            return 400;
        }

        //////////////////////////////////////////////////////////////////////////////////////////////////
        // START GREEDY NEAREST NEIGHBOUR HERE
        // 1. grab a random location and mark as starting point
        // 2. find the nearest unvisited neighbour, set it as the current location and mark as visited
        // 3. repeat 2 until there is no unvisited location
        // 4. return route back to starting point
        // 5. compute route
        // 6. repeat 1-5 with different starting points and choose iteration with shortest trip
        // 6. DONE!
        //////////////////////////////////////////////////////////////////////////////////////////////////

        const auto number_of_locations = phantom_node_vector.size();
        // min_route is the shortest route found
        InternalRouteResult min_route;
        min_route.shortest_path_length = std::numeric_limits<int>::max();
        // min_loc_permutation stores the order of visited locations of the shortest route
        std::vector<int> min_loc_permutation;

        // is_lonely_island[i] indicates whether node i is a node that cannot be reached from other nodes
        //  1 means that node i is a lonely island
        //  0 means that it is not known for node i
        // -1 means that node i is not a lonely island but a reachable, connected node
        std::vector<int> is_lonely_island(number_of_locations, 0);
        int count_unreachables;

        // ALWAYS START AT ANOTHER STARTING POINT
        for(int start_node = 0; start_node < number_of_locations; ++start_node)
        {

            if (is_lonely_island[start_node] >= 0)
            {
                // if node is a lonely island it is an unsuitable node to start from and shall be skipped
                if (is_lonely_island[start_node])
                    continue;
                count_unreachables = 0;
                auto start_dist_begin = result_table->begin() + (start_node * number_of_locations);
                auto start_dist_end = result_table->begin() + ((start_node + 1) * number_of_locations);
                for (auto it2 = start_dist_begin; it2 != start_dist_end; ++it2) {
                    if (*it2 == 0 || *it2 == std::numeric_limits<int>::max()) {
                        ++count_unreachables;
                    }
                }
                if (count_unreachables >= number_of_locations) {
                    is_lonely_island[start_node] = 1;
                    continue;
                }
            }

            int curr_node = start_node;
            is_lonely_island[curr_node] = -1;
            InternalRouteResult raw_route;
            //TODO: Should we always use the same vector or does it not matter at all because of loop scope?
            std::vector<int> loc_permutation(number_of_locations, -1);
            loc_permutation[start_node] = 0;
            // visited[i] indicates whether node i was already visited by the salesman
            std::vector<bool> visited(number_of_locations, false);
            visited[start_node] = true;

            PhantomNodes viapoint;
            // 3. REPEAT FOR EVERY UNVISITED NODE
            for(int via_point = 1; via_point < number_of_locations; ++via_point)
            {
                int min_dist = std::numeric_limits<int>::max();
                int min_id = -1;

                // 2. FIND NEAREST NEIGHBOUR
                auto row_begin_iterator = result_table->begin() + (curr_node * number_of_locations);
                auto row_end_iterator = result_table->begin() + ((curr_node + 1) * number_of_locations);
                for (auto it = row_begin_iterator; it != row_end_iterator; ++it) {
                    auto index = std::distance(row_begin_iterator, it);
                    if (is_lonely_island[index] < 1 && !visited[index] && *it < min_dist)
                    {
                        min_dist = *it;
                        min_id = index;
                    }
                }
                // in case there was no unvisited and reachable node found, it means that all remaining (unvisited) nodes must be lonely islands
                if (min_id == -1)
                {
                    for(int loc = 0; loc < visited.size(); ++loc) {
                        if (!visited[loc]) {
                            is_lonely_island[loc] = 1;
                        }
                    }
                    break;
                }
                // set the nearest unvisited location as the next via_point
                else
                {
                    is_lonely_island[min_id] = -1;
                    loc_permutation[min_id] = via_point;
                    visited[min_id] = true;
                    viapoint = PhantomNodes{phantom_node_vector[curr_node][0], phantom_node_vector[min_id][0]};
                    raw_route.segment_end_coordinates.emplace_back(viapoint);
                    curr_node = min_id;
                }
            }

            // 4. ROUTE BACK TO STARTING POINT
            viapoint = PhantomNodes{raw_route.segment_end_coordinates.back().target_phantom, phantom_node_vector[start_node][0]};
            raw_route.segment_end_coordinates.emplace_back(viapoint);

            // 5. COMPUTE ROUTE
            search_engine_ptr->shortest_path(raw_route.segment_end_coordinates, route_parameters.uturns, raw_route);
            // SimpleLogger().Write() << "Route starting at " << start_node << " with length " << raw_route.shortest_path_length;

            // check round trip with this starting point is shorter than the shortest round trip found till now
            if (raw_route.shortest_path_length < min_route.shortest_path_length) {
                min_route = raw_route;
                min_loc_permutation = loc_permutation;
            }
        }

        SimpleLogger().Write() << "Shortest route " << min_route.shortest_path_length;

        // return result to json
        std::unique_ptr<BaseDescriptor<DataFacadeT>> descriptor;
        descriptor = osrm::make_unique<JSONDescriptor<DataFacadeT>>(facade);

        descriptor->SetConfig(route_parameters);
        descriptor->Run(min_route, json_result);

        osrm::json::Array json_loc_permutation;
        json_loc_permutation.values.insert(json_loc_permutation.values.end(), min_loc_permutation.begin(), min_loc_permutation.end());
        json_result.values["loc_permutation"] = json_loc_permutation;

        return 200;
    }

};

#endif // ROUND_TRIP_HPP
<|endoftext|>


<commit_before>#ifndef TEST_VALID_PALINDROME_HPP
#define TEST_VALID_PALINDROME_HPP

#include <boost/test/unit_test.hpp>

#include "algorithms/strings/valid_palindrome.hpp"

BOOST_AUTO_TEST_CASE(test_valpal_empty_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome(std::string()));
    BOOST_CHECK(true == solution.isPalindrome(" "));
}

BOOST_AUTO_TEST_CASE(test_valpal_simple_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome("a"));
    BOOST_CHECK(true == solution.isPalindrome("aBa"));
    BOOST_CHECK(true == solution.isPalindrome("abba"));
    BOOST_CHECK(true == solution.isPalindrome(" a1,!"));
    BOOST_CHECK(true == solution.isPalindrome("a. "));
    BOOST_CHECK(true == solution.isPalindrome(".,"));
}

BOOST_AUTO_TEST_CASE(test_valpal_not_palindrome)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(false == solution.isPalindrome("race a car"));
    BOOST_CHECK(false == solution.isPalindrome("abac"));
    BOOST_CHECK(false == solution.isPalindrome("0P"));
}

BOOST_AUTO_TEST_CASE(test_valpal_complex_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome("A man, a plan, a canal: Panama"));
}

#endif // TEST_VALID_PALINDROME_HPP
<commit_msg>Fix test case for valid palindrom algorithm<commit_after>#ifndef TEST_VALID_PALINDROME_HPP
#define TEST_VALID_PALINDROME_HPP

#include <boost/test/unit_test.hpp>

#include "algorithms/strings/valid_palindrome.hpp"

BOOST_AUTO_TEST_CASE(test_valpal_empty_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome(std::string()));
    BOOST_CHECK(true == solution.isPalindrome(" "));
}

BOOST_AUTO_TEST_CASE(test_valpal_simple_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome("a"));
    BOOST_CHECK(true == solution.isPalindrome("aBa"));
    BOOST_CHECK(true == solution.isPalindrome("abba"));
    BOOST_CHECK(true == solution.isPalindrome("a. "));
    BOOST_CHECK(true == solution.isPalindrome(".,"));
}

BOOST_AUTO_TEST_CASE(test_valpal_not_palindrome)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(false == solution.isPalindrome("race a car"));
    BOOST_CHECK(false == solution.isPalindrome("abac"));
    BOOST_CHECK(false == solution.isPalindrome("0P"));
    BOOST_CHECK(false == solution.isPalindrome(" a1,!"));
}

BOOST_AUTO_TEST_CASE(test_valpal_complex_strings)
{
    ValidPalindrome::Solution solution;
    BOOST_CHECK(true == solution.isPalindrome("A man, a plan, a canal: Panama"));
}

#endif // TEST_VALID_PALINDROME_HPP
<|endoftext|>


<commit_before>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>

using namespace swift;
using namespace Lowering;

STATISTIC(NumFuncLinked, "Number of SIL functions linked");

//===----------------------------------------------------------------------===//
//                               Linker Helpers
//===----------------------------------------------------------------------===//

/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
  if (Mode == LinkingMode::LinkNone)
    return false;

  // If F is a declaration, first deserialize it.
  if (F->isExternalDeclaration()) {
    auto *NewFn = Loader->lookupSILFunction(F);

    if (!NewFn || NewFn->isExternalDeclaration())
      return false;

    F = NewFn;
  }

  ++NumFuncLinked;

  // Try to transitively deserialize everything referenced by this
  // function.
  Worklist.push_back(F);
  process();

  // Since we successfully processed at least one function, return true.
  return true;
}

/// Deserialize the given VTable all SIL the VTable transitively references.
bool SILLinkerVisitor::linkInVTable(ClassDecl *D) {
  // Attempt to lookup the Vtbl from the SILModule.
  SILVTable *Vtbl = Mod.lookUpVTable(D);

  // If the SILModule does not have the VTable, attempt to deserialize the
  // VTable. If we fail to do that as well, bail.
  if (!Vtbl || !(Vtbl = Loader->lookupVTable(D->getName())))
    return false;

  // Ok we found our VTable. Visit each function referenced by the VTable. If
  // any of the functions are external declarations, add them to the worklist
  // for processing.
  bool Result = false;
  for (auto P : Vtbl->getEntries()) {
    if (P.Implementation->isExternalDeclaration()) {
      Result = true;
      addFunctionToWorklist(P.Implementation);
    }
  }
  return Result;
}

//===----------------------------------------------------------------------===//
//                                  Visitors
//===----------------------------------------------------------------------===//

bool SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
  bool performFuncDeserialization = false;

  if (auto sig = AI->getCallee()->getType().castTo<SILFunctionType>()
                   ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(AI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
  bool performFuncDeserialization = false;

  if (auto sig = TAI->getCallee()->getType().castTo<SILFunctionType>()
                   ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(TAI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
  bool performFuncDeserialization = false;

  if (auto sig = PAI->getCallee()->getType().castTo<SILFunctionType>()
                    ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(PAI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
  // Needed to handle closures which are no longer applied, but are left
  // behind as dead code. This shouldn't happen, but if it does don't get into
  // an inconsistent state.
  SILFunction *Callee = FRI->getReferencedFunction();

  if (isLinkAll() ||
      hasSharedVisibility(Callee->getLinkage())) {
    addFunctionToWorklist(FRI->getReferencedFunction());
    return true;
  }

  return false;
}

// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
                                               ProtocolConformanceRef c) {
  if (!c.isConcrete())
    return false;
  auto conformance = c.getConcrete()->getRootNormalConformance();
  return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
    && isa<ClangModuleUnit>(conformance->getDeclContext()
                                       ->getModuleScopeContext());
}

bool SILLinkerVisitor::visitProtocolConformance(
    ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
  // If an abstract protocol conformance was passed in, just return false.
  if (ref.isAbstract())
    return false;

  bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);

  // Otherwise try and lookup a witness table for C.
  auto C = ref.getConcrete();

  if (!VisitedConformances.insert(C).second)
    return false;

  SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);

  // If we don't find any witness table for the conformance, bail and return
  // false.
  if (!WT) {
    Mod.createWitnessTableDeclaration(
        C, getLinkageForProtocolConformance(
               C->getRootNormalConformance(), NotForDefinition));

    // Adding the declaration may allow us to now deserialize the body.
    // Force the body if we must deserialize this witness table.
    if (mustDeserialize) {
      WT = Mod.lookUpWitnessTable(C, true);
      assert(WT && WT->isDefinition()
             && "unable to deserialize witness table when we must?!");
    } else {
      return false;
    }
  }

  // If the looked up witness table is a declaration, there is nothing we can
  // do here. Just bail and return false.
  if (WT->isDeclaration())
    return false;

  bool performFuncDeserialization = false;

  auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
    // Formally all conformances referenced by a used conformance are used.
    // However, eagerly visiting them all at this point leads to a large blowup
    // in the amount of SIL we read in. For optimization purposes we can defer
    // reading in most conformances until we need them for devirtualization.
    // However, we *must* pull in shared clang-importer-derived conformances
    // we potentially use, since we may not otherwise have a local definition.
    if (mustDeserializeProtocolConformance(Mod, c))
      performFuncDeserialization |= visitProtocolConformance(c, None);
  };

  // For each entry in the witness table...
  for (auto &E : WT->getEntries()) {
    switch (E.getKind()) {
    // If the entry is a witness method...
    case SILWitnessTable::WitnessKind::Method: {
      // And we are only interested in deserializing a specific requirement
      // and don't have that requirement, don't deserialize this method.
      if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
        continue;

      // The witness could be removed by dead function elimination.
      if (!E.getMethodWitness().Witness)
        continue;

      // Otherwise if it is the requirement we are looking for or we just want
      // to deserialize everything, add the function to the list of functions
      // to deserialize.
      performFuncDeserialization = true;
      addFunctionToWorklist(E.getMethodWitness().Witness);
      break;
    }

    // If the entry is a related witness table, see whether we need to
    // eagerly deserialize it.
    case SILWitnessTable::WitnessKind::BaseProtocol: {
      auto baseConformance = E.getBaseProtocolWitness().Witness;
      maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
      break;
    }
    case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
      auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
      maybeVisitRelatedConformance(assocConformance);
      break;
    }

    case SILWitnessTable::WitnessKind::AssociatedType:
    case SILWitnessTable::WitnessKind::Invalid:
      break;
    }
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitApplySubstitutions(const SubstitutionMap &subs) {
  bool performFuncDeserialization = false;

  for (auto &reqt : subs.getGenericSignature()->getRequirements()) {
    switch (reqt.getKind()) {
    case RequirementKind::Conformance: {
      auto conformance = subs.lookupConformance(
          reqt.getFirstType()->getCanonicalType(),
          cast<ProtocolDecl>(reqt.getSecondType()->getAnyNominal()))
        .getValue();

      // Formally all conformances referenced in a function application are
      // used. However, eagerly visiting them all at this point leads to a
      // large blowup in the amount of SIL we read in, and we aren't very
      // systematic about laziness. For optimization purposes we can defer
      // reading in most conformances until we need them for devirtualization.
      // However, we *must* pull in shared clang-importer-derived conformances
      // we potentially use, since we may not otherwise have a local definition.
      if (mustDeserializeProtocolConformance(Mod, conformance)) {
        performFuncDeserialization |=
                                    visitProtocolConformance(conformance, None);
      }
      break;
    }
    case RequirementKind::Layout:
    case RequirementKind::SameType:
    case RequirementKind::Superclass:
      break;
    }
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitInitExistentialAddrInst(
    InitExistentialAddrInst *IEI) {
  // Link in all protocol conformances that this touches.
  //
  // TODO: There might be a two step solution where the init_existential_inst
  // causes the witness table to be brought in as a declaration and then the
  // protocol method inst causes the actual deserialization. For now we are
  // not going to be smart about this to enable avoiding any issues with
  // visiting the open_existential_addr/witness_method before the
  // init_existential_inst.
  bool performFuncDeserialization = false;
  for (ProtocolConformanceRef C : IEI->getConformances()) {
    performFuncDeserialization |=
        visitProtocolConformance(C, Optional<SILDeclRef>());
  }
  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitInitExistentialRefInst(
    InitExistentialRefInst *IERI) {
  // Link in all protocol conformances that this touches.
  //
  // TODO: There might be a two step solution where the init_existential_inst
  // causes the witness table to be brought in as a declaration and then the
  // protocol method inst causes the actual deserialization. For now we are
  // not going to be smart about this to enable avoiding any issues with
  // visiting the protocol_method before the init_existential_inst.
  bool performFuncDeserialization = false;
  for (ProtocolConformanceRef C : IERI->getConformances()) {
    performFuncDeserialization |=
        visitProtocolConformance(C, Optional<SILDeclRef>());
  }
  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
  if (!isLinkAll())
    return false;

  // Grab the class decl from the alloc ref inst.
  ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
  if (!D)
    return false;

  return linkInVTable(D);
}

bool SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
  if (!isLinkAll())
    return false;

  CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
  ClassDecl *C = instTy.getClassOrBoundGenericClass();
  if (!C)
    return false;

  return linkInVTable(C);
}

//===----------------------------------------------------------------------===//
//                             Top Level Routine
//===----------------------------------------------------------------------===//

// Main loop of the visitor. Called by one of the other *visit* methods.
bool SILLinkerVisitor::process() {
  // Process everything transitively referenced by one of the functions in the
  // worklist.
  bool Result = false;
  while (!Worklist.empty()) {
    auto *Fn = Worklist.pop_back_val();

    if (Fn->getModule().isSerialized()) {
      // If the containing module has been serialized,
      // Remove The Serialized state (if any)
      //  This allows for more optimizations
      Fn->setSerialized(IsSerialized_t::IsNotSerialized);
    }

    DEBUG(llvm::dbgs() << "Process imports in function: "
                       << Fn->getName() << "\n");

    for (auto &BB : *Fn) {
      for (auto &I : BB) {
        // Should we try linking?
        if (visit(&I)) {
          for (auto *F : FunctionDeserializationWorklist) {

            DEBUG(llvm::dbgs() << "Imported function: "
                               << F->getName() << "\n");
            F->setBare(IsBare);

            if (F->isExternalDeclaration()) {
              if (auto *NewFn = Loader->lookupSILFunction(F)) {
                if (NewFn->isExternalDeclaration())
                  continue;

                NewFn->verify();
                Worklist.push_back(NewFn);
                Result = true;

                ++NumFuncLinked;
              }
            }
          }
          FunctionDeserializationWorklist.clear();
        } else {
          assert(FunctionDeserializationWorklist.empty() &&
                 "Worklist should "
                 "always be empty if visit does not return true.");
        }
      }
    }
  }

  // If we return true, we deserialized at least one function.
  return Result;
}
<commit_msg>SIL Linker: Remove redundant code from linkInVTable()<commit_after>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>

using namespace swift;
using namespace Lowering;

STATISTIC(NumFuncLinked, "Number of SIL functions linked");

//===----------------------------------------------------------------------===//
//                               Linker Helpers
//===----------------------------------------------------------------------===//

/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
  if (Mode == LinkingMode::LinkNone)
    return false;

  // If F is a declaration, first deserialize it.
  if (F->isExternalDeclaration()) {
    auto *NewFn = Loader->lookupSILFunction(F);

    if (!NewFn || NewFn->isExternalDeclaration())
      return false;

    F = NewFn;
  }

  ++NumFuncLinked;

  // Try to transitively deserialize everything referenced by this
  // function.
  Worklist.push_back(F);
  process();

  // Since we successfully processed at least one function, return true.
  return true;
}

/// Deserialize the given VTable all SIL the VTable transitively references.
bool SILLinkerVisitor::linkInVTable(ClassDecl *D) {
  // Attempt to lookup the Vtbl from the SILModule.
  SILVTable *Vtbl = Mod.lookUpVTable(D);
  if (!Vtbl)
    return false;

  // Ok we found our VTable. Visit each function referenced by the VTable. If
  // any of the functions are external declarations, add them to the worklist
  // for processing.
  bool Result = false;
  for (auto P : Vtbl->getEntries()) {
    if (P.Implementation->isExternalDeclaration()) {
      Result = true;
      addFunctionToWorklist(P.Implementation);
    }
  }
  return Result;
}

//===----------------------------------------------------------------------===//
//                                  Visitors
//===----------------------------------------------------------------------===//

bool SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
  bool performFuncDeserialization = false;

  if (auto sig = AI->getCallee()->getType().castTo<SILFunctionType>()
                   ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(AI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
  bool performFuncDeserialization = false;

  if (auto sig = TAI->getCallee()->getType().castTo<SILFunctionType>()
                   ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(TAI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
  bool performFuncDeserialization = false;

  if (auto sig = PAI->getCallee()->getType().castTo<SILFunctionType>()
                    ->getGenericSignature()) {
    performFuncDeserialization |= visitApplySubstitutions(
      sig->getSubstitutionMap(PAI->getSubstitutions()));
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
  // Needed to handle closures which are no longer applied, but are left
  // behind as dead code. This shouldn't happen, but if it does don't get into
  // an inconsistent state.
  SILFunction *Callee = FRI->getReferencedFunction();

  if (isLinkAll() ||
      hasSharedVisibility(Callee->getLinkage())) {
    addFunctionToWorklist(FRI->getReferencedFunction());
    return true;
  }

  return false;
}

// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
                                               ProtocolConformanceRef c) {
  if (!c.isConcrete())
    return false;
  auto conformance = c.getConcrete()->getRootNormalConformance();
  return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
    && isa<ClangModuleUnit>(conformance->getDeclContext()
                                       ->getModuleScopeContext());
}

bool SILLinkerVisitor::visitProtocolConformance(
    ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
  // If an abstract protocol conformance was passed in, just return false.
  if (ref.isAbstract())
    return false;

  bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);

  // Otherwise try and lookup a witness table for C.
  auto C = ref.getConcrete();

  if (!VisitedConformances.insert(C).second)
    return false;

  SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);

  // If we don't find any witness table for the conformance, bail and return
  // false.
  if (!WT) {
    Mod.createWitnessTableDeclaration(
        C, getLinkageForProtocolConformance(
               C->getRootNormalConformance(), NotForDefinition));

    // Adding the declaration may allow us to now deserialize the body.
    // Force the body if we must deserialize this witness table.
    if (mustDeserialize) {
      WT = Mod.lookUpWitnessTable(C, true);
      assert(WT && WT->isDefinition()
             && "unable to deserialize witness table when we must?!");
    } else {
      return false;
    }
  }

  // If the looked up witness table is a declaration, there is nothing we can
  // do here. Just bail and return false.
  if (WT->isDeclaration())
    return false;

  bool performFuncDeserialization = false;

  auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
    // Formally all conformances referenced by a used conformance are used.
    // However, eagerly visiting them all at this point leads to a large blowup
    // in the amount of SIL we read in. For optimization purposes we can defer
    // reading in most conformances until we need them for devirtualization.
    // However, we *must* pull in shared clang-importer-derived conformances
    // we potentially use, since we may not otherwise have a local definition.
    if (mustDeserializeProtocolConformance(Mod, c))
      performFuncDeserialization |= visitProtocolConformance(c, None);
  };

  // For each entry in the witness table...
  for (auto &E : WT->getEntries()) {
    switch (E.getKind()) {
    // If the entry is a witness method...
    case SILWitnessTable::WitnessKind::Method: {
      // And we are only interested in deserializing a specific requirement
      // and don't have that requirement, don't deserialize this method.
      if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
        continue;

      // The witness could be removed by dead function elimination.
      if (!E.getMethodWitness().Witness)
        continue;

      // Otherwise if it is the requirement we are looking for or we just want
      // to deserialize everything, add the function to the list of functions
      // to deserialize.
      performFuncDeserialization = true;
      addFunctionToWorklist(E.getMethodWitness().Witness);
      break;
    }

    // If the entry is a related witness table, see whether we need to
    // eagerly deserialize it.
    case SILWitnessTable::WitnessKind::BaseProtocol: {
      auto baseConformance = E.getBaseProtocolWitness().Witness;
      maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
      break;
    }
    case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
      auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
      maybeVisitRelatedConformance(assocConformance);
      break;
    }

    case SILWitnessTable::WitnessKind::AssociatedType:
    case SILWitnessTable::WitnessKind::Invalid:
      break;
    }
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitApplySubstitutions(const SubstitutionMap &subs) {
  bool performFuncDeserialization = false;

  for (auto &reqt : subs.getGenericSignature()->getRequirements()) {
    switch (reqt.getKind()) {
    case RequirementKind::Conformance: {
      auto conformance = subs.lookupConformance(
          reqt.getFirstType()->getCanonicalType(),
          cast<ProtocolDecl>(reqt.getSecondType()->getAnyNominal()))
        .getValue();

      // Formally all conformances referenced in a function application are
      // used. However, eagerly visiting them all at this point leads to a
      // large blowup in the amount of SIL we read in, and we aren't very
      // systematic about laziness. For optimization purposes we can defer
      // reading in most conformances until we need them for devirtualization.
      // However, we *must* pull in shared clang-importer-derived conformances
      // we potentially use, since we may not otherwise have a local definition.
      if (mustDeserializeProtocolConformance(Mod, conformance)) {
        performFuncDeserialization |=
                                    visitProtocolConformance(conformance, None);
      }
      break;
    }
    case RequirementKind::Layout:
    case RequirementKind::SameType:
    case RequirementKind::Superclass:
      break;
    }
  }

  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitInitExistentialAddrInst(
    InitExistentialAddrInst *IEI) {
  // Link in all protocol conformances that this touches.
  //
  // TODO: There might be a two step solution where the init_existential_inst
  // causes the witness table to be brought in as a declaration and then the
  // protocol method inst causes the actual deserialization. For now we are
  // not going to be smart about this to enable avoiding any issues with
  // visiting the open_existential_addr/witness_method before the
  // init_existential_inst.
  bool performFuncDeserialization = false;
  for (ProtocolConformanceRef C : IEI->getConformances()) {
    performFuncDeserialization |=
        visitProtocolConformance(C, Optional<SILDeclRef>());
  }
  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitInitExistentialRefInst(
    InitExistentialRefInst *IERI) {
  // Link in all protocol conformances that this touches.
  //
  // TODO: There might be a two step solution where the init_existential_inst
  // causes the witness table to be brought in as a declaration and then the
  // protocol method inst causes the actual deserialization. For now we are
  // not going to be smart about this to enable avoiding any issues with
  // visiting the protocol_method before the init_existential_inst.
  bool performFuncDeserialization = false;
  for (ProtocolConformanceRef C : IERI->getConformances()) {
    performFuncDeserialization |=
        visitProtocolConformance(C, Optional<SILDeclRef>());
  }
  return performFuncDeserialization;
}

bool SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
  if (!isLinkAll())
    return false;

  // Grab the class decl from the alloc ref inst.
  ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
  if (!D)
    return false;

  return linkInVTable(D);
}

bool SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
  if (!isLinkAll())
    return false;

  CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
  ClassDecl *C = instTy.getClassOrBoundGenericClass();
  if (!C)
    return false;

  return linkInVTable(C);
}

//===----------------------------------------------------------------------===//
//                             Top Level Routine
//===----------------------------------------------------------------------===//

// Main loop of the visitor. Called by one of the other *visit* methods.
bool SILLinkerVisitor::process() {
  // Process everything transitively referenced by one of the functions in the
  // worklist.
  bool Result = false;
  while (!Worklist.empty()) {
    auto *Fn = Worklist.pop_back_val();

    if (Fn->getModule().isSerialized()) {
      // If the containing module has been serialized,
      // Remove The Serialized state (if any)
      //  This allows for more optimizations
      Fn->setSerialized(IsSerialized_t::IsNotSerialized);
    }

    DEBUG(llvm::dbgs() << "Process imports in function: "
                       << Fn->getName() << "\n");

    for (auto &BB : *Fn) {
      for (auto &I : BB) {
        // Should we try linking?
        if (visit(&I)) {
          for (auto *F : FunctionDeserializationWorklist) {

            DEBUG(llvm::dbgs() << "Imported function: "
                               << F->getName() << "\n");
            F->setBare(IsBare);

            if (F->isExternalDeclaration()) {
              if (auto *NewFn = Loader->lookupSILFunction(F)) {
                if (NewFn->isExternalDeclaration())
                  continue;

                NewFn->verify();
                Worklist.push_back(NewFn);
                Result = true;

                ++NumFuncLinked;
              }
            }
          }
          FunctionDeserializationWorklist.clear();
        } else {
          assert(FunctionDeserializationWorklist.empty() &&
                 "Worklist should "
                 "always be empty if visit does not return true.");
        }
      }
    }
  }

  // If we return true, we deserialized at least one function.
  return Result;
}
<|endoftext|>


<commit_before><commit_msg>Fix crash in 64-bit builds due to unsigned underflow.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linkmgr2.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:18:44 $
 *
 *  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_sfx2.hxx"

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"

#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"

#include "app.hrc"
#include "sfxresid.hxx"

#define _SVSTDARR_STRINGSDTOR

#include <svtools/svstdarr.hxx>

namespace sfx2
{

SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )

SvLinkManager::SvLinkManager()
    : pPersist( 0 )
{
}

SvLinkManager::~SvLinkManager()
{
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( (*ppRef)->Is() )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
        }
        delete *ppRef;
    }
}

/************************************************************************
|*    SvLinkManager::Remove()
|*
|*    Beschreibung
*************************************************************************/

void SvLinkManager::Remove( SvBaseLink *pLink )
{
    // keine Links doppelt einfuegen
    int bFound = FALSE;
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( pLink == *(*ppRef) )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
            (*(*ppRef)).Clear();
            bFound = TRUE;
        }

        // falls noch leere rum stehen sollten, weg damit
        if( !(*ppRef)->Is() )
        {
            delete *ppRef;
            aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
            if( bFound )
                return ;
            --ppRef;
        }
    }
}

void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
    if( nCnt && nPos < aLinkTbl.Count() )
    {
        if( nPos + nCnt > aLinkTbl.Count() )
            nCnt = aLinkTbl.Count() - nPos;

        SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
        for( USHORT n = nCnt; n; --n, ++ppRef )
        {
            if( (*ppRef)->Is() )
            {
                (*(*ppRef))->Disconnect();
                (*(*ppRef))->pLinkMgr = 0;
            }
            delete *ppRef;
        }
        aLinkTbl.Remove( nPos, nCnt );
    }
}

BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
    // keine Links doppelt einfuegen
    for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLinkRef* pTmp = aLinkTbl[ n ];
        if( !pTmp->Is() )
            aLinkTbl.DeleteAndDestroy( n-- );

        if( pLink == *pTmp )
            return FALSE;
    }

    SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
    pLink->pLinkMgr = this;
    aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
    return TRUE;
}

BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
                                USHORT nObjType,
                                USHORT nUpdateMode,
                                const String* pName )
{
    // unbedingt zuerst
    pLink->SetObjType( nObjType );
    if( pName )
        pLink->SetName( *pName );
    pLink->SetUpdateMode( nUpdateMode );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
                                    const String& rServer,
                                    const String& rTopic,
                                    const String& rItem )
{
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    String sCmd;
    ::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );

    pLink->SetObjType( OBJECT_CLIENT_DDE );
    pLink->SetName( sCmd );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
    DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    if( pLink->GetObjType() == OBJECT_CLIENT_SO )
        pLink->SetObjType( OBJECT_CLIENT_DDE );

    return Insert( pLink );
}

// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
                                        String* pType,
                                        String* pFile,
                                        String* pLinkStr,
                                        String* /*pFilter*/ ) const
{
    BOOL bRet = FALSE;
    String aLN = pLink->GetLinkSourceName();
    if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
    {
        USHORT nTmp = 0;
        String sCmd( aLN );
        String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
        String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );

        if( pType )
            *pType = sServer;
        if( pFile )
            *pFile = sTopic;
        if( pLinkStr )
            *pLinkStr = sCmd.Copy( nTmp );
        bRet = TRUE;
    }
    return bRet;
}

void SvLinkManager::UpdateAllLinks(
    BOOL bAskUpdate,
    BOOL /*bCallErrHdl*/,
    BOOL bUpdateGrfLinks,
    Window* pParentWin )
{
    SvStringsDtor aApps, aTopics, aItems;
    String sApp, sTopic, sItem;

    // erstmal eine Kopie vom Array machen, damit sich updatende Links in
    // Links in ... nicht dazwischen funken!!
    SvPtrarr aTmpArr( 255, 50 );
    USHORT n;
    for( n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLink* pLink = *aLinkTbl[ n ];
        if( !pLink )
        {
            Remove( n-- );
            continue;
        }
        aTmpArr.Insert( pLink, aTmpArr.Count() );
    }

    for( n = 0; n < aTmpArr.Count(); ++n )
    {
        SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];

        // suche erstmal im Array nach dem Eintrag
        USHORT nFndPos = USHRT_MAX;
        for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
            if( pLink == *aLinkTbl[ i ] )
            {
                nFndPos = i;
                break;
            }

        if( USHRT_MAX == nFndPos )
            continue;                   // war noch nicht vorhanden!

        // Graphic-Links noch nicht updaten
        if( !pLink->IsVisible() ||
            ( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
            continue;

        if( bAskUpdate )
        {
            int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
            if( RET_YES != nRet )
                return ;        // es soll nichts geupdatet werden
            bAskUpdate = FALSE;     // einmal reicht
        }

        pLink->Update();
    }
}

/************************************************************************
|*    SvBaseLink::CreateObject()
|*
|*    Beschreibung
*************************************************************************/

SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
    if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
        return new SvDDEObject();
    return SvLinkSourceRef();
}

BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
    // keine doppelt einfuegen
    if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
        return FALSE;

    aServerTbl.Insert( pObj, aServerTbl.Count() );
    return TRUE;
}

void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
    USHORT nPos = aServerTbl.GetPos( pObj );
    if( USHRT_MAX != nPos )
        aServerTbl.Remove( nPos, 1 );
}

void MakeLnkName( String& rName, const String* pType, const String& rFile,
                    const String& rLink, const String* pFilter )
{
    if( pType )
        (rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
    else if( rName.Len() )
        rName.Erase();

    ((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
        cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
    if( pFilter )
        ((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}

}

<commit_msg>INTEGRATION: CWS asyncdialogs (1.3.96); FILE MERGED 2006/09/20 20:25:07 pb 1.3.96.3: RESYNC: (1.4-1.5); FILE MERGED 2006/07/12 20:46:42 pb 1.3.96.2: RESYNC: (1.3-1.4); FILE MERGED 2006/03/22 07:31:09 pb 1.3.96.1: fix: #i57125# use SetLinkManager()<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linkmgr2.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-22 10:55:21 $
 *
 *  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_sfx2.hxx"

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"

#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"

#include "app.hrc"
#include "sfxresid.hxx"

#define _SVSTDARR_STRINGSDTOR

#include <svtools/svstdarr.hxx>

namespace sfx2
{

SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )

SvLinkManager::SvLinkManager()
    : pPersist( 0 )
{
}

SvLinkManager::~SvLinkManager()
{
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( (*ppRef)->Is() )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->SetLinkManager( NULL );
        }
        delete *ppRef;
    }
}

/************************************************************************
|*    SvLinkManager::Remove()
|*
|*    Beschreibung
*************************************************************************/

void SvLinkManager::Remove( SvBaseLink *pLink )
{
    // keine Links doppelt einfuegen
    int bFound = FALSE;
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( pLink == *(*ppRef) )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->SetLinkManager( NULL );
            (*(*ppRef)).Clear();
            bFound = TRUE;
        }

        // falls noch leere rum stehen sollten, weg damit
        if( !(*ppRef)->Is() )
        {
            delete *ppRef;
            aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
            if( bFound )
                return ;
            --ppRef;
        }
    }
}

void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
    if( nCnt && nPos < aLinkTbl.Count() )
    {
        if( nPos + nCnt > aLinkTbl.Count() )
            nCnt = aLinkTbl.Count() - nPos;

        SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
        for( USHORT n = nCnt; n; --n, ++ppRef )
        {
            if( (*ppRef)->Is() )
            {
                (*(*ppRef))->Disconnect();
                (*(*ppRef))->SetLinkManager( NULL );
            }
            delete *ppRef;
        }
        aLinkTbl.Remove( nPos, nCnt );
    }
}

BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
    // keine Links doppelt einfuegen
    for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLinkRef* pTmp = aLinkTbl[ n ];
        if( !pTmp->Is() )
            aLinkTbl.DeleteAndDestroy( n-- );

        if( pLink == *pTmp )
            return FALSE;
    }

    SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
    pLink->SetLinkManager( this );
    aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
    return TRUE;
}

BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
                                USHORT nObjType,
                                USHORT nUpdateMode,
                                const String* pName )
{
    // unbedingt zuerst
    pLink->SetObjType( nObjType );
    if( pName )
        pLink->SetName( *pName );
    pLink->SetUpdateMode( nUpdateMode );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
                                    const String& rServer,
                                    const String& rTopic,
                                    const String& rItem )
{
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    String sCmd;
    ::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );

    pLink->SetObjType( OBJECT_CLIENT_DDE );
    pLink->SetName( sCmd );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
    DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    if( pLink->GetObjType() == OBJECT_CLIENT_SO )
        pLink->SetObjType( OBJECT_CLIENT_DDE );

    return Insert( pLink );
}

// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
                                        String* pType,
                                        String* pFile,
                                        String* pLinkStr,
                                        String* /*pFilter*/ ) const
{
    BOOL bRet = FALSE;
    String aLN = pLink->GetLinkSourceName();
    if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
    {
        USHORT nTmp = 0;
        String sCmd( aLN );
        String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
        String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );

        if( pType )
            *pType = sServer;
        if( pFile )
            *pFile = sTopic;
        if( pLinkStr )
            *pLinkStr = sCmd.Copy( nTmp );
        bRet = TRUE;
    }
    return bRet;
}

void SvLinkManager::UpdateAllLinks(
    BOOL bAskUpdate,
    BOOL /*bCallErrHdl*/,
    BOOL bUpdateGrfLinks,
    Window* pParentWin )
{
    SvStringsDtor aApps, aTopics, aItems;
    String sApp, sTopic, sItem;

    // erstmal eine Kopie vom Array machen, damit sich updatende Links in
    // Links in ... nicht dazwischen funken!!
    SvPtrarr aTmpArr( 255, 50 );
    USHORT n;
    for( n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLink* pLink = *aLinkTbl[ n ];
        if( !pLink )
        {
            Remove( n-- );
            continue;
        }
        aTmpArr.Insert( pLink, aTmpArr.Count() );
    }

    for( n = 0; n < aTmpArr.Count(); ++n )
    {
        SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];

        // suche erstmal im Array nach dem Eintrag
        USHORT nFndPos = USHRT_MAX;
        for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
            if( pLink == *aLinkTbl[ i ] )
            {
                nFndPos = i;
                break;
            }

        if( USHRT_MAX == nFndPos )
            continue;                   // war noch nicht vorhanden!

        // Graphic-Links noch nicht updaten
        if( !pLink->IsVisible() ||
            ( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
            continue;

        if( bAskUpdate )
        {
            int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
            if( RET_YES != nRet )
                return ;        // es soll nichts geupdatet werden
            bAskUpdate = FALSE;     // einmal reicht
        }

        pLink->Update();
    }
}

/************************************************************************
|*    SvBaseLink::CreateObject()
|*
|*    Beschreibung
*************************************************************************/

SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
    if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
        return new SvDDEObject();
    return SvLinkSourceRef();
}

BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
    // keine doppelt einfuegen
    if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
        return FALSE;

    aServerTbl.Insert( pObj, aServerTbl.Count() );
    return TRUE;
}

void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
    USHORT nPos = aServerTbl.GetPos( pObj );
    if( USHRT_MAX != nPos )
        aServerTbl.Remove( nPos, 1 );
}

void MakeLnkName( String& rName, const String* pType, const String& rFile,
                    const String& rLink, const String* pFilter )
{
    if( pType )
        (rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
    else if( rName.Len() )
        rName.Erase();

    ((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
        cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
    if( pFilter )
        ((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}

}

<|endoftext|>


<commit_before><commit_msg>fix timed wait for condition<commit_after><|endoftext|>