<commit_before>// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#include <docopt/docopt.h>
#include <sstream>
#include <fstream>
#include <unordered_map>
#include <unordered_set>

#include <fmt/format.h>
#include <fmt/ostream.h>

#include "HBonds.hpp"
#include "Autocorrelation.hpp"
#include "Errors.hpp"
#include "utils.hpp"
#include "warnings.hpp"

using namespace chemfiles;
constexpr double PI = 3.141592653589793238463;

static const char OPTIONS[] =
R"(Compute list of hydrogen bonds along a trajectory. Selections for the acceptor
and donor atoms can be specified using the chemfiles selection language. It is
possible to provide an alternative unit cell or topology for the trajectory file
if they are not defined in the trajectory format. Hydrogen bonds are defined as
electrostatic attraction between two polar groups: the donor group is a hydrogen
atom covalently bound to an electronegative atom (usually O, N, F) while the
acceptor group is another highly electronegative atom. The criteria used depend
on a maximum donor-acceptor distance and a maximum acceptor-donor-H angle.
Hydrogen bonds criteria can be specified.

For more information about chemfiles selection language, please see
http://chemfiles.org/chemfiles/latest/selections.html

Usage:
  cfiles hbonds [options] <trajectory>
  cfiles hbonds (-h | --help)

Examples:
  cfiles hbonds water.xyz --cell 15:15:25 --guess-bonds
  cfiles hbonds in.pdb --donors=="bonds: type(#1) == O and type(#2) == H"
  cfiles hbonds protein.pdb --acceptors=="atoms: type N" --angle 20.0

Options:
  -h --help                     show this help
  -o <file>, --output=<file>    write result to <file>. This default to the
                                trajectory file name with the `.hbonds.dat`
                                extension.
  --format=<format>             force the input file format to be <format>
  -t <path>, --topology=<path>  alternative topology file for the input
  --topology-format=<format>    use <format> as format for the topology file
  --guess-bonds                 guess the bonds in the input
  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of
                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and
                                'c' are in angstroms, 'α', 'β', and 'γ' are in
                                degrees.
  --steps=<steps>               steps to use from the input. <steps> format
                                is <start>:<end>[:<stride>] with <start>, <end>
                                and <stride> optional. The used steps goes from
                                <start> to <end> (excluded) by steps of
                                <stride>. The default values are 0 for <start>,
                                the number of steps for <end> and 1 for
                                <stride>.
  --donors=<sel>                selection to use for the donors. This must be a
                                selection of size 2, with the hydrogen atom as
                                second atom. [default: bonds: type(#2) == H]
  --acceptors=<sel>             selection to use for the acceptors. This must
                                be a selection of size 1.
                                [default: atoms: type O or type N or type F]
  --distance=<distance>         distance criterion to use for the hydrogen bond
                                detection. <distance> is the donor-acceptor
                                maximum distance in angstroms. [default: 3.5]
  --angle=<angle>               angle criterion to use for the hydrogen bond
                                detection. <angle> is the acceptor-donor-hydrogen
                                maximum angle in degrees. [default: 30.0]
  --autocorrelation=<output>    compute the hydrogen bond existence
                                autocorrelation and output it to the given
                                <ouput> file. This can be used to retrieve the
                                lifetime of hydrogen bonds.
)";

struct hbond {
    size_t donor;
    size_t hydrogen;
    size_t acceptor;
};

bool operator==(const hbond& lhs, const hbond& rhs) {
    return (lhs.donor == rhs.donor && lhs.hydrogen == rhs.hydrogen && lhs.acceptor == rhs.acceptor);
}

inline void hash_combine(size_t& hash, size_t value) {
    hash ^= std::hash<size_t>()(value) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}

namespace std {
    template <> struct hash<hbond> {
        size_t operator()(const hbond& bond) const {
            size_t hash = 0;
            hash_combine(hash, bond.donor);
            hash_combine(hash, bond.hydrogen);
            hash_combine(hash, bond.acceptor);
            return hash;
        }
    };
}

static HBonds::Options parse_options(int argc, const char* argv[]) {
    auto options_str = command_header("hbonds", HBonds().description()) + "\n";
    options_str += "Laura Scalfi <laura.scalfi@ens.fr>\n";
    options_str += OPTIONS;
    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, "");

    HBonds::Options options;
    options.trajectory = args.at("<trajectory>").asString();
    options.guess_bonds = args.at("--guess-bonds").asBool();

    options.acceptor_selection = args.at("--acceptors").asString();
    options.donor_selection = args.at("--donors").asString();

    options.distance = string2double(args.at("--distance").asString());
    options.angle = string2double(args.at("--angle").asString()) * PI / 180;

    if (args.at("--output")) {
        options.outfile = args.at("--output").asString();
    } else {
        options.outfile = options.trajectory + ".hbonds.dat";
    }

    if (args.at("--autocorrelation")) {
        options.autocorr_output = args.at("--autocorrelation").asString();
        options.autocorrelation = true;
    } else {
        options.autocorrelation = false;
    }

    if (args.at("--steps")) {
        options.steps = steps_range::parse(args.at("--steps").asString());
    }

    if (args.at("--format")) {
        options.format = args.at("--format").asString();
    }

    if (args.at("--topology")) {
        if (options.guess_bonds) {
            throw CFilesError("Can not use both '--topology' and '--guess-bonds'");
        }
        options.topology = args.at("--topology").asString();
    }

    if (args.at("--topology-format")) {
        if (options.topology == "") {
            throw CFilesError("Can not use '--topology-format' without a '--topology'");
        }
        options.topology_format = args.at("--topology-format").asString();
    }

    if (args.at("--cell")) {
        options.custom_cell = true;
        options.cell = parse_cell(args.at("--cell").asString());
    }

    return options;
}

std::string HBonds::description() const {
    return "compute hydrogen bonds using distance/angle criteria";
}

int HBonds::run(int argc, const char* argv[]) {
    auto options = parse_options(argc, argv);

    auto donors = Selection(options.donor_selection);
    if (donors.size() != 2) {
        throw CFilesError("Can not use a selection for donors with size that is not 2.");
    }

    auto acceptors = Selection(options.acceptor_selection);
    if (acceptors.size() != 1) {
        throw CFilesError("Can not use a selection for acceptors with size larger than 1.");
    }

    std::ofstream outfile(options.outfile, std::ios::out);
    if (!outfile.is_open()) {
        throw CFilesError("Could not open the '" + options.outfile + "' file.");
    }
    fmt::print(outfile, "# Hydrogen bonds in {}\n", options.trajectory);
    fmt::print(outfile, "# Between '{}' and '{}'\n", options.acceptor_selection, options.donor_selection);

    auto infile = Trajectory(options.trajectory, 'r', options.format);
    if (options.custom_cell) {
        infile.set_cell(options.cell);
    }

    if (options.topology != "") {
        infile.set_topology(options.topology, options.topology_format);
    }

    auto existing_bonds = std::unordered_map<hbond, std::vector<float>>();
    size_t used_steps = 0;
    for (auto step: options.steps) {
        if (step >= infile.nsteps()) {
            break;
        }
        auto frame = infile.read_step(step);
        if (options.guess_bonds) {
            frame.guess_bonds();
        }

        auto bonds = std::unordered_set<hbond>();
        auto matched = donors.evaluate(frame);
        if (matched.empty()) {
            warn("no atom matching the donnor selection at step " + std::to_string(step));
        }

        for (auto match: matched) {
            assert(match.size() == 2);

            size_t donor = match[0];
            size_t hydrogen = match[1];

            if (frame[hydrogen].type() != "H") {
                warn_once(
                    "the second atom in the donors selection might not be an "
                    "hydrogen (expected type H, got type " + frame[hydrogen].type() + ")"
                );
            }

            auto acceptors_list = acceptors.list(frame);
            if (acceptors_list.empty()) {
                warn("no atom matching the acceptor selection at step " + std::to_string(step));
            }

            for (auto acceptor: acceptors_list) {
                if (acceptor != donor && frame.topology()[acceptor].type() != "H") {
                    auto distance = frame.distance(acceptor, donor);
                    auto theta = frame.angle(acceptor, donor, hydrogen);
                    if (distance < options.distance && theta < options.angle) {
                        bonds.emplace(hbond{donor, hydrogen, acceptor});
                    }
                }
            }
        }

        fmt::print(outfile, "# step n_bonds\n");
        fmt::print(outfile, "{} {}\n", step, bonds.size());
        fmt::print(outfile, "# Donnor Hydrogen Acceptor\n", step);
        for (auto& bond: bonds) {
            fmt::print(outfile, "{} {} {}\n", bond.donor, bond.hydrogen, bond.acceptor);
        }

        if (options.autocorrelation) {
            for (auto& bond: bonds) {
                auto it = existing_bonds.find(bond);
                if (it == existing_bonds.end()) {
                    // New bond. Insert it and pad with zeros
                    auto pair = existing_bonds.emplace(bond, std::vector<float>(used_steps, 0.0));
                    pair.first->second.push_back(1.0);
                } else {
                    // Already seen this bond, add a single 1
                    it->second.push_back(1.0);
                }
            }
            // Add 0 to all bonds we did not see in this frame
            for (auto& it: existing_bonds) {
                if (it.second.size() != used_steps + 1) {
                    it.second.push_back(0.0);
                }
            }
        }
        used_steps += 1;
    }

    if (options.autocorrelation) {
        // Compute the autocorrelation for all bonds and average them
        auto correlator = Autocorrelation(used_steps);
        for (auto&& it: std::move(existing_bonds)) {
            correlator.add_timeserie(std::move(it.second));
        }
        correlator.normalize();
        auto& correlation = correlator.get_result();

        std::ofstream outcorr(options.autocorr_output, std::ios::out);
        if (!outcorr.is_open()) {
            throw CFilesError("Could not open the '" + options.autocorr_output + "' file.");
        }
        fmt::print(outcorr, "# Auto correlation between H-bonds existence\n");
        fmt::print(outcorr, "# step value\n");

        auto norm = correlation[0];
        for (size_t i=0; i<correlation.size() / 2; i++) {
            fmt::print(outcorr, "{} {}\n", i * options.steps.stride(), correlation[i] / norm);
        }
    }

    return 0;
}
<commit_msg>Do not compute autocorrelation if no step was used<commit_after>// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#include <docopt/docopt.h>
#include <sstream>
#include <fstream>
#include <unordered_map>
#include <unordered_set>

#include <fmt/format.h>
#include <fmt/ostream.h>

#include "HBonds.hpp"
#include "Autocorrelation.hpp"
#include "Errors.hpp"
#include "utils.hpp"
#include "warnings.hpp"

using namespace chemfiles;
constexpr double PI = 3.141592653589793238463;

static const char OPTIONS[] =
R"(Compute list of hydrogen bonds along a trajectory. Selections for the acceptor
and donor atoms can be specified using the chemfiles selection language. It is
possible to provide an alternative unit cell or topology for the trajectory file
if they are not defined in the trajectory format. Hydrogen bonds are defined as
electrostatic attraction between two polar groups: the donor group is a hydrogen
atom covalently bound to an electronegative atom (usually O, N, F) while the
acceptor group is another highly electronegative atom. The criteria used depend
on a maximum donor-acceptor distance and a maximum acceptor-donor-H angle.
Hydrogen bonds criteria can be specified.

For more information about chemfiles selection language, please see
http://chemfiles.org/chemfiles/latest/selections.html

Usage:
  cfiles hbonds [options] <trajectory>
  cfiles hbonds (-h | --help)

Examples:
  cfiles hbonds water.xyz --cell 15:15:25 --guess-bonds
  cfiles hbonds in.pdb --donors=="bonds: type(#1) == O and type(#2) == H"
  cfiles hbonds protein.pdb --acceptors=="atoms: type N" --angle 20.0

Options:
  -h --help                     show this help
  -o <file>, --output=<file>    write result to <file>. This default to the
                                trajectory file name with the `.hbonds.dat`
                                extension.
  --format=<format>             force the input file format to be <format>
  -t <path>, --topology=<path>  alternative topology file for the input
  --topology-format=<format>    use <format> as format for the topology file
  --guess-bonds                 guess the bonds in the input
  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of
                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and
                                'c' are in angstroms, 'α', 'β', and 'γ' are in
                                degrees.
  --steps=<steps>               steps to use from the input. <steps> format
                                is <start>:<end>[:<stride>] with <start>, <end>
                                and <stride> optional. The used steps goes from
                                <start> to <end> (excluded) by steps of
                                <stride>. The default values are 0 for <start>,
                                the number of steps for <end> and 1 for
                                <stride>.
  --donors=<sel>                selection to use for the donors. This must be a
                                selection of size 2, with the hydrogen atom as
                                second atom. [default: bonds: type(#2) == H]
  --acceptors=<sel>             selection to use for the acceptors. This must
                                be a selection of size 1.
                                [default: atoms: type O or type N or type F]
  --distance=<distance>         distance criterion to use for the hydrogen bond
                                detection. <distance> is the donor-acceptor
                                maximum distance in angstroms. [default: 3.5]
  --angle=<angle>               angle criterion to use for the hydrogen bond
                                detection. <angle> is the acceptor-donor-hydrogen
                                maximum angle in degrees. [default: 30.0]
  --autocorrelation=<output>    compute the hydrogen bond existence
                                autocorrelation and output it to the given
                                <ouput> file. This can be used to retrieve the
                                lifetime of hydrogen bonds.
)";

struct hbond {
    size_t donor;
    size_t hydrogen;
    size_t acceptor;
};

bool operator==(const hbond& lhs, const hbond& rhs) {
    return (lhs.donor == rhs.donor && lhs.hydrogen == rhs.hydrogen && lhs.acceptor == rhs.acceptor);
}

inline void hash_combine(size_t& hash, size_t value) {
    hash ^= std::hash<size_t>()(value) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}

namespace std {
    template <> struct hash<hbond> {
        size_t operator()(const hbond& bond) const {
            size_t hash = 0;
            hash_combine(hash, bond.donor);
            hash_combine(hash, bond.hydrogen);
            hash_combine(hash, bond.acceptor);
            return hash;
        }
    };
}

static HBonds::Options parse_options(int argc, const char* argv[]) {
    auto options_str = command_header("hbonds", HBonds().description()) + "\n";
    options_str += "Laura Scalfi <laura.scalfi@ens.fr>\n";
    options_str += OPTIONS;
    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, "");

    HBonds::Options options;
    options.trajectory = args.at("<trajectory>").asString();
    options.guess_bonds = args.at("--guess-bonds").asBool();

    options.acceptor_selection = args.at("--acceptors").asString();
    options.donor_selection = args.at("--donors").asString();

    options.distance = string2double(args.at("--distance").asString());
    options.angle = string2double(args.at("--angle").asString()) * PI / 180;

    if (args.at("--output")) {
        options.outfile = args.at("--output").asString();
    } else {
        options.outfile = options.trajectory + ".hbonds.dat";
    }

    if (args.at("--autocorrelation")) {
        options.autocorr_output = args.at("--autocorrelation").asString();
        options.autocorrelation = true;
    } else {
        options.autocorrelation = false;
    }

    if (args.at("--steps")) {
        options.steps = steps_range::parse(args.at("--steps").asString());
    }

    if (args.at("--format")) {
        options.format = args.at("--format").asString();
    }

    if (args.at("--topology")) {
        if (options.guess_bonds) {
            throw CFilesError("Can not use both '--topology' and '--guess-bonds'");
        }
        options.topology = args.at("--topology").asString();
    }

    if (args.at("--topology-format")) {
        if (options.topology == "") {
            throw CFilesError("Can not use '--topology-format' without a '--topology'");
        }
        options.topology_format = args.at("--topology-format").asString();
    }

    if (args.at("--cell")) {
        options.custom_cell = true;
        options.cell = parse_cell(args.at("--cell").asString());
    }

    return options;
}

std::string HBonds::description() const {
    return "compute hydrogen bonds using distance/angle criteria";
}

int HBonds::run(int argc, const char* argv[]) {
    auto options = parse_options(argc, argv);

    auto donors = Selection(options.donor_selection);
    if (donors.size() != 2) {
        throw CFilesError("Can not use a selection for donors with size that is not 2.");
    }

    auto acceptors = Selection(options.acceptor_selection);
    if (acceptors.size() != 1) {
        throw CFilesError("Can not use a selection for acceptors with size larger than 1.");
    }

    std::ofstream outfile(options.outfile, std::ios::out);
    if (!outfile.is_open()) {
        throw CFilesError("Could not open the '" + options.outfile + "' file.");
    }
    fmt::print(outfile, "# Hydrogen bonds in {}\n", options.trajectory);
    fmt::print(outfile, "# Between '{}' and '{}'\n", options.acceptor_selection, options.donor_selection);

    auto infile = Trajectory(options.trajectory, 'r', options.format);
    if (options.custom_cell) {
        infile.set_cell(options.cell);
    }

    if (options.topology != "") {
        infile.set_topology(options.topology, options.topology_format);
    }

    auto existing_bonds = std::unordered_map<hbond, std::vector<float>>();
    size_t used_steps = 0;
    for (auto step: options.steps) {
        if (step >= infile.nsteps()) {
            break;
        }
        auto frame = infile.read_step(step);
        if (options.guess_bonds) {
            frame.guess_bonds();
        }

        auto bonds = std::unordered_set<hbond>();
        auto matched = donors.evaluate(frame);
        if (matched.empty()) {
            warn("no atom matching the donnor selection at step " + std::to_string(step));
        }

        for (auto match: matched) {
            assert(match.size() == 2);

            size_t donor = match[0];
            size_t hydrogen = match[1];

            if (frame[hydrogen].type() != "H") {
                warn_once(
                    "the second atom in the donors selection might not be an "
                    "hydrogen (expected type H, got type " + frame[hydrogen].type() + ")"
                );
            }

            auto acceptors_list = acceptors.list(frame);
            if (acceptors_list.empty()) {
                warn("no atom matching the acceptor selection at step " + std::to_string(step));
            }

            for (auto acceptor: acceptors_list) {
                if (acceptor != donor && frame.topology()[acceptor].type() != "H") {
                    auto distance = frame.distance(acceptor, donor);
                    auto theta = frame.angle(acceptor, donor, hydrogen);
                    if (distance < options.distance && theta < options.angle) {
                        bonds.emplace(hbond{donor, hydrogen, acceptor});
                    }
                }
            }
        }

        fmt::print(outfile, "# step n_bonds\n");
        fmt::print(outfile, "{} {}\n", step, bonds.size());
        fmt::print(outfile, "# Donnor Hydrogen Acceptor\n", step);
        for (auto& bond: bonds) {
            fmt::print(outfile, "{} {} {}\n", bond.donor, bond.hydrogen, bond.acceptor);
        }

        if (options.autocorrelation) {
            for (auto& bond: bonds) {
                auto it = existing_bonds.find(bond);
                if (it == existing_bonds.end()) {
                    // New bond. Insert it and pad with zeros
                    auto pair = existing_bonds.emplace(bond, std::vector<float>(used_steps, 0.0));
                    pair.first->second.push_back(1.0);
                } else {
                    // Already seen this bond, add a single 1
                    it->second.push_back(1.0);
                }
            }
            // Add 0 to all bonds we did not see in this frame
            for (auto& it: existing_bonds) {
                if (it.second.size() != used_steps + 1) {
                    it.second.push_back(0.0);
                }
            }
        }
        used_steps += 1;
    }

    if (options.autocorrelation && used_steps != 0) {
        // Compute the autocorrelation for all bonds and average them
        auto correlator = Autocorrelation(used_steps);
        for (auto&& it: std::move(existing_bonds)) {
            correlator.add_timeserie(std::move(it.second));
        }
        correlator.normalize();
        auto& correlation = correlator.get_result();

        std::ofstream outcorr(options.autocorr_output, std::ios::out);
        if (!outcorr.is_open()) {
            throw CFilesError("Could not open the '" + options.autocorr_output + "' file.");
        }
        fmt::print(outcorr, "# Auto correlation between H-bonds existence\n");
        fmt::print(outcorr, "# step value\n");

        auto norm = correlation[0];
        for (size_t i=0; i<correlation.size() / 2; i++) {
            fmt::print(outcorr, "{} {}\n", i * options.steps.stride(), correlation[i] / norm);
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * MLPLM.cpp
 *
 *  Created on: 20.11.2013
 *      Author: cls
 */

#include "PLM.h"
#include <omp.h>
#include "../coarsening/PartitionCoarsening.h"
#include "../coarsening/ClusterContractor.h"
#include "../coarsening/ClusteringProjector.h"
#include "../auxiliary/Log.h"

#include <sstream>

namespace NetworKit {

PLM::PLM(bool refine, double gamma, std::string par, count maxIter) : parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter) {

}

Partition PLM::run(const Graph& G) {
	DEBUG("calling run method on " , G.toString());

	count z = G.upperNodeIdBound();

	std::vector<bool> active(z); // record if node must be processed
	active.assign(z, true);

	// SATELLITE FOLLOWING: initially deactivate satellies
	// G.forNodes([&](node v){
	// 	if
	// });	// TODO: parallel

	// init communities to singletons
	Partition zeta(z);
	G.forNodes([&](node v) {
		zeta.toSingleton(v);
	});
	index o = zeta.upperBound();

	// init graph-dependent temporaries
	std::vector<double> volNode(z, 0.0);
	// $\omega(E)$
	edgeweight total = G.totalEdgeWeight();
	DEBUG("total edge weight: " , total);
	edgeweight divisor = (2 * total * total); // needed in modularity calculation

	G.parallelForNodes([&](node u) { // calculate and store volume of each node
		volNode[u] += G.weightedDegree(u);
		volNode[u] += G.weight(u, u); // consider self-loop twice
		TRACE("init volNode[" , u , "] to " , volNode[u]);
	});

	// init community-dependent temporaries
	std::vector<double> volCommunity(o, 0.0);
	zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
		volCommunity[C] = volNode[u];
	});

	// first move phase
	bool moved = false; // indicates whether any node has been moved in the last pass
	bool change = false; // indicates whether the communities have changed at all

	/*
	 * try to improve modularity by moving a node to neighboring clusters
	 */
	auto tryMove = [&](node u) {
		if (active[u]) { // only consider active nodes
			TRACE("trying to move node " , u);

			// collect edge weight to neighbor clusters
			std::map<index, edgeweight> affinity;
			G.forWeightedNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					affinity[C] += weight;
				}
			});

			// sub-functions

			// $\vol(C \ {x})$ - volume of cluster C excluding node x
			auto volCommunityMinusNode = [&](index C, node x) {
				double volC = 0.0;
				double volN = 0.0;
				volC = volCommunity[C];
				if (zeta[x] == C) {
					volN = volNode[x];
					return volC - volN;
				} else {
					return volC;
				}
			};

			auto modGain = [&](node u, index C, index D) {
				double volN = 0.0;
				volN = volNode[u];
				double delta = (affinity[D] - affinity[C]) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor;
				TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total));
				return delta;
			};

			index best = none;
			index C = none;
			index D = none;
			double deltaBest = -1;

			C = zeta[u];

			TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C);
			bool core = true;
			G.forNeighborsOf(u, [&](node v) {
				D = zeta[v];
				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D);
					TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
					core = false;
				}
			});

			// CORE NODE DEACTIVATION: deactivate core node
			if (core) {
				active[u] = false;
			}

			TRACE("deltaBest=" , deltaBest);
			if (deltaBest > 0) { // if modularity improvement possible
				assert (best != C && best != none);// do not "move" to original cluster

				zeta[u] = best; // move to best cluster
				TRACE("node " , u , " moved");

				// mod update
				double volN = 0.0;
				volN = volNode[u];
				// update the volume of the two clusters
				#pragma omp atomic update
				volCommunity[C] -= volN;
				#pragma omp atomic update
				volCommunity[best] += volN;

				moved = true; // change to clustering has been made

			} else {
				TRACE("node " , u , " not moved");
			}

			// CORE NODE DEACTIVATION: when u changes community, activate all neighbors
			if (moved) {
				G.forNeighborsOf(u, [&](node v){
					active[v] = true;
				});
			}
		} else {
			TRACE("node ", u, "inactive");
		}

	};

	// performs node moves
	auto movePhase = [&](){
		count iter = 0;
		do {
			moved = false;
			// apply node movement according to parallelization strategy
			if (this->parallelism == "none") {
				G.forNodes(tryMove);
			} else if (this->parallelism == "simple") {
				G.parallelForNodes(tryMove);
			} else if (this->parallelism == "balanced") {
				G.balancedParallelForNodes(tryMove);
			} else {
				ERROR("unknown parallelization strategy: " , this->parallelism);
				throw std::runtime_error("unknown parallelization strategy");
			}
			if (moved) change = true;

			if (iter == maxIter) {
				WARN("move phase aborted after ", maxIter, " iterations");
			}
			iter += 1;
		} while (moved && (iter <= maxIter));
		DEBUG("iterations in move phase: ", iter);
	};

	// first move phase

	// DEBUG
	count nInactive = 0;
	G.forNodes([&](node v) {
		if (!active[v]) {
			nInactive += 1;
		}
	});
	INFO("number of active nodes: ", nInactive);
	// DEBUG
	movePhase();

	if (change) {
		DEBUG("nodes moved, so begin coarsening and recursive call");
		std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta);	// coarsen graph according to communitites
		Partition zetaCoarse = run(coarsened.first);

		zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph
		// refinement phase
		if (refine) {
			DEBUG("refinement phase");
			// reinit community-dependent temporaries
			o = zeta.upperBound();
			volCommunity.clear();
			volCommunity.resize(o, 0.0);
			zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
				edgeweight volN = volNode[u];
				#pragma omp atomic update
				volCommunity[C] += volN;
			});

			// second move phase
			movePhase();
		}
	}
	return zeta;
}

std::string NetworKit::PLM::toString() const {
	std::string refined;
	if (refine) {
		refined = "refinement";
	} else {
		refined = "";
	}

	std::stringstream stream;
	stream << "PLM(" << parallelism << "," << refined << ")";

	return stream.str();
}

std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) {
	bool parallelCoarsening = false; // switch between parallel and sequential coarsening
	if (parallelCoarsening) {
		PartitionCoarsening parCoarsening;
		return parCoarsening.run(G, zeta);
	} else {
		ClusterContractor seqCoarsening;
		return seqCoarsening.run(G, zeta);
	}

}

Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) {
	Partition zetaFine(Gfine.upperNodeIdBound());
	zetaFine.setUpperBound(zetaCoarse.upperBound());

	Gfine.forNodes([&](node v) {
		node mv = nodeToMetaNode[v];
		index cv = zetaCoarse[mv];
		zetaFine[v] = cv;
	});

	return zetaFine;
}

} /* namespace NetworKit */
<commit_msg>fixed<commit_after>/*
 * MLPLM.cpp
 *
 *  Created on: 20.11.2013
 *      Author: cls
 */

#include "PLM.h"
#include <omp.h>
#include "../coarsening/PartitionCoarsening.h"
#include "../coarsening/ClusterContractor.h"
#include "../coarsening/ClusteringProjector.h"
#include "../auxiliary/Log.h"

#include <sstream>

namespace NetworKit {

PLM::PLM(bool refine, double gamma, std::string par, count maxIter) : parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter) {

}

Partition PLM::run(const Graph& G) {
	DEBUG("calling run method on " , G.toString());

	count z = G.upperNodeIdBound();

	std::vector<bool> active(z); // record if node must be processed
	active.assign(z, true);

	// SATELLITE FOLLOWING: initially deactivate satellies
	// G.forNodes([&](node v){
	// 	if
	// });	// TODO: parallel

	// init communities to singletons
	Partition zeta(z);
	G.forNodes([&](node v) {
		zeta.toSingleton(v);
	});
	index o = zeta.upperBound();

	// init graph-dependent temporaries
	std::vector<double> volNode(z, 0.0);
	// $\omega(E)$
	edgeweight total = G.totalEdgeWeight();
	DEBUG("total edge weight: " , total);
	edgeweight divisor = (2 * total * total); // needed in modularity calculation

	G.parallelForNodes([&](node u) { // calculate and store volume of each node
		volNode[u] += G.weightedDegree(u);
		volNode[u] += G.weight(u, u); // consider self-loop twice
		TRACE("init volNode[" , u , "] to " , volNode[u]);
	});

	// init community-dependent temporaries
	std::vector<double> volCommunity(o, 0.0);
	zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
		volCommunity[C] = volNode[u];
	});

	// first move phase
	bool moved = false; // indicates whether any node has been moved in the last pass
	bool change = false; // indicates whether the communities have changed at all

	/*
	 * try to improve modularity by moving a node to neighboring clusters
	 */
	auto tryMove = [&](node u) {
		if (active[u]) { // only consider active nodes
			TRACE("trying to move node " , u);

			// collect edge weight to neighbor clusters
			std::map<index, edgeweight> affinity;
			G.forWeightedNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					affinity[C] += weight;
				}
			});

			// sub-functions

			// $\vol(C \ {x})$ - volume of cluster C excluding node x
			auto volCommunityMinusNode = [&](index C, node x) {
				double volC = 0.0;
				double volN = 0.0;
				volC = volCommunity[C];
				if (zeta[x] == C) {
					volN = volNode[x];
					return volC - volN;
				} else {
					return volC;
				}
			};

			auto modGain = [&](node u, index C, index D) {
				double volN = 0.0;
				volN = volNode[u];
				double delta = (affinity[D] - affinity[C]) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor;
				TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total));
				return delta;
			};

			index best = none;
			index C = none;
			index D = none;
			double deltaBest = -1;

			C = zeta[u];

			TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C);
			bool core = true;
			G.forNeighborsOf(u, [&](node v) {
				D = zeta[v];
				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D);
					TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
					core = false;
				}
			});

			// CORE NODE DEACTIVATION: deactivate core node
			if (core) {
				active[u] = false;
			}

			TRACE("deltaBest=" , deltaBest);
			if (deltaBest > 0) { // if modularity improvement possible
				assert (best != C && best != none);// do not "move" to original cluster

				zeta[u] = best; // move to best cluster
				TRACE("node " , u , " moved");

				// mod update
				double volN = 0.0;
				volN = volNode[u];
				// update the volume of the two clusters
				#pragma omp atomic update
				volCommunity[C] -= volN;
				#pragma omp atomic update
				volCommunity[best] += volN;

				moved = true; // change to clustering has been made

			} else {
				TRACE("node " , u , " not moved");
			}

			// CORE NODE DEACTIVATION: when u changes community, activate all neighbors
			if (moved) {
				G.forNeighborsOf(u, [&](node v){
					active[v] = true;
				});
			}
		} else {
			TRACE("node ", u, "inactive");
		}

	};

	// performs node moves
	auto movePhase = [&](){
		count iter = 0;
		do {
			moved = false;
			// apply node movement according to parallelization strategy
			if (this->parallelism == "none") {
				G.forNodes(tryMove);
			} else if (this->parallelism == "simple") {
				G.parallelForNodes(tryMove);
			} else if (this->parallelism == "balanced") {
				G.balancedParallelForNodes(tryMove);
			} else {
				ERROR("unknown parallelization strategy: " , this->parallelism);
				throw std::runtime_error("unknown parallelization strategy");
			}
			if (moved) change = true;

			if (iter == maxIter) {
				WARN("move phase aborted after ", maxIter, " iterations");
			}
			iter += 1;

			// DEBUG
			count nInactive = 0;
			G.forNodes([&](node v) {
				if (!active[v]) {
					nInactive += 1;
				}
			});
			INFO("number of inactive nodes: ", nInactive);
			// DEBUG

		} while (moved && (iter <= maxIter));
		DEBUG("iterations in move phase: ", iter);
	};

	// first move phase
	movePhase();

	if (change) {
		DEBUG("nodes moved, so begin coarsening and recursive call");
		std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta);	// coarsen graph according to communitites
		Partition zetaCoarse = run(coarsened.first);

		zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph
		// refinement phase
		if (refine) {
			DEBUG("refinement phase");
			// reinit community-dependent temporaries
			o = zeta.upperBound();
			volCommunity.clear();
			volCommunity.resize(o, 0.0);
			zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
				edgeweight volN = volNode[u];
				#pragma omp atomic update
				volCommunity[C] += volN;
			});

			// second move phase
			movePhase();
		}
	}
	return zeta;
}

std::string NetworKit::PLM::toString() const {
	std::string refined;
	if (refine) {
		refined = "refinement";
	} else {
		refined = "";
	}

	std::stringstream stream;
	stream << "PLM(" << parallelism << "," << refined << ")";

	return stream.str();
}

std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) {
	bool parallelCoarsening = false; // switch between parallel and sequential coarsening
	if (parallelCoarsening) {
		PartitionCoarsening parCoarsening;
		return parCoarsening.run(G, zeta);
	} else {
		ClusterContractor seqCoarsening;
		return seqCoarsening.run(G, zeta);
	}

}

Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) {
	Partition zetaFine(Gfine.upperNodeIdBound());
	zetaFine.setUpperBound(zetaCoarse.upperBound());

	Gfine.forNodes([&](node v) {
		node mv = nodeToMetaNode[v];
		index cv = zetaCoarse[mv];
		zetaFine[v] = cv;
	});

	return zetaFine;
}

} /* namespace NetworKit */
<|endoftext|>


<commit_before>/** ==========================================================================
 * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
 * with no warranties. This code is yours to share, use and modify with no
 * strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
 * ============================================================================*/

#include "crashhandler.hpp"

#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__))
#error "crashhandler_unix.cpp used but it's a windows system"
#endif

#include <csignal>
#include <cstring>
#include <unistd.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <thread>
#include <atomic>
#include <map>
#include <mutex>
#include <fmt/format.h>

 // Linux/Clang, OSX/Clang, OSX/gcc
#if (defined(__clang__) || defined(__APPLE__))
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif

//namespace {

	static const std::map<g3::SignalType, std::string> chSignals = {
	   {SIGABRT, "SIGABRT"},
	   {SIGFPE, "SIGFPE"},
	   {SIGILL, "SIGILL"},
	   {SIGSEGV, "SIGSEGV"},
	   {SIGTERM, "SIGTERM"},
	};

	//std::map<int, std::string> gSignals = kSignals;

	bool shouldDoExit()
	{
		static std::atomic<uint64_t> firstExit{ 0 };
		auto const count = firstExit.fetch_add(1, std::memory_order_relaxed);
		return (0 == count);
	}

	void restoreSignalHandler(int signal_number)
	{
		struct sigaction action;
		memset(&action, 0, sizeof(action)); //
		sigemptyset(&action.sa_mask);
		action.sa_handler = SIG_DFL; // take default action for the signal
		sigaction(signal_number, &action, NULL);
	}

	void exitWithDefaultSignalHandler(g3::SignalType fatal_signal_id, pid_t process_id)
	{
		const int signal_number = static_cast<int>(fatal_signal_id);
		restoreSignalHandler(signal_number);
		std::cerr << "\n\n" << __FUNCTION__ << ":" << __LINE__ << ". Signal ID: " << signal_number << "   \n\n" << std::flush;

		kill(process_id, signal_number);
		exit(signal_number);
	}

	// Dump of stack,. then exit through g3log background worker
	// ALL thanks to this thread at StackOverflow. Pretty much borrowed from:
	// Ref: http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
	void signalHandler(int signal_number, siginfo_t* info, void* unused_context)
	{
		// Only one signal will be allowed past this point
		if (false == shouldDoExit())
		{
			while (true)
			{
				std::this_thread::sleep_for(std::chrono::seconds(1));
			}
		}

		const std::string err_msg = fmt::format(
			"signal {:d} ({:s}) catched; shutting log-core down (errno: {}, signal code: {}, exit status: {})",
			signal_number, chSignals.at(signal_number), info->si_errno, info->si_code, info->si_status);

		CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
			"logs/log-core.log", "log-core", LogLevel::ERROR,
			err_msg, 0, "", "")));
		CLogManager::Get()->Destroy();

		exitWithDefaultSignalHandler(signal_number, info->si_pid);
	}

//} // end anonymous namespace

// Redirecting and using signals. In case of fatal signals g3log should log the fatal signal
// and flush the log queue and then "rethrow" the signal to exit
namespace g3 {
	// References:
	// sigaction : change the default action if a specific signal is received
	//             http://linux.die.net/man/2/sigaction
	//             http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=%2Fcom.ibm.aix.basetechref%2Fdoc%2Fbasetrf2%2Fsigaction.html
	//
	// signal: http://linux.die.net/man/7/signal and
	//         http://msdn.microsoft.com/en-us/library/xdkz3x12%28vs.71%29.asp
	//
	// memset +  sigemptyset: Maybe unnecessary to do both but there seems to be some confusion here
	//          ,plenty of examples when both or either are used
	//          http://stackoverflow.com/questions/6878546/why-doesnt-parent-process-return-to-the-exact-location-after-handling-signal_number
	//namespace internal {

		//bool shouldBlockForFatalHandling() {
		//   return true;  // For windows we will after fatal processing change it to false
		//}

		/// string representation of signal ID
		/*std::string exitReasonName(g3::SignalType fatal_id) {

		   int signal_number = static_cast<int>(fatal_id);
		   switch (signal_number) {
			  case SIGABRT: return "SIGABRT";
				 break;
			  case SIGFPE: return "SIGFPE";
				 break;
			  case SIGSEGV: return "SIGSEGV";
				 break;
			  case SIGILL: return "SIGILL";
				 break;
			  case SIGTERM: return "SIGTERM";
				 break;
			  default:
				 std::ostringstream oss;
				 oss << "UNKNOWN SIGNAL(" << signal_number << ")";
				 return oss.str();
		   }
		}*/

		// Triggered by g3log->g3LogWorker after receiving a FATAL trigger
		// which is LOG(FATAL), CHECK(false) or a fatal signal our signalhandler caught.
		// --- If LOG(FATAL) or CHECK(false) the signal_number will be SIGABRT
	//} // end g3::internal

	// This will override the default signal handler setup and instead
	// install a custom set of signals to handle
	/*void overrideSetupSignals(const std::map<int, std::string> overrideSignals) {
	   static std::mutex signalLock;
	   std::lock_guard<std::mutex> guard(signalLock);
	   for (const auto& sig : gSignals) {
		  restoreSignalHandler(sig.first);
	   }

	   gSignals = overrideSignals;
	   installCrashHandler(); // installs all the signal handling for gSignals
	}*/

	// restores the signal handler back to default
	//void restoreSignalHandlerToDefault() {
	//   overrideSetupSignals(kSignals);
	//}

	// installs the signal handling for whatever signal set that is currently active
	// If you want to setup your own signal handling then
	// You should instead call overrideSetupSignals()
	void installCrashHandler()
	{
		struct sigaction action;
		memset(&action, 0, sizeof(action));
		sigemptyset(&action.sa_mask);
		action.sa_sigaction = &signalHandler; // callback to crashHandler for fatal signals
											  // sigaction to use sa_sigaction file. ref: http://www.linuxprogrammingblog.com/code-examples/sigaction
		action.sa_flags = SA_SIGINFO;

		// do it verbose style - install all signal actions
		for (const auto &sig_pair : chSignals)
		{
			if (sigaction(sig_pair.first, &action, nullptr) < 0)
			{
				const std::string error = "sigaction - " + sig_pair.second;
				perror(error.c_str());
			}
		}
	}
} // end namespace g3

<commit_msg>cleanup UNIX crashhandler<commit_after>/** ==========================================================================
 * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
 * with no warranties. This code is yours to share, use and modify with no
 * strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
 * ============================================================================*/

#include "crashhandler.hpp"

#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__))
#error "crashhandler_unix.cpp used but it's a windows system"
#endif

#include <csignal>
#include <cstring>
#include <unistd.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <thread>
#include <atomic>
#include <map>
#include <mutex>
#include <fmt/format.h>

 // Linux/Clang, OSX/Clang, OSX/gcc
#if (defined(__clang__) || defined(__APPLE__))
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif

#include "CLogger.hpp"

namespace
{
	static const std::map<g3::SignalType, std::string> gSignals = {
	   {SIGABRT, "SIGABRT"},
	   {SIGFPE, "SIGFPE"},
	   {SIGILL, "SIGILL"},
	   {SIGSEGV, "SIGSEGV"},
	   {SIGTERM, "SIGTERM"},
	};

	bool IsFirstSignal()
	{
		static std::atomic<int> firstExit{ 0 };
		auto const count = firstExit.fetch_add(1, std::memory_order_relaxed);
		return (count == 0);
	}

	void RestoreSignalHandler(int signal_number)
	{
		struct sigaction action;
		memset(&action, 0, sizeof(action)); //
		sigemptyset(&action.sa_mask);
		action.sa_handler = SIG_DFL; // take default action for the signal
		sigaction(signal_number, &action, NULL);
	}

	void ExitWithDefaultSignalHandler(crashhandler::Signal fatal_signal_id, pid_t process_id)
	{
		const int signal_number = static_cast<int>(fatal_signal_id);
		RestoreSignalHandler(signal_number);
		std::cerr << "\n\n" << __FUNCTION__ << ":" << __LINE__ << ". Signal ID: " << signal_number << "   \n\n" << std::flush;

		kill(process_id, signal_number);
		exit(signal_number);
	}

	void SignalHandler(int signal_number, siginfo_t* info, void* unused_context)
	{
		// Only one signal will be allowed past this point
		if (!IsFirstSignal())
		{
			while (true)
				std::this_thread::sleep_for(std::chrono::seconds(1));
		}

		const std::string err_msg = fmt::format(
			"signal {:d} ({:s}) catched; shutting log-core down (errno: {}, signal code: {}, exit status: {})",
			signal_number, gSignals.at(signal_number), info->si_errno, info->si_code, info->si_status);

		CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
			"logs/log-core.log", "log-core", LogLevel::ERROR,
			err_msg, 0, "", "")));
		CLogManager::Get()->Destroy();

		ExitWithDefaultSignalHandler(signal_number, info->si_pid);
	}
}

namespace crashhandler
{
	void Install()
	{
		struct sigaction action;
		memset(&action, 0, sizeof(action));
		sigemptyset(&action.sa_mask);
		action.sa_sigaction = &SignalHandler;
		action.sa_flags = SA_SIGINFO;

		for (const auto &sig_pair : gSignals)
		{
			if (sigaction(sig_pair.first, &action, nullptr) < 0)
			{
				const std::string error = "sigaction - " + sig_pair.second;
				perror(error.c_str());
			}
		}
	}
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
//  *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "propertiesdialog.h"

PropertiesDialog::PropertiesDialog(QWidget *parent,RecipeDB *db):QWidget(parent)
{

    // Store pointer to database
    database=db;

    // Initialize internal variables
    propertyList=new IngredientPropertyList;

    // Design dialog

    layout = new QGridLayout( this, 1, 1, 0, 0);
    QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
    layout->addMultiCell( spacer_left, 1,4,0,0 );
    QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
    layout->addMultiCell(spacer_top,0,0,1,4);

    propertyListView=new KListView (this);
    layout->addMultiCellWidget (propertyListView,1,4,1,6);
    propertyListView->addColumn("Id");
    propertyListView->addColumn("Property");
    propertyListView->addColumn("Units");
    QSpacerItem* spacer_toButtons = new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
    layout->addItem(spacer_toButtons,1,7);
    addPropertyButton=new QPushButton(this);
    addPropertyButton->setText("+");
    addPropertyButton->setFixedSize(QSize(32,32));
    addPropertyButton->setFlat(true);
    layout->addWidget(addPropertyButton,1,8);
    QSpacerItem* spacer_betweenButtons = new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
    layout->addItem(spacer_betweenButtons,2,7);
    removePropertyButton=new QPushButton(this);
    removePropertyButton->setText("-");
    removePropertyButton->setFixedSize(QSize(32,32));
    removePropertyButton->setFlat(true);
    layout->addWidget(removePropertyButton,3,8);

    // Populate UI with data
    reloadPropertyList();

    // Connect signals & slots
    connect(addPropertyButton,SIGNAL(clicked()),this,SLOT(createNewProperty()));
    connect(removePropertyButton,SIGNAL(clicked()),this,SLOT(removeProperty()));
}

PropertiesDialog::~PropertiesDialog()
{
}

void PropertiesDialog::createNewProperty(void)
{
ElementList list;
database->loadUnits(&list);
CreatePropertyDialog* propertyDialog=new CreatePropertyDialog(&list);

if ( propertyDialog->exec() == QDialog::Accepted ) {
   QString name = propertyDialog->newPropertyName();
   QString units= propertyDialog->newUnitsName();
   int perUnits= 1;
   if (!((name.isNull()) || (units.isNull()))) // Make sure none of the fields are empty
      database->addProperty(name, units);
}
delete propertyDialog;

reloadPropertyList();
}

void PropertiesDialog::reloadPropertyList(void)
{
propertyList->clear(); // Empty list
propertyListView->clear(); // Clear the view
database->loadProperties(propertyList);

//Populate this data into the KListView
	for ( IngredientProperty *prop =propertyList->getFirst(); prop; prop =propertyList->getNext() )
	{
	QListViewItem *it= new QListViewItem(propertyListView,QString::number(prop->id),prop->name,prop->units);

	}

}

void PropertiesDialog::removeProperty(void)
{
int propertyID;
QListViewItem *it;
if (it=propertyListView->selectedItem())
{
propertyID=it->text(0).toInt();
}
database->removeProperty(propertyID);

}

void PropertiesDialog::reload(void)
{
this->reloadPropertyList();
}<commit_msg>Reload elements after removing an element from the list.<commit_after>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                                       *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
//  *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "propertiesdialog.h"

PropertiesDialog::PropertiesDialog(QWidget *parent,RecipeDB *db):QWidget(parent)
{

    // Store pointer to database
    database=db;

    // Initialize internal variables
    propertyList=new IngredientPropertyList;

    // Design dialog

    layout = new QGridLayout( this, 1, 1, 0, 0);
    QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
    layout->addMultiCell( spacer_left, 1,4,0,0 );
    QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
    layout->addMultiCell(spacer_top,0,0,1,4);

    propertyListView=new KListView (this);
    layout->addMultiCellWidget (propertyListView,1,4,1,6);
    propertyListView->addColumn("Id");
    propertyListView->addColumn("Property");
    propertyListView->addColumn("Units");
    QSpacerItem* spacer_toButtons = new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
    layout->addItem(spacer_toButtons,1,7);
    addPropertyButton=new QPushButton(this);
    addPropertyButton->setText("+");
    addPropertyButton->setFixedSize(QSize(32,32));
    addPropertyButton->setFlat(true);
    layout->addWidget(addPropertyButton,1,8);
    QSpacerItem* spacer_betweenButtons = new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
    layout->addItem(spacer_betweenButtons,2,7);
    removePropertyButton=new QPushButton(this);
    removePropertyButton->setText("-");
    removePropertyButton->setFixedSize(QSize(32,32));
    removePropertyButton->setFlat(true);
    layout->addWidget(removePropertyButton,3,8);

    // Populate UI with data
    reloadPropertyList();

    // Connect signals & slots
    connect(addPropertyButton,SIGNAL(clicked()),this,SLOT(createNewProperty()));
    connect(removePropertyButton,SIGNAL(clicked()),this,SLOT(removeProperty()));
}

PropertiesDialog::~PropertiesDialog()
{
}

void PropertiesDialog::createNewProperty(void)
{
ElementList list;
database->loadUnits(&list);
CreatePropertyDialog* propertyDialog=new CreatePropertyDialog(&list);

if ( propertyDialog->exec() == QDialog::Accepted ) {
   QString name = propertyDialog->newPropertyName();
   QString units= propertyDialog->newUnitsName();
   int perUnits= 1;
   if (!((name.isNull()) || (units.isNull()))) // Make sure none of the fields are empty
      database->addProperty(name, units);
}
delete propertyDialog;

reloadPropertyList();
}

void PropertiesDialog::reloadPropertyList(void)
{
propertyList->clear(); // Empty list
propertyListView->clear(); // Clear the view
database->loadProperties(propertyList);

//Populate this data into the KListView
	for ( IngredientProperty *prop =propertyList->getFirst(); prop; prop =propertyList->getNext() )
	{
	QListViewItem *it= new QListViewItem(propertyListView,QString::number(prop->id),prop->name,prop->units);

	}

}

void PropertiesDialog::removeProperty(void)
{
int propertyID;
QListViewItem *it;
if (it=propertyListView->selectedItem())
{
propertyID=it->text(0).toInt();
}
database->removeProperty(propertyID);

reloadPropertyList(); //Update the list
}

void PropertiesDialog::reload(void)
{
this->reloadPropertyList();
}<|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <string>
#include <vector>
#include <exception>

#include <configuration.hpp>

#include <ArgumentList.hpp>
#include <utils.hpp>
#include <SNR.hpp>

int main(int argc, char *argv[]) {
  bool DMsSamples = false;
  unsigned int padding = 0;
  AstroData::Observation observation;
  PulsarSearch::snrConf conf;

  try {
    isa::utils::ArgumentList args(argc, argv);
    DMsSamples = args.getSwitch("-dms_samples");
    bool samplesDMs = args.getSwitch("-samples_dms");
    if ( (DMsSamples && samplesDMs) || (!DMsSamples && !samplesDMs) ) {
      std::cerr << "-dms_samples and -samples_dms are mutually exclusive." << std::endl;
      return 1;
    }
    padding = args.getSwitchArgument< unsigned int >("-padding");
    conf.setNrThreadsD0(args.getSwitchArgument< unsigned int >("-threadsD0"));
    conf.setNrItemsD0(args.getSwitchArgument< unsigned int >("-itemsD0"));
    conf.setSubbandDedispersion(args.getSwitch("-subband"));
    observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >("-beams"));
    observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples"));
    if ( conf.getSubbandDedispersion() ) {
      observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), 0.0f, 0.0f);
    } else {
      observation.setDMSubbandingRange(1, 0.0f, 0.0f);
    }
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0f, 0.0f);
  } catch  ( isa::utils::SwitchNotFound & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << "Usage: " << argv[0] << " [-dms_samples | -samples_dms] -padding ... -threadsD0 ... -itemsD0 ... -beams ... -samples ... -dms ..." << std::endl;
    std::cerr << "\t -subband : -subbanding_dms ..." << std::endl;
    return 1;
  }

  // Generate kernel
  std::string * code;
  if ( DMsSamples ) {
    code = PulsarSearch::getSNRDMsSamplesOpenCL< inputDataType >(conf, inputDataName, observation,  observation.getNrSamplesPerBatch(), padding);
    std::cout << *code << std::endl;
  } else {
    code = PulsarSearch::getSNRSamplesDMsOpenCL< inputDataType >(conf, inputDataName, observation,  observation.getNrSamplesPerBatch(), padding);
    std::cout << *code << std::endl;
  }

  return 0;
}

<commit_msg>Update the use of Observation interface in printCode.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <string>
#include <vector>
#include <exception>

#include <configuration.hpp>

#include <ArgumentList.hpp>
#include <utils.hpp>
#include <SNR.hpp>

int main(int argc, char *argv[]) {
  bool DMsSamples = false;
  unsigned int padding = 0;
  AstroData::Observation observation;
  PulsarSearch::snrConf conf;

  try {
    isa::utils::ArgumentList args(argc, argv);
    DMsSamples = args.getSwitch("-dms_samples");
    bool samplesDMs = args.getSwitch("-samples_dms");
    if ( (DMsSamples && samplesDMs) || (!DMsSamples && !samplesDMs) ) {
      std::cerr << "-dms_samples and -samples_dms are mutually exclusive." << std::endl;
      return 1;
    }
    padding = args.getSwitchArgument< unsigned int >("-padding");
    conf.setNrThreadsD0(args.getSwitchArgument< unsigned int >("-threadsD0"));
    conf.setNrItemsD0(args.getSwitchArgument< unsigned int >("-itemsD0"));
    conf.setSubbandDedispersion(args.getSwitch("-subband"));
    observation.setNrSynthesizedBeams(args.getSwitchArgument< unsigned int >("-beams"));
    observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples"));
    if ( conf.getSubbandDedispersion() ) {
      observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), 0.0f, 0.0f);
    } else {
      observation.setDMSubbandingRange(1, 0.0f, 0.0f);
    }
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0f, 0.0f);
  } catch  ( isa::utils::SwitchNotFound & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << "Usage: " << argv[0] << " [-dms_samples | -samples_dms] -padding ... -threadsD0 ... -itemsD0 ... -beams ... -samples ... -dms ..." << std::endl;
    std::cerr << "\t -subband : -subbanding_dms ..." << std::endl;
    return 1;
  }

  // Generate kernel
  std::string * code;
  if ( DMsSamples ) {
    code = PulsarSearch::getSNRDMsSamplesOpenCL< inputDataType >(conf, inputDataName, observation,  observation.getNrSamplesPerBatch(), padding);
    std::cout << *code << std::endl;
  } else {
    code = PulsarSearch::getSNRSamplesDMsOpenCL< inputDataType >(conf, inputDataName, observation,  observation.getNrSamplesPerBatch(), padding);
    std::cout << *code << std::endl;
  }

  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cfrstd.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 15:23:09 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <cfrstd.hxx>

// NOT FULLY DEFINED SERVICES

/*                      CSS Styles
                        ----------

Colors:
-   light background color              #eeeeff
-   dark background color               #ccccff
-   self in navibar background color    #2222ad

Fonts:
-   page title              20, bold, Arial
-   navibar main            12, bold, Arial
-   navibar sub              8, Arial, kapitlchen
-   attrtable title line     8, bold, Arial, kapitlchen
-   attrtable value line     8, Arial kapitlchen

-   namespace chain         13, bold
-   table title             13, bold
-   template line           13

-   member paragraph title  12, bold

-   docu paragraph title    11, bold
-   standard text           11

-   hierarchy               11, monospace

classes:

    td.title                page title
    h3                      table title
    h4                      member paragraph title

    td.nmain                navigation main bar
    td.nsub                 navigation sub bar
    a.nmain                 links in navigation main bar
    a.nsub                  links in navigation sub bar

    td.attr1                attribute table head line
    td.attr2                attribute table value line

    p.namechain             namespace chain in head of pages
    p.tpl                   template line in head of pages

    pre.doc                 preformatted docu
    pre.hierarchy           class bases hierarchy graphic

    dl.syntax               function- or variable-declaration field
    a.syntax                link in function- or variable-declaration field

    p.dt                    docu paragraph title
    dl.dt                   docu paragraph title

    p                       standard text
    dl                      standard text
    dd                      standard text
*/

#define CRLF "\n"

namespace
{
const char * const C_sStdStyle =
    "h3 { font-size:13pt; font-weight:bold; margin-top:3pt; margin-bottom:1pt; }"CRLF
    "p, dt, dd, pre  { font-size:11pt; margin-top:3pt; margin-bottom:1pt; }"CRLF

    "table.lightbg { background-color:#eeeeff; }"CRLF
    "table.subtitle { margin-top:6pt; margin-bottom:6pt; }"CRLF

    "td { font-size:11pt; }"CRLF
    "td.title { font-family: Arial; font-size:19pt; font-weight:bold; text-align:center; background-color:#ccccff; line-height:30pt; }"CRLF
    "td.subtitle { font-family: Arial; font-size:13pt; background-color:#ccccff; line-height:20pt; }"CRLF
    "td.crosstitle { font-size:12pt; font-weight:bold; background-color:#eeeeff; line-height:15pt; }"CRLF
    "td.imdetail { width:100%; background-color:#eeeeff; }"CRLF
    "a.membertitle { font-size:12pt; font-weight:bold; line-height:18pt; }"CRLF

    "td.imsum_left { width:30%;  }"CRLF
    "td.imsum_right { width:70%;  }"CRLF

    "td.navimain, a.navimain { text-align:center; font-family: Arial; font-size:12pt; font-weight:bold; }"CRLF
    "td.navimainself { text-align:center; font-family: Arial; font-size:12pt; font-weight:bold; color:#ffffff; background-color:#2222ad; }"CRLF
    "td.navimainnone { text-align:center; font-family: Arial; font-size:12pt; }"CRLF
    "td.attrtitle { font-weight:bold; background-color:#eeeeff; }"CRLF
    "td.navisub, a.navisub, td.attrtitle, td.attrvalue { text-align:center; font-family: Arial; font-size:9pt; font-variant:small-caps; }"CRLF
    "td.navimain, td.navisub { padding-left:7pt; padding-right:7pt; }"CRLF

    "p.raise  { font-size:11pt; margin-top:0pt; text-align:right; padding-right:5pt; }"CRLF

    "a.navimain, a.navisub  { color:#000000; }"CRLF
    ".dt     { font-weight:bold; }"CRLF
    ".namechain  { font-size:13pt; font-weight:bold; margin-top:3pt; margin-bottom:6pt; }"CRLF
    ".tpl        { font-size:13pt; margin-top:3pt; margin-bottom:6pt; }"CRLF
    ;
}   // anonymous namespace

StdFrame::StdFrame()
    :   sDevelopersGuideHtmlRoot(),
        bSimpleLinks(false)
{
}

DYN Html_Image *
StdFrame::LogoSrc() const
{
    return 0;

//    return  new Html_Image( "logodot-blu.gif",
//                            "109",
//                            "54",
//                            "RIGHT",
//                            "0",
//                            "OpenOffice" );

}

const char *
StdFrame::LogoLink() const
{
    return "";
//  return "http://www.sun.com";
//  return "http://www.openoffice.org";
}

const char *
StdFrame::CopyrightText() const
{
//  return "Copyright © 2002 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303 USA.";
    return "Copyright © 2003 Sun Microsystems, Inc.";
//  return "Copyright 2001 OpenOffice.org Foundation. All Rights Reserved.";

}

const char *
StdFrame::CssStyle() const
{
    return C_sStdStyle;
}

const char *
StdFrame::DevelopersGuideHtmlRoot() const
{
    return sDevelopersGuideHtmlRoot;
}

bool
StdFrame::SimpleLinks() const
{
    return bSimpleLinks;
}

void
StdFrame::Set_DevelopersGuideHtmlRoot( const String & i_directory )
{
    if (NOT i_directory.empty())
    {
        if (i_directory.char_at(i_directory.length()-1) == '/')
        {
            sDevelopersGuideHtmlRoot.assign(i_directory,i_directory.length()-1);
            return;
        }
    }
    sDevelopersGuideHtmlRoot = i_directory;
}

void
StdFrame::Set_SimpleLinks()
{
    bSimpleLinks = true;
}
<commit_msg>INTEGRATION: CWS adc11 (1.6.14); FILE MERGED 2005/02/18 18:28:08 np 1.6.14.1: #i39458#, #115997#<commit_after>/*************************************************************************
 *
 *  $RCSfile: cfrstd.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 08:52:42 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <cfrstd.hxx>

// NOT FULLY DEFINED SERVICES

/*                      CSS Styles
                        ----------

Colors:
-   light background color              #eeeeff
-   dark background color               #ccccff
-   self in navibar background color    #2222ad

Fonts:
-   page title              20, bold, Arial
-   navibar main            12, bold, Arial
-   navibar sub              8, Arial, kapitlchen
-   attrtable title line     8, bold, Arial, kapitlchen
-   attrtable value line     8, Arial kapitlchen

-   namespace chain         13, bold
-   table title             13, bold
-   template line           13

-   member paragraph title  12, bold

-   docu paragraph title    11, bold
-   standard text           11

-   hierarchy               11, monospace

classes:

    td.title                page title
    h3                      table title
    h4                      member paragraph title

    td.nmain                navigation main bar
    td.nsub                 navigation sub bar
    a.nmain                 links in navigation main bar
    a.nsub                  links in navigation sub bar

    td.attr1                attribute table head line
    td.attr2                attribute table value line

    p.namechain             namespace chain in head of pages
    p.tpl                   template line in head of pages

    pre.doc                 preformatted docu
    pre.hierarchy           class bases hierarchy graphic

    dl.syntax               function- or variable-declaration field
    a.syntax                link in function- or variable-declaration field

    p.dt                    docu paragraph title
    dl.dt                   docu paragraph title

    p                       standard text
    dl                      standard text
    dd                      standard text
*/

#define CRLF "\n"

namespace
{
const char * const C_sStdStyle =
    "/*See bottom of file for explanations.*/"CRLF
    CRLF
    "body { background-color:#ffffff; }"CRLF
    CRLF
    "h3             { font-size:13pt; font-weight:bold;"CRLF
    "                 margin-top:3pt; margin-bottom:1pt; }"CRLF
    "p, dt, dd, pre { font-size:11pt;"CRLF
    "                 margin-top:3pt; margin-bottom:1pt; }"CRLF
    "pre            { font-family:monospace; }"CRLF
    CRLF
    "table.lightbg  { background-color:#eeeeff; }"CRLF
    "table.subtitle { margin-top:6pt; margin-bottom:6pt; }"CRLF
    CRLF
    "td             {                     font-size:11pt; }"CRLF
    "td.title       { font-family: Arial; font-size:19pt; font-weight:bold;"CRLF
    "                 line-height:30pt;   background-color:#ccccff; text-align:center; }"CRLF
    "td.subtitle    { font-family: Arial; font-size:13pt;"CRLF
    "                 line-height:20pt;   background-color:#ccccff; }"CRLF
    "td.crosstitle  {                     font-size:12pt; font-weight:bold;"CRLF
    "                 line-height:15pt;   background-color:#eeeeff; }"CRLF
    "td.imdetail    { width:100%;         background-color:#eeeeff; }"CRLF
    CRLF
    "td.imsum_left  { width:30%;  }"CRLF
    "td.imsum_right { width:70%;  }"CRLF
    CRLF
    "td.navimain, a.navimain"CRLF
    "                   { text-align:center; font-family: Arial; font-size:12pt; font-weight:bold; }"CRLF
    "td.navimainself    { text-align:center; font-family: Arial; font-size:12pt; font-weight:bold;"CRLF
    "                     color:#ffffff; background-color:#2222ad; }"CRLF
    "td.navimainnone    { text-align:center; font-family: Arial; font-size:12pt; }"CRLF
    "td.navisub, a.navisub"CRLF
    "                   { text-align:center; font-family: Arial; font-size:9pt; font-variant:small-caps; }"CRLF
    "td.navimain, td.navisub"CRLF
    "                   { padding-left:7pt; padding-right:7pt; }"CRLF
    CRLF
    "a.membertitle  { font-size:12pt; font-weight:bold; line-height:18pt; }"CRLF
    "a.navimain, a.navisub  { color:#000000; }"CRLF
    ".dt            { font-weight:bold; }"CRLF
    ".namechain     { font-size:13pt; font-weight:bold;"CRLF
    "                 margin-top:3pt; margin-bottom:6pt; }"CRLF
    ;

const char * const C_sCssExplanations =
    "/* Explanation of CSS classes:"CRLF
    CRLF
    "table.lightbg      Background of navigation bar."CRLF
    ".navimain          Text in main navigation bar."CRLF
    ".navisub           Text in lower navigation bar."CRLF
    "td.navimainself    Cell in main navigation bar with \"selected\" shadow: You are here."CRLF
    "td.navimainnone    Cell in main navigation bar with no link."CRLF
    CRLF
    ".namechain         Line with current module path."CRLF
    CRLF
    "td.crosstitle      Comment box for bases (base interfaces etc.)"CRLF
    "td.imsum_left      Left part of such boxes."CRLF
    "td.imsum_right     Right part of such boxes."CRLF
    CRLF
    "td.title           Main title of the page like \"interface XYz\""CRLF
    ".subtitle          Tables, and head cells of those, which list members"CRLF
    "                   like \"method summary\" and \"method details\"."CRLF
    CRLF
    "td.imdetail        Background table of method's detail description."CRLF
    "a.membertitle      Method name (as jump label) in method's detail"CRLF
    "                   description."CRLF
    "*/"CRLF
    ;
}   // anonymous namespace

StdFrame::StdFrame()
    :   sDevelopersGuideHtmlRoot(),
        bSimpleLinks(false)
{
}

DYN Html_Image *
StdFrame::LogoSrc() const
{
    return 0;

//    return  new Html_Image( "logodot-blu.gif",
//                            "109",
//                            "54",
//                            "RIGHT",
//                            "0",
//                            "OpenOffice" );

}

const char *
StdFrame::LogoLink() const
{
    return "";
//  return "http://www.sun.com";
//  return "http://www.openoffice.org";
}

const char *
StdFrame::CopyrightText() const
{
    return "Copyright © 2003 Sun Microsystems, Inc.";

//  return "Copyright © 2002 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303 USA.";
//  return "Copyright 2001 OpenOffice.org Foundation. All Rights Reserved.";
}

const char *
StdFrame::CssStyle() const
{
    return C_sStdStyle;
}

const char *
StdFrame::CssStylesExplanation() const
{
    return C_sCssExplanations;
}

const char *
StdFrame::DevelopersGuideHtmlRoot() const
{
    return sDevelopersGuideHtmlRoot;
}

bool
StdFrame::SimpleLinks() const
{
    return bSimpleLinks;
}

void
StdFrame::Set_DevelopersGuideHtmlRoot( const String & i_directory )
{
    if (NOT i_directory.empty())
    {
        if (i_directory.char_at(i_directory.length()-1) == '/')
        {
            sDevelopersGuideHtmlRoot.assign(i_directory,i_directory.length()-1);
            return;
        }
    }
    sDevelopersGuideHtmlRoot = i_directory;
}

void
StdFrame::Set_SimpleLinks()
{
    bSimpleLinks = true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_tag.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 16:48:57 $
 *
 *  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_autodoc.hxx"

#include <precomp.h>
#include "hfi_tag.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"

using ary::info::DocuTex2;

inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
    aTextOut.Out().Enter(o_rText);
}

inline void
HF_IdlTag::Leave_TextOut() const
{
    aTextOut.Out().Leave();
}

inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
    i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}

HF_IdlTag::HF_IdlTag( Environment &                 io_rEnv,
                      const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl( io_rEnv, 0 ),
        pTitleOut(0),
        aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}

HF_IdlTag::~HF_IdlTag()
{
}

void
HF_IdlTag::Produce_byData( Xml::Element &              o_rTitle,
                           Xml::Element &              o_rText,
                           const ary::info::AtTag2 &   i_rTag ) const
{
    pTitleOut = &o_rTitle;
    Enter_TextOut(o_rText);
    i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
    Leave_TextOut();
}

void
HF_IdlTag::Produce_byData( Xml::Element &      o_rTitle,
                           Xml::Element &      o_rText,
                           const std::vector< csi::dsapi::DT_SeeAlsoAtTag* > &
                                                i_seeAlsoVector ) const
{
    o_rTitle << "See also";
    for ( std::vector< csi::dsapi::DT_SeeAlsoAtTag* >::const_iterator
            it = i_seeAlsoVector.begin();
          it != i_seeAlsoVector.end();
          ++it )
    {
        if (it != i_seeAlsoVector.begin())
        {
            o_rText << ", ";
        }
        HF_IdlTypeText
            aLinkText(Env(), o_rText, true, &aTextOut.ScopeGivingCe());
        aLinkText.Produce_byData( (*it)->LinkText() );
    }
}

void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << i_rTag.Title();
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << "See also";

    HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
    aLinkText.Produce_byData( i_rTag.LinkText() );

    aTextOut.CurOut() << new Html::LineBreak;
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
    csv_assert( pTitleOut != 0 );
    StreamLock sl(100);
    *pTitleOut
        << ( sl() << "Parameter " << i_rTag.Title() << c_str );
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
    csv_assert(pTitleOut != 0);

    if ( i_rTag.Text().IsEmpty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay =
        autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
                                        i_rTag.Text().TextOfFirstToken() );
    if (sDisplay.empty())
        return;

    *pTitleOut << "Since ";
    DocuTex2 aHelp;
    aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
    PutText_Out(aHelp);
}

//********************      HF_IdlShortDocu     *********************/

HF_IdlShortDocu::HF_IdlShortDocu( Environment &         io_rEnv,
                                  Xml::Element &        o_rOut )
    :   HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}

HF_IdlShortDocu::~HF_IdlShortDocu()
{
}

void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
    if (i_rCe.Docu() == 0)
        return;

    const ce_info &
        rDocu = *i_rCe.Docu();
    if ( rDocu.IsDeprecated() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if ( rDocu.IsOptional() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aText( Env(), &CurOut(), i_rCe);
    rDocu.Short().DisplayAt(aText);
}

//********************      HF_IdlDocuTextDisplay       *********************/

HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment &                 io_rEnv,
                                              Xml::Element *                o_pOut,
                                              const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl(io_rEnv, o_pOut),
        sScope(),
        sLinkToken(),
        bGatherLink(false),
        pScopeGivingCe(&i_rScopeGivingCe)
{
}

HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}

void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
    if (bGatherLink)
    {
        if (sLinkToken.length() == 0)
        {
            sLinkToken = i_rToken.GetText();
            return;
        }
        else
        {
            if ( pScopeGivingCe == 0 )
            {   // only in original file
                TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
            }

//          Would be duplicate, therefore we do nothing:
//            else
//            {
//                Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
//                Cerr() << "  Link won't be created, but all tokens shown plain." << Endl();
//                Cerr() << "  \"" << sLinkToken << "\"";
//                if ( pScopeGivingCe != 0 )
//                    Cerr() << " in " << pScopeGivingCe->LocalName();
//                Cerr() << Endl();
//            }

            StopLinkGathering();
        }
    }   // endif (bGatherLink)

    CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
}

void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateTypeLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateMemberLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
    CurOut()
        >> *new Html::Bold
           << i_rToken.GetText();
    CurOut()
        << " ";
}

void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
    CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}

void
HF_IdlDocuTextDisplay::Display_EOL()
{
    CurOut() << "\n";
}

void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
    if (strchr(sLinkToken,':') != 0)
    {
        TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
        CurOut() << sLinkToken;
        return;
    }
    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
    aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}

void
HF_IdlDocuTextDisplay::CreateMemberLink()
{

    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());

    const char *
        sSplit = strchr(sLinkToken,':');

    if (sSplit != 0)
    {
        String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
        String sMember(sSplit+2);

        if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
            aLink.Produce_LinkInDocu(sScope, sCe, sMember);
        else
            aLink.Produce_LocalLinkInDocu(sMember);
    }
    else
    {
        aLink.Produce_LocalLinkInDocu(sLinkToken);
    }
}
<commit_msg>INTEGRATION: CWS adc17 (1.12.18); FILE MERGED 2007/08/31 14:45:31 np 1.12.18.2: #i80569# remove wrong pchs. 2007/08/10 10:37:09 np 1.12.18.1: #i23626 correct spacing in autodoc output#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_tag.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 13:59:20 $
 *
 *  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
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_tag.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"

using ary::info::DocuTex2;

inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
    aTextOut.Out().Enter(o_rText);
}

inline void
HF_IdlTag::Leave_TextOut() const
{
    aTextOut.Out().Leave();
}

inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
    i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}

HF_IdlTag::HF_IdlTag( Environment &                 io_rEnv,
                      const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl( io_rEnv, 0 ),
        pTitleOut(0),
        aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}

HF_IdlTag::~HF_IdlTag()
{
}

void
HF_IdlTag::Produce_byData( Xml::Element &              o_rTitle,
                           Xml::Element &              o_rText,
                           const ary::info::AtTag2 &   i_rTag ) const
{
    pTitleOut = &o_rTitle;
    Enter_TextOut(o_rText);
    i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
    Leave_TextOut();
}

void
HF_IdlTag::Produce_byData( Xml::Element &      o_rTitle,
                           Xml::Element &      o_rText,
                           const std::vector< csi::dsapi::DT_SeeAlsoAtTag* > &
                                                i_seeAlsoVector ) const
{
    o_rTitle << "See also";
    for ( std::vector< csi::dsapi::DT_SeeAlsoAtTag* >::const_iterator
            it = i_seeAlsoVector.begin();
          it != i_seeAlsoVector.end();
          ++it )
    {
        if (it != i_seeAlsoVector.begin())
        {
            o_rText << ", ";
        }
        HF_IdlTypeText
            aLinkText(Env(), o_rText, true, &aTextOut.ScopeGivingCe());
        aLinkText.Produce_byData( (*it)->LinkText() );
    }
}

void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << i_rTag.Title();
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << "See also";

    HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
    aLinkText.Produce_byData( i_rTag.LinkText() );

    aTextOut.CurOut() << new Html::LineBreak;
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
    csv_assert( pTitleOut != 0 );
    StreamLock sl(100);
    *pTitleOut
        << ( sl() << "Parameter " << i_rTag.Title() << c_str );
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
    csv_assert(pTitleOut != 0);

    if ( i_rTag.Text().IsEmpty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay =
        autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
                                        i_rTag.Text().TextOfFirstToken() );
    if (sDisplay.empty())
        return;

    *pTitleOut << "Since ";
    DocuTex2 aHelp;
    aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
    PutText_Out(aHelp);
}

//********************      HF_IdlShortDocu     *********************/

HF_IdlShortDocu::HF_IdlShortDocu( Environment &         io_rEnv,
                                  Xml::Element &        o_rOut )
    :   HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}

HF_IdlShortDocu::~HF_IdlShortDocu()
{
}

void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
    if (i_rCe.Docu() == 0)
        return;

    const ce_info &
        rDocu = *i_rCe.Docu();
    if ( rDocu.IsDeprecated() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if ( rDocu.IsOptional() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aText( Env(), &CurOut(), i_rCe);
    rDocu.Short().DisplayAt(aText);
}

//********************      HF_IdlDocuTextDisplay       *********************/

HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment &                 io_rEnv,
                                              Xml::Element *                o_pOut,
                                              const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl(io_rEnv, o_pOut),
        sScope(),
        sLinkToken(),
        bGatherLink(false),
        pScopeGivingCe(&i_rScopeGivingCe)
{
}

HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}

void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
    if (bGatherLink)
    {
        if (sLinkToken.length() == 0)
        {
            sLinkToken = i_rToken.GetText();
            return;
        }
        else
        {
            if ( pScopeGivingCe == 0 )
            {   // only in original file
                TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
            }

//          Would be duplicate, therefore we do nothing:
//            else
//            {
//                Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
//                Cerr() << "  Link won't be created, but all tokens shown plain." << Endl();
//                Cerr() << "  \"" << sLinkToken << "\"";
//                if ( pScopeGivingCe != 0 )
//                    Cerr() << " in " << pScopeGivingCe->LocalName();
//                Cerr() << Endl();
//            }

            StopLinkGathering();
        }
    }   // endif (bGatherLink)

//DBG    CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
    CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}

void
HF_IdlDocuTextDisplay::Display_White()
{
    CurOut() << " ";
}

void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateTypeLink();
// DBG      CurOut() << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateMemberLink();
// DBG      CurOut() << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
    CurOut()
        >> *new Html::Bold
           << i_rToken.GetText();
// DBG      CurOut() << " ";
}

void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
    CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}

void
HF_IdlDocuTextDisplay::Display_EOL()
{
    CurOut() << "\n";
}

void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
    if (strchr(sLinkToken,':') != 0)
    {
        TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
        CurOut() << sLinkToken;
        return;
    }
    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
    aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}

void
HF_IdlDocuTextDisplay::CreateMemberLink()
{

    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());

    const char *
        sSplit = strchr(sLinkToken,':');

    if (sSplit != 0)
    {
        String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
        String sMember(sSplit+2);

        if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
            aLink.Produce_LinkInDocu(sScope, sCe, sMember);
        else
            aLink.Produce_LocalLinkInDocu(sMember);
    }
    else
    {
        aLink.Produce_LocalLinkInDocu(sLinkToken);
    }
}
<|endoftext|>