<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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.

*******************************************************************************/

//==============================================================================
// CLI application
//==============================================================================

#include "cliapplication.h"
#include "cliinterface.h"
#include "cliutils.h"
#include "pluginmanager.h"

//==============================================================================

#include <iostream>

//==============================================================================

#include <Qt>

//==============================================================================

#include <QCoreApplication>
#include <QXmlStreamReader>

//==============================================================================

namespace OpenCOR {

//==============================================================================

CliApplication::CliApplication(QCoreApplication *pApp) :
    mApp(pApp),
    mPluginManager(0),
    mLoadedCliPlugins(Plugins())
{
}

//==============================================================================

CliApplication::~CliApplication()
{
    // Delete some internal objects

    delete mPluginManager;
}

//==============================================================================

void CliApplication::loadPlugins()
{
    // Load all the plugins by creating our plugin manager

    mPluginManager = new PluginManager(mApp, false);

    // Keep track of our loaded CLI plugins

    foreach (Plugin *plugin, mPluginManager->loadedPlugins())
        if (qobject_cast<CliInterface *>(plugin->instance()))
            mLoadedCliPlugins << plugin;
}

//==============================================================================

QString CliApplication::pluginDescription(Plugin *pPlugin) const
{
    // Retrieve and return the plugin's default description, stripped out of all
    // its HTML (should it have some)
    // Note: we enclose the CLI plugin's default description within an html tag
    //       so that the stripping out can proceed without any problem...

    QXmlStreamReader description(""+pPlugin->info()->description()+"");
    QString res = QString();

    while (!description.atEnd())
        if (description.readNext() == QXmlStreamReader::Characters)
            res += description.text();

    return res;
}

//==============================================================================

void CliApplication::about() const
{
    // Output some information about OpenCOR

    version();

    std::cout << osName().toStdString() << std::endl;
    std::cout << copyright().toStdString() << std::endl;
    std::cout << std::endl;
    std::cout << mApp->applicationName().toStdString()
              << " is a cross-platform CellML-based modelling environment,"
              << " which can be used to organise, edit,"
              << " simulate and analyse CellML files."
              << std::endl;
}

//==============================================================================

bool CliApplication::command(const QStringList &pArguments, int *pRes) const
{
    // Make sure that we have at least one argument

    if (!pArguments.count())
        return false;

    // Determine whether the command is to be executed by all the CLI plugins or
    // only a given CLI plugin

    static const QString CommandSeparator = "::";

    QString commandName = pArguments.first();
    QString commandPlugin = commandName;
    int commandSeparatorPosition = commandName.indexOf(CommandSeparator);

    if (commandSeparatorPosition != -1) {
        commandPlugin = commandPlugin.remove(commandSeparatorPosition, commandName.length()-commandSeparatorPosition);
        commandName = commandName.remove(0, commandPlugin.length()+CommandSeparator.length());

        // Make sure that the plugin to which the command is to be sent exists

        if (!commandPlugin.isEmpty()) {
            bool pluginFound = false;
            bool pluginHasCliSupport = false;

            foreach (Plugin *plugin, mPluginManager->loadedPlugins())
                if (!commandPlugin.compare(plugin->name())) {
                    pluginFound = true;
                    pluginHasCliSupport = qobject_cast<CliInterface *>(plugin->instance());

                    break;
                }

            if (!pluginFound) {
                std::cout << "The " << commandPlugin.toStdString() << " plugin could not be found." << std::endl;

                return true;
            } else if (!pluginHasCliSupport) {
                std::cout << "The " << commandPlugin.toStdString() << " plugin does not support the execution of commands." << std::endl;

                return true;
            }
        }
    } else {
        commandPlugin = QString();
    }

    // Make sure that we have a command name

    if (commandName.isEmpty())
        return false;

    // Make sure that we have at least one CLI-enabled plugin

    if (mLoadedCliPlugins.isEmpty()) {
        std::cout << "No plugins could be found to run the command." << std::endl;

        return true;
    }

    // Send the command to the plugin(s)

    foreach (Plugin *plugin, mLoadedCliPlugins)
        if (    commandPlugin.isEmpty()
            || !commandPlugin.compare(plugin->name())) {
            QStringList arguments = pArguments;

            arguments.removeFirst();
            // Note: since the first argument corresponds to the command
            //       itself...

            if (qobject_cast<CliInterface *>(plugin->instance())->executeCommand(commandName, arguments))
                *pRes = -1;
        }

    return true;
}

//==============================================================================

void CliApplication::help() const
{
    // Output some help

    std::cout << "Usage: " << mApp->applicationName().toStdString()
              << " [-a|--about] [-c|--command [<plugin>::]<command> <options>] [-h|--help] [-p|--plugins] [-s|--status] [-v|--version] [<files>]"
              << std::endl;
    std::cout << " -a, --about     Display some information about OpenCOR"
              << std::endl;
    std::cout << " -c, --command   Send a command to one or all the CLI plugins"
              << std::endl;
    std::cout << " -h, --help      Display this help information"
              << std::endl;
    std::cout << " -p, --plugins   Display all the CLI plugins"
              << std::endl;
    std::cout << " -s, --status    Display the status of all the plugins"
              << std::endl;
    std::cout << " -v, --version   Display the version of OpenCOR"
              << std::endl;
}

//==============================================================================

void CliApplication::plugins() const
{
    // Output some information about our CLI plugins, so first make sure that we
    // have at least one of them

    if (mLoadedCliPlugins.isEmpty()) {
        std::cout << "No CLI plugins could be found." << std::endl;

        return;
    }

    // First, we retrieve all the CLI plugins information

    QStringList pluginsInfo = QStringList();

    foreach (Plugin *plugin, mLoadedCliPlugins) {
        // Retrieve the CLI plugin and its default description

        QString pluginInfo = plugin->name();
        QString pluginDesc = pluginDescription(plugin);

        if (!pluginDesc.isEmpty())
            pluginInfo += ": "+pluginDesc;

        // Add the plugin information to our list

        pluginsInfo << pluginInfo;
    }

    // Now, we can output the plugin information in alphabetical order

    pluginsInfo.sort(Qt::CaseInsensitive);

    if (pluginsInfo.count() == 1)
        std::cout << "The following CLI plugin is available:" << std::endl;
    else
        std::cout << "The following CLI plugins are available:" << std::endl;

    foreach (const QString &pluginInfo, pluginsInfo)
        std::cout << " - " << pluginInfo.toStdString() << std::endl;
}

//==============================================================================

void CliApplication::status() const
{
    // Output the status of all the plugins that should (have) normally be(en)
    // loaded, so first make sure that we have at least one of them

    if (mPluginManager->loadedPlugins().isEmpty()) {
        std::cout << "No plugins could be found." << std::endl;

        return;
    }

    // First, we retrieve all the plugins information

    QStringList pluginsInfo = QStringList();

    foreach (Plugin *plugin, mPluginManager->plugins()) {
        // Retrieve the plugin and its status

        QString pluginInfo = plugin->name()+": ";

        // Retrieve the plugin's status

        switch (plugin->status()) {
        case Plugin::NotWanted:
            pluginInfo += "the plugin is not wanted.";

            break;
        case Plugin::NotNeeded:
            pluginInfo += "the plugin is not needed.";

            break;
        case Plugin::NotLoaded:
            pluginInfo += QString("the plugin could not be loaded due to the following problem: %1.").arg(formatMessage(plugin->statusErrors()));

            break;
        case Plugin::NotPlugin:
            pluginInfo += "this is not a plugin.";

            break;
        case Plugin::NotCorePlugin:
            pluginInfo += "the plugin claims to be the core plugin, but it is not.";

            break;
        case Plugin::InvalidCorePlugin:
            pluginInfo += "the plugin should be the core plugin, but it does not support the core interface.";

            break;
        case Plugin::NotCliPluginNoCliSupport:
            pluginInfo += "the plugin supports the CLI interface, but it does not claim to be CLI-capable.";

            break;
        case Plugin::NotCliPluginNoCliInterface:
            pluginInfo += "the plugin claims to be CLI-capable, but it does not support the CLI interface.";

            break;
        case Plugin::MissingOrInvalidDependencies:
            if (plugin->statusErrorsCount() == 1)
                pluginInfo += QString("the plugin could not be loaded due to the %1 plugin being missing or invalid.").arg(plugin->statusErrors());
            else
                pluginInfo += QString("the plugin could not be loaded due to missing or invalid plugins:\n%1").arg(plugin->statusErrors());

            break;
        default:
            // Plugin::Loaded

            pluginInfo += "the plugin is loaded and fully functional.";
        }

        // Add the plugin information to our list

        pluginsInfo << pluginInfo;
    }

    // Now, we can output the plugin information in alphabetical order

    pluginsInfo.sort(Qt::CaseInsensitive);

    if (pluginsInfo.count() == 1)
        std::cout << "The following plugin is available:" << std::endl;
    else
        std::cout << "The following plugins are available:" << std::endl;

    foreach (const QString &pluginInfo, pluginsInfo)
        std::cout << " - " << pluginInfo.toStdString() << std::endl;
}

//==============================================================================

void CliApplication::version() const
{
    // Output the version of OpenCOR

    std::cout << OpenCOR::version(mApp).toStdString() << std::endl;
}

//==============================================================================

bool CliApplication::run(int *pRes)
{
    // See what needs doing with the CLI options, if anything

    *pRes = 0;   // By default, everything is fine

    bool aboutOption = false;
    bool commandOption = false;
    bool helpOption = false;
    bool pluginsOption = false;
    bool statusOption = false;
    bool versionOption = false;

    QStringList appArguments = mApp->arguments();
    QStringList commandArguments = QStringList();

    appArguments.removeFirst();
    // Note: we remove the first argument since it corresponds to the full path
    //       to our executable, which we are not interested in...

    foreach (const QString &argument, appArguments) {
        if (!argument.compare("-a") || !argument.compare("--about")) {
            aboutOption = true;
        } else if (!argument.compare("-c") || !argument.compare("--command")) {
            commandOption = true;
        } else if (!argument.compare("-h") || !argument.compare("--help")) {
            helpOption = true;
        } else if (!argument.compare("-p") || !argument.compare("--plugins")) {
            pluginsOption = true;
        } else if (!argument.compare("-s") || !argument.compare("--status")) {
            statusOption = true;
        } else if (!argument.compare("-v") || !argument.compare("--version")) {
            versionOption = true;
        } else if (argument.startsWith("-")) {
            // The user provided at least one unknown option

            help();

            *pRes = -1;

            break;
        } else if (commandOption) {
            // Not an option, so we consider it to be part of a command

            commandArguments << argument;
        }
    }

    // Handle the option the user requested, if any

    if (!*pRes) {
        if (aboutOption) {
            about();
        } else if (commandOption) {
            // Make sure that we have at least one argument (which would be the
            // command itself) before loading the plugins and then sending the
            // command to the plugin(s)

            if (commandArguments.isEmpty()) {
                help();
            } else {
                loadPlugins();

                if (!command(commandArguments, pRes))
                    help();
            }
        } else if (helpOption) {
            help();
        } else if (pluginsOption) {
            loadPlugins();

            plugins();
        } else if (statusOption) {
            loadPlugins();

            status();
        } else if (versionOption) {
            version();
        } else {
            // The user didn't provide any option that requires running OpenCOR
            // as a CLI application

            return false;
        }
    }

    return true;
}

//==============================================================================

}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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.

*******************************************************************************/

//==============================================================================
// CLI application
//==============================================================================

#include "cliapplication.h"
#include "cliinterface.h"
#include "cliutils.h"
#include "pluginmanager.h"

//==============================================================================

#include <iostream>

//==============================================================================

#include <Qt>

//==============================================================================

#include <QCoreApplication>
#include <QXmlStreamReader>

//==============================================================================

namespace OpenCOR {

//==============================================================================

CliApplication::CliApplication(QCoreApplication *pApp) :
    mApp(pApp),
    mPluginManager(0),
    mLoadedCliPlugins(Plugins())
{
}

//==============================================================================

CliApplication::~CliApplication()
{
    // Delete some internal objects

    delete mPluginManager;
}

//==============================================================================

void CliApplication::loadPlugins()
{
    // Load all the plugins by creating our plugin manager

    mPluginManager = new PluginManager(mApp, false);

    // Keep track of our loaded CLI plugins

    foreach (Plugin *plugin, mPluginManager->loadedPlugins())
        if (qobject_cast<CliInterface *>(plugin->instance()))
            mLoadedCliPlugins << plugin;
}

//==============================================================================

QString CliApplication::pluginDescription(Plugin *pPlugin) const
{
    // Retrieve and return the plugin's default description, stripped out of all
    // its HTML (should it have some)
    // Note: we enclose the CLI plugin's default description within an html tag
    //       so that the stripping out can proceed without any problem...

    QXmlStreamReader description(""+pPlugin->info()->description()+"");
    QString res = QString();

    while (!description.atEnd())
        if (description.readNext() == QXmlStreamReader::Characters)
            res += description.text();

    return res;
}

//==============================================================================

void CliApplication::about() const
{
    // Output some information about OpenCOR

    version();

    std::cout << osName().toStdString() << std::endl;
    std::cout << copyright().toStdString() << std::endl;
    std::cout << std::endl;
    std::cout << mApp->applicationName().toStdString()
              << " is a cross-platform CellML-based modelling environment,"
              << " which can be used to organise, edit,"
              << " simulate and analyse CellML files."
              << std::endl;
}

//==============================================================================

bool CliApplication::command(const QStringList &pArguments, int *pRes) const
{
    // Make sure that we have at least one argument

    if (!pArguments.count())
        return false;

    // Determine whether the command is to be executed by all the CLI plugins or
    // only a given CLI plugin

    static const QString CommandSeparator = "::";

    QString commandName = pArguments.first();
    QString commandPlugin = commandName;
    int commandSeparatorPosition = commandName.indexOf(CommandSeparator);

    if (commandSeparatorPosition != -1) {
        commandPlugin = commandPlugin.remove(commandSeparatorPosition, commandName.length()-commandSeparatorPosition);
        commandName = commandName.remove(0, commandPlugin.length()+CommandSeparator.length());

        // Make sure that the plugin to which the command is to be sent exists

        if (!commandPlugin.isEmpty()) {
            bool pluginFound = false;
            bool pluginHasCliSupport = false;

            foreach (Plugin *plugin, mPluginManager->loadedPlugins())
                if (!commandPlugin.compare(plugin->name())) {
                    pluginFound = true;
                    pluginHasCliSupport = qobject_cast<CliInterface *>(plugin->instance());

                    break;
                }

            if (!pluginFound) {
                std::cout << "The " << commandPlugin.toStdString() << " plugin could not be found." << std::endl;

                return true;
            } else if (!pluginHasCliSupport) {
                std::cout << "The " << commandPlugin.toStdString() << " plugin does not support the execution of commands." << std::endl;

                return true;
            }
        }
    } else {
        commandPlugin = QString();
    }

    // Make sure that we have a command name

    if (commandName.isEmpty())
        return false;

    // Make sure that we have at least one CLI-enabled plugin

    if (mLoadedCliPlugins.isEmpty()) {
        std::cout << "No plugins could be found to run the command." << std::endl;

        return true;
    }

    // Send the command to the plugin(s)

    foreach (Plugin *plugin, mLoadedCliPlugins)
        if (    commandPlugin.isEmpty()
            || !commandPlugin.compare(plugin->name())) {
            QStringList arguments = pArguments;

            arguments.removeFirst();
            // Note: since the first argument corresponds to the command
            //       itself...

            if (qobject_cast<CliInterface *>(plugin->instance())->executeCommand(commandName, arguments))
                *pRes = -1;
        }

    return true;
}

//==============================================================================

void CliApplication::help() const
{
    // Output some help

    std::cout << "Usage: " << mApp->applicationName().toStdString()
              << " [-a|--about] [-c|--command [<plugin>::]<command> <options>] [-h|--help] [-p|--plugins] [-s|--status] [-v|--version] [<files>]"
              << std::endl;
    std::cout << " -a, --about     Display some information about OpenCOR"
              << std::endl;
    std::cout << " -c, --command   Send a command to one or all the CLI plugins"
              << std::endl;
    std::cout << " -h, --help      Display this help information"
              << std::endl;
    std::cout << " -p, --plugins   Display all the CLI plugins"
              << std::endl;
    std::cout << " -s, --status    Display the status of all the plugins"
              << std::endl;
    std::cout << " -v, --version   Display the version of OpenCOR"
              << std::endl;
}

//==============================================================================

void CliApplication::plugins() const
{
    // Output some information about our CLI plugins, so first make sure that we
    // have at least one of them

    if (mLoadedCliPlugins.isEmpty()) {
        std::cout << "No CLI plugins could be found." << std::endl;

        return;
    }

    // First, we retrieve all the CLI plugins information

    QStringList pluginsInfo = QStringList();

    foreach (Plugin *plugin, mLoadedCliPlugins) {
        // Retrieve the CLI plugin and its default description

        QString pluginInfo = plugin->name();
        QString pluginDesc = pluginDescription(plugin);

        if (!pluginDesc.isEmpty())
            pluginInfo += ": "+pluginDesc;

        // Add the plugin information to our list

        pluginsInfo << pluginInfo;
    }

    // Now, we can output the plugin information in alphabetical order

    pluginsInfo.sort(Qt::CaseInsensitive);

    if (pluginsInfo.count() == 1)
        std::cout << "The following CLI plugin is available:" << std::endl;
    else
        std::cout << "The following CLI plugins are available:" << std::endl;

    foreach (const QString &pluginInfo, pluginsInfo)
        std::cout << " - " << pluginInfo.toStdString() << std::endl;
}

//==============================================================================

void CliApplication::status() const
{
    // Output the status of all the plugins that should (have) normally be(en)
    // loaded, so first make sure that we have at least one of them

    if (mPluginManager->loadedPlugins().isEmpty()) {
        std::cout << "No plugins could be found." << std::endl;

        return;
    }

    // First, we retrieve all the plugins information

    QStringList pluginsInfo = QStringList();

    foreach (Plugin *plugin, mPluginManager->plugins()) {
        // Retrieve the plugin and its status

        QString pluginInfo = plugin->name()+": ";

        // Retrieve the plugin's status

        switch (plugin->status()) {
        case Plugin::NotWanted:
            pluginInfo += "the plugin is not wanted.";

            break;
        case Plugin::NotNeeded:
            pluginInfo += "the plugin is not needed.";

            break;
        case Plugin::NotLoaded:
            pluginInfo += QString("the plugin could not be loaded due to the following problem: %1.").arg(formatMessage(plugin->statusErrors()));

            break;
        case Plugin::NotPlugin:
            pluginInfo += "this is not a plugin.";

            break;
        case Plugin::NotCorePlugin:
            pluginInfo += "the plugin claims to be the core plugin, but it is not.";

            break;
        case Plugin::InvalidCorePlugin:
            pluginInfo += "the plugin should be the core plugin, but it does not support the core interface.";

            break;
        case Plugin::NotCliPluginNoCliSupport:
            pluginInfo += "the plugin supports the CLI interface, but it does not claim to be CLI-capable.";

            break;
        case Plugin::NotCliPluginNoCliInterface:
            pluginInfo += "the plugin claims to be CLI-capable, but it does not support the CLI interface.";

            break;
        case Plugin::MissingOrInvalidDependencies:
            if (plugin->statusErrorsCount() == 1)
                pluginInfo += QString("the plugin could not be loaded due to the %1 plugin being missing or invalid.").arg(plugin->statusErrors());
            else
                pluginInfo += QString("the plugin could not be loaded due to missing or invalid plugins:\n%1").arg(plugin->statusErrors());

            break;
        default:
            // Plugin::Loaded

            pluginInfo += "the plugin is loaded and fully functional.";
        }

        // Add the plugin information to our list

        pluginsInfo << pluginInfo;
    }

    // Now, we can output the plugin information in alphabetical order

    pluginsInfo.sort(Qt::CaseInsensitive);

    if (pluginsInfo.count() == 1)
        std::cout << "The following plugin is available:" << std::endl;
    else
        std::cout << "The following plugins are available:" << std::endl;

    foreach (const QString &pluginInfo, pluginsInfo)
        std::cout << " - " << pluginInfo.toStdString() << std::endl;
}

//==============================================================================

void CliApplication::version() const
{
    // Output the version of OpenCOR

    std::cout << OpenCOR::version(mApp).toStdString() << std::endl;
}

//==============================================================================

bool CliApplication::run(int *pRes)
{
    // See what needs doing with the CLI options, if anything

    *pRes = 0;   // By default, everything is fine

    bool aboutOption = false;
    bool commandOption = false;
    bool helpOption = false;
    bool pluginsOption = false;
    bool statusOption = false;
    bool versionOption = false;

    QStringList appArguments = mApp->arguments();
    QStringList commandArguments = QStringList();

    appArguments.removeFirst();
    // Note: we remove the first argument since it corresponds to the full path
    //       to our executable, which we are not interested in...

    foreach (const QString &appArgument, appArguments) {
        if (!appArgument.compare("-a") || !appArgument.compare("--about")) {
            aboutOption = true;
        } else if (!appArgument.compare("-c") || !appArgument.compare("--command")) {
            commandOption = true;
        } else if (!appArgument.compare("-h") || !appArgument.compare("--help")) {
            helpOption = true;
        } else if (!appArgument.compare("-p") || !appArgument.compare("--plugins")) {
            pluginsOption = true;
        } else if (!appArgument.compare("-s") || !appArgument.compare("--status")) {
            statusOption = true;
        } else if (!appArgument.compare("-v") || !appArgument.compare("--version")) {
            versionOption = true;
        } else if (appArgument.startsWith("-")) {
            // The user provided at least one unknown option

            help();

            *pRes = -1;

            break;
        } else if (commandOption) {
            // Not an option, so we consider it to be part of a command

            commandArguments << appArgument;
        }
    }

    // Handle the option the user requested, if any

    if (!*pRes) {
        if (aboutOption) {
            about();
        } else if (commandOption) {
            // Make sure that we have at least one argument (which would be the
            // command itself) before loading the plugins and then sending the
            // command to the plugin(s)

            if (commandArguments.isEmpty()) {
                help();
            } else {
                loadPlugins();

                if (!command(commandArguments, pRes))
                    help();
            }
        } else if (helpOption) {
            help();
        } else if (pluginsOption) {
            loadPlugins();

            plugins();
        } else if (statusOption) {
            loadPlugins();

            status();
        } else if (versionOption) {
            version();
        } else {
            // The user didn't provide any option that requires running OpenCOR
            // as a CLI application

            return false;
        }
    }

    return true;
}

//==============================================================================

}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProperty2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include "vtkProperty2D.h"

// Creates a vtkProperty2D with the following default values:
// Opacity 1, Color (1,0,0), CompositingOperator VTK_SRC
vtkProperty2D::vtkProperty2D()
{
  this->Opacity = 1.0;
  this->Color[0] = 1.0;
  this->Color[1] = 0.0;
  this->Color[2] = 0.0;
  this->CompositingOperator = VTK_SRC;
}

vtkProperty2D::~vtkProperty2D()
{

}

void vtkProperty2D::PrintSelf(ostream& os, vtkIndent indent)
{

  this->vtkObject::PrintSelf(os, indent);

  os << indent << "Opacity: " << this->Opacity << "\n";
  os << indent << "Color: (" << this->Color[0] << ", "
			     << this->Color[1] << ", "
			     << this->Color[2] << ")\n";

  char compString[100];

  switch (this->CompositingOperator)
    {
    case VTK_BLACK:
	strcpy(compString, "VTK_BLACK\0");
	break;
    case VTK_NOT_DEST:
        strcpy(compString, "VTK_NOT_DEST\0");
 	break;
    case VTK_SRC_AND_DEST:
	strcpy(compString, "VTK_SRC_AND_DEST\0");
	break;
    case VTK_SRC_OR_DEST:
	strcpy(compString, "VTK_SRC_OR_DEST\0");
	break;
    case VTK_NOT_SRC:
	strcpy(compString, "VTK_NOT_SRC\0");
	break;
    case VTK_SRC_XOR_DEST:
	strcpy(compString, "VTK_SRC_XOR_DEST\0");
	break;
    case VTK_SRC_AND_notDEST:
	strcpy(compString, "VTK_SRC_AND_notDEST\0");
	break;
    case VTK_SRC:
	strcpy(compString, "VTK_SRC\0");
	break;
    case VTK_WHITE:
 	strcpy(compString, "VTK_WHITE\0");
	break;
    default:
	strcpy(compString, "UNKNOWN!\0");
	break;
    }

  os << indent << "Compositing Operator: " << compString << "\n";
}

<commit_msg>ENH: made default color white<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProperty2D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/

#include "vtkProperty2D.h"

// Creates a vtkProperty2D with the following default values:
// Opacity 1, Color (1,0,0), CompositingOperator VTK_SRC
vtkProperty2D::vtkProperty2D()
{
  this->Opacity = 1.0;
  this->Color[0] = 1.0;
  this->Color[1] = 1.0;
  this->Color[2] = 1.0;
  this->CompositingOperator = VTK_SRC;
}

vtkProperty2D::~vtkProperty2D()
{

}

void vtkProperty2D::PrintSelf(ostream& os, vtkIndent indent)
{

  this->vtkObject::PrintSelf(os, indent);

  os << indent << "Opacity: " << this->Opacity << "\n";
  os << indent << "Color: (" << this->Color[0] << ", "
			     << this->Color[1] << ", "
			     << this->Color[2] << ")\n";

  char compString[100];

  switch (this->CompositingOperator)
    {
    case VTK_BLACK:
	strcpy(compString, "VTK_BLACK\0");
	break;
    case VTK_NOT_DEST:
        strcpy(compString, "VTK_NOT_DEST\0");
 	break;
    case VTK_SRC_AND_DEST:
	strcpy(compString, "VTK_SRC_AND_DEST\0");
	break;
    case VTK_SRC_OR_DEST:
	strcpy(compString, "VTK_SRC_OR_DEST\0");
	break;
    case VTK_NOT_SRC:
	strcpy(compString, "VTK_NOT_SRC\0");
	break;
    case VTK_SRC_XOR_DEST:
	strcpy(compString, "VTK_SRC_XOR_DEST\0");
	break;
    case VTK_SRC_AND_notDEST:
	strcpy(compString, "VTK_SRC_AND_notDEST\0");
	break;
    case VTK_SRC:
	strcpy(compString, "VTK_SRC\0");
	break;
    case VTK_WHITE:
 	strcpy(compString, "VTK_WHITE\0");
	break;
    default:
	strcpy(compString, "UNKNOWN!\0");
	break;
    }

  os << indent << "Compositing Operator: " << compString << "\n";
}

<|endoftext|>


<commit_before>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

extern "C" {
#include <signal.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
#include <syslog.h>
}

#include "debug.h"
#include "remotepluginprocess.h"

#include <QDebug>

using namespace RemotePluginProcessNS;

RemotePluginProcess *process = NULL;

void messageHandler(QtMsgType type, const char *msg)
{
    int priority;
    switch (type) {
        case QtWarningMsg: priority = LOG_WARNING; break;
        case QtCriticalMsg: priority = LOG_CRIT; break;
        case QtFatalMsg: priority = LOG_EMERG; break;
        case QtDebugMsg:
                         /* fall through */
        default: priority = LOG_INFO; break;
    }

    syslog(priority, msg);
}

int main(int argc, char *argv[])
{
    qInstallMsgHandler(messageHandler);
    debugInit();

    TRACE() << "handler:" << (void *)messageHandler;

#ifndef NO_SIGNON_USER
    if (!::getuid()) {
        BLAME() << argv[0] << " cannot be started with root priviledges!!!";
        exit(2);
    }
#endif

    QCoreApplication app(argc, argv);

    if (argc < 2) {
        TRACE() << "Type of plugin is not specified";
        exit(1);
    }

    QString type = app.arguments().at(1); TRACE() << type;

    fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);

    process = RemotePluginProcess::createRemotePluginProcess(type, &app);

    if (!process)
        return 1;

    fprintf(stdout, "process started");
    fflush(stdout);

    QObject::connect(process, SIGNAL(processStopped()), &app, SLOT(quit()));
    return app.exec();
}
<commit_msg>pluginprocess: fix compilation warning<commit_after>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

extern "C" {
#include <signal.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
#include <syslog.h>
}

#include "debug.h"
#include "remotepluginprocess.h"

#include <QDebug>

using namespace RemotePluginProcessNS;

RemotePluginProcess *process = NULL;

void messageHandler(QtMsgType type, const char *msg)
{
    int priority;
    switch (type) {
        case QtWarningMsg: priority = LOG_WARNING; break;
        case QtCriticalMsg: priority = LOG_CRIT; break;
        case QtFatalMsg: priority = LOG_EMERG; break;
        case QtDebugMsg:
                         /* fall through */
        default: priority = LOG_INFO; break;
    }

    syslog(priority, "%s", msg);
}

int main(int argc, char *argv[])
{
    qInstallMsgHandler(messageHandler);
    debugInit();

    TRACE() << "handler:" << (void *)messageHandler;

#ifndef NO_SIGNON_USER
    if (!::getuid()) {
        BLAME() << argv[0] << " cannot be started with root priviledges!!!";
        exit(2);
    }
#endif

    QCoreApplication app(argc, argv);

    if (argc < 2) {
        TRACE() << "Type of plugin is not specified";
        exit(1);
    }

    QString type = app.arguments().at(1); TRACE() << type;

    fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);

    process = RemotePluginProcess::createRemotePluginProcess(type, &app);

    if (!process)
        return 1;

    fprintf(stdout, "process started");
    fflush(stdout);

    QObject::connect(process, SIGNAL(processStopped()), &app, SLOT(quit()));
    return app.exec();
}
<|endoftext|>


<commit_before>#include "Chapter6.h"

USING_NS_CC;

//==========================================================================
#define CL(__className__) [](){ return __className__::create();}
static Size s_visibleSize;
static Vec2 s_origin;
static Vec2 s_centre;
static Scene* s_currScene;

namespace
{
    static std::function<Layer*()> createFunctions[] = {
        CL(UIDemoLabel),
        CL(UIDemoLabelEffect),
        CL(UIDemoLabelTypesetting),
        CL(UIDemoMenu),
        CL(UIDemoTextField),
        CL(UIDemoControlExtensions),
        CL(UIDemoEditBox),
        CL(UIDemoScrollView),
        CL(UIDemoTableView),
    };

    static int sceneIdx = -1;

#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))

    static Layer* next()
    {
        sceneIdx++;
        sceneIdx = sceneIdx % MAX_LAYER;

        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }

    static Layer* back()
    {
        sceneIdx--;
        int total = MAX_LAYER;
        if( sceneIdx < 0 )
            sceneIdx += total;

        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }

    static Layer* restart()
    {
        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }
}

Scene* Chapter6::createScene()
{
    sceneIdx = -1;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // some upfront items that we need
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    s_visibleSize = Director::getInstance()->getVisibleSize();
    s_origin = Director::getInstance()->getVisibleOrigin();
    s_centre = s_origin + s_visibleSize / 2;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene with physics world for our game to hold everything
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    s_currScene = Scene::create();

    s_currScene->addChild(next());

    // return the scene
    return s_currScene;
}

bool UIDemo::init()
{
    if (Layer::init())
    {
        //create title
        TTFConfig ttfConfig("arial.ttf", 32);
        auto titleLabel = Label::createWithTTF(ttfConfig,"UI Chapter Samples");
        addChild(titleLabel, 9999);
        titleLabel->setPosition(Vec2(s_origin.x + s_visibleSize.width/2, s_origin.y + s_visibleSize.height - 30));

        //create subtitle
        std::string strSubtitle = subtitle();
        if( ! strSubtitle.empty() )
        {
            ttfConfig.fontSize = 20;
            auto subTitleLabel = Label::createWithTTF(ttfConfig, strSubtitle.c_str());
            addChild(subTitleLabel, 9999);
            subTitleLabel->setPosition(Vec2(s_origin.x + s_visibleSize.width/2, s_origin.y + s_visibleSize.height - 70));
        }

        //create menu
        auto backItem = MenuItemImage::create("leftNormal.png", "leftSelected.png", CC_CALLBACK_1(UIDemo::backCallback, this) );
        auto restartItem = MenuItemImage::create("restartNormal.png", "restartSelected.png", CC_CALLBACK_1(UIDemo::restartCallback, this) );
        auto nextItem = MenuItemImage::create("rightNormal.png", "rightSelected.png", CC_CALLBACK_1(UIDemo::nextCallback, this) );

        auto menu = Menu::create(backItem, restartItem, nextItem, nullptr);
        menu->setPosition(Vec2::ZERO);
        addChild(menu, 9999);

        auto restartItemSize = restartItem->getContentSize();
        backItem->setPosition(s_centre.x - restartItemSize.width * 2, s_origin.y + restartItemSize.height / 2);
        restartItem->setPosition(s_centre.x, s_origin.y + restartItemSize.height / 2);
        nextItem->setPosition(s_centre.x + restartItemSize.width * 2, s_origin.y + restartItemSize.height/2);

        return true;
    }

    return false;
}

void UIDemo::restartCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( restart() );
    Director::getInstance()->replaceScene(s_currScene);
}

void UIDemo::nextCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( next() );
    Director::getInstance()->replaceScene(s_currScene);
}

void UIDemo::backCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( back() );
    Director::getInstance()->replaceScene(s_currScene);
}

//=====================================================================================
// MARK: - UIDemoLabel
std::string UIDemoLabel::subtitle() const
{
    return "Label Sample Code";
}

bool UIDemoLabel::init()
{
    if (UIDemo::init()) {
        //create a BMFont label
        auto bmFntLabel = Label::createWithBMFont("bitmapFontTest.fnt", "This is BMFont Label");
        bmFntLabel->setPosition(s_centre + Vec2(-50,100));
        this->addChild(bmFntLabel);

        //create a TTF label
        auto ttfLabel = Label::createWithTTF("This is TTF Label", "arial.ttf", 40);
        ttfLabel->setPosition(s_centre);
        this->addChild(ttfLabel);

        //create a TTF label from TTFConfig
        TTFConfig labelConfig;
        labelConfig.fontFilePath = "arial.ttf";
        labelConfig.fontSize = 20;
        labelConfig.glyphs = GlyphCollection::DYNAMIC;
        labelConfig.outlineSize = 0;
        labelConfig.customGlyphs = nullptr;
        labelConfig.distanceFieldEnabled = false;
        auto ttfLabelFromTTFConfig = Label::createWithTTF(labelConfig, "This is TTF Label created from TTFConfig");
        ttfLabelFromTTFConfig->setPosition(s_centre + Vec2(50, -30));
        this->addChild(ttfLabelFromTTFConfig);

        //create a label use SystemFont
        auto systemFontLabel = Label::createWithSystemFont("This is a Label created form System Font", "Helvetical", 36);
        systemFontLabel->setPosition(s_centre + Vec2(100,-100));
        this->addChild(systemFontLabel);

        //create a label use atlas file
        auto atlasLabel = Label::createWithCharMap("labelatlasimg.png",24,32,'0');
        atlasLabel->setString("12345");
        atlasLabel->setPosition(s_centre + Vec2(0,150));
        this->addChild(atlasLabel);

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoLabelEffect
std::string UIDemoLabelEffect::subtitle() const
{
    return "Label Effect Sample Code";
}

bool UIDemoLabelEffect::init()
{
    if (UIDemo::init()) {

        //create a white ttf label with red shadow
        auto ttfLabelWithShadow = Label::createWithTTF("Label With Shadow", "arial.ttf", 40);
        ttfLabelWithShadow->setPosition(s_centre + Vec2(0,100));
        ttfLabelWithShadow->enableShadow(Color4B::RED, Size(2,2));
        this->addChild(ttfLabelWithShadow);

        //create a white ttf label with yellow outline
        auto ttfLabelWithOutline = Label::createWithTTF("Label with outline", "arial.ttf", 60);
        ttfLabelWithOutline->setPosition(s_centre);
        ttfLabelWithOutline->enableOutline(Color4B::YELLOW, 4);
        this->addChild(ttfLabelWithOutline);

        //create a white ttf label with green glow effect
        auto ttfLabelWithGlow = Label::createWithTTF("Label with Glow", "arial.ttf", 40);
        ttfLabelWithGlow->setPosition(s_centre + Vec2(0,-100));
        ttfLabelWithGlow->enableGlow(Color4B::GREEN);
        this->addChild(ttfLabelWithGlow);

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoLabelTypesetting
std::string UIDemoLabelTypesetting::subtitle() const
{
    return "Label Typesetting Sample Code";
}

bool UIDemoLabelTypesetting::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoMenu
std::string UIDemoMenu::subtitle() const
{
    return "Menu Sample Code";
}

bool UIDemoMenu::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoTextField
std::string UIDemoTextField::subtitle() const
{
    return "TextField Sample Code";
}

bool UIDemoTextField::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoControlExtensions
std::string UIDemoControlExtensions::subtitle() const
{
    return "ControlExtensions Sample Code";
}

bool UIDemoControlExtensions::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoEditBox
std::string UIDemoEditBox::subtitle() const
{
    return "EditBox Sample Code";
}

bool UIDemoEditBox::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoScrollView
std::string UIDemoScrollView::subtitle() const
{
    return "ScrollView Sample Code";
}

bool UIDemoScrollView::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoTableView
std::string UIDemoTableView::subtitle() const
{
    return "TableView Sample Code";
}

bool UIDemoTableView::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}
<commit_msg>finish label section<commit_after>#include "Chapter6.h"

USING_NS_CC;

//==========================================================================
#define CL(__className__) [](){ return __className__::create();}
static Size s_visibleSize;
static Vec2 s_origin;
static Vec2 s_centre;
static Scene* s_currScene;

namespace
{
    static std::function<Layer*()> createFunctions[] = {
        CL(UIDemoLabel),
        CL(UIDemoLabelEffect),
        CL(UIDemoLabelTypesetting),
        CL(UIDemoMenu),
        CL(UIDemoTextField),
        CL(UIDemoControlExtensions),
        CL(UIDemoEditBox),
        CL(UIDemoScrollView),
        CL(UIDemoTableView),
    };

    static int sceneIdx = -1;

#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))

    static Layer* next()
    {
        sceneIdx++;
        sceneIdx = sceneIdx % MAX_LAYER;

        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }

    static Layer* back()
    {
        sceneIdx--;
        int total = MAX_LAYER;
        if( sceneIdx < 0 )
            sceneIdx += total;

        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }

    static Layer* restart()
    {
        auto layer = (createFunctions[sceneIdx])();
        return layer;
    }
}

Scene* Chapter6::createScene()
{
    sceneIdx = -1;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // some upfront items that we need
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    s_visibleSize = Director::getInstance()->getVisibleSize();
    s_origin = Director::getInstance()->getVisibleOrigin();
    s_centre = s_origin + s_visibleSize / 2;

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene with physics world for our game to hold everything
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    s_currScene = Scene::create();

    s_currScene->addChild(next());

    // return the scene
    return s_currScene;
}

bool UIDemo::init()
{
    if (Layer::init())
    {
        //create title
        TTFConfig ttfConfig("arial.ttf", 32);
        auto titleLabel = Label::createWithTTF(ttfConfig,"UI Chapter Samples");
        addChild(titleLabel, 9999);
        titleLabel->setPosition(Vec2(s_origin.x + s_visibleSize.width/2, s_origin.y + s_visibleSize.height - 30));

        //create subtitle
        std::string strSubtitle = subtitle();
        if( ! strSubtitle.empty() )
        {
            ttfConfig.fontSize = 20;
            auto subTitleLabel = Label::createWithTTF(ttfConfig, strSubtitle.c_str());
            addChild(subTitleLabel, 9999);
            subTitleLabel->setPosition(Vec2(s_origin.x + s_visibleSize.width/2, s_origin.y + s_visibleSize.height - 70));
        }

        //create menu
        auto backItem = MenuItemImage::create("leftNormal.png", "leftSelected.png", CC_CALLBACK_1(UIDemo::backCallback, this) );
        auto restartItem = MenuItemImage::create("restartNormal.png", "restartSelected.png", CC_CALLBACK_1(UIDemo::restartCallback, this) );
        auto nextItem = MenuItemImage::create("rightNormal.png", "rightSelected.png", CC_CALLBACK_1(UIDemo::nextCallback, this) );

        auto menu = Menu::create(backItem, restartItem, nextItem, nullptr);
        menu->setPosition(Vec2::ZERO);
        addChild(menu, 9999);

        auto restartItemSize = restartItem->getContentSize();
        backItem->setPosition(s_centre.x - restartItemSize.width * 2, s_origin.y + restartItemSize.height / 2);
        restartItem->setPosition(s_centre.x, s_origin.y + restartItemSize.height / 2);
        nextItem->setPosition(s_centre.x + restartItemSize.width * 2, s_origin.y + restartItemSize.height/2);

        return true;
    }

    return false;
}

void UIDemo::restartCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( restart() );
    Director::getInstance()->replaceScene(s_currScene);
}

void UIDemo::nextCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( next() );
    Director::getInstance()->replaceScene(s_currScene);
}

void UIDemo::backCallback(Ref* sender)
{
    s_currScene = Scene::create();
    s_currScene->addChild( back() );
    Director::getInstance()->replaceScene(s_currScene);
}

//=====================================================================================
// MARK: - UIDemoLabel
std::string UIDemoLabel::subtitle() const
{
    return "Label Sample Code";
}

bool UIDemoLabel::init()
{
    if (UIDemo::init()) {
        //create a BMFont label
        auto bmFntLabel = Label::createWithBMFont("bitmapFontTest.fnt", "This is BMFont Label");
        bmFntLabel->setPosition(s_centre + Vec2(-50,100));
        this->addChild(bmFntLabel);

        //create a TTF label
        auto ttfLabel = Label::createWithTTF("This is TTF Label", "arial.ttf", 40);
        ttfLabel->setPosition(s_centre);
        this->addChild(ttfLabel);

        //create a TTF label from TTFConfig
        TTFConfig labelConfig;
        labelConfig.fontFilePath = "arial.ttf";
        labelConfig.fontSize = 20;
        labelConfig.glyphs = GlyphCollection::DYNAMIC;
        labelConfig.outlineSize = 0;
        labelConfig.customGlyphs = nullptr;
        labelConfig.distanceFieldEnabled = false;
        auto ttfLabelFromTTFConfig = Label::createWithTTF(labelConfig, "This is TTF Label created from TTFConfig");
        ttfLabelFromTTFConfig->setPosition(s_centre + Vec2(50, -30));
        this->addChild(ttfLabelFromTTFConfig);

        //create a label use SystemFont
        auto systemFontLabel = Label::createWithSystemFont("This is a Label created form System Font", "Helvetical", 36);
        systemFontLabel->setPosition(s_centre + Vec2(100,-100));
        this->addChild(systemFontLabel);

        //create a label use atlas file
        auto atlasLabel = Label::createWithCharMap("labelatlasimg.png",24,32,'0');
        atlasLabel->setString("12345");
        atlasLabel->setPosition(s_centre + Vec2(0,150));
        this->addChild(atlasLabel);

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoLabelEffect
std::string UIDemoLabelEffect::subtitle() const
{
    return "Label Effect Sample Code";
}

bool UIDemoLabelEffect::init()
{
    if (UIDemo::init()) {

        //create a white ttf label with red shadow
        auto ttfLabelWithShadow = Label::createWithTTF("Label With Shadow", "arial.ttf", 40);
        ttfLabelWithShadow->setPosition(s_centre + Vec2(0,100));
        ttfLabelWithShadow->enableShadow(Color4B::RED, Size(2,2));
        this->addChild(ttfLabelWithShadow);

        //create a white ttf label with yellow outline
        auto ttfLabelWithOutline = Label::createWithTTF("Label with outline", "arial.ttf", 60);
        ttfLabelWithOutline->setPosition(s_centre);
        ttfLabelWithOutline->enableOutline(Color4B::YELLOW, 4);
        this->addChild(ttfLabelWithOutline);

        //create a white ttf label with green glow effect
        auto ttfLabelWithGlow = Label::createWithTTF("Label with Glow", "arial.ttf", 40);
        ttfLabelWithGlow->setPosition(s_centre + Vec2(0,-100));
        ttfLabelWithGlow->enableGlow(Color4B::GREEN);
        this->addChild(ttfLabelWithGlow);

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoLabelTypesetting
std::string UIDemoLabelTypesetting::subtitle() const
{
    return "Label Typesetting Sample Code";
}

bool UIDemoLabelTypesetting::init()
{
    if (UIDemo::init()) {
        auto s = Director::getInstance()->getWinSize();
        TTFConfig config("arial.ttf",30);

        //create a label with left text alignment
        auto ttf0 = Label::createWithTTF(config,"Alignment 0\nnew line",TextHAlignment::LEFT);
        ttf0->setPosition(s_centre + Vec2(-100, 100));
        this->addChild(ttf0);

        //create a long sentence with line wrap
        TTFConfig config1("arial.ttf",14);
        auto ttf1 = Label::createWithTTF(config1,"This is a very long sentence!This is a very long sentence!This is a very long sentence!This is a very long sentence!",
                                         TextHAlignment::LEFT,
                                         200);
//        ttf1->setLineBreakWithoutSpace(true);     //uncomment this line to see the affects
        ttf1->setPosition(s_centre);
        this->addChild(ttf1);

        //create a label with kerning
        TTFConfig config2("arial.ttf",24);
        auto ttf2 = Label::createWithTTF(config1,"Label with Kerning!");
        ttf2->setPosition(s_centre + Vec2(0,-100));
        ttf2->setTextColor(Color4B::RED);
        ttf2->setAdditionalKerning(8.0);
        this->addChild(ttf2);

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoMenu
std::string UIDemoMenu::subtitle() const
{
    return "Menu Sample Code";
}

bool UIDemoMenu::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoTextField
std::string UIDemoTextField::subtitle() const
{
    return "TextField Sample Code";
}

bool UIDemoTextField::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoControlExtensions
std::string UIDemoControlExtensions::subtitle() const
{
    return "ControlExtensions Sample Code";
}

bool UIDemoControlExtensions::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoEditBox
std::string UIDemoEditBox::subtitle() const
{
    return "EditBox Sample Code";
}

bool UIDemoEditBox::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoScrollView
std::string UIDemoScrollView::subtitle() const
{
    return "ScrollView Sample Code";
}

bool UIDemoScrollView::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}

//=====================================================================================
// MARK: - UIDemoTableView
std::string UIDemoTableView::subtitle() const
{
    return "TableView Sample Code";
}

bool UIDemoTableView::init()
{
    if (UIDemo::init()) {

        return true;
    }

    return true;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Gabriel Ebner
*/
#include "checker/simple_pp.h"
#include "kernel/instantiate.h"
#include "kernel/type_checker.h"
#include "kernel/for_each_fn.h"

namespace lean {

format compose_many(std::initializer_list<format> const & fmts) {
    format res;
    bool first = true;
    for (auto & fmt : fmts) {
        if (first) {
            res = fmt;
            first = false;
        } else {
            res = compose(res, fmt);
        }
    }
    return res;
}

static format pp_name(name n) {
    bool last = true;
    format fmt;
    while (n) {
        auto limb = n.is_numeral() ? format(n.get_numeral()) : format(n.get_string());
        fmt = last ? limb : compose_many({limb, format("."), fmt});
        last = false;
        n = n.get_prefix();
    }
    return last ? format("[anonymous]") : fmt;
}

struct simple_pp_fn {
    type_checker m_tc;
    lowlevel_notations m_notations;
    unsigned m_indent = 0;

    simple_pp_fn(environment const & env, lowlevel_notations const & notations) :
            m_tc(env), m_notations(notations) {}

    static constexpr unsigned MAX_PRIO = 1024;
    struct result {
        format m_fmt;
        unsigned m_prio;

        result(format const & fmt, unsigned prio) : m_fmt(fmt), m_prio(prio) {}
        result(format const & fmt) : m_fmt(fmt), m_prio(MAX_PRIO) {}

        result maybe_paren() const { return maybe_paren(MAX_PRIO); }
        result maybe_paren(unsigned new_prio) const {
            if (m_prio < new_prio) {
                return paren(m_fmt);
            } else {
                return *this;
            }
        }

        operator format() const { return m_fmt; }
    };

    result pp_meta(name const & n) {
        return compose(format("?"), pp_name(n));
    }

    result pp_level(level const & l) {
        switch (l.kind()) {
            case level_kind::Zero: return format("0");
            case level_kind::Succ: return result(compose(pp_level(succ_of(l)).maybe_paren(1), format("+1")), 0);
            case level_kind::Max:
                return result(compose_many({format("max"), space(),
                                            pp_level(max_lhs(l)).maybe_paren(1),
                                            pp_level(max_rhs(l)).maybe_paren(1)}), 0);
            case level_kind::IMax:
                return result(compose_many({format("imax"), space(),
                                            pp_level(imax_lhs(l)).maybe_paren(1),
                                            pp_level(imax_rhs(l)).maybe_paren(1)}), 0);
            case level_kind::Param: return pp_name(param_id(l));
            case level_kind::Global: return pp_name(global_id(l));
            case level_kind::Meta: return pp_meta(meta_id(l));
        }
        lean_unreachable();
    }

    result pp_var(expr const & e) {
        return compose(format("#"), format(var_idx(e)));
    }

    result pp_sort(expr const & e) {
        if (sort_level(e) == mk_level_zero()) {
            return format("Prop");
        } else if (sort_level(e) == mk_level_one()) {
            return format("Type");
        } else {
            return compose_many({format("Type"), space(), pp_level(sort_level(e)).maybe_paren()});
        }
    }

    result pp_const(expr const & e) {
        return pp_name(const_name(e));
    }

    result pp_meta(expr const & e) {
        return pp_meta(mlocal_name(e));
    }

    result pp_local(expr const & e) {
        return pp_name(local_pp_name(e));
    }

    bool is_implicit(expr const & f) {
        if (!closed(f)) {
            // the Lean type checker assumes expressions are closed.
            return false;
        }
        try {
            expr t = m_tc.relaxed_whnf(m_tc.infer(f));
            if (is_pi(t)) {
                binder_info bi = binding_info(t);
                return bi.is_implicit() || bi.is_strict_implicit() || bi.is_inst_implicit();
            } else {
                return false;
            }
        } catch (exception &) {
            return false;
        }
    }

    expr get_explicit_args(expr e, buffer<expr> & args) {
        while (is_app(e)) {
            if (!is_implicit(app_fn(e))) {
                args.push_back(app_arg(e));
            }
            e = app_fn(e);
        }
        std::reverse(args.begin(), args.end());
        return e;
    }

    result pp_app(expr const & e) {
        buffer<expr> args;
        auto fn = get_explicit_args(e, args);

        if (is_constant(fn)) {
            auto it = m_notations.find(const_name(fn));
            if (it != m_notations.end()) {
                format fmt;
                auto prec = it->second.m_prec;
                if (it->second.m_kind == lowlevel_notation_kind::Postfix && args.size() == 1) {
                    fmt = compose_many({pp(args[0]).maybe_paren(prec), format(it->second.m_token)});
                }
                if (it->second.m_kind == lowlevel_notation_kind::Prefix && args.size() == 1) {
                    fmt = compose_many({format(it->second.m_token), pp(args[0]).maybe_paren(prec)});
                }
                if (it->second.m_kind == lowlevel_notation_kind::Infix && args.size() == 2) {
                    fmt = compose_many({pp(args[0]).maybe_paren(prec),
                                        format(it->second.m_token),
                                        pp(args[1]).maybe_paren(prec)});
                }
                if (!fmt.is_nil_fmt())
                    return result(group(fmt), it->second.m_prec-1);
            }
        }

        format fmt = pp(fn).maybe_paren();
        for (auto & arg : args) {
            fmt = compose_many({fmt, space(), pp(arg).maybe_paren()});
        }
        return result(group(fmt), MAX_PRIO-1);
    }

    std::unordered_set<name, name_hash> used_names;
    name get_unused(name n) {
        if (!used_names.count(n)) return n;

        n = n.get_subscript_base();
        for (unsigned i = 1;; i++) {
            auto n_i = n.append_after(i);
            if (!used_names.count(n_i))
                return n_i;
        }
    }

    struct local_const {
        simple_pp_fn * m_fn;
        name m_pp_name;
        expr m_lc;

        local_const(simple_pp_fn * fn, name pp_name, expr const & domain, binder_info const & bi) : m_fn(fn) {
            m_pp_name = m_fn->get_unused(pp_name);
            m_fn->used_names.insert(m_pp_name);
            m_lc = mk_local(m_pp_name, m_pp_name, domain, bi);
            m_fn->m_tc.push_local(m_pp_name, domain, bi);
        }
        ~local_const() {
            m_fn->used_names.erase(m_pp_name);
            m_fn->m_tc.pop_local();
        }

        expr const & domain() const { return mlocal_type(m_lc); }

        local_const(simple_pp_fn * fn, expr const & binder) :
                local_const(fn, binding_name(binder), binding_domain(binder), binding_info(binder)) {}
    };

    void mark_used_const_names(expr const & e) {
        for_each(e, [&] (expr const & c, unsigned) {
            if (is_constant(c))
                used_names.insert(const_name(c));
            return true;
        });
    }

    format wrap_binder(std::initializer_list<format> const & fmts, binder_info const & bi) {
        auto fmt = compose_many(fmts);
        if (bi.is_implicit()) {
            return compose_many({format("{"), fmt, format("}")});
        } else if (bi.is_strict_implicit()) {
            return compose_many({format("{{"), fmt, format("}}")});
        } else if (bi.is_inst_implicit()) {
            return compose_many({format("["), fmt, format("]")});
        } else {
            return fmt;
        }
    }

    result pp_lambda(expr const & e) {
        local_const lc(this, e);
        return result(group(compose_many({format("λ"), space(),
                                          wrap_binder({pp(lc.m_lc), space(), format(":"), space(),
                                                       pp(binding_domain(e)).maybe_paren(1)}, binding_info(e)),
                                          format(","), space(), pp(instantiate(binding_body(e), lc.m_lc))})), 0);
    }

    result pp_pi(expr e) {
        if (!has_free_vars(binding_body(e))) {
            // implication
            return result(group(compose_many({pp(binding_domain(e)).maybe_paren(25), space(), format("->"),
                                              space(), pp(binding_body(e)).maybe_paren(24)})), 24);
        } else {
            auto bi = binding_info(e);
            auto ty = binding_domain(e);

            buffer<local_const> lcs;
            do {
                lcs.emplace_back(this, e);
                e = instantiate(binding_body(e), lcs.back().m_lc);
            } while (is_pi(e) && has_free_vars(binding_body(e)) &&
                    binding_info(e) == bi &&
                    m_tc.is_def_eq(binding_domain(e), ty));

            format bound_vars;
            for (auto & lc : lcs) {
                if (!bound_vars.is_nil_fmt()) bound_vars = compose(bound_vars, space());
                bound_vars = compose_many({bound_vars, pp_name(lc.m_pp_name)});
            }

            auto fmt = compose_many({format("Π"), space(),
                                     wrap_binder({bound_vars, space(), format(":"), space(),
                                                  pp(ty).maybe_paren(1)}, bi),
                                     format(","), space(), pp(e)});
            return result(group(fmt), 0);
        }
    }

    result pp_macro(expr const &) {
        return format("[macro]");
    }

    result pp_let(expr const & e) {
        local_const lc(this, let_name(e), let_type(e), binder_info());
        return result(group(compose_many({format("let"), space(), pp(lc.m_lc), space(), format(":"), space(),
                                    pp(let_type(e)).maybe_paren(1), space(), format(":="), space(), pp(let_value(e)), format(","),
                                    space(), pp(instantiate(let_body(e), lc.m_lc))})), 0);
    }

    result pp(expr const & e) {
        switch (e.kind()) {
            case expr_kind::Var: return pp_var(e);
            case expr_kind::Sort: return pp_sort(e);
            case expr_kind::Constant: return pp_const(e);
            case expr_kind::Meta: return pp_meta(e);
            case expr_kind::Local: return pp_local(e);
            case expr_kind::App: return pp_app(e);
            case expr_kind::Lambda: return pp_lambda(e);
            case expr_kind::Pi: return pp_pi(e);
            case expr_kind::Macro: return pp_macro(e);
            case expr_kind::Let: return pp_let(e);
        }
        lean_unreachable();
    }
};

format simple_pp(name const & n) {
    return pp_name(n);
}

format simple_pp(environment const & env, expr const & e, lowlevel_notations const & notations) {
    simple_pp_fn fn(env, notations);
    fn.mark_used_const_names(e);
    return fn.pp(e);
}

}
<commit_msg>chore(checker/simple_pp): pretty-print changed Sort/Prop/Type<commit_after>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Gabriel Ebner
*/
#include "checker/simple_pp.h"
#include "kernel/instantiate.h"
#include "kernel/type_checker.h"
#include "kernel/for_each_fn.h"

namespace lean {

format compose_many(std::initializer_list<format> const & fmts) {
    format res;
    bool first = true;
    for (auto & fmt : fmts) {
        if (first) {
            res = fmt;
            first = false;
        } else {
            res = compose(res, fmt);
        }
    }
    return res;
}

static format pp_name(name n) {
    bool last = true;
    format fmt;
    while (n) {
        auto limb = n.is_numeral() ? format(n.get_numeral()) : format(n.get_string());
        fmt = last ? limb : compose_many({limb, format("."), fmt});
        last = false;
        n = n.get_prefix();
    }
    return last ? format("[anonymous]") : fmt;
}

struct simple_pp_fn {
    type_checker m_tc;
    lowlevel_notations m_notations;
    unsigned m_indent = 0;

    simple_pp_fn(environment const & env, lowlevel_notations const & notations) :
            m_tc(env), m_notations(notations) {}

    static constexpr unsigned MAX_PRIO = 1024;
    struct result {
        format m_fmt;
        unsigned m_prio;

        result(format const & fmt, unsigned prio) : m_fmt(fmt), m_prio(prio) {}
        result(format const & fmt) : m_fmt(fmt), m_prio(MAX_PRIO) {}

        result maybe_paren() const { return maybe_paren(MAX_PRIO); }
        result maybe_paren(unsigned new_prio) const {
            if (m_prio < new_prio) {
                return paren(m_fmt);
            } else {
                return *this;
            }
        }

        operator format() const { return m_fmt; }
    };

    result pp_meta(name const & n) {
        return compose(format("?"), pp_name(n));
    }

    result pp_level(level const & l) {
        switch (l.kind()) {
            case level_kind::Zero: return format("0");
            case level_kind::Succ: return result(compose(pp_level(succ_of(l)).maybe_paren(1), format("+1")), 0);
            case level_kind::Max:
                return result(compose_many({format("max"), space(),
                                            pp_level(max_lhs(l)).maybe_paren(1),
                                            pp_level(max_rhs(l)).maybe_paren(1)}), 0);
            case level_kind::IMax:
                return result(compose_many({format("imax"), space(),
                                            pp_level(imax_lhs(l)).maybe_paren(1),
                                            pp_level(imax_rhs(l)).maybe_paren(1)}), 0);
            case level_kind::Param: return pp_name(param_id(l));
            case level_kind::Global: return pp_name(global_id(l));
            case level_kind::Meta: return pp_meta(meta_id(l));
        }
        lean_unreachable();
    }

    result pp_var(expr const & e) {
        return compose(format("#"), format(var_idx(e)));
    }

    result pp_sort(expr const & e) {
        if (sort_level(e) == mk_level_zero()) {
            return format("Prop");
        } else if (sort_level(e) == mk_level_one()) {
            return format("Type");
        } else if (is_succ(sort_level(e))) {
            return compose_many({format("Type"), space(), pp_level(succ_of(sort_level(e))).maybe_paren()});
        } else {
            return compose_many({format("Sort"), space(), pp_level(sort_level(e)).maybe_paren()});
        }
    }

    result pp_const(expr const & e) {
        return pp_name(const_name(e));
    }

    result pp_meta(expr const & e) {
        return pp_meta(mlocal_name(e));
    }

    result pp_local(expr const & e) {
        return pp_name(local_pp_name(e));
    }

    bool is_implicit(expr const & f) {
        if (!closed(f)) {
            // the Lean type checker assumes expressions are closed.
            return false;
        }
        try {
            expr t = m_tc.relaxed_whnf(m_tc.infer(f));
            if (is_pi(t)) {
                binder_info bi = binding_info(t);
                return bi.is_implicit() || bi.is_strict_implicit() || bi.is_inst_implicit();
            } else {
                return false;
            }
        } catch (exception &) {
            return false;
        }
    }

    expr get_explicit_args(expr e, buffer<expr> & args) {
        while (is_app(e)) {
            if (!is_implicit(app_fn(e))) {
                args.push_back(app_arg(e));
            }
            e = app_fn(e);
        }
        std::reverse(args.begin(), args.end());
        return e;
    }

    result pp_app(expr const & e) {
        buffer<expr> args;
        auto fn = get_explicit_args(e, args);

        if (is_constant(fn)) {
            auto it = m_notations.find(const_name(fn));
            if (it != m_notations.end()) {
                format fmt;
                auto prec = it->second.m_prec;
                if (it->second.m_kind == lowlevel_notation_kind::Postfix && args.size() == 1) {
                    fmt = compose_many({pp(args[0]).maybe_paren(prec), format(it->second.m_token)});
                }
                if (it->second.m_kind == lowlevel_notation_kind::Prefix && args.size() == 1) {
                    fmt = compose_many({format(it->second.m_token), pp(args[0]).maybe_paren(prec)});
                }
                if (it->second.m_kind == lowlevel_notation_kind::Infix && args.size() == 2) {
                    fmt = compose_many({pp(args[0]).maybe_paren(prec),
                                        format(it->second.m_token),
                                        pp(args[1]).maybe_paren(prec)});
                }
                if (!fmt.is_nil_fmt())
                    return result(group(fmt), it->second.m_prec-1);
            }
        }

        format fmt = pp(fn).maybe_paren();
        for (auto & arg : args) {
            fmt = compose_many({fmt, space(), pp(arg).maybe_paren()});
        }
        return result(group(fmt), MAX_PRIO-1);
    }

    std::unordered_set<name, name_hash> used_names;
    name get_unused(name n) {
        if (!used_names.count(n)) return n;

        n = n.get_subscript_base();
        for (unsigned i = 1;; i++) {
            auto n_i = n.append_after(i);
            if (!used_names.count(n_i))
                return n_i;
        }
    }

    struct local_const {
        simple_pp_fn * m_fn;
        name m_pp_name;
        expr m_lc;

        local_const(simple_pp_fn * fn, name pp_name, expr const & domain, binder_info const & bi) : m_fn(fn) {
            m_pp_name = m_fn->get_unused(pp_name);
            m_fn->used_names.insert(m_pp_name);
            m_lc = mk_local(m_pp_name, m_pp_name, domain, bi);
            m_fn->m_tc.push_local(m_pp_name, domain, bi);
        }
        ~local_const() {
            m_fn->used_names.erase(m_pp_name);
            m_fn->m_tc.pop_local();
        }

        expr const & domain() const { return mlocal_type(m_lc); }

        local_const(simple_pp_fn * fn, expr const & binder) :
                local_const(fn, binding_name(binder), binding_domain(binder), binding_info(binder)) {}
    };

    void mark_used_const_names(expr const & e) {
        for_each(e, [&] (expr const & c, unsigned) {
            if (is_constant(c))
                used_names.insert(const_name(c));
            return true;
        });
    }

    format wrap_binder(std::initializer_list<format> const & fmts, binder_info const & bi) {
        auto fmt = compose_many(fmts);
        if (bi.is_implicit()) {
            return compose_many({format("{"), fmt, format("}")});
        } else if (bi.is_strict_implicit()) {
            return compose_many({format("{{"), fmt, format("}}")});
        } else if (bi.is_inst_implicit()) {
            return compose_many({format("["), fmt, format("]")});
        } else {
            return fmt;
        }
    }

    result pp_lambda(expr const & e) {
        local_const lc(this, e);
        return result(group(compose_many({format("λ"), space(),
                                          wrap_binder({pp(lc.m_lc), space(), format(":"), space(),
                                                       pp(binding_domain(e)).maybe_paren(1)}, binding_info(e)),
                                          format(","), space(), pp(instantiate(binding_body(e), lc.m_lc))})), 0);
    }

    result pp_pi(expr e) {
        if (!has_free_vars(binding_body(e))) {
            // implication
            return result(group(compose_many({pp(binding_domain(e)).maybe_paren(25), space(), format("->"),
                                              space(), pp(binding_body(e)).maybe_paren(24)})), 24);
        } else {
            auto bi = binding_info(e);
            auto ty = binding_domain(e);

            buffer<local_const> lcs;
            do {
                lcs.emplace_back(this, e);
                e = instantiate(binding_body(e), lcs.back().m_lc);
            } while (is_pi(e) && has_free_vars(binding_body(e)) &&
                    binding_info(e) == bi &&
                    m_tc.is_def_eq(binding_domain(e), ty));

            format bound_vars;
            for (auto & lc : lcs) {
                if (!bound_vars.is_nil_fmt()) bound_vars = compose(bound_vars, space());
                bound_vars = compose_many({bound_vars, pp_name(lc.m_pp_name)});
            }

            auto fmt = compose_many({format("Π"), space(),
                                     wrap_binder({bound_vars, space(), format(":"), space(),
                                                  pp(ty).maybe_paren(1)}, bi),
                                     format(","), space(), pp(e)});
            return result(group(fmt), 0);
        }
    }

    result pp_macro(expr const &) {
        return format("[macro]");
    }

    result pp_let(expr const & e) {
        local_const lc(this, let_name(e), let_type(e), binder_info());
        return result(group(compose_many({format("let"), space(), pp(lc.m_lc), space(), format(":"), space(),
                                    pp(let_type(e)).maybe_paren(1), space(), format(":="), space(), pp(let_value(e)), format(","),
                                    space(), pp(instantiate(let_body(e), lc.m_lc))})), 0);
    }

    result pp(expr const & e) {
        switch (e.kind()) {
            case expr_kind::Var: return pp_var(e);
            case expr_kind::Sort: return pp_sort(e);
            case expr_kind::Constant: return pp_const(e);
            case expr_kind::Meta: return pp_meta(e);
            case expr_kind::Local: return pp_local(e);
            case expr_kind::App: return pp_app(e);
            case expr_kind::Lambda: return pp_lambda(e);
            case expr_kind::Pi: return pp_pi(e);
            case expr_kind::Macro: return pp_macro(e);
            case expr_kind::Let: return pp_let(e);
        }
        lean_unreachable();
    }
};

format simple_pp(name const & n) {
    return pp_name(n);
}

format simple_pp(environment const & env, expr const & e, lowlevel_notations const & notations) {
    simple_pp_fn fn(env, notations);
    fn.mark_used_const_names(e);
    return fn.pp(e);
}

}
<|endoftext|>


<commit_before>#include <unistd.h>
#include <cassert>
#include <boost/utility/binary.hpp>
#include <boost/shared_ptr.hpp>

#include "gen-cpp/Barista.h"
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>

/**
 * Sample Barista C++ Client
 *
 * @author anantb
 * @date 11/07/2013
 *
 */

using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace barista;

int main () {
  try {
    boost::shared_ptr<TSocket> transport(new TSocket("128.52.161.243", 9000));
    shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
    BaristaClient client(protocol);

    transport->open();
    double version = client.get_version();
    cout << version << endl;

    ConnectionParams con_params = ConnectionParams();
    con_params.__set_user("postgres");
    con_params.__set_password("postgres");
    con_params.__set_database("postgres");

    Connection con;
    client.open_connection(con, con_params);
    ResultSet res;
    client.execute_sql(res, con, "SELECT 6.824 as id, 'Distributed Systems' as name", vector<string>());
    for(vector<Tuple>::iterator tuple_it = res.tuples.begin(); tuple_it != res.tuples.end(); ++tuple_it) {
      for(vector<string>::iterator cell_it = (*tuple_it).cells.begin(); cell_it != (*tuple_it).cells.end(); ++cell_it) {
        cout << *cell_it << "\t";
      }
      cout << "\n";
    }
    client.close_connection(con);
    transport->close();
  } catch (TException &tx) {
    cout << "ERROR: " << tx.what();
  }

  return 0;
}
<commit_msg>cpp client<commit_after>#include <unistd.h>
#include <cassert>
#include <boost/utility/binary.hpp>
#include <boost/shared_ptr.hpp>

#include "gen-cpp/Barista.h"
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>

/**
 * Sample Barista C++ Client
 *
 * @author anantb
 * @date 11/07/2013
 *
 */

using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace barista;

int main () {
  try {
    boost::shared_ptr<TSocket> transport(new TSocket("128.52.161.243", 9000));
    shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
    BaristaClient client(protocol);

    transport->open();
    double version = client.get_version();
    cout << version << endl;

    ConnectionParams con_params = ConnectionParams();
    con_params.__set_user("postgres");
    con_params.__set_password("postgres");
    con_params.__set_database("postgres");

    Connection con;
    client.open_connection(con, con_params);
    ResultSet res;
    client.execute_sql(res, con, "SELECT 6.824 as id, 'Distributed Systems' as name", NULL);
    for(vector<Tuple>::iterator tuple_it = res.tuples.begin(); tuple_it != res.tuples.end(); ++tuple_it) {
      for(vector<string>::iterator cell_it = (*tuple_it).cells.begin(); cell_it != (*tuple_it).cells.end(); ++cell_it) {
        cout << *cell_it << "\t";
      }
      cout << "\n";
    }
    client.close_connection(con);
    transport->close();
  } catch (TException &tx) {
    cout << "ERROR: " << tx.what();
  }

  return 0;
}
<|endoftext|>