<commit_before>/**
 *
 * @file ESP8266WiFiMulti.cpp
 * @date 16.05.2015
 * @author Markus Sattler
 *
 * Copyright (c) 2015 Markus Sattler. All rights reserved.
 * This file is part of the esp8266 core for Arduino environment.
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "ESP8266WiFiMulti.h"
#include <limits.h>
#include <string.h>

ESP8266WiFiMulti::ESP8266WiFiMulti() {
}

ESP8266WiFiMulti::~ESP8266WiFiMulti() {
    APlistClean();
}

bool ESP8266WiFiMulti::addAP(const char* ssid, const char *passphrase) {
    return APlistAdd(ssid, passphrase);
}

wl_status_t ESP8266WiFiMulti::run(void) {

    int8_t scanResult;
    wl_status_t status = WiFi.status();
    if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {

		ledState(1);
        scanResult = WiFi.scanComplete();
        if(scanResult == WIFI_SCAN_RUNNING) {
            // scan is running
            return WL_NO_SSID_AVAIL;
        } else if(scanResult > 0) {
            // scan done analyze
            WifiAPlist_t bestNetwork { NULL, NULL };
            int bestNetworkDb = INT_MIN;
            uint8 bestBSSID[6];
            int32_t bestChannel;

            DEBUG_WIFI_MULTI("[WIFI] scan done\n");
            delay(0);

            if(scanResult <= 0) {
                DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
            } else {
                DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult);
                for(int8_t i = 0; i < scanResult; ++i) {

                    String ssid_scan;
                    int32_t rssi_scan;
                    uint8_t sec_scan;
                    uint8_t* BSSID_scan;
                    int32_t chan_scan;
                    bool hidden_scan;

                    WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);

                    bool known = false;
                    for(uint32_t x = 0; x < APlist.size(); x++) {
                        WifiAPlist_t entry = APlist[x];
                        if(ssid_scan == entry.ssid) { // SSID match
                            known = true;
                            if(rssi_scan > bestNetworkDb) { // best network
                                if(sec_scan == ENC_TYPE_NONE || entry.passphrase) { // check for passphrase if not open wlan
                                    bestNetworkDb = rssi_scan;
                                    bestChannel = chan_scan;
                                    memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork));
                                    memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
                                }
                            }
                            break;
                        }
                    }

                    if(known) {
                        DEBUG_WIFI_MULTI(" ---> ");
                    } else {
                        DEBUG_WIFI_MULTI("      ");
                    }

                    DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == ENC_TYPE_NONE) ? ' ' : '*');
                    delay(0);
                }
            }

            // clean up ram
            WiFi.scanDelete();
			ledState(1);
            DEBUG_WIFI_MULTI("\n\n");
            delay(0);

            if(bestNetwork.ssid) {
                DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
				/*Serial.println("wifi.begin");
				Serial.println(bestNetwork.ssid);
				Serial.println(bestNetwork.passphrase);
				Serial.println(bestChannel);
				Serial.println("-------------");*/
                WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
                status = WiFi.status();
				int s = 0;
                // wait for connection or fail
                while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
                    delay(10);
					s++;
                    status = WiFi.status();
					if (s % 10 == 0) {
						ledState(1);
						if (s % 150 == 0)break;
					}
                }
				if(status==WL_CONNECTED)ledState(2);
#ifdef DEBUG_ESP_WIFI
                IPAddress ip;
                uint8_t * mac;
                switch(status) {
                    case WL_CONNECTED:
                        ip = WiFi.localIP();
                        mac = WiFi.BSSID();
                        DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
                        DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
                        DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
                        DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
                        DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
                        break;
                    case WL_NO_SSID_AVAIL:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
                        break;
                    case WL_CONNECT_FAILED:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
                        break;
                    default:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
                        break;
                }
#endif
            } else {
				ledState(3);
                DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
            }
        } else {
			ledState(3);
            // start scan
            DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
            WiFi.disconnect();

            DEBUG_WIFI_MULTI("[WIFI] start scan\n");
            // scan wifi async mode
            WiFi.scanNetworks(true);
        }
    }
    return status;
}

// ##################################################################################

bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) {

    WifiAPlist_t newAP;

    if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
        // fail SSID to long or missing!
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n");
        return false;
    }

    if(passphrase && strlen(passphrase) > 63) {
        // fail passphrase to long!
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n");
        return false;
    }

    newAP.ssid = strdup(ssid);

    if(!newAP.ssid) {
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
        return false;
    }

    if(passphrase && *passphrase != 0x00) {
        newAP.passphrase = strdup(passphrase);
        if(!newAP.passphrase) {
            DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
            free(newAP.ssid);
            return false;
        }
    }

    APlist.push_back(newAP);
    DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
    return true;
}

void ESP8266WiFiMulti::APlistClean(void) {
    for(uint32_t i = 0; i < APlist.size(); i++) {
        WifiAPlist_t entry = APlist[i];
        if(entry.ssid) {
            free(entry.ssid);
        }
        if(entry.passphrase) {
            free(entry.passphrase);
        }
    }
    APlist.clear();
}

void ESP8266WiFiMulti::ledState(int i)
{
	int j = 0;
	switch (i)
	{
	case 1://接続中
		Nefry.setLed(0x00, 0x4f, 0x00);
		delay(50);
		Nefry.setLed(0x00, 0x00, 0x00);
		break;
	case 2://接続完了
		Nefry.setLed(0x00, 0xff, 0xff);
		break;
	case 3://接続失敗
		for (j = 0; j < 4; j++) {
			Nefry.setLed(0xff, 0x00, 0x00);
			delay(50);
			Nefry.setLed(0x00, 0x00, 0x00);
			delay(50);
		}
		break;
	default:
		break;
	}
}

<commit_msg>WriteModeへの移行と検索時間の延長<commit_after>/**
 *
 * @file ESP8266WiFiMulti.cpp
 * @date 16.05.2015
 * @author Markus Sattler
 *
 * Copyright (c) 2015 Markus Sattler. All rights reserved.
 * This file is part of the esp8266 core for Arduino environment.
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "ESP8266WiFiMulti.h"
#include <limits.h>
#include <string.h>

ESP8266WiFiMulti::ESP8266WiFiMulti() {
}

ESP8266WiFiMulti::~ESP8266WiFiMulti() {
    APlistClean();
}

bool ESP8266WiFiMulti::addAP(const char* ssid, const char *passphrase) {
    return APlistAdd(ssid, passphrase);
}

wl_status_t ESP8266WiFiMulti::run(void) {

    int8_t scanResult;
    wl_status_t status = WiFi.status();
    if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {

		ledState(1);
        scanResult = WiFi.scanComplete();
        if(scanResult == WIFI_SCAN_RUNNING) {
            // scan is running
            return WL_NO_SSID_AVAIL;
        } else if(scanResult > 0) {
            // scan done analyze
            WifiAPlist_t bestNetwork { NULL, NULL };
            int bestNetworkDb = INT_MIN;
            uint8 bestBSSID[6];
            int32_t bestChannel;

            DEBUG_WIFI_MULTI("[WIFI] scan done\n");
            delay(0);

            if(scanResult <= 0) {
                DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
            } else {
                DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult);
                for(int8_t i = 0; i < scanResult; ++i) {

                    String ssid_scan;
                    int32_t rssi_scan;
                    uint8_t sec_scan;
                    uint8_t* BSSID_scan;
                    int32_t chan_scan;
                    bool hidden_scan;

                    WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);

                    bool known = false;
                    for(uint32_t x = 0; x < APlist.size(); x++) {
                        WifiAPlist_t entry = APlist[x];
                        if(ssid_scan == entry.ssid) { // SSID match
                            known = true;
                            if(rssi_scan > bestNetworkDb) { // best network
                                if(sec_scan == ENC_TYPE_NONE || entry.passphrase) { // check for passphrase if not open wlan
                                    bestNetworkDb = rssi_scan;
                                    bestChannel = chan_scan;
                                    memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork));
                                    memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
                                }
                            }
                            break;
                        }
                    }

                    if(known) {
                        DEBUG_WIFI_MULTI(" ---> ");
                    } else {
                        DEBUG_WIFI_MULTI("      ");
                    }

                    DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == ENC_TYPE_NONE) ? ' ' : '*');
                    delay(0);
                }
            }

            // clean up ram
            WiFi.scanDelete();
			ledState(1);
            DEBUG_WIFI_MULTI("\n\n");
            delay(0);

            if(bestNetwork.ssid) {
                DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
				/*Serial.println("wifi.begin");
				Serial.println(bestNetwork.ssid);
				Serial.println(bestNetwork.passphrase);
				Serial.println(bestChannel);
				Serial.println("-------------");*/
                WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
                status = WiFi.status();
				int s = 0;
                // wait for connection or fail
                while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
                    delay(10);
					s++;
                    status = WiFi.status();
					if (s % 10 == 0) {
						ledState(1);
						if (s % 250 == 0)break;
					}
					if (status == WL_CONNECTED)break;
					Nefry.push_sw_();
                }
				if(status==WL_CONNECTED)ledState(2);
#ifdef DEBUG_ESP_WIFI
                IPAddress ip;
                uint8_t * mac;
                switch(status) {
                    case WL_CONNECTED:
                        ip = WiFi.localIP();
                        mac = WiFi.BSSID();
                        DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
                        DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
                        DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
                        DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
                        DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
                        break;
                    case WL_NO_SSID_AVAIL:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
                        break;
                    case WL_CONNECT_FAILED:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
                        break;
                    default:
                        DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
                        break;
                }
#endif
            } else {
				ledState(3);
                DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
            }
        } else {
			ledState(3);
            // start scan
            DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
            WiFi.disconnect();

            DEBUG_WIFI_MULTI("[WIFI] start scan\n");
            // scan wifi async mode
            WiFi.scanNetworks(true);
        }
    }
    return status;
}

// ##################################################################################

bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) {

    WifiAPlist_t newAP;

    if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
        // fail SSID to long or missing!
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n");
        return false;
    }

    if(passphrase && strlen(passphrase) > 63) {
        // fail passphrase to long!
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n");
        return false;
    }

    newAP.ssid = strdup(ssid);

    if(!newAP.ssid) {
        DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
        return false;
    }

    if(passphrase && *passphrase != 0x00) {
        newAP.passphrase = strdup(passphrase);
        if(!newAP.passphrase) {
            DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
            free(newAP.ssid);
            return false;
        }
    }

    APlist.push_back(newAP);
    DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
    return true;
}

void ESP8266WiFiMulti::APlistClean(void) {
    for(uint32_t i = 0; i < APlist.size(); i++) {
        WifiAPlist_t entry = APlist[i];
        if(entry.ssid) {
            free(entry.ssid);
        }
        if(entry.passphrase) {
            free(entry.passphrase);
        }
    }
    APlist.clear();
}

void ESP8266WiFiMulti::ledState(int i)
{
	int j = 0;
	switch (i)
	{
	case 1://接続中
		Nefry.setLed(0x00, 0x4f, 0x00);
		delay(50);
		Nefry.setLed(0x00, 0x00, 0x00);
		break;
	case 2://接続完了
		Nefry.setLed(0x00, 0xff, 0xff);
		break;
	case 3://接続失敗
		for (j = 0; j < 4; j++) {
			Nefry.setLed(0xff, 0x00, 0x00);
			delay(50);
			Nefry.setLed(0x00, 0x00, 0x00);
			delay(50);
		}
		break;
	default:
		break;
	}
}

<|endoftext|>


<commit_before>//
//   Copyright 2013 Pixar
//
//   Licensed under the Apache License, Version 2.0 (the "Apache License")
//   with the following modification; you may not use this file except in
//   compliance with the Apache License and the following modification to it:
//   Section 6. Trademarks. is deleted and replaced with:
//
//   6. Trademarks. This License does not grant permission to use the trade
//      names, trademarks, service marks, or product names of the Licensor
//      and its affiliates, except as required to comply with Section 4(c) of
//      the License and to reproduce the content of the NOTICE file.
//
//   You may obtain a copy of the Apache License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the Apache License with the above modification is
//   distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//   KIND, either express or implied. See the Apache License for the specific
//   language governing permissions and limitations under the Apache License.
//

#include "particles.h"

#include <far/ptexIndices.h>
#include <far/patchMap.h>

#ifdef OPENSUBDIV_HAS_TBB
#include <tbb/parallel_for.h>
#include <tbb/atomic.h>
tbb::atomic<int> g_tbbCounter;
class TbbUpdateKernel {
public:
    TbbUpdateKernel(float speed,
                    STParticles::Position *positions,
                    float *velocities,
                    std::vector<STParticles::FaceInfo> const &adjacency,
                    OpenSubdiv::Osd::PatchCoord *patchCoords,
                    OpenSubdiv::Far::PatchMap const *patchMap) :
        _speed(speed), _positions(positions), _velocities(velocities),
        _adjacency(adjacency), _patchCoords(patchCoords), _patchMap(patchMap) {
    }

    void operator () (tbb::blocked_range<int> const &r) const {
        for (int i = r.begin(); i < r.end(); ++i) {
            STParticles::Position * p = _positions + i;
            float    *dp = _velocities + i*2;

            // apply velocity
            p->s += dp[0] * _speed;
            p->t += dp[1] * _speed;

            // make sure particles can't skip more than 1 face boundary at a time
            assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));

            // check if the particle is jumping a boundary
            // note: a particle can jump 2 edges at a time (a "diagonal" jump)
            //       this is not treated here.
            int edge = -1;
            if (p->s >= 1.0f) edge = 1;
            if (p->s <= 0.0f) edge = 3;
            if (p->t >= 1.0f) edge = 2;
            if (p->t <= 0.0f) edge = 0;

            if (edge>=0) {
                // warp the particle to the other side of the boundary
                STParticles::WarpParticle(_adjacency, edge, p, dp);
            }
            assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));

            // resolve particle positions into patch handles
            OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
                _patchMap->FindPatch(p->ptexIndex, p->s, p->t);
            if (handle) {
                int index = g_tbbCounter.fetch_and_add(1);
                _patchCoords[index] =
                    OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t);
            }
        }
    }
private:
    float _speed;
    STParticles::Position *_positions;
    float *_velocities;
    std::vector<STParticles::FaceInfo> const &_adjacency;
    OpenSubdiv::Osd::PatchCoord *_patchCoords;
    OpenSubdiv::Far::PatchMap const *_patchMap;
};
#endif

#include <cassert>

STParticles::STParticles(Refiner const & refiner,
                         PatchTable const *patchTable,
                         int nParticles, bool centered) :
    _speed(1.0f) {

    OpenSubdiv::Far::PtexIndices ptexIndices(refiner);

    // Create a far patch map
    _patchMap = new OpenSubdiv::Far::PatchMap(*patchTable);

    int nPtexFaces = ptexIndices.GetNumFaces();

    srand(static_cast<int>(2147483647));

    {   // initialize positions

        _positions.resize(nParticles);
        Position * pos = &_positions[0];

        for (int i = 0; i < nParticles; ++i) {
            pos->ptexIndex = (int)(((float)rand()/(float)RAND_MAX) * nPtexFaces);
            pos->s = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
            pos->t = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
            ++pos;
        }
    }

    {   // initialize velocities
        _velocities.resize(nParticles * 2);

        for (int i = 0; i < nParticles; ++i) {
            // initialize normalized random directions
            float s = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
                  t = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
                  l = sqrtf(s*s+t*t);

            _velocities[2*i  ] = s / l;
            _velocities[2*i+1] = t / l;
        }
    }

    {   // initialize topology adjacency
        _adjacency.resize(nPtexFaces);

        OpenSubdiv::Far::TopologyLevel const & refBaseLevel = refiner.GetLevel(0);

        int nfaces = refBaseLevel.GetNumFaces(),
           adjfaces[4],
           adjedges[4];

        for (int face=0, ptexface=0; face<nfaces; ++face) {

            OpenSubdiv::Far::ConstIndexArray fverts = refBaseLevel.GetFaceVertices(face);

            if (fverts.size()==4) {
                ptexIndices.GetAdjacency(refiner, face, 0, adjfaces, adjedges);
                _adjacency[ptexface] = FaceInfo(adjfaces, adjedges, false);
                ++ptexface;
            } else {
                for (int vert=0; vert<fverts.size(); ++vert) {
                    ptexIndices.GetAdjacency(refiner, face, vert, adjfaces, adjedges);
                    _adjacency[ptexface+vert] =
                        FaceInfo(adjfaces, adjedges, true);
                }
                ptexface+=fverts.size();
            }
        }
    }
    //std::cout << *this;
}

inline void
FlipS(STParticles::Position * p, float * dp) {
    p->s = 1.0f-p->s;
    dp[0] = - dp[0];
}

inline void
FlipT(STParticles::Position * p, float * dp) {
    p->t = 1.0f-p->t;
    dp[1] = - dp[1];
}

inline void
SwapST(STParticles::Position * p, float * dp) {
    std::swap(p->s, p->t);
    std::swap(dp[0], dp[1]);
}

inline void
Rotate(int rot, STParticles::Position * p, float * dp) {

    switch (rot & 3) {
        default: return;
        case 1: FlipS(p, dp); SwapST(p, dp); break;
        case 2: FlipS(p, dp); FlipT(p, dp);  break;
        case 3: FlipT(p, dp); SwapST(p, dp); break;
    }
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

inline void
Trim(STParticles::Position * p) {
    if (p->s <0.0f) p->s = 1.0f + p->s;
    if (p->s>=1.0f) p->s = p->s - 1.0f;
    if (p->t <0.0f) p->t = 1.0f + p->t;
    if (p->t>=1.0f) p->t = p->t - 1.0f;
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

inline void
Clamp(STParticles::Position * p) {
         if (p->s<0.0f) {
        p->s=0.0f;
    } else if (p->s>1.0f) {
        p->s=1.0f;
    }
         if (p->t<0.0f) {
        p->t=0.0f;
    } else if (p->t>1.0f) {
        p->t=1.0f;
    }
}

inline void
Bounce(int edge, STParticles::Position * p, float * dp) {
    switch (edge) {
        case 0: assert(p->t<=0.0f); p->t = -p->t;       dp[1] = -dp[1]; break;
        case 1: assert(p->s>=1.0f); p->s = 2.0f - p->s; dp[0] = -dp[0]; break;
        case 2: assert(p->t>=1.0f); p->t = 2.0f - p->t; dp[1] = -dp[1]; break;
        case 3: assert(p->s<=0.0f); p->s = -p->s;       dp[0] = -dp[0]; break;
    }

    // because 'diagonal' cases aren't handled, stick particles to edges when
    // if they cross 2 boundaries
    Clamp(p);
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

void
STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
                          int edge, Position * p, float * dp) {
    assert(p->ptexIndex<(int)adjacency.size() and (edge>=0 and edge<4));

    FaceInfo const & f = adjacency[p->ptexIndex];

    int afid = f.adjface(edge),
        aeid = f.adjedge(edge);

    if (afid==-1) {
        // boundary detected: bounce the particle
        Bounce(edge, p, dp);
    } else {
        FaceInfo const & af = adjacency[afid];
        int rot = edge - aeid + 2;

        bool fIsSubface = f.isSubface(),
             afIsSubface = af.isSubface();

        if (fIsSubface != afIsSubface) {
            // XXXX manuelk domain should be split properly
            Bounce(edge, p, dp);
        } else {
            Trim(p);
            Rotate(rot, p, dp);
            p->ptexIndex = afid; // move particle to adjacent face
        }
    }
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

STParticles::~STParticles() {
    delete _patchMap;
}

void
STParticles::Update(float deltaTime) {

    if (fabs(GetSpeed()) < 0.001f) return;
    float speed = GetSpeed() * std::max(0.001f, std::min(deltaTime, 0.5f));

    _patchCoords.clear();

    // XXX: this process should be parallelized.
#ifdef OPENSUBDIV_HAS_TBB

    _patchCoords.resize((int)GetNumParticles());
    TbbUpdateKernel kernel(speed, &_positions[0], &_velocities[0],
                           _adjacency, &_patchCoords[0], _patchMap);;
    g_tbbCounter = 0;
    tbb::blocked_range<int> range(0, GetNumParticles(), 256);
    tbb::parallel_for(range, kernel);
    _patchCoords.resize(g_tbbCounter);
#else
    Position *  p = &_positions[0];
    float    * dp = &_velocities[0];
    for (int i=0; i<GetNumParticles(); ++i, ++p, dp+=2) {
        // apply velocity
        p->s += dp[0] * speed;
        p->t += dp[1] * speed;

        // make sure particles can't skip more than 1 face boundary at a time
        assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));

        // check if the particle is jumping a boundary
        // note: a particle can jump 2 edges at a time (a "diagonal" jump)
        //       this is not treated here.
        int edge = -1;

        if (p->s >= 1.0f) edge = 1;
        if (p->s <= 0.0f) edge = 3;
        if (p->t >= 1.0f) edge = 2;
        if (p->t <= 0.0f) edge = 0;

        if (edge>=0) {
            // warp the particle to the other side of the boundary
            WarpParticle(_adjacency, edge, p, dp);
        }
        assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));

        // resolve particle positions into patch handles
        OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
            _patchMap->FindPatch(p->ptexIndex, p->s, p->t);
        if (handle) {
            _patchCoords.push_back(
                OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t));
        }
    }
#endif
}

// Dump adjacency info
std::ostream & operator << (std::ostream & os,
    STParticles::FaceInfo const & f) {

    os << "  adjface: " << f.adjfaces[0] << ' '
                        << f.adjfaces[1] << ' '
                        << f.adjfaces[2] << ' '
                        << f.adjfaces[3]
       << "  adjedge: " << f.adjedge(0) << ' '
                        << f.adjedge(1) << ' '
                        << f.adjedge(2) << ' '
                        << f.adjedge(3)
       << "  flags:";

    if (f.flags == 0) {
        os << " (none)";
    } else {
        if (f.isSubface()) {
            std::cout << " subface";
        }
    }
    os << std::endl;

    return os;
}

std::ostream & operator << (std::ostream & os,
    STParticles const & particles) {

    for (int i=0; i<(int)particles._adjacency.size(); ++i) {
        os << particles._adjacency[i];
    }

    return os;
}

<commit_msg>glEvalLimit: Fix an assertion failure when rand() takes RAND_MAX<commit_after>//
//   Copyright 2013 Pixar
//
//   Licensed under the Apache License, Version 2.0 (the "Apache License")
//   with the following modification; you may not use this file except in
//   compliance with the Apache License and the following modification to it:
//   Section 6. Trademarks. is deleted and replaced with:
//
//   6. Trademarks. This License does not grant permission to use the trade
//      names, trademarks, service marks, or product names of the Licensor
//      and its affiliates, except as required to comply with Section 4(c) of
//      the License and to reproduce the content of the NOTICE file.
//
//   You may obtain a copy of the Apache License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the Apache License with the above modification is
//   distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//   KIND, either express or implied. See the Apache License for the specific
//   language governing permissions and limitations under the Apache License.
//

#include "particles.h"

#include <far/ptexIndices.h>
#include <far/patchMap.h>

#ifdef OPENSUBDIV_HAS_TBB
#include <tbb/parallel_for.h>
#include <tbb/atomic.h>
tbb::atomic<int> g_tbbCounter;
class TbbUpdateKernel {
public:
    TbbUpdateKernel(float speed,
                    STParticles::Position *positions,
                    float *velocities,
                    std::vector<STParticles::FaceInfo> const &adjacency,
                    OpenSubdiv::Osd::PatchCoord *patchCoords,
                    OpenSubdiv::Far::PatchMap const *patchMap) :
        _speed(speed), _positions(positions), _velocities(velocities),
        _adjacency(adjacency), _patchCoords(patchCoords), _patchMap(patchMap) {
    }

    void operator () (tbb::blocked_range<int> const &r) const {
        for (int i = r.begin(); i < r.end(); ++i) {
            STParticles::Position * p = _positions + i;
            float    *dp = _velocities + i*2;

            // apply velocity
            p->s += dp[0] * _speed;
            p->t += dp[1] * _speed;

            // make sure particles can't skip more than 1 face boundary at a time
            assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));

            // check if the particle is jumping a boundary
            // note: a particle can jump 2 edges at a time (a "diagonal" jump)
            //       this is not treated here.
            int edge = -1;
            if (p->s >= 1.0f) edge = 1;
            if (p->s <= 0.0f) edge = 3;
            if (p->t >= 1.0f) edge = 2;
            if (p->t <= 0.0f) edge = 0;

            if (edge>=0) {
                // warp the particle to the other side of the boundary
                STParticles::WarpParticle(_adjacency, edge, p, dp);
            }
            assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));

            // resolve particle positions into patch handles
            OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
                _patchMap->FindPatch(p->ptexIndex, p->s, p->t);
            if (handle) {
                int index = g_tbbCounter.fetch_and_add(1);
                _patchCoords[index] =
                    OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t);
            }
        }
    }
private:
    float _speed;
    STParticles::Position *_positions;
    float *_velocities;
    std::vector<STParticles::FaceInfo> const &_adjacency;
    OpenSubdiv::Osd::PatchCoord *_patchCoords;
    OpenSubdiv::Far::PatchMap const *_patchMap;
};
#endif

#include <cassert>

STParticles::STParticles(Refiner const & refiner,
                         PatchTable const *patchTable,
                         int nParticles, bool centered) :
    _speed(1.0f) {

    OpenSubdiv::Far::PtexIndices ptexIndices(refiner);

    // Create a far patch map
    _patchMap = new OpenSubdiv::Far::PatchMap(*patchTable);

    int nPtexFaces = ptexIndices.GetNumFaces();

    srand(static_cast<int>(2147483647));

    {   // initialize positions

        _positions.resize(nParticles);
        Position * pos = &_positions[0];

        for (int i = 0; i < nParticles; ++i) {
            pos->ptexIndex = std::min(
                (int)(((float)rand()/(float)RAND_MAX) * nPtexFaces), nPtexFaces-1);
            pos->s = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
            pos->t = centered ? 0.5f : (float)rand()/(float)RAND_MAX;
            ++pos;
        }
    }

    {   // initialize velocities
        _velocities.resize(nParticles * 2);

        for (int i = 0; i < nParticles; ++i) {
            // initialize normalized random directions
            float s = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
                  t = 2.0f*(float)rand()/(float)RAND_MAX - 1.0f,
                  l = sqrtf(s*s+t*t);

            _velocities[2*i  ] = s / l;
            _velocities[2*i+1] = t / l;
        }
    }

    {   // initialize topology adjacency
        _adjacency.resize(nPtexFaces);

        OpenSubdiv::Far::TopologyLevel const & refBaseLevel = refiner.GetLevel(0);

        int nfaces = refBaseLevel.GetNumFaces(),
           adjfaces[4],
           adjedges[4];

        for (int face=0, ptexface=0; face<nfaces; ++face) {

            OpenSubdiv::Far::ConstIndexArray fverts = refBaseLevel.GetFaceVertices(face);

            if (fverts.size()==4) {
                ptexIndices.GetAdjacency(refiner, face, 0, adjfaces, adjedges);
                _adjacency[ptexface] = FaceInfo(adjfaces, adjedges, false);
                ++ptexface;
            } else {
                for (int vert=0; vert<fverts.size(); ++vert) {
                    ptexIndices.GetAdjacency(refiner, face, vert, adjfaces, adjedges);
                    _adjacency[ptexface+vert] =
                        FaceInfo(adjfaces, adjedges, true);
                }
                ptexface+=fverts.size();
            }
        }
    }
    //std::cout << *this;
}

inline void
FlipS(STParticles::Position * p, float * dp) {
    p->s = 1.0f-p->s;
    dp[0] = - dp[0];
}

inline void
FlipT(STParticles::Position * p, float * dp) {
    p->t = 1.0f-p->t;
    dp[1] = - dp[1];
}

inline void
SwapST(STParticles::Position * p, float * dp) {
    std::swap(p->s, p->t);
    std::swap(dp[0], dp[1]);
}

inline void
Rotate(int rot, STParticles::Position * p, float * dp) {

    switch (rot & 3) {
        default: return;
        case 1: FlipS(p, dp); SwapST(p, dp); break;
        case 2: FlipS(p, dp); FlipT(p, dp);  break;
        case 3: FlipT(p, dp); SwapST(p, dp); break;
    }
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

inline void
Trim(STParticles::Position * p) {
    if (p->s <0.0f) p->s = 1.0f + p->s;
    if (p->s>=1.0f) p->s = p->s - 1.0f;
    if (p->t <0.0f) p->t = 1.0f + p->t;
    if (p->t>=1.0f) p->t = p->t - 1.0f;
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

inline void
Clamp(STParticles::Position * p) {
         if (p->s<0.0f) {
        p->s=0.0f;
    } else if (p->s>1.0f) {
        p->s=1.0f;
    }
         if (p->t<0.0f) {
        p->t=0.0f;
    } else if (p->t>1.0f) {
        p->t=1.0f;
    }
}

inline void
Bounce(int edge, STParticles::Position * p, float * dp) {
    switch (edge) {
        case 0: assert(p->t<=0.0f); p->t = -p->t;       dp[1] = -dp[1]; break;
        case 1: assert(p->s>=1.0f); p->s = 2.0f - p->s; dp[0] = -dp[0]; break;
        case 2: assert(p->t>=1.0f); p->t = 2.0f - p->t; dp[1] = -dp[1]; break;
        case 3: assert(p->s<=0.0f); p->s = -p->s;       dp[0] = -dp[0]; break;
    }

    // because 'diagonal' cases aren't handled, stick particles to edges when
    // if they cross 2 boundaries
    Clamp(p);
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

void
STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
                          int edge, Position * p, float * dp) {
    assert(p->ptexIndex<(int)adjacency.size() and (edge>=0 and edge<4));

    FaceInfo const & f = adjacency[p->ptexIndex];

    int afid = f.adjface(edge),
        aeid = f.adjedge(edge);

    if (afid==-1) {
        // boundary detected: bounce the particle
        Bounce(edge, p, dp);
    } else {
        FaceInfo const & af = adjacency[afid];
        int rot = edge - aeid + 2;

        bool fIsSubface = f.isSubface(),
             afIsSubface = af.isSubface();

        if (fIsSubface != afIsSubface) {
            // XXXX manuelk domain should be split properly
            Bounce(edge, p, dp);
        } else {
            Trim(p);
            Rotate(rot, p, dp);
            p->ptexIndex = afid; // move particle to adjacent face
        }
    }
    assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));
}

STParticles::~STParticles() {
    delete _patchMap;
}

void
STParticles::Update(float deltaTime) {

    if (fabs(GetSpeed()) < 0.001f) return;
    float speed = GetSpeed() * std::max(0.001f, std::min(deltaTime, 0.5f));

    _patchCoords.clear();

    // XXX: this process should be parallelized.
#ifdef OPENSUBDIV_HAS_TBB

    _patchCoords.resize((int)GetNumParticles());
    TbbUpdateKernel kernel(speed, &_positions[0], &_velocities[0],
                           _adjacency, &_patchCoords[0], _patchMap);;
    g_tbbCounter = 0;
    tbb::blocked_range<int> range(0, GetNumParticles(), 256);
    tbb::parallel_for(range, kernel);
    _patchCoords.resize(g_tbbCounter);
#else
    Position *  p = &_positions[0];
    float    * dp = &_velocities[0];
    for (int i=0; i<GetNumParticles(); ++i, ++p, dp+=2) {
        // apply velocity
        p->s += dp[0] * speed;
        p->t += dp[1] * speed;

        // make sure particles can't skip more than 1 face boundary at a time
        assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f));

        // check if the particle is jumping a boundary
        // note: a particle can jump 2 edges at a time (a "diagonal" jump)
        //       this is not treated here.
        int edge = -1;

        if (p->s >= 1.0f) edge = 1;
        if (p->s <= 0.0f) edge = 3;
        if (p->t >= 1.0f) edge = 2;
        if (p->t <= 0.0f) edge = 0;

        if (edge>=0) {
            // warp the particle to the other side of the boundary
            WarpParticle(_adjacency, edge, p, dp);
        }
        assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f));

        // resolve particle positions into patch handles
        OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
            _patchMap->FindPatch(p->ptexIndex, p->s, p->t);
        if (handle) {
            _patchCoords.push_back(
                OpenSubdiv::Osd::PatchCoord(*handle, p->s, p->t));
        }
    }
#endif
}

// Dump adjacency info
std::ostream & operator << (std::ostream & os,
    STParticles::FaceInfo const & f) {

    os << "  adjface: " << f.adjfaces[0] << ' '
                        << f.adjfaces[1] << ' '
                        << f.adjfaces[2] << ' '
                        << f.adjfaces[3]
       << "  adjedge: " << f.adjedge(0) << ' '
                        << f.adjedge(1) << ' '
                        << f.adjedge(2) << ' '
                        << f.adjedge(3)
       << "  flags:";

    if (f.flags == 0) {
        os << " (none)";
    } else {
        if (f.isSubface()) {
            std::cout << " subface";
        }
    }
    os << std::endl;

    return os;
}

std::ostream & operator << (std::ostream & os,
    STParticles const & particles) {

    for (int i=0; i<(int)particles._adjacency.size(); ++i) {
        os << particles._adjacency[i];
    }

    return os;
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
                               const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
                               const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
        fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
        fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
        fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
        uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
            l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
            l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );

            if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
            }
            else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
                l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
                l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
                FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
            l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
                {
                    l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_def_mn_freq_ratio <= literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
                }
                else if ((l_def_mn_freq_ratio > literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>dis spec ops dcbf HW414958<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
                               const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
                               const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
        fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
        fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
        fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
        uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
            l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
            l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );

            if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
            }
            else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
                l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
                l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
                FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
            l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
            l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
                {
                    l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_def_mn_freq_ratio <= literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
                }
                else if ((l_def_mn_freq_ratio > literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012 QtHttpServer Project.
 * 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.
 *     * Neither the name of the QtHttpServer nor the
 *       names of its contributors may 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 QTHTTPSERVER 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.
 */

#include "qhttpreply.h"

#include <QtNetwork/QNetworkCookie>

#include "qhttpconnection_p.h"
#include "qhttprequest.h"

#include <zlib.h>

class QHttpReply::Private : public QObject
{
    Q_OBJECT
public:
    Private(QHttpConnection *c, QHttpReply *parent);

public slots:
    void close();

private:
    QHttpReply *q;
    static QHash<int, QByteArray> statusCodes;

public:
    QHttpConnection *connection;
    int status;
    QHash<QByteArray, QByteArray> rawHeaders;
    QList<QNetworkCookie> cookies;
    QByteArray data;
};

QHash<int, QByteArray> QHttpReply::Private::statusCodes;

QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
    : QObject(parent)
    , q(parent)
    , connection(c)
    , status(200)
{
    if (statusCodes.isEmpty()) {
        statusCodes.insert(100, "Continue");
        statusCodes.insert(101, "Switching Protocols");
        statusCodes.insert(200, "OK");
        statusCodes.insert(201, "Created");
        statusCodes.insert(202, "Accepted");
        statusCodes.insert(203, "Non-Authoritative Information");
        statusCodes.insert(204, "No Content");
        statusCodes.insert(205, "Reset Content");
        statusCodes.insert(206, "Partial Content");
        statusCodes.insert(300, "Multiple Choices");
        statusCodes.insert(301, "Moved Permanently");
        statusCodes.insert(302, "Found");
        statusCodes.insert(303, "See Other");
        statusCodes.insert(304, "Not Modified");
        statusCodes.insert(305, "Use Proxy");
        statusCodes.insert(307, "Temporary Redirect");
        statusCodes.insert(400, "Bad Request");
        statusCodes.insert(401, "Unauthorized");
        statusCodes.insert(402, "Payment Required");
        statusCodes.insert(403, "Forbidden");
        statusCodes.insert(404, "Not Found");
        statusCodes.insert(405, "Method Not Allowed");
        statusCodes.insert(406, "Not Acceptable");
        statusCodes.insert(407, "Proxy Authentication Required");
        statusCodes.insert(408, "Request Time-out");
        statusCodes.insert(409, "Conflict");
        statusCodes.insert(410, "Gone");
        statusCodes.insert(411, "Length Required");
        statusCodes.insert(412, "Precondition Failed");
        statusCodes.insert(413, "Request Entity Too Large");
        statusCodes.insert(414, "Request-URI Too Large");
        statusCodes.insert(415, "Unsupported Media Type");
        statusCodes.insert(416, "Requested range not satisfiable");
        statusCodes.insert(417, "Expectation Failed");
        statusCodes.insert(500, "Internal Server Error");
        statusCodes.insert(501, "Not Implemented");
        statusCodes.insert(502, "Bad Gateway");
        statusCodes.insert(503, "Service Unavailable");
        statusCodes.insert(504, "Gateway Time-out");
        statusCodes.insert(505, "HTTP Version not supported");
    }
    q->setBuffer(&data);
    q->open(QIODevice::WriteOnly);
}

void QHttpReply::Private::close()
{
    connection->write("HTTP/1.1 ");
    connection->write(QByteArray::number(status));
    connection->write(" ");
    connection->write(statusCodes.value(status));
    connection->write("\r\n");

    const QHttpRequest *request = connection->requestFor(q);
    if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) {
        QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
        if (acceptEncodings.contains("deflate")) {
            z_stream z;
            z.zalloc = NULL;
            z.zfree = NULL;
            z.opaque = NULL;

            if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
                QByteArray newData;
                unsigned char buf[1024];
                z.avail_in = data.size();
                z.next_in = reinterpret_cast<Bytef*>(data.data());
                z.avail_out = 1024;
                z.next_out = buf;
                int ret = Z_OK;
                while (ret == Z_OK) {
//                    qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
                    ret = deflate(&z, Z_FINISH);
//                    qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
                    if (ret == Z_STREAM_END) {
                        newData.append((const char*)buf, 1024 - z.avail_out);
                        data = newData;
                        rawHeaders["Content-Encoding"] = "deflate";
                        rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8();
//                        qDebug() << "END";
                        break;
                    } else if (ret != Z_OK) {
//                        qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
                    }
                    if (z.avail_out == 0) {
                        newData.append((const char*)buf, 1024);
                        z.avail_out = 1024;
                        z.next_out = buf;
                    }
                }
//                qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
            }
        }
    }

    if (!rawHeaders.contains("Content-Length")) {
        rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8());
    }
    foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
        connection->write(rawHeader);
        connection->write(": ");
        connection->write(rawHeaders.value(rawHeader));
        connection->write("\r\n");
    }

    foreach (const QNetworkCookie &cookie, cookies) {
        connection->write("Set-Cookie: ");
        connection->write(cookie.toRawForm());
        connection->write(";\r\n");
    }

    connection->write("\r\n");
    connection->write(data);
    q->deleteLater();
}

QHttpReply::QHttpReply(QHttpConnection *parent)
    : QBuffer(parent)
    , d(new Private(parent, this))
{
}

QHttpReply::~QHttpReply()
{
    delete d;
}

int QHttpReply::status() const
{
    return d->status;
}

void QHttpReply::setStatus(int status)
{
    d->status = status;
}

bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
    return d->rawHeaders.contains(headerName);
}

//QVariant QHttpReply::header(KnownHeaders header) const
//{
//    return QVariant();
//}

QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
    return d->rawHeaders.value(headerName);
}

void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
    d->rawHeaders.insert(headerName, value);
}

QList<QByteArray> QHttpReply::rawHeaderList() const
{
    return d->rawHeaders.keys();
}

const QList<QNetworkCookie> &QHttpReply::cookies() const
{
    return d->cookies;
}

void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
    if (d->cookies == cookies) return;
    d->cookies = cookies;
}

void QHttpReply::close()
{
    QBuffer::close();
//    QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
    d->close();
}

#include "qhttpreply.moc"
<commit_msg>fix a big memory leak<commit_after>/* Copyright (c) 2012 QtHttpServer Project.
 * 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.
 *     * Neither the name of the QtHttpServer nor the
 *       names of its contributors may 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 QTHTTPSERVER 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.
 */

#include "qhttpreply.h"

#include <QtNetwork/QNetworkCookie>

#include "qhttpconnection_p.h"
#include "qhttprequest.h"

#include <zlib.h>

class QHttpReply::Private : public QObject
{
    Q_OBJECT
public:
    Private(QHttpConnection *c, QHttpReply *parent);

public slots:
    void close();

private:
    QHttpReply *q;
    static QHash<int, QByteArray> statusCodes;

public:
    QHttpConnection *connection;
    int status;
    QHash<QByteArray, QByteArray> rawHeaders;
    QList<QNetworkCookie> cookies;
    QByteArray data;
};

QHash<int, QByteArray> QHttpReply::Private::statusCodes;

QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent)
    : QObject(parent)
    , q(parent)
    , connection(c)
    , status(200)
{
    if (statusCodes.isEmpty()) {
        statusCodes.insert(100, "Continue");
        statusCodes.insert(101, "Switching Protocols");
        statusCodes.insert(200, "OK");
        statusCodes.insert(201, "Created");
        statusCodes.insert(202, "Accepted");
        statusCodes.insert(203, "Non-Authoritative Information");
        statusCodes.insert(204, "No Content");
        statusCodes.insert(205, "Reset Content");
        statusCodes.insert(206, "Partial Content");
        statusCodes.insert(300, "Multiple Choices");
        statusCodes.insert(301, "Moved Permanently");
        statusCodes.insert(302, "Found");
        statusCodes.insert(303, "See Other");
        statusCodes.insert(304, "Not Modified");
        statusCodes.insert(305, "Use Proxy");
        statusCodes.insert(307, "Temporary Redirect");
        statusCodes.insert(400, "Bad Request");
        statusCodes.insert(401, "Unauthorized");
        statusCodes.insert(402, "Payment Required");
        statusCodes.insert(403, "Forbidden");
        statusCodes.insert(404, "Not Found");
        statusCodes.insert(405, "Method Not Allowed");
        statusCodes.insert(406, "Not Acceptable");
        statusCodes.insert(407, "Proxy Authentication Required");
        statusCodes.insert(408, "Request Time-out");
        statusCodes.insert(409, "Conflict");
        statusCodes.insert(410, "Gone");
        statusCodes.insert(411, "Length Required");
        statusCodes.insert(412, "Precondition Failed");
        statusCodes.insert(413, "Request Entity Too Large");
        statusCodes.insert(414, "Request-URI Too Large");
        statusCodes.insert(415, "Unsupported Media Type");
        statusCodes.insert(416, "Requested range not satisfiable");
        statusCodes.insert(417, "Expectation Failed");
        statusCodes.insert(500, "Internal Server Error");
        statusCodes.insert(501, "Not Implemented");
        statusCodes.insert(502, "Bad Gateway");
        statusCodes.insert(503, "Service Unavailable");
        statusCodes.insert(504, "Gateway Time-out");
        statusCodes.insert(505, "HTTP Version not supported");
    }
    q->setBuffer(&data);
    q->open(QIODevice::WriteOnly);
}

void QHttpReply::Private::close()
{
    connection->write("HTTP/1.1 ");
    connection->write(QByteArray::number(status));
    connection->write(" ");
    connection->write(statusCodes.value(status));
    connection->write("\r\n");

    const QHttpRequest *request = connection->requestFor(q);
    if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) {
        QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(',');
        if (acceptEncodings.contains("deflate")) {
            z_stream z;
            z.zalloc = NULL;
            z.zfree = NULL;
            z.opaque = NULL;

            if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) {
                QByteArray newData;
                unsigned char buf[1024];
                z.avail_in = data.size();
                z.next_in = reinterpret_cast<Bytef*>(data.data());
                z.avail_out = 1024;
                z.next_out = buf;
                int ret = Z_OK;
                while (ret == Z_OK) {
//                    qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out;
                    ret = deflate(&z, Z_FINISH);
//                    qDebug() << Q_FUNC_INFO << __LINE__ << z.avail_in << z.avail_out << ret;
                    if (ret == Z_STREAM_END) {
                        newData.append((const char*)buf, 1024 - z.avail_out);
                        data = newData;
                        rawHeaders["Content-Encoding"] = "deflate";
                        rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8();
//                        qDebug() << "END";
                        break;
                    } else if (ret != Z_OK) {
//                        qDebug() << Q_FUNC_INFO << __LINE__ << ret << z.msg;
                    }
                    if (z.avail_out == 0) {
                        newData.append((const char*)buf, 1024);
                        z.avail_out = 1024;
                        z.next_out = buf;
                    }
                }
                deflateEnd(&z);
//                qDebug() << Q_FUNC_INFO << __LINE__ << newData.length();
            }
        }
    }

    if (!rawHeaders.contains("Content-Length")) {
        rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8());
    }
    foreach (const QByteArray &rawHeader, rawHeaders.keys()) {
        connection->write(rawHeader);
        connection->write(": ");
        connection->write(rawHeaders.value(rawHeader));
        connection->write("\r\n");
    }

    foreach (const QNetworkCookie &cookie, cookies) {
        connection->write("Set-Cookie: ");
        connection->write(cookie.toRawForm());
        connection->write(";\r\n");
    }

    connection->write("\r\n");
    connection->write(data);
    q->deleteLater();
}

QHttpReply::QHttpReply(QHttpConnection *parent)
    : QBuffer(parent)
    , d(new Private(parent, this))
{
}

QHttpReply::~QHttpReply()
{
    delete d;
}

int QHttpReply::status() const
{
    return d->status;
}

void QHttpReply::setStatus(int status)
{
    d->status = status;
}

bool QHttpReply::hasRawHeader(const QByteArray &headerName) const
{
    return d->rawHeaders.contains(headerName);
}

//QVariant QHttpReply::header(KnownHeaders header) const
//{
//    return QVariant();
//}

QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const
{
    return d->rawHeaders.value(headerName);
}

void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
{
    d->rawHeaders.insert(headerName, value);
}

QList<QByteArray> QHttpReply::rawHeaderList() const
{
    return d->rawHeaders.keys();
}

const QList<QNetworkCookie> &QHttpReply::cookies() const
{
    return d->cookies;
}

void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies)
{
    if (d->cookies == cookies) return;
    d->cookies = cookies;
}

void QHttpReply::close()
{
    QBuffer::close();
//    QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection);
    d->close();
}

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


<commit_before>#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <sstream>

#include <engine/gfx/Shader.hpp>
using namespace std;

namespace
{

boost::expected<std::string, std::string>
load_shader_from_cstring_path(char const* path)
{
  // Read the Vertex Shader code from the file
  std::ifstream istream(path, std::ios::in);
  std::stringstream sstream;

  if (! istream.is_open()) {
    return boost::make_unexpected("Error opening file at path '" + std::string{path} + "'");
  }

  std::string next_line = "";
  while(std::getline(istream, next_line)) {
    sstream << "\n" << next_line;
  }
  // explicit, dtor should do this.
  istream.close();
  return sstream.str();
}

} // ns anonymous

namespace engine
{
namespace gfx
{

boost::expected<GLuint, std::string>
compile_shader(char const* data, GLenum const type)
{
  GLuint const handle = glCreateShader(type);

  // TODO: move this into std::utils, something like std::vec::with_size() (also with_capacity())
  auto vec_with_size = [](auto const size) {
    std::vector<char> buffer;
    buffer.resize(size);
    return buffer;
  };

  // Compile Vertex Shader
  glShaderSource(handle, 1, &data, nullptr);
  glCompileShader(handle);

  // Check Vertex Shader
  GLint is_compiled = GL_FALSE;
  glGetShaderiv(handle, GL_COMPILE_STATUS, &is_compiled);
  if (is_compiled) {
    return handle;
  }
  GLint InfoLogLength = 0;
  glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &InfoLogLength);
  if (0 > InfoLogLength) {
    auto constexpr err = "Compiling shader failed and could not retrieve OpenGL Log info for object";
    return boost::make_unexpected(err);
  }

  auto const buffer_size = InfoLogLength + 1; // +1 for null terminator character '\0'
  auto buffer = vec_with_size(buffer_size);
  glGetShaderInfoLog(handle, buffer_size, nullptr, buffer.data());
  return boost::make_unexpected( std::string{buffer.cbegin(), buffer.cend()} );
}

template<typename T>
boost::expected<GLuint, std::string>
compile_shader(T const& data, GLenum const type)
{ return compile_shader(data.c_str(), type); }

boost::expected<GLuint, std::string>
LoadShaders(char const* vertex_file_path, char const* fragment_file_path)
{
  // Create the shaders
#define ONLY_OK(VAR_DECL, V, expr) \
    auto V = expr; \
    if (! V) { return boost::make_unexpected(V.error()); } \
    VAR_DECL = *V;

#define ONLY_OK_HELPER(VAR_DECL, V, expr) \
  ONLY_OK(VAR_DECL, expected_##V, expr)

#define ONLY_IFOK_HELPER(VAR_DECL, to_concat, expr) \
  ONLY_OK_HELPER(VAR_DECL, to_concat, expr)

#define DO_MONAD(VAR_DECL, expr) ONLY_IFOK_HELPER(VAR_DECL, __COUNTER__, expr)

  // Read the Vertex Shader code from the file
  DO_MONAD(auto vertex_shader_source, load_shader_from_cstring_path(vertex_file_path));

  // Read the Fragment Shader code from the file
  DO_MONAD(auto fragment_shader_source, load_shader_from_cstring_path(fragment_file_path));

  DO_MONAD(GLuint const VertexShaderID, compile_shader(vertex_shader_source, GL_VERTEX_SHADER));
  DO_MONAD(GLuint const FragmentShaderID, compile_shader(fragment_shader_source, GL_FRAGMENT_SHADER));

  // Link the program
  printf("Linking program\n");
  GLuint const ProgramID = glCreateProgram();
  if (0 == ProgramID) {
    return boost::make_unexpected("GlCreateProgram returned 0.");
  }
  glAttachShader(ProgramID, VertexShaderID);
  glAttachShader(ProgramID, FragmentShaderID);
  glLinkProgram(ProgramID);

  // Check the program
  GLint Result;
  glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
  if (Result == GL_FALSE) {
    printf("%s\n", "Linking the shader failed.");
  }
  GLint InfoLogLength;
  glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
  if ( InfoLogLength > 1 ) {
    std::vector<char> ProgramErrorMessage(InfoLogLength+1);
    glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
    printf("there was an error.");
    printf("%s\n", &ProgramErrorMessage[0]);
  }

  glDetachShader(ProgramID, VertexShaderID);
  glDetachShader(ProgramID, FragmentShaderID);

  glDeleteShader(VertexShaderID);
  glDeleteShader(FragmentShaderID);
  return ProgramID;
}

} // ns gfx
} // ns engine
<commit_msg>Some refactoring<commit_after>#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <sstream>

#include <engine/gfx/Shader.hpp>

namespace
{

// TODO: move to util function
boost::expected<std::string, std::string>
read_file(char const* path)
{
  // Read the Vertex Shader code from the file
  std::ifstream istream(path, std::ios::in);
  std::stringstream sstream;

  if (! istream.is_open()) {
    return boost::make_unexpected("Error opening file at path '" + std::string{path} + "'");
  }

  std::string next_line = "";
  while(std::getline(istream, next_line)) {
    sstream << "\n" << next_line;
  }
  // explicit, dtor should do this.
  istream.close();
  return sstream.str();
}

inline bool
is_compiled(GLuint const handle)
{
  GLint is_compiled = GL_FALSE;
  glGetShaderiv(handle, GL_COMPILE_STATUS, &is_compiled);
  return GL_FALSE != is_compiled;
}

inline void
gl_compile_shader(GLuint const handle, char const* source)
{
  GLint *p_length = nullptr;
  auto constexpr shader_count = 1; // We're only compiling one shader (in this function anyway).
  glShaderSource(handle, 1, &source, p_length);
  glCompileShader(handle);
}

} // ns anonymous

namespace engine
{
namespace gfx
{

// TODO: export as reusable fn
// also, make an abstraction over the source, not just vector<char>
inline std::string
retrieve_shader_log(GLuint const handle)
{
  // We have to do a low-level dance to get the OpenGL shader logs.
  //
  // 1. Ask OpenGL how buffer space we need to retrieve the buffer.
  // 2. Retrieve the data into our buffer.
  // 3. Return the buffer.

  // TODO: move this into std::utils, something like std::vec::with_size() (also with_capacity())
  auto vec_with_size = [](auto const size) {
    std::vector<char> buffer;
    buffer.resize(size);
    return buffer;
  };

  // Step 1
  GLint log_length = 0;
  glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
  if (0 > log_length) {
    // fix this msg
    return "Compiling shader failed and could not retrieve OpenGL Log info for object";
  }

  // Step 2
  auto const buffer_size = log_length + 1; // +1 for null terminator character '\0'
  auto buffer = vec_with_size(buffer_size);
  glGetShaderInfoLog(handle, buffer_size, nullptr, buffer.data());

  // Step 3
  return std::string{buffer.cbegin(), buffer.cend()};
}

boost::expected<GLuint, std::string>
compile_shader(char const* data, GLenum const type)
{
  GLuint const handle = glCreateShader(type);
  gl_compile_shader(handle, data);

  // Check Vertex Shader
  if (true == is_compiled(handle)) {
    return handle;
  }
  return boost::make_unexpected(retrieve_shader_log(handle));
}

template<typename T>
boost::expected<GLuint, std::string>
compile_shader(T const& data, GLenum const type)
{ return compile_shader(data.c_str(), type); }

boost::expected<GLuint, std::string>
LoadShaders(char const* vertex_file_path, char const* fragment_file_path)
{
  // Create the shaders
#define ONLY_OK(VAR_DECL, V, expr) \
    auto V = expr; \
    if (! V) { return boost::make_unexpected(V.error()); } \
    VAR_DECL = *V;

#define ONLY_OK_HELPER(VAR_DECL, V, expr) \
  ONLY_OK(VAR_DECL, expected_##V, expr)

#define ONLY_IFOK_HELPER(VAR_DECL, to_concat, expr) \
  ONLY_OK_HELPER(VAR_DECL, to_concat, expr)

#define DO_MONAD(VAR_DECL, expr) ONLY_IFOK_HELPER(VAR_DECL, __COUNTER__, expr)

  // Read the Vertex Shader code from the file
  DO_MONAD(auto vertex_shader_source, read_file(vertex_file_path));

  // Read the Fragment Shader code from the file
  DO_MONAD(auto fragment_shader_source, read_file(fragment_file_path));

  DO_MONAD(GLuint const VertexShaderID, compile_shader(vertex_shader_source, GL_VERTEX_SHADER));
  DO_MONAD(GLuint const FragmentShaderID, compile_shader(fragment_shader_source, GL_FRAGMENT_SHADER));

  // Link the program
  printf("Linking program\n");
  GLuint const ProgramID = glCreateProgram();
  if (0 == ProgramID) {
    return boost::make_unexpected("GlCreateProgram returned 0.");
  }
  glAttachShader(ProgramID, VertexShaderID);
  glAttachShader(ProgramID, FragmentShaderID);
  glLinkProgram(ProgramID);

  // Check the program
  GLint Result;
  glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
  if (Result == GL_FALSE) {
    printf("%s\n", "Linking the shader failed.");
  }
  GLint InfoLogLength;
  glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
  if ( InfoLogLength > 1 ) {
    std::vector<char> ProgramErrorMessage(InfoLogLength+1);
    glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
    printf("there was an error.");
    printf("%s\n", &ProgramErrorMessage[0]);
  }

  glDetachShader(ProgramID, VertexShaderID);
  glDetachShader(ProgramID, FragmentShaderID);

  glDeleteShader(VertexShaderID);
  glDeleteShader(FragmentShaderID);
  return ProgramID;
}

} // ns gfx
} // ns engine
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlithlp.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: dvo $ $Date: 2001-07-09 20:10:43 $
 *
 *  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 _SW_XMLITHLP_HXX
#define _SW_XMLITHLP_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include <xmloff/xmlement.hxx>
#endif

class SvxBorderLine;
struct SvXMLEnumMapEntry;
class SvXMLUnitConverter;
class Color;
enum SvxGraphicPosition;
namespace rtl { class OUString; }

/** Define various helper variables and functions for xmlimpit.cxx and
 * xmlexpit.cxx.  */

#define SVX_XML_BORDER_STYLE_NONE 0
#define SVX_XML_BORDER_STYLE_SOLID 1
#define SVX_XML_BORDER_STYLE_DOUBLE 2

#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2

sal_Bool lcl_frmitems_parseXMLBorder( const ::rtl::OUString& rValue,
                                      const SvXMLUnitConverter& rUnitConverter,
                                      sal_Bool& rHasStyle, sal_uInt16& rStyle,
                                      sal_Bool& rHasWidth, sal_uInt16& rWidth,
                                      sal_uInt16& rNamedWidth,
                                      sal_Bool& rHasColor, Color& rColor );

void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
                                     sal_uInt16 nOutWidth, sal_uInt16 nInWidth,
                                     sal_uInt16 nDistance );

void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
                                     sal_uInt16 nWidth, sal_Bool bDouble );

sal_Bool lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
                                    sal_Bool bHasStyle, sal_uInt16 nStyle,
                                    sal_Bool bHasWidth, sal_uInt16 nWidth,
                                    sal_uInt16 nNamedWidth,
                                    sal_Bool bHasColor, const Color& rColor );

void lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
                                sal_uInt16 nWidth, sal_uInt16 nOutWidth,
                                sal_uInt16 nInWidth, sal_uInt16 nDistance );

void lcl_frmitems_MergeXMLHoriPos( SvxGraphicPosition& ePos,
                                   SvxGraphicPosition eHori );

void lcl_frmitems_MergeXMLVertPos( SvxGraphicPosition& ePos,
                                     SvxGraphicPosition eVert );

extern const sal_uInt16 aSBorderWidths[];
extern const sal_uInt16 aDBorderWidths[5*11];

extern const struct SvXMLEnumMapEntry psXML_BorderStyles[];
extern const struct SvXMLEnumMapEntry psXML_NamedBorderWidths[];
extern const struct SvXMLEnumMapEntry psXML_BrushRepeat[];
extern const struct SvXMLEnumMapEntry psXML_BrushHoriPos[];
extern const struct SvXMLEnumMapEntry psXML_BrushVertPos[];
extern const struct SvXMLEnumMapEntry psXML_BreakType[];
extern const struct SvXMLEnumMapEntry aXMLTableAlignMap[];
extern const struct SvXMLEnumMapEntry aXMLTableVAlignMap[];

#endif
<commit_msg>fixed header to include definition of enum SvxGraphicsPosition<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlithlp.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dvo $ $Date: 2001-07-12 14:42:19 $
 *
 *  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 _SW_XMLITHLP_HXX
#define _SW_XMLITHLP_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include <xmloff/xmlement.hxx>
#endif

#ifndef _HINTIDS_HXX
#include "hintids.hxx"  // for following include
#endif

#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx> // for SvxGraphicsPosition
#endif

class SvxBorderLine;
struct SvXMLEnumMapEntry;
class SvXMLUnitConverter;
class Color;
namespace rtl { class OUString; }

/** Define various helper variables and functions for xmlimpit.cxx and
 * xmlexpit.cxx.  */

#define SVX_XML_BORDER_STYLE_NONE 0
#define SVX_XML_BORDER_STYLE_SOLID 1
#define SVX_XML_BORDER_STYLE_DOUBLE 2

#define SVX_XML_BORDER_WIDTH_THIN 0
#define SVX_XML_BORDER_WIDTH_MIDDLE 1
#define SVX_XML_BORDER_WIDTH_THICK 2

sal_Bool lcl_frmitems_parseXMLBorder( const ::rtl::OUString& rValue,
                                      const SvXMLUnitConverter& rUnitConverter,
                                      sal_Bool& rHasStyle, sal_uInt16& rStyle,
                                      sal_Bool& rHasWidth, sal_uInt16& rWidth,
                                      sal_uInt16& rNamedWidth,
                                      sal_Bool& rHasColor, Color& rColor );

void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
                                     sal_uInt16 nOutWidth, sal_uInt16 nInWidth,
                                     sal_uInt16 nDistance );

void lcl_frmitems_setXMLBorderWidth( SvxBorderLine& rLine,
                                     sal_uInt16 nWidth, sal_Bool bDouble );

sal_Bool lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
                                    sal_Bool bHasStyle, sal_uInt16 nStyle,
                                    sal_Bool bHasWidth, sal_uInt16 nWidth,
                                    sal_uInt16 nNamedWidth,
                                    sal_Bool bHasColor, const Color& rColor );

void lcl_frmitems_setXMLBorder( SvxBorderLine*& rpLine,
                                sal_uInt16 nWidth, sal_uInt16 nOutWidth,
                                sal_uInt16 nInWidth, sal_uInt16 nDistance );

void lcl_frmitems_MergeXMLHoriPos( SvxGraphicPosition& ePos,
                                   SvxGraphicPosition eHori );

void lcl_frmitems_MergeXMLVertPos( SvxGraphicPosition& ePos,
                                     SvxGraphicPosition eVert );

extern const sal_uInt16 aSBorderWidths[];
extern const sal_uInt16 aDBorderWidths[5*11];

extern const struct SvXMLEnumMapEntry psXML_BorderStyles[];
extern const struct SvXMLEnumMapEntry psXML_NamedBorderWidths[];
extern const struct SvXMLEnumMapEntry psXML_BrushRepeat[];
extern const struct SvXMLEnumMapEntry psXML_BrushHoriPos[];
extern const struct SvXMLEnumMapEntry psXML_BrushVertPos[];
extern const struct SvXMLEnumMapEntry psXML_BreakType[];
extern const struct SvXMLEnumMapEntry aXMLTableAlignMap[];
extern const struct SvXMLEnumMapEntry aXMLTableVAlignMap[];

#endif
<|endoftext|>