<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dp_ucb.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-01-26 17:49:23 $
 *
 *  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 "dp_misc.hrc"
#include "dp_misc.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "rtl/ustrbuf.hxx"
#include "ucbhelper/content.hxx"
#include "xmlscript/xml_helper.hxx"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/ucb/CommandFailedException.hpp"
#include "com/sun/star/ucb/XContentCreator.hpp"
#include "com/sun/star/ucb/ContentInfo.hpp"
#include "com/sun/star/ucb/ContentInfoAttribute.hpp"

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

namespace dp_misc
{

const OUString StrTitle::operator () ()
{
    return OUSTR("Title");
}

//==============================================================================
bool create_ucb_content(
    ::ucb::Content * ret_ucbContent, OUString const & url,
    Reference<XCommandEnvironment> const & xCmdEnv,
    bool throw_exc )
{
    try {
        // dilemma: no chance to use the given iahandler here, because it would
        //          raise no such file dialogs, else no interaction for
        //          passwords, ...? xxx todo
        ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() );
        if (! ucbContent.isFolder())
            ucbContent.openStream()->closeInput();
        if (ret_ucbContent != 0)
            *ret_ucbContent = ::ucb::Content( url, xCmdEnv );
        return true;
    }
    catch (RuntimeException &) {
        throw;
    }
    catch (Exception &) {
        if (throw_exc)
            throw;
    }
    return false;
}

//==============================================================================
bool create_folder(
    ::ucb::Content * ret_ucb_content, OUString const & url_,
    Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content(
            &ucb_content, url_, xCmdEnv, false /* no throw */ ))
    {
        if (ucb_content.isFolder()) {
            if (ret_ucb_content != 0)
                *ret_ucb_content = ucb_content;
            return true;
        }
    }

    OUString url( url_ );
    // xxx todo: find parent
    sal_Int32 slash = url.lastIndexOf( '/' );
    if (slash < 0) {
        // fallback:
        url = expandUnoRcUrl( url );
        slash = url.lastIndexOf( '/' );
    }
    if (slash < 0) {
        // invalid: has to be at least "auth:/..."
        if (throw_exc)
            throw ContentCreationException(
                OUSTR("Cannot create folder (invalid path): ") + url,
                Reference<XInterface>(), ContentCreationError_UNKNOWN );
        return false;
    }
    ::ucb::Content parentContent;
    if (! create_folder(
            &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc ))
        return false;
    Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY );
    if (xCreator.is())
    {
        const Any title( ::rtl::Uri::decode( url.copy( slash + 1 ),
                                             rtl_UriDecodeWithCharset,
                                             RTL_TEXTENCODING_UTF8 ) );
        const Sequence<ContentInfo> infos(
            xCreator->queryCreatableContentsInfo() );
        for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos )
        {
            // look KIND_FOLDER:
            ContentInfo const & info = infos[ pos ];
            if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0)
            {
                // make sure the only required bootstrap property is "Title":
                Sequence<beans::Property> const & rProps = info.Properties;
                if (rProps.getLength() != 1 ||
                    !rProps[ 0 ].Name.equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("Title") ))
                    continue;

                try {
                    if (parentContent.insertNewContent(
                            info.Type,
                            Sequence<OUString>( &StrTitle::get(), 1 ),
                            Sequence<Any>( &title, 1 ),
                            ucb_content )) {
                        if (ret_ucb_content != 0)
                            *ret_ucb_content = ucb_content;
                        return true;
                    }
                }
                catch (RuntimeException &) {
                    throw;
                }
                catch (CommandFailedException &) {
                    // Interaction Handler already handled the error
                    // that has occured...
                }
                catch (Exception &) {
                    if (throw_exc)
                        throw;
                    return false;
                }
            }
        }
    }
    if (throw_exc)
        throw ContentCreationException(
            OUSTR("Cannot create folder: ") + url,
            Reference<XInterface>(), ContentCreationError_UNKNOWN );
    return false;
}

//==============================================================================
bool erase_path( OUString const & url,
                 Reference<XCommandEnvironment> const & xCmdEnv,
                 bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ ))
    {
        try {
            ucb_content.executeCommand(
                OUSTR("delete"), Any( true /* delete physically */ ) );
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception &) {
            if (throw_exc)
                throw;
            return false;
        }
    }
    return true;
}

//==============================================================================
::rtl::ByteSequence readFile( ::ucb::Content & ucb_content )
{
    ::rtl::ByteSequence bytes;
    Reference<io::XOutputStream> xStream(
        ::xmlscript::createOutputStream( &bytes ) );
    if (! ucb_content.openStream( xStream ))
        throw RuntimeException(
            OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 );
    return bytes;
}

//==============================================================================
bool readLine( OUString * res, OUString const & startingWith,
               ::ucb::Content & ucb_content, rtl_TextEncoding textenc )
{
    // read whole file:
    ::rtl::ByteSequence bytes( readFile( ucb_content ) );
    OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()),
                   bytes.getLength(), textenc );
    sal_Int32 pos = 0;
    for (;;)
    {
        if (file.match( startingWith, pos ))
        {
            ::rtl::OUStringBuffer buf;
            sal_Int32 start = pos;
            pos += startingWith.getLength();
            for (;;)
            {
                pos = file.indexOf( LF, pos );
                if (pos < 0) { // EOF
                    buf.append( file.copy( start ) );
                }
                else
                {
                    if (pos > 0 && file[ pos - 1 ] == CR)
                    {
                        // consume extra CR
                        buf.append( file.copy( start, pos - start - 1 ) );
                        ++pos;
                    }
                    else
                        buf.append( file.copy( start, pos - start ) );
                    ++pos; // consume LF
                    // check next line:
                    if (pos < file.getLength() &&
                        (file[ pos ] == ' ' || file[ pos ] == '\t'))
                    {
                        buf.append( static_cast<sal_Unicode>(' ') );
                        ++pos;
                        start = pos;
                        continue;
                    }
                }
                break;
            }
            *res = buf.makeStringAndClear();
            return true;
        }
        // next line:
        sal_Int32 next_lf = file.indexOf( LF, pos );
        if (next_lf < 0) // EOF
            break;
        pos = next_lf + 1;
    }
    return false;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.136); FILE MERGED 2006/09/01 17:25:12 kaib 1.9.136.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dp_ucb.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:42:29 $
 *
 *  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_desktop.hxx"

#include "dp_misc.hrc"
#include "dp_misc.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "rtl/ustrbuf.hxx"
#include "ucbhelper/content.hxx"
#include "xmlscript/xml_helper.hxx"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/ucb/CommandFailedException.hpp"
#include "com/sun/star/ucb/XContentCreator.hpp"
#include "com/sun/star/ucb/ContentInfo.hpp"
#include "com/sun/star/ucb/ContentInfoAttribute.hpp"

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

namespace dp_misc
{

const OUString StrTitle::operator () ()
{
    return OUSTR("Title");
}

//==============================================================================
bool create_ucb_content(
    ::ucb::Content * ret_ucbContent, OUString const & url,
    Reference<XCommandEnvironment> const & xCmdEnv,
    bool throw_exc )
{
    try {
        // dilemma: no chance to use the given iahandler here, because it would
        //          raise no such file dialogs, else no interaction for
        //          passwords, ...? xxx todo
        ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() );
        if (! ucbContent.isFolder())
            ucbContent.openStream()->closeInput();
        if (ret_ucbContent != 0)
            *ret_ucbContent = ::ucb::Content( url, xCmdEnv );
        return true;
    }
    catch (RuntimeException &) {
        throw;
    }
    catch (Exception &) {
        if (throw_exc)
            throw;
    }
    return false;
}

//==============================================================================
bool create_folder(
    ::ucb::Content * ret_ucb_content, OUString const & url_,
    Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content(
            &ucb_content, url_, xCmdEnv, false /* no throw */ ))
    {
        if (ucb_content.isFolder()) {
            if (ret_ucb_content != 0)
                *ret_ucb_content = ucb_content;
            return true;
        }
    }

    OUString url( url_ );
    // xxx todo: find parent
    sal_Int32 slash = url.lastIndexOf( '/' );
    if (slash < 0) {
        // fallback:
        url = expandUnoRcUrl( url );
        slash = url.lastIndexOf( '/' );
    }
    if (slash < 0) {
        // invalid: has to be at least "auth:/..."
        if (throw_exc)
            throw ContentCreationException(
                OUSTR("Cannot create folder (invalid path): ") + url,
                Reference<XInterface>(), ContentCreationError_UNKNOWN );
        return false;
    }
    ::ucb::Content parentContent;
    if (! create_folder(
            &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc ))
        return false;
    Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY );
    if (xCreator.is())
    {
        const Any title( ::rtl::Uri::decode( url.copy( slash + 1 ),
                                             rtl_UriDecodeWithCharset,
                                             RTL_TEXTENCODING_UTF8 ) );
        const Sequence<ContentInfo> infos(
            xCreator->queryCreatableContentsInfo() );
        for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos )
        {
            // look KIND_FOLDER:
            ContentInfo const & info = infos[ pos ];
            if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0)
            {
                // make sure the only required bootstrap property is "Title":
                Sequence<beans::Property> const & rProps = info.Properties;
                if (rProps.getLength() != 1 ||
                    !rProps[ 0 ].Name.equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("Title") ))
                    continue;

                try {
                    if (parentContent.insertNewContent(
                            info.Type,
                            Sequence<OUString>( &StrTitle::get(), 1 ),
                            Sequence<Any>( &title, 1 ),
                            ucb_content )) {
                        if (ret_ucb_content != 0)
                            *ret_ucb_content = ucb_content;
                        return true;
                    }
                }
                catch (RuntimeException &) {
                    throw;
                }
                catch (CommandFailedException &) {
                    // Interaction Handler already handled the error
                    // that has occured...
                }
                catch (Exception &) {
                    if (throw_exc)
                        throw;
                    return false;
                }
            }
        }
    }
    if (throw_exc)
        throw ContentCreationException(
            OUSTR("Cannot create folder: ") + url,
            Reference<XInterface>(), ContentCreationError_UNKNOWN );
    return false;
}

//==============================================================================
bool erase_path( OUString const & url,
                 Reference<XCommandEnvironment> const & xCmdEnv,
                 bool throw_exc )
{
    ::ucb::Content ucb_content;
    if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ ))
    {
        try {
            ucb_content.executeCommand(
                OUSTR("delete"), Any( true /* delete physically */ ) );
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception &) {
            if (throw_exc)
                throw;
            return false;
        }
    }
    return true;
}

//==============================================================================
::rtl::ByteSequence readFile( ::ucb::Content & ucb_content )
{
    ::rtl::ByteSequence bytes;
    Reference<io::XOutputStream> xStream(
        ::xmlscript::createOutputStream( &bytes ) );
    if (! ucb_content.openStream( xStream ))
        throw RuntimeException(
            OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 );
    return bytes;
}

//==============================================================================
bool readLine( OUString * res, OUString const & startingWith,
               ::ucb::Content & ucb_content, rtl_TextEncoding textenc )
{
    // read whole file:
    ::rtl::ByteSequence bytes( readFile( ucb_content ) );
    OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()),
                   bytes.getLength(), textenc );
    sal_Int32 pos = 0;
    for (;;)
    {
        if (file.match( startingWith, pos ))
        {
            ::rtl::OUStringBuffer buf;
            sal_Int32 start = pos;
            pos += startingWith.getLength();
            for (;;)
            {
                pos = file.indexOf( LF, pos );
                if (pos < 0) { // EOF
                    buf.append( file.copy( start ) );
                }
                else
                {
                    if (pos > 0 && file[ pos - 1 ] == CR)
                    {
                        // consume extra CR
                        buf.append( file.copy( start, pos - start - 1 ) );
                        ++pos;
                    }
                    else
                        buf.append( file.copy( start, pos - start ) );
                    ++pos; // consume LF
                    // check next line:
                    if (pos < file.getLength() &&
                        (file[ pos ] == ' ' || file[ pos ] == '\t'))
                    {
                        buf.append( static_cast<sal_Unicode>(' ') );
                        ++pos;
                        start = pos;
                        continue;
                    }
                }
                break;
            }
            *res = buf.makeStringAndClear();
            return true;
        }
        // next line:
        sal_Int32 next_lf = file.indexOf( LF, pos );
        if (next_lf < 0) // EOF
            break;
        pos = next_lf + 1;
    }
    return false;
}

}
<|endoftext|>


<commit_before>#define ARDUINO 10001

#include <LiquidCrystal_I2C.h>
#include <string.h>
#include <Wire.h>

#define LED_PIN 13

void setup()
{
    pinMode(LED_PIN, OUTPUT);
}

void loop()
{
    digitalWrite(LED_PIN, HIGH);
    delay(1000);
    digitalWrite(LED_PIN, LOW);
    delay(1000);
}
<commit_msg>Removing my useless attempt at trying to not edit the new LCD library<commit_after>#include <LiquidCrystal_I2C.h>
#include <string.h>
#include <Wire.h>

#define LED_PIN 13

void setup()
{
    pinMode(LED_PIN, OUTPUT);
}

void loop()
{
    digitalWrite(LED_PIN, HIGH);
    delay(1000);
    digitalWrite(LED_PIN, LOW);
    delay(1000);
}
<|endoftext|>


<commit_before>#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>

#include <boost/serialization/vector.hpp>

#include <iostream>
#include <vector>
#include <fstream>

#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_oarchive.hpp>

namespace mpi = boost::mpi;

class SerExample{
    friend class boost::serialization::access;

    template<class Archive>  void serialize(Archive & ar, const unsigned int /*version*/)
    {
        ar & val;
    }

public:
    std::string val;
    SerExample() {}
    SerExample(std::string val): val(val) {}
};

std::ostream &operator<<(std::ostream &os, SerExample const &m) {
    return os << "[" << m.val << "]";
}

int main(int argc, char **argv){
    mpi::environment env(argc, argv);
    mpi::communicator world;
    std::cout << "I am process " << world.rank() << " of " << world.size()
              << "." << std::endl;

    if (world.rank() == 0){
        for (int i =1; i < world.size(); i++){
            world.send(i, 1, std::string("ehlo ") + std::to_string(i));
        }

        for (int i = 1; i< world.size(); i++){
            std::vector<SerExample> tmp;
            world.recv(i, 1, tmp);

            std::cout << "received vector: " << std::endl;
            for (auto const & value: tmp){
                std::cout << value << value;
            }
        }

    } else {
        std::string tmp;
        world.recv(0, 1, tmp);

        std::cout << "Received " << tmp << "\n";
        std::vector<SerExample> response;
        response.push_back(SerExample("test"));
        response.push_back(SerExample(tmp));
        world.send(0, 1, response);
    }
    return 0;
}
<commit_msg>fix typo<commit_after>#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>

#include <boost/serialization/vector.hpp>

#include <iostream>
#include <vector>
#include <fstream>

#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_oarchive.hpp>

namespace mpi = boost::mpi;

class SerExample{
    friend class boost::serialization::access;

    template<class Archive>  void serialize(Archive & ar, const unsigned int /*version*/)
    {
        ar & val;
    }

public:
    std::string val;
    SerExample() {}
    SerExample(std::string val): val(val) {}
};

std::ostream &operator<<(std::ostream &os, SerExample const &m) {
    return os << "[" << m.val << "]";
}

int main(int argc, char **argv){
    mpi::environment env(argc, argv);
    mpi::communicator world;
    std::cout << "I am process " << world.rank() << " of " << world.size()
              << "." << std::endl;

    if (world.rank() == 0){
        for (int i =1; i < world.size(); i++){
            world.send(i, 1, std::string("ehlo ") + std::to_string(i));
        }

        for (int i = 1; i< world.size(); i++){
            std::vector<SerExample> tmp;
            world.recv(i, 1, tmp);

            std::cout << "received vector: " << std::endl;
            for (auto const & value: tmp){
                std::cout << value << std::endl;
            }
        }

    } else {
        std::string tmp;
        world.recv(0, 1, tmp);

        std::cout << "Received " << tmp << "\n";
        std::vector<SerExample> response;
        response.push_back(SerExample("test"));
        response.push_back(SerExample(tmp));
        world.send(0, 1, response);
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                webView->show();
                break;
            // TODO Other cases
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
            case 4:
                webView->setWindowState(Qt::WindowNoState);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }

    /*
     *  Set window position
     *  $API.setWindowPosition (left, top)
     * */
    Q_INVOKABLE void setWindowPosition (int left, int top) {
        webView->move(left, top);
    }

    /*
     *  Get window position
     *  $API.getWindowPosition (left, top)
     * */
    Q_INVOKABLE QObject *getWindowPosition () {
        QObject *position = new QObject();
        QPoint point = webView->pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Get mouse position
     *  $API.getMousePosition()
     *
     * */
    Q_INVOKABLE QObject *getMousePosition () {
        QObject *position = new QObject();
        QPoint point = QCursor::pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Debug
     *  $API.debug(message)
     *
     * */
    Q_INVOKABLE void debug (QString message) {
        qDebug() << message;
    }

};

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {

        // set background transparent for webview
        QPalette pal = view->palette();
        pal.setBrush(QPalette::Base, Qt::transparent);
        view->page()->setPalette(pal);
        view->setAttribute(Qt::WA_TranslucentBackground);

        view->setWindowFlags(Qt::FramelessWindowHint);
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

#include "main.moc"
<commit_msg>Added BOTTOM_MOST feature.<commit_after>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED" << "BOTTOM_MOST";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                break;
            case 1:
                webView->setWindowFlags(Qt::WindowStaysOnBottomHint);
                break;
            // TODO Other cases
            webView->show();
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
            case 4:
                webView->setWindowState(Qt::WindowNoState);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }

    /*
     *  Set window position
     *  $API.setWindowPosition (left, top)
     * */
    Q_INVOKABLE void setWindowPosition (int left, int top) {
        webView->move(left, top);
    }

    /*
     *  Get window position
     *  $API.getWindowPosition (left, top)
     * */
    Q_INVOKABLE QObject *getWindowPosition () {
        QObject *position = new QObject();
        QPoint point = webView->pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Get mouse position
     *  $API.getMousePosition()
     *
     * */
    Q_INVOKABLE QObject *getMousePosition () {
        QObject *position = new QObject();
        QPoint point = QCursor::pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Debug
     *  $API.debug(message)
     *
     * */
    Q_INVOKABLE void debug (QString message) {
        qDebug() << message;
    }

};

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {
        // set background transparent for webview
        QPalette pal = view->palette();
        pal.setBrush(QPalette::Base, Qt::transparent);
        view->page()->setPalette(pal);
        view->setAttribute(Qt::WA_TranslucentBackground);

        view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags());
    }

    if (QString(argv[5]) == "BOTTOM_MOST") {
        view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags());
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

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


<commit_before>#include "dispatch_queue.h"

#include <chrono>
#include <thread>
#include <cstdio>

namespace
{
    void hello() { std::printf("hello world\n"); }
    void add(int a, int b) { std::printf("%d + %d = %d\n", a, b, a + b); }
}

int main(void)
{
    dispatch_queue_t dq;
    dq.dispatch_async(hello);
    dq.dispatch_async(std::bind(add, 123, 456));

    {
        auto bound_counter = 0;
        for (auto i = 0; i < 1024; ++i) {
            dq.dispatch_async([&]() { ++bound_counter; });
        }

        dq.dispatch_flush();
        std::printf("bound_counter = %d\n", bound_counter);
    }

    std::printf("dispatch_sync sleep for 1s... ");
    std::fflush(stdout);
    dq.dispatch_sync([] { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); });
    std::printf("and we're back.\n");

    {
        auto i = 0;
        dq.dispatch_async([&] {
            std::printf("level %d\n", i++);
            dq.dispatch_async([&] {
                std::printf("level %d\n", i++);
                dq.dispatch_async([&] { std::printf("level %d\n", i++); });
            });
        });
    }

    {
        auto param_counter = 0;
        for (auto i = 0; i < 2048; ++i) {
            dq.dispatch_async(std::bind([](int& c) { ++c; }, std::ref(param_counter)));
        }

        dq.dispatch_flush();
        std::printf("param_counter = %d\n", param_counter);
    }

    return 0;
}

<commit_msg>remove unneeded ()<commit_after>#include "dispatch_queue.h"

#include <chrono>
#include <thread>
#include <cstdio>

namespace
{
    void hello() { std::printf("hello world\n"); }
    void add(int a, int b) { std::printf("%d + %d = %d\n", a, b, a + b); }
}

int main(void)
{
    dispatch_queue_t dq;
    dq.dispatch_async(hello);
    dq.dispatch_async(std::bind(add, 123, 456));

    {
        auto bound_counter = 0;
        for (auto i = 0; i < 1024; ++i) {
            dq.dispatch_async([&] { ++bound_counter; });
        }

        dq.dispatch_flush();
        std::printf("bound_counter = %d\n", bound_counter);
    }

    std::printf("dispatch_sync sleep for 1s... ");
    std::fflush(stdout);
    dq.dispatch_sync([] { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); });
    std::printf("and we're back.\n");

    {
        auto i = 0;
        dq.dispatch_async([&] {
            std::printf("level %d\n", i++);
            dq.dispatch_async([&] {
                std::printf("level %d\n", i++);
                dq.dispatch_async([&] { std::printf("level %d\n", i++); });
            });
        });
    }

    {
        auto param_counter = 0;
        for (auto i = 0; i < 2048; ++i) {
            dq.dispatch_async(std::bind([](int& c) { ++c; }, std::ref(param_counter)));
        }

        dq.dispatch_flush();
        std::printf("param_counter = %d\n", param_counter);
    }

    return 0;
}

<|endoftext|>


<commit_before>#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <iostream>

//#include <vulkan/vulkan.h> // Vulkan will be autometically loaded by GLFW.

#include <stdexcept>
#include <functional>
#include <cstring>

//template <typename T>
//class VDeleter {
//public:
//    VDeleter() : VDeleter([](T, VkAllocationCallbacks*) {}) {}

//    VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [=](T obj) { deletef(obj, nullptr); };
//    }

//    VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [&instance, deletef](T obj) { deletef(instance, obj, nullptr); };
//    }

//    VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [&device, deletef](T obj) { deletef(device, obj, nullptr); };
//    }

//    ~VDeleter() {
//        cleanup();
//    }

//    const T* operator &() const {
//        return &object;
//    }

//    T* replace() {
//        cleanup();
//        return &object;
//    }

//    operator T() const {
//        return object;
//    }

//    void operator=(T rhs) {
//        if (rhs != object) {
//            cleanup();
//            object = rhs;
//        }
//    }

//    template<typename V>
//    bool operator==(V rhs) {
//        return object == T(rhs);
//    }

//private:
//    T object{VK_NULL_HANDLE};
//    std::function<void(T)> deleter;

//    void cleanup() {
//        if (object != VK_NULL_HANDLE) {
//            deleter(object);
//        }
//        object = VK_NULL_HANDLE;
//    }
//};

const int WIDTH = 800;
const int HEIGHT = 600;

const std::vector<const char*> validationLayers = {
    "VK_LAYER_LUNARG_standard_validation"
};

#ifdef NDEBUG
    const bool enableValidationLayers = false;
#else
    const bool enableValidationLayers = true;
#endif

class HelloTriangleApplication {
public:
    void run() {
            initWindow();
            initVulkan();
            mainLoop();
    }

private:
    GLFWwindow* window;

//    VDeleter<VkInstance> instance {vkDestoryInstance};
    VkInstance instance;

    void initWindow() {
        // init GLFW library.
        glfwInit();

        // Tell GLFW not to create OpenGL context by default.
        glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
        // Disable resizing window operation here.
        glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

        // glfwCreateWindow(width, height, title, monitorIndex(optional))
        window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);

    }

    void initVulkan() {
        // init Vulkan library by creating an instance.
        createInstance();
    }

    void mainLoop() {
        // Keep the app running until either an error occurs
        //    or the window is closed.
        while (!glfwWindowShouldClose(window)) {
            glfwPollEvents();
        }

        glfwDestroyWindow(window);

        glfwTerminate();
    }

    void createInstance() {
        // Optional info
        VkApplicationInfo appInfo = {};
        appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; // not optional
        appInfo.pApplicationName = "Hello Triangle";
        appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.pEngineName = "No Engine";
        appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.apiVersion = VK_API_VERSION_1_0;

        // Non-optional info. (Define Global extensions and validation layers)
        VkInstanceCreateInfo createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        createInfo.pApplicationInfo = &appInfo;

        // Specify our desired global extensions.
        unsigned int glfwExtensionCount = 0;
        const char** glfwExtensions;

        glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);

        createInfo.enabledExtensionCount = glfwExtensionCount;
        createInfo.ppEnabledExtensionNames = glfwExtensions;

        // Determine the global validation layers to enable.
        createInfo.enabledLayerCount = 0;
        VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);

        if (result != VK_SUCCESS) {
            throw std::runtime_error("Failed to create Vulkan instance!");
        }
    }

    /**
     * @brief checkValidationLayerSupport
     * Check if all of the requested layers are available.
     * @return
     */
    bool checkValidationLayerSupport() {
        uint32_t layerCount;
        vkEnumerateInstanceLayerProperties(&layerCount, nullptr);

        std::vector<VkLayerProperties> avaliableLayers(layerCount);
        vkEnumerateInstanceLayerProperties(&layerCount, avaliableLayers.data());

        return false;
    }
};

int main()
{
    HelloTriangleApplication app;

    try {
        app.run();
    } catch (const std::runtime_error& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

<commit_msg>complete-image-view<commit_after>#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <iostream>

//#include <vulkan/vulkan.h> // Vulkan will be autometically loaded by GLFW.

#include <stdexcept>
#include <functional>
#include <cstring>
#include <vector>
#include <map>
#include <set>

//template <typename T>
//class VDeleter {
//public:
//    VDeleter() : VDeleter([](T, VkAllocationCallbacks*) {}) {}

//    VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [=](T obj) { deletef(obj, nullptr); };
//    }

//    VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [&instance, deletef](T obj) { deletef(instance, obj, nullptr); };
//    }

//    VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef) {
//        this->deleter = [&device, deletef](T obj) { deletef(device, obj, nullptr); };
//    }

//    ~VDeleter() {
//        cleanup();
//    }

//    const T* operator &() const {
//        return &object;
//    }

//    T* replace() {
//        cleanup();
//        return &object;
//    }

//    operator T() const {
//        return object;
//    }

//    void operator=(T rhs) {
//        if (rhs != object) {
//            cleanup();
//            object = rhs;
//        }
//    }

//    template<typename V>
//    bool operator==(V rhs) {
//        return object == T(rhs);
//    }

//private:
//    T object{VK_NULL_HANDLE};
//    std::function<void(T)> deleter;

//    void cleanup() {
//        if (object != VK_NULL_HANDLE) {
//            deleter(object);
//        }
//        object = VK_NULL_HANDLE;
//    }
//};

const int WIDTH = 800;
const int HEIGHT = 600;

const std::vector<const char*> validationLayers = {
    "VK_LAYER_LUNARG_standard_validation"
};

const std::vector<const char*> deviceExtensions = {
    VK_KHR_SWAPCHAIN_EXTENSION_NAME
};

#ifdef NDEBUG
    const bool enableValidationLayers = false;
#else
    const bool enableValidationLayers = true;
#endif

VkResult CreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback) {
    auto func = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
    if (func != nullptr) {
        return func(instance, pCreateInfo, pAllocator, pCallback);
    } else {
        return VK_ERROR_EXTENSION_NOT_PRESENT;
    }
}

void DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator) {
    auto func = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
    if (func != nullptr) {
        func(instance, callback, pAllocator);
    }
}

struct QueueFamilyIndices {
    int graphicsFamily = -1;
    int presentFamily = -1;

    bool isComplete() {
        return graphicsFamily >= 0 && presentFamily >= 0;
    }
};

struct SwapChainSupportDetails {
    VkSurfaceCapabilitiesKHR capabilities;
    std::vector<VkSurfaceFormatKHR> formats;
    std::vector<VkPresentModeKHR> presentModes;
};

class HelloTriangleApplication {
public:
    void run() {
            initWindow();
            initVulkan();
            mainLoop();
    }

private:
    GLFWwindow* window;

    VkInstance instance;
    VkDebugReportCallbackEXT callback;

    VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
    VkDevice device;

    VkQueue graphicsQueue;
    VkQueue presentQueue;

    VkSurfaceKHR surface;

    VkSwapchainKHR swapChain;
    std::vector<VkImage> swapChainImages;
    VkFormat swapChainImageFormat;
    VkExtent2D swapChainExtent;
    std::vector<VkImageView> swapChainImageViews;

    void initWindow() {
        // init GLFW library.
        glfwInit();

        // Tell GLFW not to create OpenGL context by default.
        glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
        // Disable resizing window operation here.
        glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

        // glfwCreateWindow(width, height, title, monitorIndex(optional))
        window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);

    }

    void initVulkan() {
        // init Vulkan library by creating an instance.
        createInstance();
        setupDebugCallback();
        createSurface();
        pickPhysicalDevice();
        createLogicalDevice();
        createSwapChain();
        createImageViews();
    }

    void createSurface() {
        if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
            throw std::runtime_error("failed to create window surface!");
        }
    }

    void pickPhysicalDevice() {
        uint32_t deviceCount = 0;
        vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);

        if (deviceCount == 0) {
            throw std::runtime_error("failed to find GPUs with Vulkan support!");
        }

        std::vector<VkPhysicalDevice> devices(deviceCount);
        vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());

        for (const auto& device : devices) {
            if (isDeviceSuitable(device)) {
                physicalDevice = device;
                break;
            }
        }

        if (physicalDevice == VK_NULL_HANDLE) {
            throw std::runtime_error("failed to find a suitable GPU!");
        }
    }

    void createLogicalDevice() {
        QueueFamilyIndices indices = findQueueFamilies(physicalDevice);

        std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
        std::set<int> uniqueQueueFamilies = {indices.graphicsFamily, indices.presentFamily};

        float queuePriority = 1.0f;
        for (int queueFamily : uniqueQueueFamilies) {
            VkDeviceQueueCreateInfo queueCreateInfo = {};
            queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
            queueCreateInfo.queueFamilyIndex = queueFamily;
            queueCreateInfo.queueCount = 1;
            queueCreateInfo.pQueuePriorities = &queuePriority;
            queueCreateInfos.push_back(queueCreateInfo);
        }

        VkPhysicalDeviceFeatures deviceFeatures = {};

        VkDeviceCreateInfo createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;

        createInfo.pQueueCreateInfos = queueCreateInfos.data();
        createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());

        createInfo.pEnabledFeatures = &deviceFeatures;

        createInfo.enabledExtensionCount = deviceExtensions.size();
        createInfo.ppEnabledExtensionNames = deviceExtensions.data();

        if (enableValidationLayers) {
            createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
            createInfo.ppEnabledLayerNames = validationLayers.data();
        } else {
            createInfo.enabledLayerCount = 0;
        }

        if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
            throw std::runtime_error("failed to create logical device!");
        }

        // Retrieving queue handles
        vkGetDeviceQueue(device, indices.graphicsFamily, 0, &graphicsQueue);
        vkGetDeviceQueue(device, indices.presentFamily, 0, &presentQueue);
    }

    void createSwapChain() {
        SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);

        VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
        VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
        VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);

        uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
        if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
           imageCount = swapChainSupport.capabilities.maxImageCount;
        }

        VkSwapchainCreateInfoKHR createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
        createInfo.surface = surface;

        createInfo.minImageCount = imageCount;
        createInfo.imageFormat = surfaceFormat.format;
        createInfo.imageColorSpace = surfaceFormat.colorSpace;
        createInfo.imageExtent = extent;
        createInfo.imageArrayLayers = 1;
        createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;

        QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
        uint32_t queueFamilyIndices[] = {(uint32_t) indices.graphicsFamily, (uint32_t) indices.presentFamily};

        if (indices.graphicsFamily != indices.presentFamily) {
           createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
           createInfo.queueFamilyIndexCount = 2;
           createInfo.pQueueFamilyIndices = queueFamilyIndices;
        } else {
           createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
        }

        createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
        createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
        createInfo.presentMode = presentMode;
        createInfo.clipped = VK_TRUE;

        createInfo.oldSwapchain = VK_NULL_HANDLE;

        if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
           throw std::runtime_error("failed to create swap chain!");
        }

        vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
        swapChainImages.resize(imageCount);
        vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());

        swapChainImageFormat = surfaceFormat.format;
        swapChainExtent = extent;
    }

    void createImageViews() {
        swapChainImageViews.resize(swapChainImages.size());

        for (size_t i = 0; i < swapChainImages.size(); i++) {
            VkImageViewCreateInfo createInfo = {};
            createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
            createInfo.image = swapChainImages[i];
            createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
            createInfo.format = swapChainImageFormat;
            createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
            createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
            createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
            createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
            createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
            createInfo.subresourceRange.baseMipLevel = 0;
            createInfo.subresourceRange.levelCount = 1;
            createInfo.subresourceRange.baseArrayLayer = 0;
            createInfo.subresourceRange.layerCount = 1;

            if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) {
                throw std::runtime_error("failed to create image views!");
            }
        }
    }

    VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
        if (availableFormats.size() == 1 && availableFormats[0].format == VK_FORMAT_UNDEFINED) {
            return {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
        }

        for (const auto& availableFormat : availableFormats) {
            if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
                return availableFormat;
            }
        }

        return availableFormats[0];
    }

    VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
        if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
            return capabilities.currentExtent;
        } else {
            VkExtent2D actualExtent = {WIDTH, HEIGHT};

            actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
            actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));

            return actualExtent;
        }
    }

    VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes) {
        VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;

        for (const auto& availablePresentMode : availablePresentModes) {
            if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
                return availablePresentMode;
            } else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
                bestMode = availablePresentMode;
            }
        }

        return bestMode;
    }

    SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
        SwapChainSupportDetails details;

        vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);

        uint32_t formatCount;
        vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);

        if (formatCount != 0) {
            details.formats.resize(formatCount);
            vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
        }

        uint32_t presentModeCount;
        vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);

        if (presentModeCount != 0) {
            details.presentModes.resize(presentModeCount);
            vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
        }

        return details;
    }

    bool isDeviceSuitable(VkPhysicalDevice device) {
        QueueFamilyIndices indices = findQueueFamilies(device);

        bool extensionsSupported = checkDeviceExtensionSupport(device);

        bool swapChainAdequate = false;
        if (extensionsSupported) {
            SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
            swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
        }

        return indices.isComplete() && extensionsSupported && swapChainAdequate;
    }

    bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
        uint32_t extensionCount;
        vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);

        std::vector<VkExtensionProperties> availableExtensions(extensionCount);
        vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());

        std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());

        for (const auto& extension : availableExtensions) {
            requiredExtensions.erase(extension.extensionName);
        }

        return requiredExtensions.empty();
    }

    /**
     * @brief findQueueFamilies
     *  Check if the physical device support queue type: VK_queue_graphics_bit
     * @param device
     * @return
     */
    QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) {
        QueueFamilyIndices indices;

        uint32_t queueFamilyCount = 0;
        vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);

        std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
        vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());

        int i = 0;
        for (const auto& queueFamily : queueFamilies) {
            if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
                indices.graphicsFamily = i;
            }

            if (indices.isComplete()) {
                break;
            }

            i++;
        }

        return indices;
    }

    void setupDebugCallback() {
        if (!enableValidationLayers) return;

        // flags field allows you to filter which types of msg you would like to receive.
        VkDebugReportCallbackCreateInfoEXT createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
        createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
        createInfo.pfnCallback = debugCallback;

        if (CreateDebugReportCallbackEXT(instance, &createInfo, nullptr, &callback) != VK_SUCCESS) {
            throw std::runtime_error("failed to set up debug callback!");
        }
    }

    void mainLoop() {
        // Keep the app running until either an error occurs
        //    or the window is closed.
        while (!glfwWindowShouldClose(window)) {
            glfwPollEvents();
        }

        glfwDestroyWindow(window);

        glfwTerminate();
    }

    void createInstance() {
        // Check if we are able to enable all requested layers.
        if (enableValidationLayers && !checkValidationLayerSupport()) {
            throw std::runtime_error("Validation layers requested, but not available!");
        }

        // Optional info
        VkApplicationInfo appInfo = {};
        appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; // not optional
        appInfo.pApplicationName = "Hello Triangle";
        appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.pEngineName = "No Engine";
        appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.apiVersion = VK_API_VERSION_1_0;

        // Non-optional info. (Define Global extensions and validation layers)
        VkInstanceCreateInfo createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        createInfo.pApplicationInfo = &appInfo;

        // Specify our desired global extensions.
        unsigned int glfwExtensionCount = 0;
        const char** glfwExtensions;

        glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);

//        createInfo.enabledExtensionCount = glfwExtensionCount;
//        createInfo.ppEnabledExtensionNames = glfwExtensions;
        auto extensions = getRequiredExtensions();
        createInfo.enabledExtensionCount = extensions.size();
        createInfo.ppEnabledExtensionNames = extensions.data();

        // Determine the global validation layers to enable.
        if (enableValidationLayers) {
            createInfo.enabledLayerCount = validationLayers.size();
            createInfo.ppEnabledLayerNames = validationLayers.data();
        } else {
            createInfo.enabledLayerCount = 0;
        }

        VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);

        if (result != VK_SUCCESS) {
            throw std::runtime_error("Failed to create Vulkan instance!");
        }
    }

    /**
     * @brief checkValidationLayerSupport
     * Check if all of the requested layers are available.
     * @return
     */
    bool checkValidationLayerSupport() {
        uint32_t layerCount;
        vkEnumerateInstanceLayerProperties(&layerCount, nullptr);

        std::vector<VkLayerProperties> availableLayers(layerCount);
        vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());

        // Check if all of the layers in validationLayers exist in the availableLayers list.
        for (const char* layerName : validationLayers) {
            bool layerFound = false;

            for (const auto& layerProperties : availableLayers) {
                if (strcmp(layerName, layerProperties.layerName) == 0) {
                    layerFound = true;
                    break;
                }
            }

            if (!layerFound) {
                return false;
            }
        }

        return true;
    }

    /**
     * @brief getRequiredExtensions
     * @return the required list of extensions based on validation layers are
     *      enabled or not.
     */
    std::vector<const char*> getRequiredExtensions() {
        std::vector<const char*> extensions;

        unsigned int glfwExtensionCount = 0;
        const char** glfwExtensions;
        glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);

        for (unsigned int i = 0; i < glfwExtensionCount; i++) {
            extensions.push_back(glfwExtensions[i]);
        }

        if (enableValidationLayers) {
            extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
        }

        return extensions;
    }

    /**
     * @brief debugCallback
     * @param flags: Type of msg
     * @param objType: Type of obj
     * @param obj
     * @param location
     * @param code
     * @param layerPrefix
     * @param msg
     * @param userData
     */
    static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
        VkDebugReportFlagsEXT flags,
        VkDebugReportObjectTypeEXT objType,
        uint64_t obj,
        size_t location,
        int32_t code,
        const char* layerPrefix,
        const char* msg,
        void* userData) {

        std::cerr << "validation layer: " << msg << std::endl;

        return VK_FALSE;
    }
};

int main()
{
    HelloTriangleApplication app;

    try {
        app.run();
    } catch (const std::runtime_error& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <unistd.h>

using namespace boost;
using namespace std;

int main()
{
    vector<string> command;
    cout  << "$ ";
    string converter;                           //converts all bits of string into one piece
    string to_be_tokenized;
    getline(cin, to_be_tokenized);
    char_separator<char> delim("^&| ", ";", keep_empty_tokens);
    tokenizer< char_separator<char>  > mytok(to_be_tokenized, delim);

    for(auto it = mytok.begin(); it != mytok.end(); ++it)
    {
        converter += " ";
        converter += *it;
        converter += " \0";
    }
    cout << converter << endl;
    command.push_back(converter);

}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

execvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "SerialPort.h"
#include <stdio.h>
#include <string.h>

using namespace std;

char* portName = "\\\\.\\COM20";

#define MAX_DATA_LENGTH 255

char incomingData[MAX_DATA_LENGTH];

//Control signals for turning on and turning off the led
//Check arduino code
char ledON[] = "ON\n";
char ledOFF[] = "OFF\n";

//Arduino SerialPort object
SerialPort *arduino;

//Blinking Delay
const unsigned int BLINKING_DELAY = 1000;

//If you want to send data then define "SEND" else comment it out
#define SEND

void exampleReceiveData(void)
{
    int readResult = arduino->readSerialPort(incomingData, MAX_DATA_LENGTH);
    printf("%s", incomingData);
    Sleep(10);
}

void exampleWriteData(unsigned int delayTime)
{
    arduino->writeSerialPort(ledON, MAX_DATA_LENGTH);
    Sleep(delayTime);
    arduino->writeSerialPort(ledOFF, MAX_DATA_LENGTH);
    Sleep(delayTime);
}

int main()
{
    arduino = new SerialPort(portName);

    //Checking if arduino is connected or not
    if (arduino->isConnected()){
        std::cout << "Connection established at port " << portName << endl;
    }

    #ifdef SEND
        while(arduino->isConnected()) exampleWriteData(BLINKING_DELAY);
    #else // SEND
        while(arduino->isConnected()) exampleReceiveData();
    #endif // SEND
}
<commit_msg>feat(autoConnect)<commit_after>#include <iostream>
#include "SerialPort.h"
#include <stdio.h>
#include <string.h>

using namespace std;

char* portName = "\\\\.\\COM20";

#define MAX_DATA_LENGTH 255

char incomingData[MAX_DATA_LENGTH];

//Control signals for turning on and turning off the led
//Check arduino code
char ledON[] = "ON\n";
char ledOFF[] = "OFF\n";

//Arduino SerialPort object
SerialPort *arduino;

//Blinking Delay
const unsigned int BLINKING_DELAY = 1000;

//If you want to send data then define "SEND" else comment it out
#define SEND

void exampleReceiveData(void)
{
    int readResult = arduino->readSerialPort(incomingData, MAX_DATA_LENGTH);
    printf("%s", incomingData);
    Sleep(10);
}

void exampleWriteData(unsigned int delayTime)
{
    arduino->writeSerialPort(ledON, MAX_DATA_LENGTH);
    Sleep(delayTime);
    arduino->writeSerialPort(ledOFF, MAX_DATA_LENGTH);
    Sleep(delayTime);
}

void autoConnect(void)
{
    //wait connection
	while (!arduino->isConnected()) {
		Sleep(100);
		arduino = new SerialPort(portName);
	}

    //Checking if arduino is connected or not
	if (arduino->isConnected()) {
		std::cout << "Connection established at port " << portName << endl;
	}

	#ifdef SEND
        while(arduino->isConnected()) exampleWriteData(BLINKING_DELAY);
    #else // SEND
        while(arduino->isConnected()) exampleReceiveData();
    #endif // SEND

    //if the serial connection is lost
	autoConnect();
}

int main()
{
    arduino = new SerialPort(portName);

    autoConnect();
}
<|endoftext|>


<commit_before>27e06773-ad5d-11e7-b564-ac87a332f658<commit_msg>bug fix<commit_after>2851fa57-ad5d-11e7-b423-ac87a332f658<|endoftext|>


<commit_before>a5586319-4b02-11e5-9293-28cfe9171a43<commit_msg>add file<commit_after>a5642a7d-4b02-11e5-89e1-28cfe9171a43<|endoftext|>


<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTranslator>
#include <QDebug>
#include "myclass.h"
#include "settings.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Settings settings(0, "xiaoyong", "2048-Qt");
    settings.setVersion(QString(VER));

    // Localization
    QString locale;
    if (settings.contains("language")) {
        locale = settings.value("language").toString();
    } else {
        locale = QLocale::system().name();
        settings.setValue("language", locale);
    }
    QString tsFile = "2048-qt_" + locale;

    QTranslator translator;
    if (translator.load(tsFile, ":/ts")) {
        qDebug() << "Successfully loaded " + tsFile;
    } else {
        qDebug() << "Failed to load " + tsFile;
    }
    app.installTranslator(&translator);

    QQmlApplicationEngine engine;

    // Access C++ object "myClass" from QML as "myClass"
    MyClass myClass;
    engine.rootContext()->setContextProperty("myClass", &myClass);

    // Access C++ object "settings" from QML as "settings"
    engine.rootContext()->setContextProperty("settings", &settings);

    engine.load(QUrl(QStringLiteral("qrc:///qml/main.qml")));

    return app.exec();
}
<commit_msg>avoided trying to load English translation file<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTranslator>
#include <QDebug>
#include "myclass.h"
#include "settings.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Settings settings(0, "xiaoyong", "2048-Qt");
    settings.setVersion(QString(VER));

    // Localization
    QString locale;
    if (settings.contains("language")) {
        locale = settings.value("language").toString();
    } else {
        locale = QLocale::system().name();
        settings.setValue("language", locale);
    }

    QTranslator translator;
    if (! locale.startsWith("en")) {
        QString tsFile = "2048-qt_" + locale;

        if (translator.load(tsFile, ":/ts")) {
            qDebug() << "Successfully loaded " + tsFile;
            app.installTranslator(&translator);
        } else {
            qDebug() << "Failed to load " + tsFile;
        }
    }

    QQmlApplicationEngine engine;

    // Access C++ object "myClass" from QML as "myClass"
    MyClass myClass;
    engine.rootContext()->setContextProperty("myClass", &myClass);

    // Access C++ object "settings" from QML as "settings"
    engine.rootContext()->setContextProperty("settings", &settings);

    engine.load(QUrl(QStringLiteral("qrc:///qml/main.qml")));

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: cjg
 *
 * Created on 30 settembre 2009, 12.21
 */

#include <iostream>
#include "ConfigFile.h"
#include "AfUnixCommunicator.h"
#include "Backend.h"

using namespace std;

int main(int argc, char** argv) {
    if(argc != 2) {
        cerr << "Usage: " << argv[0] << " /path/to/config.xml" << endl;
        return 1;
    }
    ConfigFile *cf = new ConfigFile(argv[1]);
    ConfigFile::Section communicators =
            cf->GetTopLevel()->GetSection("communicators");
    string default_communicator_name =
            cf->GetTopLevel()->GetElement("default_communicator").GetValue("value");
    ConfigFile::Element default_communicator =
            communicators.GetElement(default_communicator_name);
    Communicator *c = Communicator::Create(default_communicator);
    Backend *b = new Backend(c);
    b->Start();
    delete b;
    delete c;
    delete cf;
    return 0;
}

<commit_msg>catching all exception<commit_after>/*
 * File:   main.cpp
 * Author: cjg
 *
 * Created on 30 settembre 2009, 12.21
 */

#include <iostream>
#include "ConfigFile.h"
#include "AfUnixCommunicator.h"
#include "Backend.h"

using namespace std;

int main(int argc, char** argv) {
    if(argc != 2) {
        cerr << "Usage: " << argv[0] << " /path/to/config.xml" << endl;
        return 1;
    }
    try {
        ConfigFile *cf = new ConfigFile(argv[1]);
        ConfigFile::Section communicators =
                cf->GetTopLevel()->GetSection("communicators");
        string default_communicator_name =
                cf->GetTopLevel()->GetElement("default_communicator").GetValue("value");
        ConfigFile::Element default_communicator =
                communicators.GetElement(default_communicator_name);
        Communicator *c = Communicator::Create(default_communicator);
        Backend *b = new Backend(c);
        b->Start();
        delete b;
        delete c;
        delete cf;
    } catch (string &e) {
        cerr << "Exception: " << e << endl;
    } catch(const char *e) {
        cerr << "Exception: " << e << endl;
    }
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "obscure.h"

using namespace std;
using namespace Magick;

static const struct option opts[] = {{"help", no_argument, 0, 'h'},
                                     {"alt-image", required_argument, 0, 'm'},
                                     {"output", required_argument, 0, 'o'},
                                     {"root", no_argument, 0, 'd'},
                                     {"display", no_argument, 0, 'D'},
                                     {"blur", optional_argument, 0, 'b'},
                                     {"shade", optional_argument, 0, 'S'},
                                     {"swirl", optional_argument, 0, 's'},
                                     {"spread", optional_argument, 0, 'p'},
                                     {"implode", optional_argument, 0, 'i'},
                                     {"wave", optional_argument, 0, 'w'},
                                     {0, 0, 0, 0}};

static void help() {
  cout << "ShantyLocker [OPTIONS...]         " << endl;
  cout << "    -h --help                        "
       << "Show help" << endl;
  cout << "    -m --alt-image [path]            "
       << "Use image at [path] as background to transpose obfuscated windows "
          "onto. Can't be used with --root"
       << endl;
  cout << "    -o --output [path]               "
       << "Save resulting lock screen image to path" << endl;
  cout << "    -d --root                        "
       << "Obfuscate the desktop as one window, instead of each visible window "
          "individually"
       << endl;
  cout << "    -D --display                     "
          "Display the generated image for fast option tweaking"
       << endl;
  cout << "  Obfuscation methodologies:         (built-in functions provided "
          "by ImageMagick)"
       << endl;
  cout << "    -b --blur [radius]               Blurs image. [radius] "
          "specifies the radius of the Gaussian"
       << endl;
  cout << "    -S --shade [value]               " << endl;
  cout << "    -s --swirl [degrees]             Swirl the image from the "
          "center by [degrees]"
       << endl;
  cout << "    -p --spread [amount]             Spread pixels randomly within "
          "image by [amount]"
       << endl;
  cout << "    -i --implode [factor]            Implode image by [factor]"
       << endl;
  cout << "    -w --wave [amplitude]            Must use with --alt-image for best effect"
       << endl;
}

int main(int argc, char** argv) {
  vector<function<void(Image&, double)>> operations;
  vector<double> params;

  // Default values for operations
  double rad = 5;
  double shade_factor = 20;
  double swirl_factor = 720;
  size_t spread_factor = 12;
  double implode_factor = 50;
  double amp = 5;
  bool desktop = false;
  bool display = false;

  // Default destination image to x:root
  Image base("x:root");

  string alt_image;

  // Get user's home directory, returns /home/user
  string path(getpwuid(getuid())->pw_dir);
  path += "/.config/shantylocker.png";

  int optidx;
  int c;

  while ((c = getopt_long(argc, argv, "hm:o:dDb::S::s::p::i::w::", opts,
                          &optidx)) != -1) {
    switch (c) {
      case 'h':
        help();
        return 0;

      case 'm':
        alt_image = string(optarg);
        if (alt_image[0] == '-') {
            cerr << "Argument required for -m or --root option" << endl;
            throw new invalid_argument("Argument required for -m or --root option");
        }
        base = Image(alt_image);
        break;

      case 'o':
        path = string(optarg);
        if (path[0] == '-') {
            cerr << "Argument required for -o or --output option" << endl;
            throw new invalid_argument("Argument required for -o or --output option");
        }
        break;

      case 'd':
        desktop = true;
        break;

      case 'D':
        display = true;
        break;

      case 'b':
        try {
            rad = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --blur. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(blur);
        params.push_back(rad);
        break;

      case 'S':
        try {
          shade_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --shade. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(shade);
        params.push_back(shade_factor);
        break;

      case 's':
        try {
            swirl_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --swirl. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(swirl);
        params.push_back(swirl_factor);
        break;
      case 'p':
        try {
            spread_factor = (size_t)stoi(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --spread. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(spread);
        params.push_back(spread_factor);
        break;
      case 'i':
        try {
            implode_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --implode. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(implode);
        params.push_back(implode_factor);
        break;

      case 'w':
        try {
            amp = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --wave. Using default..." << endl;
        }
        operations.push_back(wave);
        params.push_back(amp);
        break;

      case '?':
        help();
        return 1;
      default:
        if (optopt == 'c') {
            fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        }
        else if (isprint(optopt)) {
            fprintf(stderr, "Unknown option -%c.\n", optopt);
        }
        else {
            fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
        }
        return 1;
    }
  }

  InitializeMagick(*argv);

  int screens;

  // 1st parameter takes display name. If NULL, uses DISPLAY env
  xcb_connection_t* connection = xcb_connect(NULL, &screens);

  // Get the first screen
  const xcb_setup_t* setup = xcb_get_setup(connection);
  xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
  xcb_screen_t* screen = iter.data;

  // Either fill visible_windows, or insert root window
  vector<unique_ptr<rectangle_t>> visible_windows;
  if (desktop) {
    visible_windows.push_back(make_unique<rectangle_t>(0, 0, screen->width_in_pixels,
                                                       screen->height_in_pixels));
  }
  else {
      get_visible_windows(connection, screen, visible_windows);
  }
  execute_operations(visible_windows, operations, params, base);

  if (display) {
      base.display();
  }

  base.write(path);
  TerminateMagick();
  xcb_disconnect(connection);
  return 0;
}<commit_msg>formatting<commit_after>#include <iostream>
#include "obscure.h"

using namespace std;
using namespace Magick;

static const struct option opts[] = {{"help", no_argument, 0, 'h'},
                                     {"alt-image", required_argument, 0, 'm'},
                                     {"output", required_argument, 0, 'o'},
                                     {"root", no_argument, 0, 'd'},
                                     {"display", no_argument, 0, 'D'},
                                     {"blur", optional_argument, 0, 'b'},
                                     {"shade", optional_argument, 0, 'S'},
                                     {"swirl", optional_argument, 0, 's'},
                                     {"spread", optional_argument, 0, 'p'},
                                     {"implode", optional_argument, 0, 'i'},
                                     {"wave", optional_argument, 0, 'w'},
                                     {0, 0, 0, 0}};

static void help() {
  cout << "ShantyLocker [OPTIONS...]         " << endl;
  cout << "    -h --help                        "
       << "Show help" << endl;
  cout << "    -m --alt-image [path]            "
       << "Use image at [path] as background to transpose obfuscated windows "
          "onto. Can't be used with --root"
       << endl;
  cout << "    -o --output [path]               "
       << "Save resulting lock screen image to path" << endl;
  cout << "    -d --root                        "
       << "Obfuscate the desktop as one window, instead of each visible window "
          "individually"
       << endl;
  cout << "    -D --display                     "
          "Display the generated image for fast option tweaking"
       << endl;
  cout << "  Obfuscation methodologies:         (built-in functions provided "
          "by ImageMagick)"
       << endl;
  cout << "    -b --blur [radius]               Blurs image. [radius] "
          "specifies the radius of the Gaussian"
       << endl;
  cout << "    -S --shade [value]               " << endl;
  cout << "    -s --swirl [degrees]             Swirl the image from the "
          "center by [degrees]"
       << endl;
  cout << "    -p --spread [amount]             Spread pixels randomly within "
          "image by [amount]"
       << endl;
  cout << "    -i --implode [factor]            Implode image by [factor]"
       << endl;
  cout << "    -w --wave [amplitude]            Must use with --alt-image for best effect"
       << endl;
}

int main(int argc, char** argv) {
  vector<function<void(Image&, double)>> operations;
  vector<double> params;

  // Default values for operations
  double rad = 5;
  double shade_factor = 20;
  double swirl_factor = 720;
  size_t spread_factor = 12;
  double implode_factor = 50;
  double amp = 5;
  bool desktop = false;
  bool display = false;

  // Default destination image to x:root
  Image base("x:root");

  string alt_image;

  // Get user's home directory, returns /home/user
  string path(getpwuid(getuid())->pw_dir);
  path += "/.config/shantylocker.png";

  int optidx;
  int c;

  while ((c = getopt_long(argc, argv, "hm:o:dDb::S::s::p::i::w::", opts,
                          &optidx)) != -1) {
    switch (c) {
      case 'h':
        help();
        return 0;

      case 'm':
        alt_image = string(optarg);
        if (alt_image[0] == '-') {
            cerr << "Argument required for -m or --root option" << endl;
            throw new invalid_argument("Argument required for -m or --root option");
        }
        base = Image(alt_image);
        break;

      case 'o':
        path = string(optarg);
        if (path[0] == '-') {
            cerr << "Argument required for -o or --output option" << endl;
            throw new invalid_argument("Argument required for -o or --output option");
        }
        break;

      case 'd':
        desktop = true;
        break;

      case 'D':
        display = true;
        break;

      case 'b':
        try {
            rad = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --blur. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(blur);
        params.push_back(rad);
        break;

      case 'S':
        try {
          shade_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --shade. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(shade);
        params.push_back(shade_factor);
        break;

      case 's':
        try {
            swirl_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --swirl. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(swirl);
        params.push_back(swirl_factor);
        break;
      case 'p':
        try {
            spread_factor = (size_t)stoi(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --spread. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(spread);
        params.push_back(spread_factor);
        break;
      case 'i':
        try {
            implode_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --implode. Using default..." << endl;
        } catch (const logic_error& e) {}
        operations.push_back(implode);
        params.push_back(implode_factor);
        break;

      case 'w':
        try {
            amp = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --wave. Using default..." << endl;
        }
        operations.push_back(wave);
        params.push_back(amp);
        break;

      case '?':
        help();
        return 1;
      default:
        if (optopt == 'c') {
            fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        }
        else if (isprint(optopt)) {
            fprintf(stderr, "Unknown option -%c.\n", optopt);
        }
        else {
            fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
        }
        return 1;
    }
  }

  InitializeMagick(*argv);

  int screens;

  // 1st parameter takes display name. If NULL, uses DISPLAY env
  xcb_connection_t* connection = xcb_connect(NULL, &screens);

  // Get the first screen
  const xcb_setup_t* setup = xcb_get_setup(connection);
  xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
  xcb_screen_t* screen = iter.data;

  // Either fill visible_windows, or insert root window
  vector<unique_ptr<rectangle_t>> visible_windows;
  if (desktop) {
    visible_windows.push_back(make_unique<rectangle_t>(0, 0,
                                                       screen->width_in_pixels,
                                                       screen->height_in_pixels));
  }
  else {
      get_visible_windows(connection, screen, visible_windows);
  }
  execute_operations(visible_windows, operations, params, base);

  if (display) {
      base.display();
  }

  base.write(path);
  TerminateMagick();
  xcb_disconnect(connection);
  return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2015 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.

#include <Common/HighQueuePch.h>

#include <HighQueue/details/HQMemoryBlockPool.h>
#include <Common/Log.h>
using namespace HighQueue;

HQMemoryBlockPool::HQMemoryBlockPool()
: poolSize_(0)
, blockSize_(0)
, blockCount_(0)
, rootOffset_(NULL_OFFSET)
{
}

HQMemoryBlockPool::HQMemoryBlockPool(
    size_t poolSize,
    size_t blockSize)
: poolSize_(poolSize)
, blockSize_(cacheAlignedMessageSize(blockSize))
, blockCount_(0)
, rootOffset_(NULL_OFFSET)
{
    preAllocate(blockSize_, poolSize_);
}

size_t HQMemoryBlockPool::preAllocate(size_t blockSize, size_t poolSize)
{
    auto sizeofthis = sizeof(HQMemoryBlockPool);
    auto intThis = uintptr_t(this);
    auto endThis = intThis + sizeofthis + CacheLineSize - 1;
    endThis -= endThis % CacheLineSize;
    size_t current = endThis - intThis;
    if(current + blockSize_ > poolSize)
    {
        throw std::invalid_argument("HQMemoryBlockPool: aligned offset + message size exceeds pool size.");
    }
    poolSize_ = poolSize;
    blockSize_ = blockSize;
    blockCount_ = 0;

    auto baseAddress = reinterpret_cast<byte_t *>(this);
    rootOffset_ = current;
    while(current != NULL_OFFSET)
    {
        auto next = current + blockSize_;
        if(next + blockSize_ > poolSize_)
        {
            next = NULL_OFFSET;
        }

        reinterpret_cast<size_t &>(baseAddress[current]) = next;
        current = next;
        blockCount_ += 1;
    }
    return blockCount_;
}

bool HQMemoryBlockPool::tryAllocate(Message & message)
{
    SpinLock::Guard guard(lock_);
    auto offset = rootOffset_;
    auto ok = offset != NULL_OFFSET;
    if(ok)
    {
        auto baseAddress = reinterpret_cast<byte_t *>(this);
        rootOffset_ = reinterpret_cast<size_t &>(baseAddress[offset]);
        message.set(this, blockSize_, offset, 0);
    }
    return ok;
}

void HQMemoryBlockPool::allocate(Message & message)
{
    if(!tryAllocate(message))
    {
        throw std::runtime_error("Memory allocation for message failed");
    }
}

void HQMemoryBlockPool::release(Message & message)
{
    auto baseAddress = reinterpret_cast<byte_t *>(this);
    if(message.getContainer() != baseAddress)
    {
        throw std::runtime_error("Message returned to wrong allocator.");
    }

    SpinLock::Guard guard(lock_);
    LogVerbose("Release " << message.getOffset());
    *message.get<size_t>() = rootOffset_;
    rootOffset_ = message.getOffset();
    message.reset();
}

bool HQMemoryBlockPool::isEmpty() const
{
    return rootOffset_ == NULL_OFFSET;
}

size_t HQMemoryBlockPool::cacheAlignedMessageSize(size_t blockSize)
{
    return ((blockSize + CacheLineSize - 1) / CacheLineSize) * CacheLineSize;
}

size_t HQMemoryBlockPool::spaceNeeded(size_t blockSize, size_t messageCount)
{
    return sizeof(HQMemoryBlockPool) + cacheAlignedMessageSize(blockSize) * messageCount + CacheLineSize;
}
<commit_msg>Remove verbose message in HQMemoryBlockPool.cpp<commit_after>// Copyright (c) 2015 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.

#include <Common/HighQueuePch.h>

#include <HighQueue/details/HQMemoryBlockPool.h>
#include <Common/Log.h>
using namespace HighQueue;

HQMemoryBlockPool::HQMemoryBlockPool()
: poolSize_(0)
, blockSize_(0)
, blockCount_(0)
, rootOffset_(NULL_OFFSET)
{
}

HQMemoryBlockPool::HQMemoryBlockPool(
    size_t poolSize,
    size_t blockSize)
: poolSize_(poolSize)
, blockSize_(cacheAlignedMessageSize(blockSize))
, blockCount_(0)
, rootOffset_(NULL_OFFSET)
{
    preAllocate(blockSize_, poolSize_);
}

size_t HQMemoryBlockPool::preAllocate(size_t blockSize, size_t poolSize)
{
    auto sizeofthis = sizeof(HQMemoryBlockPool);
    auto intThis = uintptr_t(this);
    auto endThis = intThis + sizeofthis + CacheLineSize - 1;
    endThis -= endThis % CacheLineSize;
    size_t current = endThis - intThis;
    if(current + blockSize_ > poolSize)
    {
        throw std::invalid_argument("HQMemoryBlockPool: aligned offset + message size exceeds pool size.");
    }
    poolSize_ = poolSize;
    blockSize_ = blockSize;
    blockCount_ = 0;

    auto baseAddress = reinterpret_cast<byte_t *>(this);
    rootOffset_ = current;
    while(current != NULL_OFFSET)
    {
        auto next = current + blockSize_;
        if(next + blockSize_ > poolSize_)
        {
            next = NULL_OFFSET;
        }

        reinterpret_cast<size_t &>(baseAddress[current]) = next;
        current = next;
        blockCount_ += 1;
    }
    return blockCount_;
}

bool HQMemoryBlockPool::tryAllocate(Message & message)
{
    SpinLock::Guard guard(lock_);
    auto offset = rootOffset_;
    auto ok = offset != NULL_OFFSET;
    if(ok)
    {
        auto baseAddress = reinterpret_cast<byte_t *>(this);
        rootOffset_ = reinterpret_cast<size_t &>(baseAddress[offset]);
        message.set(this, blockSize_, offset, 0);
    }
    return ok;
}

void HQMemoryBlockPool::allocate(Message & message)
{
    if(!tryAllocate(message))
    {
        throw std::runtime_error("Memory allocation for message failed");
    }
}

void HQMemoryBlockPool::release(Message & message)
{
    auto baseAddress = reinterpret_cast<byte_t *>(this);
    if(message.getContainer() != baseAddress)
    {
        throw std::runtime_error("Message returned to wrong allocator.");
    }

    SpinLock::Guard guard(lock_);
    *message.get<size_t>() = rootOffset_;
    rootOffset_ = message.getOffset();
    message.reset();
}

bool HQMemoryBlockPool::isEmpty() const
{
    return rootOffset_ == NULL_OFFSET;
}

size_t HQMemoryBlockPool::cacheAlignedMessageSize(size_t blockSize)
{
    return ((blockSize + CacheLineSize - 1) / CacheLineSize) * CacheLineSize;
}

size_t HQMemoryBlockPool::spaceNeeded(size_t blockSize, size_t messageCount)
{
    return sizeof(HQMemoryBlockPool) + cacheAlignedMessageSize(blockSize) * messageCount + CacheLineSize;
}
<|endoftext|>