<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-

 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <fnmatch.h>
#include "dnf-reldep.h"
#include "dnf-sack-private.hpp"
#include "hy-subject.h"
#include "hy-subject-private.hpp"
#include "hy-module-form.h"
#include "hy-iutil-private.hpp"
#include "hy-nevra.hpp"
#include "hy-module-form-private.hpp"
#include "hy-types.h"
#include "hy-query-private.hpp"
#include "hy-selector.h"
#include "hy-util-private.hpp"
#include "sack/packageset.hpp"

// most specific to least
const HyForm HY_FORMS_MOST_SPEC[] = {
    HY_FORM_NEVRA, HY_FORM_NA, HY_FORM_NAME, HY_FORM_NEVR, HY_FORM_NEV, _HY_FORM_STOP_ };

const HyModuleFormEnum HY_MODULE_FORMS_MOST_SPEC[] = {
        HY_MODULE_FORM_NSVCAP,
        HY_MODULE_FORM_NSVCA,
        HY_MODULE_FORM_NSVAP,
        HY_MODULE_FORM_NSVA,
        HY_MODULE_FORM_NSAP,
        HY_MODULE_FORM_NSA,
        HY_MODULE_FORM_NSVCP,
        HY_MODULE_FORM_NSVP,
        HY_MODULE_FORM_NSVC,
        HY_MODULE_FORM_NSV,
        HY_MODULE_FORM_NSP,
        HY_MODULE_FORM_NS,
        HY_MODULE_FORM_NAP,
        HY_MODULE_FORM_NA,
        HY_MODULE_FORM_NP,
        HY_MODULE_FORM_N,
        _HY_MODULE_FORM_STOP_};

HySubject
hy_subject_create(const char * pattern)
{
    return g_strdup(pattern);
}

void
hy_subject_free(HySubject subject)
{
    g_free(subject);
}

void
hy_possibilities_free(HyPossibilities iter)
{
    g_free(iter->subject);
    g_free(iter->forms);
    g_free(iter->module_forms);
    g_free(iter);
}

static HyForm *
forms_dup(const HyForm *forms)
{
    if (forms == NULL)
        return NULL;
    HyForm *res = NULL;
    const int BLOCK_SIZE = 6;
    HyForm form;
    int i = 0;
    do {
        res = static_cast<HyForm *>(solv_extend(res, i, 1, sizeof(HyForm), BLOCK_SIZE));
        form = forms[i];
        res[i++] = form;
    } while (form != _HY_FORM_STOP_);
    return res;
}

static HyModuleFormEnum *
module_forms_dup(const HyModuleFormEnum *forms)
{
    if (forms == NULL)
        return NULL;
    HyModuleFormEnum *res = NULL;
    const int BLOCK_SIZE = 17;
    HyModuleFormEnum form;
    int i = 0;
    do {
        res = static_cast<HyModuleFormEnum *>(solv_extend(res, i, 1, sizeof(HyModuleFormEnum), BLOCK_SIZE));
        form = forms[i];
        res[i++] = form;
    } while (form != _HY_MODULE_FORM_STOP_);
    return res;
}

static HyPossibilities
possibilities_create(HySubject subject, const HyForm *forms, const HyModuleFormEnum *module_forms,
                     enum poss_type type)
{
    HyPossibilities poss = static_cast<HyPossibilities>(g_malloc0(sizeof(*poss)));
    poss->subject = hy_subject_create(subject);
    poss->forms = forms_dup(forms);
    poss->module_forms = module_forms_dup(module_forms);
    poss->type = type;
    if (forms == NULL && module_forms == NULL)
        poss->current = -1;
    else
        poss->current = 0;
    return poss;
}

HyPossibilities
hy_subject_nevra_possibilities(HySubject subject, HyForm *forms)
{
    const HyForm *default_forms = forms == NULL ? HY_FORMS_MOST_SPEC : forms;
    return possibilities_create(subject, default_forms, NULL, TYPE_NEVRA);
}

HyPossibilities
hy_subject_module_form_possibilities(HySubject subject, HyModuleFormEnum *forms)
{
    const HyModuleFormEnum *default_forms = forms == NULL ? HY_MODULE_FORMS_MOST_SPEC : forms;
    return possibilities_create(subject, NULL, default_forms, TYPE_MODULE_FORM);
}

int
hy_possibilities_next_nevra(HyPossibilities iter, HyNevra *out_nevra)
{
    if (iter->type != TYPE_NEVRA || iter->current == -1)
        return -1;
    HyForm form = iter->forms[iter->current];
    Nevra nevra;
    while (form != _HY_FORM_STOP_) {
        iter->current++;
        if (hy_nevra_possibility(iter->subject, form, &nevra) == 0) {
            *out_nevra = new Nevra(std::move(nevra));
            return 0;
        }
        form = iter->forms[iter->current];
        nevra.clear();
    }
    *out_nevra = nullptr;
    return -1;
}

int
hy_possibilities_next_module_form(HyPossibilities iter, HyModuleForm *out_module_form)
{
    if (iter->type != TYPE_MODULE_FORM || iter->current == -1)
        return -1;
    HyModuleFormEnum form = iter->module_forms[iter->current];
    while (form != _HY_MODULE_FORM_STOP_) {
        iter->current++;
        *out_module_form = hy_module_form_create();
        if (module_form_possibility(iter->subject, form, *out_module_form) == 0) {
            return 0;
        }
        form = iter->module_forms[iter->current];
        g_clear_pointer(out_module_form, hy_module_form_free);
    }
    return -1;
}

/* Given a subject, attempt to create a query choose the first one, and update
 * the query to try to match it.
 *
 * This code is based on rpm-software-management/dnf/subject.py:get_best_query() at git
 * revision: 1d83fdc0280ca4202281ef489afe600e2f51a32a
 */
HyQuery
hy_subject_get_best_solution(HySubject subject, DnfSack *sack, HyForm *forms, HyNevra *nevra,
                             gboolean icase, gboolean with_nevra, gboolean with_provides,
                             gboolean with_filenames)
{
    int ret = 0;
    HyQuery query = NULL;

    if (with_nevra) {
        HyPossibilities iter = hy_subject_nevra_possibilities(subject, forms);
        while (ret != -1) {
            ret = hy_possibilities_next_nevra(iter, nevra);
            if (ret != -1) {
                query = hy_query_from_nevra(*nevra, sack, icase);
                if (!hy_query_is_empty(query)) {
                    hy_possibilities_free(iter);
                    return query;
                }
                hy_query_free(query);
            }
        }
        hy_possibilities_free(iter);
        delete *nevra;
        *nevra = nullptr;
        query = hy_query_create(sack);
        hy_query_filter(query, HY_PKG_NEVRA, HY_GLOB, subject);
        if (!hy_query_is_empty(query))
            return query;
        hy_query_free(query);
    }
    if (with_provides) {
        query = hy_query_create(sack);
        hy_query_filter(query, HY_PKG_PROVIDES, HY_GLOB, subject);
        if (!hy_query_is_empty(query))
            return query;
        hy_query_free(query);
    }

    if (with_filenames && hy_is_file_pattern(subject)) {
        query = hy_query_create(sack);
        hy_query_filter(query, HY_PKG_FILE, HY_GLOB, subject);
        return query;
    }

    query = hy_query_create(sack);
    hy_query_filter_empty(query);
    return query;
}

HySelector
hy_subject_get_best_sltr(HySubject subject, DnfSack *sack, HyForm *forms, bool obsoletes,
                         const char *reponame)
{
    HyNevra nevra{nullptr};
    HyQuery query = hy_subject_get_best_solution(subject, sack, forms, &nevra, FALSE, TRUE, TRUE,
                                                 TRUE);
    if (!hy_query_is_empty(query)) {
        hy_query_filter(query, HY_PKG_ARCH, HY_NEQ, "src");
        if (obsoletes && nevra && nevra->hasJustName()) {
            DnfPackageSet *pset;
            pset = hy_query_run_set(query);
            HyQuery query_obsoletes = hy_query_clone(query);
            hy_query_filter_package_in(query_obsoletes, HY_PKG_OBSOLETES, HY_EQ, pset);
            delete pset;
            hy_query_union(query, query_obsoletes);
            hy_query_free(query_obsoletes);
        }
        if (reponame != NULL) {
            HyQuery installed_query = hy_query_clone(query);
            hy_query_filter(installed_query, HY_PKG_REPONAME, HY_EQ, HY_SYSTEM_REPO_NAME);
            hy_query_filter(query, HY_PKG_REPONAME, HY_EQ, reponame);
            hy_query_union(query, installed_query);
            hy_query_free(installed_query);
        }
    }
    delete nevra;
    HySelector selector = hy_query_to_selector(query);
    hy_query_free(query);
    return selector;
}

/* Given a subject, attempt to create a "selector".
 *
 */
HySelector
hy_subject_get_best_selector(HySubject subject, DnfSack *sack)
{
    return hy_subject_get_best_sltr(subject, sack, NULL, FALSE, NULL);
}

#define MATCH_EMPTY(i) (matches[i].rm_so >= matches[i].rm_eo)

static bool
copy_str_from_subexpr(std::string & target, const char* source,
    regmatch_t* matches, int i)
{
    int subexpr_len = matches[i].rm_eo - matches[i].rm_so;
    if (subexpr_len == 0)
        return false;
    target = std::string(source + matches[i].rm_so, subexpr_len);
    return true;
}

int
hy_nevra_possibility(const char *nevra_str, int form, HyNevra nevra)
{
    enum { NAME = 1, EPOCH = 3, VERSION = 4, RELEASE = 5, ARCH = 6 };
    regex_t reg;
    char *epoch = nullptr;

    regmatch_t matches[10];

    regcomp(&reg, nevra_form_regex[form - 1], REG_EXTENDED);
    int ret = regexec(&reg, nevra_str, 10, matches, 0);
    regfree(&reg);
    if (ret != 0)
    return -1;
    if (!MATCH_EMPTY(EPOCH)) {
        copy_str_from_subexpr(&epoch, nevra_str, matches, EPOCH);
        nevra->setEpoch(atoi(epoch));
        free(epoch);
    }
    std::string tmp;
    if (!copy_str_from_subexpr(tmp, nevra_str, matches, NAME))
        return -1;
    nevra->setName(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, VERSION))
        nevra->setVersion(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, RELEASE))
        nevra->setRelease(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, ARCH))
        nevra->setArch(tmp);
    return 0;
}

#undef MATCH_EMPTY
<commit_msg>hy_subject_get_best_solution() can use nevra glob filter only if forms aren't specified<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-

 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <stdlib.h>
#include <fnmatch.h>
#include "dnf-reldep.h"
#include "dnf-sack-private.hpp"
#include "hy-subject.h"
#include "hy-subject-private.hpp"
#include "hy-module-form.h"
#include "hy-iutil-private.hpp"
#include "hy-nevra.hpp"
#include "hy-module-form-private.hpp"
#include "hy-types.h"
#include "hy-query-private.hpp"
#include "hy-selector.h"
#include "hy-util-private.hpp"
#include "sack/packageset.hpp"

// most specific to least
const HyForm HY_FORMS_MOST_SPEC[] = {
    HY_FORM_NEVRA, HY_FORM_NA, HY_FORM_NAME, HY_FORM_NEVR, HY_FORM_NEV, _HY_FORM_STOP_ };

const HyModuleFormEnum HY_MODULE_FORMS_MOST_SPEC[] = {
        HY_MODULE_FORM_NSVCAP,
        HY_MODULE_FORM_NSVCA,
        HY_MODULE_FORM_NSVAP,
        HY_MODULE_FORM_NSVA,
        HY_MODULE_FORM_NSAP,
        HY_MODULE_FORM_NSA,
        HY_MODULE_FORM_NSVCP,
        HY_MODULE_FORM_NSVP,
        HY_MODULE_FORM_NSVC,
        HY_MODULE_FORM_NSV,
        HY_MODULE_FORM_NSP,
        HY_MODULE_FORM_NS,
        HY_MODULE_FORM_NAP,
        HY_MODULE_FORM_NA,
        HY_MODULE_FORM_NP,
        HY_MODULE_FORM_N,
        _HY_MODULE_FORM_STOP_};

HySubject
hy_subject_create(const char * pattern)
{
    return g_strdup(pattern);
}

void
hy_subject_free(HySubject subject)
{
    g_free(subject);
}

void
hy_possibilities_free(HyPossibilities iter)
{
    g_free(iter->subject);
    g_free(iter->forms);
    g_free(iter->module_forms);
    g_free(iter);
}

static HyForm *
forms_dup(const HyForm *forms)
{
    if (forms == NULL)
        return NULL;
    HyForm *res = NULL;
    const int BLOCK_SIZE = 6;
    HyForm form;
    int i = 0;
    do {
        res = static_cast<HyForm *>(solv_extend(res, i, 1, sizeof(HyForm), BLOCK_SIZE));
        form = forms[i];
        res[i++] = form;
    } while (form != _HY_FORM_STOP_);
    return res;
}

static HyModuleFormEnum *
module_forms_dup(const HyModuleFormEnum *forms)
{
    if (forms == NULL)
        return NULL;
    HyModuleFormEnum *res = NULL;
    const int BLOCK_SIZE = 17;
    HyModuleFormEnum form;
    int i = 0;
    do {
        res = static_cast<HyModuleFormEnum *>(solv_extend(res, i, 1, sizeof(HyModuleFormEnum), BLOCK_SIZE));
        form = forms[i];
        res[i++] = form;
    } while (form != _HY_MODULE_FORM_STOP_);
    return res;
}

static HyPossibilities
possibilities_create(HySubject subject, const HyForm *forms, const HyModuleFormEnum *module_forms,
                     enum poss_type type)
{
    HyPossibilities poss = static_cast<HyPossibilities>(g_malloc0(sizeof(*poss)));
    poss->subject = hy_subject_create(subject);
    poss->forms = forms_dup(forms);
    poss->module_forms = module_forms_dup(module_forms);
    poss->type = type;
    if (forms == NULL && module_forms == NULL)
        poss->current = -1;
    else
        poss->current = 0;
    return poss;
}

HyPossibilities
hy_subject_nevra_possibilities(HySubject subject, HyForm *forms)
{
    const HyForm *default_forms = forms == NULL ? HY_FORMS_MOST_SPEC : forms;
    return possibilities_create(subject, default_forms, NULL, TYPE_NEVRA);
}

HyPossibilities
hy_subject_module_form_possibilities(HySubject subject, HyModuleFormEnum *forms)
{
    const HyModuleFormEnum *default_forms = forms == NULL ? HY_MODULE_FORMS_MOST_SPEC : forms;
    return possibilities_create(subject, NULL, default_forms, TYPE_MODULE_FORM);
}

int
hy_possibilities_next_nevra(HyPossibilities iter, HyNevra *out_nevra)
{
    if (iter->type != TYPE_NEVRA || iter->current == -1)
        return -1;
    HyForm form = iter->forms[iter->current];
    Nevra nevra;
    while (form != _HY_FORM_STOP_) {
        iter->current++;
        if (hy_nevra_possibility(iter->subject, form, &nevra) == 0) {
            *out_nevra = new Nevra(std::move(nevra));
            return 0;
        }
        form = iter->forms[iter->current];
        nevra.clear();
    }
    *out_nevra = nullptr;
    return -1;
}

int
hy_possibilities_next_module_form(HyPossibilities iter, HyModuleForm *out_module_form)
{
    if (iter->type != TYPE_MODULE_FORM || iter->current == -1)
        return -1;
    HyModuleFormEnum form = iter->module_forms[iter->current];
    while (form != _HY_MODULE_FORM_STOP_) {
        iter->current++;
        *out_module_form = hy_module_form_create();
        if (module_form_possibility(iter->subject, form, *out_module_form) == 0) {
            return 0;
        }
        form = iter->module_forms[iter->current];
        g_clear_pointer(out_module_form, hy_module_form_free);
    }
    return -1;
}

/* Given a subject, attempt to create a query choose the first one, and update
 * the query to try to match it.
 *
 * This code is based on rpm-software-management/dnf/subject.py:get_best_query() at git
 * revision: 1d83fdc0280ca4202281ef489afe600e2f51a32a
 */
HyQuery
hy_subject_get_best_solution(HySubject subject, DnfSack *sack, HyForm *forms, HyNevra *nevra,
                             gboolean icase, gboolean with_nevra, gboolean with_provides,
                             gboolean with_filenames)
{
    int ret = 0;
    HyQuery query = NULL;

    if (with_nevra) {
        HyPossibilities iter = hy_subject_nevra_possibilities(subject, forms);
        while (ret != -1) {
            ret = hy_possibilities_next_nevra(iter, nevra);
            if (ret != -1) {
                query = hy_query_from_nevra(*nevra, sack, icase);
                if (!hy_query_is_empty(query)) {
                    hy_possibilities_free(iter);
                    return query;
                }
                hy_query_free(query);
            }
        }
        hy_possibilities_free(iter);
        delete *nevra;
        *nevra = nullptr;
        if (!forms) {
            query = hy_query_create(sack);
            hy_query_filter(query, HY_PKG_NEVRA, HY_GLOB, subject);
            if (!hy_query_is_empty(query))
                return query;
            hy_query_free(query);
        }
    }
    if (with_provides) {
        query = hy_query_create(sack);
        hy_query_filter(query, HY_PKG_PROVIDES, HY_GLOB, subject);
        if (!hy_query_is_empty(query))
            return query;
        hy_query_free(query);
    }

    if (with_filenames && hy_is_file_pattern(subject)) {
        query = hy_query_create(sack);
        hy_query_filter(query, HY_PKG_FILE, HY_GLOB, subject);
        return query;
    }

    query = hy_query_create(sack);
    hy_query_filter_empty(query);
    return query;
}

HySelector
hy_subject_get_best_sltr(HySubject subject, DnfSack *sack, HyForm *forms, bool obsoletes,
                         const char *reponame)
{
    HyNevra nevra{nullptr};
    HyQuery query = hy_subject_get_best_solution(subject, sack, forms, &nevra, FALSE, TRUE, TRUE,
                                                 TRUE);
    if (!hy_query_is_empty(query)) {
        hy_query_filter(query, HY_PKG_ARCH, HY_NEQ, "src");
        if (obsoletes && nevra && nevra->hasJustName()) {
            DnfPackageSet *pset;
            pset = hy_query_run_set(query);
            HyQuery query_obsoletes = hy_query_clone(query);
            hy_query_filter_package_in(query_obsoletes, HY_PKG_OBSOLETES, HY_EQ, pset);
            delete pset;
            hy_query_union(query, query_obsoletes);
            hy_query_free(query_obsoletes);
        }
        if (reponame != NULL) {
            HyQuery installed_query = hy_query_clone(query);
            hy_query_filter(installed_query, HY_PKG_REPONAME, HY_EQ, HY_SYSTEM_REPO_NAME);
            hy_query_filter(query, HY_PKG_REPONAME, HY_EQ, reponame);
            hy_query_union(query, installed_query);
            hy_query_free(installed_query);
        }
    }
    delete nevra;
    HySelector selector = hy_query_to_selector(query);
    hy_query_free(query);
    return selector;
}

/* Given a subject, attempt to create a "selector".
 *
 */
HySelector
hy_subject_get_best_selector(HySubject subject, DnfSack *sack)
{
    return hy_subject_get_best_sltr(subject, sack, NULL, FALSE, NULL);
}

#define MATCH_EMPTY(i) (matches[i].rm_so >= matches[i].rm_eo)

static bool
copy_str_from_subexpr(std::string & target, const char* source,
    regmatch_t* matches, int i)
{
    int subexpr_len = matches[i].rm_eo - matches[i].rm_so;
    if (subexpr_len == 0)
        return false;
    target = std::string(source + matches[i].rm_so, subexpr_len);
    return true;
}

int
hy_nevra_possibility(const char *nevra_str, int form, HyNevra nevra)
{
    enum { NAME = 1, EPOCH = 3, VERSION = 4, RELEASE = 5, ARCH = 6 };
    regex_t reg;
    char *epoch = nullptr;

    regmatch_t matches[10];

    regcomp(&reg, nevra_form_regex[form - 1], REG_EXTENDED);
    int ret = regexec(&reg, nevra_str, 10, matches, 0);
    regfree(&reg);
    if (ret != 0)
    return -1;
    if (!MATCH_EMPTY(EPOCH)) {
        copy_str_from_subexpr(&epoch, nevra_str, matches, EPOCH);
        nevra->setEpoch(atoi(epoch));
        free(epoch);
    }
    std::string tmp;
    if (!copy_str_from_subexpr(tmp, nevra_str, matches, NAME))
        return -1;
    nevra->setName(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, VERSION))
        nevra->setVersion(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, RELEASE))
        nevra->setRelease(tmp);
    if (copy_str_from_subexpr(tmp, nevra_str, matches, ARCH))
        nevra->setArch(tmp);
    return 0;
}

#undef MATCH_EMPTY
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 */

#include "XSLTInputSource.hpp"

#include <cassert>

#include <framework/URLInputSource.hpp>
#include <util/BinFileInputStream.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/StdBinInputStream.hpp>
#include <PlatformSupport/URISupport.hpp>

XSLTInputSource::XSLTInputSource() :
	InputSource(""),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(const XMLCh*	systemId) :
	InputSource(systemId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(
			const XMLCh*	systemId,
			const XMLCh*	publicId) :
	InputSource(systemId, publicId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(const char*	systemId) :
	InputSource(systemId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(
			const char*		systemId,
			const char*		publicId) :
	InputSource(systemId,
				publicId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(XalanNode*		node) :
	InputSource(""),
	m_stream(0),
	m_node(node)
{
}

#if defined(XALAN_NO_NAMESPACES)
XSLTInputSource::XSLTInputSource(istream*		stream) :
#else
XSLTInputSource::XSLTInputSource(std::istream*	stream) :
#endif
	InputSource(""),
	m_stream(stream),
	m_node(0)
{
}

BinInputStream*
XSLTInputSource::makeStream() const
{
	BinInputStream*		theResult = 0;

	if (m_stream != 0)
	{
		theResult = new StdBinInputStream(*m_stream);
	}
	else if (m_node == 0)
	{
#if 1
		URISupport::URLAutoPtrType	theURL = URISupport::getURLFromString(getSystemId());

		theResult = theURL->makeNewStream();
#else
		const XMLCh* const	theSystemID =
			getSystemId();

		const unsigned int	theColonIndex = indexOf(theSystemID, ':');
		const unsigned int	theLength = length(theSystemID);

		if (theColonIndex == theLength)
		{
			// No ':', so assume it's a file.
			theResult = new BinFileInputStream(theSystemID);
		}
		else
		{
			// It could be a DOS-style file spec...
			const unsigned int	theBackslashIndex = indexOf(theSystemID, '\\');

			if (theBackslashIndex < theLength && theBackslashIndex == 2)
			{
				// OK, another shot at a file...
				theResult = new BinFileInputStream(theSystemID);
			}
			else
			{
				URLInputSource inputSource(getSystemId());

				theResult = inputSource.makeStream();
			}
		}
#endif
	}

	return theResult;
}

void
XSLTInputSource::setNode(XalanNode*		node)
{
	m_node = node;
}

XalanNode*
XSLTInputSource::getNode() const
{
	return m_node;
}
<commit_msg>Fixed default constructor problem.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 */

#include "XSLTInputSource.hpp"

#include <cassert>

#include <framework/URLInputSource.hpp>
#include <util/BinFileInputStream.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/StdBinInputStream.hpp>
#include <PlatformSupport/URISupport.hpp>

XSLTInputSource::XSLTInputSource() :
	InputSource(),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(const XMLCh*	systemId) :
	InputSource(systemId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(
			const XMLCh*	systemId,
			const XMLCh*	publicId) :
	InputSource(systemId, publicId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(const char*	systemId) :
	InputSource(systemId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(
			const char*		systemId,
			const char*		publicId) :
	InputSource(systemId,
				publicId),
	m_stream(0),
	m_node(0)
{
}

XSLTInputSource::XSLTInputSource(XalanNode*		node) :
	InputSource(""),
	m_stream(0),
	m_node(node)
{
}

#if defined(XALAN_NO_NAMESPACES)
XSLTInputSource::XSLTInputSource(istream*		stream) :
#else
XSLTInputSource::XSLTInputSource(std::istream*	stream) :
#endif
	InputSource(""),
	m_stream(stream),
	m_node(0)
{
}

BinInputStream*
XSLTInputSource::makeStream() const
{
	BinInputStream*		theResult = 0;

	if (m_stream != 0)
	{
		theResult = new StdBinInputStream(*m_stream);
	}
	else if (m_node == 0)
	{
#if 1
		URISupport::URLAutoPtrType	theURL = URISupport::getURLFromString(getSystemId());

		theResult = theURL->makeNewStream();
#else
		const XMLCh* const	theSystemID =
			getSystemId();

		const unsigned int	theColonIndex = indexOf(theSystemID, ':');
		const unsigned int	theLength = length(theSystemID);

		if (theColonIndex == theLength)
		{
			// No ':', so assume it's a file.
			theResult = new BinFileInputStream(theSystemID);
		}
		else
		{
			// It could be a DOS-style file spec...
			const unsigned int	theBackslashIndex = indexOf(theSystemID, '\\');

			if (theBackslashIndex < theLength && theBackslashIndex == 2)
			{
				// OK, another shot at a file...
				theResult = new BinFileInputStream(theSystemID);
			}
			else
			{
				URLInputSource inputSource(getSystemId());

				theResult = inputSource.makeStream();
			}
		}
#endif
	}

	return theResult;
}

void
XSLTInputSource::setNode(XalanNode*		node)
{
	m_node = node;
}

XalanNode*
XSLTInputSource::getNode() const
{
	return m_node;
}
<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  HashKit library
 *
 *  Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
 *  Copyright (C) 2006-2009 Brian Aker All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *      * Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *      * Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the
 *  distribution.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
*
* By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
* code any way you wish, private, educational, or commercial.  It's free.
* Use for hash table lookup, or anything where one collision in 2^^32 is
* acceptable.  Do NOT use for cryptographic purposes.
* http://burtleburtle.net/bob/hash/index.html
*
* Modified by Brian Pontz for libmemcached
* TODO:
* Add big endian support
*/

#include <libhashkit/common.h>

#define hashsize(n) ((uint32_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))

#define mix(a,b,c) \
{ \
  a -= c;  a ^= rot(c, 4);  c += b; \
  b -= a;  b ^= rot(a, 6);  a += c; \
  c -= b;  c ^= rot(b, 8);  b += a; \
  a -= c;  a ^= rot(c,16);  c += b; \
  b -= a;  b ^= rot(a,19);  a += c; \
  c -= b;  c ^= rot(b, 4);  b += a; \
}

#define final(a,b,c) \
{ \
  c ^= b; c -= rot(b,14); \
  a ^= c; a -= rot(c,11); \
  b ^= a; b -= rot(a,25); \
  c ^= b; c -= rot(b,16); \
  a ^= c; a -= rot(c,4);  \
  b ^= a; b -= rot(a,14); \
  c ^= b; c -= rot(b,24); \
}

#define JENKINS_INITVAL 13

/*
jenkins_hash() -- hash a variable-length key into a 32-bit value
  k       : the key (the unaligned variable-length array of bytes)
  length  : the length of the key, counting by bytes
  initval : can be any 4-byte value
Returns a 32-bit value.  Every bit of the key affects every bit of
the return value.  Two keys differing by one or two bits will have
totally different hash values.

The best hash table sizes are powers of 2.  There is no need to do
mod a prime (mod is sooo slow!).  If you need less than 32 bits,
use a bitmask.  For example, if you need only 10 bits, do
  h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
*/

uint32_t hashkit_jenkins(const char *key, size_t length, void *)
{
  uint32_t a,b,c;                                          /* internal state */
  union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */

  /* Set up the internal state */
  a = b = c = 0xdeadbeef + ((uint32_t)length) + JENKINS_INITVAL;

  u.ptr = key;
#ifndef WORDS_BIGENDIAN
  if ((u.i & 0x3) == 0)
  {
    const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */

    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      b += k[1];
      c += k[2];
      mix(a,b,c);
      length -= 12;
      k += 3;
    }

    /*----------------------------- handle the last (probably partial) block */
    /*
     * "k[2]&0xffffff" actually reads beyond the end of the string, but
     * then masks off the part it's not allowed to read.  Because the
     * string is aligned, the masked-off tail is in the same word as the
     * rest of the string.  Every machine with memory protection I've seen
     * does it on word boundaries, so is OK with this.  But VALGRIND will
     * still catch it and complain.  The masking trick does make the hash
     * noticably faster for short strings (like English words).
     */
    switch(length)
    {
    case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
    case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
    case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
    case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
    case 8 : b+=k[1]; a+=k[0]; break;
    case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
    case 6 : b+=k[1]&0xffff; a+=k[0]; break;
    case 5 : b+=k[1]&0xff; a+=k[0]; break;
    case 4 : a+=k[0]; break;
    case 3 : a+=k[0]&0xffffff; break;
    case 2 : a+=k[0]&0xffff; break;
    case 1 : a+=k[0]&0xff; break;
    case 0 : return c;              /* zero length strings require no mixing */
    default: return c;
    }

  }
  else if ((u.i & 0x1) == 0)
  {
    const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
    const uint8_t  *k8;

    /*--------------- all but last block: aligned reads and different mixing */
    while (length > 12)
    {
      a += k[0] + (((uint32_t)k[1])<<16);
      b += k[2] + (((uint32_t)k[3])<<16);
      c += k[4] + (((uint32_t)k[5])<<16);
      mix(a,b,c);
      length -= 12;
      k += 6;
    }

    /*----------------------------- handle the last (probably partial) block */
    k8 = (const uint8_t *)k;
    switch(length)
    {
    case 12: c+=k[4]+(((uint32_t)k[5])<<16);
             b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
    case 10: c+=k[4];
             b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 9 : c+=k8[8];                      /* fall through */
    case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
    case 6 : b+=k[2];
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 5 : b+=k8[4];                      /* fall through */
    case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
    case 2 : a+=k[0];
             break;
    case 1 : a+=k8[0];
             break;
    case 0 : return c;                     /* zero length requires no mixing */
    default: return c;
    }

  }
  else
  {                        /* need to read the key one byte at a time */
#endif /* little endian */
    const uint8_t *k = (const uint8_t *)key;

    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      a += ((uint32_t)k[1])<<8;
      a += ((uint32_t)k[2])<<16;
      a += ((uint32_t)k[3])<<24;
      b += k[4];
      b += ((uint32_t)k[5])<<8;
      b += ((uint32_t)k[6])<<16;
      b += ((uint32_t)k[7])<<24;
      c += k[8];
      c += ((uint32_t)k[9])<<8;
      c += ((uint32_t)k[10])<<16;
      c += ((uint32_t)k[11])<<24;
      mix(a,b,c);
      length -= 12;
      k += 12;
    }

    /*-------------------------------- last block: affect all 32 bits of (c) */
    switch(length)                   /* all the case statements fall through */
    {
    case 12: c+=((uint32_t)k[11])<<24;
    case 11: c+=((uint32_t)k[10])<<16;
    case 10: c+=((uint32_t)k[9])<<8;
    case 9 : c+=k[8];
    case 8 : b+=((uint32_t)k[7])<<24;
    case 7 : b+=((uint32_t)k[6])<<16;
    case 6 : b+=((uint32_t)k[5])<<8;
    case 5 : b+=k[4];
    case 4 : a+=((uint32_t)k[3])<<24;
    case 3 : a+=((uint32_t)k[2])<<16;
    case 2 : a+=((uint32_t)k[1])<<8;
    case 1 : a+=k[0];
             break;
    case 0 : return c;
    default : return c;
    }
#ifndef WORDS_BIGENDIAN
  }
#endif

  final(a,b,c);
  return c;
}
<commit_msg>lp:1079994<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  HashKit library
 *
 *  Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
 *  Copyright (C) 2006-2009 Brian Aker All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *      * Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *      * Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the
 *  distribution.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
*
* By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
* code any way you wish, private, educational, or commercial.  It's free.
* Use for hash table lookup, or anything where one collision in 2^^32 is
* acceptable.  Do NOT use for cryptographic purposes.
* http://burtleburtle.net/bob/hash/index.html
*
* Modified by Brian Pontz for libmemcached
* TODO:
* Add big endian support
*/

#include <libhashkit/common.h>

#define hashsize(n) ((uint32_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))

#define mix(a,b,c) \
{ \
  a -= c;  a ^= rot(c, 4);  c += b; \
  b -= a;  b ^= rot(a, 6);  a += c; \
  c -= b;  c ^= rot(b, 8);  b += a; \
  a -= c;  a ^= rot(c,16);  c += b; \
  b -= a;  b ^= rot(a,19);  a += c; \
  c -= b;  c ^= rot(b, 4);  b += a; \
}

#define final(a,b,c) \
{ \
  c ^= b; c -= rot(b,14); \
  a ^= c; a -= rot(c,11); \
  b ^= a; b -= rot(a,25); \
  c ^= b; c -= rot(b,16); \
  a ^= c; a -= rot(c,4);  \
  b ^= a; b -= rot(a,14); \
  c ^= b; c -= rot(b,24); \
}

#define JENKINS_INITVAL 13

/*
jenkins_hash() -- hash a variable-length key into a 32-bit value
  k       : the key (the unaligned variable-length array of bytes)
  length  : the length of the key, counting by bytes
  initval : can be any 4-byte value
Returns a 32-bit value.  Every bit of the key affects every bit of
the return value.  Two keys differing by one or two bits will have
totally different hash values.

The best hash table sizes are powers of 2.  There is no need to do
mod a prime (mod is sooo slow!).  If you need less than 32 bits,
use a bitmask.  For example, if you need only 10 bits, do
  h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
*/

uint32_t hashkit_jenkins(const char *key, size_t length, void *)
{
  uint32_t a,b,c;                                          /* internal state */
#ifndef WORDS_BIGENDIAN
  union { const void *ptr; size_t i; } u;
  u.ptr = key;
#endif

  /* Set up the internal state */
  a = b = c = 0xdeadbeef + ((uint32_t)length) + JENKINS_INITVAL;

#ifndef WORDS_BIGENDIAN
  if ((u.i & 0x3) == 0)
  {
    const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */

    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      b += k[1];
      c += k[2];
      mix(a,b,c);
      length -= 12;
      k += 3;
    }

    /*----------------------------- handle the last (probably partial) block */
    /*
     * "k[2]&0xffffff" actually reads beyond the end of the string, but
     * then masks off the part it's not allowed to read.  Because the
     * string is aligned, the masked-off tail is in the same word as the
     * rest of the string.  Every machine with memory protection I've seen
     * does it on word boundaries, so is OK with this.  But VALGRIND will
     * still catch it and complain.  The masking trick does make the hash
     * noticably faster for short strings (like English words).
     */
    switch(length)
    {
    case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
    case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
    case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
    case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
    case 8 : b+=k[1]; a+=k[0]; break;
    case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
    case 6 : b+=k[1]&0xffff; a+=k[0]; break;
    case 5 : b+=k[1]&0xff; a+=k[0]; break;
    case 4 : a+=k[0]; break;
    case 3 : a+=k[0]&0xffffff; break;
    case 2 : a+=k[0]&0xffff; break;
    case 1 : a+=k[0]&0xff; break;
    case 0 : return c;              /* zero length strings require no mixing */
    default: return c;
    }

  }
  else if ((u.i & 0x1) == 0)
  {
    const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
    const uint8_t  *k8;

    /*--------------- all but last block: aligned reads and different mixing */
    while (length > 12)
    {
      a += k[0] + (((uint32_t)k[1])<<16);
      b += k[2] + (((uint32_t)k[3])<<16);
      c += k[4] + (((uint32_t)k[5])<<16);
      mix(a,b,c);
      length -= 12;
      k += 6;
    }

    /*----------------------------- handle the last (probably partial) block */
    k8 = (const uint8_t *)k;
    switch(length)
    {
    case 12: c+=k[4]+(((uint32_t)k[5])<<16);
             b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
    case 10: c+=k[4];
             b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 9 : c+=k8[8];                      /* fall through */
    case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
    case 6 : b+=k[2];
             a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 5 : b+=k8[4];                      /* fall through */
    case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
             break;
    case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
    case 2 : a+=k[0];
             break;
    case 1 : a+=k8[0];
             break;
    case 0 : return c;                     /* zero length requires no mixing */
    default: return c;
    }

  }
  else
  {                        /* need to read the key one byte at a time */
#endif /* little endian */
    const uint8_t *k = (const uint8_t *)key;

    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      a += ((uint32_t)k[1])<<8;
      a += ((uint32_t)k[2])<<16;
      a += ((uint32_t)k[3])<<24;
      b += k[4];
      b += ((uint32_t)k[5])<<8;
      b += ((uint32_t)k[6])<<16;
      b += ((uint32_t)k[7])<<24;
      c += k[8];
      c += ((uint32_t)k[9])<<8;
      c += ((uint32_t)k[10])<<16;
      c += ((uint32_t)k[11])<<24;
      mix(a,b,c);
      length -= 12;
      k += 12;
    }

    /*-------------------------------- last block: affect all 32 bits of (c) */
    switch(length)                   /* all the case statements fall through */
    {
    case 12: c+=((uint32_t)k[11])<<24;
    case 11: c+=((uint32_t)k[10])<<16;
    case 10: c+=((uint32_t)k[9])<<8;
    case 9 : c+=k[8];
    case 8 : b+=((uint32_t)k[7])<<24;
    case 7 : b+=((uint32_t)k[6])<<16;
    case 6 : b+=((uint32_t)k[5])<<8;
    case 5 : b+=k[4];
    case 4 : a+=((uint32_t)k[3])<<24;
    case 3 : a+=((uint32_t)k[2])<<16;
    case 2 : a+=((uint32_t)k[1])<<8;
    case 1 : a+=k[0];
             break;
    case 0 : return c;
    default : return c;
    }
#ifndef WORDS_BIGENDIAN
  }
#endif

  final(a,b,c);
  return c;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <fstream>

using namespace std;

//MACROS
const int ARRAY_SIZE = 20;
const char *INFILE = "p2data.txt";

//Global Error variables
int file_err=0;

//initialize the sorting array
int *input_array = new int[ARRAY_SIZE];
int *sorted_array = new int[ARRAY_SIZE];

//Create struct for thread args
typedef struct {
  int left;
  int right;
} sort_struct;

void print_array(const int array[ARRAY_SIZE]){
  //warning output
  cout << endl << "Output ignores leading 0's" << endl;

  //print results to the screen
  for (int i=0; i < ARRAY_SIZE; i++){
    if (array[i] != 0)
      cout << array[i] << endl;
  }
}

void get_input_from_file(string infile){
  ifstream input_stream;
  input_stream.open(INFILE);

  int temp=0, j=0;
  //Store input in sort_array
  while (input_stream >> temp){
    //if input > 20, return error and wait for new file name
    if (j < ARRAY_SIZE){
      input_array[j] = temp;
      j++;
    }
    else{
      file_err = 1;

      //close file stream
      input_stream.close();

      return;
    }
  }

  //initialize remainder of array
  while (j<ARRAY_SIZE){
    input_array[j] = 0;
    j++;
  }
}

void *merge(void * params){
  //Testing code
  //cout << "MERGE thread: " << pthread_self() << endl;

  //dereference pointer and get struct
  sort_struct *data = (sort_struct*)params;

  //get elements
  int mid = ((data->left + data->right) / 2);
  int left_count = data->left;
  int right_count = mid+1;

  //create and set looping variable to 0
  int merge_count = data->left;

  //loop until one sub_array is empty
  while (left_count <= mid && right_count <= data->right){
    //add new elements to the sorted array
    if (input_array[left_count] < input_array[right_count]){
      sorted_array[merge_count] = input_array[left_count];
      merge_count++;
      left_count++;
    }

    else if(input_array[left_count] >= input_array[right_count]){
      sorted_array[merge_count] = input_array[right_count];
      merge_count++;
      right_count++;
    }
  }

  //add the rest of the elements to the sorted array
  while (right_count <= data->right){
    sorted_array[merge_count] = input_array[right_count];
    merge_count++;
    right_count++;
  }

  while (left_count <= mid){
    sorted_array[merge_count] = input_array[left_count];
    merge_count++;
    left_count++;
  }

  //copy sorted list back to input_array
  for (int i=data->left; i<merge_count;i++){
    input_array[i] = sorted_array[i];
  }

  //return
  return 0;
}

void *mergesort(void * params){
  //testing code
  //cout << "Mergesort thread: " << pthread_self() << endl;

  //dereference pointer and get struct
  sort_struct *data = (sort_struct*)params;

  //create middle of array
  int mid = ((data->left + data->right) / 2);

  //create structures to pass to threads
  sort_struct ldata, *ldata_ptr, rdata, *rdata_ptr;

  //initialize left data structures and pointer
  ldata = (sort_struct){data->left, mid};
  ldata_ptr = &ldata;

  //initialize right data structures and pointer
  rdata = (sort_struct){mid+1, data->right};
  rdata_ptr = &rdata;

  if (data->left < data->right){
    //create threads and return values
    pthread_t l_thread, r_thread, merge_thread;
    int lt_ret_val, rt_ret_val, merge_t_ret_val;

    //call thread 1
    lt_ret_val = pthread_create(&l_thread, NULL, mergesort, ldata_ptr);

    if (lt_ret_val != 0)
      cout << "Thread (left) failed to start" << endl;
	  //testing code
	  //mergesort(ldata_ptr);

    //call thread 2
    rt_ret_val = pthread_create(&r_thread, NULL, mergesort, rdata_ptr);
    if (rt_ret_val !=0)
      cout << "Thread (right) failed to start";

    //testing code
    //mergesort(rdata_ptr);

    //wait for both to return
    pthread_join(l_thread, NULL);
    pthread_join(r_thread, NULL);

    //call thread 3 to merge the two sorted arrays
    //merge_t_ret_val = pthread_create(&merge_thread, NULL, merge, data);
	merge(data);
  }

  return 0;
}

int main(int argc, char const *argv[]) {
  //initialize array from file
  get_input_from_file(INFILE);

  //check if the file had an error
  if (file_err != 0){
    cout << "ERROR: Input list larger than " << ARRAY_SIZE << endl;
    return 0;
  }

  print_array(input_array);

  //initialize params
  sort_struct params, *param_ptr;
  params = (sort_struct){0,ARRAY_SIZE-1};
  param_ptr = &params;

  //call mergesort
  mergesort(param_ptr);

  print_array(sorted_array);

  return 0;
}
<commit_msg>Update p2apatton.cpp<commit_after>#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <fstream>

using namespace std;

//MACROS
const int ARRAY_SIZE = 20;
const char *INFILE = "p2data.txt";

//Global Error variables
int file_err=0;

//initialize the sorting array
int *input_array = new int[ARRAY_SIZE];
int *sorted_array = new int[ARRAY_SIZE];

//Create struct for thread args
typedef struct {
  int left;
  int right;
} sort_struct;

void print_array(const int array[ARRAY_SIZE]){
  //warning output
  cout << endl << "Output ignores leading 0's" << endl;

  //print results to the screen
  for (int i=0; i < ARRAY_SIZE; i++){
    if (array[i] != 0)
      cout << array[i] << endl;
  }
}

void get_input_from_file(string infile){
  ifstream input_stream;
  input_stream.open(INFILE);

  int temp=0, j=0;
  //Store input in sort_array
  while (input_stream >> temp){
    //if input > 20, return error and wait for new file name
    if (j < ARRAY_SIZE){
      input_array[j] = temp;
      j++;
    }
    else{
      file_err = 1;

      //close file stream
      input_stream.close();

      return;
    }
  }

  //initialize remainder of array
  while (j<ARRAY_SIZE){
    input_array[j] = 0;
    j++;
  }
}

void *merge(void * params){
  //Testing code
  //cout << "MERGE thread: " << pthread_self() << endl;

  //dereference pointer and get struct
  sort_struct *data = (sort_struct*)params;

  //get elements
  int mid = ((data->left + data->right) / 2);
  int left_count = data->left;
  int right_count = mid+1;

  //create and set looping variable to 0
  int merge_count = data->left;

  //loop until one sub_array is empty
  while (left_count <= mid && right_count <= data->right){
    //add new elements to the sorted array
    if (input_array[left_count] < input_array[right_count]){
      sorted_array[merge_count] = input_array[left_count];
      merge_count++;
      left_count++;
    }

    else if(input_array[left_count] >= input_array[right_count]){
      sorted_array[merge_count] = input_array[right_count];
      merge_count++;
      right_count++;
    }
  }

  //add the rest of the elements to the sorted array
  while (right_count <= data->right){
    sorted_array[merge_count] = input_array[right_count];
    merge_count++;
    right_count++;
  }

  while (left_count <= mid){
    sorted_array[merge_count] = input_array[left_count];
    merge_count++;
    left_count++;
  }

  //copy sorted list back to input_array
  for (int i=data->left; i<merge_count;i++){
    input_array[i] = sorted_array[i];
  }

  //return
  return 0;
}

void *mergesort(void * params){
  //testing code
  //cout << "Mergesort thread: " << pthread_self() << endl;

  //dereference pointer and get struct
  sort_struct *data = (sort_struct*)params;

  //create middle of array
  int mid = ((data->left + data->right) / 2);

  //create structures to pass to threads
  sort_struct ldata, *ldata_ptr, rdata, *rdata_ptr;

  //initialize left data structures and pointer
  ldata = (sort_struct){data->left, mid};
  ldata_ptr = &ldata;

  //initialize right data structures and pointer
  rdata = (sort_struct){mid+1, data->right};
  rdata_ptr = &rdata;

  if (data->left < data->right){
    //create threads and return values
    pthread_t l_thread, r_thread, merge_thread;
    int lt_ret_val, rt_ret_val, merge_t_ret_val;

    //call thread 1
    lt_ret_val = pthread_create(&l_thread, NULL, mergesort, ldata_ptr);

    if (lt_ret_val != 0)
      cout << "Thread (left) failed to start" << endl;
	  //testing code
	  //mergesort(ldata_ptr);

    //call thread 2
    rt_ret_val = pthread_create(&r_thread, NULL, mergesort, rdata_ptr);
    if (rt_ret_val !=0)
      cout << "Thread (right) failed to start";

    //testing code
    //mergesort(rdata_ptr);

    //wait for both to return
    pthread_join(l_thread, NULL);
    pthread_join(r_thread, NULL);

    //call thread 3 to merge the two sorted arrays
    merge_t_ret_val = pthread_create(&merge_thread, NULL, merge, data);

    //merge(data);
  }

  return 0;
}

int main(int argc, char const *argv[]) {
  //initialize array from file
  get_input_from_file(INFILE);

  //check if the file had an error
  if (file_err != 0){
    cout << "ERROR: Input list larger than " << ARRAY_SIZE << endl;
    return 0;
  }

  print_array(input_array);

  //initialize params
  sort_struct params, *param_ptr;
  params = (sort_struct){0,ARRAY_SIZE-1};
  param_ptr = &params;

  //call mergesort
  mergesort(param_ptr);

  print_array(sorted_array);

  return 0;
}
<|endoftext|>


<commit_before>//===-- sanitizer_win.cc --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements windows-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include <windows.h>

#include <assert.h>

#include "sanitizer_internal_defs.h"
#include "sanitizer_libc.h"

#define UNIMPLEMENTED_WIN() assert(false)

namespace __sanitizer {

int GetPid() {
  return GetProcessId(GetCurrentProcess());
}

void *MmapOrDie(uptr size) {
  void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  if (rv == 0)
    RawWrite("Failed to map!\n");
    Die();
  return rv;
}

void UnmapOrDie(void *addr, uptr size) {
  // FIXME: Use CHECK here.
  RAW_CHECK(VirtualFree(addr, size, MEM_DECOMMIT));
}

void *internal_mmap(void *addr, uptr length, int prot, int flags,
                    int fd, u64 offset) {
  UNIMPLEMENTED_WIN();
  return 0;
}

int internal_munmap(void *addr, uptr length) {
  UNIMPLEMENTED_WIN();
  return 0;
}

int internal_close(fd_t fd) {
  UNIMPLEMENTED_WIN();
  return 0;
}

fd_t internal_open(const char *filename, bool write) {
  UNIMPLEMENTED_WIN();
  return 0;
}

uptr internal_read(fd_t fd, void *buf, uptr count) {
  UNIMPLEMENTED_WIN();
  return 0;
}

uptr internal_write(fd_t fd, const void *buf, uptr count) {
  if (fd != 2) {
    UNIMPLEMENTED_WIN();
    return 0;
  }
  HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
  if (err == 0)
    return 0;  // FIXME: this might not work on some apps.
  DWORD ret;
  if (!WriteFile(err, buf, count, &ret, 0))
    return 0;
  return ret;
}

uptr internal_filesize(fd_t fd) {
  UNIMPLEMENTED_WIN();
  return -1;
}

int internal_dup2(int oldfd, int newfd) {
  UNIMPLEMENTED_WIN();
  return -1;
}

int internal_sscanf(const char *str, const char *format, ...) {
  UNIMPLEMENTED_WIN();
  return -1;
}

}  // namespace __sanitizer

#endif  // _WIN32
<commit_msg>[ASan] fix win build - add missing header<commit_after>//===-- sanitizer_win.cc --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements windows-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include <windows.h>

#include <assert.h>

#include "sanitizer_common.h"
#include "sanitizer_libc.h"

#define UNIMPLEMENTED_WIN() assert(false)

namespace __sanitizer {

int GetPid() {
  return GetProcessId(GetCurrentProcess());
}

void *MmapOrDie(uptr size) {
  void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  if (rv == 0)
    RawWrite("Failed to map!\n");
    Die();
  return rv;
}

void UnmapOrDie(void *addr, uptr size) {
  // FIXME: Use CHECK here.
  RAW_CHECK(VirtualFree(addr, size, MEM_DECOMMIT));
}

void *internal_mmap(void *addr, uptr length, int prot, int flags,
                    int fd, u64 offset) {
  UNIMPLEMENTED_WIN();
  return 0;
}

int internal_munmap(void *addr, uptr length) {
  UNIMPLEMENTED_WIN();
  return 0;
}

int internal_close(fd_t fd) {
  UNIMPLEMENTED_WIN();
  return 0;
}

fd_t internal_open(const char *filename, bool write) {
  UNIMPLEMENTED_WIN();
  return 0;
}

uptr internal_read(fd_t fd, void *buf, uptr count) {
  UNIMPLEMENTED_WIN();
  return 0;
}

uptr internal_write(fd_t fd, const void *buf, uptr count) {
  if (fd != 2) {
    UNIMPLEMENTED_WIN();
    return 0;
  }
  HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
  if (err == 0)
    return 0;  // FIXME: this might not work on some apps.
  DWORD ret;
  if (!WriteFile(err, buf, count, &ret, 0))
    return 0;
  return ret;
}

uptr internal_filesize(fd_t fd) {
  UNIMPLEMENTED_WIN();
  return -1;
}

int internal_dup2(int oldfd, int newfd) {
  UNIMPLEMENTED_WIN();
  return -1;
}

int internal_sscanf(const char *str, const char *format, ...) {
  UNIMPLEMENTED_WIN();
  return -1;
}

}  // namespace __sanitizer

#endif  // _WIN32
<|endoftext|>


<commit_before>/*
 * CLBuffer.hpp
 *
 *  Created on: July 28, 2010
 *      Author: Craig Rasmussen
 */

#ifndef CLBUFFER_HPP_
#define CLBUFFER_HPP_

#include "../../include/pv_arch.h"

#ifdef PV_USE_OPENCL

#include <OpenCL/opencl.h>

////////////////////////////////////////////////////////////////////////////////

namespace PV {

class CLBuffer {
public:

   CLBuffer(cl_context context, cl_command_queue commands,
            cl_map_flags flags, size_t size, void * host_ptr);
   virtual ~CLBuffer();

   int copyToDevice  (void * host_ptr);
   int copyFromDevice(void * host_ptr);

   void * map(cl_map_flags flags);
   int    unmap(void * mapped_ptr);

   cl_mem clMemObject(void)   {return d_buf;}

protected:

   cl_command_queue commands;          // compute command queue

   size_t size;                        // size of buffer object
   cl_mem d_buf;                       // handle to buffer on the device
};

} // namespace PV

#endif /* PV_USE_OPENCL */
#endif /* CLBUFFER_HPP_ */
<commit_msg>Reworked #ifdefs to provide a little more null functionality with not using OpenCL.<commit_after>/*
 * CLBuffer.hpp
 *
 *  Created on: July 28, 2010
 *      Author: Craig Rasmussen
 */

#ifndef CLBUFFER_HPP_
#define CLBUFFER_HPP_

#include "pv_opencl.h"

////////////////////////////////////////////////////////////////////////////////

namespace PV {

class CLBuffer {

#ifdef PV_USE_OPENCL

public:

   CLBuffer(cl_context context, cl_command_queue commands,
            cl_map_flags flags, size_t size, void * host_ptr);
   virtual ~CLBuffer();

   int copyToDevice  (void * host_ptr);
   int copyFromDevice(void * host_ptr);

   void * map(cl_map_flags flags);
   int    unmap(void * mapped_ptr);

   cl_mem clMemObject(void)   {return d_buf;}

protected:

   cl_command_queue commands;          // compute command queue

   size_t size;                        // size of buffer object
   cl_mem d_buf;                       // handle to buffer on the device

private: CLBuffer()    { ; }
#else
public:  CLBuffer()    { ; }
#endif /* PV_USE_OPENCL */

};

} // namespace PV

#endif /* CLBUFFER_HPP_ */
<|endoftext|>


<commit_before>#include "pixbuf.h"
#include <wincodec.h>

static int
sg_pixbuf_loadwincodec(struct sg_pixbuf *pbuf, const void *data, size_t len,
                       struct sg_error **err)
{
    HRESULT hr;
    IWICImagingFactory *fac = NULL;
    IWICStream *stream = NULL;
    IWICBitmapDecoder *decoder = NULL;
    IWICBitmapFrameDecode *frame = NULL;
    WICPixelFormatGUID pixelFormat, targetFormat;
    IWICComponentInfo *cinfo = NULL;
    IWICPixelFormatInfo *pinfo = NULL;
    IWICFormatConverter *converter = NULL;
    UINT chanCount, iwidth, iheight;
    sg_pixbuf_format_t pfmt;
    int r;

    hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fac));
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateStream(&stream);
    if (hr != S_OK)
        goto failed;
    hr = stream->InitializeFromMemory((BYTE *) data, len);
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateDecoderFromStream(stream, NULL, WICDecodeMetadataCacheOnDemand, &decoder);
    if (hr != S_OK)
        goto failed;
    hr = decoder->GetFrame(0, &frame);
    if (hr != S_OK)
        goto failed;
    hr = frame->GetPixelFormat(&pixelFormat);
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateComponentInfo(pixelFormat, &cinfo);
    if (hr != S_OK)
        goto failed;
    hr = cinfo->QueryInterface(IID_IWICPixelFormatInfo, (void **) &pinfo);
    if (hr != S_OK)
        goto failed;
    hr = pinfo->GetChannelCount(&chanCount);
    if (hr != S_OK)
        goto failed;

    switch (chanCount) {
    case 1:
        pfmt = SG_Y;
        targetFormat = GUID_WICPixelFormat8bppGray;
        break;

    case 3:
    case 4:
        pfmt = SG_RGBA;
        targetFormat = GUID_WICPixelFormat32bppRGBA;
        break;

    default:
        goto failed;
    }

    hr = fac->CreateFormatConverter(&converter);
    if (hr != S_OK)
        goto failed;
    hr = converter->Initialize(frame, targetFormat, WICBitmapDitherTypeNone, NULL, 0, WICBitmapPaletteTypeCustom);
    if (hr != S_OK)
        goto failed;
    hr = converter->GetSize(&iwidth, &iheight);
    if (hr != S_OK)
        goto failed;

    r = sg_pixbuf_set(pbuf, pfmt, iwidth, iheight, err);
    if (!r)
        goto done;
    r = sg_pixbuf_alloc(pbuf, err);
    if (r)
        goto done;
    converter->CopyPixels(NULL, pbuf->rowbytes, pbuf->rowbytes * pbuf->pheight, (BYTE *) pbuf->data);
    r = 0;

done:
    if (converter) converter->Release();
    if (pinfo) pinfo->Release();
    if (cinfo) cinfo->Release();
    if (frame) frame->Release();
    if (decoder) decoder->Release();
    if (stream) stream->Release();
    if (fac) fac->Release();
    return r;

failed:
    r = -1;
    goto done;
}

int
sg_pixbuf_loadpng(struct sg_pixbuf *pbuf, const void *data, size_t len,
                  struct sg_error **err)
{
    return sg_pixbuf_loadwincodec(pbuf, data, len, err);
}

int
sg_pixbuf_loadjpeg(struct sg_pixbuf *pbuf, const void *data, size_t len,
                   struct sg_error **err)
{
    return sg_pixbuf_loadwincodec(pbuf, data, len, err);
}
<commit_msg>Fix WinCodec image loader<commit_after>#include "pixbuf.h"
#include <wincodec.h>

#pragma comment(lib, "WindowsCodecs.lib")

static int
sg_pixbuf_loadwincodec(struct sg_pixbuf *pbuf, const void *data, size_t len,
                       struct sg_error **err)
{
    HRESULT hr;
    IWICImagingFactory *fac = NULL;
    IWICStream *stream = NULL;
    IWICBitmapDecoder *decoder = NULL;
    IWICBitmapFrameDecode *frame = NULL;
    WICPixelFormatGUID pixelFormat, targetFormat;
    IWICComponentInfo *cinfo = NULL;
    IWICPixelFormatInfo *pinfo = NULL;
    IWICFormatConverter *converter = NULL;
    UINT chanCount, iwidth, iheight;
    sg_pixbuf_format_t pfmt;
    int r;

    hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fac));
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateStream(&stream);
    if (hr != S_OK)
        goto failed;
    hr = stream->InitializeFromMemory((BYTE *) data, len);
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateDecoderFromStream(stream, NULL, WICDecodeMetadataCacheOnDemand, &decoder);
    if (hr != S_OK)
        goto failed;
    hr = decoder->GetFrame(0, &frame);
    if (hr != S_OK)
        goto failed;
    hr = frame->GetPixelFormat(&pixelFormat);
    if (hr != S_OK)
        goto failed;
    hr = fac->CreateComponentInfo(pixelFormat, &cinfo);
    if (hr != S_OK)
        goto failed;
    hr = cinfo->QueryInterface(IID_IWICPixelFormatInfo, (void **) &pinfo);
    if (hr != S_OK)
        goto failed;
    hr = pinfo->GetChannelCount(&chanCount);
    if (hr != S_OK)
        goto failed;

    switch (chanCount) {
    case 1:
        pfmt = SG_Y;
        targetFormat = GUID_WICPixelFormat8bppGray;
        break;

    case 3:
    case 4:
        pfmt = SG_RGBA;
        targetFormat = GUID_WICPixelFormat32bppRGBA;
        break;

    default:
        goto failed;
    }

    hr = fac->CreateFormatConverter(&converter);
    if (hr != S_OK)
        goto failed;
    hr = converter->Initialize(frame, targetFormat, WICBitmapDitherTypeNone, NULL, 0, WICBitmapPaletteTypeCustom);
    if (hr != S_OK)
        goto failed;
    hr = converter->GetSize(&iwidth, &iheight);
    if (hr != S_OK)
        goto failed;

    r = sg_pixbuf_set(pbuf, pfmt, iwidth, iheight, err);
    if (r)
        goto done;
    r = sg_pixbuf_alloc(pbuf, err);
    if (r)
        goto done;
    converter->CopyPixels(NULL, pbuf->rowbytes, pbuf->rowbytes * pbuf->pheight, (BYTE *) pbuf->data);
    r = 0;

done:
    if (converter) converter->Release();
    if (pinfo) pinfo->Release();
    if (cinfo) cinfo->Release();
    if (frame) frame->Release();
    if (decoder) decoder->Release();
    if (stream) stream->Release();
    if (fac) fac->Release();
    return r;

failed:
    r = -1;
    goto done;
}

int
sg_pixbuf_loadpng(struct sg_pixbuf *pbuf, const void *data, size_t len,
                  struct sg_error **err)
{
    return sg_pixbuf_loadwincodec(pbuf, data, len, err);
}

int
sg_pixbuf_loadjpeg(struct sg_pixbuf *pbuf, const void *data, size_t len,
                   struct sg_error **err)
{
    return sg_pixbuf_loadwincodec(pbuf, data, len, err);
}
<|endoftext|>


<commit_before>#include "batterybusinesslogic.h"
#include <qmsystem/qmled.h>

#include <QTimer>

#include <DuiLocale>
#include <DuiApplicationWindow>

BatteryBusinessLogic::BatteryBusinessLogic(SystemUIGConf *systemUIGConf) :
        systemUIGConf(systemUIGConf)
{
    battery = new QmBattery();
    deviceMode = new QmDeviceMode();
    uiNotif = new Notifier();

    /* init the battery levels */
    batteryLevels.insert(QmBattery::LevelFull, QString("100"));
    //batteryLevels.insert(QmBattery::Level75, 85); //not yet implemented
    //batteryLevels.insert(QmBattery::Level50, 60); //not yet implemented
    //batteryLevels.insert(QmBattery::Level25, 35); //not yet implemented
    batteryLevels.insert(QmBattery::LevelLow, QString("15"));
    batteryLevels.insert(QmBattery::LevelCritical, QString("5"));

    /* check if gconfvalues need to initialized */
    initSystemUIGConfKeys();

    /* connect to QmSystem signals */
    connect(battery, SIGNAL(batteryLevelChanged(Maemo::QmBattery::Level)),
            this, SLOT(batteryLevelChanged(Maemo::QmBattery::Level)));
    connect(battery, SIGNAL(batteryStateChanged(Maemo::QmBattery::State)),
            this, SLOT(batteryStateChanged(Maemo::QmBattery::State)));

    initBattery();
}

BatteryBusinessLogic::~BatteryBusinessLogic()
{
    delete uiNotif;
    uiNotif = NULL;
    delete battery;
    battery = NULL;
}

void BatteryBusinessLogic::initSystemUIGConfKeys()
{
    if(systemUIGConf->keyCount(SystemUIGConf::Battery) < 3) {
        /* GConf keys have not yet been set. */
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(deviceMode->getPSMState() == Maemo::QmDeviceMode::PSMStateOn ? true : false));
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMDisabledKey, QVariant(false));
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMThresholdKey, QVariant(batteryLevels.value(QmBattery::LevelLow)));
    }
}

// This method should be called also when the device is returned from sleep mode
void BatteryBusinessLogic::initBattery()
{
    //init the charging status
    batteryStateChanged(battery->getState());

    //init the battery level
    batteryLevelChanged((QmBattery::Level)batteryLevelValue());
}

int BatteryBusinessLogic::batteryLevelPercentage()
{
    return 100*battery->bars()/battery->maxBars();
}

int BatteryBusinessLogic::batteryLevelValue()
{
    int chargeLevelPercentage = batteryLevelPercentage();
    QmBattery::Level level;
    if(chargeLevelPercentage >= 85)
        level = QmBattery::LevelFull;
    /* Not yet implemented in QmBattery (not necessarily even needed)
    else if(chargeLevelPercentage < 85 && chargeLevelPercentage >= 60)
        level = QmBattery::Level75;
    else if(chargeLevelPercentage < 60 && chargeLevelPercentage >= 35)
        level = QmBattery::Level50;
    else if(chargeLevelPercentage < 35 && chargeLevelPercentage >= 15)
        level = QmBattery::Level25;
        */
    else if(chargeLevelPercentage < 15 && chargeLevelPercentage >= 5)
        level = QmBattery::LevelLow;
    else //chargeLevelPercentage < 5
        level = QmBattery::LevelCritical;

    return (int)level; //type has to be int. called elsewhere as well
}

void BatteryBusinessLogic::batteryStateChanged(Maemo::QmBattery::State state)
{
    switch(state) {
        case QmBattery::StateCharging:
            qDebug() << "Charging";
            emit batteryCharging();
            utiliseLED(true, QString("PatternBatteryCharging"));
            uiNotif->showNotification(trid("qtn_ener_char", "Charging"));
            break;
        case QmBattery::StateNotCharging:
            emit batteryNotCharging();
            utiliseLED(false, QString("PatternBatteryCharging"));
            break;
        default:
            break;
    }
}

void BatteryBusinessLogic::batteryLevelChanged(Maemo::QmBattery::Level level)
{
    emit batteryLevelValueChanged((int)level);
    checkPSMThreshold(level);

    switch(level) {
        case QmBattery::LevelFull:
            if(battery->getState() == QmBattery::StateCharging) {
                utiliseLED(true, QString("PatternBatteryFull"));
                QTimer::singleShot(5000, this, SLOT(utiliseLED(false, QString("PatternBatteryFull"))));
                uiNotif->showNotification(trid("qtn_ener_charcomp", "Charging complete"));
                uiNotif->showNotification(trid("qtn_ener_remcha", "Disconnect charger from power supply to save energy"));
            }
            break;
        case QmBattery::LevelLow:
            if(battery->getState() != QmBattery::StateCharging)
                uiNotif->showNotification(trid("qtn_ener_lowbatt", "Low battery"));
            break;
        default:
            break;
   }
}

void BatteryBusinessLogic::checkPSMThreshold(Maemo::QmBattery::Level level)
{
    qDebug() << "BatteryBusinessLogic::checkPSMThreshold(" << level << ")";
    if(level <= systemUIGConf->value(SystemUIGConf::BatteryPSMThresholdKey).toInt()) {
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOff
           && systemUIGConf->value(SystemUIGConf::BatteryPSMDisabledKey).toBool() == false) {
            // Send a notification that can be cancelled.
            // If it's not cancelled, after certain time the notifier emits a signal.
            // We catch this signal to set the PSM
            connect(uiNotif, SIGNAL(notifTimeout()), this, SLOT(activatePSM()));

            QHash<QString,QString> staticVariables;
            QString number;
            staticVariables.insert(QString("%a"), number.setNum(batteryLevelPercentage()));
            uiNotif->showCancellableNotification(trid("qtn_ener_psnote", "Battery charge level less than %a%. Switching to power save in %b seconds"),
                                                 10,
                                                 QString("%b"),
                                                 staticVariables);
        }
    }
    else {
        togglePSM(false);
    }
}

void BatteryBusinessLogic::activatePSM()
{
    qDebug() << "Activate PSM";
    disconnect(uiNotif, SIGNAL(notifTimeout()), this, SLOT(activatePSM()));
    togglePSM(true);
}

void BatteryBusinessLogic::togglePSM(bool toggle)
{
    qDebug() << "BatteryBusinessLogic::togglePSM(" << toggle << ")";
    if(toggle) { //turn on the PSM
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOff
           && systemUIGConf->value(SystemUIGConf::BatteryPSMDisabledKey).toBool() == false) {
            qDebug() << "Turn ON The PSM";
            deviceMode->setPSMState(QmDeviceMode::PSMStateOn);
            systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(toggle));
            emit PSMToggleValueChanged(toggle);
        }
    }
    else { //turn off the PSM
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOn) {
            qDebug() << "Turn OFF The PSM";
            deviceMode->setPSMState(QmDeviceMode::PSMStateOff);
            systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(toggle));
            emit PSMToggleValueChanged(toggle);
        }
    }
}

QStringList BatteryBusinessLogic::remainingTimeValues()
{
    qDebug() << "BatteryBusinessLogic::remainingTimeValues()";

    QStringList values;

    //TODO: replace hardcoded values with correct ones and remove temp var
    static int temp = 0; //temp
    if(temp<1) {
        values << (QString("%1").arg(120))/*battery->remainingTalkTime() * 60*/ << (QString("%1").arg(300)) /*battery->remainingStandByTime() * 60 */;
        ++temp;
    }
    else {
        values << (QString("%1").arg(130))/*battery->remainingTalkTime() * 60*/ << (QString("%1").arg(350)) /*battery->remainingStandByTime() * 60 */;
        temp = 0;
    }
    return values;
}

void BatteryBusinessLogic::utiliseLED(bool activate, const QString &pattern)
{
    QmLED led;
    if(activate)
        led.activate(pattern);
    else
        led.deactivate(pattern);
}

void BatteryBusinessLogic::togglePSMDisabled(bool disabled)
{
    qDebug() << "BatteryBusinessLogic::togglePSMDisabled(" << disabled << ")";
    systemUIGConf->setValue(SystemUIGConf::BatteryPSMDisabledKey, QVariant(disabled));
    if(disabled) //PSM disabled
        togglePSM(false);
    else
        checkPSMThreshold((Maemo::QmBattery::Level)battery->bars());
}

void BatteryBusinessLogic::setPSMThreshold(const QString &threshold)
{
    qDebug() << "BatteryBusinessLogic::setPSMthreshold(" << threshold << ")";
    systemUIGConf->setValue(SystemUIGConf::BatteryPSMThresholdKey, QVariant(threshold));
    checkPSMThreshold((Maemo::QmBattery::Level)battery->bars());
}

QVariant BatteryBusinessLogic::GConfItemValue(SystemUIGConf::GConfKey key)
{
    return systemUIGConf->value(key);
}

QStringList BatteryBusinessLogic::PSMThresholdValues()
{
    QStringList values;
    values << batteryLevels.value(QmBattery::LevelCritical)
            << batteryLevels.value(QmBattery::LevelLow)
            /* Not yet implemented in QmBattery
            << batteryLevels.value(QmBattery::Level75)
            << batteryLevels.value(QmBattery::Level50)
            << batteryLevels.value(QmBattery::Level25)
            */
            << batteryLevels.value(QmBattery::LevelFull);
    return values;

}

bool BatteryBusinessLogic::batteryChargingState()
{
    return battery->getState() == QmBattery::StateCharging;
}
<commit_msg>fast fix<commit_after>#include "batterybusinesslogic.h"
#include <qmsystem/qmled.h>

#include <QTimer>

#include <DuiLocale>
#include <DuiApplicationWindow>

BatteryBusinessLogic::BatteryBusinessLogic(SystemUIGConf *systemUIGConf) :
        systemUIGConf(systemUIGConf)
{
    battery = new QmBattery();
    deviceMode = new QmDeviceMode();
    uiNotif = new Notifier();

    /* init the battery levels */
    batteryLevels.insert(QmBattery::LevelFull, QString("100"));
    //batteryLevels.insert(QmBattery::Level75, 85); //not yet implemented
    //batteryLevels.insert(QmBattery::Level50, 60); //not yet implemented
    //batteryLevels.insert(QmBattery::Level25, 35); //not yet implemented
    batteryLevels.insert(QmBattery::LevelLow, QString("15"));
    batteryLevels.insert(QmBattery::LevelCritical, QString("5"));

    /* check if gconfvalues need to initialized */
    initSystemUIGConfKeys();

    /* connect to QmSystem signals */
    connect(battery, SIGNAL(batteryLevelChanged(Maemo::QmBattery::Level)),
            this, SLOT(batteryLevelChanged(Maemo::QmBattery::Level)));
    connect(battery, SIGNAL(batteryStateChanged(Maemo::QmBattery::State)),
            this, SLOT(batteryStateChanged(Maemo::QmBattery::State)));

    initBattery();
}

BatteryBusinessLogic::~BatteryBusinessLogic()
{
    delete uiNotif;
    uiNotif = NULL;
    delete battery;
    battery = NULL;
}

void BatteryBusinessLogic::initSystemUIGConfKeys()
{
    if(systemUIGConf->keyCount(SystemUIGConf::Battery) < 3) {
        /* GConf keys have not yet been set. */
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(deviceMode->getPSMState() == Maemo::QmDeviceMode::PSMStateOn ? true : false));
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMDisabledKey, QVariant(false));
        systemUIGConf->setValue(SystemUIGConf::BatteryPSMThresholdKey, QVariant(batteryLevels.value(QmBattery::LevelLow)));
    }
}

// This method should be called also when the device is returned from sleep mode
void BatteryBusinessLogic::initBattery()
{
    //init the charging status
    batteryStateChanged(battery->getState());

    //init the battery level
    batteryLevelChanged((QmBattery::Level)batteryLevelValue());
}

int BatteryBusinessLogic::batteryLevelPercentage()
{
    return 55; //100*battery->bars()/battery->maxBars();
}

int BatteryBusinessLogic::batteryLevelValue()
{
    int chargeLevelPercentage = batteryLevelPercentage();
    QmBattery::Level level;
    if(chargeLevelPercentage >= 85)
        level = QmBattery::LevelFull;
    /* Not yet implemented in QmBattery (not necessarily even needed)
    else if(chargeLevelPercentage < 85 && chargeLevelPercentage >= 60)
        level = QmBattery::Level75;
    else if(chargeLevelPercentage < 60 && chargeLevelPercentage >= 35)
        level = QmBattery::Level50;
    else if(chargeLevelPercentage < 35 && chargeLevelPercentage >= 15)
        level = QmBattery::Level25;
        */
    else if(chargeLevelPercentage < 15 && chargeLevelPercentage >= 5)
        level = QmBattery::LevelLow;
    else //chargeLevelPercentage < 5
        level = QmBattery::LevelCritical;

    return (int)level; //type has to be int. called elsewhere as well
}

void BatteryBusinessLogic::batteryStateChanged(Maemo::QmBattery::State state)
{
    switch(state) {
        case QmBattery::StateCharging:
            qDebug() << "Charging";
            emit batteryCharging();
            utiliseLED(true, QString("PatternBatteryCharging"));
            uiNotif->showNotification(trid("qtn_ener_char", "Charging"));
            break;
        case QmBattery::StateNotCharging:
            emit batteryNotCharging();
            utiliseLED(false, QString("PatternBatteryCharging"));
            break;
        default:
            break;
    }
}

void BatteryBusinessLogic::batteryLevelChanged(Maemo::QmBattery::Level level)
{
    emit batteryLevelValueChanged((int)level);
    checkPSMThreshold(level);

    switch(level) {
        case QmBattery::LevelFull:
            if(battery->getState() == QmBattery::StateCharging) {
                utiliseLED(true, QString("PatternBatteryFull"));
                QTimer::singleShot(5000, this, SLOT(utiliseLED(false, QString("PatternBatteryFull"))));
                uiNotif->showNotification(trid("qtn_ener_charcomp", "Charging complete"));
                uiNotif->showNotification(trid("qtn_ener_remcha", "Disconnect charger from power supply to save energy"));
            }
            break;
        case QmBattery::LevelLow:
            if(battery->getState() != QmBattery::StateCharging)
                uiNotif->showNotification(trid("qtn_ener_lowbatt", "Low battery"));
            break;
        default:
            break;
   }
}

void BatteryBusinessLogic::checkPSMThreshold(Maemo::QmBattery::Level level)
{
    qDebug() << "BatteryBusinessLogic::checkPSMThreshold(" << level << ")";
    if(level <= systemUIGConf->value(SystemUIGConf::BatteryPSMThresholdKey).toInt()) {
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOff
           && systemUIGConf->value(SystemUIGConf::BatteryPSMDisabledKey).toBool() == false) {
            // Send a notification that can be cancelled.
            // If it's not cancelled, after certain time the notifier emits a signal.
            // We catch this signal to set the PSM
            connect(uiNotif, SIGNAL(notifTimeout()), this, SLOT(activatePSM()));

            QHash<QString,QString> staticVariables;
            QString number;
            staticVariables.insert(QString("%a"), number.setNum(batteryLevelPercentage()));
            uiNotif->showCancellableNotification(trid("qtn_ener_psnote", "Battery charge level less than %a%. Switching to power save in %b seconds"),
                                                 10,
                                                 QString("%b"),
                                                 staticVariables);
        }
    }
    else {
        togglePSM(false);
    }
}

void BatteryBusinessLogic::activatePSM()
{
    qDebug() << "Activate PSM";
    disconnect(uiNotif, SIGNAL(notifTimeout()), this, SLOT(activatePSM()));
    togglePSM(true);
}

void BatteryBusinessLogic::togglePSM(bool toggle)
{
    qDebug() << "BatteryBusinessLogic::togglePSM(" << toggle << ")";
    if(toggle) { //turn on the PSM
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOff
           && systemUIGConf->value(SystemUIGConf::BatteryPSMDisabledKey).toBool() == false) {
            qDebug() << "Turn ON The PSM";
            deviceMode->setPSMState(QmDeviceMode::PSMStateOn);
            systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(toggle));
            emit PSMToggleValueChanged(toggle);
        }
    }
    else { //turn off the PSM
        if(deviceMode->getPSMState() == QmDeviceMode::PSMStateOn) {
            qDebug() << "Turn OFF The PSM";
            deviceMode->setPSMState(QmDeviceMode::PSMStateOff);
            systemUIGConf->setValue(SystemUIGConf::BatteryPSMToggleKey, QVariant(toggle));
            emit PSMToggleValueChanged(toggle);
        }
    }
}

QStringList BatteryBusinessLogic::remainingTimeValues()
{
    qDebug() << "BatteryBusinessLogic::remainingTimeValues()";

    QStringList values;

    //TODO: replace hardcoded values with correct ones and remove temp var
    static int temp = 0; //temp
    if(temp<1) {
        values << (QString("%1").arg(120))/*battery->remainingTalkTime() * 60*/ << (QString("%1").arg(300)) /*battery->remainingStandByTime() * 60 */;
        ++temp;
    }
    else {
        values << (QString("%1").arg(130))/*battery->remainingTalkTime() * 60*/ << (QString("%1").arg(350)) /*battery->remainingStandByTime() * 60 */;
        temp = 0;
    }
    return values;
}

void BatteryBusinessLogic::utiliseLED(bool activate, const QString &pattern)
{
    QmLED led;
    if(activate)
        led.activate(pattern);
    else
        led.deactivate(pattern);
}

void BatteryBusinessLogic::togglePSMDisabled(bool disabled)
{
    qDebug() << "BatteryBusinessLogic::togglePSMDisabled(" << disabled << ")";
    systemUIGConf->setValue(SystemUIGConf::BatteryPSMDisabledKey, QVariant(disabled));
    if(disabled) //PSM disabled
        togglePSM(false);
    else
        checkPSMThreshold((Maemo::QmBattery::Level)battery->bars());
}

void BatteryBusinessLogic::setPSMThreshold(const QString &threshold)
{
    qDebug() << "BatteryBusinessLogic::setPSMthreshold(" << threshold << ")";
    systemUIGConf->setValue(SystemUIGConf::BatteryPSMThresholdKey, QVariant(threshold));
    checkPSMThreshold((Maemo::QmBattery::Level)battery->bars());
}

QVariant BatteryBusinessLogic::GConfItemValue(SystemUIGConf::GConfKey key)
{
    return systemUIGConf->value(key);
}

QStringList BatteryBusinessLogic::PSMThresholdValues()
{
    QStringList values;
    values << batteryLevels.value(QmBattery::LevelCritical)
            << batteryLevels.value(QmBattery::LevelLow)
            /* Not yet implemented in QmBattery
            << batteryLevels.value(QmBattery::Level75)
            << batteryLevels.value(QmBattery::Level50)
            << batteryLevels.value(QmBattery::Level25)
            */
            << batteryLevels.value(QmBattery::LevelFull);
    return values;

}

bool BatteryBusinessLogic::batteryChargingState()
{
    return battery->getState() == QmBattery::StateCharging;
}
<|endoftext|>