<commit_before>#include "Shell.hpp"
#include <iostream>
#include <sstream>
#include "FileSystem.hpp"

using namespace std;

const int MAXCOMMANDS = 8;
const int NUMAVAILABLECOMMANDS = 16;

string availableCommands[NUMAVAILABLECOMMANDS] = {
	"quit", "format", "ls", "create", "cat", "save", "load",
	"rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help", "chmod"
};

Shell::Shell(const string &user) {
	this->user = user;
	currentDir = "/";
}

bool Shell::getCommand() {
	string userCommand, commandArr[MAXCOMMANDS];

	cout << user << ":" << currentDir << "$ ";
	getline(cin, userCommand);

	int nrOfCommands = parseCommandString(userCommand, commandArr);
	if (nrOfCommands > 0) {
		int cIndex = findCommand(commandArr[0]);
		switch (cIndex) {

		case 0: // quit
			cout << "Exiting" << endl;
			return false;
			break;
		case 1: // format
			fileSystem.format();
            currentDir = "/";
			break;
		case 2: // ls
			cout << "Listing directory" << endl;

            if (nrOfCommands < 2)
                fileSystem.ls(absolutePath(currentDir));
            else
                fileSystem.ls(absolutePath(commandArr[1]));

			break;
		case 3: // create
			fileSystem.create(absolutePath(commandArr[1]));
			break;
		case 4: // cat
			fileSystem.cat(absolutePath(commandArr[1]));
			break;
		case 5: // save
			fileSystem.save(commandArr[1]);
			break;
		case 6: // load
			fileSystem.load(commandArr[1]);
			break;
		case 7: // rm
			fileSystem.rm(absolutePath(commandArr[1]));
			break;

		case 8: // copy
			fileSystem.copy(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 9: // append
			fileSystem.append(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 10: // rename
            fileSystem.rename(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 11: // mkdir
			fileSystem.mkdir(absolutePath(commandArr[1]));
			break;

		case 12: // cd
			if (fileSystem.directoryExists(absolutePath(commandArr[1]))) {
				currentDir = "/" + absolutePath(commandArr[1]);
				if (currentDir[currentDir.length() - 1] != '/')
					currentDir += "/";
			} else {
                cout << "Directory does not exist." << endl;
            }
			break;

		case 13: // pwd
			cout << currentDir << endl;
			break;

		case 14: // help
			cout << help() << endl;
			break;
		case 15: // chmod
			if (commandArr[2].length() != 0){
				int perm = stoi(commandArr[2]);
				fileSystem.chmod(absolutePath(commandArr[1]), perm);
			} else {
				cout << "Invalid amount of arguments." << endl;
            }
			break;

		default:
			cout << "Unknown command: " << commandArr[0] << endl;
		}
	}

	return true;
}

int Shell::parseCommandString(const string &userCommand, string strArr[]) {
	stringstream ssin(userCommand);
	int counter = 0;
	while (ssin.good() && counter < MAXCOMMANDS) {
		ssin >> strArr[counter];
		counter++;
	}
	if (strArr[0] == "") {
		counter = 0;
	}
	return counter;
}

int Shell::findCommand(string &command) {
	int index = -1;
	for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) {
		if (command == availableCommands[i]) {
			index = i;
		}
	}
	return index;
}

string Shell::absolutePath(string path) const {
	/// Fix relative path
	if (path.length() == 0 || path[0] != '/')
		path = currentDir + path;
	path = path.substr(1);

    vector<string> parts = split(path, '/');
    vector<string> temp;

    /// Replace ./ and ../
    for (string part : parts) {
        if (part == "..") {
            if (!temp.empty())
                temp.pop_back();
        } else if (part != ".") {
            temp.push_back(part);
        }
    }

    path = "";
    for (size_t i=0; i<temp.size(); i++) {
        if (i > 0)
            path += "/";
        path += temp[i];
    }

	return path;
}

string Shell::help() {
	string helpStr;
	helpStr += "OSD Disk Tool .oO Help Screen Oo.\n";
	helpStr += "-----------------------------------------------------------------------------------\n";
	helpStr += "* quit:                             Quit OSD Disk Tool\n";
	helpStr += "* format;                           Formats disk\n";
	helpStr += "* ls     <path>:                    Lists contents of <path>.\n";
	helpStr += "* create <path>:                    Creates a file and stores contents in <path>\n";
	helpStr += "* cat    <path>:                    Dumps contents of <file>.\n";
	helpStr += "* save   <real-file>:               Saves disk to <real-file>\n";
	helpStr += "* read   <real-file>:               Reads <real-file> onto disk\n";
	helpStr += "* rm     <file>:                    Removes <file>\n";
	helpStr += "* copy   <source>    <destination>: Copy <source> to <destination>\n";
	helpStr += "* append <source>    <destination>: Appends contents of <source> to <destination>\n";
	helpStr += "* rename <old-file>  <new-file>:    Renames <old-file> to <new-file>\n";
	helpStr += "* mkdir  <directory>:               Creates a new directory called <directory>\n";
	helpStr += "* cd     <directory>:               Changes current working directory to <directory>\n";
	helpStr += "* pwd:                              Get current working directory\n";
	helpStr += "* help:                             Prints this help screen\n";
	return helpStr;
}

vector<string> Shell::split(string text, char delimiter) {
    vector<string> parts;

    while (text.find(delimiter) != string::npos) {
        size_t pos = text.find(delimiter);
        parts.push_back(text.substr(0, pos));
        text = text.substr(pos+1);
    }

    if (!text.empty())
        parts.push_back(text);

    return parts;
}
<commit_msg>Shell code cleanup<commit_after>#include "Shell.hpp"
#include <iostream>
#include <sstream>
#include "FileSystem.hpp"

using namespace std;

const int MAXCOMMANDS = 8;
const int NUMAVAILABLECOMMANDS = 16;

string availableCommands[NUMAVAILABLECOMMANDS] = {
	"quit", "format", "ls", "create", "cat", "save", "load",
	"rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help", "chmod"
};

Shell::Shell(const string &user) {
	this->user = user;
	currentDir = "/";
}

bool Shell::getCommand() {
	string userCommand, commandArr[MAXCOMMANDS];

	cout << user << ":" << currentDir << "$ ";
	getline(cin, userCommand);

	int nrOfCommands = parseCommandString(userCommand, commandArr);
	if (nrOfCommands > 0) {
		int cIndex = findCommand(commandArr[0]);
		switch (cIndex) {

		case 0: // quit
			cout << "Exiting" << endl;
			return false;
			break;
		case 1: // format
			fileSystem.format();
            currentDir = "/";
			break;
		case 2: // ls
			cout << "Listing directory" << endl;

            if (nrOfCommands < 2)
                fileSystem.ls(absolutePath(currentDir));
            else
                fileSystem.ls(absolutePath(commandArr[1]));

			break;
		case 3: // create
			fileSystem.create(absolutePath(commandArr[1]));
			break;
		case 4: // cat
			fileSystem.cat(absolutePath(commandArr[1]));
			break;
		case 5: // save
			fileSystem.save(commandArr[1]);
			break;
		case 6: // load
			fileSystem.load(commandArr[1]);
			break;
		case 7: // rm
			fileSystem.rm(absolutePath(commandArr[1]));
			break;

		case 8: // copy
			fileSystem.copy(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 9: // append
			fileSystem.append(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 10: // rename
            fileSystem.rename(absolutePath(commandArr[1]), absolutePath(commandArr[2]));
			break;

		case 11: // mkdir
			fileSystem.mkdir(absolutePath(commandArr[1]));
			break;

		case 12: // cd
			if (fileSystem.directoryExists(absolutePath(commandArr[1]))) {
				currentDir = "/" + absolutePath(commandArr[1]);
				if (currentDir[currentDir.length() - 1] != '/')
					currentDir += "/";
			} else {
                cout << "Directory does not exist." << endl;
            }
			break;

		case 13: // pwd
			cout << currentDir << endl;
			break;

		case 14: // help
			cout << help() << endl;
			break;

		case 15: // chmod
			if (commandArr[2].length() != 0){
				int perm = stoi(commandArr[2]);
				fileSystem.chmod(absolutePath(commandArr[1]), perm);
			} else {
				cout << "Invalid amount of arguments." << endl;
            }
			break;

		default:
			cout << "Unknown command: " << commandArr[0] << endl;
		}
	}

	return true;
}

int Shell::parseCommandString(const string &userCommand, string strArr[]) {
	stringstream ssin(userCommand);
	int counter = 0;
	while (ssin.good() && counter < MAXCOMMANDS) {
		ssin >> strArr[counter];
		counter++;
	}
	if (strArr[0] == "") {
		counter = 0;
	}
	return counter;
}

int Shell::findCommand(string &command) {
	int index = -1;
	for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) {
		if (command == availableCommands[i]) {
			index = i;
		}
	}
	return index;
}

string Shell::absolutePath(string path) const {
	// Fix relative path
	if (path.length() == 0 || path[0] != '/')
		path = currentDir + path;
	path = path.substr(1);

    vector<string> parts = split(path, '/');
    vector<string> temp;

    // Replace ./ and ../
    for (string part : parts) {
        if (part == "..") {
            if (!temp.empty())
                temp.pop_back();
        } else if (part != ".") {
            temp.push_back(part);
        }
    }

    path = "";
    for (size_t i=0; i<temp.size(); i++) {
        if (i > 0)
            path += "/";
        path += temp[i];
    }

	return path;
}

string Shell::help() {
	string helpStr;
	helpStr += "OSD Disk Tool .oO Help Screen Oo.\n";
	helpStr += "-----------------------------------------------------------------------------------\n";
	helpStr += "* quit:                             Quit OSD Disk Tool\n";
	helpStr += "* format;                           Formats disk\n";
	helpStr += "* ls     <path>:                    Lists contents of <path>.\n";
	helpStr += "* create <path>:                    Creates a file and stores contents in <path>\n";
	helpStr += "* cat    <path>:                    Dumps contents of <file>.\n";
	helpStr += "* save   <real-file>:               Saves disk to <real-file>\n";
	helpStr += "* read   <real-file>:               Reads <real-file> onto disk\n";
	helpStr += "* rm     <file>:                    Removes <file>\n";
	helpStr += "* copy   <source>    <destination>: Copy <source> to <destination>\n";
	helpStr += "* append <source>    <destination>: Appends contents of <source> to <destination>\n";
	helpStr += "* rename <old-file>  <new-file>:    Renames <old-file> to <new-file>\n";
	helpStr += "* mkdir  <directory>:               Creates a new directory called <directory>\n";
	helpStr += "* cd     <directory>:               Changes current working directory to <directory>\n";
	helpStr += "* pwd:                              Get current working directory\n";
    helpStr += "* chmod  <file>      <permissions>: Change permissions for <file> to <permissions>.\n";
	helpStr += "* help:                             Prints this help screen\n";
	return helpStr;
}

vector<string> Shell::split(string text, char delimiter) {
    vector<string> parts;

    while (text.find(delimiter) != string::npos) {
        size_t pos = text.find(delimiter);
        parts.push_back(text.substr(0, pos));
        text = text.substr(pos+1);
    }

    if (!text.empty())
        parts.push_back(text);

    return parts;
}
<|endoftext|>


<commit_before>//********************************************************************
//
//This program displays a list of numbers and their squares.
//
//By: JESUS HILARIO HERNANDEZ
//Last Updated: October 5th, 2016
//
//********************************************************************

#include <iostream>

using namespace std;

int main()
{

    /* Input validation when using numbers. */
    int number;

    cout << "Enter a number in the range 1-10: ";
    while (!(cin >> number) || (number < 1 || number > 10))
    {
        // Explain error
        cout << "ERROR: A number must be pressed.\n"
        << "Enter a value in the range 1-10: ";
        // Clear input stream
        cin.clear();
        // Discard previous input
        cin.ignore(1200, '\n');
    }

    cout << "You entered the number " << number << endl;

    /* Input validation when using characters */
    char choice;

    cout << "Enter Y or N: ";
    cin >> choice;

    while (!(choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N'))
    {
        cout << "ERROR: Either Y or N must be pressed.\n"
        << "Enter Y or N: ";
        // clear input stream
        cin.clear();
        // discard previous input
        cin.ignore(1200, '\n');
        // enter choice again
        cin >> choice;
    }
    cout << "You have chosen " << choice << endl;

    /* Input validation when using strings */

    string stringChoice;

    cout << "Enter \"yes\" or \"no\": ";
    cin >> stringChoice;

    while (!(stringChoice == "yes") && !(stringChoice == "no"))
    {
        cout << "ERROR: You must type either \"yes\" or \"no\".\n"
        << "Enter \"yes\" or \"no\": ";
        // clear input stream
        cin.clear();
        // discard previous input
        cin.ignore(1200, '\n');
        cin >> stringChoice;
    }

    cout << "You have enter: " << stringChoice << endl;

    return 0;
}
<commit_msg>Update input-validation-using-while-loops.cpp<commit_after>//********************************************************************
//This program displays a list of numbers and their squares.
//
//By: JESUS HILARIO HERNANDEZ
//Last Updated: December 6th, 2016
//********************************************************************
#include <iostream>
using namespace std;

int main()
{

    /* Input validation when using numbers. */
    int number;

    cout << "Enter a number in the range 1-10: ";
    while (!(cin >> number) || (number < 1 || number > 10))
    {
        // Explain error
        cout << "ERROR: A number must be pressed.\n"
        << "Enter a value in the range 1-10: ";
        // Clear input stream
        cin.clear();
        // Discard previous input
        cin.ignore(1200, '\n');
    }

    cout << "You entered the number " << number << endl;

    /* Input validation when using characters */
    char choice;

    cout << "Enter Y or N: ";
    cin >> choice;

    while (!(choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N'))
    {
        cout << "ERROR: Either Y or N must be pressed.\n"
        << "Enter Y or N: ";
        // clear input stream
        cin.clear();
        // discard previous input
        cin.ignore(1200, '\n');
        // enter choice again
        cin >> choice;
    }
    cout << "You have chosen " << choice << endl;

    /* Input validation when using strings */

    string stringChoice;

    cout << "Enter \"yes\" or \"no\": ";
    cin >> stringChoice;

    while (!(stringChoice == "yes") && !(stringChoice == "no"))
    {
        cout << "ERROR: You must type either \"yes\" or \"no\".\n"
        << "Enter \"yes\" or \"no\": ";
        // clear input stream
        cin.clear();
        // discard previous input
        cin.ignore(1200, '\n');
        // Re-enter choice again
        cin >> stringChoice;
    }

    cout << "You have enter: " << stringChoice << endl;

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: datman.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2004-06-17 16:15:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX

#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORM_HPP_
#include <com/sun/star/form/XForm.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_
#include <com/sun/star/form/XLoadable.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
// #100312# --------------------
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class Window;

//-----------------------------------------------------------------------------
namespace bib
{
    class BibView;
    // #100312# -----------
    class BibBeamer;
}

class BibToolBar;
struct BibDBDescriptor;

// #100312# ---------------------
class BibInterceptorHelper
    :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;

protected:
    ~BibInterceptorHelper( );

public:
    BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);

    void ReleaseInterceptor();

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};

typedef cppu::WeakComponentImplHelper2  <   ::com::sun::star::beans::XPropertyChangeListener
                                        ,   ::com::sun::star::form::XLoadable
                                        >   BibDataManager_Base;
class BibDataManager
            :public ::comphelper::OMutexAndBroadcastHelper
            ,public BibDataManager_Base
{
private:
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                   m_xForm;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            m_xGridModel;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >           m_xSourceProps;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer >        m_xParser;
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >         m_xFormCtrl;
        // #100312# -------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >      m_xFormDispatch;
        BibInterceptorHelper* m_pInterceptorHelper;

        ::rtl::OUString                     aActiveDataTable;
        ::rtl::OUString                     aDataSourceURL;
        ::rtl::OUString                     aQuoteChar;
        ::com::sun::star::uno::Any                      aUID;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >              xBibCursor;

        ::cppu::OInterfaceContainerHelper   m_aLoadListeners;

        ::bib::BibView*             pBibView;
        BibToolBar*                 pToolbar;

        rtl::OUString               sIdentifierMapping;
protected:

        void                        InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
        void                        SetMeAsUidListener();
        void                        RemoveMeAsUidListener();

        void                        UpdateAddressbookCursor(::rtl::OUString aSourceName);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    createGridModel( const ::rtl::OUString& rName );

        // XLoadable
        virtual void SAL_CALL load(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL unload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL reload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isLoaded(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
public:

        BibDataManager();
        ~BibDataManager();

        virtual void                SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
                                                                throw( ::com::sun::star::uno::RuntimeException );
        virtual void                SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                                                                throw( ::com::sun::star::uno::RuntimeException );

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                   createDatabaseForm( BibDBDescriptor&    aDesc);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            updateGridModel();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getDataSources();

        ::rtl::OUString             getActiveDataSource() {return aDataSourceURL;}
        void                        setActiveDataSource(const ::rtl::OUString& rURL);

        ::rtl::OUString             getActiveDataTable();
        void                        setActiveDataTable(const ::rtl::OUString& rTable);

        void                        setFilter(const ::rtl::OUString& rQuery);
        ::rtl::OUString                     getFilter();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getQueryFields();
        ::rtl::OUString                     getQueryField();
        void                        startQueryWith(const ::rtl::OUString& rQuery);

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer >&         getParser() { return m_xParser; }
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >&                    getForm()   { return m_xForm; }

        ::rtl::OUString                     getControlName(sal_Int32 nFormatKey );

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            loadControlModel(const ::rtl::OUString& rName,
                                                        sal_Bool bForceListBox = sal_False);
        void                        saveCtrModel(const ::rtl::OUString& rName,
                                                    const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel);

        sal_Bool                        moveRelative(long nMove);

        void                        CreateMappingDialog(Window* pParent);
        ::rtl::OUString             CreateDBChangeDialog(Window* pParent);

        void                        DispatchDBChangeDialog();
        sal_Bool                    HasActiveConnection() const;

        void                        SetView( ::bib::BibView* pView ) { pBibView = pView; }

        void                        SetToolbar(BibToolBar* pSet);

        const rtl::OUString&        GetIdentifierMapping();
        void                        ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
        // #100312# ----------
        void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);

        sal_Bool                    HasActiveConnection();
};

#endif
<commit_msg>INTEGRATION: CWS dba20 (1.11.90); FILE MERGED 2004/11/18 10:44:54 fs 1.11.90.1: #i37070# XSQLQueryComposer superseded by XSingleSelectQueryComposer<commit_after>/*************************************************************************
 *
 *  $RCSfile: datman.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-05 12:41:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX

#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORM_HPP_
#include <com/sun/star/form/XForm.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSINGLESELECTQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_
#include <com/sun/star/form/XLoadable.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
// #100312# --------------------
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class Window;

//-----------------------------------------------------------------------------
namespace bib
{
    class BibView;
    // #100312# -----------
    class BibBeamer;
}

class BibToolBar;
struct BibDBDescriptor;

// #100312# ---------------------
class BibInterceptorHelper
    :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;

protected:
    ~BibInterceptorHelper( );

public:
    BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);

    void ReleaseInterceptor();

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};

typedef cppu::WeakComponentImplHelper2  <   ::com::sun::star::beans::XPropertyChangeListener
                                        ,   ::com::sun::star::form::XLoadable
                                        >   BibDataManager_Base;
class BibDataManager
            :public ::comphelper::OMutexAndBroadcastHelper
            ,public BibDataManager_Base
{
private:
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                       m_xForm;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >                m_xGridModel;
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >               m_xSourceProps;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >   m_xParser;
        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >             m_xFormCtrl;
        // #100312# -------------------
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >      m_xFormDispatch;
        BibInterceptorHelper* m_pInterceptorHelper;

        ::rtl::OUString                     aActiveDataTable;
        ::rtl::OUString                     aDataSourceURL;
        ::rtl::OUString                     aQuoteChar;
        ::com::sun::star::uno::Any                      aUID;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >              xBibCursor;

        ::cppu::OInterfaceContainerHelper   m_aLoadListeners;

        ::bib::BibView*             pBibView;
        BibToolBar*                 pToolbar;

        rtl::OUString               sIdentifierMapping;
protected:

        void                        InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
        void                        SetMeAsUidListener();
        void                        RemoveMeAsUidListener();

        void                        UpdateAddressbookCursor(::rtl::OUString aSourceName);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
                                    createGridModel( const ::rtl::OUString& rName );

        // XLoadable
        virtual void SAL_CALL load(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL unload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL reload(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isLoaded(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
public:

        BibDataManager();
        ~BibDataManager();

        virtual void                SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
                                                                throw( ::com::sun::star::uno::RuntimeException );
        virtual void                SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                                                                throw( ::com::sun::star::uno::RuntimeException );

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >                   createDatabaseForm( BibDBDescriptor&    aDesc);

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            updateGridModel();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getDataSources();

        ::rtl::OUString             getActiveDataSource() {return aDataSourceURL;}
        void                        setActiveDataSource(const ::rtl::OUString& rURL);

        ::rtl::OUString             getActiveDataTable();
        void                        setActiveDataTable(const ::rtl::OUString& rTable);

        void                        setFilter(const ::rtl::OUString& rQuery);
        ::rtl::OUString                     getFilter();

        ::com::sun::star::uno::Sequence< ::rtl::OUString>           getQueryFields();
        ::rtl::OUString                     getQueryField();
        void                        startQueryWith(const ::rtl::OUString& rQuery);

        const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >&    getParser() { return m_xParser; }
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >&                        getForm()   { return m_xForm; }

        ::rtl::OUString                     getControlName(sal_Int32 nFormatKey );

        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >            loadControlModel(const ::rtl::OUString& rName,
                                                        sal_Bool bForceListBox = sal_False);
        void                        saveCtrModel(const ::rtl::OUString& rName,
                                                    const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel);

        sal_Bool                        moveRelative(long nMove);

        void                        CreateMappingDialog(Window* pParent);
        ::rtl::OUString             CreateDBChangeDialog(Window* pParent);

        void                        DispatchDBChangeDialog();
        sal_Bool                    HasActiveConnection() const;

        void                        SetView( ::bib::BibView* pView ) { pBibView = pView; }

        void                        SetToolbar(BibToolBar* pSet);

        const rtl::OUString&        GetIdentifierMapping();
        void                        ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}

        ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
        // #100312# ----------
        void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);

        sal_Bool                    HasActiveConnection();
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slideview.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-07-20 06:24:59 $
 *
 *  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
 *
 ************************************************************************/

#ifndef INCLUDED_SLIDESHOW_SLIDEVIEW_HXX
#define INCLUDED_SLIDESHOW_SLIDEVIEW_HXX

#include "unoview.hxx"

/* Definition of SlideView factory method */
namespace slideshow
{
    namespace internal
    {
        class EventQueue;
        class EventMultiplexer;

        /** Factory for SlideView

            @param xView
            UNO slide view this object should encapsulate

            @param rEventQueue
            Global event queue, to be used for notification
            messages.

            @param rViewChangeFunc
            Functor to call, when the UNO view signals a repaint.
        */
        UnoViewSharedPtr createSlideView(
            ::com::sun::star::uno::Reference<
                ::com::sun::star::presentation::XSlideShowView> const& xView,
            EventQueue&                                                rEventQueue,
            EventMultiplexer&                                          rEventMultiplexer );
    }
}

#endif /* INCLUDED_SLIDESHOW_SLIDEVIEW_HXX */

<commit_msg>INTEGRATION: CWS changefileheader (1.4.46); FILE MERGED 2008/03/31 14:00:31 rt 1.4.46.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: slideview.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_SLIDESHOW_SLIDEVIEW_HXX
#define INCLUDED_SLIDESHOW_SLIDEVIEW_HXX

#include "unoview.hxx"

/* Definition of SlideView factory method */
namespace slideshow
{
    namespace internal
    {
        class EventQueue;
        class EventMultiplexer;

        /** Factory for SlideView

            @param xView
            UNO slide view this object should encapsulate

            @param rEventQueue
            Global event queue, to be used for notification
            messages.

            @param rViewChangeFunc
            Functor to call, when the UNO view signals a repaint.
        */
        UnoViewSharedPtr createSlideView(
            ::com::sun::star::uno::Reference<
                ::com::sun::star::presentation::XSlideShowView> const& xView,
            EventQueue&                                                rEventQueue,
            EventMultiplexer&                                          rEventMultiplexer );
    }
}

#endif /* INCLUDED_SLIDESHOW_SLIDEVIEW_HXX */

<|endoftext|>


<commit_before>#include "Tiler.h"
#include "cinder/gl/gl.h"
#include "cinder/app/App.h"
#include "cinder/Rand.h"

#include <algorithm>
#include <sstream>

using namespace reza::tiler;
using namespace cinder;
using namespace glm;
using namespace std;

Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha )
: mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha )
{
    mWindowWidth = app::toPixels( mWindowRef->getWidth() );
    mWindowHeight = app::toPixels( mWindowRef->getHeight() );

    mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth );
    mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight );

    mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth );
    mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight );

    mCurrentTile = -1;

    if( mAlpha ) {
        auto fmt = gl::Fbo::Format().samples( gl::Fbo::getMaxSamples() );
        mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, fmt );
        mFboRef->bindFramebuffer();
        gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) );
        mFboRef->unbindFramebuffer();
    }
}

bool Tiler::nextTile()
{
    if( mCurrentTile == mNumTilesX * mNumTilesY ) {
        if( mAlpha ) {
            mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        } else {
            mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        }
        mCurrentTile = -1;
        return false;
    }

    if( mCurrentTile == -1 ) {
        mCurrentTile = 0;
        if( mSurfaceRef && mSurfaceRef->getSize() != ivec2( mImageWidth, mImageHeight ) ) {
            mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha );
        }
        else {
            mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha );
        }
    }
    else {
        if( mAlpha ) {
            mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        } else {
            mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        }
    }

    int tileX = mCurrentTile % mNumTilesX;
    int tileY = mCurrentTile / mNumTilesX;

    int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth;
    int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight;

    mCurrentArea.x1 = tileX * mTileWidth;
    mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth;
    mCurrentArea.y1 = tileY * mTileHeight;
    mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight;

    update();
    mCurrentTile++;
    return true;
}

void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane )
{
    CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane );
    setMatrices( cam );
}

void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight )
{
    ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f );
}

void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane )
{
    mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) );
    mCurrentFrustumNear = nearPlane;
    mCurrentFrustumFar = farPlane;
    mCurrentFrustumPersp = true;
}

void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane )
{
    mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) );
    mCurrentFrustumNear = nearPlane;
    mCurrentFrustumFar = farPlane;
    mCurrentFrustumPersp = false;
}

bool Tiler::getAlpha()
{
    return mAlpha;
}

ci::Surface& Tiler::getSurface()
{
    while ( nextTile() ) { }
    return *mSurfaceRef;
}

void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn )
{
    mDrawBgFn = drawBgFn;
}

void Tiler::setDrawFn( const std::function<void()> &drawFn )
{
    mDrawFn = drawFn;
}

void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn )
{
    mDrawHudFn = drawHudFn;
}

void Tiler::setMatrices( const CameraPersp &camera )
{
    mCamera = camera;
    float left, top, right, bottom, nearPlane, farPlane;
    camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane );

    if( camera.isPersp() ) {
        frustum( left, right, bottom, top, nearPlane, farPlane );
    }
    else {
        ortho( left, right, bottom, top, nearPlane, farPlane );
    }
}

void Tiler::update()
{
    if( mAlpha ) {
        mFboRef->bindFramebuffer();
        gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) );
    }

    float sx = (float) mCurrentArea.x1 / (float) mImageWidth;
    float sy = (float) mCurrentArea.y1 / (float) mImageHeight;
    float ex = (float) mCurrentArea.x2 / (float) mImageWidth;
    float ey = (float) mCurrentArea.y2 / (float) mImageHeight;

    vec2 ul = vec2(sx, sy);
    vec2 ur = vec2(ex, sy);
    vec2 lr = vec2(ex, ey);
    vec2 ll = vec2(sx, ey);

    float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth();
    float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth();
    float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight();
    float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight();

    if( mDrawBgFn ) {
        gl::pushMatrices();
        gl::pushViewport();
        gl::viewport( mCurrentArea.getSize() );
        mDrawBgFn( ul, ur, lr, ll );
        gl::popViewport();
        gl::popMatrices();
    }

    CameraPersp cam = mCamera;
    gl::pushMatrices();

    gl::pushViewport();
    gl::viewport( mCurrentArea.getSize() );

    gl::pushProjectionMatrix();
    if( mCurrentFrustumPersp ) {
        gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) );
    } else {
        gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) );
    }

    gl::pushViewMatrix();
    gl::setViewMatrix( cam.getViewMatrix() );

    if( mDrawFn ) {
        mDrawFn();
    }

    gl::popViewMatrix();
    gl::popProjectionMatrix();
    gl::popViewport();
    gl::popMatrices();

    if( mDrawHudFn ) {
        mDrawHudFn( ul, ur, lr, ll );
    }

    if( mAlpha ) {
        mFboRef->unbindFramebuffer();
    }
}<commit_msg>flipped y texcoord when drawing background<commit_after>#include "Tiler.h"
#include "cinder/gl/gl.h"
#include "cinder/app/App.h"
#include "cinder/Rand.h"

#include <algorithm>
#include <sstream>

using namespace reza::tiler;
using namespace cinder;
using namespace glm;
using namespace std;

Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha )
: mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha )
{
    mWindowWidth = app::toPixels( mWindowRef->getWidth() );
    mWindowHeight = app::toPixels( mWindowRef->getHeight() );

    mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth );
    mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight );

    mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth );
    mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight );

    mCurrentTile = -1;

    if( mAlpha ) {
        auto fmt = gl::Fbo::Format().samples( gl::Fbo::getMaxSamples() );
        mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, fmt );
        mFboRef->bindFramebuffer();
        gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) );
        mFboRef->unbindFramebuffer();
    }
}

bool Tiler::nextTile()
{
    if( mCurrentTile == mNumTilesX * mNumTilesY ) {
        if( mAlpha ) {
            mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        } else {
            mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        }
        mCurrentTile = -1;
        return false;
    }

    if( mCurrentTile == -1 ) {
        mCurrentTile = 0;
        if( mSurfaceRef && mSurfaceRef->getSize() != ivec2( mImageWidth, mImageHeight ) ) {
            mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha );
        }
        else {
            mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha );
        }
    }
    else {
        if( mAlpha ) {
            mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        } else {
            mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() );
        }
    }

    int tileX = mCurrentTile % mNumTilesX;
    int tileY = mCurrentTile / mNumTilesX;

    int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth;
    int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight;

    mCurrentArea.x1 = tileX * mTileWidth;
    mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth;
    mCurrentArea.y1 = tileY * mTileHeight;
    mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight;

    update();
    mCurrentTile++;
    return true;
}

void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane )
{
    CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane );
    setMatrices( cam );
}

void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight )
{
    ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f );
}

void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane )
{
    mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) );
    mCurrentFrustumNear = nearPlane;
    mCurrentFrustumFar = farPlane;
    mCurrentFrustumPersp = true;
}

void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane )
{
    mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) );
    mCurrentFrustumNear = nearPlane;
    mCurrentFrustumFar = farPlane;
    mCurrentFrustumPersp = false;
}

bool Tiler::getAlpha()
{
    return mAlpha;
}

ci::Surface& Tiler::getSurface()
{
    while ( nextTile() ) { }
    return *mSurfaceRef;
}

void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn )
{
    mDrawBgFn = drawBgFn;
}

void Tiler::setDrawFn( const std::function<void()> &drawFn )
{
    mDrawFn = drawFn;
}

void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn )
{
    mDrawHudFn = drawHudFn;
}

void Tiler::setMatrices( const CameraPersp &camera )
{
    mCamera = camera;
    float left, top, right, bottom, nearPlane, farPlane;
    camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane );

    if( camera.isPersp() ) {
        frustum( left, right, bottom, top, nearPlane, farPlane );
    }
    else {
        ortho( left, right, bottom, top, nearPlane, farPlane );
    }
}

void Tiler::update()
{
    if( mAlpha ) {
        mFboRef->bindFramebuffer();
        gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) );
    }

    float sx = (float) mCurrentArea.x1 / (float) mImageWidth;
    float sy = 1.0 - (float) mCurrentArea.y1 / (float) mImageHeight;
    float ex = (float) mCurrentArea.x2 / (float) mImageWidth;
    float ey = 1.0 - (float) mCurrentArea.y2 / (float) mImageHeight;

    vec2 ul = vec2( sx, sy );
    vec2 ur = vec2( ex, sy );
    vec2 lr = vec2( ex, ey );
    vec2 ll = vec2( sx, ey );

    if( mDrawBgFn ) {
        gl::pushMatrices();
        gl::pushViewport();
        gl::viewport( mCurrentArea.getSize() );
        mDrawBgFn( ul, ur, lr, ll );
        gl::popViewport();
        gl::popMatrices();
    }

    float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth();
    float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth();
    float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight();
    float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight();

    CameraPersp cam = mCamera;
    gl::pushMatrices();

    gl::pushViewport();
    gl::viewport( mCurrentArea.getSize() );

    gl::pushProjectionMatrix();
    if( mCurrentFrustumPersp ) {
        gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) );
    } else {
        gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) );
    }

    gl::pushViewMatrix();
    gl::setViewMatrix( cam.getViewMatrix() );

    if( mDrawFn ) {
        mDrawFn();
    }

    gl::popViewMatrix();
    gl::popProjectionMatrix();
    gl::popViewport();
    gl::popMatrices();

    if( mDrawHudFn ) {
        mDrawHudFn( ul, ur, lr, ll );
    }

    if( mAlpha ) {
        mFboRef->unbindFramebuffer();
    }
}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#include	"../StroikaPreComp.h"

#include	"Event.h"

using	namespace	Stroika::Foundation;
using	namespace	Stroika::Foundation::Execution;

/*
 ********************************************************************************
 ************************************** Event ***********************************
 ********************************************************************************
 */
#if		qTrack_ThreadUtils_HandleCounts
uint32_t	Event::sCurAllocatedHandleCount		=	0;
#endif
void	Event::Wait (Time::DurationSecondsType timeout)
{
	CheckForThreadAborting ();
	#if			qPlatform_Windows
		AssertNotNull (fEventHandle);
		// must be careful about rounding errors in int->DurationSecondsType->int
	Again:
		DWORD	result	=	::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true);
		switch (result) {
			case	WAIT_TIMEOUT:	DoThrow (WaitTimedOutException ());
			case	WAIT_ABANDONED:	DoThrow (WaitAbandonedException ());
			case	WAIT_IO_COMPLETION:	CheckForThreadAborting (); goto Again;	// roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting
		}
		Verify (result == WAIT_OBJECT_0);
	#elif		qUseThreads_StdCPlusPlus
		std::unique_lock<std::mutex> lock (fMutex_);
		Time::DurationSecondsType	until	=	Time::GetTickCount () + timeout;
		Assert (until >= timeout);	// so no funny overflow issues...
		while (not fTriggered_) {
			CheckForThreadAborting ();
			Time::DurationSecondsType	remaining	=	until - Time::GetTickCount ();
			if (remaining < 0) {
				DoThrow (WaitTimedOutException ());
			}
//tmphack til I figure out this lock/waiting stuff -
remaining = min (remaining, 5);
			if (fConditionVariable_.wait_for (lock, std::chrono::duration<double> (remaining)) == std::cv_status::timeout) {
//				DoThrow (WaitTimedOutException ());
			}
		}
		fTriggered_ = false	;	// autoreset
	#else
		AssertNotImplemented ();
	#endif
}
<commit_msg>A few hacks to the POSIX Event::Wait () code to try and debug that stuff on linux<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#include	"../StroikaPreComp.h"

#include	"Event.h"

using	namespace	Stroika::Foundation;
using	namespace	Stroika::Foundation::Execution;

/*
 ********************************************************************************
 ************************************** Event ***********************************
 ********************************************************************************
 */
#if		qTrack_ThreadUtils_HandleCounts
uint32_t	Event::sCurAllocatedHandleCount		=	0;
#endif
void	Event::Wait (Time::DurationSecondsType timeout)
{
	CheckForThreadAborting ();
	#if			qPlatform_Windows
		AssertNotNull (fEventHandle);
		// must be careful about rounding errors in int->DurationSecondsType->int
	Again:
		DWORD	result	=	::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true);
		switch (result) {
			case	WAIT_TIMEOUT:	DoThrow (WaitTimedOutException ());
			case	WAIT_ABANDONED:	DoThrow (WaitAbandonedException ());
			case	WAIT_IO_COMPLETION:	CheckForThreadAborting (); goto Again;	// roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting
		}
		Verify (result == WAIT_OBJECT_0);
	#elif		qUseThreads_StdCPlusPlus
		std::unique_lock<std::mutex> lock (fMutex_);
		Time::DurationSecondsType	until	=	Time::GetTickCount () + timeout;
		Assert (until >= timeout);	// so no funny overflow issues...
		while (not fTriggered_) {
			CheckForThreadAborting ();
			Time::DurationSecondsType	remaining	=	until - Time::GetTickCount ();
			if (remaining < 0) {
				DoThrow (WaitTimedOutException ());
			}
//tmphack til I figure out this lock/waiting stuff -
if (remaining > 5) {
	remaining = 5;
}
			if (fConditionVariable_.wait_for (lock, std::chrono::duration<double> (remaining)) == std::cv_status::timeout) {
//				DoThrow (WaitTimedOutException ());
			}
		}
		fTriggered_ = false	;	// autoreset
	#else
		AssertNotImplemented ();
	#endif
}
<|endoftext|>


<commit_before>#include <QApplication>
#include "qkeymapper.h"

#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif

int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication a(argc, argv);
    QApplication::setStyle(QStyleFactory::create("Fusion"));

#ifdef ADJUST_PRIVILEGES
//    BOOL adjustresult = QKeyMapper::AdjustPrivileges();
//    qDebug() << "AdjustPrivileges Result:" << adjustresult;

    BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
    qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif

    QKeyMapper w;

    // Remove "?" Button from QDialog
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowMinimizeButtonHint;
    flags |= Qt::WindowCloseButtonHint;
    w.setWindowFlags(flags);

    w.show();

    return a.exec();
}
<commit_msg>Add debug timestamp for log output.<commit_after>#include <QApplication>
#include "qkeymapper.h"

#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif

int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication a(argc, argv);
    QApplication::setStyle(QStyleFactory::create("Fusion"));

#ifdef DEBUG_LOGOUT_ON
    qSetMessagePattern("%{time [hh:mm:ss.zzz]} Message:%{message}");
#endif

#ifdef ADJUST_PRIVILEGES
//    BOOL adjustresult = QKeyMapper::AdjustPrivileges();
//    qDebug() << "AdjustPrivileges Result:" << adjustresult;

    BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
    qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif

    QKeyMapper w;

    // Remove "?" Button from QDialog
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowMinimizeButtonHint;
    flags |= Qt::WindowCloseButtonHint;
    w.setWindowFlags(flags);

    w.show();

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


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "ADPiecewiseLinearInterpolationMaterial.h"

#include "MooseVariableFE.h"

registerADMooseObject("MooseApp", ADPiecewiseLinearInterpolationMaterial);

defineADValidParams(
    ADPiecewiseLinearInterpolationMaterial,
    ADMaterial,
    params.addClassDescription(
        "Compute a property using a piecewise linear interpolation to define "
        "its dependence on a variable");
    params.addRequiredParam<std::string>("property",
                                         "The name of the property this material will compute");
    params.addRequiredCoupledVar(
        "variable",
        "The name of the variable whose value is used as the abscissa in the interpolation");
    params.addParam<std::vector<Real>>("x", "The abscissa values");
    params.addParam<std::vector<Real>>("y", "The ordinate values");
    params.addParam<std::vector<Real>>("xy_data",
                                       "All function data, supplied in abscissa, ordinate pairs");
    params.addParam<Real>("scale_factor",
                          1.0,
                          "Scale factor to be applied to the ordinate values"););

template <ComputeStage compute_stage>
ADPiecewiseLinearInterpolationMaterial<compute_stage>::ADPiecewiseLinearInterpolationMaterial(
    const InputParameters & parameters)
  : ADMaterial<compute_stage>(parameters),
    _prop_name(adGetParam<std::string>("property")),
    _coupled_var(adCoupledValue("variable")),
    _scale_factor(adGetParam<Real>("scale_factor")),
    _property(adDeclareADProperty<Real>(_prop_name))
{
  std::vector<Real> x;
  std::vector<Real> y;

  if ((parameters.isParamValid("x")) || (parameters.isParamValid("y")))
  {
    if (!((parameters.isParamValid("x")) && (parameters.isParamValid("y"))))
      mooseError("In ", _name, ": Both 'x' and 'y' must be specified if either one is specified.");

    if (parameters.isParamValid("xy_data"))
      mooseError("In ", _name, ": Cannot specify 'x', 'y', and 'xy_data' together.");

    x = adGetParam<std::vector<Real>>("x");
    y = adGetParam<std::vector<Real>>("y");
  }
  else if (parameters.isParamValid("xy_data"))
  {
    std::vector<Real> xy = adGetParam<std::vector<Real>>("xy_data");
    unsigned int xy_size = xy.size();
    if (xy_size % 2 != 0)
      mooseError("In ", _name, ": Length of data provided in 'xy_data' must be a multiple of 2.");

    unsigned int x_size = xy_size / 2;
    x.reserve(x_size);
    y.reserve(x_size);
    for (unsigned int i = 0; i < xy_size / 2; ++i)
    {
      x.push_back(xy[i * 2]);
      y.push_back(xy[i * 2 + 1]);
    }
  }

  try
  {
    _linear_interp = libmesh_make_unique<LinearInterpolation>(x, y);
  }
  catch (std::domain_error & e)
  {
    mooseError("In ", _name, ": ", e.what());
  }
}

template <ComputeStage compute_stage>
void
ADPiecewiseLinearInterpolationMaterial<compute_stage>::computeQpProperties()
{
  _property[_qp] = _scale_factor * _linear_interp->sampleDerivative(_coupled_var[_qp].value()) *
                   _coupled_var[_qp];
}

template <>
void
ADPiecewiseLinearInterpolationMaterial<RESIDUAL>::computeQpProperties()
{
  Moose::out << "res: " << _coupled_var[_qp] << std::endl;
  _property[_qp] = _scale_factor * _linear_interp->sample(_coupled_var[_qp]);
  Moose::out << "res prop: " << _property[_qp] << std::endl;
}
<commit_msg>Fix up calculation of material property value and derivatives<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "ADPiecewiseLinearInterpolationMaterial.h"

#include "MooseVariableFE.h"

registerADMooseObject("MooseApp", ADPiecewiseLinearInterpolationMaterial);

defineADValidParams(
    ADPiecewiseLinearInterpolationMaterial,
    ADMaterial,
    params.addClassDescription(
        "Compute a property using a piecewise linear interpolation to define "
        "its dependence on a variable");
    params.addRequiredParam<std::string>("property",
                                         "The name of the property this material will compute");
    params.addRequiredCoupledVar(
        "variable",
        "The name of the variable whose value is used as the abscissa in the interpolation");
    params.addParam<std::vector<Real>>("x", "The abscissa values");
    params.addParam<std::vector<Real>>("y", "The ordinate values");
    params.addParam<std::vector<Real>>("xy_data",
                                       "All function data, supplied in abscissa, ordinate pairs");
    params.addParam<Real>("scale_factor",
                          1.0,
                          "Scale factor to be applied to the ordinate values"););

template <ComputeStage compute_stage>
ADPiecewiseLinearInterpolationMaterial<compute_stage>::ADPiecewiseLinearInterpolationMaterial(
    const InputParameters & parameters)
  : ADMaterial<compute_stage>(parameters),
    _prop_name(adGetParam<std::string>("property")),
    _coupled_var(adCoupledValue("variable")),
    _scale_factor(adGetParam<Real>("scale_factor")),
    _property(adDeclareADProperty<Real>(_prop_name))
{
  std::vector<Real> x;
  std::vector<Real> y;

  if ((parameters.isParamValid("x")) || (parameters.isParamValid("y")))
  {
    if (!((parameters.isParamValid("x")) && (parameters.isParamValid("y"))))
      mooseError("In ", _name, ": Both 'x' and 'y' must be specified if either one is specified.");

    if (parameters.isParamValid("xy_data"))
      mooseError("In ", _name, ": Cannot specify 'x', 'y', and 'xy_data' together.");

    x = adGetParam<std::vector<Real>>("x");
    y = adGetParam<std::vector<Real>>("y");
  }
  else if (parameters.isParamValid("xy_data"))
  {
    std::vector<Real> xy = adGetParam<std::vector<Real>>("xy_data");
    unsigned int xy_size = xy.size();
    if (xy_size % 2 != 0)
      mooseError("In ", _name, ": Length of data provided in 'xy_data' must be a multiple of 2.");

    unsigned int x_size = xy_size / 2;
    x.reserve(x_size);
    y.reserve(x_size);
    for (unsigned int i = 0; i < xy_size / 2; ++i)
    {
      x.push_back(xy[i * 2]);
      y.push_back(xy[i * 2 + 1]);
    }
  }

  try
  {
    _linear_interp = libmesh_make_unique<LinearInterpolation>(x, y);
  }
  catch (std::domain_error & e)
  {
    mooseError("In ", _name, ": ", e.what());
  }
}

template <ComputeStage compute_stage>
void
ADPiecewiseLinearInterpolationMaterial<compute_stage>::computeQpProperties()
{
  _property[_qp].value() = _scale_factor * _linear_interp->sample(_coupled_var[_qp].value());
  _property[_qp].derivatives() = _scale_factor *
                                 _linear_interp->sampleDerivative(_coupled_var[_qp].value()) *
                                 _coupled_var[_qp].derivatives();
}

template <>
void
ADPiecewiseLinearInterpolationMaterial<RESIDUAL>::computeQpProperties()
{
  _property[_qp] = _scale_factor * _linear_interp->sample(_coupled_var[_qp]);
}
<|endoftext|>