blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
cac2367cfa0119c9b372a4b7328a03b69ff1e4e3
ee2e06bda0a5a2c70a0b9bebdd4c45846f440208
/c++/Pattern/Source/ChainOfResponsibility/Main.cpp
ec8378064086249b5d72ee5ddb6b5eacf467258b
[]
no_license
RobinLiu/Test
0f53a376e6753ece70ba038573450f9c0fb053e5
360eca350691edd17744a2ea1b16c79e1a9ad117
refs/heads/master
2021-01-01T19:46:55.684640
2011-07-06T13:53:07
2011-07-06T13:53:07
1,617,721
2
0
null
null
null
null
GB18030
C++
false
false
547
cpp
/******************************************************************** created: 2006/07/20 filename: Main.cpp author: 李创 http://www.cppblog.com/converse/ purpose: ChainOfResponsibility模式的测试代码 *********************************************************************/ #include "ChainOfResponsibility.h" #include <stdlib.h> int main() { Handler *p1 = new ConcreateHandler1(); Handler *p2 = new ConcreateHandler2(p1); p2->HandleRequset(); delete p2; system("pause"); return 0; }
[ "[email protected]@43938a50-64aa-11de-9867-89bd1bae666e" ]
[ [ [ 1, 25 ] ] ]
694b1bf3590f957159fb3e32c74899102a1014ff
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nrenderpath/nrenderpath2.cc
775819054a8b4ddec121b4c74ae7bd92d65ecc3f
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,633
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nRenderPath2.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nrenderpath/nRenderPath2.h" //#include "nrenderpath/nrprendertarget.h" #include "nrenderpath/nrpxmlparser.h" //------------------------------------------------------------------------------ /** */ nRenderPath2::nRenderPath2() : isOpen(false), inBegin(false), sequenceShaderIndex(0) { // empty } //------------------------------------------------------------------------------ /** */ nRenderPath2::~nRenderPath2() { // empty } //------------------------------------------------------------------------------ /** Open the XML document. This will just load the XML document and initialize the shader path. The rest of the initialization happens inside nRenderPath2::Open(). This 2-step approach is necessary to prevent a shader initialization chicken/egg problem */ bool nRenderPath2::OpenXml() { this->xmlParser.SetRenderPath(this); if (!this->xmlParser.OpenXml()) { return false; } n_assert(!this->shaderPath.IsEmpty()); n_assert(!this->name.IsEmpty()); return true; } //------------------------------------------------------------------------------ /** Close the XML document. This method should be called after nRenderPath2::Open() to release the memory assigned to the XML document data. */ void nRenderPath2::CloseXml() { this->xmlParser.CloseXml(); } //------------------------------------------------------------------------------ /** Open the render path. This will parse the xml file which describes the render path and configure the render path object from it. */ bool nRenderPath2::Open() { n_assert(!this->isOpen); n_assert(!this->inBegin); this->phaseShaderIndex = 0; this->sequenceShaderIndex = 0; if (!xmlParser.ParseXml()) { return false; } this->Validate(); this->isOpen = true; return true; } //------------------------------------------------------------------------------ /** Close the render path. This will delete all embedded objects. */ void nRenderPath2::Close() { n_assert(this->isOpen); n_assert(!this->inBegin); this->name.Clear(); for (int index = 0; index < this->passes.Size(); ++index) { this->passes[index].ReleaseTextures(); } this->passes.Clear(); this->renderTargets.Clear(); this->isOpen = false; } //------------------------------------------------------------------------------ /** Begin rendering the render path. This will validate all embedded objects. Returns the number of scene passes in the render path. After begin, each pass should be "rendered" recursively. */ int nRenderPath2::Begin() { n_assert(!this->inBegin); this->inBegin = true; return this->passes.Size(); } //------------------------------------------------------------------------------ /** Finish rendering the render path. */ void nRenderPath2::End() { n_assert(this->inBegin); this->inBegin = false; } //------------------------------------------------------------------------------ /** Validate the render path. This will simply invoke Validate() on all render targets and pass objects. */ void nRenderPath2::Validate() { n_assert(!this->isOpen); // reset index of phases and indices this->phaseShaderIndex = 0; this->sequenceShaderIndex = 0; // validate render targets int numRenderTargets = this->renderTargets.Size(); for (int index = 0; index < numRenderTargets; ++index) { this->renderTargets[index].Validate(); } // validate shaders int numShaders = this->shaders.Size(); for (int index = 0; index < numShaders; ++index) { this->shaders[index].Validate(); } // validate passes int passIndex; int numPasses = this->passes.Size(); for (passIndex = 0; passIndex < numPasses; passIndex++) { this->passes[passIndex].SetRenderPath(this); this->passes[passIndex].Validate(); } // at the end of this process, we have the number of sequence shaders } //------------------------------------------------------------------------------ /** Find a render target by name. */ nRpRenderTarget* nRenderPath2::FindRenderTarget(const nString& n) const { int i; int num = this->renderTargets.Size(); for (i = 0; i < num; i++) { if (this->renderTargets[i].GetName() == n) { return &(this->renderTargets[i]); } } // fallthrough: not found return 0; } //------------------------------------------------------------------------------ /** */ void nRenderPath2::AddRenderTarget(nRpRenderTarget& rt) { rt.Validate(); this->renderTargets.Append(rt); } //------------------------------------------------------------------------------ /** Find a shader definition index by its name. Return -1 if not found. */ int nRenderPath2::FindShaderIndex(const char* name) const { int num = this->shaders.Size(); for (int index = 0; index < num; ++index) { if (strcmp(this->shaders[index].GetName(), name) == 0) { return index; } } // fallthrough: not found return -1; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 217 ] ] ]
51c1464a51f1e9d746c9acb39c63dbe30d0c4998
c5db5e5afdf4156baf1f6fcc2aafa2b00dd277bd
/FreeOrion/client/human/chmain.h
ce918550e685a5b7fa8dfcd063d1505cfeb6c126
[]
no_license
dbuksbaum/FreeOrion
9b3158ca6e977c39c3384fcb407f9cfd57bd4bea
a9d1dc663334a51737fbe1e7fd743576c05ff768
refs/heads/master
2023-08-17T10:21:38.565335
2011-12-23T13:21:40
2011-12-23T13:21:40
3,041,422
3
0
null
null
null
null
UTF-8
C++
false
false
147
h
// -*- C++ -*- #ifndef _CHMAIN_H #define _CHMAIN_H int mainConfigOptionsSetup(int argc, char* argv[]); int mainSetupAndRunOgre(); #endif
[ "geoffthemedio@dbd5520b-6a0a-0410-a553-f54834df5b05" ]
[ [ [ 1, 8 ] ] ]
7173ce826c5627f3e2699ac106cd296ede82ef93
b5ab57edece8c14a67cc98e745c7d51449defcff
/CD - Sprint 1/Captain's Log - Code/MainGame/Source/GameObjects/CItem.cpp
6e5756885a929c9b916294ed569b4f4aef8e194a
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
156
cpp
#include "CItem.h" void CItem::Collect() { } void CItem::AddEffect() { } void CItem::RemoveEffect() { } void CItem::Drop() { }
[ "dpmakin@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 21 ] ] ]
9daa427dc4bf79efa5a2d9a3dd1708a674fb4248
52ee98d8e00d66f71139a2e86f1464244eb1616b
/reverse.cpp
6e6bfff132dbd16b3614749d32bc3c8ac1823999
[]
no_license
shaoyang/algorithm
ea0784e2b92465e54517016a7a8623c109ac9fc1
571b6423f5cf7c4bee21ff99b69b972d491c970d
refs/heads/master
2016-09-05T12:37:14.878376
2011-03-22T16:21:58
2011-03-22T16:21:58
1,502,765
0
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
#include<iostream> using namespace std; typedef struct Node{ int data; Node* next; }Node; Node* reverse(Node* head){ if(head==NULL) return NULL; if(head->next == NULL) return head; Node* prev = head; Node* cur = head->next; head->next = NULL; if(cur==NULL) cout<<"NULL"<<endl; Node* temp; while(cur != NULL){ //cout<<cur->data; temp = cur->next; cur->next = prev; prev = cur; cur = temp; } return prev; } int main(){ int i=2; Node* head; Node* cur; head = new Node; head->data = 1; head->next = NULL; cur = head; while(i<10){ Node* temp = new Node; temp->data = i; temp->next = NULL; cur->next = temp; cur = temp; i++; } head = reverse(head); cur = head; while(cur!=NULL){ cout<<cur->data<<" "; cur = cur->next; } system("pause"); return 0; }
[ [ [ 1, 53 ] ] ]
83e0d4012ea24e9c3e874d5c01fa78a9336621b3
27651c3f5f829bff0720d7f835cfaadf366ee8fa
/QBluetooth/Connection/SerialPort/Server/Impl/QBtSerialPortServer_stub.cpp
93b9c6ec5608f53c9ed52ffaa428b8a86f1ff5d1
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
cpscotti/Push-Snowboarding
8883907e7ee2ddb9a013faf97f2d9673b9d0fad5
cc3cc940292d6d728865fe38018d34b596943153
refs/heads/master
2021-05-27T16:35:49.846278
2011-07-08T10:25:17
2011-07-08T10:25:17
1,395,155
1
1
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
/* * QBtSerialPortServer_stub.cpp * * * Author: Ftylitakis Nikolaos * * 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. */ #include "../QBtSerialPortServer_stub.h" QBtSerialPortServerPrivate::QBtSerialPortServerPrivate(QBtSerialPortServer* publicClass) : p_ptr(publicClass) { } QBtSerialPortServerPrivate::~QBtSerialPortServerPrivate() { } void QBtSerialPortServerPrivate::StartListener() { } void QBtSerialPortServerPrivate::StopListener() { } void QBtSerialPortServerPrivate::SendData(const QString data) { }
[ "cpscotti@c819a03f-852d-4de4-a68c-c3ac47756727" ]
[ [ [ 1, 45 ] ] ]
4e2de770d4470f9964f9418e6f69dd9e683ac042
61c263eb77eb64cf8ab42d2262fc553ac51a6399
/src/RageDisplay_OGL.cpp
aaf40e2d9716ee9bdef5930edd2a43984e69f523
[]
no_license
ycaihua/fingermania
20760830f6fe7c48aa2332b67f455eef8f9246a3
daaa470caf02169ea6533669aa511bf59f896805
refs/heads/master
2021-01-20T09:36:38.221802
2011-01-23T12:31:19
2011-01-23T12:31:19
40,102,565
1
0
null
null
null
null
UTF-8
C++
false
false
61,522
cpp
#include "global.h" #include "RageDisplay_OGL.h" #include "RageDisplay_OGL_Helpers.h" using namespace RageDisplay_OGL_Helpers; #include "RageFile.h" #include "RageSurface.h" #include "RageSurfaceUtils.h" #include "RageUtil.h" #include "RageLog.h" #include "RageTextureManager.h" #include "RageMath.h" #include "RageTypes.h" #include "RageUtil.h" #include "EnumHelper.h" #include "Foreach.h" #include "DisplayResolutions.h" #include "LocalizedString.h" #include "arch/LowLevelWindow/LowLevelWindow.h" #include <set> #if defined(_MSC_VER) #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") #endif #ifdef NO_GL_FLUSH #define glFlush() #endif static bool g_bReversePackedPixelsWorks = true; static bool g_bColorIndexTableWorks = true; static float g_line_range[2]; static float g_point_range[2]; static int g_glVersion; static int g_gluVersion; static int g_iMaxTextureUnits = 0; static const GLenum RageSpriteVertexFormat = GL_T2F_C4F_N3F_V3F; static GLhandleARB g_bTextureMatrixShader = 0; static map<unsigned, RenderTarget*> g_mapRenderTargets; static RenderTarget* g_pCurrentRenderTarget = NULL; static LowLevelWindow* g_pWind; static bool g_bInvertY = false; static void InvalidateObjects(); static RageDisplay::PixelFormatDesc PIXEL_FORMAT_DESC[NUM_PixelFormat] = { { 32, { 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF } }, { 32, { 0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF, } }, { 16, { 0xF000, 0x0F00, 0x00F0, 0x000F, } }, { 16, { 0xF800, 0x07C0, 0x003E, 0x0001, } }, { 16, { 0xF800, 0x07C0, 0x003E, 0x0000 } }, { 24, { 0xFF0000, 0x00FF00, 0x0000FF, 0x000000 } }, { 8, { 0, 0, 0, 0 } }, { 24, { 0x0000FF, 0x00FF00, 0xFF0000, 0x000000 } }, { 16, { 0x7C00, 0x03E0, 0x001F, 0x0000 } } }; struct GLPixFmtInfo_t { GLenum internalfmt; GLenum format; GLenum type; } const g_GLPixFmtInfo[NUM_PixelFormat] = { { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, }, { GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, }, { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, }, { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, }, { GL_RGB5, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, }, { GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, }, { GL_COLOR_INDEX8_EXT, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, }, { GL_RGB8, GL_BGR, GL_UNSIGNED_BYTE, }, { GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, }, { GL_RGB5, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, } }; static void FixLittleEndian() { #if defined(ENDIAN_LITTLE) static bool bInitialized = false; if (bInitialized) return; bInitialized = true; for (int i = 0; i < NUM_PixelFormat; ++i) { RageDisplay::PixelFormatDesc &pf = PIXEL_FORMAT_DESC[i]; if (g_GLPixFmtInfo[i].type != GL_UNSIGNED_BYTE || pf.bpp == 8) continue; for (int mask = 0; mask < 4; ++mask) { int m = pf.masks[mask]; switch(pf.bpp) { case 24: m = Swap24(m); break; case 32: m = Swap32(m); break; default: ASSERT(0); } pf.masks[mask] = m; } } #endif } static void TurnOffHardwareVBO() { if (GLExt.glBindBufferARB) { GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); GLExt.glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } RageDisplay_OGL::RageDisplay_OGL() { LOG->Trace("RageDisplay_OGL::RageDisplay_OGL()"); LOG->MapLog("renderer", "Current renderer: OpenGL"); FixLittleEndian(); RageDisplay_OGL_Helpers::Init(); g_pWind = NULL; g_bTextureMatrixShader = 0; } RString GetInfoLog(GLhandleARB h) { GLint iLength; GLExt.glGetObjectParameterivARB(h, GL_OBJECT_INFO_LOG_LENGTH_ARB, &iLength); if (!iLength) return RString(); GLcharARB* pInfoLog = new GLcharARB[iLength]; GLExt.glGetInfoLogARB(h, iLength, &iLength, pInfoLog); RString sRet = pInfoLog; delete[] pInfoLog; TrimRight(sRet); return sRet; } GLhandleARB CompileShader(GLenum ShaderType, RString sFile, vector<RString> asDefines) { RString sBuffer; { RageFile file; if (!file.Open(sFile)) { LOG->Warn("Error compiling shader %s: %s", sFile.c_str(), file.GetError().c_str()); return 0; } if (file.Read(sBuffer, file.GetFileSize()) == -1) { LOG->Warn("Error compiling shader %s: %s", sFile.c_str(), file.GetError().c_str()); return 0; } } LOG->Trace("Compiling shader %s", sFile.c_str()); GLhandleARB hShader = GLExt.glCreateShaderObjectARB(ShaderType); vector<const GLcharARB*> apData; vector<GLint> aiLength; FOREACH(RString, asDefines, s) { *s = ssprintf("#define %s\n", s->c_str()); apData.push_back(s->data); aiLength.push_back(s->size()); } apData.push_back("#line 1\n"); aiLength.push_back(8); apData.push_back(sBuffer.data); aiLength.push_back(sBuffer.size()); GLExt.glShaderSourceARB(hShader, apData.size(), &apData[0], &aiLength[0]); GLExt.glCompileShaderARB(hShader); RString sInfo = GetInfoLog(hShader); GLint bCompileStatus = GL_FALSE; GLExt.glGetObjectParameterivARB(hShader, GL_OBJECT_COMPILE_STATUS_ARB, &bCompileStatus); if (!bCompileStatus) { LOG->Warn("Error compiling shader %s;\n%s", sFile.c_str(), sInfo.c_str()); GLExt.glDeleteObjectARB(hShader); return 0; } if (!sInfo.empty()) LOG->Trace("Messages compiling shader %s:\n%s", sFile.c_str(), sInfo.c_str()); return hShader; } GLhandleARB LoadShader(GLenum ShaderType, RString sFile, vector<RString> asDefines) { if (!GLExt.m_bGL_ARB_fragment_shader && ShaderType == GL_FRAGMENT_SHADER_ARB) return 0; if (!GLExt.m_bGL_ARB_vertex_shader && ShaderType == GL_VERTEX_SHADER_ARB) return 0; GLhandleARB hShader = CompileShader(ShaderType, sFile, asDefines); if (hShader == 0) return 0; GLhandleARB hProgram = GLExt.glCreateProgramObjectARB(); GLExt.glAttachObjectARB(hProgram, hShader); GLExt.glDeleteObjectARB(hShader); GLExt.glLinkProgramARB(hProgram); GLint bLinkStatus = false; GLExt.glGetObjectParameterARB(hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinkStatus); if (!bLinkStatus) { LOG->Warn("Error linking shader: %s: %s", sFile.c_str(), GetInfoLog(hProgram).c_str()); GLExt.glDeleteObjectARB(hProgram); return 0; } return hProgram; } static int g_iAttribTextureMatrixScale; static GLhandleARB g_bUnpremultiplyShader = 0; static GLhandleARB g_bColorBurnShader = 0; static GLhandleARB g_bColorDodgeShader = 0; static GLhandleARB g_bVividLightShader = 0; static GLhandleARB g_hHardMixShader = 0; static GLhandleARB g_hYUYV422Shader = 0; void InitShaders() { vector<RString> asDefines; g_bTextureMatrixShader = LoadShader(GL_VERTEX_SHADER_ARB, "Data/Shaders/GLSL/Texture matrix scaling.vert", asDefines); g_bUnpremultiplyShader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/Unpremultiply.frag", asDefines); g_bColorBurnShader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/Color burn.frag", asDefines); g_bColorDodgeShader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/Color dodge.frag", asDefines); g_bVividLightShader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/Vivid light.frag", asDefines); g_hHardMixShader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/Hard mix.frag", asDefines); g_hYUYV422Shader = LoadShader(GL_FRAGMENT_SHADER_ARB, "Data/Shaders/GLSL/YUYV422.frag", asDefines); if (g_bTextureMatrixShader) { FlushGLErrors(); g_iAttribTextureMatrixScale = GLExt.glGetAttribLocationARB(g_bTextureMatrixShader, "TextureMatrixScale"); if (g_iAttribTextureMatrixScale == -1) { LOG->Trace( "Scaling shader link failed: couldn't bind attribute \"TextureMatrixScale\"" ); GLExt.glDeleteObjectARB(g_bTextureMatrixShader); g_bTextureMatrixShader = 0; } else { AssertNoGLError(); GLExt.glVertexAttrib2fARB(g_iAttribTextureMatrixScale, 1, 1); GLenum iError = glGetError(); if (iError == GL_INVALID_OPERATION) { LOG->Trace("Scaling shader failed: glVertexAttrib2fARB returned GL_INVALID_OPERATION"); GLExt.glDeleteObjectARB(g_bTextureMatrixShader); g_bTextureMatrixShader = 0; } else { ASSERT_M(iError == GL_NO_ERROR, GLToString(iError)); } } } } static LocalizedString OBTAIN_AN_UPDATED_VIDEO_DRIVER("RageDisplay_OGL", "Obtain an updated driver from your video card manufacturer."); static LocalizedString GLDIRECT_IS_NOT_COMPATIBLE("RageDisplay_OGL", "GLDriver was detected. GLDirect is not compatible with this game and should be disabled."); RString RageDisplay_OGL::Init(const VideoModeParams& p, bool bAllowUnacceleratedRenderer) { g_pWind = LowLevelWindow::Create(); bool bIgnore = false; RString sError = SetVideoMode(p, bIgnore); if (sError != "") return sError; g_pWind->LogDebugInformation(); LOG->Info("OGL Vendor: %s", glGetString(GL_VENDOR)); LOG->Info("OGL Renderer: %s", glGetString(GL_RENDERER)); LOG->Info("OGL Version: %s", glGetString(GL_VERSION)); LOG->Info("OGL Max texture size: %i", GetMaxTextureSize()); LOG->Info("OGL Texture units: %i", g_iMaxTextureUnits); LOG->Info("GLU Version: %s", gluGetString(GLU_VERSION)); LOG->Info("OGL Extensions: "); { const char* szExtensionString = (const char*)glGetString(GL_EXTENSIONS); vector<RString> asExtensions; split(szExtensionString, " ", asExtensions); sort(asExtensions.begin(), asExtensions.end()); size_t iNextToPrint = 0; while (iNextToPrint < asExtensions.size()) { size_t iLastToPrint = iNextToPrint; RString sType; for (size_t i = iNextToPrint; i < asExtensions.size(); ++i) { vector<RString> asBits; split(asExtensions[i], "_", asBits); RString sThisType; if (asBits.size() > 2) sThisType = join("_", asBits.begin(), asBits.begin() + 2); if (i > iNextToPrint && sThisType != sType) break; sType = sThisType; iLastToPrint = i; } if (iNextToPrint == iLastToPrint) { LOG->Info(" %s", asExtensions[iNextToPrint].c_str()); ++iNextToPrint; continue; } RString sList = sprintf(" %s: ", sType.c_str()); while (iNextToPrint <= iLastToPrint) { vector<RString> asBits; split(asExtensions[iNextToPrint], "_", asBits); RString sShortExt = join("_", asBits.begin() + 2, asBits.end()); sList += sShortExt; if (iNextToPrint < iLastToPrint) sList += ", "; if (iNextToPrint == iLastToPrint || sList.size() + asExtensions[iNextToPrint + 1].size() > 120) { LOG->Info("%s", sList.c_str()); sList = " "; } ++iNextToPrint; } } } if (g_pWind->IsSoftwareRenderer(sError)) { if (!bAllowUnacceleratorRenderer) return sError + " " + OBTAIN_AN_UPDATED_VIDEO_DRIVER.GetValue() + "\n\n"; LOG->Warn("Low-performance OpenGL renderer: %s", sError.c_str()); } #if defined(_WINDOWS) if (!strncmp((const char*)glGetString(GL_RENDERER), "GLDirect", 8)) return GLDIRECT_IS_NOT_COMPATIBLE.GetValue() + "\n"; #endif glGetFloatv(GL_LINE_WIDTH_RANGE, g_line_range); glGetFloatv(GL_POINT_SIZE_RANGE, g_point_range); return RString(); } RageDisplay_OGL::~RageDisplay_OGL() { delete g_pWind; } void RageDisplay_OGL::GetDisplayResolutions(DisplayResolutions& out) const { out.clear(); g_pWind->getDisplayResolutions(out); } static void CheckPalettedTextures() { RString sError; do { if (!GLExt.HasExtension("GL_EXT_paletted_texture")) { sError = "GL_EXT_paletted_texture missing"; break; } if (GLExt.glColorTableEXT == NULL) { sError = "glColorTableEXT missing"; break; } if (GLExt.glGetColorTableParameterivEXT == NULL) { sError = "glGetColorTableParameterivEXT missing"; break; } GLenum glTexFormat = g_GLPixFmtInfo[PixelFormat_PAL].internalfmt; GLenum glImageFormat = g_GLPixFmtInfo[PixelFormat_PAL].format; GLenum glImageType = g_GLPixFmtInfo[PixelFormat_PAL].type; int iBits = 8; FlushGLErrors(); #define GL_CHECK_ERROR(f) \ {\ GLenum glError = glGetError();\ if (glError != GL_NO_ERROR) { \ sError = ssprintf(f " failed (%s)", GLToString(glError).c_str()); \ break; \ } \ } glTexImage2D(GL_PROXY_TEXTURE_2D, 0, glTexFormat, 16, 16, 0, glImageFormat, glImageType, NULL); GL_CHECK_ERROR("glTexImage2D"); GLuint iFormat = 0; glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GLenum(GL_TEXTURE_INTERNAL_FORMAT), (GLint*)&iFormat); GL_CHECK_ERROR( "glGetTexLevelParameteriv(GL_TEXTURE_INTERNAL_FORMAT)" ); if (iFormat != glTexFormat) { sError = ssprintf("Expected format %s, got %s instead", GLToString(glTexFormat).c_str(), GLToString(iFormat).c_str()); break; } GLubyte palette[256 * 4]; memset(palette, 0, sizeof(palette)); GLExt.glColorTableEXT(GL_PROXY_TEXTURE_2D, GL_RGBA8, 256, GL_RGBA, GL_UNSIGNED_BYTE, palette); GL_CHECK_ERROR("glColorTableEXT"); GLint iSize = 0; glGetTexLevelParameteriv(GL_RPOXY_TEXTURE_2D, 0, GLenum(GL_TEXTURE_INDEX_SIZE_EXT), &iSize); GL_CHECK_ERROR("glGetTexLevelParameteriv(GL_TEXTURE_INDEX_SIZE_EXT)"); if (iBits > iSize || iSize > 8) { sError = ssprintf("Expected %i-bit palette, got a %i-bit one instead", iBits, (int)iSize); } GLint iRealWidth = 0; GLExt.glGetColorTableParameterivEXT(GL_RPOXY_TEXTURE_2D, GL_COLOR_TABLE_WIDTH, &iRealWidth); GL_CHECK_ERROR("glGetColorTableParameterivEXT(GL_COLOR_TABLE_WIDTH)"); if (iRealWidth != 1 << iBits) { sError = ssprintf("GL_COLOR_TABLE_WIDTH returned %i instead of %i", int(iRealWidth), 1 << iBits); break; } GLint iRealFormat = 0; GLExt.glGetColorTableParameterivEXT(GL_PROXY_TEXTURE_2D, GL_COLOR_TABLE_FORMAT, &iRealFormat); GL_CHECK_ERROR("glGetColorTableParameterivEXT(GL_COLOR_TABLE_FORMAT)"); if (iRealFormat != GL_RGBA8) { sError = ssprintf("GL_COLOR_TABLE_FORMAT returned %s instead of GL_RGBA8", GLToString(iRealFormat).c_str()); break; } } while (0); #undef GL_CHECK_ERROR if (sError == "") return; GLExt.glColorTableEXT = NULL; GLExt.glGetColorTableParameterivEXT = NULL; LOG->Info("Paletted textures disabled: %s", sError.c_str()); } static void CheckReversePackedPixels() { FlushGLErrors(); glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, NULL); const GLenum glError = glGetError(); if (glError == GL_NO_ERROR) { g_bReversePackedPixelsWorks = true; } else { g_bReversePackedPixelsWorks = false; LOG->Info("GL_UNSIGNED_SHORT_1_5_5_5_REV failed (%s), disabled", GLToString(glError).c_str()); } } void SetupExtensions() { const float fGLVersion = StringToFloat((const char*)glGetString(GL_VERSION)); g_glVersion = lrintf(fGLVersion * 10); const float fGLUVersion = StringToFloat((const char*)gluGetString(GLU_VERSION)); g_gluVersion = lrintf(fGLUVersion * 10); GLExt.Load(g_pWind); g_iMaxTextureUnits = 1; if (GLExt.glActiveTextureARB != NULL) glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&g_iMaxTextureUnits); CheckPalettedTextures(); CheckReversePackedPixels(); { GLint iMaxTableSize = 0; glGetIntegerv(GL_MAX_PIXEL_MAP_TABLE, &iMaxTableSize); if (iMaxTableSize < 256) { LOG->Info("GL_MAX_PIXEL_MAP_TABLE is only %d", int(iMaxTableSize)); g_bColorIndexTableWorks = false; } else { g_bColorIndexTableWorks = true; } } } void RageDisplay_OGL::ResolutionChanged() { if (BeginFrame()) EndFrame(); RageDisplay::ResolutionChanged(); } RString RageDisplay_OGL::TryVideoMode(const VideoModeParams& p, bool& bNewDeviceOut) { RString err; err = g_pWind->TryVideoMode(p, bNewDeviceOut); if (err != "") return err; SetupExtensions(); if (bNewDeviceOut) { if( TEXTUREMAN ) TEXTUREMAN->InvalidateTextures(); FOREACHM(unsigned, RenderTarget*, g_mapRenderTargets, rt) delete rt->second; g_mapRenderTargets.clear(); InvalidateObjects(); InitShaders(); } if (GLExt.wglSwapIntervalEXT) GLExt.wglSwapIntervalEXT(p.vsync); ResolutionChanged(); return RString(); } int RageDisplay_OGL::GetMaxTextureSize() const { GLint size; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ); return size; } bool RageDisplay_OGL::BeginFrame() { int fWidth = g_pWind->GetActualVideoModeParams().width; int fHeight = g_pWind->GetActualVideoModeParams().height; glViewport( 0, 0, fWidth, fHeight ); glClearColor( 0,0,0,0 ); SetZWrite( true ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); return RageDisplay::BeginFrame(); } void RageDisplay_OGL::EndFrame() { glFlush(); FrameLimitBeforeVsync( g_pWind->GetActualVideoModeParams().rate ); g_pWind->SwapBuffers(); FrameLimitAfterVsync(); g_pWind->Update(); RageDisplay::EndFrame(); } RageSurface* RageDisplay_OGL::CreateScreenshot() { int width = g_pWind->GetActualVideoModeParams().width; int height = g_pWind->GetActualVideoModeParams().height; const PixelFormatDesc &desc = PIXEL_FORMAT_DESC[PixelFormat_RGBA8]; RageSurface *image = CreateSurface( width, height, desc.bpp, desc.masks[0], desc.masks[1], desc.masks[2], 0 ); DebugFlushGLErrors(); glReadBuffer( GL_FRONT ); DebugAssertNoGLError(); glReadPixels( 0, 0, g_pWind->GetActualVideoModeParams().width, g_pWind->GetActualVideoModeParams().height, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels ); DebugAssertNoGLError(); RageSurfaceUtils::FlipVertically( image ); return image; } RageSurface *RageDisplay_OGL::GetTexture( unsigned iTexture ) { if( iTexture == 0 ) return NULL; FlushGLErrors(); glBindTexture( GL_TEXTURE_2D, iTexture ); GLint iHeight, iWidth, iAlphaBits; glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &iHeight ); glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &iWidth ); glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_ALPHA_SIZE, &iAlphaBits ); int iFormat = iAlphaBits? PixelFormat_RGBA8:PixelFormat_RGB8; const PixelFormatDesc &desc = PIXEL_FORMAT_DESC[iFormat]; RageSurface *pImage = CreateSurface( iWidth, iHeight, desc.bpp, desc.masks[0], desc.masks[1], desc.masks[2], desc.masks[3] ); glGetTexImage( GL_TEXTURE_2D, 0, g_GLPixFmtInfo[iFormat].format, GL_UNSIGNED_BYTE, pImage->pixels ); AssertNoGLError(); return pImage; } VideoModeParams RageDisplay_OGL::GetActualVideoModeParams() const { return g_pWind->GetActualVideoModeParams(); } static void SetupVertices( const RageSpriteVertex v[], int iNumVerts ) { static float *Vertex, *Texture, *Normal; static GLubyte *Color; static int Size = 0; if( iNumVerts > Size ) { Size = iNumVerts; delete [] Vertex; delete [] Color; delete [] Texture; delete [] Normal; Vertex = new float[Size*3]; Color = new GLubyte[Size*4]; Texture = new float[Size*2]; Normal = new float[Size*3]; } for( unsigned i = 0; i < unsigned(iNumVerts); ++i ) { Vertex[i*3+0] = v[i].p[0]; Vertex[i*3+1] = v[i].p[1]; Vertex[i*3+2] = v[i].p[2]; Color[i*4+0] = v[i].c.r; Color[i*4+1] = v[i].c.g; Color[i*4+2] = v[i].c.b; Color[i*4+3] = v[i].c.a; Texture[i*2+0] = v[i].t[0]; Texture[i*2+1] = v[i].t[1]; Normal[i*3+0] = v[i].n[0]; Normal[i*3+1] = v[i].n[1]; Normal[i*3+2] = v[i].n[2]; } glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 3, GL_FLOAT, 0, Vertex ); glEnableClientState( GL_COLOR_ARRAY ); glColorPointer( 4, GL_UNSIGNED_BYTE, 0, Color ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glTexCoordPointer( 2, GL_FLOAT, 0, Texture ); if( GLExt.glClientActiveTextureARB != NULL ) { GLExt.glClientActiveTextureARB( GL_TEXTURE1_ARB ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glTexCoordPointer( 2, GL_FLOAT, 0, Texture ); GLExt.glClientActiveTextureARB( GL_TEXTURE0_ARB ); } glEnableClientState( GL_NORMAL_ARRAY ); glNormalPointer( GL_FLOAT, 0, Normal ); } void RageDisplay_OGL::SendCurrentMatrices() { RageMatrix projection; RageMatrixMultiply( &projection, GetCentering(), GetProjectionTop() ); if( g_bInvertY ) { RageMatrix flip; RageMatrixScale( &flip, +1, -1, +1 ); RageMatrixMultiply( &projection, &flip, &projection ); } glMatrixMode( GL_PROJECTION ); glLoadMatrixf( (const float*)&projection ); RageMatrix modelView; RageMatrixMultiply( &modelView, GetViewTop(), GetWorldTop() ); glMatrixMode( GL_MODELVIEW ); glLoadMatrixf( (const float*)&modelView ); glMatrixMode( GL_TEXTURE ); glLoadMatrixf( (const float*)GetTextureTop() ); } class RageCompiledGeometrySWOGL : public RageCompiledGeometry { public: void Allocate( const vector<msMesh> &vMeshes ) { m_vPosition.resize( max(1u, GetTotalVertices()) ); m_vTexture.resize( max(1u, GetTotalVertices()) ); m_vNormal.resize( max(1u, GetTotalVertices()) ); m_vTexMatrixScale.resize( max(1u, GetTotalVertices()) ); m_vTriangles.resize( max(1u, GetTotalTriangles()) ); } void Change(const vector<msMesh>& vMeshes) { for (unsigned i = 0; i < vMeshes.size(); i++) { const MeshInfo& meshInfo = m_vmeshInfo[i]; const msMesh& mesh = vMeshes[i]; const vector<RageModelVertex>& Vertices = mesh.Vertices; const vector<msTriangle>& Triangles = mesh.Triangles; for (unsigned j = 0; j < Vertices.size(); j++) { m_vPosition[meshInfo.iVertexStart + j] = Vertices[j].p; m_vTexture[meshInfo.iVertexStart + j] = Vertices[j].t; m_vNormal[meshInfo.iVertexStart + j] = Vertices[j].n; m_vTexMatrixScale[meshInfo.iVertexStart + j] = Vertices[j].TextureMatrixScale; } for (unsigned j = 0; j < Triangles.size(); j++) for (unsigned k = 0; k < 3; k++) { int iVertexIndexInVBO = meshInfo.iVertexStart + Triangles[j].nVertexIndices[k]; m_vTriangles[meshInfo.iTriangleStart + j].nVertexIndices[k] = (uint16_t)iVertexIndexInVBO; } } } void Draw(int iMeshIndex) const { TurnOffHardwareVBO(); const MeshInfo& meshInfo = m_vMeshInfo[iMeshIndex]; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &m_vPosition[0]); glDisableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, &m_vTexture[0]); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, &m_vNormal[0]); if (meshInfo.m_bNeedsTextureMatrixScale) { RageMatrix mat; glGetFloatv(GL_TEXTURE_MATRIX, (float*)mat); mat.m[3][0] = 0; mat.m[3][1] = 0; mat.m[3][2] = 0; glMatrixMode(GL_TEXTURE); glLoadMatrixf((const float*)mat); } glDrawElements( GL_TRIANGLES, meshInfo.iTriangleCount * 3, GL_UNSIGNED_SHORT, &m_vTriangles[0] + mesh.iTriangleStart); } protected: vector<RageVector3> m_vPosition; vector<RageVertor2> m_vTexture; vector<RageVector3> m_vNormal; vector<msTriangle> m_vTriangle; vector<RageVector2> m_vTexMatrixScale; }; class InvalidateObject; static set<InvalidateObject*> g_InvalidateList; class InvalidateObject { public: InvalidateObject() { g_InvalidateList.insert(this); } virtual ~InvalidateObject() { g_InvalidateList.erase(this); } virtual void Invalidate() = 0; }; static void InvalidateObjects() { FOREACHS(InvalidateObject*, g_InvalidateList, it) (*it)->Invalidate(); } class RageCompiledGeometryHWOGL : public RageCompiledGeometrySWOGL, public InvalidateObject { protected: GLuint m_nPositions; GLuint m_nTextureCoords; GLuint m_nNormals; GLuint m_nTriangles; GLuint m_nTextureMatrixScale; void AllocateBuffers(); void UploadData(); public: RageCompiledGeometryHWOGL(); ~RageCompiledGeometryHWOGL(); void Invalidate(); void Allocate(const vector<msMesh>& vMeshes); void Change(const vector<msMesh>& vMeshes); void Draw(int iMeshIndex) const; }; RageCompiledGeometryHWOGL::RageCompiledGeometryHWOGL() { m_nPositions = 0; m_nTextureCoords = 0; m_nNormals = 0; m_nTriangles = 0; m_nTextureMatrixScale = 0; AllocateBuffers(); } RageCompiledGeometryHWOGL::~RageCompiledGeometryHWOGL() { DebugFlushGLErrors(); GLExt.glDeleteBuffersARB(1, &m_nPositions); DebugAssertNoGLErrors(); GLExt.glDeleteBuffersARB(1, &m_nTextureCoords); DebugAssertNoGLErrors(); GLExt.glDeleteBuffersARB(1, &m_nNormals); DebugAssertNoGLErrors(); GLExt.glDeleteBuffersARB(1, &m_nTriangles); DebugAssertNoGLErrors(); GLExt.glDeleteBuffersARB(1, &m_nTextureMatrixScale); DebugAssertNoGLErrors(); } void RageCompiledGeometryHWOGL::AllocateBuffers() { DebugFlushGLErrors(); if (!m_nPositions) { GLExt.glGenBuffersARB(1, &m_nPositions); DebugAssertNoGLError(); } if (!m_nTextureCoords) { GLExt.glGenBuffersARB(1, &m_nTextureCoords); DebugAssertNoGLError(); } if (!m_nNormals) { GLExt.glGenBuffersARB(1, &m_nNormals); DebugAssertNoGLError(); } if (!m_nTriangles) { GLExt.glGenBuffersARB(1, m_nTriangles); DebugAssertNoGLError(); } if (!m_nTextureMatrixScale) { GLExt.glGenBuffersARB(1, &m_nTextureMatrixScale); DebugAssertNoGLError(); } } void RageCompiledGeometryHWOGL::UploadData() { DebugFlushGLErrors(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nPositions); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector3), &m_vPositions[0], GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureCoords); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector2), &m_vTexture[0], GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nNormals); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector3), &m_vNormal[0], GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_nTriangles); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(msTriangle), &m_vTriangles[0], GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); if (m_bAnyNeedsTextureMatrixScale) { GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureMatrixScale); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector2), &m_vTexMatrixScale[0], GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); } } void RageCompiledGeometryHWOGL::Invalidate() { m_nPositions = 0; m_nTextureCoords = 0; m_nNormals = 0; m_nTriangles = 0; m_nTextureMatrixScale = 0; AllocateBuffers(); UploadData(); } void RageCompiledGeometryHWOGL::Allocate(const vector<msMesh>& vMeshes) { DebugFlushGLErrors(); RageCompiledGeometrySWOGL::Allocate(vMeshes); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nPositions); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector3), NULL, GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureCoords); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector2), NULL, GL_STATIC_DRAW_ARB); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nNormals); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector3), NULL, GL_STATIC_DRAW_ARB); DebugAssertNoGLErrors(); GLExt.glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_nTriangles); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(msTriangle), NULL, GL_STATIC_DRAW_ARB); DebugAssertNoGLErrors(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureMatrixScale); DebugAssertNoGLError(); GLExt.glBufferDataARB( GL_ARRAY_BUFFER_ARB, GetTotalVertices() * sizeof(RageVector2), NULL, GL_STATIC_DRAW_ARB); } void RageCompiledGeometryHWOGL::Change(const vector<msMesh>& vMeshes) { RageCompiledGeometrySWOGL::Change(vMeshes); UploadData(); } void RageCompiledGeometryHWOGL::Draw(int iMeshIndex) const { DebugFlushGLErrors(); const MeshInfo& meshInfo = m_vMeshInfo[iMeshIndex]; if (!meshInfo.iVertexCount || !meshInfo.iTriangleCount) return; glEnableClientState(GL_VERTEX_ARRAY); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nPositions); DebugAssertNoGLError(); glVertexPointer(3, GL_FLOAT, 0, NULL); DebugAssertNoGLError(); glDisableClientState(GL_COLOR_ARRAY); DebugAssertNoGLError(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureCoords); DebugAssertNoGLError(); glTexCoordPointer(2, GL_FLOAT, 0, NULL); DebugAssertNoGLError(); GLboolean bLighting; glGetBooleanv(GL_LIGHTING, &bLighting); GLboolean bTextureGenS; glGetBooleanv(GL_TEXTURE_GEN_S, &bTextureGenS); GLboolean bTextureGenT; glGetBooleanv(GL_TEXTURE_GEN_T, &bTextureGenT); if (bLighting || bTextureGenS || bTextureGenT) { glEnableClientState(GL_NORMAL_ARRAY); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nNormals); DebugAssertNoGLError(); glNormalPointer(GL_FLOAT, 0, NULL); DebugAssertNoGLError(); } else { glDisableClientState(GL_NORMAL_ARRAY); DebugAssertNoGLError(); } if (meshInfo.m_bNeedsTextureMatrixScale) { if (g_bTextureMatrixShader != 0) { GLExt.glEnableVertexAttribArrayARB(g_iAttribTextureMatrixScale); DebugAssertNoGLError(); GLExt.glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_nTextureMatrixScale); DebugAssertNoGLError(); GLExt.glVertexAttribPointerARB(g_iAttribTextureMatrixScale, 2, GL_FLOAT, false, 0, NULL); DebugAssertNoGLError(); GLExt.glUseProgramObjectARB(g_bTextureMatrixShader); DebugAssertNoGLError(); } else { RageMatrix mat; glGetFloatv(GL_TEXTURE_MATRIX, (float*)mat); mat.m[3][0] = 0; mat.m[3][1] = 0; mat.m[3][2] = 0; glMatrixMode(GL_TEXTURE); glLoadMatrixf((const float*)mat); DebugAssertNoGLError(); } } GLExt.glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_nTriangles); DebugAssertNoGLError(); #define BUFFER_OFFSET(o) ((char*)(o)) ASSERT(GLExt.glDrawRangeElements); GLExt.glDrawRangeElements( GL_TRIANGLES, meshInfo.iVertexStart, meshInfo.iVertexStart + meshInfo.iVertexCount - 1, meshInfo.iTriangleCount * 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(meshInfo.iTriangleStart * sizeof(msTriangle))); DebugAssertNoGLError(); if (meshInfo.m_bNeedsTextureMatrixScale && g_bTextureMatrixShader != 0) { GLExt.glDisableVertexAttribArrayARB(g_iAttribTextureMatrixScale); GLExt.glUseProgramObjectARB(0); } } RageCompiledGeometry* RageDisplay_OGL::CreateCompiledGeometry() { if (GLExt.glGenBuffersARB) return new RageCompiledGeometryHWOGL; else return new RageCompiledGeometrySWOGL; } void RageDisplay_OGL::DeleteCompiledGeometry(RageCompiledGeometry* p) { delete p; } void RageDisplay_OGL::DrawQuadsInternal(const RageSpriteVertex v[], int iNumVerts) { TurnOffHardwareVBO(); SendCurrentMatrices(); SetupVertices(v, iNumVerts); glDrawArrays(GL_QUADS, 0, iNumVerts); } void RageDisplay_OGL::DrawQuadStripInternal(const RageSpriteVertex v[], int iNumVerts) { TurnOffHardwareVBO(); SendCurrentMatrices(); SetupVertices(v, iNumVerts); glDrawArrays(GL_QUAD_STRIP, 0, iNumVerts); } void RageDisplay_OGL::DrawSymmetricQuadStripInternal(const RageSpriteVertex v[], int iNumVerts) { int iNumPieces = (iNumVerts - 3) / 3; int iNumTriangles = iNumPieces * 4; int iNumIndices = iNumTriangles * 3; static vector<uint16_t> vIndices; unsigned uOldSize = vIndices.size(); unsigned uNewSize = max(uOldSize, (unsigned)iNumIndices); vIndices.resize(uNewSize); for (uint16_t i = (uint16_t)uOldSize / 12; i < (uint16_t)iNumPieces; i++) { vIndices[i*12+0] = i*3+1; vIndices[i*12+1] = i*3+3; vIndices[i*12+2] = i*3+0; vIndices[i*12+3] = i*3+1; vIndices[i*12+4] = i*3+4; vIndices[i*12+5] = i*3+3; vIndices[i*12+6] = i*3+1; vIndices[i*12+7] = i*3+5; vIndices[i*12+8] = i*3+4; vIndices[i*12+9] = i*3+1; vIndices[i*12+10] = i*3+2; vIndices[i*12+11] = i*3+5; } TurnOffHardwareVBO(); SetCurrentMatrices(); SetupVertices(v, iNumVerts); glDrawElements( GL_TRIANGLES, iNumIndices, GL_UNSIGNED_SHORT, &vIndices[0]); } void RageDisplay_OGL::DrawFanInternal(const RageSpriteVertex v[], int iNumVerts) { TurnOffHardwareVBO(); SendCurrentMatrices(); SetupVertices(v, iNumVerts); glDrawArrays(GL_TRIANGLE_FAN, 0, iNumVerts); } void RageDisplay_OGL::DrawStripInternal(const RageSpriteVertex v[], int iNumVerts) { TurnOffHardwareVBO(); SendCurrentMatrices(); SetupVertics(v, iNumVerts); glDrawArrays(GL_TRIANGLE_STRIP, 0, iNumVerts); } void RageDisplay_OGL::DrawTrianglesInternal(const RageSpriteVertx v[], int iNumVerts) { TurnOffHardwareVBO(); SendCurrentMatrices(); SetupVertices( v, iNumVerts ); glDrawArrays( GL_TRIANGLES, 0, iNumVerts ); } void RageDisplay_OGL::DrawCompiledGemoetryInternal(const RageCompiledGeometry* p, int iMeshIndex) { TurnOffHardwareVBO(); SendCurrentMatrices(); p->Draw(iMeshIndex); } void RageDisplay_OGL::DrawLineStripInternal(const RageSpriteVertex v[], int iNumVerts, float fLineWidth) { TurnOffHardwareVBO(); if (!GetActualVideoModeParams().bSmoothLines) { RageDisplay::DrawLineStripInternal(v, iNumVerts, fLineWidth); return; } SendCurrentMatrices(); glEnable(GL_LINE_SMOOTH); { const RageMatrix* pMat = GetProjectionTop(); float fW = 2 / pMat->m[0][0]; float fH = -2 / pMat->m[1][1]; float fWidthVal = float(g_pWind->GetActualVideoModeParams().width) / fW; float fHeightVal = float(g_pWind->GetActualVideoModeParams().height) / fH; fLineWidth *= (fWidthVal + fHeightVal) / 2; } fLineWidth = clamp(fLineWidth, g_line_range[0], g_line_range[1]); fLineWidth = clamp(fLineWidth, g_point_range[0], g_point_range[1]); glLineWidth(fLineWidth); SetupVertices(v, iNumVerts); glDrawArrays(GL_LINE_STRIP, 0, iNumVerts); glDisable(GL_LINE_SMOOTH); glPointSize(fLineWidth); RageMatrix mat; glGetFloatv(GL_MODELVIEW_MATRIX, (float*)mat); if (mat.m[0][0] < 1e-5 && mat.m[1][1] < 1e-5) return; glEnable(GL_POINT_SMOOTH); SetupVertices(v, iNumVerts); glDrawArrays(GL_POINTS, 0, iNumVerts); glDisable(GL_POINT_SMOOTH); } static bool SetTextureUnit(TextureUnit tu) { if( GLExt.glActiveTextureARB == NULL ) return false; if( (int) tu > g_iMaxTextureUnits ) return false; GLExt.glActiveTextureARB(enum_add2(GL_TEXTURE0_ARB, tu)); return true; } void RageDisplay_OGL::ClearAllTextures() { FOREACH_ENUM(TextureUnit, i) SetTexture(i, 0); if( GLExt.glActiveTextureARB ) GLExt.glActiveTextureARB(GL_TEXTURE0_ARB); } int RageDisplay_OGL::GetNumTextureUnits() { if (GLExt.glActiveTextureARB == NULL) return 1; else return g_iMaxTextureUnits; } void RageDisplay_OGL::SetTexture(TextureUnit tu, unsigned iTexture) { if (!SetTextureUnit(tu)) return; if (iTexture) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, iTexture); } else { glDisable(GL_TEXTURE_2D); } } void RageDisplay_OGL::SetTextureMode(TextureUnit tu, TextureMode tm) { if (!SetTextureUnit(tu)) return; switch(tm) { case TextureMode_Modulate: glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); break; case TextureMode_Add: glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); break; case TextureMode_Glow: if (!GLExt.m_bARB_texture_env_combine && !GLExt.m_bEXT_texture_env_combine) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); return; } glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi( GL_TEXTURE_ENV, GLenum(GL_COMBINE_RGB_EXT), GL_REPLACE ); glTexEnvi(GL_TEXTURE_ENV, GLenum(GL_SOURCE0_RGB_EXT), GL_PRIMARY_COLOR_EXT); glTexEnvi(GL_TEXTURE_ENV, GLenum(GL_COMBINE_ALPHA_EXT), GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GLenum(GL_OPERAND0_ALPHA_EXT), GL_SRC_ALPHA); glTexEnvi( GL_TEXTURE_ENV, GLenum(GL_SOURCE0_ALPHA_EXT), GL_PRIMARY_COLOR_EXT ); glTexEnvi(GL_TEXTURE_ENV, GLenum(GL_OPERAND1_ALPHA_EXT), GL_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV, GLenum(GL_SOURCE1_ALPHA_EXT), GL_TEXTURE); break; } } void RageDisplay_OGL::SetTextureFiltering(TextureUnit tu, bool b) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, b ? GL_LINEAR : GL_NEAREST); GLint iMinFilters; if (b) { GLint iWidth1 = -1; GLint iWidth2 = -1; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &iWidth1); glGetTexLevelParameteriv(GL_TEXTURE_2D, 1, GL_TEXTURE_WIDTh, &iWidth2); if (iWidth1 > 1 && iWidth2 != 0) { if( g_pWind->GetActualVideoModeParams().bTrilinearFiltering ) iMinFilter = GL_LINEAR_MIPMAP_LINEAR; else iMinFilter = GL_LINEAR_MIPMAP_NEAREST; } else { iMinFilter = GL_LINEAR; } } else { iMinFilter = GL_NEAREST; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, iMinFilter); } void RageDisplay_OGL::SetEffectMode(EffectMode effect) { if (GLExt.glUseProgramObjectARB == NULL) return; GLhandleARB hShader = 0; switch(effect) { case EffectMode_Normal: hShader = 0; break; case EffectMode_Unpremultiply: hShader = g_bUnpremultiplyShader; break; case EffectMode_ColorBurn: hShader = g_bColorBurnShader; break; case EffectMode_ColorDodge: hShader = g_bVividDodgeShader; break; case EffectMode_VividLight: hShader = g_bVividLightShader; break; case EffectMode_HardMix: hShader = g_hHardMixShader; break; case EffectMode_YUYV422: hShader = g_hYUYV422Shader; break; } DebugFlushGLErrors(); GLExt.glUseProgramObjectARB(hShader); if (hShader == 0) return; GLint iTexture1 = GLExt.glGetUniformLocationARB(hShader, "Texture1"); GLint iTexture2 = GLExt.glGetUniformLocationARB(hShader, "Texture2"); GLExt.glUniform1iARB( iTexture1, 0 ); GLExt.glUniform1iARB( iTexture2, 1 ); if( effect == EffectMode_YUYV422 ) { GLint iTextureWidthUniform = GLExt.glGetUniformLocationARB( hShader, "TextureWidth" ); GLint iWidth; glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &iWidth ); GLExt.glUniform1iARB( iTextureWidthUniform, iWidth ); } DebugAssertNoGLError(); } bool RageDisplay_OGL::IsEffectModeSupported( EffectMode effect ) { switch( effect ) { case EffectMode_Normal: return true; case EffectMode_Unpremultiply: return g_bUnpremultiplyShader != 0; case EffectMode_ColorBurn: return g_bColorBurnShader != 0; case EffectMode_ColorDodge: return g_bColorDodgeShader != 0; case EffectMode_VividLight: return g_bVividLightShader != 0; case EffectMode_HardMix: return g_hHardMixShader != 0; case EffectMode_YUYV422: return g_hYUYV422Shader != 0; } return false; } void RageDisplay_OGL::SetBlendMode( BlendMode mode ) { glEnable(GL_BLEND); if( GLExt.glBlendEquation != NULL ) { if( mode == BLEND_INVERT_DEST ) GLExt.glBlendEquation( GL_FUNC_SUBTRACT ); else if( mode == BLEND_SUBTRACT ) GLExt.glBlendEquation( GL_FUNC_REVERSE_SUBTRACT ); else GLExt.glBlendEquation( GL_FUNC_ADD ); } int iSourceRGB, iDestRGB; int iSourceAlpha = GL_ONE, iDestAlpha = GL_ONE_MINUS_SRC_ALPHA; switch( mode ) { case BLEND_NORMAL: iSourceRGB = GL_SRC_ALPHA; iDestRGB = GL_ONE_MINUS_SRC_ALPHA; break; case BLEND_ADD: iSourceRGB = GL_SRC_ALPHA; iDestRGB = GL_ONE; break; case BLEND_SUBTRACT: iSourceRGB = GL_SRC_ALPHA; iDestRGB = GL_ONE_MINUS_SRC_ALPHA; break; case BLEND_COPY_SRC: iSourceRGB = GL_ONE; iDestRGB = GL_ZERO; iSourceAlpha = GL_ONE; iDestAlpha = GL_ZERO; break; case BLEND_ALPHA_MASK: iSourceRGB = GL_ZERO; iDestRGB = GL_ONE; iSourceAlpha = GL_ZERO; iDestAlpha = GL_SRC_ALPHA; break; case BLEND_ALPHA_KNOCK_OUT: iSourceRGB = GL_ZERO; iDestRGB = GL_ONE; iSourceAlpha = GL_ZERO; iDestAlpha = GL_ONE_MINUS_SRC_ALPHA; break; case BLEND_WEIGHTED_MULTIPLY: iSourceRGB = GL_DST_COLOR; iDestRGB = GL_SRC_COLOR; break; case BLEND_INVERT_DEST: iSourceRGB = GL_ONE; iDestRGB = GL_ONE; break; case BLEND_NO_EFFECT: iSourceRGB = GL_ZERO; iDestRGB = GL_ONE; iSourceAlpha = GL_ZERO; iSourceAlpha = GL_ONE; break; DEFAULT_FAIL( mode ); } if( GLExt.glBlendFuncSeparateEXT != NULL ) GLExt.glBlendFuncSeparateEXT( iSourceRGB, iDestRGB, iSourceAlpha, iDestAlpha ); else glBlendFunc( iSourceRGB, iDestRGB ); } bool RageDisplay_OGL::IsZWriteEnabled() const { bool a; glGetBooleanv( GL_DEPTH_WRITEMASK, (unsigned char*)&a ); return a; } bool RageDisplay_OGL::IsZTestEnabled() const { GLenum a; glGetIntegerv( GL_DEPTH_FUNC, (GLint*)&a ); return a != GL_ALWAYS; } void RageDisplay_OGL::ClearZBuffer() { bool write = IsZWriteEnabled(); SetZWrite( true ); glClear( GL_DEPTH_BUFFER_BIT ); SetZWrite( write ); } void RageDisplay_OGL::SetZWrite( bool b ) { glDepthMask( b ); } void RageDisplay_OGL::SetZBias( float f ) { float fNear = SCALE( f, 0.0f, 1.0f, 0.05f, 0.0f ); float fFar = SCALE( f, 0.0f, 1.0f, 1.0f, 0.95f ); glDepthRange( fNear, fFar ); } void RageDisplay_OGL::SetZTestMode( ZTestMode mode ) { glEnable( GL_DEPTH_TEST ); switch( mode ) { case ZTEST_OFF: glDepthFunc( GL_ALWAYS ); break; case ZTEST_WRITE_ON_PASS: glDepthFunc( GL_LEQUAL ); break; case ZTEST_WRITE_ON_FAIL: glDepthFunc( GL_GREATER ); break; default: ASSERT( 0 ); } } void RageDisplay_OGL::SetTextureWrapping( TextureUnit tu, bool b ) { SetTextureUnit( tu ); GLenum mode = b ? GL_REPEAT : GL_CLAMP_TO_EDGE; glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mode ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mode ); } void RageDisplay_OGL::SetMaterial( const RageColor &emissive, const RageColor &ambient, const RageColor &diffuse, const RageColor &specular, float shininess ) { GLboolean bLighting; glGetBooleanv( GL_LIGHTING, &bLighting ); if( bLighting ) { glMaterialfv( GL_FRONT, GL_EMISSION, emissive ); glMaterialfv( GL_FRONT, GL_AMBIENT, ambient ); glMaterialfv( GL_FRONT, GL_DIFFUSE, diffuse ); glMaterialfv( GL_FRONT, GL_SPECULAR, specular ); glMaterialf( GL_FRONT, GL_SHININESS, shininess ); } else { RageColor c = diffuse; c.r += emissive.r + ambient.r; c.g += emissive.g + ambient.g; c.b += emissive.b + ambient.b; glColor4fv( c ); } } void RageDisplay_OGL::SetLighting( bool b ) { if( b ) glEnable( GL_LIGHTING ); else glDisable( GL_LIGHTING ); } void RageDisplay_OGL::SetLightOff( int index ) { glDisable( GL_LIGHT0+index ); } void RageDisplay_OGL::SetLightDirectional( int index, const RageColor &ambient, const RageColor &diffuse, const RageColor &specular, const RageVector3 &dir ) { glPushMatrix(); glLoadIdentity(); glEnable( GL_LIGHT0+index ); glLightfv( GL_LIGHT0+index, GL_AMBIENT, ambient ); glLightfv( GL_LIGHT0+index, GL_DIFFUSE, diffuse ); glLightfv( GL_LIGHT0+index, GL_SPECULAR, specular ); float position[4] = {dir.x, dir.y, dir.z, 0}; glLightfv( GL_LIGHT0+index, GL_POSITION, position ); glPopMatrix(); } void RageDisplay_OGL::SetCullMode() { switch(mode) { case CULL_BACK: glEnable(GL_CULL_FACE); glCullFace(GL_BACK); break; case CULL_FRONT: glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); break; case CULL_NONE: glDisable(GL_CULL_FACE); break; default: ASSERT(0); } } const RageDisplay::PixelFormatDesc* RageDisplay_OGL::GetPixelFormatDesc(PixelFormat pf) const { ASSERT(pf < NUM_PixelFormat); return &PIXEL_FORMAT_DESC[pf]; } bool RageDisplay_OGL::SupportsThreadedRendering() { return g_pWind->SupportsThreadedRendering(); } void RageDisplay_OGL::BeginConcurrentRenderingMainThread() { g_pWind->BeginConcurrentRenderingMainThread(); } void RageDisplay_OGL::EndConcurrentRenderingMainThread() { g_pWind->EndConcurrentRenderingMainThread(); } void RageDisplay_OGL::BeginConcurrentRendering() { g_pWind->BeginConcurrentRendering(); RageDisplay::BeginConcurrentRendering(); } void RageDisplay_OGL::EndConcurrentRendering() { g_pWind->EndConcurrentRendering(); } void RageDisplay_OGL::DeleteTexture(unsigned iTexture) { if (iTexture == 0) return; if (g_mapRenderTargets.find(iTexture) != g_mapRenderTargets.end()) { delete g_mapRenderTargets[iTexture]; g_mapRenderTargets.erase(iTexture); return; } DebugFlushGLErrors(); glDeleteTextures(1, reinterpret_cast<GLuint*>(&iTexture)); DebugAssertNoGLError(); } PixelFormat RageDisplay_OGL::GetImgPixelFormat(RageSurface* &img, bool& bFreeImg, int width, int height, bool bPalettedTexture) { PixelFormat pixfmt = FindPixelFormat(img->format->BitsPerPixel, img->format->Rmask, img->format->Gmask, img->format->Bmask, img->format->Amask); bool bSupported = true; if (!bPalettedTexture && img->fmt.BytesPerPixel == 1 && !g_bColorIndexTableWorks) bSupported = false; if (pixfmt == PixelFormatInvalid || !SupportsSurfaceFormat(pixfmt)) bSupported = false; if (!bSupported) { pixfmt = PixelFormat_RGBA8; ASSERT(SupportsSurfaceFormat(pixfmt)); const PixelFormatDesc* pfd = DISPLAY->GetPixelFormatDesc(pixfmt); RageSurface* imgconv = CreateSurface(img->w, img->h, pfd->bpp, pfd->masks[0], pfd->masks[1], pfd->masks[2], pfd->masks[3]); RageSurfaceUtils::Blit(img, imgconv, width, height); img = imgconv; bFreeImg = true; } else { bFreeImg = false; } return pixfmt; } void SetPixelMapForSurface(int glImageFormat, int glTexFormat, const RageSurfacePalette* palette) { if( glImageFormat != GL_COLOR_INDEX || glTexFormat == GL_COLOR_INDEX8_EXT ) { glPixelTransferi( GL_MAP_COLOR, false ); return; } GLushort buf[4][256]; memset(buf, 0, sizeof(buf)); for (int i = 0; i < palette->ncolors; ++i) { buf[0][i] = SCALE(palette->colors[i].r, 0, 255, 0, 65535); buf[1][i] = SCALE(palette->colors[i].g, 0, 255, 0, 65535); buf[2][i] = SCALE(palette->colors[i].b, 0, 255, 0, 65535); buf[3][i] = SCALE(palette->colors[i].a, 0, 255, 0, 65535); } DebugFlushGLErrors(); glPixelMapusv(GL_PIXEL_MAP_I_TO_R, 256, buf[0]); glPixelMapusv(GL_PIXEL_MAP_I_TO_G, 256, buf[1]); glPixelMapusv(GL_PIXEL_MAP_I_TO_B, 256, buf[2]); glPixelMapusv(GL_PIXEL_AMP_I_TO_A, 256, buf[3]); glPixelTransferi(GL_MAP_COLOR, true); DebugAssertNoGLError(); } unsigned RageDisplay_OGL::CreateTexture( PixelFormat pixfmt, RageSurface* pImg, bool bGenerateMipMaps) { ASSERT(pixfmt < NUM_PixelFormat); bool bFreeImg; PixelFormat SurfacePixFmt = GetImgPixelFormat(pImg, bFreeImg, pImg->w, pImg->h, pixfmt == PixelFormat_PAL); ASSERT(SurfacePixFmt != PixelFormat_Invalid); GLenum glTexFormat = g_GLPixFmtInfo[pixfmt].internalfmt; GLenum glImageFormat = g_GLPixFmtInfo[SurfacePixFmt].format; GLenum glImageType = g_GLPixFmtInfo[SurfacePixFmt].type; SetPixelMapForSurface(glImageFormat, glTexFormat, pImg->format->palette); if (bGenerateMipMap && g_gluVersion < 13) { switch(pixfmt) { case PixelFormat_RGBA8: case PixelFormat_RGB8: case PixelFormat_PAL: case PixelFormat_BGR8: break; default: LOG->Trace("Can't generate mipmaps for type %s because GLU version %.1f is too old.", GLToString(glImageType).c_str(), g_gluVersion / 10.0f); bGenerateMipMaps = false; break; } } SetTextureUnit(TextureUnit_1); unsigned int iTexHandle; glGenTextures(1, reinterpret_cast<GLuint*>(&iTexHandle)); ASSERT(iTexHandle); glBindTexture(GL_TEXTURE_2D, iTexHandle); if (g_pWind->GetActualVideoModeParams().bAnisotropicFiltering && GLExt.HasExtension("GL_EXT_texture_filter_anisotropic")) { GLfloat fLargestSupportedAnisotropy; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargestSupportedAnisotropy); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargestSupportedAnisotropy); } SetTextureFiltering(TextureUnit_1, true); SetTextureWrapping(TextureUnit_1, false); glPixelStorei(GL_UNPACK_ROW_LENGTH, pImg->pitch / pImg->format->BytesPerPixel); if (pixfmt == PixelFormat_PAL) { GLubyte palette[256 * 4]; memset(palette, 0, sizeof(palette)); int p = 0; for( int i = 0; i < pImg->format->palette->ncolors; ++i ) { palette[p++] = pImg->format->palette->colors[i].r; palette[p++] = pImg->format->palette->colors[i].g; palette[p++] = pImg->format->palette->colors[i].b; palette[p++] = pImg->format->palette->colors[i].a; } GLExt.glColorTableEXT(GL_TEXTURE_2D, GL_RGBA8, 256, GL_RGBA, GL_UNSIGNED_BYTE, palette); GLint iRealFormat = 0; GLExt.glGetColorTableParameterivEXT(GL_TEXTURE_2D, GL_COLOR_TABLE_FORMAT, &iRealFormat); ASSERT(iRealFormat == GL_RGBA8); } LOG->Trace( "%s (format %s, %ix%i, format %s, type %s, pixfmt %i, imgpixfmt %i)", bGenerateMipMaps? "gluBuild2DMipmaps":"glTexImage2D", GLToString(glTexFormat).c_str(), pImg->w, pImg->h, GLToString(glImageFormat).c_str(), GLToString(glImageType).c_str(), pixfmt, SurfacePixFmt ); DebugFlushGLErrors(); if (bGenerateMipMaps) { GLenum error = gluBuild2DMipmaps( GL_TEXTURE_2D, glTexFormat, pImg->w, pImg->h, glImageFormat, glImageType, pImg->pixels); ASSERT_M(error == 0, (char*)gluErrorString(error)); } else { glTexImage2D( GL_TEXTURE_2D, 0, glTexFormat, power_of_two(pImg->w), power_of_two(pImg->h), 0, glImageFormat, glImageType, NULL); if (pImg->pixels) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, pImg->w, pImg->h, glImageFormat, glImageType, pImg->pixels); DebugAssertNoGLError(); } if (pixfmt == PixelFormat_PAL) { GLint iSize = 0; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GLenum(GL_TEXTURE_INDEX_SIZE_EXT), &iSize); if (iSize != 8) RageException::Throw("Thought paletted textures worked, but they don't"); } glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glFlush(); if (bFreeImg) delete pImg; return iTexHandle; } struct RageTextureLock_OGL:public RageTextureLock, public InvalidateObject { public: RageTextureLock_OGL() { m_iTexHandle = 0; m_iBuffer = 0; CreateObject(); } ~RageTextureLock_OGL() { ASSERT(m_iTexHandle == 0); GLExt.glDeleteBuffersARB(1, &m_iBuffer); } void Invalidate() { m_iTexHandle = 0; } void Lock(unsigned iTexHandle, RageSurface *pSurface) { ASSERT(m_iTexHandle == 0); ASSERT(pSurface->pixels == NULL); CreateObject(); m_iTexHandle = iTexHandle; GLExt.glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_iBuffer); int iSize = pSurface->h * pSurface->pitch; GLExt.glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, iSize, NULL, GL_STREAM_DRAW); void *pSurfaceMemory = GLExt.glMapBufferARB( GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY ); pSurface->pixels = (uint8*)pSurfaceMemory; pSurface->pixels_owned = false; } void Unlock(RageSurface* pSurface, bool bChanged) { GLExt.glUnmapBufferARB( GL_PIXEL_UNPACK_BUFFER_ARB ); pSurface->pixels = (uint8_t *) BUFFER_OFFSET(0); if (bChanged) DISPLAY->UpdateTexture(m_iTexHandle, pSurface, 0, 0, pSurface->w, pSurface->h); pSurface->pixels = NULL; m_iTexHandle = 0; GLExt.glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); } private: void CreateObject() { if( m_iBuffer != 0 ) return; DebugFlushGLErrors(); GLExt.glGenBuffersARB( 1, &m_iBuffer ); DebugAssertNoGLError(); } GLuint m_iBuffer; unsigned m_iTexHandle; }; RageTextureLock *RageDisplay_OGL::CreateTextureLock() { if( !GLExt.HasExtension("GL_ARB_pixel_buffer_object") ) return NULL; return new RageTextureLock_OGL; } void RageDisplay_OGL::UpdateTexture( unsigned iTexHandle, RageSurface* pImg, int iXOffset, int iYOffset, int iWidth, int iHeight ) { glBindTexture( GL_TEXTURE_2D, iTexHandle ); bool bFreeImg; PixelFormat SurfacePixFmt = GetImgPixelFormat( pImg, bFreeImg, iWidth, iHeight, false ); glPixelStorei( GL_UNPACK_ROW_LENGTH, pImg->pitch / pImg->format->BytesPerPixel ); GLenum glImageFormat = g_GLPixFmtInfo[SurfacePixFmt].format; GLenum glImageType = g_GLPixFmtInfo[SurfacePixFmt].type; if( pImg->format->palette ) { GLenum glTexFormat = 0; glGetTexLevelParameteriv( GL_PROXY_TEXTURE_2D, 0, GLenum(GL_TEXTURE_INTERNAL_FORMAT), (GLint *) &glTexFormat ); SetPixelMapForSurface( glImageFormat, glTexFormat, pImg->format->palette ); } glTexSubImage2D( GL_TEXTURE_2D, 0, iXOffset, iYOffset, iWidth, iHeight, glImageFormat, glImageType, pImg->pixels ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glFlush(); if( bFreeImg ) delete pImg; } class RenderTarget_FramebufferObject: public RenderTarget { public: RenderTarget_FramebufferObject(); ~RenderTarget_FramebufferObject(); void Create( const RenderTargetParam &param, int &iTextureWidthOut, int &iTextureHeightOut ); unsigned GetTexture() const { return m_iTexHandle; } void StartRenderingTo(); void FinishRenderingTo(); virtual bool InvertY() const { return true; } private: unsigned int m_iFrameBufferHandle; unsigned int m_iTexHandle; unsigned int m_iDepthBufferHandle; }; RenderTarget_FramebufferObject::RenderTarget_FramebufferObject() { m_iFrameBufferHandle = 0; m_iTexHandle = 0; m_iDepthBufferHandle = 0; } RenderTarget_FramebufferObject::~RenderTarget_FramebufferObject() { if( m_iDepthBufferHandle ) GLExt.glDeleteRenderbuffersEXT( 1, reinterpret_cast<GLuint*>(&m_iDepthBufferHandle) ); if( m_iFrameBufferHandle ) GLExt.glDeleteFramebuffersEXT( 1, reinterpret_cast<GLuint*>(&m_iFrameBufferHandle) ); if( m_iTexHandle ) glDeleteTextures( 1, reinterpret_cast<GLuint*>(&m_iTexHandle) ); } void RenderTarget_FramebufferObject::Create(const RenderTargetParam& param, int& iTextureWidthOut, int& iTextureHeightOut) { m_Param = param; DebugFlushGLErrors(); glGenTextures(1, reinterpret_cast<GLuint*>(&m_iTexHandle)); ASSERT(m_iTexHandle); int iTextureWidth = power_of_two(param.iWidth); int iTextureHeight = power_of_two(param.iHeight); iTextureWidthOut = iTextureWidth; iTextureHeightOut = iTextureHeight; glBindTexture(GL_TEXTURE_2D, m_iTexHandle); GLenum internalformat; GLenum type = param.bWidthAlpha ? GL_RGBA : GL_RGB; if (param.bFloat && GLExt.m_bGL_ARB_texture_float) internalformat = param.bWithAlpha ? GL_RGBA16F_ARB : GL_RGB16F_ARB; else internalformat = param.bWithAlpha ? GL_RGBA8 : GL_RGB8; glTexImage2D(GL_TEXTURE_2D, 0, internalformat, iTextureWidth, iTextureHeight, 0, type, GL_UNSIGNED_BYTE, NULL); DebugAssertNoGLError(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLExt.glGenFramebuffersEXT(1, reinterpret_cast<GLuint*>(&m_iFramebufferHandle)); ASSERT(m_iFramebufferHandle); GLExt.glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_iFramebufferHandle); GLExt.glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_iTexHandle, 0); DebugAssertNoGLError(); if (param.bWithDepthBuffer) { GLExt.glGenRenderbuffersEXT(1, reinterpret_cast<GLuint*>(&m_iDepthBufferHandle)); ASSERT(m_iDepthbufferHandle); GLExt.glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, iTextureWidth, iTextureHeight); GLExt.glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_iDepthBufferHandle); } GLenum status = GLExt.glCheckFramebuffersStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: FAIL_M("GL_FRAMEBUFFER_UNSUPPORTED_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT"); break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: FAIL_M("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT"); break; default: ASSERT(0); } GLExt.glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } void RenderTarget_FramebufferObject::StartRenderingTo() { GLExt.glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_iFramebufferHandle); } void RenderTarget_FramebufferObject::FinishRendering() { GLExt.glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } bool RageDisplay_OGL::SupportsRenderToTexture() const { return GLExt.m_bGL_EXT_framebuffer_object || g_pWind->SupportsRenderToTexture(); } unsigned RageDisplay_OGL::CreateRenderTarget(const RenderTargetParam& param, int& iTextureWidthOut, int& iTextureHeightOut) { RenderTarget* pTarget; if (GLExt.m_bGL_EXT_framebuffer_object) pTarget = new RenderTarget_FramebufferObject; else pTarget = g_pWind->CreateRenderTarget(); pTarget->Create(param, iTextureWidthOut, iTextureHeightOut); unsigned iTexture = pTarget->GetTexture(); ASSERT(g_mapRenderTargets.find(iTexture) == g_mapRenderTargets.end()); g_mapRenderTargets[iTexture] = pTarget; return iTexture; } void RageDisplay_OGL::SetRenderTarget(unsigned iTexture, bool bPreserveTexture) { if (iTexture == 0) { g_bInvertY = false; glFrontFace(GL_CCW); DISPLAY->CameraPopMatrix(); int fWidth = g_pWind->GetActualVideoModeParams().width; int fHeight = g_pWind->GetActualVideoModeParams().height; glViewport(0, 0, fWidth, fHeight); if (g_pCurrentRenderTarget) g_pCurrentRenderTarget->FinishRenderingTo(); g_pCurrentRenderTarget = NULL; return; } if (g_pCurrentRenderTarget != NULL) SetRenderTarget(0, true); ASSERT(g_mapRenderTargets.find(iTexture) != g_mapRenderTargets.end()); RenderTarget* pTarget = g_mapRenderTargets[iTexture]; pTarget->StartRenderingTo(); g_pCurrentRenderTarget = pTarget; glViewport(0, 0, pTarget->GetParam().iWidth, pTarget->GetParam().iHeight); g_bInvertY = pTarget->InvertY(); if( g_bInvertY ) glFrontFace( GL_CW ); DISPLAY->CameraPushMatrix(); SetDefaultRenderStates(); glClearColor(0, 0, 0, 0); SetZWrite(true); if (!bPreserveTexture) { int iBit = GL_COLOR_BUFFER_BIT; if (pTarget->GetParam().bWithDepthBuffer) iBit |= GL_DEPTH_BUFFER_BIT; glClear(iBit); } } void RageDisplay_OGL::SetPolygonMode(PolygonMode pm) { Glenum m; switch(pm) { case POLYGON_FILL: m = GL_FILL; break; case POLYGON_LINE: m = GL_LINE; break; default: ASSERT(0); return; } glPolygonMode(GL_FRONT_AND_BACK, m); } void RageDisplay_OGL::SetLineWidth(float fWidth) { glLineWidth(fWidth); } RString RageDisplay_OGL::GetTextureDiagnostics(unsigned iTexture) const { return RString(); } void RageDisplay_OGL::SetAlphaTest(bool b) { glAlphaFunc(GL_GREATOR, 0.01f); if (b) glEnable(GL_ALPHA_TEST); else glDisable(GL_ALPHA_TEST); } bool RageDisplay_OGL::SupportsSurfaceFormat(PixelFormat pixfmt) { switch(g_GLPixelFmtInfo[pixfmt].type) { case GL_UNSIGNED_SHORT_1_5_5_5_REV: return GLExt.m_bGL_EXT_bgra && g_bReversePackedPixelsWorks; default: return true; } } bool RageDisplay_OGL::SupportsTextureFormat(PixelFormat pixfmt, bool bRealtime) { if (bRealtime && !SupportsSurfaceFormat(pixfmt)) return false; switch(g_GLPixFmtInfo[pixfmt].format) { case GL_COLOR_INDEX: return GLExt.glColorTableEXT && GLExt.glGetColorTableParameterivEXT; case GL_BGR: case GL_BGRA: return GLExt.m_bGL_EXT_bgra; default: return true; } } bool RageDisplay_OGL::SupportsPerVertexMatrixScale() { return GLExt.glGenBuffersARB && g_bTextureMatrixShader != 0; } void RageDisplay_OGL::SetSphereEnvironmentMapping(TextureUnit* tu, bool b) { if (!SetTextureUnit(tu)) return; if (b) { glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); } else { glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } }
[ [ [ 1, 2365 ] ] ]
ca5b22823edb5b971ce1306fb820338740d436e0
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Scada/ScdOPC/Client/GroupParamsDlg.h
817bf596cccf0ae93bf7589d973d478048cbfaf6
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
h
//************************************************************************** // // Copyright (c) FactorySoft, INC. 1996-1998, All Rights Reserved // //************************************************************************** // // Filename : GroupParamsDlg.h // $Author : Jim Hansen // // Description: Dialog to view and modify the group parameters. // (mainly the update rate and active flag) // //************************************************************************** class GroupParamsDlg : public CDialog { // Construction public: GroupParamsDlg(IUnknown* pGroup, CWnd* pParent = NULL); // Dialog Data //{{AFX_DATA(GroupParamsDlg) enum { IDD = IDD_GROUP_PARAMS }; BOOL m_active; float m_deadband; DWORD m_LCID; CString m_name; DWORD m_rate; long m_timebias; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(GroupParamsDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: OPCGroupStateMgt opcGroup; OPCHANDLE client, server; // Generated message map functions //{{AFX_MSG(GroupParamsDlg) virtual BOOL OnInitDialog(); afx_msg void OnApply(); virtual void OnOK(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ [ [ 1, 52 ] ] ]
a8b780dd897d9f2428ec3eec8661cf435b9ca230
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/DBClient/DBField.cpp
40e9b23ed350c406ac7627d34de47aa9591dc3bd
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
4,871
cpp
//============================================================================ // Date : 26.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry ([email protected]) //============================================================================ #include "DBField.h" #include "CommonUtils.h" #include "SystemUtils.h" #include "IVariantImpl.h" IFieldImpl::IFieldImpl() { } bool IFieldImpl::FinalizeCreate() { return true; } void IFieldImpl::BeforeDestroy() { Common::ISyncObject Locker(GetSynObj()); Field.Release(); Statement.Release(); Connection.Release(); } IFaces::RetCode IFieldImpl::GetField(long *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { *value = Field->GetAsLong(); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(unsigned long *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { *value = Field->GetAsULong(); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(double *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { *value = Field->GetAsDouble(); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetStrField(IFaces::IVariant **value, bool asUnicode) const { if (!value || *value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { std::string Value = Field->GetAsString(); Common::RefObjPtr<IFaces::IVariant> NewVar = IFacesImpl::CreateVariant(GetSynObj()); if (asUnicode) (IFacesImpl::IVariantHelper(NewVar)) = System::AStringToWString(Value).c_str(); else (IFacesImpl::IVariantHelper(NewVar)) = Value.c_str(); return NewVar.QueryInterface(value); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(IFaces::DBIFaces::DateTime *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { std::tm Tm = Field->GetAsTimestamp(); value->Dt.Year = Tm.tm_year + 1900; value->Dt.Month = Tm.tm_mon; value->Dt.Day = Tm.tm_mday; value->Tm.Hour = Tm.tm_hour; value->Tm.Hour = Tm.tm_min; value->Tm.Hour = Tm.tm_sec; } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(IFaces::DBIFaces::Date *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { Common::StringVectorPtr Items = Common::SplitString(Field->GetAsString(), ':'); if (!Items.get() || Items->size() != 3) return IFaces::retFail; value->Year = Common::FromString<unsigned short>((*Items.get())[0]); value->Month = Common::FromString<unsigned short>((*Items.get())[1]); value->Day = Common::FromString<unsigned short>((*Items.get())[2]); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(IFaces::DBIFaces::Time *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { DB::TimeStruct Tm = Field->GetAsTime(); value->Hour = Tm.Hour; value->Min = Tm.Min; value->Sec = Tm.Sec; } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode IFieldImpl::GetField(bool *value) const { if (!value) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Field.Get()) return IFaces::retFail; try { *value = Field->GetAsBool(); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } void IFieldImpl::Init(Common::SharedPtr<DB::Connection> connection, Common::SharedPtr<DB::Statement> statement, unsigned index) { Common::ISyncObject Locker(GetSynObj()); Field = statement->GetField(index); Statement = statement; Connection = connection; }
[ "TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277" ]
[ [ [ 1, 206 ] ] ]
c37dd7a8eee9d9c8d3b8707a89d6c67600e25a71
5e1b3c4e0dcbaf0c591203c7b1737e8bdbc5053c
/lib/util/timer.h
3dae545891e40649c129ef3489106b9dc5a685bc
[ "BSD-2-Clause" ]
permissive
WexWorks/Pub
14b1cc590820ac094df9c7235cbc15ce46c8a23f
dc9c3b542a4150541e1bb6861d4cb55667bc5150
refs/heads/master
2016-09-05T16:39:04.182012
2011-07-21T01:15:36
2011-07-21T01:15:36
2,063,874
0
0
null
null
null
null
UTF-8
C++
false
false
681
h
// Copyright (c) 2011 by WexWorks, LLC -- All Rights Reserved #ifndef TIMER_H_ #define TIMER_H_ #ifdef WINDOWS #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #define VC_EXTRALEAN 1 #define NOMINMAX #include "windows.h" #endif typedef LARGE_INTEGER TimerVal; #endif #if defined LINUX || defined ANDROID #include <sys/time.h> typedef struct timeval TimerVal; #endif namespace ww { class Timer { public: Timer(); ~Timer() {} double Elapsed() const; void Restart(); static const char *String(double seconds); const char *String() const { return String(Elapsed()); } private: TimerVal start_time_; }; } // namespace ww #endif // TIMER_H_
[ [ [ 1, 42 ] ] ]
16aa1b0c921d32800c25d95d594d0f514ed98cc5
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/threads/multithreaded_object_extension.cpp
8880d5a432dd41117916d5dd4b9e9b556c6a4c94
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
6,978
cpp
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_MULTITHREADED_OBJECT_EXTENSIOn_CPP #define DLIB_MULTITHREADED_OBJECT_EXTENSIOn_CPP #include "multithreaded_object_extension.h" namespace dlib { // ---------------------------------------------------------------------------------------- multithreaded_object:: multithreaded_object ( ): s(m_), is_running_(false), should_stop_(false), threads_started(0) { } // ---------------------------------------------------------------------------------------- multithreaded_object:: ~multithreaded_object ( ) { DLIB_ASSERT(number_of_threads_alive() == 0, "\tmultithreaded_object::~multithreaded_object()" << "\n\tYou have let a multithreaded object destruct itself before terminating its threads" << "\n\tthis: " << this ); } // ---------------------------------------------------------------------------------------- void multithreaded_object:: clear ( ) { auto_mutex M(m_); stop(); wait(); dead_threads.clear(); is_running_ = false; should_stop_ = false; } // ---------------------------------------------------------------------------------------- bool multithreaded_object:: is_running ( ) const { auto_mutex M(m_); return is_running_; } // ---------------------------------------------------------------------------------------- unsigned long multithreaded_object:: number_of_threads_registered ( ) const { auto_mutex M(m_); return thread_ids.size() + dead_threads.size(); } // ---------------------------------------------------------------------------------------- unsigned long multithreaded_object:: number_of_threads_alive ( ) const { auto_mutex M(m_); return threads_started; } // ---------------------------------------------------------------------------------------- void multithreaded_object:: wait ( ) const { auto_mutex M(m_); DLIB_ASSERT(thread_ids.is_in_domain(get_thread_id()) == false, "\tvoid multithreaded_object::wait()" << "\n\tYou can NOT call this function from one of the threads registered in this object" << "\n\tthis: " << this ); while (threads_started > 0) s.wait(); } // ---------------------------------------------------------------------------------------- void multithreaded_object:: start ( ) { auto_mutex M(m_); const unsigned long num_threads_registered = dead_threads.size() + thread_ids.size(); // start any dead threads for (unsigned long i = threads_started; i < num_threads_registered; ++i) { if (create_new_thread<multithreaded_object,&multithreaded_object::thread_helper>(*this) == false) { should_stop_ = true; is_running_ = false; throw thread_error(); } ++threads_started; } is_running_ = true; should_stop_ = false; s.broadcast(); } // ---------------------------------------------------------------------------------------- void multithreaded_object:: pause ( ) { auto_mutex M(m_); is_running_ = false; } // ---------------------------------------------------------------------------------------- void multithreaded_object:: stop ( ) { auto_mutex M(m_); should_stop_ = true; is_running_ = false; s.broadcast(); } // ---------------------------------------------------------------------------------------- bool multithreaded_object:: should_stop ( ) const { auto_mutex M(m_); DLIB_ASSERT(thread_ids.is_in_domain(get_thread_id()), "\tbool multithreaded_object::should_stop()" << "\n\tYou can only call this function from one of the registered threads in this object" << "\n\tthis: " << this ); while (is_running_ == false && should_stop_ == false) s.wait(); return should_stop_; } // ---------------------------------------------------------------------------------------- void multithreaded_object:: thread_helper( ) { mfp mf; const thread_id_type id = get_thread_id(); try { // if there is a dead_thread sitting around then pull it // out and put it into mf { auto_mutex M(m_); if (dead_threads.size() > 0) { dead_threads.dequeue(mf); mfp temp; thread_id_type id_temp = id; temp = mf; thread_ids.add(id_temp,temp); } } if (mf.is_set()) { // call the registered thread function mf(); auto_mutex M(m_); if (thread_ids.is_in_domain(id)) { mfp temp; thread_id_type id_temp; thread_ids.remove(id,id_temp,temp); } // put this thread's registered function back into the dead_threads queue dead_threads.enqueue(mf); } auto_mutex M(m_); --threads_started; // If this is the last thread to terminate then // signal that that is the case. if (threads_started == 0) { is_running_ = false; should_stop_ = false; s.broadcast(); } } catch (...) { auto_mutex M(m_); if (thread_ids.is_in_domain(id)) { mfp temp; thread_id_type id_temp; thread_ids.remove(id,id_temp,temp); } --threads_started; // If this is the last thread to terminate then // signal that that is the case. if (threads_started == 0) { is_running_ = false; should_stop_ = false; s.broadcast(); } throw; } } // ---------------------------------------------------------------------------------------- } #endif // DLIB_MULTITHREADED_OBJECT_EXTENSIOn_CPP
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 245 ] ] ]
176f410f2dd011b24090d1057130b73c0603b0ca
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/BASIC1/PipeTerm.CPP
d9360d0d8cafadbc95451909623eb8509b034eb5
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,434
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "sc_defs.h" #define __PIPETERM_CPP #include "pipeterm.h" #include "scd_wm.h" //#include "optoff.h" //========================================================================== static double Drw_PipeTerm[] = { DD_Poly, -3,3, 3,0, -3,-3, -3,3, DD_TagPos, 0, -6.5, DD_End }; static IOAreaRec PipeTermIOAreaList[] = {{"Inputof Stack", "In" , 0, LIO_In0 , nc_MLnk, 0, 1, IOPipeEntry}, {NULL}}; //========================================================================== IMPLEMENT_MODELUNIT(CPipeTerm, "PipeTerm", "1",Drw_PipeTerm, "Feed", "T", TOC_ALL|TOC_GRP_GENERAL|TOC_STD_KENWALT, "Process:Unit:Pipe_Terminator", "Pipe Terminator") //========================================================================== CPipeTerm::CPipeTerm (pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) : MdlNode(pClass_, TagIn, pAttach, eAttach), //Contents("Content", this, TOA_Embedded), m_Flows("Flows", this, TOA_Embedded), m_VPB("VL_Basic", this, NULL), m_FRB("Reg", FBRShow_All, FBReg_Pi|FBReg_Qm|FBReg_Qv|FBReg_QvStep, FBReg_Off) { SetAllowedModes(false, NM_All|SM_Direct/*|SM_Inline|SM_Buffered*/|HM_All|LFM_Simple|LFM_Linear|LFM_Full);// "Transfer", "Inline", NULL); //SetAllowedFlowModes(); AttachClassInfo(nc_MSrcSnk,NULL); //FEP.AssignFlwEqnGroup(PipeGroup, PipeGroup.Default(), this); AttachIOAreas(PipeTermIOAreaList, &ValveGroup, &ValveGroup); //Initialise(); m_dHead=0; m_dPOut=Std_P; }; // ------------------------------------------------------------------------- CPipeTerm::~CPipeTerm () { }; // ------------------------------------------------------------------------- void CPipeTerm::ResetData(flag Complete) { for (int i=0; i<NoFlwIOs(); i++) for (int j=0; j<NIOFBs(i); j++) IOFB(i,j)->ResetData(Complete); } //-------------------------------------------------------------------------- void CPipeTerm::BuildDataDefn(DataDefnBlk &DDB) { DDB.BeginStruct(this, NULL, NULL, DDB_NoPage); DDB.Text ("Flow Conditions"); DDB.Double ("Mass_Flow", "Qm", DC_Qm, "kg/s", xidQm, this, isResult|noFile|noSnap); DDB.Double ("Vol_Flow", "Qv", DC_Qv, "L/s", xidQv, this, isResult|noFile|noSnap); DDB.Double ("NVol_Flow", "NQv", DC_NQv, "NL/s", xidNQv, this, isResult|noFile|noSnap); DDB.Double ("Temperature", "T", DC_T, "C", xidTemp, this, isResult|noFile|noSnap); DDB.Double ("Density", "Rho", DC_Rho, "kg/m^3", xidRho, this, isResult|noFile|noSnap); DDB.Double ("NDensity", "NRho", DC_Rho, "kg/m^3", xidNRho, this, isResult|noFile|noSnap); DDB.Double ("PressureIn", "PIn", DC_P, "kPag", xidPIn, this, isResult|noFile|noSnap); DDB.Double ("PressureOut", "POut", DC_P, "kPag", xidPOut, this, isResult|noFile|noSnap); DDB.Visibility(NSHM_All); flag ParmOK=true; DDB.Visibility(); DDB.Text (""); DDB.Double("PressureOutRqd","POutRqd", DC_P, "kPag", &m_dPOut, this, isParm); DDB.Double("Head", "", DC_L, "m", &m_dHead, this, isParm); BuildDataDefnElevation(DDB); DDB.Text (""); m_FRB.BuildDataDefn(DDB, this, true); DDB.Visibility(NM_Dynamic|SM_All|HM_All); DDB.Text (""); m_VPB.BuildDataDefn(DDB, this, "Posn", 1); DDB.Visibility(NSHM_All); if (NoFlwIOs()>0 && !DDB.ForFileSnpScn()) IOFB(0,0)->BuildDataDefn(FBDDOpt_WithAll, DDB, this, "CtrlEqn", 2); DDB.Visibility(); DDB.Object(&m_Flows, this, NULL, NULL, DDB_RqdPage); DDB.Text(""); DDB.EndStruct(); } //// -------------------------------------------------------------------------- // //flag CPipeTerm::DataXchg(DataChangeBlk & DCB) // { // if (NIOs>=1 && DCB.dwUserInfo==1 && IOFB_Rmt(0,0)->DataXchg(DCB)) // return 1; // if (NIOs>=2 && DCB.dwUserInfo==2 && IOFB_Rmt(1,0)->DataXchg(DCB)) // return 1; // if (MN_Lnk::DataXchg(DCB)) // return 1; // if (RB.DataXchg(DCB)) // return 1; // // return 0; // } // ------------------------------------------------------------------------- flag CPipeTerm::DataXchg(DataChangeBlk & DCB) { switch (DCB.lHandle) { // case xidSSMode: // if (DCB.rB) // { // SSMode=*DCB.rB; // if (SSMode & SSM_ConstP) // m_iCFWhat &= ~CFWhatFlow; // } // DCB.B=SSMode; // return 1; // case xidQmRqd: // if (DCB.rD) // Contents.SetQmRqdTo(GEZ(*DCB.rD), true); // DCB.D=Contents.QmRqd(); // return 1; // case xidQvRqd: // if (DCB.rD) // Contents.SetQvRqdTo(GEZ(*DCB.rD), !DCB.ForFiling());// CNM true); recovery of QAL // DCB.D=Contents.QvRqd(); // return 1; // case xidNQvRqd: // if (DCB.rD) // Contents.SetNQvRqdTo(GEZ(*DCB.rD), !DCB.ForFiling());// CNM true); recovery of QAL // DCB.D=Contents.NQvRqd(); // return 1; // case xidTRqd: // if (DCB.rD) // Contents.SetTRqdTo(Range(CDB.MinT, *DCB.rD, CDB.MaxT)); // DCB.D=Contents.TRqd(); // return 1; // case xidPRqd: // if (DCB.rD) // Contents.SetPRqdTo(Max(1.0, *DCB.rD)); //// Contents.SetPRqdTo(Range(CDB.MinP, Max(1.0, *DCB.rD), CDB.MaxP)); // DCB.D=Contents.PRqd(); // return 1; case xidRho: DCB.D=m_Flows.Rho(som_ALL); return 1; // case xidLevel: // DCB.D=dNAN; // return 1; // case xidPMean: // if (DCB.rD) // m_Flows.SetPress(Max(1.0, *DCB.rD)); // DCB.D=m_Flows.Press(); // return 1; // case xidSolFrac: // DCB.D=m_Flows.MassFrac(som_Sol); // return 1; // case xidLiqFrac: // DCB.D=m_Flows.MassFrac(som_Liq); // return 1; // case xidVapFrac: // DCB.D=m_Flows.MassFrac(som_Gas);//Frac(); // return 1; // case xidMoleVapFrac: // DCB.D=m_Flows.MoleFrac(som_Gas); // return 1; case xidTemp: if (DCB.rD) m_Flows.SetTemp(*DCB.rD); DCB.D=m_Flows.Temp();//som_ALL); return 1; } if (MdlNode::DataXchg(DCB)) return 1; if (m_FRB.DataXchg(DCB, this)) return 1; switch (DCB.dwUserInfo) { case 1: if (m_VPB.DataXchg(DCB)) return 1; break; case 2: if (NoFlwIOs()>0 && !DCB.ForFileSnpScn()) if (IOFB(0,0)->DataXchg(DCB)) return 1; break; } return 0; } // ------------------------------------------------------------------------- flag CPipeTerm::ValidateData(ValidateDataBlk & VDB) { flag OK=MdlNode::ValidateData(VDB); if (!m_FRB.ValidateData(VDB, this)) OK=false; m_dHead=GEZ(m_dHead); if(NoFlwIOs()>=1 && !IOFB(0,0)->ValidateData(VDB)) OK=false; EvalState(); //if (AllowMineServe()) // SetCI(1, m_FRB.What()== FBReg_Pi || m_FRB.What()==FBReg_Po); if (!OK) { int xxx=0; } return OK; }; // ------------------------------------------------------------------------- flag CPipeTerm::PreStartCheck() { return MdlNode::PreStartCheck(); }; //-------------------------------------------------------------------------- flag CPipeTerm::GetModelAction(CMdlActionArray & Acts) { //CMdlAction {MAT_NULL, MAT_State, MAT_Value}; CMdlAction M0(0, MAT_State, !m_VPB.On(), "Open", 1); CMdlAction M1(1, MAT_State, m_VPB.On(), "Close", 0); CMdlAction M2(2, MAT_Value, m_VPB.On(), "Manual Posn (%)", true, m_VPB.ManualPosition(this)*100, 0.0, 100.0, m_VPB.ActualPosition(this, &m_FRB)*100); Acts.SetSize(0); Acts.SetAtGrow(0, M0); Acts.SetAtGrow(1, M1); Acts.SetAtGrow(2, M2); Acts.SetAtGrow(3, CMdlAction(3, MAT_Switch)); return True; }; //-------------------------------------------------------------------------- flag CPipeTerm::SetModelAction(CMdlAction & Act) { switch (Act.iIndex) { case 0: m_VPB.SetOn(Act.iValue!=0); break; case 1: m_VPB.SetOn(Act.iValue!=0); break; case 2: m_VPB.SetManualPosition(Act.dValue*0.01); break; case 3: m_VPB.SetOn(!m_VPB.On()); break; } return true; }; //--------------------------------------------------------------------------- void CPipeTerm::PostConnect(int IONo) { //IOFB(IONo,0)->AssignFlwEqnGroup(ValveGroup, ValveGroup.Default(), this); MdlNode::PostConnect(IONo); }; //-------------------------------------------------------------------------- long CPipeTerm::NodeFlwTask(NodeFlwTasks Task) { if (Task==NFT_PBQueryRemove) { //if (fCrossConnected || NoFlwIOs()>1) // return 0; //if (NoFlwIOs()==0 || IO_In(0)) // return 0; // //long nIn=0; //long nOut=0; //for (int i=0; i<NoFlwIOs(); i++) // { // if (IO_In(i)) // nIn++; // else if (IO_Out(i)) // nOut++; // } // //if (nIn>0 || nOut>0) // return 0; //else // return 1; return 0; } else return MdlNode::NodeFlwTask(Task); } //-------------------------------------------------------------------------- void CPipeTerm::SetDatums(int Pass, CFlwNodeIndexList & List, int IOIn) { SetDatums_Node(Pass, List, IOIn, NULL); }; //-------------------------------------------------------------------------- flag CPipeTerm::Set_Sizes() { return true; }; //-------------------------------------------------------------------------- void CPipeTerm::StartSolution() { } //-------------------------------------------------------------------------- void CPipeTerm::StartStep() { //dTime=ICGetTimeInc(); } //--------------------------------------------------------------------------- void CPipeTerm::ConfigureJoins() { for (int i=0; i<NoProcessIOs(); i++) SetIO_Open(i, 0, false, ESS_Denied); //if (NoFlwIOs()>0) // { // if (0)//fForceOpen) // IOFB(0,0)->SetBiDirectionalFlow(); // else // IOFB(0,0)->SetUniDirectionalFlow(True, IOFB(0,0)->UDFOpenP(), 0.0);//FB.UDFCloseP());//OpenPress, CloseP); // } }; //-------------------------------------------------------------------------- void CPipeTerm::EvalJoinPressures(long JoinMask) { for (int i = 0; i < NoFlwIOs(); i++) { Set_IOP_Self(i,m_dPOut); if (NetMethod()==NM_Probal) { Set_IOP_Flng(i,m_dPOut); Clr_RhoH_Self(i); } else Set_IOP_RhoH_Self(i, m_dPOut, m_Flows.Rho(som_SL), m_dHead); } }; //-------------------------------------------------------------------------- flag CPipeTerm::EvalFlowEquations(eScdFlwEqnTasks Task, CSpPropInfo *pProps, int IONo, int FE, int LnkNo) { if (IONo>0 || FE>0) return False; if (Task!=FET_GetMode) IOFB(0,FE)->SetRegulator(m_FRB.What()); return IOFB(0,FE)->EvaluateFlwEqn(Task, pProps, m_VPB.On()!=0, false, m_VPB.ActualPosition(this, &m_FRB), &IOFBFlng_Rmt(0)->PhD(), NULL); }; //-------------------------------------------------------------------------- void CPipeTerm::EvalState() { }; //-------------------------------------------------------------------------- void CPipeTerm::EvalCtrlActions(eScdCtrlTasks Tasks) { //if (NoCtrlIOs()>0) // { // int io=CIOWithId_Self(CIOId_Pos); // if (io>=0) // m_VPB.SetReqdPosition(CIO_Value(io)); // } //if (!m_FRB.On()) m_VPB.EvalCtrlActions(this); } //-------------------------------------------------------------------------- void CPipeTerm::ClosureInfo() { int Dirn=0; if (m_Closure.DoFlows()) { CClosureInfo &CI=m_Closure[0]; for (int i=0;i<NoFlwIOs(); i++) { SpConduit &C=*IOConduit(i); if (IO_In(i)) { CI.m_HfLoss += C.totHf(); CI.m_HsLoss += C.totHs(); CI.m_MassLoss += C.QMass(); } else if (IO_Out(i)) { CI.m_HfGain += C.totHf(); CI.m_HsGain += C.totHs(); CI.m_MassGain += C.QMass(); } } } }; // -------------------------------------------------------------------------- void CPipeTerm::EvalProductsInit(EvalProductsInitTasks Task) { for (int i=0;i<NoFlwIOs(); i++) if (IO_Out(i) || IO_Zero(i)) EvalProductsInit_Source(Task, i, IOConduit(i)->QMass(som_SL), IOConduit(i)->QMass(som_Gas)); } //-------------------------------------------------------------------------- void CPipeTerm::EvalProducts(CNodeEvalIndex & NEI) { int i, nOut=0, nIn=0; bool CI2On=false; switch (NetMethod()) { case NM_Probal: case NM_Dynamic: { for (i=0;i<NoFlwIOs(); i++) { if (IO_Out(i) || IO_Zero(i)) { SpConduit& Q = *IOConduit(i); //Q.QZero(); //m_Flows.QZero(); m_Flows.SetTempPress(AmbientTemp(), IOP_Self(i)); Q.QSetM(m_Flows, som_ALL, IOQmEst_Out(i)*1e-6, IOP_Self(i)); CI2On=IO_Out(i); } else if (IO_In(i)) // Defined Input { m_Flows.QSetF(*IOConduit(i), som_ALL, 1.0, IOP_Self(i)); } } break; } } SetCI(2, CI2On); } //-------------------------------------------------------------------------- void CPipeTerm::EvalDerivs(CNodeEvalIndex & NEI) { }; //-------------------------------------------------------------------------- void CPipeTerm::EvalDiscrete() { m_VPB.EvalDiscrete(this); } //-------------------------------------------------------------------------- dword CPipeTerm::ModelStatus() { dword Status=MdlNode::ModelStatus(); if (NoFlwIOs()>0) { Status |= ((m_VPB.On() && m_VPB.ActualPosition(this, &m_FRB)>0.0) ? FNS_On : FNS_Off); Status |= (IOConduit(0)->QMass()>gs_DisplayZeroFlow ? FNS_UFlw : FNS_UNoFlw); int HasFlw=0; double TFlw=0.0; for (int i=0; i<NoFlwIOs(); i++) { TFlw+=IOQm_In(i); if (IOConduit(i)->QMass()>gs_DisplayZeroFlow) HasFlw=1; } Status |= (HasFlw ? FNS_UFlw : FNS_UNoFlw); if (NoFlwIOs()==1) { if (TFlw>1.0e-6) Status |= FNS_IsSnk; else if (TFlw<-1.0e-6) Status |= FNS_IsSrc; } } return Status; }; //-------------------------------------------------------------------------- flag CPipeTerm::CIStrng(int No, pchar & pS) { // NB check CBCount is large enough. switch (No-CBContext()) { case 1: pS="E\tBad Regulator Configuration"; return 1; case 2: pS="E\tReverse Flow into Pipe Terminator"; return 1; default: return MdlNode::CIStrng(No, pS); } }; //==========================================================================
[ [ [ 1, 10 ], [ 12, 14 ], [ 18, 24 ], [ 26, 37 ], [ 41, 80 ], [ 82, 92 ], [ 94, 95 ], [ 97, 230 ], [ 234, 247 ], [ 249, 249 ], [ 254, 254 ], [ 256, 260 ], [ 262, 266 ], [ 268, 271 ], [ 273, 274 ], [ 276, 328 ], [ 330, 330 ], [ 332, 357 ], [ 359, 359 ], [ 369, 377 ], [ 379, 396 ], [ 399, 408 ], [ 410, 417 ], [ 420, 459 ], [ 461, 462 ], [ 465, 465 ], [ 469, 469 ], [ 471, 475 ], [ 479, 483 ], [ 485, 485 ], [ 487, 487 ], [ 489, 492 ], [ 494, 510 ], [ 512, 512 ], [ 514, 519 ], [ 521, 542 ], [ 545, 551 ] ], [ [ 11, 11 ], [ 25, 25 ], [ 38, 40 ], [ 81, 81 ], [ 93, 93 ], [ 96, 96 ], [ 231, 233 ], [ 248, 248 ], [ 250, 253 ], [ 255, 255 ], [ 261, 261 ], [ 267, 267 ], [ 272, 272 ], [ 275, 275 ], [ 329, 329 ], [ 331, 331 ], [ 358, 358 ], [ 360, 368 ], [ 378, 378 ], [ 397, 398 ], [ 409, 409 ], [ 418, 419 ], [ 460, 460 ], [ 463, 464 ], [ 466, 468 ], [ 470, 470 ], [ 476, 478 ], [ 484, 484 ], [ 486, 486 ], [ 488, 488 ], [ 493, 493 ], [ 511, 511 ], [ 513, 513 ], [ 520, 520 ], [ 543, 544 ] ], [ [ 15, 17 ] ] ]
5a4a042025e0ee8fc1e0c495bba9e6cae75f1128
6e4bb28aaf9b5104647cf5e5f3b44dfbf2538b79
/bricks/AssemblyInfo.cpp
c8ba53d02b8efc58c716a5a55232cee3366c9336
[]
no_license
Spasik17/glarkanoid
ed67223d036cecc358b7a35d5ad54cd4862a4619
1476350df389a6d77422f7bf2d7f10e9a80384ec
refs/heads/master
2020-04-07T10:26:38.924253
2008-10-03T23:20:15
2008-10-03T23:20:15
35,031,224
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("bricks")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("bricks")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2008")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ "[email protected]@e7f348e6-90ee-11dd-a562-694a26f4c3aa" ]
[ [ [ 1, 40 ] ] ]
0e5269e06d736ee0c4a52c8fe0d5e6c45cedd7da
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SETools/SEToolsCommon/SECollada/SEColladaScene.h
e13cfbe0318bfb824df5fa5bd862603471834a25
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
12,165
h
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // 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. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #ifndef Swing_ColladaScene_H #define Swing_ColladaScene_H #include "SEToolsCommonLIB.h" #include "SEToolsUtility.h" #include "SEImageConverter.h" #include "SwingFoundation.h" #include "SEColladaEffect.h" #include "SEColladaMaterial.h" #include "SEColladaAnimation.h" #include "SEColladaUnimaterialMesh.h" #include "SEColladaInstanceLight.h" #include "SEColladaInstanceCamera.h" #include "SEColladaInstanceMaterial.h" #include "SEColladaInstanceController.h" #include "SEColladaTransformation.h" namespace Swing { //---------------------------------------------------------------------------- // Description:a helper class // Author:Sun Che // Date:20090914 //---------------------------------------------------------------------------- class SE_TOOLS_COMMON_API SEColladaShaderElements { public: SEColladaShaderElements(void) { memset(this, 0, sizeof(SEColladaShaderElements)); } ~SEColladaShaderElements(void){} domCommon_color_or_texture_type* Emission; domCommon_color_or_texture_type* Ambient; domCommon_color_or_texture_type* Diffuse; domCommon_color_or_texture_type* Specular; domCommon_float_or_param_type* Shininess; domCommon_color_or_texture_type* Reflective; domCommon_float_or_param_type* Reflectivity; domCommon_color_or_texture_type_complexType* Transparent; domCommon_float_or_param_type* Transarency; domCommon_float_or_param_type* IndexOfRefaction; }; //---------------------------------------------------------------------------- // Description: This is a singleton class. // Author:Sun Che // Date:20090914 //---------------------------------------------------------------------------- class SE_TOOLS_COMMON_API SEColladaScene { public: SEColladaScene(SEImageConverter* pImageConverter); ~SEColladaScene(void); // Current coordinate frame orientation mode, depending on the DCC tools. // All of them are right-handed system. // // Y_UP: // | Y // | // | X // O-------- // / // Z / // // Z_UP: // | Z // | / // | / Y // |/ // O-------- // X // // X_UP: // | X // | // Y | // -------O // / // / Z // enum OrientationMode { OM_Y_UP, OM_Z_UP, OM_X_UP, OM_UNKNOWN }; enum SkinEffect { SE_DEFAULT, SE_MATERIAL, SE_MATERIALTEXTURE, SE_UNKNOWN }; // Load a COLLADA DOM file, then create a Swing Engine scene graph base on // COLLADA runtime scene graph. bool Load(const char* acFilename); // Get scene graph root node. SENode* GetScene(void); // Member access. int GetImageCount(void) const; SEImage* GetImage(const char* acName); SEImage* GetImage(int i); SEColladaEffect* GetEffect(const char* acName); SEColladaMaterial* GetMaterial(const char* acName); SEColladaInstanceMaterial* GetInstanceMaterial(const char* acName); SENode* GetNode(const char* acName); SENode* GetGeometry(const char* acName); SELight* GetLight(const char* acName); SECamera* GetCamera(const char* acName); // Import options. bool EnableKeyFrameController; // Default: true bool EnableJointMesh; // Default: false bool EnableTCoord; // Default: true bool EnableControllers; // Default: true private: // This helper class represents a specific type of transformation // happened at a specific time. class KeyInfo { public: KeyInfo(void) { Time = 0.0f; Type = SEColladaTransformation::TT_UNKNOWN; } bool operator == (const KeyInfo& rKeyInfo) const { return (Time == rKeyInfo.Time) && (Type == rKeyInfo.Type); } bool operator < (const KeyInfo& rKeyInfo) const { return Time < rKeyInfo.Time; } float Time; SEColladaTransformation::TransformType Type; }; // This helper class holds the relationship between a Swing Engine bone // node and a COLLADA joint node. class Bone { public: Bone(void) { BoneNode = 0; BoneDomNode = 0; } SENode* BoneNode; domNode* BoneDomNode; }; // This helper class represents the weight of a bone that is applied to // a specific vertex. class BoneWeight { public: BoneWeight(void) { BoneID = -1; Weight = 0.0f; } bool operator == (const BoneWeight& rBoneWeight) const { return Weight == rBoneWeight.Weight; } bool operator < (const BoneWeight& rBoneWeight) const { return Weight < rBoneWeight.Weight; } int BoneID; float Weight; }; // Entry point. bool LoadScene(domVisual_sceneRef spDomVisualScene); // COLLADA mesh triangulation. unsigned int GetMaxOffset(domInputLocalOffset_Array& rInputArray); void CreateTrianglesFromPolygons(domMesh* pDomMesh, domPolygons* pDomPolygons); void CreateTrianglesFromPolylist(domMesh* pDomMesh, domPolylist* pDomPolylist); void Triangulate(DAE* pDAE); // Node stuff. SENode* LoadNode(domNodeRef spDomNode, SENode* pParentNode); void GetLocalTransSequence(SENode* pNode, domNodeRef spDomNode, std::vector<SEColladaTransformation*>& rColladaTransSequence); SETransformation GetLocalTransformation( std::vector<SEColladaTransformation*>& rColladaTransSequence, float fTime = 0.0f); SETriMesh* CreateJointMesh(const char* acJointName, float fSize = 2.0f); domNode* GetDomNodeBySID(domNodeRef spDomNode, xsNCName strSID); SENode* GetBoneNodeByDomNode(domNode* pDomNode); // Geometry stuff. SENode* LoadGeometry(domGeometryRef spDomGeometry); SENode* LoadInstanceGeometry(domInstance_geometryRef spLib); void PackVertices(SEColladaUnimaterialMesh* pUniMesh, domListOfFloats* pDomPositionData, int iPositionStride, domListOfUInts& rDomIndexData, int iIndexCount, int iStride, int iPositionOffset, SEVector3f* aNormal); void PackTextures(SEColladaUnimaterialMesh* pUniMesh, domListOfFloats* pDomTCoordData, int iTCoordStride, domListOfUInts& rDomIndexData, int iIndexCount, int iStride, int iTCoordOffset); SETriMesh* BuildTriangles(domTriangles* pDomTriangles); void ParseGeometry(SENode*& rpMeshRoot, domGeometry* pDomGeometry); // Image stuff. bool LoadImageLibrary(domLibrary_imagesRef spLib); SEImage* LoadImage(domImageRef spDomImage); // Material stuff. bool LoadMaterialLibrary(domLibrary_materialsRef spLib); SEColladaMaterial* LoadMaterial(domMaterialRef spDomMaterial); SEColladaInstanceMaterial* LoadInstanceMaterial( domInstance_materialRef spLib); // Effect stuff. bool LoadEffectLibrary(domLibrary_effectsRef spLib); SEColladaEffect* LoadEffect(domEffectRef spDomEffect); SEColorRGB GetColor(domCommon_color_or_texture_type_complexType* pParam); float GetFloat(domCommon_float_or_param_type* pParam); SETexture* GetTextureFromShaderElement( std::map<std::string, domCommon_newparam_type*>& rNewParams, domCommon_color_or_texture_type* pShaderElement); // Animation stuff. bool LoadAnimationLibrary(domLibrary_animationsRef spLib); SEColladaAnimation* LoadAnimation(domAnimationRef spDomAnimation); SEColladaAnimationSource* LoadAnimationSource(domSourceRef spDomSource); SEColladaAnimationSampler* LoadAnimationSampler( SEColladaAnimation* pAnimation, domSamplerRef spDomSampler); SEColladaAnimationChannel* LoadAnimationChannel( SEColladaAnimation* pAnimation, domChannelRef spDomChannel); void BuildKeyFrameController(SENode* pNode, std::vector<SEColladaTransformation*>& rColladaTransSequence); // Light stuff. SELight* LoadLight(domLightRef spDomLight); SEColladaInstanceLight* LoadInstanceLight(SENode* pParentNode, domInstance_lightRef spDomInstanceLight); void ParseConstant(SEColladaEffect* pEffect, SEColladaShaderElements* pShaderElements, domProfile_COMMON::domTechnique::domConstant* pDomConstant); void ParseLambert(SEColladaEffect* pEffect, SEColladaShaderElements* pShaderElements, domProfile_COMMON::domTechnique::domLambert* pDomLambert); void ParsePhong(SEColladaEffect* pEffect, SEColladaShaderElements* pShaderElements, domProfile_COMMON::domTechnique::domPhong* pDomPhong); void ParseBlinn(SEColladaEffect* pEffect, SEColladaShaderElements* pShaderElements, domProfile_COMMON::domTechnique::domBlinn* pDomblinn); void ProcessLights(void); // Camera stuff. SECamera* LoadCamera(domCameraRef spDomCamera); SEColladaInstanceCamera* LoadInstanceCamera(SENode* pParentNode, domInstance_cameraRef spDomInstanceCamera); void ProcessCameras(void); // Controller stuff. SENode* LoadInstanceController(domInstance_controllerRef spLib); void ProcessControllers(void); void ProcessSkin(SEColladaInstanceController* pIController); void ProcessMorph(SEColladaInstanceController* pIController); // Clean the runtime before loading a new scene. void CleanUp(void); DAE* m_pDAE; SEImageConverter* m_pImageConverter; SENodePtr m_spSceneRoot; static OrientationMode ms_eOrientationMode; std::vector<SEImagePtr> m_Images; std::vector<SEColladaEffectPtr> m_Effects; std::vector<SEColladaMaterialPtr> m_Materials; std::vector<SEColladaInstanceMaterialPtr> m_InstanceMaterials; std::vector<SEColladaInstanceLightPtr> m_InstanceLights; std::vector<SEColladaInstanceCameraPtr> m_InstanceCameras; std::vector<SEColladaAnimationPtr> m_Animations; std::map<std::string, SENodePtr> m_Nodes; std::vector<SENodePtr> m_Geometries; std::vector<SELightPtr> m_Lights; std::vector<SECameraPtr> m_Cameras; std::vector<SEColladaInstanceControllerPtr> m_InstanceControllers; std::vector<Bone> m_Bones; // Internal use. public: // Transform the input DCC coordinate to Swing Engine coordinate.Say, // from a right-handed based system to Swing Engine left-handed based // system. static SEVector3f GetTransformedVector(float fX, float fY, float fZ); // Generate Swing Engine inverse binding transformation object base on // DCC inverse binding matrix. static void GetInverseBindingTransformation(SETransformation& rDstTransformation, domListOfFloats* pSrcMatrix, int iSrcBase); }; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 344 ] ] ]
7649f8781054bbf1fdcbca492b1f493318212637
e54a8a3c8ec07c208cc27fb9ac83cfceb0d1cddf
/wseWidgets.h
5d476e49281fc2036469bd061dd42a749008e73f
[]
no_license
joshcates/wse
e1eadf5121f43b65b598a7148bf65ce84a2c5fce
be0987e8f0ef26941abef96d939a7fcbe4cb02c1
refs/heads/master
2020-06-04T14:03:17.752837
2011-09-12T22:38:33
2011-09-12T22:38:33
2,157,531
1
0
null
null
null
null
UTF-8
C++
false
false
1,716
h
//--------------------------------------------------------------------------- // // Copyright 2010 University of Utah. All rights reserved // //--------------------------------------------------------------------------- #ifndef WIDGETS_H #define WIDGETS_H #include <QLabel> #include <QListWidget> #include <QGraphicsScene> #include <QGraphicsView> namespace wse { /** Extends the QListWidget to support drag-and-drop of filenames. */ class QImageList : public QListWidget { Q_OBJECT public: QImageList(QWidget *parent = NULL) : QListWidget(parent) {} ~QImageList() {} protected: QStringList mimeTypes() const; Qt::DropActions supportedDropActions(); bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action); signals: void imageDropped(QString); }; /** */ class QPreviewScene : public QGraphicsScene { Q_OBJECT public: QPreviewScene(QWidget *parent = 0); ~QPreviewScene() {} void setBackground(const QImage &bg); protected: void dragEnterEvent(QGraphicsSceneDragDropEvent *event); void dragMoveEvent(QGraphicsSceneDragDropEvent *event); void dropEvent(QGraphicsSceneDragDropEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *e); signals: void imageDropped(QString); void imagePicked(int,int); private: QGraphicsPixmapItem *mBackground; QGraphicsSimpleTextItem *mText; }; class QPreviewWidget : public QGraphicsView { Q_OBJECT public: QPreviewWidget(QWidget *parent = 0); ~QPreviewWidget() {} void resizeEvent(QResizeEvent *event); void setBackground(const QImage &bg); private: QPreviewScene *mScene; }; } // end namespace wse #endif
[ [ [ 1, 78 ] ] ]
02147e1bc306ea549581099162d5220698348e2e
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/disassembler/CTC0.h
ea9c79d8989c2c19144b4e51521339d6c801e031
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
326
h
/* CTC0 */ void AllegrexInstructionTemplate< 0x40c00000, 0xffe007ff >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment) { using namespace Allegrex; ::strcpy(opcode_name, "ctc0"); ::sprintf(operands, "%s, $%d", gpr_name[rt(opcode)], rd(opcode)); ::strcpy(comment, ""); }
[ [ [ 1, 9 ] ] ]
be6a2bd835e289424e73e714fd0bb274aff69e80
5ed707de9f3de6044543886ea91bde39879bfae6
/ASFootball/ASFIsapi/Source/Hold/HubPageBuilder.h
0eb3ce0e387ac1153c4ddf9d8b90cd91d99c1ed2
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
2,717
h
/* HubPageBuilder.h */ /******************************************************************************/ /******************************************************************************/ #ifndef HubPageBuilderH #define HubPageBuilderH #include "ASFootballHTMLPageBuilder.h" /******************************************************************************/ class THubLineItemHtmlView : public TPageOptionsHtmlView { public: THubLineItemHtmlView(THtmlPageOptions& pageOptions) : TPageOptionsHtmlView(pageOptions) {} virtual bool show() throw(Exception) { return(true); } }; /******************************************************************************/ class HubRightPanelHtmlView : public TTypeAlphaRightPanelHtmlView { protected: bool fAnyInvolvedTradeMessages; public: HubRightPanelHtmlView(THtmlPageOptions& pageOptions) : TTypeAlphaRightPanelHtmlView(pageOptions,tt_None,550, "Front Office",""), fAnyInvolvedTradeMessages(false) {} protected: void writeItemRow(THubLineItemHtmlView& lineItemHtmlView,THTMLWriter& htmlWriter); bool buildParticStatusMessages(THTMLWriter& htmlWriter) throw(Exception); void buildDraftMessages(THTMLWriter& htmlWriter); void buildSeasonMessages(THTMLWriter& htmlWriter); void buildMyTradeMessages(THTMLWriter& htmlWriter,TTradeVector& tradeVector); void buildOtherTradeMessages(THTMLWriter& htmlWriter,TTradeVector& tradeVector); void buildTradeMessages(THTMLWriter& htmlWriter); virtual void writeContentView(THTMLWriter& htmlWriter); }; /******************************************************************************/ class HubBodyHTMLView : public TFootballTypeAlphaBodyHTMLView { protected: HubRightPanelHtmlView fRightPanel; public: HubBodyHTMLView(THtmlPageOptions& pageOptions) : TFootballTypeAlphaBodyHTMLView(pageOptions), fRightPanel(pageOptions) {} protected: virtual void writeRightPanelView(THTMLWriter& htmlWriter) { fRightPanel.Write(htmlWriter); } }; /******************************************************************************/ class HubPageHTMLView : public TFootballTypeAlphaPageHTMLView { HubBodyHTMLView fBodyView; public: HubPageHTMLView(THtmlPageOptions& pageOptions) : TFootballTypeAlphaPageHTMLView(pageOptions), fBodyView(pageOptions) {} protected: virtual AnsiString getPageTitle(void) const { return("Hub"); } virtual void writeBodyView(THTMLWriter& htmlWriter) { fBodyView.Write(htmlWriter); } }; #endif /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 83 ] ] ]
f6a3a34348afe7477a0b01af74a13a226fe77fac
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleAffectors/ParticleUniverseBaseColliderFactory.h
47f76dd148eb68c4348e07153ec33d5592963e52
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_BASE_COLLIDER_FACTORY_H__ #define __PU_BASE_COLLIDER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseBaseColliderTokens.h" #include "ParticleUniverseBaseCollider.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** This factory is just a dummy factory. */ class _ParticleUniverseExport BaseColliderFactory : public ParticleAffectorFactory { protected: BaseColliderWriter mBaseColliderWriter; BaseColliderTranslator mBaseColliderTranslator; public: BaseColliderFactory(void) {}; virtual ~BaseColliderFactory(void) {}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType(void) const { return "Dummy02"; // Dummy Factory, only for setting up token definitions. } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, "PU: BaseColliderFactory is a dummy factory.", "BaseColliderFactory::createAffector"); } /** See ScriptReader */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mBaseColliderTranslator.translateChildProperty(compiler, node); }; /** See ScriptReader */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mBaseColliderTranslator.translateChildObject(compiler, node); }; /* */ virtual void write(ParticleScriptSerializer* serializer , const IElement* element) { // Delegate mBaseColliderWriter.write(serializer, element); } }; } #endif
[ [ [ 1, 68 ] ] ]
f62f0de35d68769745110185437b150980d7cb6c
c9390a163ae5f0bc6fdc1560be59939dcbe3eb07
/Skin/WithoutSliderCtrl/WithoutSliderCtrl.h
a3e05290af853cd23619b07a18cc2f2162549b3a
[]
no_license
trimpage/multifxvst
2ceae9da1768428288158319fcf03d603ba47672
1cb40f8e0cc873f389f2818b2f40665d2ba2b18b
refs/heads/master
2020-04-06T13:23:41.059632
2010-11-04T14:32:54
2010-11-04T14:32:54
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,198
h
/* CWithoutSliderCtrl range : 0 => 400 (car le plus adapté a la souris) faudrait faire un produit en croix mais .... */ #ifndef _CWithoutSliderCtrl_ #define _CWithoutSliderCtrl_ class CWithoutSliderCtrl : public CSliderCtrl { public: CWithoutSliderCtrl(); virtual ~CWithoutSliderCtrl(); //{{AFX_VIRTUAL(CWithoutSliderCtrl) protected: virtual void PreSubclassWindow(); virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL protected: virtual bool SetKnobPos(float nPos); virtual bool UpdateKnobPos(int nDeltaPos); //{{AFX_MSG(CWithoutSliderCtrl) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnPaint(); afx_msg void OnLButtonDown(UINT nFlags, ::CPoint point); afx_msg void OnMouseMove(UINT nFlags, ::CPoint point); afx_msg void OnLButtonUp(UINT nFlags, ::CPoint point); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() protected: float ConvertIN400(int valnot400); int ConvertNOTIN400(float val400); bool m_bDragging; float pos; POINT m_ptHit; virtual BOOL OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult); }; #endif
[ "CTAF@3e78e570-a0aa-6544-9a6b-7e87a0c009bc" ]
[ [ [ 1, 51 ] ] ]
a202ff0b209dd9ef2578fe3a9b5cf882f747aa51
e1bf514046ee44622d96b7f4541cf406d87a9ee6
/CarTest/GroundPlane.h
89a01a6e73aa66481ba805a5def07ad22afc9f22
[]
no_license
phigley/VehicleTestBed
89d97d8439492062be53d29904b6f8e392cd3f63
340b5c920b3ccc179bb910f39c16d473864bed0c
refs/heads/master
2021-01-13T12:56:42.496354
2009-10-30T00:59:28
2009-10-30T00:59:28
350,645
1
0
null
null
null
null
UTF-8
C++
false
false
409
h
#ifndef GROUNDPLANE_H_ #define GROUNDPLANE_H_ #include "Engine/Color.h" namespace Engine { class Window; } class GroundPlane { public: GroundPlane(float grid_size, const Engine::Color& color1_, const Engine::Color& color2_); void render(const Engine::Window& window); private: float halfGridSize; Engine::Color color1; Engine::Color color2; }; #endif // GROUNDPLANE_H_
[ [ [ 1, 26 ] ] ]
2dc3310e3ba78c56c3cc6f493c4c7f38cd69148e
e8c9bfda96c507c814b3378a571b56de914eedd4
/engineTest/PieSensor.cpp
ee72ef88dfcc1cfd6a73ed311e151a22b99c70ce
[]
no_license
VirtuosoChris/quakethecan
e2826f832b1a32c9d52fb7f6cf2d972717c4275d
3159a75117335f8e8296f699edcfe87f20d97720
refs/heads/master
2021-01-18T09:20:44.959838
2009-04-20T13:32:36
2009-04-20T13:32:36
32,121,382
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include "Sensors.h" PieSensor::PieSensor(){ //default } PieSensor::PieSensor(int slice){ num_slices = slice; range = 5000; angle = 360.0 / (num_slices * 2); offset = 360.0 / (num_slices * 4); orientation = 0; areas = new int[num_slices * 2]; clear(); } void PieSensor::clear(){ for(int i = 0; i < (num_slices * 2); i++) areas[i] = 0; } PieSensor::~PieSensor(){ delete [] areas; }
[ "cthomas.mail@f96ad80a-2d29-11de-ba44-d58fe8a9ce33" ]
[ [ [ 1, 24 ] ] ]
31aa0d18f9b8b9995fc9d49021b45ac6656c0620
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DomMemDebug.cpp
2efe379bbda3a56fdbf10f3da2ce9670d41fe6c8
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,685
cpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * 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. */ /* * $Id: DomMemDebug.cpp,v 1.4 2004/09/08 13:55:43 peiyongz Exp $ */ #include "DomMemDebug.hpp" #include "DOMString.hpp" #include "NodeImpl.hpp" #include "NamedNodeMapImpl.hpp" #include <stdio.h> XERCES_CPP_NAMESPACE_BEGIN DomMemDebug::DomMemDebug() { liveStringHandles = DOMString::gLiveStringHandleCount; totalStringHandles = DOMString::gTotalStringHandleCount; liveStringBuffers = DOMString::gLiveStringDataCount; totalStringBuffers = DOMString::gTotalStringDataCount; liveNodeImpls = NodeImpl::gLiveNodeImpls; totalNodeImpls = NodeImpl::gTotalNodeImpls; liveNamedNodeMaps = NamedNodeMapImpl::gLiveNamedNodeMaps; totalNamedNodeMaps = NamedNodeMapImpl::gTotalNamedNodeMaps; }; DomMemDebug::~DomMemDebug() { }; bool DomMemDebug::operator == (const DomMemDebug &other) { bool r = liveStringHandles == other.liveStringHandles && liveStringBuffers == other.liveStringBuffers && liveNodeImpls == other.liveNodeImpls && liveNamedNodeMaps == other.liveNamedNodeMaps; return r; }; bool DomMemDebug::operator != (const DomMemDebug &other) { return ! operator == (other); }; void DomMemDebug::operator = (const DomMemDebug &other) { liveStringHandles = other.liveStringHandles; totalStringHandles = other.totalStringHandles; liveStringBuffers = other.liveStringBuffers; totalStringBuffers = other.totalStringBuffers; liveNodeImpls = other.liveNodeImpls; totalNodeImpls = other.totalNodeImpls; liveNamedNodeMaps = other.liveNamedNodeMaps; totalNamedNodeMaps = other.totalNamedNodeMaps; }; void DomMemDebug::print() { printf("DOM reference counted memory alloction statistics:\n" " live string handles: %d\n" " total string handles: %d\n" " live string buffers: %d\n" " total string buffers: %d\n" " live nodeImpls: %d\n" " total nodeImpls: %d\n" " live NamedNodeMaps: %d\n" " total NamedNodeMaps: %d\n", liveStringHandles , totalStringHandles, liveStringBuffers , totalStringBuffers , liveNodeImpls , totalNodeImpls , liveNamedNodeMaps , totalNamedNodeMaps); }; void DomMemDebug::printDifference(const DomMemDebug &other) { int d; d = liveStringHandles - other.liveStringHandles; if (d != 0) printf(" %d StringHandles.", d); d = liveStringBuffers - other.liveStringBuffers; if (d != 0) printf(" %d StringBuffers.", d); d = liveNodeImpls - other.liveNodeImpls; if (d != 0) printf(" %d NodeImpls.", d); d = liveNamedNodeMaps - other.liveNamedNodeMaps; if (d != 0) printf(" %d NamedNodeMaps.", d); printf("\n"); }; XERCES_CPP_NAMESPACE_END
[ [ [ 1, 124 ] ] ]
900183352fd0b0d9aa4fd26352d1c95b60b2240a
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/win32/inps.cpp
ab12a0a605a67a4816d5a57f7203d011492e0464
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
8,302
cpp
// Burner Input Set dialog module #include "burner.h" HWND hInpsDlg = NULL; // Handle to the Input Set Dialog static HBRUSH hWhiteBGBrush; unsigned int nInpsInput = 0; // The input number we are redefining static struct BurnInputInfo bii; // Info about the input static int nDlgState = 0; static int nInputCode = -1; // If in state 3, code N was nInputCode static int nCounter = 0; // Counter of frames since the dialog was made static struct GameInp* pgi = NULL; // Current GameInp static struct GameInp OldInp; // Old GameInp static int bOldPush = 0; // 1 if the push button was pressed last time static bool bGrabMouse = false; static bool bOldLeftAltkeyMapped; static int InpsInit() { TCHAR szTitle[128]; memset(&OldInp, 0, sizeof(OldInp)); pgi = NULL; if (nInpsInput >= nGameInpCount + nMacroCount) { // input out of range return 1; } pgi = GameInp + nInpsInput; memset(&bii,0,sizeof(bii)); BurnDrvGetInputInfo(&bii, nInpsInput); if (bii.nType & BIT_GROUP_CONSTANT) { // This dialog doesn't handle constants return 1; } OldInp = *pgi; bOldPush = 0; bGrabMouse = false; bOldLeftAltkeyMapped = bLeftAltkeyMapped; bLeftAltkeyMapped = true; // Set the dialog title if (nInpsInput >= nGameInpCount) { // Macro _stprintf(szTitle, FBALoadStringEx(IDS_INPSET_MOVENAME), pgi->Macro.szName); } else { // Normal input if (bii.szName == NULL || bii.szName[0] == _T('\0')) { _stprintf(szTitle, FBALoadStringEx(IDS_INPSET_MOVE)); } else { _stprintf(szTitle, FBALoadStringEx(IDS_INPSET_MOVENAME), bii.szName); } } SetWindowText(hInpsDlg, szTitle); InputFind(2); nDlgState = 4; nInputCode = -1; nCounter = 0; return 0; } static int InpsExit() { bOldPush = 0; if (pgi != NULL) { *pgi=OldInp; } memset(&OldInp, 0, sizeof(OldInp)); bLeftAltkeyMapped = bOldLeftAltkeyMapped; nDlgState = 0; return 0; } static int SetInput(int nCode) { if ((pgi->nInput & GIT_GROUP_MACRO) == 0) { if (bii.nType & BIT_GROUP_CONSTANT) { // Don't change dip switches! DestroyWindow(hInpsDlg); dialogDelete(IDD_INPS); return 0; } if ((bii.nType & BIT_GROUP_ANALOG) && (nCode & 0xFF) < 0x10) { // Analog controls if (strcmp(bii.szInfo + 4, "-axis-neg") == 0 || strcmp(bii.szInfo + 4, "-axis-pos") == 0) { if ((nCode & 0xF000) == 0x4000) { if (nCode & 1) { pgi->nInput = GIT_JOYAXIS_POS; } else { pgi->nInput = GIT_JOYAXIS_NEG; } pgi->Input.JoyAxis.nJoy = (nCode & 0x0F00) >> 8; pgi->Input.JoyAxis.nAxis = (nCode & 0x0F) >> 1; } } else { // Map entire axis if ((nCode & 0xF000) == 0x4000) { pgi->nInput = GIT_JOYAXIS_FULL; pgi->Input.JoyAxis.nJoy = (nCode & 0x0F00) >> 8; pgi->Input.JoyAxis.nAxis = (nCode & 0x0F) >> 1; } else { pgi->nInput = GIT_MOUSEAXIS; pgi->Input.MouseAxis.nMouse = (nCode & 0x0F00) >> 8; pgi->Input.MouseAxis.nAxis = (nCode & 0x0F) >> 1; } } } else { pgi->nInput = GIT_SWITCH; pgi->Input.Switch.nCode = (unsigned short)nCode; } } else { pgi->Macro.nMode = 0x01; // Mark macro as in use pgi->Macro.Switch.nCode = (unsigned short)nCode; // Assign switch } OldInp = *pgi; InpdListMake(0); // Update list with new input type return 0; } static int InpsPushUpdate() { int nPushState = 0; if (pgi == NULL || nInpsInput >= nGameInpCount) { return 0; } // See if the push button is pressed nPushState = SendDlgItemMessage(hInpsDlg, IDC_INPS_PUSH, BM_GETSTATE, 0, 0); if (nPushState & BST_PUSHED) { nPushState = 1; } else { nPushState = 0; } if (nPushState) { switch (OldInp.nType) { case BIT_DIGITAL: // Set digital inputs to 1 pgi->nInput = GIT_CONSTANT; pgi->Input.Constant.nConst = 1; break; case BIT_DIPSWITCH: // Set dipswitch block to 0xFF pgi->nInput = GIT_CONSTANT; pgi->Input.Constant.nConst = 0xFF; break; } } else { // Change back *pgi = OldInp; } if (nPushState != bOldPush) { // refresh view InpdListMake(0); } bOldPush = nPushState; return nPushState; } static void InpsUpdateControl(int nCode) { TCHAR szString[MAX_PATH] = _T(""); TCHAR szDevice[MAX_PATH] = _T(""); TCHAR szControl[MAX_PATH] = _T(""); _stprintf(szString, _T("%s"), InputCodeDesc(nCode)); SetWindowText(GetDlgItem(hInpsDlg, IDC_INPS_CONTROL), szString); InputGetControlName(nCode, szDevice, szControl); _sntprintf(szString, sizearray(szString), _T("%s %s"), szDevice, szControl); SetWindowText(GetDlgItem(hInpsDlg, IDC_INPS_CONTROL_NAME), szString); } int InpsUpdate() { TCHAR szTemp[MAX_PATH] = _T(""); int nButtonState; int nFind = -1; if (hInpsDlg == NULL) { // Don't do anything if the dialog isn't created return 1; } if (nCounter < 0x100000) { // advance frames since dialog was created nCounter++; } if (InpsPushUpdate()) { return 0; } nButtonState = SendDlgItemMessage(hInpsDlg, IDC_INPS_GRABMOUSE, BM_GETSTATE, 0, 0); if (bGrabMouse) { if ((nButtonState & BST_CHECKED) == 0) { bGrabMouse = false; nDlgState = 2; return 0; } } else { if (nButtonState & BST_CHECKED) { bGrabMouse = true; nDlgState = 4; return 0; } } // This doesn't work properly if (nButtonState & BST_PUSHED) { return 0; } nButtonState = SendDlgItemMessage(hInpsDlg, IDCANCEL, BM_GETSTATE, 0, 0); if (nButtonState & BST_PUSHED) { return 0; } nFind = InputFind(nDlgState); if (nDlgState & 4) { // 4 = Waiting for all controls to be released if (bGrabMouse ? nFind >= 0 : (nFind >= 0 && nFind < 0x8000)) { if (nCounter >= 60) { // Alert the user that a control is stuck _stprintf(szTemp, FBALoadStringEx(IDS_INPSET_WAITING), InputCodeDesc(nFind)); SetWindowText(GetDlgItem(hInpsDlg, IDC_INPS_CONTROL), szTemp); nCounter = 0; } return 0; } // All keys released SetWindowText(GetDlgItem(hInpsDlg, IDC_INPS_CONTROL), _T("")); SetWindowText(GetDlgItem(hInpsDlg, IDC_INPS_CONTROL_NAME), _T("")); nDlgState = 8; } if (nDlgState & 8) { // 8 = Waiting for a control to be activated if (bGrabMouse ? nFind < 0 : (nFind < 0 || nFind >= 0x8000)) { return 0; } // Key pressed nInputCode = nFind; InpsUpdateControl(nInputCode); nDlgState = 16; } if (nDlgState & 16) { // 16 = waiting for control to be released if (bGrabMouse ? nFind >= 0 : (nFind >= 0 && nFind < 0x8000)) { if (nInputCode != nFind) { nInputCode = nFind; InpsUpdateControl(nInputCode); } return 0; } // Key released SetInput(nInputCode); nDlgState = 0; DestroyWindow(hInpsDlg); // Quit dialog dialogDelete(IDD_INPS); } return 0; } static INT_PTR CALLBACK InpsDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam) { if (Msg == WM_INITDIALOG) { hInpsDlg = hDlg; hWhiteBGBrush = CreateSolidBrush(RGB(0xFF,0xFF,0xFF)); if (InpsInit()) { DestroyWindow(hInpsDlg); dialogDelete(IDD_INPS); return FALSE; } SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hDlg, IDC_INPS_CONTROL), TRUE); return FALSE; } if (Msg == WM_CLOSE) { DestroyWindow(hInpsDlg); dialogDelete(IDD_INPS); return 0; } if (Msg == WM_DESTROY) { DeleteObject(hWhiteBGBrush); InpsExit(); hInpsDlg = NULL; return 0; } if (Msg == WM_COMMAND) { int Id = LOWORD(wParam); int Notify = HIWORD(wParam); if (Id == IDCANCEL && Notify == BN_CLICKED) { SendMessage(hDlg, WM_CLOSE, 0, 0); return 0; } } if (Msg == WM_CTLCOLORSTATIC) { if ((HWND)lParam == GetDlgItem(hDlg, IDC_INPS_CONTROL)) { return (BOOL)hWhiteBGBrush; } } return 0; } int InpsCreate() { dialogDelete(IDD_INPS); DestroyWindow(hInpsDlg); // Make sure exitted hInpsDlg = NULL; hInpsDlg = FBACreateDialog(IDD_INPS, dialogGet(IDD_INPD), (DLGPROC)InpsDialogProc); if (hInpsDlg == NULL) { return 1; } dialogAdd(IDD_INPS, hInpsDlg); wndInMid(hInpsDlg, dialogGet(IDD_INPD)); ShowWindow(hInpsDlg, SW_NORMAL); return 0; }
[ [ [ 1, 335 ] ] ]
50999b8783e8be9aab5c2382d66a989a1f122df6
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SEMath/SESphere3.cpp
17dee7eba39aaca034cb83a2411c66c44d537bb7
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,831
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // 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. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEFoundationPCH.h" #include "SESphere3.h" using namespace Swing; //---------------------------------------------------------------------------- SESphere3f::SESphere3f() { } //---------------------------------------------------------------------------- SESphere3f::SESphere3f(const SEVector3f& rCenter, float fRadius) : Center(rCenter), Radius(fRadius) { } //---------------------------------------------------------------------------- SESphere3f::SESphere3f(const SESphere3f& rSphere) : Center(rSphere.Center), Radius(rSphere.Radius) { } //---------------------------------------------------------------------------- SESphere3f& SESphere3f::operator=(const SESphere3f& rSphere) { Center = rSphere.Center; Radius = rSphere.Radius; return *this; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 49 ] ] ]
a8d4682df60697736a17d59cff680d5c21cd7307
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/MainGame/Source/Managers/CEventClient.h
db3b2c7c93fe96824366def2cb8203185858cdbd
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
171
h
#pragma once class CEventClient { public: CEventClient(void); ~CEventClient(void); //EVENT HANDLER virtual void HandleEvent(CGameEvent* pEvent) = 0; };
[ "notserp007@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 12 ] ] ]
6657236893dfd7a88b2fbd1d6945afbe51064ea9
51d93b29d2ee286e666c18471574817b9d9ef670
/ghost/bnetprotocol.cpp
0153746639786d332c640a1bebdd8f5a895c8506
[ "Apache-2.0" ]
permissive
crazzy263/ghostplusplus-nibbits
824d6735fccd3daa92e27797e9de29931028b530
2ea18f5d82a97351b82d16bc734469896b2ffedf
refs/heads/master
2021-01-16T22:05:54.409065
2009-11-26T22:20:28
2009-11-26T22:20:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,693
cpp
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "ghost.h" #include "util.h" #include "bnetprotocol.h" CBNETProtocol :: CBNETProtocol( ) { unsigned char ClientToken[] = { 220, 1, 203, 7 }; m_ClientToken = UTIL_CreateByteArray( ClientToken, 4 ); } CBNETProtocol :: ~CBNETProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// bool CBNETProtocol :: RECEIVE_SID_NULL( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_NULL" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length return ValidateLength( data ); } CIncomingGameHost *CBNETProtocol :: RECEIVE_SID_GETADVLISTEX( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_GETADVLISTEX" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> GamesFound // if( GamesFound > 0 ) // 10 bytes -> ??? // 2 bytes -> Port // 4 bytes -> IP // null term string -> GameName // 2 bytes -> ??? // 8 bytes -> HostCounter if( ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY GamesFound = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); if( UTIL_ByteArrayToUInt32( GamesFound, false ) > 0 && data.size( ) >= 25 ) { BYTEARRAY Port = BYTEARRAY( data.begin( ) + 18, data.begin( ) + 20 ); BYTEARRAY IP = BYTEARRAY( data.begin( ) + 20, data.begin( ) + 24 ); BYTEARRAY GameName = UTIL_ExtractCString( data, 24 ); if( data.size( ) >= GameName.size( ) + 35 ) { BYTEARRAY HostCounter; HostCounter.push_back( UTIL_ExtractHex( data, GameName.size( ) + 27, true ) ); HostCounter.push_back( UTIL_ExtractHex( data, GameName.size( ) + 29, true ) ); HostCounter.push_back( UTIL_ExtractHex( data, GameName.size( ) + 31, true ) ); HostCounter.push_back( UTIL_ExtractHex( data, GameName.size( ) + 33, true ) ); return new CIncomingGameHost( IP, UTIL_ByteArrayToUInt16( Port, false ), string( GameName.begin( ), GameName.end( ) ), HostCounter ); } } } return NULL; } bool CBNETProtocol :: RECEIVE_SID_ENTERCHAT( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_ENTERCHAT" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // null terminated string -> UniqueName if( ValidateLength( data ) && data.size( ) >= 5 ) { m_UniqueName = UTIL_ExtractCString( data, 4 ); return true; } return false; } CIncomingChatEvent *CBNETProtocol :: RECEIVE_SID_CHATEVENT( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_CHATEVENT" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> EventID // 4 bytes -> ??? // 4 bytes -> Ping // 12 bytes -> ??? // null terminated string -> User // null terminated string -> Message if( ValidateLength( data ) && data.size( ) >= 29 ) { BYTEARRAY EventID = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); BYTEARRAY Ping = BYTEARRAY( data.begin( ) + 12, data.begin( ) + 16 ); BYTEARRAY User = UTIL_ExtractCString( data, 28 ); BYTEARRAY Message = UTIL_ExtractCString( data, User.size( ) + 29 ); switch( UTIL_ByteArrayToUInt32( EventID, false ) ) { case CBNETProtocol :: EID_SHOWUSER: case CBNETProtocol :: EID_JOIN: case CBNETProtocol :: EID_LEAVE: case CBNETProtocol :: EID_WHISPER: case CBNETProtocol :: EID_TALK: case CBNETProtocol :: EID_BROADCAST: case CBNETProtocol :: EID_CHANNEL: case CBNETProtocol :: EID_USERFLAGS: case CBNETProtocol :: EID_WHISPERSENT: case CBNETProtocol :: EID_CHANNELFULL: case CBNETProtocol :: EID_CHANNELDOESNOTEXIST: case CBNETProtocol :: EID_CHANNELRESTRICTED: case CBNETProtocol :: EID_INFO: case CBNETProtocol :: EID_ERROR: case CBNETProtocol :: EID_EMOTE: return new CIncomingChatEvent( (CBNETProtocol :: IncomingChatEvent)UTIL_ByteArrayToUInt32( EventID, false ), UTIL_ByteArrayToUInt32( Ping, false ), string( User.begin( ), User.end( ) ), string( Message.begin( ), Message.end( ) ) ); } } return NULL; } bool CBNETProtocol :: RECEIVE_SID_CHECKAD( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_CHECKAD" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length return ValidateLength( data ); } bool CBNETProtocol :: RECEIVE_SID_STARTADVEX3( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_STARTADVEX3" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Status if( ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY Status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); if( UTIL_ByteArrayToUInt32( Status, false ) == 0 ) return true; } return false; } BYTEARRAY CBNETProtocol :: RECEIVE_SID_PING( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_PING" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Ping if( ValidateLength( data ) && data.size( ) >= 8 ) return BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); return BYTEARRAY( ); } bool CBNETProtocol :: RECEIVE_SID_LOGONRESPONSE( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_LOGONRESPONSE" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Status if( ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY Status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); if( UTIL_ByteArrayToUInt32( Status, false ) == 1 ) return true; } return false; } bool CBNETProtocol :: RECEIVE_SID_AUTH_INFO( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_AUTH_INFO" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> LogonType // 4 bytes -> ServerToken // 4 bytes -> ??? // 8 bytes -> MPQFileTime // null terminated string -> IX86VerFileName // null terminated string -> ValueStringFormula if( ValidateLength( data ) && data.size( ) >= 25 ) { m_LogonType = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); m_ServerToken = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 12 ); m_MPQFileTime = BYTEARRAY( data.begin( ) + 16, data.begin( ) + 24 ); m_IX86VerFileName = UTIL_ExtractCString( data, 24 ); m_ValueStringFormula = UTIL_ExtractCString( data, m_IX86VerFileName.size( ) + 25 ); return true; } return false; } bool CBNETProtocol :: RECEIVE_SID_AUTH_CHECK( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_AUTH_CHECK" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> KeyState // null terminated string -> KeyStateDescription if( ValidateLength( data ) && data.size( ) >= 9 ) { m_KeyState = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); m_KeyStateDescription = UTIL_ExtractCString( data, 8 ); if( UTIL_ByteArrayToUInt32( m_KeyState, false ) == KR_GOOD ) return true; } return false; } bool CBNETProtocol :: RECEIVE_SID_AUTH_ACCOUNTLOGON( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_AUTH_ACCOUNTLOGON" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Status // if( Status == 0 ) // 32 bytes -> Salt // 32 bytes -> ServerPublicKey if( ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); if( UTIL_ByteArrayToUInt32( status, false ) == 0 && data.size( ) >= 72 ) { m_Salt = BYTEARRAY( data.begin( ) + 8, data.begin( ) + 40 ); m_ServerPublicKey = BYTEARRAY( data.begin( ) + 40, data.begin( ) + 72 ); return true; } } return false; } bool CBNETProtocol :: RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_AUTH_ACCOUNTLOGONPROOF" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Status if( ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY Status = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); if( UTIL_ByteArrayToUInt32( Status, false ) == 0 ) return true; } return false; } BYTEARRAY CBNETProtocol :: RECEIVE_SID_WARDEN( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_WARDEN" ); // DEBUG_PRINT( data ); // 2 bytes -> Header // 2 bytes -> Length // n bytes -> Data if( ValidateLength( data ) && data.size( ) >= 4 ) return BYTEARRAY( data.begin( ) + 4, data.end( ) ); return BYTEARRAY( ); } vector<CIncomingFriendList *> CBNETProtocol :: RECEIVE_SID_FRIENDSLIST( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_FRIENDSLIST" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 1 byte -> Total // for( 1 .. Total ) // null term string -> Account // 1 byte -> Status // 1 byte -> Area // 4 bytes -> ??? // null term string -> Location vector<CIncomingFriendList *> Friends; if( ValidateLength( data ) && data.size( ) >= 5 ) { unsigned int i = 5; unsigned char Total = data[4]; while( Total > 0 ) { Total--; if( data.size( ) < i + 1 ) break; BYTEARRAY Account = UTIL_ExtractCString( data, i ); i += Account.size( ) + 1; if( data.size( ) < i + 7 ) break; unsigned char Status = data[i]; unsigned char Area = data[i + 1]; i += 6; BYTEARRAY Location = UTIL_ExtractCString( data, i ); i += Location.size( ) + 1; Friends.push_back( new CIncomingFriendList( string( Account.begin( ), Account.end( ) ), Status, Area, string( Location.begin( ), Location.end( ) ) ) ); } } return Friends; } vector<CIncomingClanList *> CBNETProtocol :: RECEIVE_SID_CLANMEMBERLIST( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_CLANMEMBERLIST" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> ??? // 1 byte -> Total // for( 1 .. Total ) // null term string -> Name // 1 byte -> Rank // 1 byte -> Status // null term string -> Location vector<CIncomingClanList *> ClanList; if( ValidateLength( data ) && data.size( ) >= 9 ) { unsigned int i = 9; unsigned char Total = data[8]; while( Total > 0 ) { Total--; if( data.size( ) < i + 1 ) break; BYTEARRAY Name = UTIL_ExtractCString( data, i ); i += Name.size( ) + 1; if( data.size( ) < i + 3 ) break; unsigned char Rank = data[i]; unsigned char Status = data[i + 1]; i += 2; // in the original VB source the location string is read but discarded, so that's what I do here BYTEARRAY Location = UTIL_ExtractCString( data, i ); i += Location.size( ) + 1; ClanList.push_back( new CIncomingClanList( string( Name.begin( ), Name.end( ) ), Rank, Status ) ); } } return ClanList; } CIncomingClanList *CBNETProtocol :: RECEIVE_SID_CLANMEMBERSTATUSCHANGE( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED SID_CLANMEMBERSTATUSCHANGE" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // null terminated string -> Name // 1 byte -> Rank // 1 byte -> Status // null terminated string -> Location if( ValidateLength( data ) && data.size( ) >= 5 ) { BYTEARRAY Name = UTIL_ExtractCString( data, 4 ); if( data.size( ) >= Name.size( ) + 7 ) { unsigned char Rank = data[Name.size( ) + 5]; unsigned char Status = data[Name.size( ) + 6]; // in the original VB source the location string is read but discarded, so that's what I do here BYTEARRAY Location = UTIL_ExtractCString( data, Name.size( ) + 7 ); return new CIncomingClanList( string( Name.begin( ), Name.end( ) ), Rank, Status ); } } return NULL; } //////////////////// // SEND FUNCTIONS // //////////////////// BYTEARRAY CBNETProtocol :: SEND_PROTOCOL_INITIALIZE_SELECTOR( ) { BYTEARRAY packet; packet.push_back( 1 ); // DEBUG_Print( "SENT PROTOCOL_INITIALIZE_SELECTOR" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_NULL( ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_NULL ); // SID_NULL packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later AssignLength( packet ); // DEBUG_Print( "SENT SID_NULL" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_STOPADV( ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_STOPADV ); // SID_STOPADV packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later AssignLength( packet ); // DEBUG_Print( "SENT SID_STOPADV" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_GETADVLISTEX( string gameName ) { unsigned char MapFilter1[] = { 255, 3, 0, 0 }; unsigned char MapFilter2[] = { 255, 3, 0, 0 }; unsigned char MapFilter3[] = { 0, 0, 0, 0 }; unsigned char NumGames[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_GETADVLISTEX ); // SID_GETADVLISTEX packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, MapFilter1, 4 ); // Map Filter UTIL_AppendByteArray( packet, MapFilter2, 4 ); // Map Filter UTIL_AppendByteArray( packet, MapFilter3, 4 ); // Map Filter UTIL_AppendByteArray( packet, NumGames, 4 ); // maximum number of games to list UTIL_AppendByteArrayFast( packet, gameName ); // Game Name packet.push_back( 0 ); // Game Password is NULL packet.push_back( 0 ); // Game Stats is NULL AssignLength( packet ); // DEBUG_Print( "SENT SID_GETADVLISTEX" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_ENTERCHAT( ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_ENTERCHAT ); // SID_ENTERCHAT packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // Account Name is NULL on Warcraft III/The Frozen Throne packet.push_back( 0 ); // Stat String is NULL on CDKEY'd products AssignLength( packet ); // DEBUG_Print( "SENT SID_ENTERCHAT" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_JOINCHANNEL( string channel ) { unsigned char NoCreateJoin[] = { 2, 0, 0, 0 }; unsigned char FirstJoin[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_JOINCHANNEL ); // SID_JOINCHANNEL packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later if( channel.size( ) > 0 ) UTIL_AppendByteArray( packet, NoCreateJoin, 4 ); // flags for no create join else UTIL_AppendByteArray( packet, FirstJoin, 4 ); // flags for first join UTIL_AppendByteArrayFast( packet, channel ); AssignLength( packet ); // DEBUG_Print( "SENT SID_JOINCHANNEL" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_CHATCOMMAND( string command ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_CHATCOMMAND ); // SID_CHATCOMMAND packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, command ); // Message AssignLength( packet ); // DEBUG_Print( "SENT SID_CHATCOMMAND" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_CHECKAD( ) { unsigned char Zeros[] = { 0, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_CHECKAD ); // SID_CHECKAD packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? AssignLength( packet ); // DEBUG_Print( "SENT SID_CHECKAD" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_STARTADVEX3( unsigned char state, BYTEARRAY mapGameType, BYTEARRAY mapFlags, BYTEARRAY mapWidth, BYTEARRAY mapHeight, string gameName, string hostName, uint32_t upTime, string mapPath, BYTEARRAY mapCRC, BYTEARRAY mapSHA1, uint32_t hostCounter ) { // todotodo: sort out how GameType works, the documentation is horrendous /* Game type tag: (read W3GS_GAMEINFO for this field) 0x00000001 - Custom 0x00000009 - Blizzard/Ladder Map author: (mask 0x00006000) can be combined *0x00002000 - Blizzard 0x00004000 - Custom Battle type: (mask 0x00018000) cant be combined 0x00000000 - Battle *0x00010000 - Scenario Map size: (mask 0x000E0000) can be combined with 2 nearest values 0x00020000 - Small 0x00040000 - Medium *0x00080000 - Huge Observers: (mask 0x00700000) cant be combined 0x00100000 - Allowed observers 0x00200000 - Observers on defeat *0x00400000 - No observers Flags: 0x00000800 - Private game flag (not used in game list) */ unsigned char Unknown[] = { 255, 3, 0, 0 }; unsigned char CustomGame[] = { 0, 0, 0, 0 }; string HostCounterString = UTIL_ToHexString( hostCounter ); if( HostCounterString.size( ) < 8 ) HostCounterString.insert( 0, 8 - HostCounterString.size( ), '0' ); HostCounterString = string( HostCounterString.rbegin( ), HostCounterString.rend( ) ); BYTEARRAY packet; // make the stat string BYTEARRAY StatString; UTIL_AppendByteArrayFast( StatString, mapFlags ); StatString.push_back( 0 ); UTIL_AppendByteArrayFast( StatString, mapWidth ); UTIL_AppendByteArrayFast( StatString, mapHeight ); UTIL_AppendByteArrayFast( StatString, mapCRC ); UTIL_AppendByteArrayFast( StatString, mapPath ); UTIL_AppendByteArrayFast( StatString, hostName ); StatString.push_back( 0 ); UTIL_AppendByteArrayFast( StatString, mapSHA1 ); StatString = UTIL_EncodeStatString( StatString ); if( mapGameType.size( ) == 4 && mapFlags.size( ) == 4 && mapWidth.size( ) == 2 && mapHeight.size( ) == 2 && !gameName.empty( ) && !hostName.empty( ) && !mapPath.empty( ) && mapCRC.size( ) == 4 && mapSHA1.size( ) == 20 && StatString.size( ) < 128 && HostCounterString.size( ) == 8 ) { // make the rest of the packet packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_STARTADVEX3 ); // SID_STARTADVEX3 packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( state ); // State (16 = public, 17 = private, 18 = close) packet.push_back( 0 ); // State continued... packet.push_back( 0 ); // State continued... packet.push_back( 0 ); // State continued... UTIL_AppendByteArray( packet, upTime, false ); // time since creation UTIL_AppendByteArrayFast( packet, mapGameType ); // Game Type, Parameter UTIL_AppendByteArray( packet, Unknown, 4 ); // ??? UTIL_AppendByteArray( packet, CustomGame, 4 ); // Custom Game UTIL_AppendByteArrayFast( packet, gameName ); // Game Name packet.push_back( 0 ); // Game Password is NULL packet.push_back( 98 ); // Slots Free (ascii 98 = char 'b' = 11 slots free) - note: do not reduce this as this is the # of PID's Warcraft III will allocate UTIL_AppendByteArrayFast( packet, HostCounterString, false ); // Host Counter UTIL_AppendByteArrayFast( packet, StatString ); // Stat String packet.push_back( 0 ); // Stat String null terminator (the stat string is encoded to remove all even numbers i.e. zeros) AssignLength( packet ); } else CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_STARTADVEX3" ); // DEBUG_Print( "SENT SID_STARTADVEX3" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_NOTIFYJOIN( string gameName ) { unsigned char ProductID[] = { 0, 0, 0, 0 }; unsigned char ProductVersion[] = { 14, 0, 0, 0 }; // Warcraft III is 14 BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_NOTIFYJOIN ); // SID_NOTIFYJOIN packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, ProductID, 4 ); // Product ID UTIL_AppendByteArray( packet, ProductVersion, 4 ); // Product Version UTIL_AppendByteArrayFast( packet, gameName ); // Game Name packet.push_back( 0 ); // Game Password is NULL AssignLength( packet ); // DEBUG_Print( "SENT SID_NOTIFYJOIN" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_PING( BYTEARRAY pingValue ) { BYTEARRAY packet; if( pingValue.size( ) == 4 ) { packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_PING ); // SID_PING packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, pingValue ); // Ping Value AssignLength( packet ); } else CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_PING" ); // DEBUG_Print( "SENT SID_PING" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_LOGONRESPONSE( BYTEARRAY clientToken, BYTEARRAY serverToken, BYTEARRAY passwordHash, string accountName ) { // todotodo: check that the passed BYTEARRAY sizes are correct (don't know what they should be right now so I can't do this today) BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_LOGONRESPONSE ); // SID_LOGONRESPONSE packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, clientToken ); // Client Token UTIL_AppendByteArrayFast( packet, serverToken ); // Server Token UTIL_AppendByteArrayFast( packet, passwordHash ); // Password Hash UTIL_AppendByteArrayFast( packet, accountName ); // Account Name AssignLength( packet ); // DEBUG_Print( "SENT SID_LOGONRESPONSE" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_NETGAMEPORT( uint16_t serverPort ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_NETGAMEPORT ); // SID_NETGAMEPORT packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, serverPort, false ); // local game server port AssignLength( packet ); // DEBUG_Print( "SENT SID_NETGAMEPORT" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_INFO( unsigned char ver, bool TFT, string countryAbbrev, string country ) { unsigned char ProtocolID[] = { 0, 0, 0, 0 }; unsigned char PlatformID[] = { 54, 56, 88, 73 }; // "IX86" unsigned char ProductID_ROC[] = { 51, 82, 65, 87 }; // "WAR3" unsigned char ProductID_TFT[] = { 80, 88, 51, 87 }; // "W3XP" unsigned char Version[] = { ver, 0, 0, 0 }; unsigned char Language[] = { 83, 85, 110, 101 }; // "enUS" unsigned char LocalIP[] = { 127, 0, 0, 1 }; unsigned char TimeZoneBias[] = { 44, 1, 0, 0 }; // 300 minutes (GMT -0500) unsigned char LocaleID[] = { 9, 4, 0, 0 }; // 0x0409 English (United States) unsigned char LanguageID[] = { 9, 4, 0, 0 }; // 0x0409 English (United States) BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_AUTH_INFO ); // SID_AUTH_INFO packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, ProtocolID, 4 ); // Protocol ID UTIL_AppendByteArray( packet, PlatformID, 4 ); // Platform ID if( TFT ) UTIL_AppendByteArray( packet, ProductID_TFT, 4 ); // Product ID (TFT) else UTIL_AppendByteArray( packet, ProductID_ROC, 4 ); // Product ID (ROC) UTIL_AppendByteArray( packet, Version, 4 ); // Version UTIL_AppendByteArray( packet, Language, 4 ); // Language UTIL_AppendByteArray( packet, LocalIP, 4 ); // Local IP for NAT compatibility UTIL_AppendByteArray( packet, TimeZoneBias, 4 ); // Time Zone Bias UTIL_AppendByteArray( packet, LocaleID, 4 ); // Locale ID UTIL_AppendByteArray( packet, LanguageID, 4 ); // Language ID UTIL_AppendByteArrayFast( packet, countryAbbrev ); // Country Abbreviation UTIL_AppendByteArrayFast( packet, country ); // Country AssignLength( packet ); // DEBUG_Print( "SENT SID_AUTH_INFO" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_CHECK( bool TFT, BYTEARRAY clientToken, BYTEARRAY exeVersion, BYTEARRAY exeVersionHash, BYTEARRAY keyInfoROC, BYTEARRAY keyInfoTFT, string exeInfo, string keyOwnerName ) { uint32_t NumKeys = 0; if( TFT ) NumKeys = 2; else NumKeys = 1; BYTEARRAY packet; if( clientToken.size( ) == 4 && exeVersion.size( ) == 4 && exeVersionHash.size( ) == 4 && keyInfoROC.size( ) == 36 && ( !TFT || keyInfoTFT.size( ) == 36 ) ) { packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_AUTH_CHECK ); // SID_AUTH_CHECK packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, clientToken ); // Client Token UTIL_AppendByteArrayFast( packet, exeVersion ); // EXE Version UTIL_AppendByteArrayFast( packet, exeVersionHash ); // EXE Version Hash UTIL_AppendByteArray( packet, NumKeys, false ); // number of keys in this packet UTIL_AppendByteArray( packet, (uint32_t)0, false ); // boolean Using Spawn (32 bit) UTIL_AppendByteArrayFast( packet, keyInfoROC ); // ROC Key Info if( TFT ) UTIL_AppendByteArrayFast( packet, keyInfoTFT ); // TFT Key Info UTIL_AppendByteArrayFast( packet, exeInfo ); // EXE Info UTIL_AppendByteArrayFast( packet, keyOwnerName ); // CD Key Owner Name AssignLength( packet ); } else CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_CHECK" ); // DEBUG_Print( "SENT SID_AUTH_CHECK" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_ACCOUNTLOGON( BYTEARRAY clientPublicKey, string accountName ) { BYTEARRAY packet; if( clientPublicKey.size( ) == 32 ) { packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_AUTH_ACCOUNTLOGON ); // SID_AUTH_ACCOUNTLOGON packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, clientPublicKey ); // Client Key UTIL_AppendByteArrayFast( packet, accountName ); // Account Name AssignLength( packet ); } else CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_ACCOUNTLOGON" ); // DEBUG_Print( "SENT SID_AUTH_ACCOUNTLOGON" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY clientPasswordProof ) { BYTEARRAY packet; if( clientPasswordProof.size( ) == 20 ) { packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_AUTH_ACCOUNTLOGONPROOF ); // SID_AUTH_ACCOUNTLOGONPROOF packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, clientPasswordProof ); // Client Password Proof AssignLength( packet ); } else CONSOLE_Print( "[BNETPROTO] invalid parameters passed to SEND_SID_AUTH_ACCOUNTLOGON" ); // DEBUG_Print( "SENT SID_AUTH_ACCOUNTLOGONPROOF" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_WARDEN( BYTEARRAY wardenResponse ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_WARDEN ); // SID_WARDEN packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArrayFast( packet, wardenResponse ); // warden response AssignLength( packet ); // DEBUG_Print( "SENT SID_WARDEN" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_FRIENDSLIST( ) { BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_FRIENDSLIST ); // SID_FRIENDSLIST packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later AssignLength( packet ); // DEBUG_Print( "SENT SID_FRIENDSLIST" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CBNETProtocol :: SEND_SID_CLANMEMBERLIST( ) { unsigned char Cookie[] = { 0, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( BNET_HEADER_CONSTANT ); // BNET header constant packet.push_back( SID_CLANMEMBERLIST ); // SID_CLANMEMBERLIST packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, Cookie, 4 ); // cookie AssignLength( packet ); // DEBUG_Print( "SENT SID_CLANMEMBERLIST" ); // DEBUG_Print( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// bool CBNETProtocol :: AssignLength( BYTEARRAY &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false ); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CBNETProtocol :: ValidateLength( BYTEARRAY &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length uint16_t Length; BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = UTIL_ByteArrayToUInt16( LengthBytes, false ); if( Length == content.size( ) ) return true; } return false; } // // CIncomingGameHost // CIncomingGameHost :: CIncomingGameHost( BYTEARRAY &nIP, uint16_t nPort, string nGameName, BYTEARRAY &nHostCounter ) { m_IP = nIP; m_Port = nPort; m_GameName = nGameName; m_HostCounter = nHostCounter; } CIncomingGameHost :: ~CIncomingGameHost( ) { } string CIncomingGameHost :: GetIPString( ) { string Result; if( m_IP.size( ) >= 4 ) { for( unsigned int i = 0; i < 4; i++ ) { Result += UTIL_ToString( (unsigned int)m_IP[i] ); if( i < 3 ) Result += "."; } } return Result; } // // CIncomingChatEvent // CIncomingChatEvent :: CIncomingChatEvent( CBNETProtocol :: IncomingChatEvent nChatEvent, uint32_t nPing, string nUser, string nMessage ) { m_ChatEvent = nChatEvent; m_Ping = nPing; m_User = nUser; m_Message = nMessage; } CIncomingChatEvent :: ~CIncomingChatEvent( ) { } // // CIncomingFriendList // CIncomingFriendList :: CIncomingFriendList( string nAccount, unsigned char nStatus, unsigned char nArea, string nLocation ) { m_Account = nAccount; m_Status = nStatus; m_Area = nArea; m_Location = nLocation; } CIncomingFriendList :: ~CIncomingFriendList( ) { } string CIncomingFriendList :: GetDescription( ) { string Description; Description += GetAccount( ) + "\n"; Description += ExtractStatus( GetStatus( ) ) + "\n"; Description += ExtractArea( GetArea( ) ) + "\n"; Description += ExtractLocation( GetLocation( ) ) + "\n\n"; return Description; } string CIncomingFriendList :: ExtractStatus( unsigned char status ) { string Result; if( status & 1 ) Result += "<Mutual>"; if( status & 2 ) Result += "<DND>"; if( status & 4 ) Result += "<Away>"; if( Result.empty( ) ) Result = "<None>"; return Result; } string CIncomingFriendList :: ExtractArea( unsigned char area ) { switch( area ) { case 0: return "<Offline>"; case 1: return "<No Channel>"; case 2: return "<In Channel>"; case 3: return "<Public Game>"; case 4: return "<Private Game>"; case 5: return "<Private Game>"; } return "<Unknown>"; } string CIncomingFriendList :: ExtractLocation( string location ) { string Result; if( location.substr( 0, 4 ) == "PX3W" ) Result = location.substr( 4 ); if( Result.empty( ) ) Result = "."; return Result; } // // CIncomingClanList // CIncomingClanList :: CIncomingClanList( string nName, unsigned char nRank, unsigned char nStatus ) { m_Name = nName; m_Rank = nRank; m_Status = nStatus; } CIncomingClanList :: ~CIncomingClanList( ) { } string CIncomingClanList :: GetRank( ) { switch( m_Rank ) { case 0: return "Recruit"; case 1: return "Peon"; case 2: return "Grunt"; case 3: return "Shaman"; case 4: return "Chieftain"; } return "Rank Unknown"; } string CIncomingClanList :: GetStatus( ) { if( m_Status == 0 ) return "Offline"; else return "Online"; } string CIncomingClanList :: GetDescription( ) { string Description; Description += GetName( ) + "\n"; Description += GetStatus( ) + "\n"; Description += GetRank( ) + "\n\n"; return Description; }
[ "hogantp@a7494f72-a4b0-11dd-a887-7ffe1a420f8d" ]
[ [ [ 1, 1146 ] ] ]
4837069593b440f23c53674b6d48621f3b984442
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/FugueDLL/Parser/Parse Functors/Aliases.h
51d25b7706cfab65cb65756970b1b6667cb3c2a4
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
h
// // The Epoch Language Project // FUGUE Virtual Machine // // Parser semantic action functors - type aliases // #pragma once #include "Parser/Parse Functors/ParseFunctorBase.h" // // Inform the parse analyzer that we want to set up a type alias // struct RegisterAliasName : public ParseFunctorBase { RegisterAliasName(Parser::ParserState& state) : ParseFunctorBase(state) { } template <typename IteratorType> void operator () (IteratorType begin, IteratorType end) const { std::wstring str(begin, end); Trace(L"RegisterAliasName", str); State.SetParsePosition(begin); State.SaveStringIdentifier(StripWhitespace(str), SavedStringSlot_Alias); } }; // // Inform the parse analyzer of what type we want to create an alias for // struct RegisterAliasType : public ParseFunctorBase { RegisterAliasType(Parser::ParserState& state) : ParseFunctorBase(state) { } template <typename IteratorType> void operator () (IteratorType begin, IteratorType end) const { std::wstring str(begin, end); Trace(L"RegisterAliasType", str); State.SetParsePosition(begin); State.CreateTypeAlias(StripWhitespace(str)); } }; // // Look up the actual type that backs an aliased type. This // function places the resolved type name onto the parse // stack, but does not generate any runtime operations. // struct ResolveAliasAndPushNoStack : public ParseFunctorBase { ResolveAliasAndPushNoStack(Parser::ParserState& state) : ParseFunctorBase(state) { } template <typename IteratorType> void operator () (IteratorType begin, IteratorType end) const { std::wstring str(begin, end); Trace(L"ResolveAliasAndPushNoStack", str); State.SetParsePosition(begin); State.PushIdentifier(StripWhitespace(widen(State.ResolveAlias(str)))); State.CountParameter(); } };
[ [ [ 1, 77 ] ] ]
77d554ad0c7d472eb0e3961e246e3b7eb6f9ab6b
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/C45SplitSet.cpp
206e7be263b7f532d23c5f54f24a99ae6e04e846
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
#include "StdAfx.h" #include "C45SplitSet.h" C45SplitSet::C45SplitSet(void) { } C45SplitSet::~C45SplitSet(void) { }
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 10 ] ] ]
723e97046fb137ad1ba8f9f6603fdf3da096b7a3
867f5533667cce30d0743d5bea6b0c083c073386
/EchoServer/EchoServer_Cxx/stdafx.cpp
0e7b44946b2952c98f35f349ba00b7817e40713f
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
GB18030
C++
false
false
274
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // EchoServer_Cxx.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 8 ] ] ]
4e194b4a1d43d89b226aec59fd09389105490dc2
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Geometry/WmlFrustum3.cpp
bb4034f22331eb1f143cbe4c2d40c7419a90ed85
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
5,659
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlFrustum3.h" using namespace Wml; //---------------------------------------------------------------------------- template <class Real> Frustum3<Real>::Frustum3 () : m_kOrigin(Vector3<Real>::ZERO), m_kLVector(Vector3<Real>::UNIT_X), m_kUVector(Vector3<Real>::UNIT_Y), m_kDVector(Vector3<Real>::UNIT_Z) { m_fLBound = (Real)1.0; m_fUBound = (Real)1.0; m_fDMin = (Real)1.0; m_fDMax = (Real)2.0; Update(); } //---------------------------------------------------------------------------- template <class Real> Vector3<Real>& Frustum3<Real>::Origin () { return m_kOrigin; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>& Frustum3<Real>::Origin () const { return m_kOrigin; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real>& Frustum3<Real>::LVector () { return m_kLVector; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>& Frustum3<Real>::LVector () const { return m_kLVector; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real>& Frustum3<Real>::UVector () { return m_kUVector; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>& Frustum3<Real>::UVector () const { return m_kUVector; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real>& Frustum3<Real>::DVector () { return m_kDVector; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>& Frustum3<Real>::DVector () const { return m_kDVector; } //---------------------------------------------------------------------------- template <class Real> Real& Frustum3<Real>::LBound () { return m_fLBound; } //---------------------------------------------------------------------------- template <class Real> const Real& Frustum3<Real>::LBound () const { return m_fLBound; } //---------------------------------------------------------------------------- template <class Real> Real& Frustum3<Real>::UBound () { return m_fUBound; } //---------------------------------------------------------------------------- template <class Real> const Real& Frustum3<Real>::UBound () const { return m_fUBound; } //---------------------------------------------------------------------------- template <class Real> Real& Frustum3<Real>::DMin () { return m_fDMin; } //---------------------------------------------------------------------------- template <class Real> const Real& Frustum3<Real>::DMin () const { return m_fDMin; } //---------------------------------------------------------------------------- template <class Real> Real& Frustum3<Real>::DMax () { return m_fDMax; } //---------------------------------------------------------------------------- template <class Real> const Real& Frustum3<Real>::DMax () const { return m_fDMax; } //---------------------------------------------------------------------------- template <class Real> Real Frustum3<Real>::GetDRatio () const { return m_fDRatio; } //---------------------------------------------------------------------------- template <class Real> Real Frustum3<Real>::GetMTwoLF () const { return ((Real)-2.0)*m_fLBound*m_fDMax; } //---------------------------------------------------------------------------- template <class Real> Real Frustum3<Real>::GetMTwoUF () const { return ((Real)-2.0)*m_fUBound*m_fDMax; } //---------------------------------------------------------------------------- template <class Real> void Frustum3<Real>::ComputeVertices (Vector3<Real> akVertex[8]) const { Vector3<Real> kDScaled = m_fDMin*m_kDVector; Vector3<Real> kLScaled = m_fLBound*m_kLVector; Vector3<Real> kUScaled = m_fUBound*m_kUVector; akVertex[0] = kDScaled - kLScaled - kUScaled; akVertex[1] = kDScaled - kLScaled + kUScaled; akVertex[2] = kDScaled + kLScaled + kUScaled; akVertex[3] = kDScaled + kLScaled - kUScaled; for (int i = 0, ip = 4; i < 4; i++, ip++) { akVertex[ip] = m_kOrigin + m_fDRatio*akVertex[i]; akVertex[i] += m_kOrigin; } } //---------------------------------------------------------------------------- template <class Real> void Frustum3<Real>::Update () { m_fDRatio = m_fDMax/m_fDMin; m_fMTwoLF = ((Real)-2.0)*m_fLBound*m_fDMax; m_fMTwoUF = ((Real)-2.0)*m_fUBound*m_fDMax; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template class WML_ITEM Frustum3<float>; template class WML_ITEM Frustum3<double>; } //----------------------------------------------------------------------------
[ [ [ 1, 181 ] ] ]
198a78146b7a4909ec0649ce9a17ef26ec6fd32d
10c14a95421b63a71c7c99adf73e305608c391bf
/gui/core/qnumeric.cpp
c3a3eede73f5aa1844475ade8cab69bf44401639
[]
no_license
eaglezzb/wtlcontrols
73fccea541c6ef1f6db5600f5f7349f5c5236daa
61b7fce28df1efe4a1d90c0678ec863b1fd7c81c
refs/heads/master
2021-01-22T13:47:19.456110
2009-05-19T10:58:42
2009-05-19T10:58:42
33,811,815
0
0
null
null
null
null
UTF-8
C++
false
false
2,612
cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnumeric.h" #include "qnumeric_p.h" QT_BEGIN_NAMESPACE Q_GUI_EXPORT bool qIsInf(double d) { return qt_is_inf(d); } Q_GUI_EXPORT bool qIsNaN(double d) { return qt_is_nan(d); } Q_GUI_EXPORT bool qIsFinite(double d) { return qt_is_finite(d); } Q_GUI_EXPORT bool qIsInf(float f) { return qt_is_inf(f); } Q_GUI_EXPORT bool qIsNaN(float f) { return qt_is_nan(f); } Q_GUI_EXPORT bool qIsFinite(float f) { return qt_is_finite(f); } Q_GUI_EXPORT double qSNaN() { return qt_snan(); } Q_GUI_EXPORT double qQNaN() { return qt_qnan(); } Q_GUI_EXPORT double qInf() { return qt_inf(); } QT_END_NAMESPACE
[ "zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7" ]
[ [ [ 1, 58 ] ] ]
d0fc484d1d6335afd8713dae9f8f71173b2de41b
a96b15c6a02225d27ac68a7ed5f8a46bddb67544
/SetGame/GazaPacker.cpp
3b9e83eccee40de24e9296530cf68098e218e3f6
[]
no_license
joelverhagen/Gaza-2D-Game-Engine
0dca1549664ff644f61fe0ca45ea6efcbad54591
a3fe5a93e5d21a93adcbd57c67c888388b402938
refs/heads/master
2020-05-15T05:08:38.412819
2011-04-03T22:22:01
2011-04-03T22:22:01
1,519,417
3
0
null
null
null
null
UTF-8
C++
false
false
2,830
cpp
#include "GazaPacker.hpp" namespace Gaza { namespace RectanglePacking { Packer::Packer(BaseHandler * handler) { this->handler = handler; maximumWidthPower = (unsigned int)Utility::round(Utility::log2(maximumImageWidth)); maximumHeightPower = (unsigned int)Utility::round(Utility::log2(maximumImageHeight)); currentPowerSum = 0; nextSet = true; currentWidthPower = 0; currentHeightPower = 0; handler->initialize(getContainerWidth(), getContainerHeight()); } Packer::~Packer() { } sf::IntRect * Packer::addRectangle(unsigned int width, unsigned int height) { sf::IntRect * rectangle = new sf::IntRect(0, 0, width, height); rectangles.push_back(rectangle); bool success = handler->addRectangle(rectangle); while(!success) { bool resize = incrementContainerSize(); if(!resize) { // we've resized, but there was a problem (meaning we resized to a size that was too big) delete rectangle; rectangles.pop_back(); return 0; } handler->initialize(getContainerWidth(), getContainerHeight()); for(unsigned int i = 0; i < rectangles.size(); i++) { success = handler->addRectangle(rectangles[i]); if(!success) { // the rectangle will still not fit, so we'll need to resize again break; } } } return rectangle; } unsigned int Packer::getContainerWidth() { return Utility::power(2, currentWidthPower); } unsigned int Packer::getContainerHeight() { return Utility::power(2, currentHeightPower); } bool Packer::incrementContainerSize() { if(currentWidthPower == maximumWidthPower && currentHeightPower == maximumHeightPower) { return false; } unsigned int previousWidthPower = currentWidthPower; unsigned int previousHeightPower = currentHeightPower; if(nextSet) { nextSet = false; currentPowerSum += 1; if(currentPowerSum > maximumWidthPower) { currentWidthPower = maximumWidthPower; } else { currentWidthPower = currentPowerSum; } currentHeightPower = currentPowerSum - currentWidthPower; if(currentWidthPower > maximumWidthPower || currentHeightPower > maximumHeightPower) { // roll back changes nextSet = true; currentPowerSum -= 1; currentWidthPower = previousWidthPower; currentHeightPower = previousHeightPower; return false; } } else { currentHeightPower++; currentWidthPower--; if(currentWidthPower <= 0 || currentHeightPower <= 0 || currentWidthPower >= maximumWidthPower || currentHeightPower >= maximumHeightPower) { nextSet = true; } } return true; } } }
[ [ [ 1, 125 ] ] ]
b4f6c169172daf46078e6848e7750a7cc98c9435
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/test/included/unit_test.hpp
854935ac46f05df46cf958b142feee052ef2080f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,575
hpp
// (C) Copyright Gennadiy Rozental 2001-2005. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile: unit_test.hpp,v $ // // Version : $Revision: 1.1 $ // // Description : included (vs. linked) version of Unit Test Framework // *************************************************************************** #ifndef BOOST_INCLUDED_UNIT_TEST_FRAMEWORK_HPP_071894GER #define BOOST_INCLUDED_UNIT_TEST_FRAMEWORK_HPP_071894GER #include <boost/test/impl/compiler_log_formatter.ipp> #include <boost/test/impl/execution_monitor.ipp> #include <boost/test/impl/framework.ipp> #include <boost/test/impl/plain_report_formatter.ipp> #include <boost/test/impl/progress_monitor.ipp> #include <boost/test/impl/results_collector.ipp> #include <boost/test/impl/results_reporter.ipp> #include <boost/test/impl/test_tools.ipp> #include <boost/test/impl/unit_test_log.ipp> #include <boost/test/impl/unit_test_main.ipp> #include <boost/test/impl/unit_test_monitor.ipp> #include <boost/test/impl/unit_test_parameters.ipp> #include <boost/test/impl/unit_test_suite.ipp> #include <boost/test/impl/xml_log_formatter.ipp> #include <boost/test/impl/xml_report_formatter.ipp> #define BOOST_TEST_INCLUDED #include <boost/test/unit_test.hpp> // *************************************************************************** // Revision History : // // $Log: unit_test.hpp,v $ // Revision 1.1 2006/02/06 10:02:52 rogeeff // make the name similar to the primary header name // // Revision 1.14 2006/02/01 07:57:50 rogeeff // included components entry points // // Revision 1.13 2005/02/20 08:27:08 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // Revision 1.12 2005/02/01 08:59:38 rogeeff // supplied_log_formatters split // change formatters interface to simplify result interface // // Revision 1.11 2005/02/01 06:40:07 rogeeff // copyright update // old log entries removed // minor stilistic changes // depricated tools removed // // Revision 1.10 2005/01/22 19:22:13 rogeeff // implementation moved into headers section to eliminate dependency of included/minimal component on src directory // // *************************************************************************** #endif // BOOST_INCLUDED_UNIT_TEST_FRAMEWORK_HPP_071894GER
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 65 ] ] ]
c35bc11cff9e7620b60f71afd59581b582818640
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/map/aux_/include_preprocessed.hpp
96833c78d38d0b0bf9ae4f6b4ae75fb51cdb63e2
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,473
hpp
// Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/map/aux_/include_preprocessed.hpp,v $ // $Date: 2006/04/17 23:49:40 $ // $Revision: 1.1 $ // NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION! #include <boost/mpl/aux_/config/typeof.hpp> #include <boost/mpl/aux_/config/ctps.hpp> #include <boost/mpl/aux_/config/preprocessor.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> #if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) # define AUX778076_INCLUDE_DIR typeof_based #elif defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) # define AUX778076_INCLUDE_DIR no_ctps #else # define AUX778076_INCLUDE_DIR plain #endif #if !defined(BOOST_NEEDS_TOKEN_PASTING_OP_FOR_TOKENS_JUXTAPOSING) # define AUX778076_HEADER \ AUX778076_INCLUDE_DIR/BOOST_MPL_PREPROCESSED_HEADER \ /**/ #else # define AUX778076_HEADER \ BOOST_PP_CAT(AUX778076_INCLUDE_DIR,/)##BOOST_MPL_PREPROCESSED_HEADER \ /**/ #endif # include BOOST_PP_STRINGIZE(boost/mpl/map/aux_/preprocessed/AUX778076_HEADER) # undef AUX778076_HEADER # undef AUX778076_INCLUDE_DIR #undef BOOST_MPL_PREPROCESSED_HEADER
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 47 ] ] ]
6bbcf35558f3a9693edbc868b0984aca5d2c97d7
01fa6f43ad536f4c9656be0f2c7da69c6fc9dc1c
/wedview.cpp
77b25a2ea7e2e21c71657e7cb5e1027ac2e173f0
[]
no_license
akavel/wed-editor
76a22b7ff1bb4b109cfe5f3cc630e18ebb91cd51
6a10c167e46bfcb65adb514a1278634dfcb384c1
refs/heads/master
2021-01-19T19:33:18.124144
2010-04-16T20:32:17
2010-04-16T20:32:17
10,511,499
1
0
null
null
null
null
UTF-8
C++
false
false
189,817
cpp
/* =====[ wedview.cpp ]========================================== Description: The wed project, implementation of the wedview.cpp Defines the behavior for the application. Compiled: MS-VC 6.00 Notes: <Empty Notes> Revisions: REV DATE BY DESCRIPTION ---- -------- ----------- ---------------------------- 0.00 1/6/2009 Peter Glen Initial version. ======================================================================= */ ////////////////////////////////////////////////////////////////////// // wedView.cpp : implementation of the CWedView class // #include "stdafx.h" #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <io.h> #include <direct.h> #include "wed.h" #include "MainFrm.h" #include "StrList.h" #include "wedDoc.h" #include "wedView.h" #include "FileInfo.h" #include "bufferlist.h" #include "gotoline.h" #include "page1.h" #include "page2.h" #include "setup.h" #include "coco.h" #include "oleComm.h" #include "mxpad.h" #include "holdhead.h" #include "editor.h" #include "undo.h" #include "diff.h" #include "src.h" #include "search.h" #include "srcsel.h" #include "mainfrm.h" #include "stringex.h" #include "RegEx.h" #include "misc.h" #include "register.h" #include "FileDialogST.h" ////////////////////////////////////////////////////////////////////// Coco cocowin; ColeComm m_ole; ////////////////////////////////////////////////////////////////////// #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CMainFrame* pMainFrame; extern CWedApp theApp; ////////////////////////////////////////////////////////////////////// int tabs[10]; int tabstop = 4; int backwrap; int kblock = FALSE; CStringList holding[10]; CStringList macros[10]; CStringList backmacros[10]; CString delim = "<>,/:;{}[]() \t+-\"\'="; CString wdelim = "-/{}[]() \t"; char Mfilter[] = "\ Macro Files (*.mac)\0*.mac\0\ All Files\0*.*\0\0\ "; char Ffilter[] = "\ All files (*.*)\0*.*\0\ 'C' source files (*.c)\0*.c\0\ Header files (*.h)\0*.h\0\ C++ source files (*.cpp)\0*.cpp\0\ PHP source files (*.php)\0*.php\0\ Text files (*.txt)\0*.txt\0\ Java Source files (*.java)\0*.java\0\ Perl Source files (*.pl)\0*.pl\0\ Batch files (*.bat)\0*.bat\0\ Shell files (*.sh)\0*.sh\0\ Config files (*.conf)\0*.conf\0\ Definition files (*.def)\0*.def\0\ Resource files (*.rc)\0*.rc\0\ Make files (*.dsw; *.dsp; Makefile)\0*.dsw;*.dsp;Makefile\0\0\ "; int holdflag[10] = {0}; int newcount = 0; int currhold = 0; int currmac = 0; int Tab2Space = 0; int in_draw = FALSE; static int play = FALSE; // CWedView IMPLEMENT_DYNCREATE(CWedView, CView) BEGIN_MESSAGE_MAP(CWedView, CView) //{{AFX_MSG_MAP(CWedView) ON_WM_CHAR() ON_WM_KEYDOWN() ON_WM_KEYUP() ON_WM_SYSKEYDOWN() ON_WM_SYSCHAR() ON_WM_SYSKEYUP() ON_WM_SETFOCUS() ON_WM_CREATE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONDBLCLK() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_VSCROLL() ON_WM_SHOWWINDOW() ON_COMMAND(ID_VIEW_VIEWHEX, OnViewViewhex) ON_WM_HSCROLL() ON_COMMAND(ID_VIEW_FONTS, OnViewFonts) ON_WM_KILLFOCUS() ON_COMMAND(ID_VIEW_FOREGROUNDCOLOR, OnViewForegroundcolor) ON_COMMAND(ID_VIEW_BACKGROUNDCOLOR, OnViewBackgroundcolor) ON_COMMAND(ID_VIEW_HIGHLITEBACKGROUND, OnViewHighlitebackground) ON_COMMAND(ID_VIEW_COLOMNHIGHLITEBACKGROUND, OnViewColomnhighlitebackground) ON_COMMAND(ID_VIEW_SELECTPRINTERFONT, OnViewSelectprinterfont) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_COMMAND(ID_VIEW_VIEWHOLDINGHEADS, OnViewViewholdingheads) ON_COMMAND(ID_WINDOW_MAXIMIZEMAIN, OnWindowMaximizemain) ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) ON_COMMAND(ID_EDIT_REDO, OnEditRedo) ON_WM_RBUTTONDOWN() ON_COMMAND(ID_OPERATIONS_SELECTLINE, OnOperationsSelectline) ON_COMMAND(ID_SEARCH_FIND, OnSearchFind) ON_COMMAND(ID_SEARCH_REPLACE, OnSearchReplace) ON_COMMAND(ID_VIEW_STOPDIFFING, OnViewStopdiffing) ON_COMMAND(ID_EDIT_RECORDMACRO, OnEditRecordmacro) ON_COMMAND(ID_EDIT_PLAYMACRO, OnEditPlaymacro) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER1, OnSearchSelextholdingBuffer1) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER2, OnSearchSelextholdingBuffer2) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER3, OnSearchSelextholdingBuffer3) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER4, OnSearchSelextholdingBuffer4) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER5, OnSearchSelextholdingBuffer5) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER6, OnSearchSelextholdingBuffer6) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER7, OnSearchSelextholdingBuffer7) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER8, OnSearchSelextholdingBuffer8) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER9, OnSearchSelextholdingBuffer9) ON_COMMAND(ID_SEARCH_SELEXTHOLDING_BUFFER10, OnSearchSelextholdingBuffer10) ON_COMMAND(ID_MOVE_NEXTCHARACTER, OnMoveNextcharacter) ON_COMMAND(ID_MOVE_PREVIOUSCHAR, OnMovePreviouschar) ON_COMMAND(ID_MOVE_NEXTLINE, OnMoveNextline) ON_COMMAND(ID_MOVE_PREVIOUSLINE, OnMovePreviousline) ON_COMMAND(ID_MOVE_PAGEDOWN, OnMovePagedown) ON_COMMAND(ID_MOVE_PAGEUP, OnMovePageup) ON_COMMAND(ID_MOVE_NEXTWORD, OnMoveNextword) ON_COMMAND(ID_MOVE_PREVIOUSEWORD, OnMovePreviouseword) ON_COMMAND(ID_MOVE_ENDOFWORD, OnMoveEndofword) ON_COMMAND(ID_MOVE_BEGINNINGOFWORD, OnMoveBeginningofword) ON_COMMAND(ID_MOVE_NEXTPARAGRAPH, OnMoveNextparagraph) ON_COMMAND(ID_MOVE_PREVIOUSEPARAGRAPH, OnMovePreviouseparagraph) ON_COMMAND(ID_MOVE_ENDOFLINE, OnMoveEndofline) ON_COMMAND(ID_MOVE_BEGINNINGOFLINE, OnMoveBeginningofline) ON_COMMAND(ID_MOVE_BEGINNINGOFFILE, OnMoveBeginningoffile) ON_COMMAND(ID_MOVE_ENDOFFILE, OnMoveEndoffile) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_UPPERCASEWORD, OnEditUppercaseword) ON_COMMAND(ID_EDIT_LOWERCASEWORD, OnEditLowercaseword) ON_COMMAND(ID_EDIT_CAPITALIZEWORD, OnEditCapitalizeword) ON_COMMAND(ID_EDIT_STARTSELECTALTL, OnEditStartselectaltl) ON_COMMAND(ID_EDIT_STARTCOLUMNSELECTALTC, OnEditStartcolumnselectaltc) ON_COMMAND(ID_SELECT_CANCELSELECT, OnSelectCancelselect) ON_COMMAND(ID_SELECT_SELECTALL, OnSelectSelectall) ON_COMMAND(ID_EDIT_CUTTOHOLDING, OnEditCuttoholding) ON_COMMAND(ID_EDIT_COPYTOHOLDING, OnEditCopytoholding) ON_COMMAND(ID_EDIT_PASTEHOLDING, OnEditPasteholding) ON_COMMAND(ID_SEARCH_CANCELFIND, OnSearchCancelfind) ON_COMMAND(ID_MOVE_GOTOLINE, OnMoveGotoline) ON_COMMAND(ID_INSERT_INCREMENTEDNUMBER, OnInsertIncrementednumber) ON_COMMAND(ID_INSERT_SETINCREMNETSTARTVALUE, OnInsertSetincremnetstartvalue) ON_COMMAND(ID_MOVE_GOTOCOLUMN, OnMoveGotocolumn) ON_COMMAND(ID_SEARCH_FINDNEXT, OnSearchFindnext) ON_COMMAND(ID_SEARCH_FINDPREVIOUS, OnSearchFindprevious) ON_COMMAND(ID_SELECT_SELECTWORD, OnSelectSelectword) ON_COMMAND(ID_SELECT_SELECTPARAGRAPH, OnSelectSelectparagraph) ON_COMMAND(ID_VIEW_FILEPROPERTIES, OnViewFileproperties) ON_COMMAND(ID_INSERT_USER, OnInsertUser) ON_COMMAND(ID_EDIT_UPPERCASESELECTION, OnEditUppercaseselection) ON_COMMAND(ID_EDIT_LOWERCASESELECTION, OnEditLowercaseselection) ON_COMMAND(ID_INSERT_DATETIME_RFCSTANDARDDATE, OnInsertDatetimeRfcstandarddate) ON_COMMAND(ID_INSERT_DATETIME_MMDDYYHHMMSS, OnInsertDatetimeMmddyyhhmmss) ON_COMMAND(ID_INSERT_DATETIME_DDMMYYHHMMSS, OnInsertDatetimeDdmmyyhhmmss) ON_COMMAND(ID_INSERT_PAGEFEEDMARK, OnInsertPagefeedmark) ON_COMMAND(ID_INSERT_BYTE, OnInsertByte) ON_COMMAND(ID_INSERT_DATETIME_TIMEHHMMSS, OnInsertDatetimeTimehhmmss) ON_COMMAND(ID_INSERT_DATETIME_WEEKDAY, OnInsertDatetimeWeekday) ON_COMMAND(ID_INSERT_DATETIME_MONTHNAME, OnInsertDatetimeMonthname) ON_COMMAND(ID_INSERT_DATETIME_DATEFORMATTEDASLOCALE, OnInsertDatetimeDateformattedaslocale) ON_COMMAND(ID_INSERT_FUNCTION, OnInsertFunction) ON_COMMAND(ID_INSERT_FORLOOP, OnInsertForloop) ON_COMMAND(ID_INSERT_IFCONDITION, OnInsertIfcondition) ON_COMMAND(ID_SETTINGS_SETUPWED, OnSettingsSetupwed) ON_COMMAND(ID_EDIT_LOADMACRO, OnEditLoadmacro) ON_COMMAND(ID_EDIT_SAVEMACRO, OnEditSavemacro) ON_COMMAND(ID_VIEW_COCOCODECOLECTOR, OnViewCococodecolector) ON_COMMAND(ID_COMPILE_MAKE, OnCompileMake) ON_COMMAND(ID_COMPILE_EXECUTEDEVSTUDIOPROJECT, OnCompileExecutedevstudioproject) ON_COMMAND(ID_FILE_SAVEALL, OnFileSaveall) ON_COMMAND(ID_VIEW_VIEWMACROHEADS, OnViewViewmacroheads) ON_COMMAND(ID_SELECT_MARKBLOCK, OnSelectMarkblock) ON_COMMAND(ID_MOVE_ENDOFPAGE, OnMoveEndofpage) ON_COMMAND(ID_MOVE_BEGINNINGOFPAGE, OnMoveBeginningofpage) ON_COMMAND(ID_WINDOWS_NEXTBUFFER, OnWindowsNextbuffer) ON_COMMAND(ID_VIEW_FULLSCREEN, OnViewFullscreen) ON_COMMAND(ID_FILE_MULTIOPEN, OnFileMultiopen) ON_COMMAND(ID_SETTINGS_TOGGLESCROLLBARS, OnSettingsTogglescrollbars) ON_COMMAND(ID_SETTINGS_REVERSEIT, OnSettingsReverseit) ON_COMMAND(ID_MACRO_ANIMATEMACRO, OnMacroAnimatemacro) ON_COMMAND(ID_DIFF_DIFFONE, OnDiffDiffone) ON_COMMAND(ID_DIFF_DIFFTWO, OnDiffDifftwo) ON_COMMAND(ID_DIFF_DIFFTHREE, OnDiffDiffthree) ON_COMMAND(ID_DIFF_DIFFFOUR, OnDiffDifffour) ON_COMMAND(ID_DIFF_DIFFFIVE, OnDiffDiffive) ON_COMMAND(ID_EDIT_CLEANNONASCII, OnEditCleannonascii) ON_COMMAND(ID_EDIT_WRAPTOWINDOW, OnEditWraptowindow) ON_COMMAND(ID_EDIT_WEEDEMPTYLINES, OnEditWeedemptylines) ON_COMMAND(ID_INSERT_DELETEATCURSOR, OnInsertDeleteatcursor) ON_COMMAND(ID_INSERT_DELETEBEFORECURSOR, OnInsertDeletebeforecursor) ON_COMMAND(ID_INSERT_DELETELINE, OnInsertDeleteline) ON_COMMAND(ID_INSERT_DELETETILLENDOFLINE, OnInsertDeletetillendofline) ON_COMMAND(ID_INSERT_C_SWITCHCASE, OnInsertCSwitchcase) ON_COMMAND(ID_INSERT_C_TEMPLATE, OnInsertCTemplate) ON_COMMAND(ID_INSERT_JAVA_TEMPLATE, OnInsertJavaTemplate) ON_COMMAND(ID_SETTINGS_SEARCHHIGHLITECOLORFG, OnSettingsSearchhighlitecolorfg) ON_COMMAND(ID_SETTINGS_COMMENTHIGHLITECOLOR, OnSettingsCommenthighlitecolor) ON_COMMAND(ID_VIEW_GOTONEXTDIFFERENCE, OnViewGotonextdifference) ON_COMMAND(ID_VIEW_GOTOPREVIOUSDIFFERENCE, OnViewGotopreviousdifference) ON_COMMAND(ID_SETTINGS_DIFFADDCOLOR, OnSettingsDiffaddcolor) ON_COMMAND(ID_SETTINGS_DIFFCHANGEDCOLOR, OnSettingsDiffchangedcolor) ON_COMMAND(ID_SETTINGS_DIFFDELCOLOR, OnSettingsDiffdelcolor) ON_COMMAND(ID_VIEW_FILEBUFERS, OnViewFilebufers) ON_WM_MOVE() ON_WM_SETCURSOR() ON_WM_SIZE() ON_COMMAND(ID_EDIT_APPENDTOHOLDING, OnEditAppendtoholding) ON_COMMAND(ID_SEARCH_HITEDITMODE, OnSearchHiteditmode) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER10, OnMacroSelectrecordholdingBuffer10) ON_COMMAND(ID_EDIT_SELECTRECORDBUFFER_BUFFER1, OnEditSelectrecordbufferBuffer1) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER1, OnMacroSelectrecordholdingBuffer1) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER3, OnMacroSelectrecordholdingBuffer3) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER4, OnMacroSelectrecordholdingBuffer4) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER5, OnMacroSelectrecordholdingBuffer5) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER6, OnMacroSelectrecordholdingBuffer6) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER7, OnMacroSelectrecordholdingBuffer7) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER8, OnMacroSelectrecordholdingBuffer8) ON_COMMAND(ID_MACRO_SELECTRECORDHOLDING_BUFFER9, OnMacroSelectrecordholdingBuffer9) ON_COMMAND(ID_WINDOWS_MAXIMIZECURRENT, OnWindowsMaximizecurrent) ON_WM_DROPFILES() ON_COMMAND(ID_INSERT_BASIC_FORLOOP, OnInsertBasicForloop) ON_COMMAND(ID_INSERT_BASIC_IF, OnInsertBasicIf) ON_COMMAND(ID_INSERT_BASIC_SELECTCASE, OnInsertBasicSelectcase) ON_COMMAND(ID_INSERT_BASIC_FUNCTION, OnInsertBasicFunction) ON_COMMAND(ID_INSERT_JAVA_PRIVATEMETHOD, OnInsertJavaPrivatemethod) ON_COMMAND(ID_ADVANCED_LOCKKEYBOARD, OnAdvancedLockkeyboard) ON_UPDATE_COMMAND_UI(ID_ADVANCED_LOCKKEYBOARD, OnUpdateAdvancedLockkeyboard) ON_UPDATE_COMMAND_UI(ID_SEARCH_HITEDITMODE, OnUpdateSearchHiteditmode) ON_UPDATE_COMMAND_UI(ID_VIEW_VIEWHEX, OnUpdateViewViewhex) ON_COMMAND(ID_SETTINGS_ALLOWBACKSPACETOWRAPLINES, OnSettingsAllowbackspacetowraplines) ON_UPDATE_COMMAND_UI(ID_SETTINGS_ALLOWBACKSPACETOWRAPLINES, OnUpdateSettingsAllowbackspacetowraplines) ON_COMMAND(ID_SETTINGS_SAVETABSASSPACES, OnSettingsSavetabsasspaces) ON_UPDATE_COMMAND_UI(ID_SETTINGS_SAVETABSASSPACES, OnUpdateSettingsSavetabsasspaces) ON_COMMAND(ID_INSERT_DATETIME_BORDERSAFEDATE, OnInsertDatetimeBordersafedate) ON_COMMAND(ID_INSERT_TEMPLATEONE, OnInsertTemplateone) ON_COMMAND(ID_INSERT_TEMPLATETWO, OnInsertTemplatetwo) ON_COMMAND(ID_INSERT_TEMPLATETHREE, OnInsertTemplatethree) ON_COMMAND(ID_ADVANCED_SPELLCHECK, OnAdvancedSpellcheck) ON_COMMAND(ID_ADVANCED_COMMENTADSTRINGSPELLCHECK, OnAdvancedCommentadstringspellcheck) ON_COMMAND(ID_MOVE_NEXTLONGLINE, OnMoveNextlongline) ON_COMMAND(ID_MOVE_MOVEPREVIOUSLONGLINE, OnMoveMovepreviouslongline) ON_COMMAND(ID_SETTINGS_LONGLINECOLORFG, OnSettingsLonglinecolorfg) ON_COMMAND(ID_SEARCH_BRACECOUNT, OnSearchBracecount) ON_COMMAND(ID_HELP_REGISTRATION, OnHelpRegistration) ON_COMMAND(ID_ADVANCED_CLEANOLDBACKUPS, OnAdvancedCleanoldbackups) ON_COMMAND(ID_HELP_HELPONKEYWORD, OnHelpHelponkeyword) ON_COMMAND(ID_ADVANCED_CLEANOLDUNDOFILES, OnAdvancedCleanoldundofiles) ON_COMMAND(ID_SETTINGS_SETTABSTOP, OnSettingsSettabstop) ON_WM_MOUSEWHEEL() ON_COMMAND(ID_FILE_OPEN, OnFileOpen) ON_COMMAND(ID_FILE_SAVEAS2, OnFileSaveas2) ON_COMMAND(ID_ADVANCED_CLEARCURRENTIGNORELIST, OnAdvancedClearcurrentignorelist) ON_WM_TIMER() ON_COMMAND(ID_EDIT_SETWRAPPINGWIDTH, OnEditSetwrappingwidth) ON_COMMAND(ID_SEARCH_FINDINFILES, OnSearchFindinfiles) ON_COMMAND(ID_INSERT_TEMPLATES_OPENTEMPLATEFILE, OnInsertTemplatesOpentemplatefile) ON_COMMAND(ID_FILE_MULTIOPENDEST, OnFileMultiopendest) ON_COMMAND(ID_MOVE_NEXTFUNCTION, OnMoveNextfunction) ON_COMMAND(ID_FILE_PRINT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_COMMAND(ID_MOVE_PREVIOUSFUNCTION, OnMovePreviousfunction) //}}AFX_MSG_MAP END_MESSAGE_MAP() // Declare the variables needed #ifdef _DEBUG static CMemoryState oldMemState, newMemState, diffMemState; #endif // CWedView construction/destruction CWedView::CWedView() { magic = WED_MAGIC; #ifdef _DEBUG oldMemState.Checkpoint(); #endif m_LogoFont.CreateFont(64, 0, 0, 0, 0, 1, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, "Arial Black"); sLogoString = "Wed Editor"; row = col = srow = scol = 0; soh = eoh = soch = eoch = -1; AllowShighlite = 0; diffchange = FALSE; init_search = 0; diff = 0; hex = 0; highlite = 0; record = 0; drag = 0; mouse = 0; scrolldiv = 1; m_busy = 0; shift = 0; control = 0; alt = 0; hitmode = 0; } ////////////////////////////////////////////////////////////////////// // ~CWedView CWedView::~CWedView() { currentedit = NULL; #ifdef _DEBUG newMemState.Checkpoint(); if( diffMemState.Difference( oldMemState, newMemState ) ) { //P2N("WedView Memory leaked!\r\n"); //TRACE( "Memory leaked!\n" ); } #endif } ////////////////////////////////////////////////////////////////////// // CWedView drawing void CWedView::OnDraw(CDC* pDC) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int xx, yy, loop, lim; CString str; CFont *oldfont; TEXTMETRIC tm; COLORREF oldcr, oldbk, sbgcol, sfgcol; oldcr = pDC->GetTextColor(); oldbk = pDC->GetBkColor(); // Signal to others we are drawing in_draw = TRUE; // Make logical highlite int lsoh, leoh; if(soh < eoh) { lsoh = soh; leoh = eoh; } else { leoh = soh; lsoh = eoh; } // Make logical colomn highlite int lsoch, leoch; if(soch < eoch) { lsoch = soch; leoch = eoch+1; } else { leoch = soch+1; lsoch = eoch; } oldfont = pDC->SelectObject( &ff ); pDC->GetTextMetrics(&tm); // Global for the cursor functions: fflf.lfWidth = tm.tmAveCharWidth; fflf.lfHeight = tm.tmHeight; tabs[0] = tm.tmAveCharWidth * tabstop; RECT rec, rec2; GetClientRect(&rec2); pDC->GetClipBox(&rec); pDC->SetTextColor(fgcol); pDC->SetBkColor(bgcol); int height = rec.bottom - rec.top; int fullheight = rec2.bottom - rec2.top; // remainder is just incremented int fullwidth = (rec2.right - rec2.left)/ tm.tmAveCharWidth + 1; xx = 0; //P2N("lfwidth2: %d lfheight2: %d fullwith: %d\r\n", // fflf.lfWidth, fflf.lfHeight, fullwidth); // Figure out where to update loop = rec.top / tm.tmHeight; yy = loop * tm.tmHeight; // Start at line boundary lim = rec.bottom / tm.tmHeight; if(rec.bottom % tm.tmHeight) // Carry over lim++; loop += srow; // Adjust for relative pos lim += srow; // Adjust for coordinates shift if(lsoch != -1) { lsoch -= scol; leoch -= scol; } //P2N("Start draw: lim = %d loop = %d srow = %d\r\n", // lim, loop, srow); lim = min(lim, pDoc->strlist.GetCount()); int fulldiff = fullheight/tm.tmHeight - (lim-loop); if(fullheight % tm.tmHeight) fulldiff++; for( ; loop < lim; loop++) { int startp = 0, endp = 0; int split = FALSE; str = pDoc->strlist.GetLine(loop); // Adjust max col length for scroll if(pDoc->maxcol < str.GetLength()) pDoc->maxcol = str.GetLength(); // Long line colors if(str.GetLength() > 85) { sbgcol = bgcol; sfgcol = clng; pDC->SetTextColor(clng); } else { sbgcol = bgcol; sfgcol = fgcol; pDC->SetTextColor(fgcol); } // Pre-render tabs if(!hex) ExpandTabs(str); // Adjust for relative horizontal pos if(scol) str = str.Right(str.GetLength() - scol); // Padd string till eol if(!hex) { CString padd(' ', fullwidth - str.GetLength()); str +=padd; } // Comment colors, preprocessors, syntax if(!hex && !diff) { int incx; // 'C' keywords incx = str.Find("extern"); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 7; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("struct "); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 6; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("switch"); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 6; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("case"); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 4; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("if("); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 2; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("if ("); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 2; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("for("); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 3; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("for ("); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 3; sbgcol = bgcol; sfgcol = keywor; } incx = str.Find("else"); if(incx != -1) { split = TRUE; startp = incx; endp = incx + 4; sbgcol = bgcol; sfgcol = keywor; } // Preprocessing directivas incx = str.Find("#include"); if(incx != -1) { split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = prepro; } incx = str.Find("#define"); if(incx != -1) { split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = prepro; } incx = str.Find("#if"); if(incx != -1) { split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = prepro; } incx = str.Find("#else"); if(incx != -1) { split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = prepro; } incx = str.Find("#endif"); if(incx != -1) { split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = prepro; } incx = str.Find(pDoc->comment); if(incx != -1) { //pDC->SetTextColor(comm); split = TRUE; startp = incx; endp = str.GetLength(); sbgcol = bgcol; sfgcol = comm; } } // Search highlite if(AllowShighlite) { int offs = min(pDoc->ssel.lineb.GetSize()-1, loop); if(!pDoc->ssel.lineb.GetAt(offs)) { // Ignore lines not in search hit pDC->SetTextColor(fgcol); sfgcol = fgcol; if(hitmode) { lim = pDoc->strlist.GetCount()+1; continue; } } else { // Color whole line pDC->SetTextColor(srcc); sfgcol = srcc; } } else { // Cancel hit mode too hitmode = 0; } // Select Highlight if(loop >= lsoh && lsoh != -1) { pDC->SetBkColor(selcol); sbgcol = selcol; if(lsoch != -1) { split = TRUE; startp = lsoch; endp = leoch; sbgcol = cselcol; sfgcol = fgcol; } } if(loop > leoh && leoh != -1) { pDC->SetBkColor(bgcol); split = FALSE; } // Do diff coloring if(diff) { //P2N("diff color paint\r\n"); int difflag = diffa.GetAt( min(loop, diffa.GetSize()-1) ); switch(difflag) { case DIFF_ADD: pDC->SetTextColor(cadd); //P2N("diff ADD color paint\r\n"); sfgcol = cadd; break; case DIFF_DEL: pDC->SetTextColor(cdel); //P2N("diff DEL color paint\r\n"); sfgcol = cdel; break; case DIFF_CHG: pDC->SetTextColor(cchg); //P2N("diff CHG color paint\r\n"); sfgcol = cchg; break; default: pDC->SetTextColor(oldcr); sfgcol = oldcr; break; } } // --------------------------------------------- if(split) { // Display a split colored string: CString ll, mm, rr; ll = str.Left(startp); mm = str.Mid(startp, endp - startp); rr = str.Right(str.GetLength() - endp); pDC->SetBkColor(bgcol); pDC->SetTextColor(fgcol); //pDC->TabbedTextOut(xx, yy, ll, 1, tabs, 0); pDC->TextOut(xx, yy, ll); pDC->SetBkColor(sbgcol); pDC->SetTextColor(sfgcol); int offset = ll.GetLength()* tm.tmAveCharWidth; //pDC->TabbedTextOut(xx + offset, yy, mm, 1, tabs, offset); pDC->TextOut(xx + offset, yy, mm); pDC->SetBkColor(bgcol); pDC->SetTextColor(fgcol); offset = ll.GetLength()* tm.tmAveCharWidth + mm.GetLength()* tm.tmAveCharWidth; //pDC->TabbedTextOut(xx + offset, yy, rr, 1, tabs, offset); pDC->TextOut(xx + offset, yy, rr); } // --------------------------------------------- else { pDC->SetTextColor(sfgcol); if(hex) { CString num; int loop; CString padd(' ', fullwidth); pDC->TextOut(xx, yy, padd); for(loop = 0; loop < str.GetLength(); loop++) { num.Format( "%02x ", (unsigned char) str.GetAt(loop)); //pDC->TabbedTextOut(xx + tm.tmAveCharWidth * loop * 3, yy, num, // strlen(num), 1, tabs, 0); pDC->TextOut(xx + tm.tmAveCharWidth * loop * 3, yy, num); } } else { //pDC->TabbedTextOut(xx, yy, str, 1, tabs, 0); pDC->TextOut(xx, yy, str); } } // --------------------------------------------- yy+=tm.tmHeight; // Reached limit of client area, stop if(yy > fullheight && ! pDC->IsPrinting()) break; } // Clear the rest of the screen (if needed) //P2N("Full diff %d\r\n", fulldiff); if(hitmode) { fulldiff = (fullheight - yy)/tm.tmHeight; // remainder if(fullheight % tm.tmHeight) fulldiff++; } CString padd(' ', fullwidth); for(loop = 0; loop < fulldiff; loop++) { //pDC->TabbedTextOut(xx, yy, padd, 1, tabs, 0); pDC->TextOut(xx, yy, padd); yy+=tm.tmHeight; } ////////////////////////////////////////////////////////////////////////// // Paint Logo #if 1 CDC dcMem; dcMem.CreateCompatibleDC(pDC); RECT rect,m_rDataBox; GetClientRect(&rect); CopyRect(&m_rDataBox, &rect); // Calc blend rectange CFont* oldFont = pDC->SelectObject(&m_LogoFont); CSize sz = pDC->GetTextExtent(sLogoString, sLogoString.GetLength()); sz.cx += 10; sz.cy += 10; pDC->SelectObject(oldFont); //P2N("Logo string size ww=%d hh=%d\r\n", sz.cx, sz.cy); // CreateCompatibleBitmap does not work on color/memory device! HBITMAP bm =::CreateCompatibleBitmap(pDC->GetSafeHdc(), sz.cx, sz.cy); HBITMAP oldbm = (HBITMAP)::SelectObject(dcMem, bm); CRect rc(0, 0, sz.cx, sz.cx); dcMem.FillSolidRect(rc, RGB(255, 255, 255) ); // Alpha blend BLENDFUNCTION m_bf; m_bf.BlendOp = AC_SRC_OVER; m_bf.BlendFlags = 0; m_bf.SourceConstantAlpha = 100; m_bf.AlphaFormat = 0; CFont* XoldFont = dcMem.SelectObject(&m_LogoFont); int OldMode = dcMem.SetBkMode(TRANSPARENT); // shift logo box right, and print black... //COLORREF oldColor = pDC->SetTextColor(RGB(200,200,200)); //pDC->DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); // shift logo box left and print white m_rDataBox.left = 0; m_rDataBox.right = sz.cx; m_rDataBox.top = 0; m_rDataBox.bottom = sz.cy; COLORREF OldCol = dcMem.SetTextColor(RGB(200, 200, 200)); dcMem.DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); m_rDataBox.left = 5; m_rDataBox.right = sz.cx; m_rDataBox.top = 5; m_rDataBox.bottom = sz.cy; dcMem.SetTextColor(RGB(240, 240, 240)); dcMem.DrawText(sLogoString, sLogoString.GetLength(), &m_rDataBox, DT_VCENTER | DT_SINGLELINE | DT_CENTER); AlphaBlend(pDC->GetSafeHdc(), rect.right - (sz.cx + 15), rect.bottom - (sz.cy + 5), sz.cx, sz.cy, dcMem, 0,0, sz.cx, sz.cy, m_bf); dcMem.SelectObject(XoldFont); dcMem.SetTextColor(OldCol); dcMem.SetBkMode(OldMode); ::SelectObject(dcMem, oldbm); ::DeleteObject(bm); dcMem.DeleteDC(); #endif // Restore stolen settings: pDC->SetTextColor(oldcr); pDC->SetBkColor(oldbk); pDC->SelectObject(oldfont); SyncCaret(); in_draw = FALSE; } ////////////////////////////////////////////////////////////////////// // OnPreparePrinting BOOL CWedView::OnPreparePrinting(CPrintInfo* pInfo) { // WinBug if(! pInfo) return TRUE; return DoPreparePrinting(pInfo); } ////////////////////////////////////////////////////////////////////// // OnBeginPrinting void CWedView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { progress = 0; pages.SetSize(2); } ////////////////////////////////////////////////////////////////////// // OnEndPrinting void CWedView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { pages.SetSize(2); } // CWedView diagnostics #ifdef _DEBUG ////////////////////////////////////////////////////////////////////// // AssertValid void CWedView::AssertValid() const { ASSERT(magic == WED_MAGIC); CView::AssertValid(); } ////////////////////////////////////////////////////////////////////// // Dump void CWedView::Dump(CDumpContext& dc) const { CView::Dump(dc); } ////////////////////////////////////////////////////////////////////// // GetDocument CWedDoc* CWedView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWedDoc))); return (CWedDoc*)m_pDocument; } #endif //_DEBUG ////////////////////////////////////////////////////////////////////// // OnShowWindow void CWedView::OnShowWindow(BOOL bShow, UINT nStatus) { //P2N("OnShowWindow\r\n"); } ////////////////////////////////////////////////////////////////////// // OnChar void CWedView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int wants = 0; CString str, lstr, rstr; //P2N("OnChar: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); if(spp.splashed) { spp.Hide(); return; } if( kblock ) return; if(record) { CString num; num.Format( "%d %d %d %d", R_CHAR, nChar, nRepCnt, nFlags); //P2N("Recording %s\r\n", num); macros[currmac].AddTail(num); } switch(nChar) { case VK_RETURN: { if(hitmode) { CancelHit(); break; } // CR pressed: int indent = 0; if(row < pDoc->strlist.GetCount()-1) { // Split line, create new: str = pDoc->strlist.GetLine(row); int realindent, realcol, ontab; realindent = WalkStr(str, " \t"); if(realindent == -1) realindent = 0; UnTabbedPos(str, realindent, &indent, &ontab); TabbedPos(str, col, &realcol, &ontab); lstr = str.Left(realcol); if(col >= indent) rstr = str.Right(str.GetLength() - realcol); else rstr = str.Right(str.GetLength() - realindent); SaveUndo(this, UNDO_MOD, row, col, str); SaveUndo(this, UNDO_ADD|UNDO_BLOCK, row+1, col, rstr); //P2N("%s -- indent %d col: %d \r\n", // str, indent, col); if(indent > 0) { CString pad; pad = str.Left(realindent); pad += rstr; rstr = pad; } pDoc->strlist.SetLine(row, lstr); pDoc->strlist.InsertLine(row + 1, rstr); pDoc->SetModifiedFlag(); wants = 1; } // Move to next line: col = indent; row++; // Add new line if over the end if(row >= pDoc->strlist.GetCount()) { pDoc->strlist.AddTail(""); } if (wants) pDoc->UpdateAllViews(NULL); SyncCaret(); } break; case VK_BACK: // Backspace: BackSpace(); break; case VK_ESCAPE: Esc(); break; case VK_TAB: // TAB character: if(soh != -1) { TabSelection(this, shift); break; } if(shift) { int step = col % 4; if(!step) step = 4; col -= step; col = max(col, 0); SyncCaret(); } else addchar(this, '\t'); break; // -------------------------------------------------- // ctrl-a case 'a'-'a' + 1: OnSelectSelectall(); break; // ctrl-b case 'b'-'a' + 1: OnInsertCTemplate(); break; // ctrl-c // Reserved for copy // ctrl-d case 'd'-'a' + 1: OnViewGotonextdifference(); break; // ctrl-e case 'e'-'a' + 1: AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_SAVEAS2, 0); break; // ctrl-f case 'f'-'a' + 1: SearchFile(); break; // ctrl-g case 'g'-'a' + 1: message("Closing file"); AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_CLOSE, 0); break; // ctrl-h //case 'h'-'a' + 1: /// message("Opening Search Dialog"); // SearchFile(TRUE); // break; // ctrl-j case 'j'-'a' + 1: //OnInsertJavaTemplate(); break; // ctrl-k case 'k'-'a' + 1: OnViewViewhex(); break; // ctrl-l case 'l'-'a' + 1: OnEditLowercaseword(); break; // ctrl-m case 't'-'a' + 1: FindFiles(this); break; // ctrl-q case 'q'-'a' + 1: message("Arrange windows"); AfxGetMainWnd()->SendMessage(WM_COMMAND, ID_WINDOW_CASCADE, 0); break; // ctrl-r case 'r'-'a' + 1: OnViewGotopreviousdifference(); break; // ctrl-s case 's'-'a' + 1: if(!pDoc->IsModified()) { message("Document not modified"); break; } AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_SAVE, 0); break; // ctrl-u case 'u'-'a' + 1: OnEditUppercaseword(); pDoc->SetModifiedFlag(); break; // ctrl-w case 'w'-'a' + 1: OnEditCapitalizeword(); pDoc->SetModifiedFlag(); break; // ctrl-y case 'y'-'a' + 1: ReDo(this); break; // --------------------------------------------- // The default action is to add the character default: // Filter gray+- with numlock off if(nFlags == 74 || nFlags == 78) { // Confirm it was a + or - if((nChar == '+' || nChar == '-')) { if(!GetKeyState(VK_NUMLOCK)) { // P2N("GRAY+- NO NUM\r\n"); break; } } } addchar(this, nChar); break; } CView::OnChar(nChar, nRepCnt, nFlags); } ////////////////////////////////////////////////////////////////////// // OnKeyUp void CWedView::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //P2N("Keyup: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); if( kblock ) { return; } if(record) { CString num; if(nChar != VK_F7 && nChar != VK_F8) { num.Format( "%d %d %d %d", R_UP, nChar, nRepCnt, nFlags); //P2N("Recording: %s\r\n", num); macros[currmac].AddTail(num); } } switch(nChar) { case VK_SHIFT: //P2N("SHIFT UP "); shift = FALSE; break; case VK_CONTROL: //P2N("CONTROL UP "); control = FALSE; break; } //P2N("Keyup: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); CView::OnKeyUp(nChar, nRepCnt, nFlags); } static int was_home; static int was_end; ////////////////////////////////////////////////////////////////////// // OnKeyDown void CWedView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, lstr, rstr, replay; // Reset key timer lastkeypress = 0; if( kblock ) { message ("Keyboard Locked. Use: Main Menu => Advanced => Unlock KeyBoard to unlock it."); return; } if(nChar != VK_HOME) was_home = 0; if(nChar != VK_END) was_end = 0; //P2N("CWedView::OnKeyDown: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); if(record) { CString num; if( nChar != VK_F7 && nChar != VK_F8 && !(nChar >= '0' && nChar <= '9' && control)) { if(macros[currmac].GetCount() > 80) { message("Recording longer then usual ..."); } num.Format( "%d %d %d %d", R_DOWN, nChar, nRepCnt, nFlags); //P2N("Recording: %s\r\n", num); macros[currmac].AddTail(num); } } if(nChar >= '0' && nChar <= '9' && control) { SwitchRec(nChar - '0'); } else switch(nChar) { case VK_CANCEL: // control - break => ESC if(control) OnViewStopdiffing(); Esc(); break; case VK_SCROLL: //scrollock = !scrollock; //P2N("Scroll lock\r\n"); break; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ case VK_F1: OnHelpHelponkeyword(); break; case VK_F2: //OnInsertTemplateone(); break; case VK_F3: if(!shift) OnSearchFindnext(); else OnSearchFindprevious(); //OnInsertTemplatetwo(); break; case VK_F4: //OnInsertTemplatethree(); break; case VK_F5: //if(control) // // Compile // OnCompileExecutedevstudioproject(); //else // Find prev OnSearchFindprevious(); break; case VK_F6: // Find next OnSearchFindnext(); break; case VK_F7: if(control) Spellcheck(TRUE); else if(shift) Spellcheck(FALSE); else // Recording key: start_record(); break; case VK_F8: // Playback key: if(control) OnCompileMake(); else PlayMacro(shift); break; case VK_F9: if(shift) Caseselection(FALSE); else if (control) Caseselection(TRUE); else { // Open file ((CWedApp*)AfxGetApp())->OpenFile(); message ("Opening file"); } break; case VK_F11: if(shift) OnMoveNextlongline(); else if(control) {} else MoveFunction(false); break; case VK_F12: if(shift) OnMoveMovepreviouslongline(); else if(control) {} else MoveFunction(true); break; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ case VK_SHIFT: shift = TRUE; break; case VK_CONTROL: control = TRUE; break; case VK_LEFT: //P2N("RIGHT "); if(shift && soh == -1) { soh = eoh = row ; soch = eoch = col; } if(control) OnMovePreviouseword(); else OnMovePreviouschar(); break; case VK_RIGHT: //P2N("LEFT "); if(shift && soh == -1) { soh = eoh = row ; soch = eoch = col; } if(control) OnMoveNextword(); else OnMoveNextcharacter(); break; case VK_UP: //P2N("UP "); if(shift && soh == -1) soh = eoh = row ; OnMovePreviousline(); HitCusror(FALSE); break; case VK_DOWN: //P2N("DOWN "); if(shift && soh == -1) soh = eoh = row; OnMoveNextline() ; HitCusror(TRUE); break; case VK_ADD: // Grey + if(GetKeyState(VK_NUMLOCK)) break; //P2N("Grey+ "); CopyToHold(this, FALSE); break; case VK_SUBTRACT: // Grey - if(GetKeyState(VK_NUMLOCK)) break; //P2N("Grey - "); CopyToHold(this, TRUE); break; case VK_PRIOR: //P2N("PGUP "); if(shift && soh == -1) soh = eoh = row ; if(control) OnMovePreviouseparagraph(); else OnMovePageup(); HitCusror(FALSE); break; case VK_NEXT: //P2N("PGDOWN "); if(shift && soh == -1) soh = eoh = row ; if(control) OnMoveNextparagraph(); else OnMovePagedown(); HitCusror(TRUE); break; case VK_HOME: //P2N("HOME "); if(shift && soh == -1) { soh = eoh = row ; soch = eoch = col; } was_home++; if(was_home == 1) { if(control) OnMoveBeginningoffile(); else OnMoveBeginningofline(); } else if(was_home == 2) { OnMoveBeginningofpage(); } else if(was_home == 3) { OnMoveBeginningoffile(); } else { was_home = 0; } HitCusror(FALSE); break; case VK_END: //P2N("END "); if(shift && soh == -1) { soh = eoh = row ; soch = eoch = col; } was_end++; if(was_end == 1) { if(control) OnMoveEndoffile(); else OnMoveEndofline(); } else if(was_end == 2) { OnMoveEndofpage(); } else if(was_end == 3) { OnMoveEndoffile(); } else { was_end = 0; } HitCusror(TRUE); break; case VK_DELETE: Del(); //P2N("DEL "); break; case VK_INSERT: if(hitmode) { CancelHit(); break; } if(shift) { message ("Paste from clipboard"); PasteClip(this); } else if (control) { message ("Copy to clipboard"); CopyToClip(this, FALSE); } else { PasteHold(this); } break; // ctrl-b case 'b': if(control) { message ("Control - B"); } break; } //P2N("CWedView::OnKeyDown\r\n"); CView::OnKeyDown(nChar, nRepCnt, nFlags); } ////////////////////////////////////////////////////////////////////// // OnSysKeyDown void CWedView::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // Reset key timer lastkeypress = 0; //P2N("SysKeyDown: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); if(record) { CString num; if(nChar != VK_F7 && nChar != VK_F8) { num.Format( "%d %d %d %d", R_SYSDOWN, nChar, nRepCnt, nFlags); //P2N("Recording: %s\r\n", num); macros[currmac].AddTail(num); } } switch(nChar) { case VK_MENU: //P2N("ALT"); alt = TRUE; break; case VK_UP: //alt-up //P2N("ALT-UP"); break; case VK_DOWN: //alt-down //P2N("ALT-DOWN\r\n"); break; case VK_LEFT: //alt-left //P2N("ALT-LEFT\r\n); OnMoveBeginningofword(); break; case VK_RIGHT: //alt-right //P2N("ALT-RIGHT "); OnMoveEndofword() ; break; } CView::OnSysKeyDown(nChar, nRepCnt, nFlags); } ////////////////////////////////////////////////////////////////////// // OnSysChar void CWedView::OnSysChar(UINT nChar, UINT nRepCnt, UINT nFlags) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //P2N("SysChar: %d (%c) Flags: %d\r\n", nChar, nChar, nFlags); if(record) { CString num; num.Format( "%d %d %d %d", R_SYSCHAR, nChar, nRepCnt, nFlags); //P2N("Recording: %s\r\n", num); macros[currmac].AddTail(num); } CString str, lstr; if(nChar >= '0' && nChar <= '9') { //P2N("Alt-1 ctrl: %d alt: %d\r\n", control, alt); CString num; currhold = nChar - '0'; num.Format( " H %02d ", currhold); message ("Switched holding buffer"); hold(num); } else switch(tolower(nChar)) { //alt-a case 'a': // Select all OnFileSaveall(); break; //alt-b case 'b': // Show buffers ShowBuffers(); break; //alt-c case 'c': // Coloumn select OnEditStartcolumnselectaltc(); break; //alt-d case 'd': // Delete line DelLine(); break; //alt-e case 'e': message ("Opening file in source directory"); OpenSource(srcdir); break; //alt-f case 'f': FindFiles(this); break; //alt-g case 'g': // Goto OnMoveGotoline(); break; //alt-h case 'h': OnSearchHiteditmode(); break; //alt-i case 'i': OnInsertIncrementednumber(); break; //alt-j case 'j': OnViewCococodecolector(); break; //alt-k case 'k': // Kill to EOL KillToTol(); break; //alt-l case 'l': // Start line select OnEditStartselectaltl(); break; //alt-m case 'm': OnSelectMarkblock(); break; //alt-n case 'n': // Switch to next buffer SwitchToNext(); break; //alt-o case 'o': // Open file message ("Opening file in destination directory"); OpenSource(targdir); break; //alt-p case 'p': // Paragraph select OnSelectSelectparagraph(); break; //alt-q case 'q': Maximizecurrent(); break; //alt-r case 'r': // Redo ReDo(this); break; //alt-s case 's': SearchFile(); break; //alt-t case 't': // Change (Taush) SearchFile(TRUE); break; //alt-u case 'u': // Undo UnDo(this); break; //alt-v case 'v': // Select word with coloumn highlite: OnSelectSelectword(); break; //alt-w case 'w': // Write: if(!pDoc->IsModified()) { message("Document not modified"); break; } else { AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_FILE_SAVE, 0); pDoc->SetTitle(pDoc->GetPathName()); } break; //alt-x case 'x': // Exit //SetParent(parent); //AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_APP_EXIT, 0); break; //alt-y case 'y': OnViewFullscreen(); break; //alt-z case 'z': OnWindowMaximizemain(); break; default: CView::OnSysChar(nChar, nRepCnt, nFlags); break; } } ////////////////////////////////////////////////////////////////////// // OnSysKeyUp void CWedView::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { currentedit = this; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(record) { CString num; if(nChar != VK_F7 && nChar != VK_F8) { num.Format( "%d %d %d %d", R_SYSUP, nChar, nRepCnt, nFlags); //P2N("Recording: %s\r\n", num); macros[currmac].AddTail(num); } } switch(nChar) { case VK_MENU: alt = FALSE; break; } CView::OnSysKeyUp(nChar, nRepCnt, nFlags); } ////////////////////////////////////////////////////////////////////// // OnSetFocus void CWedView::OnSetFocus(CWnd* pOldWnd) { // Call default function CView::OnSetFocus(pOldWnd); currentedit = this; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); mode(modestr); // Take care of our cursor CreateCaret(&caret); ShowCaret(); wantcaret = TRUE; //SyncCaret(); // This caused dblclick to be sent // YieldToWin(); //P2N("Got Focus: %d from %d parent %d\r\n", // this, pOldWnd, GetParent()); mouse = 0; scrolldiv = (pDoc->strlist.GetCount() / 33000) + 1; SetScrollRange(SB_VERT, 0, pDoc->strlist.GetCount()/scrolldiv); SetScrollRange(SB_HORZ, 0, pDoc->maxcol); //P2N("Scrolldiv %d\r\n", scrolldiv); // Fill in diff submenu CMenu* pfMenu = GetDiffMenu(); if(pfMenu) { for (int iPos = pfMenu->GetMenuItemCount()-1; iPos >= 0; iPos--) { pfMenu->DeleteMenu(iPos, MF_BYPOSITION); } // Add an item for each available file CWedApp *app = (CWedApp*)AfxGetApp(); POSITION Pos = app->pDocTemplate->GetFirstDocPosition(); int offset = 0; for(int loop = 0; loop < 5; loop++) { if(!Pos) break; CWedDoc* doc = (CWedDoc*)app->pDocTemplate->GetNextDoc(Pos); ASSERT_VALID(doc); // Current doc, do not count if(doc == pDoc) continue; CString file = doc->GetPathName(); pfMenu->AppendMenu( MF_STRING, ID_DIFF_DIFFONE + offset , file); offset++; } } // See if file was modified outside of WED CString file = pDoc->GetPathName(); if(file != "") { struct _stat docstat3; if(!_stat(file, &docstat3)) { //P2N("file %s Docstat %d docstat2 %d \r\n", // file, pDoc->docstat2.st_mtime, docstat3.st_mtime ); if(pDoc->docstat2.st_mtime != docstat3.st_mtime) { pDoc->docstat2 = docstat3; AfxMessageBox("File changed outside Wed. Please check."); YieldToWin(); } } } } // Make POS and caret agree // If bound == 1 move 3 lines away from borders // If bound == 2 || bound == 3 move sync to the middle ////////////////////////////////////////////////////////////////////// // SyncCaret int CWedView::SyncCaret(int bound) { CString num; int wants = 0; POINT pos; RECT rec; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(!fflf.lfHeight) fflf.lfHeight = 14; if(!fflf.lfWidth) fflf.lfWidth = 8; //P2N("Sync_caret %d %d\r\n", row, col); // Make sure we are in file if(row >= pDoc->strlist.GetCount()) { row = pDoc->strlist.GetCount()-1; } // Make sure we are in view GetClientRect(&rec) ; // Display caret in new position: if(srow > row) { srow = row; if(bound == 1) srow -= 3; //P2N("Up scroll srow = %d\r\n", srow); wants = TRUE; } if(scol > col) { scol = col; //P2N("Left scroll scol = %d\r\n", scol); wants = TRUE; } int xxrow = row; // Handle hit mode if(hitmode) { int vrow = srow, xrow = srow; while(TRUE) { // Limit: if(vrow >= pDoc->strlist.GetCount()-1) break; if(vrow >= row) break; // Adjust: if(pDoc->ssel.lineb.GetAt(vrow)) xrow++; vrow++; } P2N("xrow = %d\r\n", xrow); // Adjust virtual position xxrow = xrow; } pos.x = fflf.lfWidth * (col - scol); pos.y = fflf.lfHeight * (xxrow - srow) + fflf.lfHeight - 2; // Limit it if((rec.bottom - rec.top) < pos.y ) { srow = (fflf.lfHeight * (row + 1) - (rec.bottom - rec.top))/fflf.lfHeight + 1; if(bound == 1) srow += 3; pos.y = fflf.lfHeight * (row - srow) + (fflf.lfHeight-2); wants = TRUE; //P2N("Scroll srow = %d\r\n", srow); } // Adjust horizontal scroll // Assume 2 times char width for the scroll bar if((rec.right - rec.left) < pos.x + 2 * fflf.lfWidth) { scol = (fflf.lfWidth * (col + 1) - (rec.right - rec.left))/fflf.lfWidth + 2; pos.x = fflf.lfWidth * ((col - scol) + 1); wants = TRUE; //P2N("Scroll scol = %d\r\n", scol); } // Adjust for verical scroll in bound if(bound == 3 || bound == 2 || GetKeyState(VK_SCROLL)) { int mid = ((rec.bottom - rec.top)/fflf.lfHeight)/2; if(row > mid) { srow = row - mid; //row = mid; } //P2N("bound3 scol = %d\r\n", scol); pos.x = fflf.lfWidth * (col - scol); pos.y = fflf.lfHeight * (row - srow) + (fflf.lfHeight-2); wants = TRUE; } // Check for out of bounds srow = min(srow, pDoc->strlist.GetCount()-1); srow = max(srow, 0); row = min(row, pDoc->strlist.GetCount()-1); row = max(row, 0); //col = min(col, 0); if(wants && !in_draw) pDoc->UpdateAllViews(NULL); // ----------------------------------------------- SetCaretPos(pos); // Set highlight if(soh != -1) { eoh = row; if(soch != -1) eoch = col; // Redisplay if highlight changed if(!in_draw) pDoc->UpdateAllViews(NULL); } // Massage scroll bars int lines = pDoc->strlist.GetCount()-1; SetScrollRange(SB_VERT, 0, lines/scrolldiv); SetScrollRange(SB_HORZ, 0, pDoc->maxcol); SetScrollPos(SB_HORZ, col); SetScrollPos(SB_VERT, row/scrolldiv); num.Format("Ln %d Col %d ", row, col); rowcol(num); num.Format("Ln %d ", lines); filesize(num); // Do not yield here !!! return(0); } ////////////////////////////////////////////////////////////////////// // OnUpdate void CWedView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //P2N("OnUpdate %d %d\r\n", row, col); if(lHint) { // Only from current postion to end of line RECT rec; CString str; str = pDoc->strlist.GetLine(row); rec.left = fflf.lfWidth * (col-1); rec.top = fflf.lfHeight * (row - srow); // in case of deleted char, add one rec.right = fflf.lfWidth * (str.GetLength() + 4); rec.bottom = rec.top + fflf.lfHeight; InvalidateRect(&rec, FALSE); } else { // Refresh the whole lot: InvalidateRect(NULL, FALSE); } } ////////////////////////////////////////////////////////////////////// // OnCreate int CWedView::OnCreate(LPCREATESTRUCT lpCreateStruct) { ShowScrollBar(SB_BOTH ); EnableScrollBar(0); SetFont(&ff); // Take care of our cursor //CreateCaret(&caret); ShowCaret(); //SyncCaret(); if (CView::OnCreate(lpCreateStruct) == -1) return -1; if(!SetTimer(1, 2000, NULL)) { AfxMessageBox("Cannot create timer, close spash manually"); } return 0; } ////////////////////////////////////////////////////////////////////// // ShowBuffers void CWedView::ShowBuffers() { message("Show Buffers"); BufferList bl; bl.m_cv = (long)this; bl.DoModal(); } static CPoint oldpoint; ////////////////////////////////////////////////////////////////////// // OnLButtonDown void CWedView::OnLButtonDown(UINT nFlags, CPoint point) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //P2N("Mouse: x=%d y=%d\r\n", point.x, point.y); if(fflf.lfHeight == 0 ) goto endd; if(fflf.lfWidth == 0 ) goto endd; // Translate coordinates row = point.y /fflf.lfHeight + srow; col = point.x /fflf.lfWidth + scol; row = min(row, pDoc->strlist.GetCount()-1); // Tell the system the mouse is down ... mouse = TRUE; //If we clicked on non highlite, stop highlites if(row < soh || row > eoh) { soh = eoh = soch = eoch = -1; pDoc->UpdateAllViews(NULL); } SyncCaret(); oldpoint = point; endd: ; // CView::OnLButtonDown(nFlags, point); } ////////////////////////////////////////////////////////////////////// // OnLButtonDblClk void CWedView::OnLButtonDblClk(UINT nFlags, CPoint point) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; int wbeg = 0, wend = 0, lrow; //P2N("Dblclick x:%d y:%d\r\n", point.x, point.y); if(fflf.lfHeight == 0 ) goto endd; if(fflf.lfWidth == 0 ) goto endd; lrow = point.y /fflf.lfHeight + srow; lrow = min(lrow, pDoc->strlist.GetCount()-1); //col = point.x /fflf.lfWidth; str = pDoc->strlist.GetLine(lrow); // Find word we are sitting on SelWord(str, col, &wbeg, &wend); //P2N("SelWord: %d %d\r\n", wbeg, wend); if(wbeg != wend) { col = wend-1; soh = row; eoh = row; soch = wbeg; eoch = wend; } pDoc->UpdateAllViews(NULL); SyncCaret(); endd: ; //CView::OnLButtonDblClk(nFlags, point); } static CString undostr; static int oldrow, oldcol, startrow, endrow; ////////////////////////////////////////////////////////////////////// // OnLButtonUp void CWedView::OnLButtonUp(UINT nFlags, CPoint point) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // Save undo info for this one: if(drag) { if(startrow != endrow) { // We have moved a string ... //P2N("Saveundo: start %d end %d with %s\r\n" // , startrow, endrow, undostr); SaveUndo(this, 'd', startrow, 0, undostr); SaveUndo(this, 't', endrow, 0, undostr); } } mouse = FALSE; drag = FALSE; highlite = FALSE; ReleaseCapture(); CView::OnLButtonUp(nFlags, point); } ////////////////////////////////////////////////////////////////////// // OnMouseMove void CWedView::OnMouseMove(UINT nFlags, CPoint point) { int lrow, lcol; CWedDoc* pDoc; //P2N("Mousemove %d x=%d y=%d\r\n", // this, point.x, point.y ); if(m_busy) SetCursor(WaitCursor); // If mouse is not down, no drag or highlite in progress if(!mouse) { goto end_mou; } if(fflf.lfHeight == 0 ) goto end_mou; if(fflf.lfWidth == 0 ) goto end_mou; pDoc = GetDocument(); ASSERT_VALID(pDoc); // Translate to cursor coordinates: lrow = point.y /fflf.lfHeight + srow; lcol = point.x /fflf.lfWidth; // Check for out of bounds, SetCapture can do minuses lrow = max(lrow, 0); lrow = min(lrow, pDoc->strlist.GetCount()-1); lcol = max(lcol, 0); // Move to coordinates row = lrow; col = lcol; #if 0 // Test if in action if(drag) { // Row changed, action if(oldrow != lrow) { int loop, xrow, offset; offset = lrow - oldrow; xrow = oldrow = lrow; //P2N("Drag: x=%d y=%d\r\n", point.x, point.y); // Remove old lrow = soh; SaveUndo(this, UNDO_NOP, row, col, ""); for(loop = 0; loop < draglist.GetCount(); loop++) { CString str = pDoc->strlist.GetLine(lrow); //P2N("Delete line: %s\r\n", str); SaveUndo(this, UNDO_DEL, lrow, col, str); DeleteLine(this, lrow); } if(offset > 0) { if (soh < pDoc->strlist.GetCount()-1) { lrow = ++soh; ++eoh; } } else { if (soh) { lrow = --soh; --eoh; } } // Add new, careful of last line (spent a day tracking): POSITION pos = draglist.FindIndex(0); loop = lrow; while(TRUE) { CString str2; if(!pos) break; str2 = draglist.GetNext(pos); pDoc->strlist.InsertLine(loop++, str2); //P2N("Adding: row=%d %s\r\n", lrow, str2); } //soh = xrow + 1 ; //eoh = xrow + draglist.GetCount(); endrow = lrow; pDoc->UpdateAllViews(NULL); SyncCaret(); } } else #endif if (highlite) { if(oldrow != lrow || oldcol != lcol) { col = lcol; row = lrow; //P2N("Highlite: %d\r\n", row); oldrow = lrow; oldcol = lcol; SyncCaret(); //pDoc->UpdateAllViews(NULL); } } else { #if 0 // Not in action, see if we want some if(soh != -1) { // start drag: undostr = pDoc->strlist.GetAt( pDoc->strlist.FindIndex(lrow)); // --------------------------------------------- if(lrow >= soh && lrow < eoh ) { int loop; draglist.RemoveAll(); for(loop = soh; loop <= eoh; loop++) { CString hl; hl = pDoc->strlist.GetAt( pDoc->strlist.FindIndex(loop)); draglist.AddTail(hl); //P2N("Drag pick: %s\r\n", hl); } } else { soh = -1; eoh = -1; soch = -1; eoch = -1; highlite = FALSE; } // --------------------------------------------- oldrow = lrow; startrow = lrow; drag = TRUE; } else #endif { // start higlite, only if we dragged a 1/2 char if(abs(oldpoint.x - point.x) > 2) { //P2N("Start col highlite: %d\r\n", soh); soh = eoh = lrow; soch = eoch = lcol; highlite = TRUE; } else if(abs(oldpoint.y - point.y) > 2) { //P2N("Start row highlite: %d\r\n", soh); soh = eoh = lrow; highlite = TRUE; } } SetCapture(); } end_mou: CView::OnMouseMove(nFlags, point); } ////////////////////////////////////////////////////////////////////// // OnVScroll void CWedView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); switch(nSBCode) { // Emulate keystrokes: case SB_LINEDOWN : OnKeyDown(40, 1, 336); break; case SB_LINEUP : OnKeyDown(38, 1, 328); break; case SB_PAGEDOWN : OnKeyDown(34, 1, 337); break; case SB_PAGEUP : OnKeyDown(33, 1, 329); break; case SB_LEFT : OnKeyDown(33, 1, 329); break; case SB_THUMBTRACK : row = (nPos * scrolldiv); SyncCaret(); //pDoc->UpdateAllViews(NULL); //P2N("Scroll track %d\r\n", nPos); break; } SetScrollPos(SB_VERT, row/scrolldiv); CView::OnVScroll(nSBCode, nPos, pScrollBar); } ////////////////////////////////////////////////////////////////////// // OnViewViewhex void CWedView::OnViewViewhex() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); int real, ontab; if( hex) { modestr = ""; mode(modestr); hex = FALSE; UnTabbedPos(str, col/3, &real, &ontab); col = real; } else { TabbedPos(str, col, &real, &ontab); col = real * 3; hex = TRUE; modestr = "HEX"; mode(modestr); } message ("Toggled HEX mode"); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnPrint void CWedView::OnPrint(CDC* pDC, CPrintInfo* pInfo) { CString foot; CString head; int xx = 0, yy = 0, lim; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; CFont *oldfont; TEXTMETRIC tm; //P2N("Rendering page: %d\r\n", pInfo->m_nCurPage); // Just started if(pInfo->m_nCurPage == 1) { progress = 0; // Kill previous array pages.SetSize(2); pages.SetAtGrow(pInfo->m_nCurPage, progress); pInfo->SetMaxPage(pInfo->m_nCurPage+1); } else // Remeber page boundaries for backwards scan { if(pages.GetSize() < (int)pInfo->m_nCurPage + 1) { // Add pages.SetAtGrow(pInfo->m_nCurPage, progress); pInfo->SetMaxPage(pInfo->m_nCurPage+1); } else { // Recall pInfo->m_bContinuePrinting = TRUE ; progress = pages.GetAt(pInfo->m_nCurPage); } } oldfont = pDC->SelectObject( &pp ); pDC->GetTextMetrics(&tm); // Put header and footer head.Format("%s:%d", pDoc->GetPathName(), progress); pDC->TextOut(pInfo->m_rectDraw.BottomRight().x /2 - head.GetLength() * tm.tmAveCharWidth/2, 00, head); foot.Format("- page %d -", pInfo->m_nCurPage); pDC->TextOut(pInfo->m_rectDraw.BottomRight().x /2 - foot.GetLength() * tm.tmAveCharWidth/2, pInfo->m_rectDraw.BottomRight().y - tm.tmHeight, foot); // Adjust limits to alow header/footer pInfo->m_rectDraw.BottomRight().y -= 3*tm.tmHeight; pInfo->m_rectDraw.TopLeft().y += 3*tm.tmHeight; // Leave space for hole punch and right margin pInfo->m_rectDraw.TopLeft().x += 6 * tm.tmHeight; pInfo->m_rectDraw.BottomRight().x -= 3 * tm.tmHeight; // Do it int height = pInfo->m_rectDraw.BottomRight().y - pInfo->m_rectDraw.TopLeft().y ; int width = pInfo->m_rectDraw.BottomRight().x - pInfo->m_rectDraw.TopLeft().x ; int cwidth = width / tm.tmAveCharWidth; xx = pInfo->m_rectDraw.TopLeft().x ; yy = pInfo->m_rectDraw.TopLeft().y ; lim = pDoc->strlist.GetCount() ; while(TRUE) { str = pDoc->strlist.GetLine(progress); progress++; // End of document if(progress > lim) break; // See if it is a pagefeed if(str == "\xc") { //AfxMessageBox("Pagefeed"); break; } // Tabs did not work on some printers, we expand them here ExpandTabs(str); CString str2; while(TRUE) { str2= str.Left(cwidth); // Wrap lines, no word boundary is considered pDC->TabbedTextOut(xx, yy, str2, 1, tabs, 0); yy+=tm.tmHeight; // Reached limit of string, stop if(str.GetLength() < cwidth) break; str = str.Right(str.GetLength() - cwidth); // Reached limit of client area, stop if(yy > height) break; } // Reached limit of client area, stop if(yy > height) break; } // Examine end of document if(progress > lim) { pInfo->SetMaxPage(pInfo->m_nCurPage); } // Restore stolen settings: pDC->SelectObject(oldfont); } ////////////////////////////////////////////////////////////////////// // OnPrepareDC void CWedView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo) { CView::OnPrepareDC(pDC, pInfo); // The class will pass a null pointer, ignore it if(!pDC) return; // The class will pass a null pointer, ignore it if(!pInfo) return; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int lim = pDoc->strlist.GetCount() ; pInfo->m_bContinuePrinting = TRUE ; // Only limit on real printing: if(!pInfo->m_bPreview) { if(progress >= lim) { pInfo->m_bContinuePrinting = FALSE ; } } } ////////////////////////////////////////////////////////////////////// // OnHScroll void CWedView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); switch( nSBCode) { case SB_LINELEFT: OnKeyDown(37, 1, 331); break; case SB_LINERIGHT : OnKeyDown(39, 1, 333); break; case SB_PAGELEFT: OnKeyDown(17, 1, 29); OnKeyDown(37, 1, 331); OnKeyUp(17, 1, 49181); break; case SB_PAGERIGHT: OnKeyDown(17, 1, 29); OnKeyDown(39, 1, 333); OnKeyUp(17, 1, 49181); break; case SB_THUMBTRACK : col = nPos; SyncCaret(); break; } CView::OnHScroll(nSBCode, nPos, pScrollBar); } ////////////////////////////////////////////////////////////////////// // OnViewFonts void CWedView::OnViewFonts() { LOGFONT lf; //Cfont ff.GetObject(sizeof(LOGFONT), &lf); CFontDialog dlg(&lf, CF_FIXEDPITCHONLY | CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT); if (dlg.DoModal() != IDOK) return; // Switch to new font. ff.DeleteObject(); if (!ff.CreateFontIndirect(&lf)) { //P2N("Cannot set font\r\n"); MessageBox("Cannot set font"); } // Logical parameters for the new font. //if(!ff.GetLogFont(&fflf)) // { // //P2N("Cannot set font\r\n"); // MessageBox("Cannot get logical font parameters"); // } //P2N("Selected new font: HH:%d WW: %d\r\n", // fflf.lfHeight, fflf.lfWidth); // Tell all documents about the change POSITION Pos = ((CWedApp*)AfxGetApp())->pDocTemplate-> GetFirstDocPosition(); for(;;) { if(!Pos) break; CWedDoc* doc = (CWedDoc*) ((CWedApp*)AfxGetApp())->pDocTemplate-> GetNextDoc(Pos); doc->UpdateAllViews(NULL); } } extern CWedApp theApp; static diffing = FALSE; ////////////////////////////////////////////////////////////////////// // OnInitialUpdate // Allocate one time stuff: void CWedView::OnInitialUpdate() { CView::OnInitialUpdate(); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->SetTitle(pDoc->GetPathName()); parent = GetParent(); if(!pDoc->inited) { pDoc->ssel.Create(IDD_DIALOG4); pDoc->inited = TRUE; SaveUndo(this, UNDO_MARK, row, col, ""); } } ////////////////////////////////////////////////////////////////////// // OnKillFocus void CWedView::OnKillFocus(CWnd* pNewWnd) { UnFullscreen(); HideCaret(); DestroyCaret(); currentedit = NULL; CView::OnKillFocus(pNewWnd); //soch = eoch = soh = eoh = -1; mouse = FALSE; control = shift = alt = FALSE; //P2N("Kill focus %d \r\n", this); } ////////////////////////////////////////////////////////////////////// // OnViewForegroundcolor void CWedView::OnViewForegroundcolor() { SetColor(&fgcol); } ////////////////////////////////////////////////////////////////////// // OnViewBackgroundcolor void CWedView::OnViewBackgroundcolor() { SetColor(&bgcol); } ////////////////////////////////////////////////////////////////////// // SetColor void CWedView::SetColor(COLORREF * col) { CColorDialog ccol(*col); if(ccol.DoModal() == IDOK) { *col = ccol.m_cc.rgbResult; // Tell all documents about the change POSITION Pos = ((CWedApp*)AfxGetApp())->pDocTemplate-> GetFirstDocPosition(); for(;;) { if(!Pos) break; CWedDoc* doc = (CWedDoc*) ((CWedApp*)AfxGetApp())->pDocTemplate-> GetNextDoc(Pos); doc->UpdateAllViews(NULL); } } } ////////////////////////////////////////////////////////////////////// // OnViewHighlitebackground void CWedView::OnViewHighlitebackground() { SetColor(&selcol); } ////////////////////////////////////////////////////////////////////// // OnViewColomnhighlitebackground void CWedView::OnViewColomnhighlitebackground() { SetColor(&cselcol); } ////////////////////////////////////////////////////////////////////// // OnViewSelectprinterfont void CWedView::OnViewSelectprinterfont() { LOGFONT lf; //memset(&lf, 0, sizeof(lf)); pp.GetObject(sizeof(LOGFONT), &lf); CFontDialog dlg(&lf, CF_FIXEDPITCHONLY | CF_SCREENFONTS | //CF_PRINTERFONTS | CF_INITTOLOGFONTSTRUCT); if (dlg.DoModal() == IDOK) { // switch to new font. pp.DeleteObject(); if (!pp.CreateFontIndirect(&lf)) { //P2N("Cannot set font\r\n"); MessageBox("Cannot set font"); } } } ////////////////////////////////////////////////////////////////////// // OnEditCut void CWedView::OnEditCut() { message ("Cut to clipboard"); CopyToClip(this, TRUE); } ////////////////////////////////////////////////////////////////////// // OnEditCopy void CWedView::OnEditCopy() { message ("Copy to clipboard"); CopyToClip(this, FALSE); } ////////////////////////////////////////////////////////////////////// // OnEditPaste void CWedView::OnEditPaste() { message ("Paste from clipboard"); PasteClip(this); } // Copy to holding buffer ////////////////////////////////////////////////////////////////////// // OnViewViewholdingheads void CWedView::OnViewViewholdingheads() { HoldHead hh; hh.m_edit1 = holding[0].IsEmpty() ? "empty": holding[0].GetHead() ; hh.m_edit2 = holding[1].IsEmpty() ? "empty": holding[1].GetHead() ; hh.m_edit3 = holding[2].IsEmpty() ? "empty": holding[2].GetHead() ; hh.m_edit4 = holding[3].IsEmpty() ? "empty": holding[3].GetHead() ; hh.m_edit5 = holding[4].IsEmpty() ? "empty": holding[4].GetHead() ; hh.m_edit6 = holding[5].IsEmpty() ? "empty": holding[5].GetHead() ; hh.m_edit7 = holding[6].IsEmpty() ? "empty": holding[6].GetHead() ; hh.m_edit8 = holding[7].IsEmpty() ? "empty": holding[7].GetHead() ; hh.m_edit9 = holding[8].IsEmpty() ? "empty": holding[8].GetHead() ; hh.m_edit10 = holding[9].IsEmpty() ? "empty": holding[9].GetHead() ; hh.m_edit11 = "Head of holding buffers"; hh.DoModal(); } ////////////////////////////////////////////////////////////////////// // OnWindowMaximizemain void CWedView::OnWindowMaximizemain() { AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED); } ////////////////////////////////////////////////////////////////////// // OnEditUndo void CWedView::OnEditUndo() { UnDo(this); } ////////////////////////////////////////////////////////////////////// // OnEditRedo void CWedView::OnEditRedo() { ReDo(this); } ////////////////////////////////////////////////////////////////////// // OnRButtonDown void CWedView::OnRButtonDown(UINT nFlags, CPoint point) { POINT scr = point; ClientToScreen(&scr); CMenu mm; mm.LoadMenu(IDR_MENU1); CMenu *pp = mm.GetSubMenu( 0 ); pp->TrackPopupMenu( TPM_LEFTALIGN, scr.x, scr.y, this); //P2N("RbuttonDown\r\n"); CView::OnRButtonDown(nFlags, point); } ////////////////////////////////////////////////////////////////////// // OnOperationsSelectline void CWedView::OnOperationsSelectline() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); soh = row; eoh = row; SyncCaret(); pDoc->UpdateAllViews(NULL); message("Line selected"); } ////////////////////////////////////////////////////////////////////// // OnDiffDiffone void CWedView::OnDiffDiffone() { OnDiffToX(0); } ////////////////////////////////////////////////////////////////////// // OnDiffDifftwo void CWedView::OnDiffDifftwo() { OnDiffToX(1); } ////////////////////////////////////////////////////////////////////// // OnDiffDiffthree void CWedView::OnDiffDiffthree() { OnDiffToX(2); } ////////////////////////////////////////////////////////////////////// // OnDiffDifffour void CWedView::OnDiffDifffour() { OnDiffToX(3); } ////////////////////////////////////////////////////////////////////// // OnDiffDiffive void CWedView::OnDiffDiffive() { OnDiffToX(4); } ////////////////////////////////////////////////////////////////////// // OnDiffToX void CWedView::OnDiffToX(int num) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, file; CWedDoc* doc; CMenu *mmm = GetDiffMenu(); mmm->GetMenuString(num, str, MF_BYPOSITION); CWedApp *app = (CWedApp*)AfxGetApp(); POSITION Pos = app->pDocTemplate->GetFirstDocPosition(); for(;;) { if(!Pos) break; doc = (CWedDoc*)app->pDocTemplate->GetNextDoc(Pos); ASSERT_VALID(doc); file = doc->GetPathName(); if(file == str) break; } ASSERT_VALID(doc); //P2N("diff to X: %d %s -- %s\r\n", num, str, file); POSITION pos = doc->GetFirstViewPosition(); CView *cv = doc->GetNextView(pos); ASSERT_VALID(cv); //diffing = TRUE; Busy(TRUE); dodiff(this, (CWedView*)cv); Busy(FALSE); // Make them display it diff = 1; // Color to diff specs pDoc->SetTitle( pDoc->GetPathName() + " Diff Source "); other = (CWedView*)cv; doc->SetTitle( doc->GetPathName() + " Diff Target "); ((CWedView*)cv)->diff = 2; ((CWedView*)cv)->other = this; pDoc->UpdateAllViews(NULL); doc->UpdateAllViews(NULL); } static CString old; ////////////////////////////////////////////////////////////////////// // SearchFile void CWedView::SearchFile(int replace) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str2, str = pDoc->strlist.GetLine(row); // Stop highlite if(AllowShighlite) { AllowShighlite = 0; pDoc->UpdateAllViews(NULL); } // Find word we are sitting on, or get selected word int wbeg = 0, wend = 0; if(soch != -1) { if(soch < eoch) wbeg = soch, wend = eoch+1; else wbeg = eoch, wend = soch+1; wbeg = min(wbeg, str2scr(str, str.GetLength())); wend = min(wend, str2scr(str, str.GetLength())); } else SelWord(str, col, &wbeg, &wend); //P2N("SelWord: %d %d\r\n", wbeg, wend); // Two int-s have the word if(wbeg != wend) { wbeg = scr2str(str, wbeg); wend = scr2str(str, wend); str2 = str.Mid(wbeg, wend-wbeg); } else { str2 = old; } ///P2N("Got string '%s'\r\n", str2); // Init search dialog CString old = srcdlg.m_combo1; srcdlg.m_combo1 = str2; srcdlg.m_taush = replace; if(srcdlg.m_taush) srcdlg.m_combo2 = str2; else srcdlg.m_combo2 = ""; // Activate it srcdlg.DoModal(); // Escape 'C' style CString esc_str = srcdlg.m_combo1; str_esc(srcdlg.m_combo1, esc_str.GetBuffer(200), srcdlg.m_combo1.GetLength()); esc_str.ReleaseBuffer(-1), srcdlg.m_combo1 = esc_str; old = srcdlg.m_combo1; esc_str = srcdlg.m_combo2; str_esc(srcdlg.m_combo2, esc_str.GetBuffer(200), srcdlg.m_combo2.GetLength()); esc_str.ReleaseBuffer(-1), srcdlg.m_combo2 = esc_str; if( srcdlg.m_esc || (srcdlg.m_combo1 == "" && srcdlg.m_stype != S_FUNCTION) ) { srcdlg.m_esc = FALSE; srcdlg.m_combo1 = old; return; // Cancelled } // Iterate on all documents: int lim = srcdlg.m_files.GetCount(); for(int loop3 = 0; loop3 < lim; loop3++) { CString str3; POSITION pos = srcdlg.m_files.FindIndex(loop3); if(pos) { str3 = srcdlg.m_files.GetAt(pos); CWedDoc* doc = GetDocFromPath(str3); if(doc) { DoSearch(doc, replace); } } } } ////////////////////////////////////////////////////////////////////// // DoSearch void CWedView::DoSearch(CWedDoc* pDoc, int replace) { static int in_search; if(in_search) return; in_search = TRUE; int high = 0, items = 0, loop, lim, start; ASSERT_VALID(pDoc); POSITION pos = pDoc->GetFirstViewPosition(); CWedView* pView = (CWedView*)pDoc->GetNextView(pos); // Scoped search if(pView->soh == -1) { lim = pDoc->strlist.GetCount() ; start = 0; } else { // Make logical highlite int lsoh, leoh; if(soh < eoh) { lsoh = soh; leoh = eoh; } else { leoh = soh; lsoh = eoh; } start = lsoh; lim = leoh+1; // Cancel it, looks nicer soch = eoch = soh = eoh = -1; } pDoc->ssel.ShowWindow(TRUE); pDoc->ssel.m_rep = replace; pDoc->ssel.m_src = srcdlg.m_combo1; pDoc->ssel.connect = (int)pView; pDoc->ssel.slb.ResetContent(); Busy(TRUE); //CWaitCursor cursor; CString str3 = srcdlg.m_combo1; str3.MakeUpper(); // Fill in src window title CString spath = pDoc->GetTitle(); ShortenPath(spath, 30); if(replace) { pDoc->ssel.SetWindowText(spath + " replace '" + srcdlg.m_combo1 + "'" + " with '" + srcdlg.m_combo2 + "'"); } else { pDoc->ssel.SetWindowText(spath + " searching for '" + srcdlg.m_combo1 + "'"); } // Free storage pDoc->ssel.cola.RemoveAll(); pDoc->ssel.linea.RemoveAll(); pDoc->ssel.lineb.RemoveAll(); // Redisplay curson in edit window //CreateCaret(&caret); ShowCaret(); // Pre-expand virtual list pDoc->ssel.lineb.SetAtGrow(lim, TRUE); // Start new search (regex an ucase) init_search = TRUE; // Go get it // -------------------------------------------------------- for(loop = start ; loop < lim; loop++) { if(!(loop % 100)) { CString num; num.Format("Searching at line %d found %d", loop, items); message(num); if(YieldToWinEx()) { AfxMessageBox("Aborted search, partial matches shown"); break; } } // Cancel this loop if user closed dialog if(!pDoc->ssel.m_shown) { //P2N("Closed dialalog while search\r\n"); break; } // Add lines matching criteria: int ccol = 0, found = 0, backwalk = 0; found = pView->SearchType(loop, &ccol, &backwalk); if(found) { pDoc->ssel.cola.SetAtGrow(items, ccol); pDoc->ssel.linea.SetAtGrow(items, loop + backwalk); pDoc->ssel.lineb.SetAtGrow(loop + backwalk, TRUE); CString str = pDoc->strlist.GetLine(loop + backwalk); ExpandTabs(str); pDoc->ssel.slb.AddString(str); if(items > 32000) { AfxMessageBox("Space tight, partial matches shown"); break; } if(loop >= row && !high) high = items; items++; } } Busy(FALSE); // -------------------------------------------------------- if(!items) { pDoc->ssel.slb.AddString("Not found"); } else { // Provide selection in none if(pDoc->ssel.slb.GetCurSel() == -1) { pDoc->ssel.slb.SetCurSel(high-1); pDoc->ssel.slb.SetCurSel(high); } } // Check all int lim2 = pDoc->ssel.slb.GetCount(), loop2; for(loop2 = 0; loop2 < lim2; loop2++) { pDoc->ssel.slb.SetCheck(loop2, 1); } pDoc->ssel.GotoSel(); AllowShighlite = 1; pDoc->UpdateAllViews(NULL); CString num; num.Format("Search found %d items", items); message (num); in_search = FALSE; } ////////////////////////////////////////////////////////////////////// // OnSearchFind void CWedView::OnSearchFind() { SearchFile(); } ////////////////////////////////////////////////////////////////////// // OnSearchReplace void CWedView::OnSearchReplace() { SearchFile(TRUE); } // // Get diff menu // ////////////////////////////////////////////////////////////////////// // GetDiffMenu CMenu *CWedView::GetDiffMenu() { int iPos; CMenu* pViewMenu = NULL; CMenu* pTopMenu = AfxGetMainWnd()->GetMenu(); for (iPos = pTopMenu->GetMenuItemCount()-1; iPos >= 0; iPos--) { CMenu* pMenu = pTopMenu->GetSubMenu(iPos); if (pMenu && pMenu->GetMenuItemID(1) == ID_VIEW_GOTONEXTDIFFERENCE) { //P2N("Found submenu\r\n"); pViewMenu = pMenu; break; } } if(!pViewMenu) return(NULL); //ASSERT(pViewMenu != NULL); CMenu* pfMenu = NULL; for (iPos = pViewMenu->GetMenuItemCount()-1; iPos >= 0; iPos--) { pfMenu = pViewMenu->GetSubMenu(iPos); if(pfMenu) break; } // ASSERT(pfMenu != NULL); return (pfMenu); } ////////////////////////////////////////////////////////////////////// // OnViewStopdiffing void CWedView::OnViewStopdiffing() { CWedDoc *doc; CWedApp *app = (CWedApp*)AfxGetApp(); POSITION Pos = app->pDocTemplate->GetFirstDocPosition(); for(;;) { if(!Pos) break; doc = (CWedDoc*)app->pDocTemplate->GetNextDoc(Pos); ASSERT_VALID(doc); POSITION pos = doc->GetFirstViewPosition(); CView *cv = doc->GetNextView(pos); ASSERT_VALID(cv); ((CWedView*)cv)->other = NULL; ((CWedView*)cv)->diff = 0; doc->UpdateAllViews(NULL); // Set back titles CString str2 = doc->GetTitle(); CString str3 = doc->GetPathName(); if(str3 != str2) { doc->SetTitle(str3); } } } ////////////////////////////////////////////////////////////////////// // OnEditRecordmacro void CWedView::OnEditRecordmacro() { start_record(); } ////////////////////////////////////////////////////////////////////// // start_record void CWedView::start_record() { if(play) { message("Cannot start recording while playing"); return; } if(record) { // Stop modestr = ""; mode(modestr); record = FALSE; if(macros[currmac].GetCount() == 0) { macros[currmac].AddTail(&backmacros[currmac]); message("Ended recording, and restored old macro."); } else { message("Ended recording"); } } else { // Start modestr = "REC"; mode(modestr); // Copy macros to backup backmacros[currmac].RemoveAll(); backmacros[currmac].AddTail(&macros[currmac]); macros[currmac].RemoveAll(); record = TRUE; message("Started recording"); } } ////////////////////////////////////////////////////////////////////// // OnEditPlaymacro void CWedView::OnEditPlaymacro() { // if shift is held, animate PlayMacro(shift); } ////////////////////////////////////////////////////////////////////// // PlayMacro void CWedView::PlayMacro(int animate) { int chh, flag, type, cnt; POSITION pos; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(record) { message("Cannot play back while recording"); return; } if(play) return; play = TRUE; if(macros[currmac].IsEmpty()) { message("Nothing to play back"); goto endd; } mode("PLAY"); YieldToWin(); pos = macros[currmac].GetHeadPosition(); while(TRUE) { if (!pos) break; CString replay = macros[currmac].GetNext(pos); sscanf(replay, "%d %d %d %d", &type, &chh, &cnt, &flag); //P2N("Playing: %d %d %d %d\r\n", // type, chh, cnt, flag); // Mimic keystrokes in order they got here: switch(type) { case R_DOWN: OnKeyDown(chh, cnt, flag); break; case R_CHAR: OnChar(chh, cnt, flag); break; case R_UP: OnKeyUp(chh, cnt, flag); break; case R_SYSDOWN: OnSysKeyDown(chh, cnt, flag); break; case R_SYSCHAR: OnSysChar(chh, cnt, flag); break; case R_SYSUP: OnSysKeyUp(chh, cnt, flag); break; default: //AfxMessageBox("Invalid macro entry"); //P2N("Error on playing: %d %d %d\r\n", chh, cnt, flag); break; } if(animate) { if(type == R_UP || type == R_SYSUP) { // Update the screen after every char pDoc->UpdateAllViews(NULL); // Stop if needed if(YieldToWinEx()) { message("Aborted playback"); break; } } Sleep(30); } else { if(type == R_UP || type == R_SYSUP) { // Stop if needed if(YieldToWinEx()) { message("Aborted playback"); break; } } } } endd: mode(""); play = FALSE; // Update the screen after playing back pDoc->UpdateAllViews(NULL); SyncCaret(); YieldToWin(); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer1 void CWedView::OnSearchSelextholdingBuffer1() { SwitchholdingBuffer(1); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer2 void CWedView::OnSearchSelextholdingBuffer2() { SwitchholdingBuffer(2); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer3 void CWedView::OnSearchSelextholdingBuffer3() { SwitchholdingBuffer(3); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer4 void CWedView::OnSearchSelextholdingBuffer4() { SwitchholdingBuffer(4); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer5 void CWedView::OnSearchSelextholdingBuffer5() { SwitchholdingBuffer(5); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer6 void CWedView::OnSearchSelextholdingBuffer6() { SwitchholdingBuffer(6); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer7 void CWedView::OnSearchSelextholdingBuffer7() { SwitchholdingBuffer(7); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer8 void CWedView::OnSearchSelextholdingBuffer8() { SwitchholdingBuffer(8); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer9 void CWedView::OnSearchSelextholdingBuffer9() { SwitchholdingBuffer(9); } ////////////////////////////////////////////////////////////////////// // OnSearchSelextholdingBuffer10 void CWedView::OnSearchSelextholdingBuffer10() { SwitchholdingBuffer(0); } ////////////////////////////////////////////////////////////////////// // SwitchholdingBuffer void CWedView::SwitchholdingBuffer(int buffnum) { CString num; buffnum = min(9, buffnum); buffnum = max(0, buffnum); currhold = buffnum; num.Format( " H %02d ", currhold); message ("Switched holding buffer"); hold(num); } ////////////////////////////////////////////////////////////////////// // OnMoveNextcharacter void CWedView::OnMoveNextcharacter() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); col++; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMovePreviouschar void CWedView::OnMovePreviouschar() { if(!col) message("At beginning of line"); else col--; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMoveNextline void CWedView::OnMoveNextline() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(row < pDoc->strlist.GetCount()-1) row++; else message("At end of file"); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMovePreviousline void CWedView::OnMovePreviousline() { if(row) row--; else message("At beginning of file"); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMovePagedown void CWedView::OnMovePagedown() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(row >= pDoc->strlist.GetCount()-1) { message("At end of file"); return; } RECT rec; GetClientRect(&rec) ; int height = (rec.bottom - rec.top)/fflf.lfHeight; row += height-3; row = min(row, pDoc->strlist.GetCount()-1); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMovePageup void CWedView::OnMovePageup() { if(!row) { message("At beginning of file"); return; } RECT rec; GetClientRect(&rec) ; int height = (rec.bottom - rec.top)/fflf.lfHeight; row -= height - 3; row = max(row, 0); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // Jump to begin of next word void CWedView::MoveNextword() { OnMoveNextword(); } ////////////////////////////////////////////////////////////////////// // OnMoveNextword void CWedView::OnMoveNextword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int pos; CString str = pDoc->strlist.GetLine(row); int len = str.GetLength(); // Empty string, jump to the next line if(!len) { row++; return; } pos = scr2str(str, col); if(pos >= len) return; // Step to end of current word: while(wdelim.Find(str.GetAt(pos)) == -1) { pos++; if(pos >= len) goto endd1; } // Step to end of current space: while(wdelim.Find(str.GetAt(pos)) != -1) { pos++; if(pos >= len) goto endd1; } endd1: // Jump to the next line if at EOL if(pos >= len && row < pDoc->strlist.GetCount()-1) { row++; col = 0; } else col = str2scr(str, pos); SyncCaret(); } // Jump to begin of prev word ////////////////////////////////////////////////////////////////////// // OnMovePreviouseword void CWedView::OnMovePreviouseword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int pos, ontab; CString str = pDoc->strlist.GetLine(row); int len = str.GetLength(); if(!len) return; TabbedPos(str, col, &pos, &ontab); pos = min(pos, len-1); // Step to beginning of current word: while(wdelim.Find(str.GetAt(pos)) == -1) { if(!pos) goto endd2; pos--; } // Step to beginning of this space: while(wdelim.Find(str.GetAt(pos)) != -1) { if(!pos) goto endd2; pos--; } // Step to beginning of prevous word: while(wdelim.Find(str.GetAt(pos)) == -1) { if(!pos) goto endd2; pos--; } // Step to first char of this word: while(wdelim.Find(str.GetAt(pos)) != -1) { if(pos >= len) goto endd2; pos++; } endd2: UnTabbedPos(str, pos, &col, &ontab); //col = pos; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMoveEndofword void CWedView::OnMoveEndofword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); int pos, len = str.GetLength(); if(!len) goto endd3; pos = scr2str(str, col); pos = min(pos, str.GetLength()-1); pos = max(pos,0); // Step to end of current space: while(wdelim.Find(str.GetAt(pos)) != -1) { pos++; if(pos >= len) goto endd3; } // Step to end of current word: while(wdelim.Find(str.GetAt(pos)) == -1) { pos++; if(pos >= len) { pos--; break; } } // Step back to last char while(wdelim.Find(str.GetAt(pos)) != -1) { if(!pos) goto endd3; pos--; } endd3: col = str2scr(str, pos); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMoveBeginningofword void CWedView::OnMoveBeginningofword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); int pos, len = str.GetLength(); pos = scr2str(str, col); pos = min(pos, str.GetLength()-1); pos = max(pos,0); // Step to begin of current space: while(wdelim.Find(str.GetAt(pos)) != -1) { if(!pos) goto endd4; pos--; } // Step to begin of current word: while(wdelim.Find(str.GetAt(pos)) == -1) { if(!pos) goto endd4; pos--; } // Step forward to first char: while(wdelim.Find(str.GetAt(pos)) != -1) { pos++; if(pos >= len) goto endd4; } endd4: col = str2scr(str, pos); SyncCaret(); } // Move to next paragraph ////////////////////////////////////////////////////////////////////// // OnMoveNextparagraph void CWedView::OnMoveNextparagraph() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int lcol = 0, lrow = row; CString str; while(lrow <= pDoc->strlist.GetCount()-1) { lrow++; str = pDoc->strlist.GetLine(lrow); // Break on paragraph boundary: if(str == "" ) { col = 0; message("Moved to end of Paragraph"); break; } // Break on block boundary: lcol = str.Find('}'); if(lcol != -1) { col = lcol; message("Moved to end of Block"); break; } } row = lrow; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMovePreviouseparagraph void CWedView::OnMovePreviouseparagraph() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int lcol = col, lrow = row; CString str; while(lrow) { lrow--; str = pDoc->strlist.GetLine(lrow); // Break on paragraph boundary: if(str == "" ) { col = 0; message("Moved to beginning of Paragraph"); break; } // Break on block boundary: lcol = str.Find('{'); if(lcol != -1) { // Here we move after the '{' to let the work begin col = lcol+1; message("Moved to beginning of Block"); break; } } row = lrow; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMoveEndofline void CWedView::OnMoveEndofline() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); col = str2scr(str, str.GetLength()); SyncCaret(); message("Moved to the end of Line"); } ////////////////////////////////////////////////////////////////////// // OnMoveBeginningofline void CWedView::OnMoveBeginningofline() { col = 0; SyncCaret(); message("Moved to beginning of Line"); } ////////////////////////////////////////////////////////////////////// // OnMoveBeginningofpage void CWedView::OnMoveBeginningofpage() { message("Moved to beginning of Page"); col = 0; row = srow; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnMoveBeginningoffile void CWedView::OnMoveBeginningoffile() { col = 0; row = 0; SyncCaret(); message("Moved to beginning of File"); } ////////////////////////////////////////////////////////////////////// // OnMoveEndofpage void CWedView::OnMoveEndofpage() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; RECT rec; GetClientRect(&rec) ; int height = (rec.bottom - rec.top)/fflf.lfHeight; row = srow + (height - 1); OnMoveEndofline(); SyncCaret(); message("Moved to end of Page"); } ////////////////////////////////////////////////////////////////////// // OnMoveEndoffile void CWedView::OnMoveEndoffile() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; row = pDoc->strlist.GetCount()-1; OnMoveEndofline(); SyncCaret(); message("Moved to end of File"); } ////////////////////////////////////////////////////////////////////// // OnEditUppercaseword void CWedView::OnEditUppercaseword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); if(!str.GetLength()) goto endd5; SaveUndo(this, UNDO_MOD, row, col, str); int begin, end, lpos; SelWord(str, col, &begin, &end); begin = scr2str(str, begin); end = scr2str(str, end); for(lpos = begin; lpos < end; lpos++) str.SetAt(lpos, (char)toupper(str.GetAt(lpos))); endd5: pDoc->strlist.SetLine(row, str); message("Uppercase word"); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditLowercaseword void CWedView::OnEditLowercaseword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); if(!str.GetLength()) goto endd6; SaveUndo(this, UNDO_MOD, row, col, str); int begin, end, lpos; SelWord(str, col, &begin, &end); begin = scr2str(str, begin); end = scr2str(str, end); for(lpos = begin; lpos < end; lpos++) str.SetAt(lpos, (char)tolower(str.GetAt(lpos))); endd6: pDoc->strlist.SetLine(row, str); message("Lowercase word"); pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditCapitalizeword void CWedView::OnEditCapitalizeword() { int begin, end, lpos; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); int len = str.GetLength(); if(!len) { message ("Empty line"); return; } SelWord(str, col, &begin, &end); // Convert back to string coordinates begin = scr2str(str, begin); end = scr2str(str, end); if(begin == end) { message ("Not on word"); return; } if(begin >= len) { message ("After EOL"); return; } SaveUndo(this, UNDO_MOD, row, col, str); // Lowercase all for(lpos = begin; lpos < end; lpos++) { str.SetAt(lpos, (char)tolower(str.GetAt(lpos))); } // Uppercase first str.SetAt(begin, (char)toupper(str.GetAt(begin))); pDoc->strlist.SetLine(row, str); pDoc->SetModifiedFlag(); message("Capitalize word"); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditCuttoholding void CWedView::OnEditCuttoholding() { CopyToHold(this, TRUE); } ////////////////////////////////////////////////////////////////////// // OnEditCopytoholding void CWedView::OnEditCopytoholding() { CopyToHold(this, FALSE); } ////////////////////////////////////////////////////////////////////// // OnEditPasteholding void CWedView::OnEditPasteholding() { PasteHold(this); } ////////////////////////////////////////////////////////////////////// // OnEditStartselectaltl void CWedView::OnEditStartselectaltl() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(soh == -1) { // Set markers soh = eoh = row; message ("Mark set"); } else { // Reset markers soh = eoh = -1; soch = eoch = -1; message ("Marks unset"); } SyncCaret(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnEditStartcolumnselectaltc void CWedView::OnEditStartcolumnselectaltc() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(soh == -1) soh = row; else soh =-1; if(soch == -1) { // Set soch = col; eoch = col; message ("Column mark set"); } else { // Reset soch = eoch = -1; message ("Column mark unset"); } pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnSelectCancelselect void CWedView::OnSelectCancelselect() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); message ("Stopped highlite"); soh = eoh = -1; soch = eoch = -1; pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnSelectSelectall void CWedView::OnSelectSelectall() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); soh = 0; eoh = row = pDoc->strlist.GetCount()-1; pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // InsertClip void CWedView::InsertClip() { } ////////////////////////////////////////////////////////////////////// // OnSearchCancelfind void CWedView::OnSearchCancelfind() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //pDoc->search = ""; srcdlg.m_combo1 = ""; pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnMoveGotoline void CWedView::OnMoveGotoline() { static old_goto; CGotoLine gt; CString num; num.Format("%d", old_goto); gt.m_str = num; gt.m_prompt = "Line to Go To"; gt.caption = "Goto Line"; gt.DoModal(); row = atoi(gt.m_str); old_goto = row; SyncCaret(); } //Add incremented number to current position static int serial = 0; static int linewidth = 80; ////////////////////////////////////////////////////////////////////// // OnInsertIncrementednumber void CWedView::OnInsertIncrementednumber() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString lstr, rstr, num; CString str = pDoc->strlist.GetLine(row); // Generate number: num.Format("%02d", serial); // Split line: lstr = str.Left(col); rstr = str.Right(str.GetLength() - col); SaveUndo(this, UNDO_MOD, row, col, str); // Output: pDoc->strlist.SetLine(row, lstr + num + rstr); if(shift) col += num.GetLength(); else row++; serial++; pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnInsertSetincremnetstartvalue void CWedView::OnInsertSetincremnetstartvalue() { CGotoLine gt; gt.m_str.Format("%d", serial); gt.m_prompt = "Set starting number for increment"; gt.caption = "Increment Start Value"; if(gt.DoModal() == IDOK) serial = atoi(gt.m_str); } ////////////////////////////////////////////////////////////////////// // OnMoveGotocolumn void CWedView::OnMoveGotocolumn() { static old_num; CString num; num.Format("%d", old_num); CGotoLine gt; gt.m_str = num; gt.m_prompt = "Column to Go To"; gt.caption = "Goto Column"; // Open it gt.DoModal(); col = atoi(gt.m_str); old = col; SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnSearchFindnext void CWedView::OnSearchFindnext() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, str2; int lim, cnt = row+1, ccol; CStringEx str3; if( srcdlg.m_esc || (srcdlg.m_combo1 == "" && srcdlg.m_stype != S_FUNCTION) ) { message("No active search string"); return; // Cancelled } lim = pDoc->strlist.GetCount() - 1; // See if current line has more if(srcdlg.m_stype != S_FUNCTION) { str3 = pDoc->strlist.GetLine(row); int col2 = scr2str(str3, col); if((ccol = str3.FindNoCase(srcdlg.m_combo1, col2+1)) != -1) { col = str2scr(str3, ccol); SyncCaret(); message("Found next on same line"); return; } } else { // Skip to current body ... int ccol = 0, backwalk = 0; cnt = row; while(TRUE) { int found; if(cnt >= lim) { message("Reached last searched item (func)"); break; } // Find lines matching criteria: str = pDoc->strlist.GetLine(cnt); int ccol = 0, backwalk = 0; found = SearchType(cnt, &ccol, &backwalk); if(found) { P2N("Init found at %d back: %d cnt: %d\r\n", row, backwalk, cnt); // Was on a match, go next if(cnt + backwalk == row) { cnt -= backwalk; while(TRUE) { if(cnt >= lim) { message("Reached last searched item (function search)"); break; } str = pDoc->strlist.GetLine(cnt); cnt++; if(str == "{") break; } } cnt--; break; } cnt++; } } Busy(TRUE); // Scan it while(TRUE) { int found; if(cnt >= lim) { message("Reached last searched item"); break; } if(!(cnt%100)) { CString num; num.Format("Searching at %d ", cnt); message(num); } str = pDoc->strlist.GetLine(cnt); // Find lines matching criteria: int ccol = 0, backwalk = 0; found = SearchType(cnt, &ccol, &backwalk); if(found) { row = cnt + backwalk; if(backwalk) str = pDoc->strlist.GetLine(cnt); col = str2scr(str, ccol); //P2N("Found at %d -- %d\r\n", cnt, ccol); SyncCaret(1); pDoc->UpdateAllViews(NULL); message("Found next"); break; } cnt++; } Busy(FALSE); } ////////////////////////////////////////////////////////////////////// // OnSearchFindprevious void CWedView::OnSearchFindprevious() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int cnt = max(0, row-1); CStringEx str, str2, str3; int ccol; if( srcdlg.m_esc || (srcdlg.m_combo1 == "" && srcdlg.m_stype != S_FUNCTION) ) { message("No active search string"); return; // Cancelled } str2 = srcdlg.m_combo1; // pDoc->search; // See if current line has more if(srcdlg.m_stype != S_FUNCTION) { if(col) { str3 = pDoc->strlist.GetLine(row); int col2 = scr2str(str3, col); if((ccol = str3.ReverseFindNoCase(str2, col2-1)) != -1) { col = str2scr(str3, ccol); SyncCaret(); message("Found previous on same line"); return; } } } Busy(TRUE); while(TRUE) { if(cnt < 0) { message("Reached first searched item"); break; } if(!(cnt%100)) { CString num; num.Format("Searching at %d ", cnt); message(num); } //str = pDoc->strlist.GetLine(cnt); // Find lines matching criteria: int ccol = 0, backwalk = 0; int found = SearchType(cnt, &ccol, &backwalk); if(found) { row = cnt + backwalk; str = pDoc->strlist.GetLine(cnt); col = str2scr(str, ccol); //P2N("Found at %d -- %d\r\n", cnt, ccol); pDoc->UpdateAllViews(NULL); SyncCaret(1); message("Found previous"); break; } cnt--; } Busy(FALSE); } ////////////////////////////////////////////////////////////////////// // Select word in current line, return coordinates void CWedView::OnSelectSelectword() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); int wbegin, wend; SelWord(str, col, &wbegin, &wend); if(wbegin < wend) { //P2N("Select word: %s", str.Mid(wbegin, wend)); soch = wbegin; col = eoch = wend -1; soh = row; } message ("Selected word"); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnSelectSelectparagraph void CWedView::OnSelectSelectparagraph() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int lrow = row, urow = row; int max = pDoc->strlist.GetCount(); message("Selected paragraph"); CString str; while(TRUE) { if(!lrow) break; str = pDoc->strlist.GetLine(lrow); if(str == "") break; lrow--; } soh = lrow; while(TRUE) { if(urow >= max) break; str = pDoc->strlist.GetLine(urow); if(str == "") break; urow++; } row = eoh = urow; col = 0; pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnViewFileproperties void CWedView::OnViewFileproperties() { FileInfo fi; fi.v1 = this; fi.DoModal(); } ////////////////////////////////////////////////////////////////////// // OnInsertUser void CWedView::OnInsertUser() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); SaveUndo(this, UNDO_ADD, row, col, str); str = "Peter Glen"; pDoc->strlist.InsertLine(row, str); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditUppercaseselection void CWedView::OnEditUppercaseselection() { Caseselection(TRUE); } ////////////////////////////////////////////////////////////////////// // OnEditLowercaseselection void CWedView::OnEditLowercaseselection() { Caseselection(FALSE); } // Change the case of selection ////////////////////////////////////////////////////////////////////// // Caseselection void CWedView::Caseselection(int updown) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; // Make logical highlite int lsoh, leoh; if(soh <= eoh) { lsoh = soh; leoh = eoh; } else { leoh = soh; lsoh = eoh; } if(soh == -1) { str = pDoc->strlist.GetLine(row); SaveUndo(this, UNDO_MOD, row, col, str); if(updown) str.MakeUpper(); else str.MakeLower(); pDoc->strlist.SetLine(row, str); } else { int loop2; for (loop2 = lsoh; loop2 <= leoh; loop2++) { if(!(loop2 % 100)) { CString num; num.Format( "Copy line %d", loop2); message(num); } str = pDoc->strlist.GetLine(loop2); SaveUndo(this, UNDO_MOD, loop2, col, str); if(updown) str.MakeUpper(); else str.MakeLower(); pDoc->strlist.SetLine(loop2, str); } } if(updown) message("Uppercased selection"); else message("Lowercased selection"); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeRfcstandarddate void CWedView::OnInsertDatetimeRfcstandarddate() { InsertDate("%a %b %d %H:%M:%S %Y %z "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeMmddyyhhmmss void CWedView::OnInsertDatetimeMmddyyhhmmss() { InsertDate("%m/%d/%y %H:%M:%S "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeDdmmyyhhmmss void CWedView::OnInsertDatetimeDdmmyyhhmmss() { InsertDate("%d-%m-%y %H:%M:%S "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeTimehhmmss void CWedView::OnInsertDatetimeTimehhmmss() { InsertDate("%c "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeWeekday void CWedView::OnInsertDatetimeWeekday() { InsertDate("%A "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeMonthname void CWedView::OnInsertDatetimeMonthname() { InsertDate("%B "); } ////////////////////////////////////////////////////////////////////// // OnInsertDatetimeDateformattedaslocale void CWedView::OnInsertDatetimeDateformattedaslocale() { InsertDate("%c "); } ////////////////////////////////////////////////////////////////////// // InsertDate void CWedView::InsertDate(char *format) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, lstr, rstr, nstr, dstr; str = pDoc->strlist.GetLine(row); CTime tt = CTime::GetCurrentTime(); lstr = str.Left(col); rstr = str.Right(str.GetLength() - col); dstr = tt.Format(format); SaveUndo(this, UNDO_MOD, row, col, str); nstr = lstr + dstr + rstr; pDoc->strlist.SetLine(row, nstr); col += nstr.GetLength() - str.GetLength(); pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnInsertPagefeedmark void CWedView::OnInsertPagefeedmark() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row, (CString)"\xc"); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnInsertByte void CWedView::OnInsertByte() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); static unsigned char old; unsigned char ins; CString num; CGotoLine gt; num.Format("%u", old); gt.m_str = num; gt.m_prompt = "Inser BYTE char"; gt.caption = "Enter decimal charater number"; gt.DoModal(); if(!gt.m_esc) { SaveUndo(this, UNDO_MOD, row, col, str); CString lstr, rstr, nstr, dstr; lstr = str.Left(col); rstr = str.Right(str.GetLength() - col); ins = atoi(gt.m_str) % 255; old = ins; nstr = lstr + (char)ins + rstr; pDoc->strlist.SetLine(row, nstr); col++; pDoc->UpdateAllViews(NULL); } } ////////////////////////////////////////////////////////////////////// // OnInsertFunction void CWedView::OnInsertFunction() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad; SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + ""); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("// function%d ", serial); pDoc->strlist.InsertLine(row++, str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad+"//"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("int function%d (int arg1, int arg2)", serial++); pDoc->strlist.InsertLine(row++, pad+str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "{"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "}"); // Position cursor to a good place row -= 2; col = col + 4; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnInsertForloop void CWedView::OnInsertForloop() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad(' ', col); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("for (var%d = 0; var%d < var%d; var%d++)", serial, serial, serial+1, serial); serial+=2; pDoc->strlist.InsertLine(row++, pad+str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " {"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + ""); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " }"); // Position cursor to a good place row -= 2; col = col + 4; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnInsertIfcondition void CWedView::OnInsertIfcondition() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad(' ', col); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("if (var%d < var%d)", serial, serial+1); serial+=2; pDoc->strlist.InsertLine(row++, pad + str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " {"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + ""); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " }"); // Position cursor to a good place row -= 2; col = col + 4; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnSettingsSetupwed void CWedView::OnSettingsSetupwed() { CPropertySheet ps("Wed Setup"); Page1 p1; Page2 p2; ps.m_psh.dwFlags |= PSH_NOAPPLYNOW; // ps.m_psh.dwFlags &= PSH_HASHELP; ps.AddPage(&p1); ps.AddPage(&p2); ps.DoModal(); } ////////////////////////////////////////////////////////////////////// // OnEditLoadmacro void CWedView::OnEditLoadmacro() { CFileDialogST cdf(TRUE); CString droot, dresult; droot.Format("%smacros\\", dataroot); cdf.m_ofn.lpstrInitialDir = droot; cdf.m_ofn.lpstrFilter = Mfilter; cdf.m_ofn.lpstrFile = "*.mac"; cdf.m_ofn.nFilterIndex = 1; if(cdf.DoModal() == IDCANCEL) return; dresult = cdf.GetPathName(); CFile cf; if( cf.Open( dresult, CFile::modeRead )) { //cstringlist macros[currmac].RemoveAll(); CArchive ar( &cf, CArchive::load); macros[currmac].Serialize(ar); message("Loaded Macro"); } } ////////////////////////////////////////////////////////////////////// // OnEditSavemacro void CWedView::OnEditSavemacro() { CFileDialogST cdf(FALSE); CString droot, dresult, dfile, dext; droot.Format("%smacros\\", dataroot); //cdf.m_ofn.lStructSize = sizeof(OPENFILENAME); cdf.m_ofn.lpstrInitialDir = droot; cdf.m_ofn.lpstrFilter = Mfilter; cdf.m_ofn.lpstrFile = "*.mac"; cdf.m_ofn.nFilterIndex = 1; if(cdf.DoModal() == IDCANCEL) return; dresult = cdf.GetPathName(); dfile = cdf.GetFileName(); dext = cdf.GetFileExt(); // append ".mac" if empty if(dext == "") dresult += ".mac"; //P2N("Macro file1: %s\r\n", dresult); CFile cf; if( cf.Open( dresult, CFile::modeCreate | CFile::modeWrite )) { CArchive ar( &cf, CArchive::store); macros[currmac].Serialize(ar); message("Saved Macro"); } } ////////////////////////////////////////////////////////////////////// // OnActivateView static int firstact = 0; void CWedView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView) { //P2N("CWedView::OnActivateView %d\r\n", bActivate); if(comline & !firstact) AfxGetMainWnd()->PostMessage(WM_COMMAND, ID_WINDOW_TILE_VERT, 0); firstact = TRUE; CView::OnActivateView(bActivate, pActivateView, pDeactiveView); if(bActivate) { SetTimer(2, 100, NULL); } return; } ////////////////////////////////////////////////////////////////////// // OnViewCococodecolector void CWedView::OnViewCococodecolector() { if(!IsWindow(cocowin.m_hWnd)) cocowin.Create(IDD_DIALOG9); cocowin.CenterWindow(); cocowin.ShowWindow(SW_SHOW); } ////////////////////////////////////////////////////////////////////// // OnCompileMake void CWedView::OnCompileMake() { SaveAllDocs(); // Start compiling ... message("Sending build command ..."); m_ole.SendBuild(); } ////////////////////////////////////////////////////////////////////// // OnCompileExecutedevstudioproject void CWedView::OnCompileExecutedevstudioproject() { static in_compile; if(in_compile) return; in_compile = TRUE; SaveAllDocs(); message("Sending build command ..."); m_ole.SendBuild(); // Execute recent build... message("Sending execute command ..."); m_ole.SendExec(); in_compile = FALSE; } ////////////////////////////////////////////////////////////////////// // OnFileSaveall void CWedView::OnFileSaveall() { SaveAllDocs(); } ////////////////////////////////////////////////////////////////////// // OnViewViewmacroheads void CWedView::OnViewViewmacroheads() { CString ee = "empty"; HoldHead hh; hh.m_edit1 = macros[0].IsEmpty() ? ee: macros[0].GetHead() ; hh.m_edit2 = macros[1].IsEmpty() ? ee: macros[1].GetHead() ; hh.m_edit3 = macros[2].IsEmpty() ? ee: macros[2].GetHead() ; hh.m_edit4 = macros[3].IsEmpty() ? ee: macros[3].GetHead() ; hh.m_edit5 = macros[4].IsEmpty() ? ee: macros[4].GetHead() ; hh.m_edit6 = macros[5].IsEmpty() ? ee: macros[5].GetHead() ; hh.m_edit7 = macros[6].IsEmpty() ? ee: macros[6].GetHead() ; hh.m_edit8 = macros[7].IsEmpty() ? ee: macros[7].GetHead() ; hh.m_edit9 = macros[8].IsEmpty() ? ee: macros[8].GetHead() ; hh.m_edit10 = macros[9].IsEmpty() ? ee: macros[9].GetHead() ; hh.m_edit11 = "Head of macros"; hh.DoModal(); } ////////////////////////////////////////////////////////////////////// // OnSelectMarkblock void CWedView::OnSelectMarkblock() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int lrow = row, urow = row; int max = pDoc->strlist.GetCount(); message("Selected block"); CString str; int depth = 0; while(TRUE) { if(!lrow) break; str = pDoc->strlist.GetLine(lrow); if(str.Find('{') != -1) depth--; if(depth < 0) break; if(str.Find('}') != -1) depth++; lrow--; } soh = lrow; depth = 0; while(TRUE) { if(urow >= max) break; urow++; str = pDoc->strlist.GetLine(urow); if(str.Find('}') != -1) depth--; if(depth < 0) break; if(str.Find('{') != -1) depth++; } row = eoh = urow; col = 0; CString num; num.Format("Selected %d lines", eoh - soh); message(num); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // SwitchToNext void CWedView::SwitchToNext() { // Next buffer int got = 0; CWedDoc* pDoc = NULL; CMultiDocTemplate* pDocTemplate = ((CWedApp*)AfxGetApp())->pDocTemplate; POSITION Pos = pDocTemplate->GetFirstDocPosition(); for(;;) { if(!Pos) break; CWedDoc* doc = (CWedDoc*)pDocTemplate->GetNextDoc(Pos); if(!doc) continue; ASSERT_VALID(doc); POSITION pos2 = doc->GetFirstViewPosition(); CWedView *cv = (CWedView*)doc->GetNextView(pos2); if(got == 1) { pMainFrame->MDIActivate (cv->GetParent()); got = 2; break; } if(cv == this) { got = 1; } } if(got != 2) { // wrapped around buffers, switch: POSITION Pos = pDocTemplate->GetFirstDocPosition(); CWedDoc* doc = (CWedDoc*)pDocTemplate->GetNextDoc(Pos); ASSERT_VALID(doc); POSITION pos2 = doc->GetFirstViewPosition(); CWedView *cv = (CWedView*)doc->GetNextView(pos2); ASSERT_VALID(cv); pMainFrame->MDIActivate (cv->GetParent()); } message ("Switched to next buffer"); } ////////////////////////////////////////////////////////////////////// // OnWindowsNextbuffer void CWedView::OnWindowsNextbuffer() { SwitchToNext(); } ////////////////////////////////////////////////////////////////////// // Show busy cursor void CWedView::Busy(int on) { if(on) { m_busy = TRUE; SetCursor(WaitCursor); } else { m_busy = FALSE; SetCursor(NormalCursor); } } ////////////////////////////////////////////////////////////////////// // OnViewFullscreen void CWedView::OnViewFullscreen() { if(GetParent() != parent) UnFullscreen(); else ReFullscreen(); } ////////////////////////////////////////////////////////////////////// // ReFullscreen void CWedView::ReFullscreen() { // Make the top window our owner SetParent(GetDesktopWindow()); RECT rec; SystemParametersInfo(SPI_GETWORKAREA, 0 , &rec, 0); int mmm = GetSystemMetrics(SM_CYMENUSIZE); int xxx = rec.right - rec.left; int yyy = (rec.bottom - rec.top) - mmm; MoveWindow (rec.left, rec.top, xxx, yyy); // So users will know SetWindowText("Wed Full Screen"); CreateCaret(&caret); ShowCaret(); message("Full screen view (Control-F or ESC for normal view)"); } ////////////////////////////////////////////////////////////////////// // UnFullscreen void CWedView::UnFullscreen() { // See if it is full screenized if(GetParent() == parent) return; // no BOOL maxi; CMDIFrameWnd *pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd; // Make the original owner our owner SetParent(parent); // Send resize to update it properly pFrame->MDIGetActive(&maxi); if(maxi) { // End with maxi pFrame->MDIRestore (GetParent()); pFrame->MDIMaximize(GetParent()); } else { // End with medi pFrame->MDIMaximize(GetParent()); pFrame->MDIRestore (GetParent()); } // System resource, re get it CreateCaret(&caret); ShowCaret(); SyncCaret(); YieldToWin(); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->UpdateAllViews(NULL); message("Exited Full screen view"); } ////////////////////////////////////////////////////////////////////// // OnFileMultiopen void CWedView::OnFileMultiopen() { P2N("CWedView::OnFileMultiopen\r\n"); OpenSource(srcdir); } ////////////////////////////////////////////////////////////////////// // OnSettingsTogglescrollbars void CWedView::OnSettingsTogglescrollbars() { static on = 1; if(on) ShowScrollBar(SB_BOTH, 0), on = !on; else ShowScrollBar(SB_BOTH, 1), on = !on; } // Reverse colors ////////////////////////////////////////////////////////////////////// // OnSettingsReverseit void CWedView::OnSettingsReverseit() { int tmp = fgcol; fgcol = bgcol; bgcol = tmp; // Tell all documents about the change POSITION Pos = ((CWedApp*)AfxGetApp())->pDocTemplate-> GetFirstDocPosition(); for(;;) { if(!Pos) break; CWedDoc* doc = (CWedDoc*) ((CWedApp*)AfxGetApp())->pDocTemplate-> GetNextDoc(Pos); doc->UpdateAllViews(NULL); } } ////////////////////////////////////////////////////////////////////// // OnMacroAnimatemacro void CWedView::OnMacroAnimatemacro() { PlayMacro(TRUE); } ////////////////////////////////////////////////////////////////////// // OnEditCleannonascii // Clean out char < 32 void CWedView::OnEditCleannonascii() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int changed = FALSE; CString str, str2; int lim = pDoc->strlist.GetCount(); // Iterate every line for(int loop = 0; loop < lim; loop++) { str = pDoc->strlist.GetLine(loop); int lim2 = str.GetLength(); str2 = ""; for(int loop2 = 0; loop2 < lim2; loop2++) { char cc = str.GetAt(loop2); if(cc >= 32) str2 += cc; else changed = TRUE; } pDoc->strlist.SetLine(loop, str2); } // Tell the doc if changed if(changed) pDoc->SetModifiedFlag(TRUE); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditWraptowindow -- Wrap to col 80 void CWedView::OnEditWraptowindow() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int changed = FALSE; int mark = FALSE; CString str, str2, str3; int lim = pDoc->strlist.GetCount(); // Iterate every line for(int loop = 0; loop < lim; loop++) { int count = 0; //P2N("loop = %d lim=%d\r\n", loop, lim); str = pDoc->strlist.GetLine(loop); int lim2 = str.GetLength(); if(lim2 > linewidth) { changed = TRUE; // One time only mark for undo block //if(!mark) { SaveUndo(this, UNDO_NOOP, row, col, ""); mark = TRUE; } // Tempoarily kill this line SaveUndo(this, UNDO_DEL | UNDO_BLOCK, loop, col, str); pDoc->strlist.RemoveLine(loop); lim--; int firstpass = 0; // Rebuild line while(TRUE) { char cc; int len = str.GetLength(); if(len < linewidth) { // Save remainder if any if(len) { SaveUndo(this, UNDO_ADD | UNDO_BLOCK, loop, col, ""); pDoc->strlist.InsertLine(loop++, str); lim++; // added line, more to iterate } break; } // Find space backwards int cutpoint = min(linewidth, len-1); while(TRUE) { if(!cutpoint) break; cc = str.GetAt(cutpoint); if (cc == ' ' || cc == '\t') break; cutpoint--; } // No safe cutpoint found, force cut at 80 if(!cutpoint) cutpoint = linewidth; str2 = str.Left(cutpoint); // Sitting on space, do not carry to next line if(cc == ' ' || cc == '\t') cutpoint++; str3 = str.Right(str.GetLength() - cutpoint); //P2N("str ====== %s\r\n", str3); //P2N("str2 ====== %s\r\n", str2); str = str3; SaveUndo(this, UNDO_ADD | UNDO_BLOCK, loop, col, ""); pDoc->strlist.InsertLine(loop, str2); loop++; lim++; // added line, more to iterate } loop--; } } // Tell the doc if changed if(changed) pDoc->SetModifiedFlag(TRUE); // Show it to user pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // OnEditWeedemptylines // Weed empty void CWedView::OnEditWeedemptylines() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int changed = FALSE, empty = 0; int lim = pDoc->strlist.GetCount(); SaveUndo(this, UNDO_NOP, row, col, ""); // Iterate every line for(int loop = lim; loop; loop--) { CString str = pDoc->strlist.GetLine(loop); int count = 0; if(!str.GetLength()) empty++; else empty = 0; if(empty > 3) { changed = TRUE; SaveUndo(this, UNDO_DEL | UNDO_BLOCK, loop, col, str); pDoc->strlist.RemoveLine(loop); } } // Tell the doc if changed if(changed) pDoc->SetModifiedFlag(TRUE); pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////// // Escape key pressed void CWedView::Esc() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int want = FALSE; // Cancel record if(record) start_record(); // Cancel search selection: if(AllowShighlite) { AllowShighlite = 0; want = TRUE; } // Cancel highlite selection: if(soh != -1) { want = TRUE; soh = eoh = soch = eoch = -1; record = FALSE; modestr = ""; mode(modestr); } if(want) { message ("Cancelled highlite from selections, searches and recording"); pDoc->UpdateAllViews(NULL); } else { // If did not have to cancel, then restore window UnFullscreen(); } } ////////////////////////////////////////////////////////////////////// // Del void CWedView::Del() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString lstr, rstr; if(soh != -1) { // Delete lines DeleteSelection(this); soh = eoh = -1; } else { // Delete one character or pull in prev line CString str = pDoc->strlist.GetLine(row); // If end of line, pull in previous line: int real, ontab; TabbedPos(str, col, &real, &ontab); if(real >= str.GetLength()) { // Discard this action, stop hitmode if(hitmode) { CancelHit(); return; } // Pull in prev line int old = row; SaveUndo(this, UNDO_NOOP, row, col, ""); SaveUndo(this, UNDO_MOD | UNDO_BLOCK, row, col, str); // Extend line to current pos if we point after the end int diff = real - str.GetLength(); if(diff > 0) { CString spaces(' ', diff); str+=spaces; } // Get next line rstr = pDoc->strlist.GetLine(row+1); SaveUndo(this, UNDO_DEL | UNDO_BLOCK, row+1, col, rstr); // Remove leading spaces from next line rstr.TrimLeft(); // Grab it and set it to current line pDoc->strlist.SetLine(row, str + " " + rstr); // Remove next line: DeleteLine(this, row+1); row = old; } else { // Split line, reassemble: SaveUndo(this, UNDO_MOD, row, col, str); // Sitting on tabbed region, replace tab with spaces if(ontab) { OnTabbed(str, ontab); // Recalc TabbedPos(str, col, &real, &ontab); } lstr = str.Left(real); rstr = str.Right(str.GetLength() - (real+1) ); pDoc->strlist.SetLine(row, lstr+rstr); } } pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // BackSpace void CWedView::BackSpace() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString lstr, rstr; CString str = pDoc->strlist.GetLine(row); if(col) { // Split line, reassemble: str = pDoc->strlist.GetLine(row); int real, ontab; TabbedPos(str, col, &real, &ontab); if(real > str.GetLength()) { if(col) col--; message("Backspace on dead area"); goto endd; } SaveUndo(this, UNDO_MOD, row, col, str); // Sitting on tabbed region, replace tab with spaces if(ontab) { int dummy; OnTabbed(str, ontab); // Recalc TabbedPos(str, col, &real, &dummy); } // Assemble the two parts lstr = str.Left(real-1); rstr = str.Right(str.GetLength() - real); pDoc->strlist.SetLine(row, lstr + rstr); // Adjust cursor position if(str.GetAt(real-1) == '\t') { UnTabbedPos(str, real-1, &col, &ontab); } else col--; endd: // Communicate changes pDoc->UpdateAllViews(NULL); SyncCaret(); pDoc->SetModifiedFlag(); } else { // Wrap to prev line if(backwrap) { if(row) { SaveUndo(this, UNDO_NOOP, row, col, ""); str = pDoc->strlist.GetLine(row); SaveUndo(this, UNDO_DEL | UNDO_BLOCK, row, col, str); DeleteLine(this, row); row--; CString str2 = pDoc->strlist.GetLine(row); SaveUndo(this, UNDO_MOD | UNDO_BLOCK, row, col, str2); pDoc->strlist.SetLine(row, str2 + str); col = str2.GetLength(); // Communicate changes pDoc->UpdateAllViews(NULL); SyncCaret(); pDoc->SetModifiedFlag(); } else { message ("Already at the beginning of file"); } } else { message ("Already at the beginning of line"); } } } ////////////////////////////////////////////////////////////////////// // OnInsertDeleteatcursor void CWedView::OnInsertDeleteatcursor() { Del(); } ////////////////////////////////////////////////////////////////////// // OnInsertDeletebeforecursor void CWedView::OnInsertDeletebeforecursor() { BackSpace(); } ////////////////////////////////////////////////////////////////////// // OnInsertDeleteline void CWedView::OnInsertDeleteline() { DelLine(); } ////////////////////////////////////////////////////////////////////// // DelLine void CWedView::DelLine() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); SaveUndo(this, UNDO_DEL, row, col, str); DeleteLine(this, row); pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); message ("Deleted line"); } ////////////////////////////////////////////////////////////////////// // OnInsertDeletetillendofline void CWedView::OnInsertDeletetillendofline() { KillToTol(); } ////////////////////////////////////////////////////////////////////// // KillToTol void CWedView::KillToTol() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str = pDoc->strlist.GetLine(row); CString lstr; str = pDoc->strlist.GetAt(pDoc->strlist.FindIndex(row)); SaveUndo(this, UNDO_MOD, row, col, str); int pos = scr2str(str, col); lstr = str.Left(pos); pDoc->strlist.SetLine(row, lstr); pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); message("Cleared till end of line"); } ////////////////////////////////////////////////////////////////////// // OnInsertCSwitchcase void CWedView::OnInsertCSwitchcase() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad(' ', col); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format( "switch(var%d)", serial, serial, serial+1, serial); serial+=2; pDoc->strlist.InsertLine(row++, pad+str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " {"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " case CONST1:"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " break;"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + ""); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " default:"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " break;"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + " }"); // Position cursor to a good place row -= 8; col = col + 7; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// // OnInsertCTemplate // Insert C template at cursor void CWedView::OnInsertCTemplate() { DoTemplate("template.cpp"); } ////////////////////////////////////////////////////////////////////// // OnInsertJavaTemplate // Insert Java template at cursor void CWedView::OnInsertJavaTemplate() { DoTemplate("template.java"); } ////////////////////////////////////////////////////////////////////// // DoTemplate // Insert template file at cursor void CWedView::DoTemplate(const char *file) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, num, droot; droot.Format("%stemplate\\%s", dataroot, file); CFile cf; if( cf.Open(droot, CFile::modeRead )) { num.Format("Reading template %s", droot); message(num); CArchive ar( &cf, CArchive::load); SaveUndo(this, UNDO_NOOP, row, col, ""); while(TRUE) { if(!ar.ReadString(str)) break; SaveUndo(this, UNDO_ADD | UNDO_BLOCK, row, col, ""); pDoc->strlist.InsertLine(row++, str); } } else { num.Format("Cannot open template\n%s\nWould you Like to create one ?", droot); if(AfxMessageBox(num, MB_YESNO) == IDYES ) { CFile ff; ff.Open(droot, CFile::modeCreate); ff.Close(); AfxGetApp()->OpenDocumentFile(droot); } } pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } ////////////////////////////////////////////////////////////////////// void CWedView::OnSettingsSearchhighlitecolorfg() { SetColor(&srcc); } ////////////////////////////////////////////////////////////////////// void CWedView::OnSettingsCommenthighlitecolor() { SetColor(&comm); } ////////////////////////////////////////////////////////////////////// void CWedView::OnViewGotonextdifference() { if(!diff) { AfxMessageBox("Not diffing"); return; } CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CWedDoc* pDoc2 = other->GetDocument(); ASSERT_VALID(pDoc2); int found = FALSE; int loop = row; int lim = diffa.GetSize(); // Step out of current diff while(TRUE) { if(loop >= lim) break; if(!diffa.GetAt(loop)) break; loop++; } // Walk until new diff while(TRUE) { if(loop >= lim) break; if(diffa.GetAt(loop)) { // Found found = TRUE; row = loop; pDoc->UpdateAllViews(NULL); SyncCaret(3); // Reflect selection on other document other->row = loop; other->SyncCaret(3); pDoc2->UpdateAllViews(NULL); break; } loop++; } #if 0 // Step on diff on the other buffer found = FALSE; loop = other->row; lim = other->diffa.GetSize(); // Step out of current diff while(TRUE) { if(loop >= lim) break; if(!other->diffa.GetAt(loop)) break; loop++; } // Walk until new diff while(TRUE) { if(loop >= lim) break; if(other->diffa.GetAt(loop)) { // Found found = TRUE; //row = loop; pDoc2->UpdateAllViews(NULL); SyncCaret(3); // Reflect selection on other document other->row = loop; other->SyncCaret(3); pDoc2->UpdateAllViews(NULL); break; } loop++; } #endif if(found) message("Found next diff"); else message("No more differences"); } ////////////////////////////////////////////////////////////////////// void CWedView::OnViewGotopreviousdifference() { if(!diff) { AfxMessageBox("Not diffing"); return; } CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CWedDoc* pDoc2 = other->GetDocument(); ASSERT_VALID(pDoc2); int found = FALSE; int loop = row; int lim = diffa.GetSize(); // Step out of current diff while(TRUE) { if(!loop) break; if(!diffa.GetAt(loop)) break; loop--; } // Walk until new diff while(TRUE) { if(!loop) break; if(diffa.GetAt(loop)) { // Found, step to begin of current diff while(TRUE) { if(!loop) break; if(!diffa.GetAt(loop)) { loop++; break; } loop--; } found = TRUE; row = loop; pDoc->UpdateAllViews(NULL); // Reflect selection on other document other->row = loop; other->SyncCaret(3); pDoc2->UpdateAllViews(NULL); break; } loop--; } if(found) message("Found previous diff"); else message("No more differences"); } void CWedView::OnSettingsDiffaddcolor() { SetColor(&cadd); } void CWedView::OnSettingsDiffchangedcolor() { SetColor(&cchg); } void CWedView::OnSettingsDiffdelcolor() { SetColor(&cdel); } void CWedView::OnViewFilebufers() { ShowBuffers(); } void CWedView::OnMove(int x, int y) { //P2N("Moving CWedView %d %d\r\n", x ,y); CView::OnMove(x, y); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->UpdateAllViews(NULL); SyncCaret(); YieldToWin(); } BOOL CWedView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // it is like a bad kludge, but we need it for the cursor //SyncCaret(); return CView::OnSetCursor(pWnd, nHitTest, message); } void CWedView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); //P2N("Sizing CWedView %d %d\r\n", cx ,cy); } void CWedView::OnEditAppendtoholding() { shift = TRUE; CopyToHold(this, FALSE); shift = FALSE; } void CWedView::OnSearchHiteditmode() { if(hitmode ) { hitmode = FALSE; } else { if(srcdlg.m_combo1 != "") { hitmode = TRUE; message ("Entering hit mode"); } else { message ("No search string for hit mode"); } } if(hitmode) { modestr = "HIT"; AfxGetMainWnd()->SendMessage(WM_MENUSELECT, ID_SEARCH_HITEDITMODE | (MF_CHECKED << 8), 0); } else { modestr = ""; } mode(modestr); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->UpdateAllViews(NULL); SyncCaret(); } // Move cursor to handle hit mode -> TRUE for down void CWedView::HitCusror(int direction) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); int vrow = row; // Handle hit mode if(!hitmode) return; if(direction) { while(TRUE) { // Limit if(vrow >= pDoc->strlist.GetCount()-1) { // Seek back to last valid while(TRUE) { if(!vrow) break; if(pDoc->ssel.lineb.GetAt(vrow)) { message ("At last hit"); row = vrow; break; } vrow--; } break; } if(pDoc->ssel.lineb.GetAt(vrow)) { row = vrow; break; } vrow++; } } else { while(TRUE) { // Limit if(!vrow) { // Seek forward to last valid while(TRUE) { if(vrow >= pDoc->strlist.GetCount()-1) break; if(pDoc->ssel.lineb.GetAt(vrow)) { message ("At first hit"); row = vrow; break; } vrow++; } break; } if(pDoc->ssel.lineb.GetAt(vrow)) { row = vrow; break; } vrow--; } } SyncCaret(); } void CWedView::CancelHit() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(hitmode) { message("Cancelled hit mode"); hitmode = FALSE; pDoc->UpdateAllViews(NULL); SyncCaret(); } } void CWedView::OnMacroSelectrecordholdingBuffer10() { SwitchRec(0); } void CWedView::OnEditSelectrecordbufferBuffer1() { SwitchRec(1); } void CWedView::OnMacroSelectrecordholdingBuffer1() { SwitchRec(2); } void CWedView::OnMacroSelectrecordholdingBuffer3() { SwitchRec(3); } void CWedView::OnMacroSelectrecordholdingBuffer4() { SwitchRec(4); } void CWedView::OnMacroSelectrecordholdingBuffer5() { SwitchRec(5); } void CWedView::OnMacroSelectrecordholdingBuffer6() { SwitchRec(6); } void CWedView::OnMacroSelectrecordholdingBuffer7() { SwitchRec(7); } void CWedView::OnMacroSelectrecordholdingBuffer8() { SwitchRec(8); } void CWedView::OnMacroSelectrecordholdingBuffer9() { SwitchRec(9); } void CWedView::SwitchRec(int newrec) { if(record) { message("Cannot switch buffers while recording"); } else { CString num; currmac = newrec;; num.Format( " M %02d ", currmac); message ("Switched macro buffer"); mac(num); } } ////////////////////////////////////////////////////////////////////// // Do search according to m_stype // const char *str string to search in // int *ccol column where found (-1 in not) // int *back step back this many for line int CWedView::SearchType(int loop, int *ccol, int *back) { int found = 0; CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); static CRegExp re; static CString str3; *back = 0; *ccol = 0; CString str = pDoc->strlist.GetLine(loop); if(init_search) { init_search = FALSE; if(srcdlg.m_stype == S_REGEX) { re.RegComp(srcdlg.m_combo1); } if(srcdlg.m_stype == S_FUNCTION) { } else { str3 = srcdlg.m_combo1; str3.MakeUpper(); } } if(srcdlg.m_stype == S_FUNCTION) { if(str.Left(1) == '{') { *ccol = 0; found = TRUE; // Walk backwards till non empty line while(TRUE) { // Bug in C++ post decrement on pointer (*back)--; // Reached beginning of buffer if((loop - *back) < 0) break; CString str2; str2 = pDoc->strlist.GetLine(loop + *back); //P2N("Backwalk: %s\r\n", str2); if(str2 != "") { char cc = str2[0]; cc = tolower(cc); // Found ascii or _ start if((cc >= 'a' && cc <= 'z') || cc == '_') { break; } } } } } else if(srcdlg.m_stype == S_REGEX) { if((*ccol = re.RegFind(str)) != -1) found = TRUE; } else { CString str4 = str; str4.MakeUpper(); if((*ccol = str4.Find(str3)) != -1) found = TRUE; } return(found); } void CWedView::OnWindowsMaximizecurrent() { Maximizecurrent(); } void CWedView::Maximizecurrent() { CWnd *pw = GetParent(); ASSERT(pw); WINDOWPLACEMENT wndpl; pw->GetWindowPlacement(&wndpl); wndpl.showCmd = SW_SHOWMAXIMIZED; pw->SetWindowPlacement(&wndpl); message("Maximized current window"); } void CWedView::OnDropFiles(HDROP hDropInfo) { CView::OnDropFiles(hDropInfo); } void CWedView::OnInsertBasicForloop() { OnInsertForloop(); } void CWedView::OnInsertBasicIf() { OnInsertIfcondition(); } void CWedView::OnInsertBasicSelectcase() { OnInsertCSwitchcase(); } void CWedView::OnInsertBasicFunction() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad; SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + ""); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("// class class%d ", serial); pDoc->strlist.InsertLine(row++, str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad+"//"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("public class class%d extends Applet", serial++); pDoc->strlist.InsertLine(row++, pad+str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "{"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "}"); // Position cursor to a good place row -= 2; col = col + 4; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } void CWedView::OnInsertJavaPrivatemethod() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, pad(' ', col); SaveUndo(this, UNDO_ADD, row, col, ""); str.Format("int method%d (int arg1, int arg2)", serial++); pDoc->strlist.InsertLine(row++, pad+str); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "{"); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad); SaveUndo(this, UNDO_ADD, row, col, ""); pDoc->strlist.InsertLine(row++, pad + "}"); // Position cursor to a good place row -= 2; col = col + 4; pDoc->SetModifiedFlag(); pDoc->UpdateAllViews(NULL); SyncCaret(); } // Lock keyboard // void CWedView::OnAdvancedLockkeyboard() { if(kblock) { kblock = FALSE; message ("Unocked keyboard"); } else { kblock = TRUE; message ("Locked keyboard"); } } void CWedView::OnUpdateAdvancedLockkeyboard(CCmdUI* pCmdUI) { pCmdUI->SetCheck(kblock); } void CWedView::OnUpdateSearchHiteditmode(CCmdUI* pCmdUI) { pCmdUI->SetCheck(hitmode); } void CWedView::OnUpdateViewViewhex(CCmdUI* pCmdUI) { pCmdUI->SetCheck(hex); } void CWedView::OnSettingsAllowbackspacetowraplines() { backwrap = !backwrap; } void CWedView::OnUpdateSettingsAllowbackspacetowraplines(CCmdUI* pCmdUI) { pCmdUI->SetCheck(backwrap); } void CWedView::OnSettingsSavetabsasspaces() { Tab2Space = !Tab2Space; } void CWedView::OnUpdateSettingsSavetabsasspaces(CCmdUI* pCmdUI) { pCmdUI->SetCheck(Tab2Space); } void CWedView::OnInsertDatetimeBordersafedate() { InsertDate("%d-%b-%Y "); } void CWedView::OnInsertTemplateone() { message ("Loading template one"); DoTemplate("template.1"); } void CWedView::OnInsertTemplatetwo() { message ("Loading template two"); DoTemplate("template.2"); } void CWedView::OnInsertTemplatethree() { message ("Loading template three"); DoTemplate("template.3"); } #define MAX_READ 128 void CWedView::OnAdvancedSpellcheck() { Spellcheck(FALSE); } void CWedView::OnAdvancedCommentadstringspellcheck() { Spellcheck(TRUE); } // void CWedView::Spellcheck(int strings) { CString str, idx; char buffer[MAX_READ]; str = approot; str += "spell.txt"; P2N("Dictionary: %s\r\n", str); message ("Started Spell Check"); if(access(str, 0)) { CString num; num.Format("Cannot open Dictionary: %s", str); AfxMessageBox(num); return; } // Check for index, recreate if needed idx = approot; idx += "spell.idx"; if(access(idx, 0) < 0) { CString num; num.Format("Creating dictionary index ..."); message(num); char old = 0; int found = FALSE; FILE *fp, *fp2; int count = 0, count2 = 0; fp = fopen(str, "rt"); if(!fp) { AfxMessageBox("Cannot open data file\n"); return; } fp2 = fopen(idx, "w+t"); if(!fp2) { AfxMessageBox("Cannot create index file\n"); return; } while(TRUE) { char *readd; long fpos; fpos = ftell(fp); /* prev pos */ readd = fgets(buffer, MAX_READ, fp); count++; // Is ascii? if(tolower(buffer[0]) >= 'a' && tolower(buffer[0]) <= 'z') { if(tolower(buffer[0]) != tolower(old) ) /* new buffer */ { fprintf(fp2, "%d %c\n", fpos, tolower(buffer[0])); P2N("boundary word: %s -- %d ", buffer, fpos); old = buffer[0]; count2++; } } if(feof(fp)) break; if(!readd) break; } fclose(fp); fclose(fp2); P2N("Created %d index entries %d unique\r\n", count, count2); } CString cus = approot; cus += "spell.cus"; if(access(cus, 0) < 0) { FILE *fp3 = fopen(cus, "w+t"); if(!fp3) { AfxMessageBox("Cannot create custom file\n"); return; } fclose(fp3); } Spell(this, str, idx, cus, strings); message ("Done Spell Check"); } ////////////////////////////////////////////////////////////////////// void CWedView::OnMoveNextlongline() { static in_longd; if(in_longd) { return; } in_longd = TRUE; YieldToWin(); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; int lim = pDoc->strlist.GetCount() - 1; int cnt = row + 1; Busy(TRUE); // Scan from current + 1 while(TRUE) { if(cnt >= lim) { message("Reached last long line"); break; } if(!(cnt%100)) { CString num; num.Format("Searching for long lines at %d ", cnt); message(num); } str = pDoc->strlist.GetLine(cnt); // Find lines matching criteria: if(str.GetLength() > 85) { //P2N("Found long line at %d\r\n", cnt); row = cnt; SyncCaret(1); pDoc->UpdateAllViews(NULL); message("Found next long line"); break; } cnt++; } Busy(FALSE); in_longd = FALSE; } ////////////////////////////////////////////////////////////////////// void CWedView::OnMoveMovepreviouslongline() { static in_longd; if(in_longd) return; in_longd = TRUE; YieldToWin(); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; int lim = pDoc->strlist.GetCount() - 1; int cnt = row - 1; Busy(TRUE); // Scan from current - 1 while(TRUE) { if(cnt <= 0) { message("Reached first long line"); break; } if(!(cnt%100)) { CString num; num.Format("Searching for long lines at %d ", cnt); message(num); } str = pDoc->strlist.GetLine(cnt); // Find lines matching criteria: if(str.GetLength() > 85) { //P2N("Found long line at %d\r\n", cnt); row = cnt; SyncCaret(1); pDoc->UpdateAllViews(NULL); message("Found previous long line"); break; } cnt--; } Busy(FALSE); in_longd = FALSE; } ////////////////////////////////////////////////////////////////////// void CWedView::OnSettingsLonglinecolorfg() { SetColor(&clng); } ////////////////////////////////////////////////////////////////////// void CWedView::OnFileMultiopendest() { OpenSource(targdir); } void CWedView::OnSearchBracecount() { static in_brace; if(in_brace) return; in_brace = TRUE; static CString old_brace = "{}"; CGotoLine gt; CString num; int forw = 0, back =0; gt.m_str = old_brace; gt.m_prompt = "Braces to count:"; gt.caption = "Brace Count"; gt.DoModal(); Busy(TRUE); //num.Format("Counting braces -> %s", gt.m_str); //message(num); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str; int lim = pDoc->strlist.GetCount() - 1; int cnt = row - 1; Busy(TRUE); // Scan backwards from current - 1 while(TRUE) { if(cnt <= 0) { break; } if(!(cnt%100)) { num.Format("Searching for braces at %d ", cnt); message(num); } str = pDoc->strlist.GetLine(cnt); // Find braces back += FindNumOfChar(str, gt.m_str, 0); cnt--; } // Scan forward from current + 1 cnt = row+1; while(TRUE) { if(cnt >= lim) { break; } if(!(cnt%100)) { num.Format("Searching for braces at %d ", cnt); message(num); } str = pDoc->strlist.GetLine(cnt); // Find braces forw += FindNumOfChar(str, gt.m_str, 0); cnt++; } // Process current int real, dummy; str = pDoc->strlist.GetLine(row); TabbedPos(str, col, &real, &dummy); int cafter = FindNumOfChar(str, gt.m_str, real); int cbefore = FindNumOfChar(str, gt.m_str, 0) - cafter; back += cbefore; forw += cafter; num.Format("Found %s -> Forward %d Backward: %d ", gt.m_str, forw, back); message(num); Busy(FALSE); old_brace = gt.m_str; in_brace = FALSE; } ////////////////////////////////////////////////////////////////////// // void CWedView::OnHelpRegistration() { Register rr; rr.DoModal(); } ////////////////////////////////////////////////////////////////////// // Clean backup files void CWedView::OnAdvancedCleanoldbackups() { Cleanoldfiles("backup"); } ////////////////////////////////////////////////////////////////////// void CWedView::OnAdvancedCleanoldundofiles() { Cleanoldfiles("data"); } ////////////////////////////////////////////////////////////////////// // Delete files that are older then 30 days void CWedView::Cleanoldfiles(const char *dir) { WIN32_FIND_DATA local_find; CString str, orig, fpath; HANDLE find; unsigned ret_val = 0, firstt = 0, count = 0; str = dataroot; str += dir; str += "\\"; orig = str; str += "*.*"; // Get current time CTime st = CTime::GetCurrentTime(); while (TRUE) /* do it while there is file */ { if(ret_val) break; if (firstt == 0) /* build find first */ { find = FindFirstFile(str, &local_find); if(find == INVALID_HANDLE_VALUE) ret_val = TRUE; } else { ret_val = !FindNextFile(find, &local_find); } if (ret_val) break; /* exit subroutine */ firstt++; /* find next */ if(local_find.cFileName[0] != '.') { CTime ft(local_find.ftLastWriteTime); CTimeSpan diff = st - ft; fpath.Format("%s%s", orig, local_find.cFileName); //P2N("Found file: %s %d\r\n", fpath, diff.GetDays()); // Delete if older then 30 days if(diff.GetDays() >= 30) { message(fpath); count++; _unlink(fpath); } } CString tmp; tmp.Format("%d files cleaned out.", count); message(tmp); } } ////////////////////////////////////////////////////////////////////// // void CWedView::OnHelpHelponkeyword() // Call visual 'C' Help // void CWedView::OnHelpHelponkeyword() { int ret = WinExec("C:\\WINDOWS\\HH.EXE \ C:\\Program Files\\Microsoft Visual Studio\\MSDN98\\98VSa\\1033\\msdnvs6a.col", SW_SHOW ); if(ret < 32) ret = WinExec("C:\\WINNT\\HH.EXE \ C:\\Program Files\\Microsoft Visual Studio\\MSDN98\\98VSa\\1033\\msdnvs6a.col", SW_SHOW ); if(ret < 32) AfxMessageBox("Cannot execute VC6.0 help "); } void CWedView::OnSettingsSettabstop() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //AfxMessageBox("Tabstop"); static old_goto; CGotoLine gt; CString num; num.Format("%d", tabstop); gt.m_str = num; gt.m_prompt = "New tab stop:"; gt.caption = "Set Tab Stop"; gt.DoModal(); tabstop = atoi(gt.m_str); // Contain it at 2 if(tabstop < 2) tabstop = 2; pDoc->UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////// BOOL CWedView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); //P2N("Moving CWedView mousewheel delta: %d point:x=%d point:y=%d\r\n", zDelta, pt.x, pt.y); if(zDelta > 0) { row -= 8; if(row <= 0) { row = 0; message("At beginning of file"); } SyncCaret(); } else { row += 8; if(row >= pDoc->strlist.GetCount()-1) { row = pDoc->strlist.GetCount()-1; message("At end of file"); } SyncCaret(); } return CView::OnMouseWheel(nFlags, zDelta, pt); } void CWedView::OnFileOpen() { P2N("CWedView::OnFileOpen\r\n"); OpenSource(srcdir); } void CWedView::OnFileSaveas2() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString name, ddir, fname; fname = ddir = name = pDoc->GetPathName(); PathToDir(ddir); PathToFname(fname); //P2N("Save as, original name: %s\r\n", ddir); //CFileDialog cdf(FALSE); CFileDialogST cdf(FALSE); char *buff = (char*)malloc(MAXFILENAMES + 1); if(!buff) { AfxMessageBox("Cannot get memory for SaveFileAs"); return; } *buff = '\0'; cdf.m_ofn.lpstrInitialDir = ddir; cdf.m_ofn.lpstrFilter = Ffilter; cdf.m_ofn.lpstrFile = (char *)buff; cdf.m_ofn.nMaxFile = MAXFILENAMES; cdf.m_ofn.nFilterIndex = 1; CString result; if(cdf.DoModal() == IDOK) { //CString drive = cdf.GetFileDrive(); //CString path = cdf.GetFileDir(); //CString name = cdf.GetFileName(); CString ext = cdf.GetFileExt(); //P2N("path: %s %s %s %s\r\n", drive, path, name, ext); result = cdf.m_ofn.lpstrFile; // Patch with selected extension if(ext == "") { int idx = cdf.m_ofn.nFilterIndex; if(idx > 1) { // Iterate thru crap .... except *.* char *ptr = Ffilter; idx *= 2; while(true) { if(idx == 2) { while(*ptr != 0) ptr++; ptr++; // Skip null thing P2N("Resulting extension '%s'\r\n", ptr); result += (ptr + 1); break; } while(*ptr != 0) ptr++; ptr++; // Skip null thing if(!*ptr) // Double null, terminate break; //P2N("filter %s\r\n", ptr); idx--; } } } P2N("Save As with file name '%s'\r\n", result); pDoc->SetPathName(result); pDoc->SetModifiedFlag(); pDoc->OnSaveDocument(result); } free(buff); } void CWedView::OnAdvancedClearcurrentignorelist() { extern StrList ignore; ignore.RemoveAll(); } void CWedView::OnTimer(UINT nIDEvent) { //P2N("Timer tick on CWedView\r\n"); KillTimer(nIDEvent); if(nIDEvent == 1) { if(spp.splashed) { spp.Hide(); } } else if(nIDEvent == 2) { //P2N("void CWedView::OnTimer nIDEvent %d %p\r\n", nIDEvent, this); SyncCaret(); } } void CWedView::OnEditSetwrappingwidth() { CGotoLine gt; gt.m_str.Format("%d", linewidth); gt.m_prompt = "Set line length for wrapping"; gt.caption = "Line Length"; if(gt.DoModal() == IDOK) linewidth = atoi(gt.m_str); } void CWedView::OnSearchFindinfiles() { FindFiles(this); } void CWedView::OnInsertTemplatesOpentemplatefile() { CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CString str, num, droot; droot.Format("%stemplate\\", dataroot); OpenSource(droot); } void CWedView::OnMoveNextfunction() { MoveFunction(false); } void CWedView::OnMovePreviousfunction() { MoveFunction(true); } void CWedView::MoveFunction(int up) { //P2N("CWedView::MoveFunction %p\r\n", MoveFunction); CWedDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if(up) message("Moving to previous function."); else message("Moving to next function."); int found = false, loop = row; CRegExp re; re.RegComp(pDoc->funcregex); // "^[a-z].*\\(.*\\)"); int lim = pDoc->strlist.GetCount(); while(true) { if(up) { if(--loop < 0) break; } else { if(++loop >= lim) break; } CString str = pDoc->strlist.GetLine(loop); //P2N("Scanning Line %d '%s'\r\n", loop, str); if(re.RegFind(str) >= 0) { found = true; row = loop; col = 0; SyncCaret(2); break; } } if(!found) if(up) message("Already at the first function."); else message("Already at the last function."); }
[ "none@none" ]
[ [ [ 1, 7719 ] ] ]
06710c6e7fa7c4a8e117ae00d3adbba276ff5c58
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestappfrm/inc/bctestappfrmapp.h
6f392849d965c28674d66c0e39986573c6324186
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,432
h
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares main application class. * */ #ifndef C_CBCTESTAPPFRMAPP_H #define C_CBCTESTAPPFRMAPP_H // INCLUDES #include <aknapp.h> // CONSTANTS const TUid KUidBCTestAppFrm = { 0x200045CC }; // UID of the application. // CLASS DECLARATION /** * CBCTestAppFrmApp application class. * Provides factory to create concrete document object. */ class CBCTestAppFrmApp : public CAknApplication { public: virtual void PreDocConstructL(); private: // From CApaApplication /** * From CApaApplication, CreateDocumentL. * Creates CBCTestAppFrmDocument document object. * @return A pointer to the created document object. */ CApaDocument* CreateDocumentL(); /** * From CApaApplication, AppDllUid. * Returns application's UID ( KUidBCTestAppFrm ). * @return The value of KUidBCTestAppFrm. */ TUid AppDllUid() const; }; #endif
[ "none@none" ]
[ [ [ 1, 59 ] ] ]
b3e8b067c9ef3134ed5531763fb5052177ed8938
c8999a8d12d67db8efd246e244effbe295fe7c09
/source/client/life_expert/src/SettingContainer.cpp
173aa1420134195df3b7304e04c723fa16b9ce8d
[]
no_license
sleep651/life-expert
968ada69efb070e54df40c999b46c5738d8555d1
32df3f4f720c5e9f2d89ccb4785d1071e8a81d80
refs/heads/master
2016-09-06T13:15:38.938705
2010-03-05T14:32:19
2010-03-05T14:32:19
42,040,784
0
0
null
null
null
null
UTF-8
C++
false
false
6,149
cpp
/* ======================================================================== Name : SettingContainer.cpp Author : ZhangJiawei Copyright : Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] #include <aknviewappui.h> #include <eikappui.h> #include <life_expert.rsg> // ]]] end generated region [Generated System Includes] // [[[ begin generated region: do not modify [Generated User Includes] #include "SettingContainer.h" #include "SettingContainerView.h" #include "life_expert.hrh" // ]]] end generated region [Generated User Includes] // [[[ begin generated region: do not modify [Generated Constants] // ]]] end generated region [Generated Constants] /** * First phase of Symbian two-phase construction. Should not * contain any code that could leave. */ CSettingContainer::CSettingContainer() { // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * Destroy child controls. */ CSettingContainer::~CSettingContainer() { // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * Construct the control (first phase). * Creates an instance and initializes it. * Instance is not left on cleanup stack. * @param aRect bounding rectangle * @param aParent owning parent, or NULL * @param aCommandObserver command observer * @return initialized instance of CSettingContainer */ CSettingContainer* CSettingContainer::NewL( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { CSettingContainer* self = CSettingContainer::NewLC( aRect, aParent, aCommandObserver ); CleanupStack::Pop( self ); return self; } /** * Construct the control (first phase). * Creates an instance and initializes it. * Instance is left on cleanup stack. * @param aRect The rectangle for this window * @param aParent owning parent, or NULL * @param aCommandObserver command observer * @return new instance of CSettingContainer */ CSettingContainer* CSettingContainer::NewLC( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { CSettingContainer* self = new ( ELeave ) CSettingContainer(); CleanupStack::PushL( self ); self->ConstructL( aRect, aParent, aCommandObserver ); return self; } /** * Construct the control (second phase). * Creates a window to contain the controls and activates it. * @param aRect bounding rectangle * @param aCommandObserver command observer * @param aParent owning parent, or NULL */ void CSettingContainer::ConstructL( const TRect& aRect, const CCoeControl* aParent, MEikCommandObserver* aCommandObserver ) { if ( aParent == NULL ) { CreateWindowL(); } else { SetContainerWindowL( *aParent ); } iFocusControl = NULL; iCommandObserver = aCommandObserver; InitializeControlsL(); SetRect( aRect ); ActivateL(); // [[[ begin generated region: do not modify [Post-ActivateL initializations] // ]]] end generated region [Post-ActivateL initializations] } /** * Return the number of controls in the container (override) * @return count */ TInt CSettingContainer::CountComponentControls() const { return ( int ) ELastControl; } /** * Get the control with the given index (override) * @param aIndex Control index [0...n) (limited by #CountComponentControls) * @return Pointer to control */ CCoeControl* CSettingContainer::ComponentControl( TInt aIndex ) const { // [[[ begin generated region: do not modify [Generated Contents] switch ( aIndex ) { } // ]]] end generated region [Generated Contents] // handle any user controls here... return NULL; } /** * Handle resizing of the container. This implementation will lay out * full-sized controls like list boxes for any screen size, and will layout * labels, editors, etc. to the size they were given in the UI designer. * This code will need to be modified to adjust arbitrary controls to * any screen size. */ void CSettingContainer::SizeChanged() { CCoeControl::SizeChanged(); LayoutControls(); // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } // [[[ begin generated function: do not modify /** * Layout components as specified in the UI Designer */ void CSettingContainer::LayoutControls() { } // ]]] end generated function /** * Handle key events. */ TKeyResponse CSettingContainer::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ) { // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] if ( iFocusControl != NULL && iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed ) { return EKeyWasConsumed; } return CCoeControl::OfferKeyEventL( aKeyEvent, aType ); } // [[[ begin generated function: do not modify /** * Initialize each control upon creation. */ void CSettingContainer::InitializeControlsL() { } // ]]] end generated function /** * Handle global resource changes, such as scalable UI or skin events (override) */ void CSettingContainer::HandleResourceChange( TInt aType ) { CCoeControl::HandleResourceChange( aType ); SetRect( iAvkonViewAppUi->View( TUid::Uid( ESettingContainerViewId ) )->ClientRect() ); // [[[ begin generated region: do not modify [Generated Contents] // ]]] end generated region [Generated Contents] } /** * Draw container contents. */ void CSettingContainer::Draw( const TRect& aRect ) const { // [[[ begin generated region: do not modify [Generated Contents] CWindowGc& gc = SystemGc(); gc.Clear( aRect ); // ]]] end generated region [Generated Contents] }
[ [ [ 1, 222 ] ] ]
acca6980d0c9634652f98ff22cc2048463829c3a
5851a831bcc95145bf501b40e90e224d08fa4ac9
/src/modules/append-module/ui_append.cpp
989251a0f9316e7e1de51c68eafa2bd2a411a35e
[]
no_license
jemyzhang/Cashup
a80091921a2e74f24db045dd731f7bf43c09011a
f4e768a7454bfa437ad9842172de817fa8da71e2
refs/heads/master
2021-01-13T01:35:51.871352
2010-03-06T14:26:55
2010-03-06T14:26:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include <cMzCommon.h> using namespace cMzCommon; #include "ui_append.h" #include "resource.h" #include <UiIconButton.h> #include <commondef.h> #include <common-ui.h> extern HINSTANCE instHandle; MZ_IMPLEMENT_DYNAMIC(Ui_AppendWnd) Ui_AppendWnd::Ui_AppendWnd(){ } Ui_AppendWnd::~Ui_AppendWnd(){ } BOOL Ui_AppendWnd::OnInitDialog() { // Must all the Init of parent class first! if (!Ui_BaseWnd::OnInitDialog()) { return FALSE; } // Then init the controls & other things in the window return TRUE; } void Ui_AppendWnd::DelayShow(){ ::PostMessage(GetParent(),MZ_MW_REQ_CHANGE_TITLE,IDS_MODULE_NAME,(LPARAM)instHandle); DateTime::waitms(1); int id = 0; int y = 0,m = 0,d = 0; //MzPersonDialog(id,0,m_hWnd); //MzCategoriesDialog(id,0,m_hWnd); //MzAccountsDialog(id,0,m_hWnd); //MzCalendarDialog(y,m,d,m_hWnd); double val = 0.0; MzCalculatorDialog(val,m_hWnd); } LRESULT Ui_AppendWnd::MzDefWndProc(UINT message, WPARAM wParam, LPARAM lParam) { return Ui_BaseWnd::MzDefWndProc(message, wParam, lParam); } void Ui_AppendWnd::OnMzCommand(WPARAM wParam, LPARAM lParam) { UINT_PTR id = LOWORD(wParam); }
[ "jemyzhang@e7c2eee8-530d-454e-acc3-bb8019a9d48c" ]
[ [ [ 1, 51 ] ] ]
18177a9005dee5156861c3d331d242afaa2af0d9
7dd19b99378bc5ca4a7c669617a475f551015d48
/opencamera_Lite/rtsp_stack/mainSdk.cpp
87d769f7278a1bc4056d7623d65f5552113ff152
[]
no_license
Locnath/openpernet
988a822eb590f8ed75f9b4e8c2aa7b783569b9da
67dad1ac4cfe7c336f8a06b8c50540f12407b815
refs/heads/master
2020-06-14T14:32:17.351799
2011-06-23T08:51:04
2011-06-23T08:51:04
41,778,769
0
0
null
null
null
null
UTF-8
C++
false
false
8,923
cpp
// Defines the entry point for the console application. // #ifdef __WIN32__ //#include "../win32/stdafx.h" #include <winsock2.h> #endif #include "BasicUsageEnvironment.h" #include "RTSPServer.h" #include "MPEG4ESVideoRTPSink.h" #include "H264VideoRTPSink.h" #include "RTCP.h" #include "EncoderMediaSubsession.h" #include "EncoderSource.h" #include "RTSPCommon.h" #ifndef __WIN32__ #include <netdb.h> #include <sys/socket.h> #endif #include "rsa_crypto.h" #include "RTSPSdk.h" #include "Debug.h" #ifdef __WIN32__ #include <iostream.h> #else #include <iostream> #endif UsageEnvironment* env; #define BUFSIZE 1024 #ifdef SDKH264 H264VideoRTPSink *videoSink; #else MPEG4ESVideoRTPSink* videoSink; #endif //FramedSource* videoSource; //void play(); // forward int httpRequestKey(char *recvBuffer, char *mac) { ssize_t i = 0; char sndBuffer[BUFSIZE]={0}; int sockfd, sndLen = 0; struct sockaddr_in dest_addr; char *p = (char *)sndBuffer; char host[60] = {0}; unsigned short port = 0; getHttpServerInfo(host, &port); p += snprintf((char *)p, sizeof(sndBuffer)-1, "%s ","GET"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "%s", "http://"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "%s", host); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "%s", "/com/devfy/devfy.php?"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "mac=%s ", mac); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "%s\r\n", "HTTP/1.1"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "Host:%s\r\n", host); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "User-Agent:%s\r\n", "wayde"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "Accept:%s\r\n", "*/*"); p += snprintf((char *)p, sizeof(sndBuffer)-1 - (p-(char *)sndBuffer), "Connection:%s\r\n\r\n", "Keep-Alive"); sndLen = strlen(sndBuffer); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket is failed"); exit(1); } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); dest_addr.sin_addr.s_addr = inet_addr(host); if (connect(sockfd, (struct sockaddr *)&dest_addr,sizeof(struct sockaddr)) == -1) { perror("connect is error\n"); exit(1); } if (write(sockfd,sndBuffer,sndLen) == -1) { perror("write is error\n"); exit(1); } while (i = read(sockfd, recvBuffer, BUFSIZE-1)) { if (i <= 0) { return i; } recvBuffer[i]='\0'; Debug(ckite_log_message, "recvBuffer = %s\n", recvBuffer); break; } close(sockfd); return i; } void supportMoreVideoAccess(RTSPServer *rtsp_server, int width, int height, char *type, unsigned char channel) { unsigned int video_bitrate = 0; unsigned int framerate = 0; unsigned int keyinterval = 0; unsigned int audio_bitrate = 0; unsigned int framelength = 0; unsigned int samplerate = 0; getSubsessionParaConfig(type, width, height, video_bitrate, framerate, keyinterval, audio_bitrate, framelength, samplerate); EncoderMediaSubsession* audioSubsession, *videoSubsession; ServerMediaSession* sms = ServerMediaSession::createNew(*env, type, "", "RTSP session", True /*SSM*/); if (strcmp(type, "store") != 0) { videoSubsession = EncoderMediaSubsession::createNew(*env, NULL, False, False, 6970); videoSubsession->SetVideoParameters(channel, width, height, video_bitrate, framerate, keyinterval, type); sms->addSubsession(videoSubsession); #if 0 audioSubsession = EncoderMediaSubsession::createNew(*env, NULL, True, False, 6970); audioSubsession->SetAudioParameters(audio_bitrate, framelength, samplerate, type); sms->addSubsession(audioSubsession); #endif } rtsp_server->addServerMediaSession(sms); struct sockaddr_in sa; char host_name[60] = {0}; unsigned short host_port = 0; char local_name[20] = {0}; unsigned short local_port = 0; char local_mac_addr[20] = {0}; char UserAgent[256] = {0}; char *ptr = host_name; char **pptr; int i=0; struct hostent *hptr; getServerInfo(host_name, &host_port, 1); if(strlen((char const *)host_name) < 5 || host_port == 0) { getServerInfo(host_name, &host_port, 0); } while( host_name[i] == ' '){ ptr++; i++; } if(ptr[0] >= 'A' && ptr[0] <= 'Z' || ptr[0] >= 'a' && ptr[0] <= 'z') { if((hptr = gethostbyname(ptr)) == NULL) { setSessionState(type,DNSFAILED); printf(" gethostbyname error for host:%s\n", host_name); return ; } switch(hptr->h_addrtype) { case AF_INET: case AF_INET6: #ifndef __WIN32__ pptr=hptr->h_addr_list; for(; *pptr!=NULL; pptr++) inet_ntop(hptr->h_addrtype, *pptr, host_name, sizeof(host_name)); printf("host_name = %s\n",host_name); #else strcpy(host_name, inet_ntoa(*(struct in_addr *)*(hptr->h_addr_list))); #endif break; default: printf("unknown address type\n"); break; } } Debug(ckite_log_message, "host_name = %s\n", host_name); sa.sin_family = AF_INET; sa.sin_addr.s_addr = inet_addr(host_name); sa.sin_port = htons(host_port); getDeviceInfo(channel, local_name, &local_port, local_mac_addr); getUserAgent(UserAgent, sizeof(UserAgent)); /*key*/ char key[BUFSIZE] = {0}; char *key_ptr = key; readkey(channel, key); if(strlen(key) < 256) { while(1) { memset(key, 0, sizeof(key)); httpRequestKey(key, local_mac_addr); key_ptr = strstr(key, "Key:"); if(key_ptr != NULL) { memcpy(key, key_ptr + 4, 256); writekey(channel, key); memset(key, 0, BUFSIZE); readkey(channel, key); if(strlen(key) < 256) continue; else break; } else { setSessionState(type,KEYFAILED); #ifndef __WIN32__ sleep(30*60); #else Sleep(30*60*1000); #endif } } } RTSPServer::RTSPEncoderSession* encoderSession = rtsp_server->createNewEncoderSession(sms, 1, sa, local_name, local_port, (char *)type, local_mac_addr, NULL, UserAgent, 1); char* url = rtsp_server->rtspURL(sms); *env << "Play this stream using the URL \"" << url << "\"\n"; delete[] url; } void eventLoop() { env->taskScheduler().doEventLoop(); // does not return } void realEntryMain(unsigned char channel) { // Create 'groupsocks' for RTP and RTCP: struct in_addr destinationAddress; destinationAddress.s_addr = 0; // Note: This is a multicast address. If you wish instead to stream // using unicast, then you should use the "testOnDemandRTSPServer" // test program - not this test program - as a model. const unsigned short rtpPortNum = 18888; const unsigned short rtcpPortNum = rtpPortNum+1; const unsigned char ttl = 255; const Port rtpPort(rtpPortNum); const Port rtcpPort(rtcpPortNum); Groupsock rtpGroupsock(*env, destinationAddress, rtpPort, ttl); rtpGroupsock.multicastSendOnly(); // we're a SSM source Groupsock rtcpGroupsock(*env, destinationAddress, rtcpPort, ttl); rtcpGroupsock.multicastSendOnly(); // we're a SSM source // Create a 'MPEG-4 Video RTP' sink from the RTP 'groupsock': #ifdef SDKH264 videoSink = H264VideoRTPSink::createNew(*env, NULL, &rtpGroupsock, 96/*, 4366366, "Z0LADPICwS0IAAADAyAAAAMACHihUkA=,aMuDyyA="*/); #else videoSink = MPEG4ESVideoRTPSink::createNew(*env, NULL, &rtpGroupsock, 96); #endif // Create (and start) a 'RTCP instance' for this RTP sink: const unsigned estimatedSessionBandwidth = 500; // in kbps; for RTCP b/w share const unsigned maxCNAMElen = 100; unsigned char CNAME[maxCNAMElen+1]; gethostname((char*)CNAME, maxCNAMElen); CNAME[maxCNAMElen] = '\0'; // just in case RTCPInstance* rtcp = RTCPInstance::createNew(*env, &rtcpGroupsock, estimatedSessionBandwidth, CNAME, videoSink, NULL /* we're a server */, True /* we're a SSM source */); // Note: This starts RTCP running automatically unsigned short listenPort = 0; getListenPortByChannel(&listenPort, channel); RTSPServer* rtspServer = RTSPServer::createNew(*env, listenPort); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; /// exit(1); } supportMoreVideoAccess(rtspServer, 352, 288, (char *)"live", channel); //supportMoreVideoAccess(rtspServer, 176, 144, (char *)"mobile"); //supportMoreVideoAccess(rtspServer, 0, 0, (char *)"store"); // now , subsession isn't need created //supportMoreVideoAccess(rtspServer, 720, 576, (char *)"livehd"); eventLoop(); } int main(int argc, char** argv) { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); realEntryMain(1); return 0; // only to prevent compiler warning }
[ [ [ 1, 298 ] ] ]
d37d8ff0eabcaed52d9a87f419b47df946ba78cc
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/Learning OpenCV/Chapter 2 - Introduction to OpenCV/Ex_2_5.cpp
fea4d59ba742e748fe41b068a32dce4f6eddee7c
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
#include "cv.h" #include "highgui.h" IplImage* doPyrDown( IplImage* in, int filter = IPL_GAUSSIAN_5x5 ) { // Best to make sure input image is divisible by two. // assert( in->width%2 == 0 && in->height%2 == 0 ); IplImage* out = cvCreateImage( cvSize( in->width/2, in->height/2 ), in->depth, in->nChannels ); cvPyrDown( in, out ); return( out ); }; int main(int argc, char** argv ) { IplImage* img = cvLoadImage( argv[1] ); cvNamedWindow( "Example5", CV_WINDOW_AUTOSIZE ); cvShowImage( "Example5", img ); IplImage* out = doPyrDown( img ); cvNamedWindow( "Example5-out", CV_WINDOW_AUTOSIZE ); cvShowImage( "Example5-out", out ); cvWaitKey( 0 ); cvReleaseImage( &img ); cvReleaseImage( &out ); cvDestroyWindow( "Example5" ); cvDestroyWindow( "Example5-out" ); }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 35 ] ] ]
ba24e8741ffdaff589d331d7bc0ced733110812a
822ab63b75d4d4e2925f97b9360a1b718b5321bc
/widgets/segmentview/segmentview.cpp
579ee10450c94c89e75e753f59563ff96f221a9f
[]
no_license
sriks/decii
71e4becff5c30e77da8f87a56383e02d48b78b28
02c58fbaea69c2448249710d13f2e774762da2c3
refs/heads/master
2020-05-17T23:03:27.822905
2011-12-16T07:29:38
2011-12-16T07:29:38
32,251,281
0
0
null
null
null
null
UTF-8
C++
false
false
3,611
cpp
/* * Author: Srikanth Sombhatla * Copyright 2010 Konylabs. All rights reserved. * */ #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QGraphicsLinearLayout> #include <QGraphicsWidget> #include <QGestureEvent> #include <QPanGesture> #include <QDebug> #include "segment.h" #include "segmentwidget.h" #include "segmentview.h" /*! \class SegmentView \brief A QGraphicsView derived class which encapsulates a container with a layout to hold segments. \ref Segment, SegmentWidget or any QGraphicsWidget can be added to this view. Internally this view has a container which is a \ref Segment. Hence a \ref Segment or \ref SegmentWidget can be added directly into this view, which inturn arranges the items in the order in which they are added. \section usage Usage \code Segment* labelSegment = new Segment(Qt::Vertical); labelSegment->layout()->setSpacing(0); labelSegment->addItem(new QGraphicsTextItem("Title")); labelSegment->addItem(new QGraphicsTextItem("Subtitle")); Segment* buttonSegment = new Segment(Qt::Vertical); buttonSegment->layout()->setSpacing(10); buttonSegment->addItem(new QPushButton("Upload")); QPushButton* removeButton = new QPushButton("Remove"); buttonSegment->addItem(removeButton); // Now add all segments to a segment widget. // SegmentWidget* segmentWidget = new SegmentWidget(Qt::Horizontal); // Segments apppear in the order in which they are added. segmentWidget->addItem(labelSegment); segmentWidget->addItem(buttonSegment); SegmentView segmentView = new SegmentView(Qt::Vertical); segmentView->addSegmentWidget(segmentWidget); \endcode \sa QGraphicsView QGraphicsWidget Segment SegmentWidget **/ SegmentView::SegmentView(Qt::Orientation aOrientation,QWidget *aParent) : QGraphicsView(aParent) { QGraphicsScene* s = new QGraphicsScene; setScene(s); mContainer = new Segment(aOrientation); scene()->addItem(mContainer); // ownership is transferred to scene setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } /*! Adds a \ref SegmentWidget to this view. Ownership is transferred. Since \ref SegmentWidget has a visual appearance, once it is added the size policy is set so that it can grow horizontally, but fixed vertically. This is required for vertical layout since removing an item makes other items to grow vertically. \sa addSegment **/ void SegmentView::addSegmentWidget(SegmentWidget* aSegmentWidget) { aSegmentWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); aSegmentWidget->setParentContainer(mContainer->layout()); mContainer->addItem(aSegmentWidget); } /*! Adds a \ref Segment to this view. Ownership is transferred. Use this method to add a \ref SegmentWidget with a defined sizepolicy. It is always a good practice to define the sizepolicy of items so that they are resized when other items in the layout are removed. By default, a layout tries to resize the items to fit the layout area. \sa addSegmentWidget **/ void SegmentView::addSegment(Segment* aSegment) { mContainer->addItem(aSegment); } void SegmentView::resizeEvent(QResizeEvent *event) { qDebug()<<__PRETTY_FUNCTION__; qDebug()<<"newsize:"<<event->size(); if(mContainer->size() != event->size()) { mContainer->resize(event->size().width(),mContainer->size().height()); } } // eof
[ "srikanthsombhatla@016151e7-202e-141d-2e90-f2560e693586" ]
[ [ [ 1, 101 ] ] ]
4ba728c1d5e095950f978bc67cfbf8c30ca8f660
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread_condattr_init.cpp
16f61aa6680e07a2d63959fb82517c899bc5dfa8
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
764
cpp
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: POSIX implementation of pthread on Symbian * */ #include "condvartypes.h" /* This function initializes the condition attribute object attr and sets it with default values for the attributes. */ EXPORT_C int pthread_condattr_init(pthread_condattr_t * /*attr*/) { return 0; } //End of File
[ "none@none" ]
[ [ [ 1, 30 ] ] ]
9e8c0a65a131aec1e541627a51550e1b6a21454f
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/dvr/Net/TcpSockServer.h
ec73c4b2cfd027505c9ede761c7902ec0e81e54e
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
1,939
h
/* * Copyright (c) 2009, 浙江亿蛙技术股份有限公司 * All rights reserved. * * 类名称:TCP服务器类 * 摘 要:TCP服务器。 * */ ////////////////////////////////////////////////////////////////////////// #if !defined(AFX_ALARMSERVER_H__9376B537_0FCB_40E1_BD4C_DD1B60FFBD41__INCLUDED_) #define AFX_ALARMSERVER_H__9376B537_0FCB_40E1_BD4C_DD1B60FFBD41__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #if (defined(WIN32) && !(defined(NETSDK_VERSION_SSL))) #include "../../TPLayer_IOCP/TPTCPServer.h" #else #include "../../TPLayer_Select/TPTCPServer.h" using namespace NET_TOOL; #endif // 接收回调函数 typedef int (CALLBACK *fEventCallBack)(LONG lHandle, int connId, char *szIp, WORD wPort, LONG lCommand, void *pParam, DWORD dwParamLen, DWORD dwUserData); ////////////////////////////////////////////////////////////////////////// class CTcpSockServer :public TPTCPServer, public ITPListener { public: CTcpSockServer(); virtual ~CTcpSockServer(); public: static int InitNetwork(); static int ClearNetwork(); public: // interface int StartListen(const char *szIp, int nPort, fEventCallBack cbRecAlarmFunc, DWORD dwUserdata); int StopListen(); int HeartBeat(); public: // event virtual int onData(int nEngineId, int nConnId, unsigned char* data, int nLen); virtual int onDealData(int nEngineId, int nConnId, unsigned char* buffer, int nLen); virtual int onSendDataAck(int nEngineId, int nConnId, int nId); virtual int onConnect(int nEngineId, int nConnId, char* szIp, int nPort); virtual int onClose(int nEngineId, int nConnId); virtual int onDisconnect(int nEngineId, int nConnId); virtual int onReconnect(int nEngineId, int nConnId); private: fEventCallBack m_cbServer; DWORD m_dwUserData; }; #endif // !defined(AFX_ALARMSERVER_H__9376B537_0FCB_40E1_BD4C_DD1B60FFBD41__INCLUDED_)
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 68 ] ] ]
b3203a5c8ac8592ee67c1c9de49d6a67c525e52d
a62d03eea64b3d456d95fa7c1df38f8b545319e0
/TemplateInstanceNode.cpp
4cda4bf2306f13a3dc542a5c594f329b4807abb2
[]
no_license
radtek/evtx-cpp
32dc4e30301739b069f7de19f04e807b9cdcc826
c7f08457ec19b7e617685ba9e36a59e52a25384d
refs/heads/master
2020-06-28T19:19:24.216152
2010-12-13T21:13:23
2010-12-13T21:13:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
604
cpp
#include "TemplateInstanceNode.h" #include "CustomTypes.h" namespace Bxml { TemplateInstanceNode::TemplateInstanceNode(char* data, size_t length, Context context, bool hasAttributes) : Node(data, length, context) { size += sizeof byte; tdef = new TemplateDef(data+size, length-size, context, hasAttributes); size += tdef->getSize(); tdata = new TemplateInstanceData(data+size, length-size); size += tdata->getSize(); } TemplateInstanceNode::~TemplateInstanceNode(void) { } std::wstring* TemplateInstanceNode::toXml() { // TODO: remove this stub return NULL; } }
[ "?????????????@SPARXXX-MOBILE" ]
[ [ [ 1, 27 ] ] ]
0eb17af4f6d8297f601b6e38b35c0a28198d7f54
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SERenderers/SE_OpenGL_Renderer/SEOpenGLRendering/SEOpenGLPolygonOffsetState.cpp
d9688988290e6d9b3d59076009ecc3e51dab8eb5
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // 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. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEOpenGLRendererPCH.h" #include "SEOpenGLRenderer.h" using namespace Swing; //---------------------------------------------------------------------------- void SEOpenGLRenderer::SetPolygonOffsetState(SEPolygonOffsetState* pState) { SERenderer::SetPolygonOffsetState(pState); if( pState->FillEnabled ) { glEnable(GL_POLYGON_OFFSET_FILL); } else { glDisable(GL_POLYGON_OFFSET_FILL); } if( pState->LineEnabled ) { glEnable(GL_POLYGON_OFFSET_LINE); } else { glDisable(GL_POLYGON_OFFSET_LINE); } if( pState->PointEnabled ) { glEnable(GL_POLYGON_OFFSET_POINT); } else { glDisable(GL_POLYGON_OFFSET_POINT); } glPolygonOffset(pState->Scale, pState->Bias); } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 60 ] ] ]
bcfd14541f3c12aee5aa17d756810a529adfea18
c1eae8224c4d3d380cc83ff6b218ba2a9df8d687
/Source Codes/LineConner/Main/NoiseRemoval.h
3cee43ef7e73af0b8c53e20fca7d204d596cb375
[]
no_license
pizibing/noise-removal
15bad5c0fe1b3b5fb3f8b775040fc3dfeb48e49b
c087356bfa07305ce7ac6cce8745b1e676d6dc42
refs/heads/master
2016-09-06T17:40:15.754799
2010-03-05T06:47:59
2010-03-05T06:47:59
34,849,474
1
0
null
null
null
null
UTF-8
C++
false
false
3,372
h
#ifndef NOISEREMOVAL_H_ #define NOISEREMOVAL_H_ #include "..\..\MeshUI\Common\watchtime.h" #include "..\Global\Global.h" #include "..\Global\CommonData.h" #include "..\DisjointSetUnion.h" #include "M_Point.h" #include <cmath> struct Persistence{ size_t sad, maxmin; double pValue; }; struct NoiseCluster { size_t centerPoint; vector<size_t> noisePoints; // the points set in this cluster vector<Global::POINTTYPE> noiseType; // each point's type Global::POINTTYPE type; NoiseCluster():centerPoint(UNCERTAIN), type(Global::BADPOINT){} }; class NoiseRemoval { typedef std::pair<int,int> VtxPair; typedef std::pair<double,double> DoublePair; public: NoiseRemoval(); NoiseRemoval(CommonData& cd); ~NoiseRemoval(); void CalPersistence(); void SetThreshold(double lowBound, double upBound) { m_threshold.first = lowBound; m_threshold.second = upBound; } DoublePair GetThreshold() const { return m_threshold;} vector<set<MaxMinPair>>* GetBadPaths(){ return &m_BadPathID;} void RemoveNoise(); private: void RemoveBadCriticalPoints(); // method for modifying connection void ModifyConnLine(); void ModifySadConnLine(); void ModifySadConnLine(SadPoint& sadPoint); void ModifyDualConnLine(); size_t FindCenterInCluster(NoiseCluster& cluster, Global::POINTTYPE type); size_t SelectMeasureOnNormal(size_t sadP, set<size_t>& pointSet); void FindBestMMPairOnLength(size_t sadP, set<size_t>& pointSet, vector<size_t>& ret); void FindBestMMPairOnAngle (size_t sadP, set<size_t>& pointSet, vector<size_t>& ret); // method for finding bad connection void SetEdgePathMapping(); void CalcEdgeAdjFace(); void CheckBadConnLine(); void CheckDualBadConnLine(); void FloodFillAFace(size_t fID); // some help method void FindAdjFaces(size_t vid1,size_t vid2, size_t& fid1, size_t& fid2); inline double Angle(size_t p0,size_t p1, size_t p2 ); inline double Angle(Coord& v1, Coord& v2); void TestConnection(); private: // common data vector <M_Point*>* p_vtx; set <size_t>* p_SadPointID; set <size_t>* p_MaxPointID; set <size_t>* p_MinPointID; vector <double>* p_EigenValue; map<MaxMinPair, IndexArray>* p_DualConn; map < pair<size_t,size_t>, double> m_persistence; DoublePair m_threshold; DisjointSet disjoinSet; set <size_t> m_badPoints; vector <NoiseCluster> m_NoiseCluster; map<size_t,size_t> m_center_cluster_mapping; map<size_t,size_t> m_badvtx_cluster_mapping; map <size_t, vector <size_t>> m_badPointCluster; map <size_t, size_t> m_bad_vtx_mapping; map <size_t, size_t> m_center_vtx_mapping; vector <size_t> m_newAddSad; vector<bool> m_FaceVisitFlag; map<pair<size_t,size_t>, vector<MaxMinPair> > m_EdgePathMapping;//the mapping between edge and its path vector< set<MaxMinPair> > m_BadPathID; map<pair<size_t,size_t>, vector<size_t> > m_EdgeAdjFace;// the adj-faces of one edge; SystemWatchTime m_time; }; inline double NoiseRemoval::Angle(size_t p0,size_t p1, size_t p2 ) { // calculate the angle between (p0,p1) and (p0,p2) return Angle((*Global::p_coord)[p1]-(*Global::p_coord)[p0], (*Global::p_coord)[p2]-(*Global::p_coord)[p0]); } inline double NoiseRemoval::Angle(Coord& v1, Coord& v2) { if(v1 == v2) return 0.0; return acos(dot(v1,v2)/(v1.abs()*v2.abs())); } #endif
[ "weihongyu1987@f7207f0a-2814-11df-8e46-3928208ddfa0" ]
[ [ [ 1, 121 ] ] ]
680235de02568a21613f923c7e26164444929b14
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/ipaddr.h
faabab2868dfdf39a0d863fbd4eba2c7d5b08767
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
4,412
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - IPAddress Class // George F. Riley. Georgia Tech, Spring 2002 #ifndef __ipaddr_h__ #define __ipaddr_h__ #include <string> #include <algorithm> #include "G_common_defs.h" #define IPAddrBroadcast (IPAddr_t)0xffffffff //Doc:ClassXRef class IPAddr { //Doc:Class Defines an object that specifies an \IPA\ using the familiar //Doc:Class "dotted" location. Objects of class {\tt IPAddr} have //Doc:Class an automatic typecast to type {\tt IPAddr\_t}, so an //Doc:Class {\tt IPAddr} object can be used whenever a variable of //Doc:Class {\tt IPAddr\_t} is needed. public: //Doc:Method IPAddr() : ip(0) { } //Doc:Desc Constructor for {\tt IPAddr}. The \IPA\ defaults to //Doc:Desc \IPAN\ (0). //Doc:Method IPAddr(std::string&); // Construct from dotted notation //Doc:Desc Construct an {\tt IPAddr} object using a string in the //Doc:Desc familiar "dotted" notation. //Doc:Arg1 String value specifying the desired \IPA\ in dotted notation. //Doc:Method IPAddr(IPAddr_t i) : ip(i) { } //Doc:Desc Construct an {\tt IPAddr} object with the specified //Doc:Desc 32 bit address. //Doc:Arg1 \IPA\ as a 32 bit unsigned quantity. IPAddr(const char*); // Construct from char to string operator IPAddr_t() const { return ip;} // Typecast to unsigned long operator std::string() const; // Typecast to a string bool operator==(const IPAddr& i) const { return ip == i.ip;} bool operator< (const IPAddr& i) const { return ip < i.ip;} //Doc:Method static IPAddr_t ToIP(const std::string); //Doc:Desc Convert a string (dotted notation) \IPA\ to 32 bit unsigned. //Doc:Arg1 String to convert. //Doc:Return 32 bit unsigned \IPA. //Doc:Method static char* ToDotted(IPAddr_t); //Doc:Desc Convert a 32 bit \IPA\ to a string in dotted notation. //Doc:Desc \IPA\ to convert. //Doc:Arg1 Pointer to ASCIIZ string with the \IPA\ in dotted notation. //Doc:Return The buffer pointed to is only valid until another //Doc:Return call to {\tt IPAddr} functions. public: IPAddr_t ip; }; // Define a pair for IPAddress/Port typedef std::pair<IPAddr_t, PortId_t> IPPort_t; // Define an output operator std::ostream& operator<<(std::ostream&, const IPAddr&); #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 117 ] ] ]
afb671b1012d8ed998dd9241b7e8c332ce93415e
aecc6d0ee5b767cc9c6ad2b22718f55e43abfe53
/Aesir/Attic/MapDocument.h
9ae07a3999849e0ae32f6236cbf1adf99e987c20
[]
no_license
yeah-dude/aesirtk
72ab3427535ee6c4535f4a7a16b5bd580309a2cd
fe43bedb45cdfb894935411b84c55197601a5702
refs/heads/master
2021-01-18T11:43:09.961319
2007-06-27T21:42:10
2007-06-27T21:42:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
441
h
#pragma once #include <wx/docview.h> class MapDocument : public wxDocument { DECLARE_DYNAMIC_CLASS(MapDocument) public: static const int QUADRANT_SIZE = 256; class Quadrant; wxOutputStream &SaveObject(wxOutputStream &stream) { return stream; } wxInputStream &LoadObject(wxInputStream &stream) { return stream; } void InsertTile(int x, int y, int tileIndex); private: Quadrant *root; wxPoint top_left; wxSize size; };
[ "MisterPhyrePhox@6418936e-2d2e-0410-bd97-81d43f9d527b" ]
[ [ [ 1, 16 ] ] ]
1e4c127485565e08df3404f0fd1979222a6c6f67
028d6009f3beceba80316daa84b628496a210f8d
/uidesigner/com.nokia.sdt.referenceprojects.test/data2/empty_container_3_0/reference/src/empty_container_3_0Document.cpp
bf4b9f5f04b90159562be9a1d634601f1fa4bc7c
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
cpp
// [[[ begin generated region: do not modify [Generated User Includes] #include "empty_container_3_0Document.h" #include "empty_container_3_0AppUi.h" // ]]] end generated region [Generated User Includes] /** * @brief Constructs the document class for the application. * @param anApplication the application instance */ Cempty_container_3_0Document::Cempty_container_3_0Document( CEikApplication& anApplication ) : CAknDocument( anApplication ) { } /** * @brief Completes the second phase of Symbian object construction. * Put initialization code that could leave here. */ void Cempty_container_3_0Document::ConstructL() { } /** * Symbian OS two-phase constructor. * * Creates an instance of Cempty_container_3_0Document, constructs it, and * returns it. * * @param aApp the application instance * @return the new Cempty_container_3_0Document */ Cempty_container_3_0Document* Cempty_container_3_0Document::NewL( CEikApplication& aApp ) { Cempty_container_3_0Document* self = new ( ELeave ) Cempty_container_3_0Document( aApp ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } /** * @brief Creates the application UI object for this document. * @return the new instance */ CEikAppUi* Cempty_container_3_0Document::CreateAppUiL() { return new ( ELeave ) Cempty_container_3_0AppUi; }
[ [ [ 1, 49 ] ] ]
6ae9b73f10cc1ecbc55ec4fb3b8694e6616f4576
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/BsCommon.h
0c9d4a57c8802bf9f95452156bdc1cc89f9d80ec
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
874
h
#ifndef __BS_COMMON_H_ #define __BS_COMMON_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 template< typename T > struct Deleter : public unary_function< T, void > { void operator( ) ( T& t ) { if( t ) { delete t; t = 0; } } }; template< typename T > struct PairDeleter : public unary_function< T, void > { void operator( ) ( T& t ) { if( t.second ) { delete t.second; t.second = 0; } } }; template< typename T > struct SeqDeleter { void operator( ) ( T& t ) { for_each( t.begin(), t.end(), Deleter< T::value_type > ( ) ); t.clear(); } }; template< typename T > struct AssDeleter { void operator( ) ( T& t ) { for_each( t.begin(), t.end(), PairDeleter< T::value_type > ( ) ); t.clear(); } }; #endif __BS_COMMON_H_
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 55 ] ] ]
00f751b0fc29c3b3f68d27a713231004baccc3c8
d249c8f9920b1267752342f77d6f12592cb32636
/moteurGraphique/src/Ressource/Mesh/Capsule.cpp
c72d23093d972870309448609a40495ce3208e16
[]
no_license
jgraulle/stage-animation-physique
4c9fb0f96b9f4626420046171ff60f23fe035d5d
f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae
refs/heads/master
2021-12-23T13:46:07.677761
2011-03-08T22:47:53
2011-03-08T22:47:53
33,616,188
0
0
null
2021-10-05T10:41:29
2015-04-08T15:41:32
C++
UTF-8
C++
false
false
839
cpp
/* * Capsule.cpp * * Created on: 19 fevr. 2009 * Author: jeremie GRAULLE */ #include "Capsule.h" #include <GL/gl.h> Capsule::Capsule(float rayon, float hauteur, int slices, int stacks) : slices(slices), stacks(stacks), rayon(rayon), hauteur(hauteur) { GLUquadric* quadric = gluNewQuadric(); gluQuadricTexture(quadric, GL_TRUE); idDisplayList = glGenLists(1); glNewList(idDisplayList, GL_COMPILE); glRotatef(90.0, 1.0, 0.0, 0.0); glTranslatef(0.0, 0.0, -hauteur/2.0); gluCylinder(quadric, rayon, rayon, hauteur, slices, 1); glTranslatef(0.0, 0.0, hauteur); gluSphere(quadric, rayon, slices, stacks); glTranslatef(0.0, 0.0, -hauteur); glRotatef(180.0, 1.0, 0.0, 0.0); gluSphere(quadric, rayon, slices, stacks); glEndList(); gluDeleteQuadric(quadric); } Capsule::~Capsule() {}
[ "jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb", "jeremie@74bb1adf-7843-2a67-e58d-b22fe9da3ebb" ]
[ [ [ 1, 12 ], [ 14, 33 ] ], [ [ 13, 13 ] ] ]
e90ff202d01a338237446729454ca46e08ef0fab
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WireKeysDlg.h
319066eedb473bc029f170cba631e42e55cfb722
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
7,029
h
// #if !defined(AFX_SORGANIZATORDLG_H__F91233BB_3784_4194_997B_F1278D90A9AF__INCLUDED_) #define AFX_SORGANIZATORDLG_H__F91233BB_3784_4194_997B_F1278D90A9AF__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "_common.h" #include "DLGClip.h" //////////////////////////////////////////////////////////////////////////// // AppMainDlg dialog class AppMainDlg : public CDialog { public: CDLGClip* clipWnd; void ShowBaloonAtPosition(CString sText, CString sTitle, int iX, int iY, DWORD dwTimeout); CHyperlink wpLabsLink; BOOL ChangeItemIcon(const char* szItemPath); void KillWndProcess(HWND hUnderCur); CMenuToolTip ttMenu; CMenuToolTip mcMenu; int GetWKState(); long lHotkeysState; void ScrollAction(int iAction); CFont* pIconFont; BOOL PopupAppWindow(DWORD dwProcID,BOOL bAction=0); CStringArray aExpandedFolderPaths; void SetRegInfo(); void SetWindowIcon(int iIconType=0, BOOL bForce=0); void GenerateBindingsFile(); BOOL RegisterMyHotkey(CIHotkey& oHotkey,DWORD dwCode,const char* szId,const char* szDsc, CString& sFailed, int& iCount); void AWndManagerMain(HWND forWnd, BOOL bTryToGetCaret=TRUE, int iMenu=0); void HideApplication(HWND hWin, DWORD dwHideType); void OnBossKey(); void PerformOnShutdown(); DWORD dwVolSplashTimer; DWORD dwWinAmpSplashTimer; CSplashWindow* VolumeSplWnd; CSplashWindow* WinAmpSplWnd; CSimpleMixer mixer; long ChangeVolumeControl(long lDx, int iMuter=-1); BOOL WinAmpControl(int iAction, BOOL bTryStart=1, BOOL bSplashEnabled=1, int iAdditionalPar=0); afx_msg void OnMinimizeActiveWindow(); afx_msg void OnShutDownComputer(); afx_msg void OnLockStation(); afx_msg LRESULT ONWM_THIS(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnRunQRunApplication(WPARAM wParam, LPARAM lParam); LRESULT RunQRunApp(int iWndNum, BOOL bSwitchDesk, int iEntryNum=0); afx_msg LRESULT ONWM_WIRENOTE(WPARAM wParam, LPARAM lParam); afx_msg LRESULT ONWM_EXTERN(WPARAM wParam, LPARAM lParam); BOOL IsIconMustBeHided(); DWORD dwThreadId; void AttachToClipboard(BOOL bAr); //static void ConvertSelected(HKL& hCurrentLayout, CString& sText, CString& sCopy); void SwitchResolution(int iMode); afx_msg LRESULT OnFireAlert(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnEDITTEXT(WPARAM wParam, LPARAM lParam); BOOL PerformTrayAction(int iAction,BOOL bHotKey=FALSE); BOOL bLastHalfer; BOOL bMainWindowInitialized; BOOL bAllLoaded; CString SetTrayTooltip(BOOL bUpdation=0); ~AppMainDlg(); void Finalize(); BOOL bAnyPopupIsActive; CSmartWndSizer Sizer; afx_msg LRESULT OnHotKey(WPARAM wParam, LPARAM lParam); void RegisterMyHotKeys(BOOL bSilently=FALSE); void UnRegisterMyHotKeys(BOOL bNeedRecreate=TRUE); int iRunStatus; AppMainDlg(CWnd* pParent = NULL); // standard constructor void TakeScreenshot(); BOOL TuneUpItem(const char* szTopic); BOOL TuneUpItemX(const char* szTopic); afx_msg void SetKBLayout(HKL hWhat); // Dialog Data //{{AFX_DATA(AppMainDlg) enum { IDD = IDD_ABOUTBOX }; CBitmapStatic m_Logo; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(AppMainDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); virtual void OnOK(); virtual BOOL OnInitDialog(); //}}AFX_VIRTUAL // Implementation public: CSystemTray m_STray; // Generated message map functions //{{AFX_MSG(AppMainDlg) virtual void PostNcDestroy(); afx_msg void OnDonate(); afx_msg void OnEnterKey(); afx_msg void OnHotmenuShowexepath(); afx_msg void OnHotmenuAddToQRun(); afx_msg void OnHotmenuAddToDesktop(); afx_msg void OnHotmenuAddToQLaunch(); afx_msg void OnHotmenuAddToStartMenu(); afx_msg void OnHotmenuAddToAHide(); afx_msg void OnHotmenuAddToUDFolder(); afx_msg void OnSystraySetMute(); afx_msg void OnSystraySetVol0(); afx_msg void OnSystraySetVol30(); afx_msg void OnSystraySetVol50(); afx_msg void OnSystraySetVol70(); afx_msg void OnSystraySetVol100(); afx_msg void OnSystraySendasuggestion(); afx_msg void OnSystrayDisplayProps(); afx_msg void OnSystrayAddRemProgs(); afx_msg void OnSystrayProcListPars(); afx_msg void OnHotmenuTxtPars(); afx_msg void OnSystrayScrShot(); afx_msg void OnSystrayRestoreIcons(); afx_msg void OnSystraySaveIcons(); afx_msg void OnEntcode(); afx_msg void OnWebsite(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnDestroy(); afx_msg void OnSystrayOptions(); afx_msg void OnSystrayOptions2(); afx_msg void OnEndSession(BOOL bEnding); afx_msg void StartDefBrowser(); afx_msg void StartDefEmail(); afx_msg void OnSwapCD(); afx_msg void ShowHotMenu(); afx_msg void ShowKeyBindings(); afx_msg void OnHotmenuBringinview(); afx_msg void OnHotmenuSemitransparent(); afx_msg void OnHotmenuExitmenu(); afx_msg void OnHotmenuKillprocess(); afx_msg void OnHotmenuKillprocessUnderCur(); afx_msg void OnHotmenuTransparency100(); afx_msg void OnHotmenuTransparency20(); afx_msg void OnHotmenuTransparency40(); afx_msg void OnHotmenuTransparency60(); afx_msg void OnHotmenuTransparency80(); afx_msg void OnHotmenuSwitchontop(); afx_msg void OnHotmenuPopupmainwindow(); afx_msg void OnHotmenuHidetotrayDetached(); afx_msg void OnHotmenuHidetotray(); afx_msg void OnHotmenuUnHideFromtray(); afx_msg void OnHotmenuFreememory(); afx_msg void OnHotmenuConvertselected(); afx_msg void OnHotmenuConvertselectedLW(); afx_msg void OnHotmenuUppercase(); afx_msg void OnHotmenuLowercase(); afx_msg void OnHotmenuSwitchcase(); afx_msg void OnHotmenuCountcharacters(); afx_msg void OnSystrayAbout(); afx_msg void OnReattachClips(); afx_msg void OnSystrayExit(); afx_msg void OnSystrayOpen(); afx_msg void OnSystrayShowAllApps(); afx_msg void OnSystrayBossPanic(); afx_msg void OnHotmenuTakescreenshot(); afx_msg void OnSystrayHelp(); afx_msg void OnHotmenuRunascommand(); afx_msg void OnHotmenuCalculate(); afx_msg void OnHotmenuHidecompletely(); afx_msg void OnHotmenuRunscreensaver(); afx_msg void OnHotmenuShutdown(); afx_msg void OnHotmenuRestart(); afx_msg void OnHotmenuSuspend(); afx_msg void OnHotmenuScreensaverenabled(); afx_msg void OnSystrayAddqrunapplication(); afx_msg void OnSystrayAddqrunappwnd(); afx_msg void OnSystrayAddqrunmacros(); afx_msg void OnSystrayReqMacro(); afx_msg void OnHotmenuClearclips(); afx_msg void OnSystrayPlgOptions(); afx_msg void OnSystrayPlgDownload(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. int AppendQRunSingleToMenu(CMenu* pMenuRoot, CMenu* pMenu, DWORD dwMacrosMask, int* iCountTotal=NULL, const char* szCategID=NULL); #endif
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 190 ] ] ]
ec4bcbd34ab89acdda8a79403ba355f6bdfd8705
45229380094a0c2b603616e7505cbdc4d89dfaee
/wavelets/haar_src/src/ai/AiClassifier.cpp
213fffd86e5f35565c69b95545498e8530316c10
[]
no_license
xcud/msrds
a71000cc096723272e5ada7229426dee5100406c
04764859c88f5c36a757dbffc105309a27cd9c4d
refs/heads/master
2021-01-10T01:19:35.834296
2011-11-04T09:26:01
2011-11-04T09:26:01
45,697,313
1
2
null
null
null
null
UTF-8
C++
false
false
3,042
cpp
#include "stdafx.h" #include "aiclassifier.h" AiClassifier::AiClassifier(const wchar_t* classifier_file) : m_status(ERR), m_ai_type(UNKNOWN), m_ann(0), m_svm(0) { //load classifier m_svm = new SVMachine(classifier_file); if(m_svm->status() == 0) { m_ai_type = SVM; m_status = CLASSIFIER; return; } m_ann = new ANNetwork(classifier_file); if (m_ann->status() == 0) { if (m_ann->activation_function() == AnnLayer::SIGMOID) m_ai_type = SIGMOID_ANN; else if (m_ann->activation_function() == AnnLayer::TANH) m_ai_type = TANH_ANN; else m_ai_type = ANN; m_status = CLASSIFIER; return; } } AiClassifier::AiClassifier(const wchar_t* classifier_file, const wchar_t* features_file, const std::vector<ObjectSize>& objsizes) : m_status(ERR), m_ai_type(UNKNOWN), m_ann(0), m_svm(0) { //load classifier m_svm = new SVMachine(classifier_file); if(m_svm->status() == 0) { m_ai_type = SVM; m_status = CLASSIFIER; } m_ann = new ANNetwork(classifier_file); if (m_ann->status() == 0) { if (m_ann->activation_function() == AnnLayer::SIGMOID) m_ai_type = SIGMOID_ANN; else if (m_ann->activation_function() == AnnLayer::TANH) m_ai_type = TANH_ANN; else m_ai_type = ANN; m_status = CLASSIFIER; } if (m_status != CLASSIFIER) return; //load features file for (unsigned int i = 0; i < (unsigned int)objsizes.size(); i++) { ObjectSize osize = objsizes[i]; HaarFeatures* phf = new HaarFeatures(); if (phf->load(features_file, osize.width, osize.height) != 0 || phf->get_feature_vector().length() != get_input_dimension()) { delete phf; m_status = ERR; return; } else m_features.push_back(phf); } m_status = CLASSIFIER | FEATURE_EXTRACTOR; } AiClassifier::~AiClassifier() { if (m_ann != 0) delete m_ann; if (m_svm != 0) delete m_svm; for (unsigned int i = 0; i < (unsigned int)m_features.size(); i++) { HaarFeatures* phf = m_features[i]; delete phf; } m_features.clear(); }
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 81 ] ] ]
b93cc29b01619a27d780b636a854e87090a19827
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/WorkLayer/SharedFileList.h
a3336fe17d6bd1cf0c05539bcfbcefb664826bd1
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,355
h
//this file is part of eMule //Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program 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 General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "MapKey.h" class CKnownFileList; class CServerConnect; class CPartFile; class CKnownFile; class CPublishKeywordList; class CSafeMemFile; class CServer; class CCollection; struct UnknownFile_Struct{ CString strName; CString strDirectory; }; class CSharedFileList { //friend class CSharedFilesCtrl; friend class CClientReqSocket; public: CSharedFileList(CServerConnect* in_server); ~CSharedFileList(); void SendListToServer(); void Reload(); bool SafeAddKFile(CKnownFile* toadd, bool bOnlyAdd = false); void RepublishFile(CKnownFile* pFile); int GetAllSharedFile(CList<CKnownFile *, CKnownFile*> & filelist); bool RemoveFile(CKnownFile* toremove); CKnownFile* GetFileByID(const uchar* filehash) const; CKnownFile* GetFileByIndex(int index); bool IsFilePtrInList(const CKnownFile* file) const; bool IsSharedPath(CString strPath); void PublishNextTurn() { m_lastPublishED2KFlag=true; } void CreateOfferedFilePacket(CKnownFile* cur_file, CSafeMemFile* files, CServer* pServer, CUpDownClient* pClient = NULL); uint64 GetDatasize(uint64 &pbytesLargest) const; int GetCount() {return m_Files_map.GetCount(); } int GetHashingCount(); // SLUGFILLER SafeHash void UpdateFile(CKnownFile* toupdate); void AddFilesFromDirectory(const CString& rstrDirectory,bool bAddOnlyInKnownFile=false); void AddFileFromNewlyCreatedCollection(const CString& path, const CString& fileName); void HashFailed(UnknownFile_Struct* hashed); // SLUGFILLER: SafeHash void FileHashingFinished(CKnownFile* file); void ClearED2KPublishInfo(); void ClearKadSourcePublishInfo(); void Process(); void Publish(); void AddKeywords(CKnownFile* pFile); void RemoveKeywords(CKnownFile* pFile); void DeletePartFileInstances() const; bool IsUnsharedFile(const uchar* auFileHash) const; void CopySharedFileMap(CMap<CCKey,const CCKey&,CKnownFile*,CKnownFile*> &Files_Map); CKnownFile * GetKnownFile(const CCKey & key); bool HashNewFile(const CString & strFilepath); bool AddFile(CKnownFile* pFile); void Initialize(); CMutex m_mutWriteList; private: void FindSharedFiles(); void HashNextFile(); // SLUGFILLER: SafeHash bool IsHashing(const CString& rstrDirectory, const CString& rstrName); void RemoveFromHashing(CKnownFile* hashed); // SLUGFILLER: SafeHash CMap<CCKey,const CCKey&,CKnownFile*,CKnownFile*> m_Files_map; CMap<CSKey,const CSKey&, bool, bool> m_UnsharedFiles_map; CPublishKeywordList* m_keywords; CTypedPtrList<CPtrList, UnknownFile_Struct*> waitingforhash_list; CTypedPtrList<CPtrList, UnknownFile_Struct*> currentlyhashing_list; // SLUGFILLER: SafeHash CServerConnect* server; //CSharedFilesCtrl* output; void AddShareFilesFromDir(CString strDir, bool bSubDirectories,CStringList& strListAdded,bool bAddOnlyInKnownFile=false,bool bOnlyAddFileInSubDir=false); uint32 m_lastPublishED2K; bool m_lastPublishED2KFlag; int m_currFileSrc; int m_currFileNotes; int m_currFileKey; uint32 m_lastPublishKadSrc; uint32 m_lastPublishKadNotes; }; class CAddFileThread : public CWinThread { DECLARE_DYNCREATE(CAddFileThread) protected: CAddFileThread(); public: virtual BOOL InitInstance(); virtual int Run(); void SetValues(CSharedFileList* pOwner, LPCTSTR directory, LPCTSTR filename, CPartFile* partfile = NULL); private: CSharedFileList* m_pOwner; CString m_strDirectory; CString m_strFilename; CPartFile* m_partfile; };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 119 ] ] ]
8b9c190233972988de49cf0361c1c58c45879036
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/DoAnBaoMat/Chat_Client/CreateUserDlg.h
e534add05c4ec19e6249dd2cf21f4119f5ad490f
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
984
h
#pragma once #define WSAGETSELECTERROR(lParam) HIWORD(lParam) #define WSAGETSELECTEVENT(lParam) LOWORD(lParam) #define WM_SOCKET WM_USER+1 // CreateUserDlg dialog class CreateUserDlg : public CDialog { DECLARE_DYNAMIC(CreateUserDlg) public: CreateUserDlg(CWnd* pParent = NULL); // standard constructor CreateUserDlg(SOCKET clientSock); virtual ~CreateUserDlg(); // Dialog Data enum { IDD = IDD_DIALOGCreateAcc }; LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); void SockMsg(WPARAM wParam, LPARAM lParam); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButtoncancel(); afx_msg void OnBnClickedButtoncreateuser(); SOCKET m_socketClient; int m_msgType ; int m_msgLength; };
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 31 ] ] ]
bdaf674c1f6a21a3a8bde6aedcee57757e508bb0
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/Sources/Server/M-Server/Sources/Manager/WinSockMgr.h
bd3fac3108f8fb1925c9eace203c68200960044c
[]
no_license
asdlei00/project-jb
1cc70130020a5904e0e6a46ace8944a431a358f6
0bfaa84ddab946c90245f539c1e7c2e75f65a5c0
refs/heads/master
2020-05-07T21:41:16.420207
2009-09-12T03:40:17
2009-09-12T03:40:17
40,292,178
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,488
h
/* Author : ±èÁ¤ÈÆ(Bill) ([email protected]) Release Date : 2009. 04. 22. Project Name : WinSock Manager Version : 1.00.04 Test PC : CPU - Pentium(R) 4 2.40Ghz, RAM - 1 GB Graphic - Radeon 9600 Test OS : Windows XP Professional + SP3 Test Application : Visual Studio 2008 + SP1 Contents WinSock Manager Header 2009 ¨Ï Copyright MIS Corporation. All Rights Reserved. */ #pragma once #include "Common_Define.h" #include "MSG_Parser.h" #include "CMD_Handler.h" /* Structure : USER QUERY INFO Structure Release Date : 2009. 04. 28. Version : 1.00.00 */ typedef struct _USERQUERYINFO { CClientSock* pSock; int nCommandData; }USERQUERYINFO, *PUSERQUERYINFO; typedef map<int, USERQUERYINFO> USERQUERYINFO_MAP; typedef map<int, USERQUERYINFO>::iterator USERQUERYINFO_MAP_IT; typedef map<int, USERQUERYINFO>::value_type USERQUERYINFO_MAP_VALUE; /* Class : WinSock Manager Class Release Date : 2009. 04. 22. Version : 1.00.04 */ class CWinSockMgr { private: bool m_bServerRun; CServerSock m_ServerSock; // Main Server Socket CClientSock m_ServerMgrSock; // The socket for connecting to server manager int m_nUserCount; // User map counter USERINFO_MAP m_mapUserInfo; // User map for middle server char m_szServerMgrIP[32]; bool m_bServerMgrConnect; CMSGParser m_MSGParser; CCMDHandlerMgr m_CMDHandlerMgr; public: inline CServerSock* GetServerSock() { return &m_ServerSock; } inline CClientSock* GetServerMgrSock() { return &m_ServerMgrSock; } inline bool IsServerRun() { return m_bServerRun; } void SetServerRun(bool bServerRun); inline int GetUserSize() { return m_mapUserInfo.size(); } public: void InitServerSock(); void CloseServerSock(); bool ConnectToServerMgr(const char* pszIP); void CloseServerMgrSock(); public: HRESULT AddUser(USERINFO UserInfo); HRESULT DelUser(int nIndex); HRESULT DelUser(char* pszID); void ClearUser(); PUSERINFO GetUser(int nIndex); PUSERINFO GetUser(char* pszID); public: void OnAccept(); MSG_RET OnReceive(SOCKET Socket, int nTag); protected: MSG_RET OnReceiveFromServerMgr(SOCKET Socket); MSG_RET OnReceiveFromClient(SOCKET Socket); public: HRESULT InitWinSockMgr(const char* pszServerMgrIP = LOCAL_HOST_IP); void ReleaseWinSockMgr(); public: // The basic constructor CWinSockMgr(); // The basic destructor ~CWinSockMgr(); };
[ [ [ 1, 4 ], [ 6, 20 ], [ 22, 22 ], [ 27, 27 ], [ 40, 44 ], [ 46, 55 ], [ 58, 61 ], [ 63, 63 ], [ 65, 67 ], [ 71, 71 ], [ 74, 77 ], [ 79, 80 ], [ 87, 87 ], [ 97, 97 ], [ 100, 107 ] ], [ [ 5, 5 ], [ 21, 21 ], [ 23, 26 ], [ 28, 39 ], [ 45, 45 ], [ 56, 57 ], [ 62, 62 ], [ 64, 64 ], [ 68, 70 ], [ 72, 73 ], [ 78, 78 ], [ 81, 86 ], [ 88, 96 ], [ 98, 99 ] ] ]
55e20f37372ae615486186c87c9e7647666a744d
1e01b697191a910a872e95ddfce27a91cebc57dd
/BNFReadToken.h
eb3675da7059fafc6ba57a653a9d514ddb9050f8
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
2,174
h
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2002 CÚdric Lemaire 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifndef _BNFReadToken_h_ #define _BNFReadToken_h_ #include "GrfBlock.h" namespace CodeWorker { class DtaBNFScript; class BNFClause; class ExprScriptVariable; class BNFReadToken : public GrfCommand { private: DtaBNFScript* _pBNFScript; ExprScriptVariable* _pVariableToAssign; bool _bConcatVariable; std::vector<std::string> _listOfConstants; int _iClauseReturnType; bool _bContinue; bool _bNoCase; public: BNFReadToken(DtaBNFScript* pBNFScript, GrfBlock* pParent, bool bContinue, bool bNoCase); virtual ~BNFReadToken(); virtual void accept(DtaVisitor& visitor, DtaVisitorEnvironment& env); virtual bool isABNFCommand() const; void setVariableToAssign(ExprScriptVariable* pVariableToAssign, bool bConcat, BNFClause& theClause); inline void setConstantsToMatch(const std::vector<std::string>& listOfConstants) { _listOfConstants = listOfConstants; } virtual std::string toString() const; void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const; protected: virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility); virtual std::string executeExtraction(DtaScriptVariable&) const = 0; virtual std::string compileCppExtraction() const = 0; }; } #endif
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 64 ] ] ]
b9b93d7a8f07921e621c13234097ae4173326b68
a516c830714b91b1e20f13f66517aeb8de3c7b48
/COM_Component_Src/csDLMan.cpp
2ca10578ae84d6b5b7f7fe3d0ff0c117b052bb6a
[]
no_license
kuza55/csexwb2
73787a271e053a98f30eb90e8420dc3e36320d19
e96b2b3bdc478a4c3699cc8ddccb13457164fd21
refs/heads/master
2021-01-10T08:01:05.764097
2007-08-29T11:15:47
2007-08-29T11:15:47
51,132,957
1
0
null
null
null
null
UTF-8
C++
false
false
69,656
cpp
// csDLMan.cpp : Implementation of CcsDLMan #include "stdafx.h" #include "CsExWBDLMan.h" #include "csDLMan.h" #include "ProtocolCF.h" //hookShell = SetWindowsHookEx(WH_SHELL, (HOOKPROC)ShellHookCallback, g_appInstance, threadID); /////////////////////////////////////////////// //Macros BOOL VARIANTBOOLTOBOOL(VARIANT_BOOL x) { return (x == VARIANT_TRUE) ? TRUE : FALSE; } bool VARIANTBOOLTObool(VARIANT_BOOL x) { return (x == VARIANT_TRUE) ? true : false; } VARIANT_BOOL BOOLTOVARIANTBOOL(BOOL x) { return (x) ? VARIANT_TRUE : VARIANT_FALSE; } VARIANT_BOOL boolTOVARIANTBOOL(bool x) { return (x) ? VARIANT_TRUE : VARIANT_FALSE; } /////////////////////////////////////////////// //APP typedef PassthroughAPP::CMetaFactory<PassthroughAPP::CComClassFactoryProtocol, WBPassthru> MetaFactory; //////////////////////////////////////////////// //Windows hooks structure, vars and callbacks /* Hook Scope WH_CALLWNDPROC Thread or global WH_CALLWNDPROCRET Thread or global WH_CBT Thread or global WH_DEBUG Thread or global WH_FOREGROUNDIDLE Thread or global WH_GETMESSAGE Thread or global WH_JOURNALPLAYBACK Global only WH_JOURNALRECORD Global only WH_KEYBOARD Thread or global WH_KEYBOARD_LL Global only WH_MOUSE Thread or global WH_MOUSE_LL Global only WH_MSGFILTER Thread or global WH_SHELL Thread or global WH_SYSMSGFILTER Global only */ typedef struct WBHOOKDATA { int nType; HWND hwndTarget; BOOL bHookInstalled; UINT uiHookMsgID; HOOKPROC hkprc; HHOOK hhook; } WBHOOKDATA; #define NUMHOOKS 12 static WBHOOKDATA wbhookdata[NUMHOOKS]; static LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK MessageProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK ForegroundIdleProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK CallWndRetProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK SysMsgProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK ShellProc(int nCode, WPARAM wParam, LPARAM lParam); static int nCode_CBTProc; //(CBTProc) static int nCode_MessageProc; //(MessageProc) static int nCode_SysMsgProc; //(SysMsgProc) static int nCode_ShellProc; //(ShellProc) #define H_CALLWNDPROC 0 //CallWndProc #define H_CBT 1 //CBTProc #define H_GETMESSAGE 2 //GetMsgProc #define H_KEYBOARD 3 //KeyboardProc #define H_MOUSE 4 //MouseProc #define H_MSGFILTER 5 //MessageProc #define H_KEYBOARD_LL 6 //LowLevelKeyboardProc #define H_MOUSE_LL 7 //LowLevelMouseProc #define H_FOREGROUNDIDLE 8 //ForegroundIdleProc #define H_CALLWNDPROCRET 9 //CallWndRetProc #define H_SYSMSGFILTER 10 //SysMsgProc #define H_SHELL 11 //ShellProc //Define Hook msgs //Guids generated using sdk GuidGen util #define UWM_MOUSE_HOOKPROC_MSG _T("UWM_MOUSE-{A89C6106-B837-4ce9-A1D2-B55B833272D2}") #define UWM_KEYBOARD_HOOKPROC_MSG _T("UWM_KEYBOARD-{DD6BA45D-0A52-442b-A58D-75273C3C1E0D}") #define UWM_LOWLEVELKEYBOARD_HOOKPROC_MSG _T("UWM_LOWLEVELKEYBOARD-{636CD093-89D0-46da-98D8-A756B190033A}") #define UWM_CALLWND_HOOKPROC_MSG _T("UWM_CALLWND-{6CF01631-BF0B-4479-B86A-198C63285B5E}") #define UWM_CBT_HOOKPROC_MSG _T("UWM_CBT-{AD48A334-EE9C-4ef9-AFE4-0EB2483DE790}") #define UWM_GETMSG_HOOKPROC_MSG _T("UWM_GETMSG-{2EEFC149-231C-4636-B24F-1788CA63AE0A}") #define UWM_MESSAGE_HOOKPROC_MSG _T("UWM_MESSAGE-{9508F07B-50F9-4d19-B6C2-99FE5F7E99C1}") #define UWM_LOWLEVELMOUSE_HOOKPROC_MSG _T("UWM_LOWLEVELMOUSE-{DF69AA88-8F7E-44ac-A1B3-3CED59C77E39}") #define UWM_FORGROUNDIDLE_HOOKPROC_MSG _T("UWM_FORGROUNDIDLE-{88E3AE4F-103F-4549-B24F-8964C6335706}") #define UWM_CALLWNDRET_HOOKPROC_MSG _T("UWM_CALLWNDRET-{6C5FD4ED-B340-4563-9F74-908F8E292635}") #define UWM_SYSMSG_HOOKPROC_MSG _T("UWM_SYSMSG-{13480F7E-5357-4eb3-979C-94CB6BE2B106}") #define UMW_SHELL_HOOKPROC_MSG _T("UMW_SHELL-{1E09A616-CBF9-4aaa-9A15-131B4A46A6E1}") ///////////////////////////////////////////////////////////////////////////// // CcsDLMan STDMETHODIMP CcsDLMan::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IcsDLMan }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } CcsDLMan::CcsDLMan() { m_Uid = 0; m_IEServerHwnd = NULL; //Add this instance to our global ptrs LPVOID thisPtr = reinterpret_cast<LPVOID>(this); //Just in case if(gCtrlInstances.Find(thisPtr) == -1) gCtrlInstances.Add(thisPtr); nCode_CBTProc = 0; nCode_MessageProc = 0; nCode_SysMsgProc = 0; nCode_ShellProc = 0; wbhookdata[H_CALLWNDPROC].bHookInstalled = FALSE; wbhookdata[H_CALLWNDPROC].hhook = NULL; wbhookdata[H_CALLWNDPROC].hkprc = (HOOKPROC)CallWndProc; wbhookdata[H_CALLWNDPROC].hwndTarget = NULL; wbhookdata[H_CALLWNDPROC].nType = WH_CALLWNDPROC; wbhookdata[H_CALLWNDPROC].uiHookMsgID = ::RegisterWindowMessage(UWM_CALLWND_HOOKPROC_MSG); wbhookdata[H_CBT].bHookInstalled = FALSE; wbhookdata[H_CBT].hhook = NULL; wbhookdata[H_CBT].hkprc = (HOOKPROC)CBTProc; wbhookdata[H_CBT].hwndTarget = NULL; wbhookdata[H_CBT].nType = WH_CBT; wbhookdata[H_CBT].uiHookMsgID = ::RegisterWindowMessage(UWM_CBT_HOOKPROC_MSG); wbhookdata[H_GETMESSAGE].bHookInstalled = FALSE; wbhookdata[H_GETMESSAGE].hhook = NULL; wbhookdata[H_GETMESSAGE].hkprc = (HOOKPROC)GetMsgProc; wbhookdata[H_GETMESSAGE].hwndTarget = NULL; wbhookdata[H_GETMESSAGE].nType = WH_GETMESSAGE; wbhookdata[H_GETMESSAGE].uiHookMsgID = ::RegisterWindowMessage(UWM_GETMSG_HOOKPROC_MSG); wbhookdata[H_KEYBOARD].bHookInstalled = FALSE; wbhookdata[H_KEYBOARD].hhook = NULL; wbhookdata[H_KEYBOARD].hkprc = (HOOKPROC)KeyboardProc; wbhookdata[H_KEYBOARD].hwndTarget = NULL; wbhookdata[H_KEYBOARD].nType = WH_KEYBOARD; wbhookdata[H_KEYBOARD].uiHookMsgID = ::RegisterWindowMessage(UWM_KEYBOARD_HOOKPROC_MSG); wbhookdata[H_MOUSE].bHookInstalled = FALSE; wbhookdata[H_MOUSE].hhook = NULL; wbhookdata[H_MOUSE].hkprc = (HOOKPROC)MouseProc; wbhookdata[H_MOUSE].hwndTarget = NULL; wbhookdata[H_MOUSE].nType = WH_MOUSE; wbhookdata[H_MOUSE].uiHookMsgID = ::RegisterWindowMessage(UWM_MOUSE_HOOKPROC_MSG); wbhookdata[H_MSGFILTER].bHookInstalled = FALSE; wbhookdata[H_MSGFILTER].hhook = NULL; wbhookdata[H_MSGFILTER].hkprc = (HOOKPROC)MessageProc; wbhookdata[H_MSGFILTER].hwndTarget = NULL; wbhookdata[H_MSGFILTER].nType = WH_MSGFILTER; wbhookdata[H_MSGFILTER].uiHookMsgID = ::RegisterWindowMessage(UWM_MESSAGE_HOOKPROC_MSG); wbhookdata[H_KEYBOARD_LL].bHookInstalled = FALSE; wbhookdata[H_KEYBOARD_LL].hhook = NULL; wbhookdata[H_KEYBOARD_LL].hkprc = (HOOKPROC)LowLevelKeyboardProc; wbhookdata[H_KEYBOARD_LL].hwndTarget = NULL; wbhookdata[H_KEYBOARD_LL].nType = WH_KEYBOARD_LL; wbhookdata[H_KEYBOARD_LL].uiHookMsgID = ::RegisterWindowMessage(UWM_LOWLEVELKEYBOARD_HOOKPROC_MSG); wbhookdata[H_MOUSE_LL].bHookInstalled = FALSE; wbhookdata[H_MOUSE_LL].hhook = NULL; wbhookdata[H_MOUSE_LL].hkprc = (HOOKPROC)LowLevelMouseProc; wbhookdata[H_MOUSE_LL].hwndTarget = NULL; wbhookdata[H_MOUSE_LL].nType = WH_MOUSE_LL; wbhookdata[H_MOUSE_LL].uiHookMsgID = ::RegisterWindowMessage(UWM_LOWLEVELMOUSE_HOOKPROC_MSG); wbhookdata[H_FOREGROUNDIDLE].bHookInstalled = FALSE; wbhookdata[H_FOREGROUNDIDLE].hhook = NULL; wbhookdata[H_FOREGROUNDIDLE].hkprc = (HOOKPROC)ForegroundIdleProc; wbhookdata[H_FOREGROUNDIDLE].hwndTarget = NULL; wbhookdata[H_FOREGROUNDIDLE].nType = WH_FOREGROUNDIDLE; wbhookdata[H_FOREGROUNDIDLE].uiHookMsgID = ::RegisterWindowMessage(UWM_FORGROUNDIDLE_HOOKPROC_MSG); wbhookdata[H_CALLWNDPROCRET].bHookInstalled = FALSE; wbhookdata[H_CALLWNDPROCRET].hhook = NULL; wbhookdata[H_CALLWNDPROCRET].hkprc = (HOOKPROC)CallWndRetProc; wbhookdata[H_CALLWNDPROCRET].hwndTarget = NULL; wbhookdata[H_CALLWNDPROCRET].nType = WH_CALLWNDPROCRET; wbhookdata[H_CALLWNDPROCRET].uiHookMsgID = ::RegisterWindowMessage(UWM_CALLWNDRET_HOOKPROC_MSG); wbhookdata[H_SYSMSGFILTER].bHookInstalled = FALSE; wbhookdata[H_SYSMSGFILTER].hhook = NULL; wbhookdata[H_SYSMSGFILTER].hkprc = (HOOKPROC)SysMsgProc; wbhookdata[H_SYSMSGFILTER].hwndTarget = NULL; wbhookdata[H_SYSMSGFILTER].nType = WH_SYSMSGFILTER; wbhookdata[H_SYSMSGFILTER].uiHookMsgID = ::RegisterWindowMessage(UWM_SYSMSG_HOOKPROC_MSG); wbhookdata[H_SHELL].bHookInstalled = FALSE; wbhookdata[H_SHELL].hhook = NULL; wbhookdata[H_SHELL].hkprc = (HOOKPROC)ShellProc; wbhookdata[H_SHELL].hwndTarget = NULL; wbhookdata[H_SHELL].nType = WH_SHELL; wbhookdata[H_SHELL].uiHookMsgID = ::RegisterWindowMessage(UMW_SHELL_HOOKPROC_MSG); } CcsDLMan::~CcsDLMan() { //Remove our instance //Otherwise, we will crash //Attempting to access a deleted object via an invalid ptr if(gCtrlInstances.GetSize() > 0) { LPVOID thisPtr = reinterpret_cast<LPVOID>(this); int i = gCtrlInstances.Find(thisPtr); if( i > -1) { gCtrlInstances[i] = NULL; gCtrlInstances.RemoveAt(i); } } int iSize = m_arrDL.GetSize(); if(iSize > 0) { int i = 0; for(i = 0; i < iSize ; i++) { if( m_arrDL[i] ) { m_arrDL[i] = NULL; } } m_arrDL.RemoveAll(); } //Unhook? if(wbhookdata[H_CALLWNDPROC].hhook) UnhookWindowsHookEx(wbhookdata[H_CALLWNDPROC].hhook); if(wbhookdata[H_CBT].hhook) UnhookWindowsHookEx(wbhookdata[H_CBT].hhook); if(wbhookdata[H_GETMESSAGE].hhook) UnhookWindowsHookEx(wbhookdata[H_GETMESSAGE].hhook); if(wbhookdata[H_KEYBOARD].hhook) UnhookWindowsHookEx(wbhookdata[H_KEYBOARD].hhook); if(wbhookdata[H_MOUSE].hhook) UnhookWindowsHookEx(wbhookdata[H_MOUSE].hhook); if(wbhookdata[H_MSGFILTER].hhook) UnhookWindowsHookEx(wbhookdata[H_MSGFILTER].hhook); if(wbhookdata[H_KEYBOARD_LL].hhook) UnhookWindowsHookEx(wbhookdata[H_KEYBOARD_LL].hhook); if(wbhookdata[H_MOUSE_LL].hhook) UnhookWindowsHookEx(wbhookdata[H_MOUSE_LL].hhook); if(wbhookdata[H_FOREGROUNDIDLE].hhook) UnhookWindowsHookEx(wbhookdata[H_FOREGROUNDIDLE].hhook); if(wbhookdata[H_CALLWNDPROCRET].hhook) UnhookWindowsHookEx(wbhookdata[H_CALLWNDPROCRET].hhook); if(wbhookdata[H_SYSMSGFILTER].hhook) UnhookWindowsHookEx(wbhookdata[H_SYSMSGFILTER].hhook); if(wbhookdata[H_SHELL].hhook) UnhookWindowsHookEx(wbhookdata[H_SHELL].hhook); nCode_CBTProc = 0; nCode_MessageProc = 0; nCode_SysMsgProc = 0; nCode_ShellProc = 0; } STDMETHODIMP CcsDLMan::get_HTTPSprotocol(VARIANT_BOOL *pVal) { *pVal = (gb_IsHttpsRegistered) ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } STDMETHODIMP CcsDLMan::put_HTTPSprotocol(VARIANT_BOOL newVal) { if( (m_IEServerHwnd == NULL) || (!::IsWindow(m_IEServerHwnd)) ) return AtlReportError(CLSID_csDLMan, _T("To send events to corresponding control, HWNDInternetExplorerServer property must be set."), IID_IcsDLMan,DISP_E_EXCEPTION); if( (newVal == VARIANT_TRUE) && (gb_IsHttpsRegistered == TRUE) ) { return AtlReportError(CLSID_csDLMan, _T("HTTPS protocol is already registered."), IID_IcsDLMan,DISP_E_EXCEPTION); } //Get the current InternetSession CComPtr<IInternetSession> spSession; CoInternetGetSession(0, &spSession, 0); if(newVal == VARIANT_TRUE) { //Register MetaFactory::CreateInstance(CLSID_HttpSProtocol, &m_spCFHTTPS); spSession->RegisterNameSpace(m_spCFHTTPS, CLSID_NULL, L"https", 0, 0, 0); gb_IsHttpsRegistered = TRUE; } else { //Unregister spSession->UnregisterNameSpace(m_spCFHTTPS, L"https"); m_spCFHTTPS.Release(); gb_IsHttpsRegistered = FALSE; } return S_OK; } STDMETHODIMP CcsDLMan::get_HTTPprotocol(VARIANT_BOOL *pVal) { *pVal = (gb_IsHttpRegistered) ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } STDMETHODIMP CcsDLMan::put_HTTPprotocol(VARIANT_BOOL newVal) { if( (m_IEServerHwnd == NULL) || (!::IsWindow(m_IEServerHwnd)) ) return AtlReportError(CLSID_csDLMan, _T("To send events to corresponding control, HWNDInternetExplorerServer property must be set."), IID_IcsDLMan,DISP_E_EXCEPTION); if( (newVal == VARIANT_TRUE) && (gb_IsHttpRegistered == TRUE) ) { return AtlReportError(CLSID_csDLMan, _T("HTTP protocol is already registered."), IID_IcsDLMan,DISP_E_EXCEPTION); } //Get the current InternetSession CComPtr<IInternetSession> spSession; CoInternetGetSession(0, &spSession, 0); if(newVal == VARIANT_TRUE) { //Register MetaFactory::CreateInstance(CLSID_HttpProtocol, &m_spCFHTTP); spSession->RegisterNameSpace(m_spCFHTTP, CLSID_NULL, L"http", 0, 0, 0); gb_IsHttpRegistered = TRUE; } else { //Unregister spSession->UnregisterNameSpace(m_spCFHTTP, L"http"); m_spCFHTTP.Release(); gb_IsHttpRegistered = FALSE; } return S_OK; } STDMETHODIMP CcsDLMan::DownloadUrlAsync(BSTR URL, long *DLUID) { CComPtr<IMoniker> pmk; CComPtr<IBindCtx> pbc; //CComPtr<IStream> pstm; IStream *pstm; HRESULT hr; if( (m_IEServerHwnd == NULL) || (!::IsWindow(m_IEServerHwnd)) ) return AtlReportError(CLSID_csDLMan, _T("To send events to corresponding control, HWNDInternetExplorerServer property must be set."), IID_IcsDLMan,DISP_E_EXCEPTION); WBBSCBFileDL *pBSCB = new WBBSCBFileDL(); if(!pBSCB) { return AtlReportError(CLSID_csDLMan, _T("Unable to create Download class."), IID_IcsDLMan,DISP_E_EXCEPTION); } //Pass uid to client to be used to cancel a dl m_Uid++; *DLUID = m_Uid; pBSCB->InitByClient(m_Uid, this, URL, m_IEServerHwnd); USES_CONVERSION; //Create URLMonikor //http://blogs.msdn.com/ie/archive/2006/09/13/752347.aspx hr = CreateURLMonikerEx(NULL, OLE2W(URL), &pmk, URL_MK_UNIFORM); //hr = CreateURLMoniker(NULL, OLE2W(URL), &pmk); if(FAILED(hr)) { delete pBSCB; return AtlReportError(CLSID_csDLMan, _T("Unable to create URL Moniker."),IID_IcsDLMan,DISP_E_EXCEPTION); } //Create BindCtx and register BSCB at the same time, AddRef is called hr = CreateAsyncBindCtx(0, pBSCB, NULL, &pbc); if(FAILED(hr)) { delete pBSCB; if(pmk) pmk.Release(); return AtlReportError(CLSID_csDLMan, _T("Unable to create AsyncBindCtx."),IID_IcsDLMan,DISP_E_EXCEPTION); } //Bind stream to storage hr = pmk->BindToStorage(pbc,NULL,IID_IStream,(void**)&pstm); if(FAILED(hr)) { if(pbc) pbc.Release(); delete pBSCB; if(pmk) pmk.Release(); return AtlReportError(CLSID_csDLMan, _T("BindToStorage failed."),IID_IcsDLMan,DISP_E_EXCEPTION); } //Add to Ptrarray m_arrDL.Add(pBSCB); return S_OK; } STDMETHODIMP CcsDLMan::Download(IMoniker *pmk,IBindCtx *pbc,DWORD dwBindVerb, LONG grfBINDF, BINDINFO *pBindInfo, LPCOLESTR pszHeaders, LPCOLESTR pszRedir, UINT uiCP) { HRESULT hr; //Stream will be released in the BSCB OnDataArrival IStream *pstm; //Attempt to create our BindStatusCallBack WBBSCBFileDL *filedl = NULL; //Returns a NonAddRef pointer to a new BSCB //AddRef is called on this BSCB during a successfull call //to RegisterBindStatusCallback if(WBCreateBSCBFileDL(&filedl) != S_OK) { return E_FAIL; } //Init the BSCB m_Uid++; filedl->InitByUser(m_Uid, this, pszHeaders, m_IEServerHwnd); IBindStatusCallback *pPrevBSCB = NULL; hr = RegisterBindStatusCallback(pbc, reinterpret_cast<IBindStatusCallback*>(filedl), &pPrevBSCB, 0L); /* Exception to the rule RegisterBindStatusCallback return E_FAIL Cause: Content_Disposition header returned from a server in response to a file download via a post or ,.. Example: downloading attachements from Hotmail, Yahoo, ... Unfortunately, due to no documentation regarding an E_FAIL return, and more specifically, regarding RegisterBindStatusCallback internal workings, I had to resort to using RevokeObjectParam on the previous BSCB and in my implementation of BSCB, relay certain calls to the previous BSCB to make DL work. I do not know if this is a bug or done intentionaly. */ /* KB article http://support.microsoft.com/default.aspx?scid=kb;en-us;274201 Notifies the client application that this resource contained a Content-Disposition header that indicates that this resource is an attachment. The content of this resource should not be automatically displayed. Client applications should request permission from the user. This value was added for Internet Explorer 5. */ if( (FAILED(hr)) && (pPrevBSCB) ) { //RevokeObjectParam for current BSCB, so we can register our BSCB LPOLESTR oParam = L"_BSCB_Holder_"; hr = pbc->RevokeObjectParam(oParam); if(SUCCEEDED(hr)) { //Attempt register again, should succeed now hr = RegisterBindStatusCallback(pbc, reinterpret_cast<IBindStatusCallback*>(filedl), 0, 0L); if(SUCCEEDED(hr)) { filedl->m_pPrevBSCB = pPrevBSCB; //Need to add ref to our DLMan filedl->AddRef(); pPrevBSCB->AddRef(); filedl->m_pBindCtx = pbc; pbc->AddRef(); } } } if(SUCCEEDED(hr)) { this->m_arrDL.Add(filedl); hr = pmk->BindToStorage(pbc, 0, IID_IStream, (void**)&pstm); } else { delete filedl; } return hr; } HRESULT CcsDLMan::WBCreateBSCBFileDL(WBBSCBFileDL **ppTargetBSCBFileDL) { if(ppTargetBSCBFileDL == NULL) return E_INVALIDARG; *ppTargetBSCBFileDL = new WBBSCBFileDL(); if(*ppTargetBSCBFileDL == NULL) return E_OUTOFMEMORY; return S_OK; } //This has to be set first and passed to ever BSCB for verification //before sending events, just in case client was deleted. STDMETHODIMP CcsDLMan::get_HWNDInternetExplorerServer(long *pVal) { *pVal = (long)m_IEServerHwnd; return S_OK; } STDMETHODIMP CcsDLMan::put_HWNDInternetExplorerServer(long newVal) { m_IEServerHwnd = (HWND)newVal; if( (m_IEServerHwnd == NULL) || (!::IsWindow(m_IEServerHwnd)) ) return AtlReportError(CLSID_csDLMan, _T("IE Server HWND must be a valid window!."), IID_IcsDLMan,DISP_E_EXCEPTION); return S_OK; } BOOL CcsDLMan::RemoveBSCBFromDLArr(long Uid) { int iSize = m_arrDL.GetSize(); if(iSize > 0) { int i = 0; for(i = 0; i < iSize ; i++) { if( (m_arrDL[i]) && (m_arrDL[i]->m_Uid == Uid) ) { m_arrDL[i] = NULL; m_arrDL.RemoveAt(i); return TRUE; } } } return FALSE; } HRESULT CcsDLMan::CancelFileDl(long Uid) { int isize = m_arrDL.GetSize(); if(isize > 0) { int i = 0; for(i = 0; i < isize ; i++) { if( (m_arrDL[i]) && (m_arrDL[i]->m_Uid == Uid) && (m_arrDL[i]->IsDownloading() == true) ) { //This should trigger a stop binding //which should notify the client m_arrDL[i]->CancelDL(); } } } return S_OK; } STDMETHODIMP CcsDLMan::CancelFileDownload(long DlUid) { if(CancelFileDl(DlUid) != S_OK) return AtlReportError(CLSID_csDLMan, _T("Unable to cancel file download."), IID_IcsDLMan,DISP_E_EXCEPTION); return S_OK; } STDMETHODIMP CcsDLMan::HookProcNCode(WINDOWSHOOK_TYPES lHookType, long *nCode) { if(lHookType == WHT_CBT) { *nCode = (long)nCode_CBTProc; } else if(lHookType == WHT_MSGFILTER) { *nCode = (long)nCode_MessageProc; } else if(lHookType == WHT_SYSMSGFILTER) { *nCode = (long)nCode_SysMsgProc; } else *nCode = -1; return S_OK; } //lUWMHookMsgID is our own registered messageid which is passed along //SendMessageTimeout to the client app so they can intercept the hook callback STDMETHODIMP CcsDLMan::SetupWindowsHook(WINDOWSHOOK_TYPES lHookType, long hwndTargetWnd, VARIANT_BOOL bStart, long *lUWMHookMsgID) { BOOL bInstall = VARIANTBOOLTOBOOL(bStart); if( (bInstall == TRUE) && (wbhookdata[lHookType].bHookInstalled == FALSE) ) { if(hwndTargetWnd == 0) return AtlReportError(CLSID_csDLMan, _T("Windows Hook requires a valid window handle!") ,IID_IcsDLMan,DISP_E_EXCEPTION); else wbhookdata[lHookType].hwndTarget = (HWND)hwndTargetWnd; wbhookdata[lHookType].hhook = SetWindowsHookEx( wbhookdata[lHookType].nType, wbhookdata[lHookType].hkprc, //_Module.GetModuleInstance(), GetCurrentThreadId()); _Module.GetModuleInstance(), 0); //(HINSTANCE) NULL, GetCurrentThreadId()); //Check and send back hook msgid for the client to intercept if(wbhookdata[lHookType].hhook) { *lUWMHookMsgID = (long)wbhookdata[lHookType].uiHookMsgID; wbhookdata[lHookType].bHookInstalled = bInstall; } else { return AtlReportError(CLSID_csDLMan, _T("Failed to install Hook!") ,IID_IcsDLMan,DISP_E_EXCEPTION); } } else if( (bInstall == FALSE) && (wbhookdata[lHookType].bHookInstalled == TRUE) ) { if(wbhookdata[lHookType].hhook) UnhookWindowsHookEx(wbhookdata[lHookType].hhook); wbhookdata[lHookType].bHookInstalled = bInstall; wbhookdata[lHookType].hwndTarget = NULL; } return S_OK; } ///////////////////////////////////////////////////////////////////// //WBBSCBFileDL ///////////////////////////////////////////////////////////////////// //Constructor WBBSCBFileDL::WBBSCBFileDL() { ResetInternalVars(); } WBBSCBFileDL::~WBBSCBFileDL() { if(hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } } //Urlmon.dll uses the QueryInterface method on your implementation of //IBindStatusCallback to obtain a pointer to your IHttpNegotiate interface. //Only if we have initiated the download from code by creating own Moniker STDMETHODIMP WBBSCBFileDL::QueryInterface(REFIID iid, void ** ppvObject) { if(ppvObject == NULL) return E_INVALIDARG; *ppvObject = NULL; if( (iid==IID_IBindStatusCallback) || (iid==IID_IUnknown) ) { *ppvObject = (IBindStatusCallback*)this; } else if ( iid == IID_IHttpNegotiate ) { *ppvObject = (IHttpNegotiate*)this; } else if(iid == IID_IAuthenticate) { *ppvObject = (IAuthenticate*)this; } if (NULL != *ppvObject) { AddRef(); return S_OK; } // { // OLECHAR wszBuff[39]; // int i = StringFromGUID2(iid, wszBuff, 39); // TCHAR szBuff[39]; // i = WideCharToMultiByte(CP_ACP, 0, wszBuff, -1, szBuff, 39, NULL, NULL); // vbLog((LPCTSTR)szBuff,_T("WBBSCBFileDL::QueryInterface")); // } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE WBBSCBFileDL::AddRef() { return ++m_cRef; } ULONG STDMETHODCALLTYPE WBBSCBFileDL::Release() { if(--m_cRef == 0) { delete this; return 0; } return m_cRef; } void WBBSCBFileDL::ResetInternalVars(void) { m_cRef = 0; m_Uid = 0; m_pPrevBSCB = NULL; m_pBindCtx = NULL; m_vboolCancelDL = VARIANT_FALSE; m_bCancelled = FALSE; m_fRedirect = FALSE; m_pBinding = NULL; m_pstm = NULL; m_cbOld = 0; hFile = INVALID_HANDLE_VALUE; m_Events = NULL; m_hwndEvents = NULL; m_SendProgressEvent = VARIANT_TRUE; m_strRedirectedURL = L""; m_vboolResuming = VARIANT_FALSE; m_hwndClient = NULL; } //This is used when client app initiates the dl //In this case OnResponse and BeginningTransaction are called //Here we we can resume a broken dl using OnResponse, by sending additional headers bool WBBSCBFileDL::InitByClient(long uID, CcsDLMan *EventsPtr, BSTR lpUrl, HWND client) { m_Uid = uID; m_Events = EventsPtr; fUrl = lpUrl; m_hwndClient = client; return true; } //This is used when client initiates dl, clicking on a dl link //In this case OnResponse and BeginningTransaction are never called. //WB queries our service provider for a download manager interface and calls download method //in which case we create an instance of this class and set up dl bool WBBSCBFileDL::InitByUser(long uID, CcsDLMan *pHost, LPCOLESTR UrlMonExtraHeaders, HWND client) { if(UrlMonExtraHeaders) m_strDLManExtraHeaders = UrlMonExtraHeaders; m_Events = pHost; m_Uid = uID; m_hwndClient = client; return true; } //IAuthenticate STDMETHODIMP WBBSCBFileDL::Authenticate(HWND *phwnd, LPWSTR *pszUsername, LPWSTR *pszPassword) { if (!phwnd || !pszUsername || !pszPassword) { return E_INVALIDARG; } *phwnd = NULL; *pszUsername = NULL; *pszPassword = NULL; CComBSTR strUsername(L""); CComBSTR strPassword(L""); //Default, do not cancel VARIANT_BOOL bCancel = VARIANT_TRUE; //Fire event to obtain Uname+Password if( (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) m_Events->Fire_OnFileDLAuthenticate(m_Uid, &strUsername, &strPassword, &bCancel); //Cancelled, bail if(bCancel == VARIANT_TRUE) return E_ACCESSDENIED; //allocate mem WCHAR *wszUsername = (WCHAR *)CoTaskMemAlloc((strUsername.Length()+1) *sizeof(WCHAR)); if(!wszUsername) { return E_OUTOFMEMORY; } WCHAR *wszPassword = (WCHAR *)CoTaskMemAlloc((strPassword.Length()+1) *sizeof(WCHAR)); if(!wszPassword) { return E_OUTOFMEMORY; } USES_CONVERSION; //Copy wcscpy(wszUsername, strUsername.m_str); //OLE2W(strUsername)); wszUsername[strUsername.Length()] = (WCHAR)NULL; wcscpy(wszPassword, strPassword.m_str); //OLE2W(strPassword)); wszPassword[strPassword.Length()] = (WCHAR)NULL; //Assign to out params *pszUsername = wszUsername; *pszPassword = wszPassword; return S_OK; } //IBindStatusCallback STDMETHODIMP WBBSCBFileDL::OnStartBinding(DWORD dwReserved, IBinding * pib) { //Although, MSDN, states that simply returning E_FAIL should stop the DL. But as ususal //it does not work as documented. Well, returnning E_FAIL will not stop the save as dlg //from poping up. Releasing IBinding and returning E_FAIL does the trick. //Cache the URLMON-provided IBinding interface so that we can control the download, if(m_pBinding) m_pBinding->Release(); m_pBinding = pib; if(m_pBinding) { m_pBinding->AddRef(); } if(m_pPrevBSCB) { m_pPrevBSCB->OnStopBinding(HTTP_STATUS_OK, NULL); } return S_OK; } STDMETHODIMP WBBSCBFileDL::GetPriority(LONG * pnPriority) { return E_NOTIMPL; } STDMETHODIMP WBBSCBFileDL::OnLowResource(DWORD reserved) { return E_NOTIMPL; } STDMETHODIMP WBBSCBFileDL::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { USES_CONVERSION; //Default = Continue download m_vboolCancelDL = VARIANT_FALSE; //After this call we get OnDataArrival //Notify client and set internal vars up if( ulStatusCode == BINDSTATUS_BEGINDOWNLOADDATA) { //Get the URL resource display name and extract filename + extension CUrlParts parts; fFullSavePath.Empty(); fFileName.Empty(); fFileExt.Empty(); fFileSize.Empty(); fUrl.Empty(); fUrl = szStatusText; //HTTP_QUERY_CONTENT_TYPE (text/html) //HTTP_QUERY_CONTENT_LENGTH //HTTP_QUERY_RAW_HEADERS_CRLF CComBSTR m_bstrResponseHeaders; if(m_pBinding) { //Get raw request headers and send them to client CComPtr<IWinInetHttpInfo> spWinInetHttpInfo; CComPtr<IBinding> pBinding = m_pBinding; HRESULT hrTemp = pBinding->QueryInterface(IID_IWinInetHttpInfo, (void**)&spWinInetHttpInfo); if( (SUCCEEDED(hrTemp)) && (spWinInetHttpInfo) ) { DWORD size = 0; //sizeof(DWORD) DWORD flags = 0; //Get all headers hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, 0, &size, &flags, 0); if(SUCCEEDED(hrTemp) && (size > 0)) { LPSTR pbuf = new char[size+1]; if(pbuf) { pbuf[size] = '\0'; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, pbuf, &size, &flags, 0); if( (SUCCEEDED(hrTemp)) && (pbuf[0] != '\0') ) { //pbuf should contain all request headers m_bstrResponseHeaders.Append(pbuf); } delete[] pbuf; } } size = 0; flags = 0; //Get the filesize, if content-length header is provided by server | HTTP_QUERY_FLAG_NUMBER hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, 0, &size, &flags, 0); if(SUCCEEDED(hrTemp) && (size > 0)) { LPSTR pbuf = new char[size+1]; if(pbuf) { pbuf[size] = '\0'; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, pbuf, &size, &flags, 0); if( (SUCCEEDED(hrTemp)) && (pbuf[0] != '\0') ) { //pbuf should contain size in bytes. i.e. 24955 fFileSize.Append(pbuf); } delete[] pbuf; } } //Grab the Content_Disposition header to get the filename //Content-Disposition: attachment; filename="Somefile.zip" if(m_pPrevBSCB) { size = 0; flags = 0; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_CONTENT_DISPOSITION, 0, &size, &flags, 0); if(SUCCEEDED(hrTemp) && (size > 0)) { LPSTR pbuf = new char[size+1]; if(pbuf) { pbuf[size] = '\0'; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_CONTENT_DISPOSITION, pbuf, &size, &flags, 0); if( (SUCCEEDED(hrTemp)) && (pbuf[0] != '\0') ) { int i = size - 2; CTmpBuffer final(size); while ( ( i > -1 ) && (pbuf[i] != '"') ) { if(pbuf[i] == '.') { LPSTR pext = &pbuf[i]; final.Append(pext, size - (i+1)); fFileExt.Append(final); } --i; } if( i > 0 ) { LPSTR pname = &pbuf[i+1]; //=" final.ResetBuffer(); final.Append(pname, size - (i+2)); fFileName.Append(final); } } delete[] pbuf; } } } } //No wininet }//No binding //Get file name and extension, if empty if(fFileName.Length() == 0) { if(parts.SplitUrl(fUrl) == true) { if(parts.GetFileNameLen() > 0) { fFileName = parts.GetFileNameAsBSTR(); } if(parts.GetFileExtensionLen() > 0) { fFileExt = parts.GetFileExtensionAsBSTR(); } } parts.ResetBuffers(); } //Final checks, if failed, set to default if(fFileName.Length() == 0) fFileName = L""; if(fFileExt.Length() == 0) fFileExt = L""; if(fFileSize.Length() == 0) fFileSize = L"0"; if(m_strRedirectedURL.Length() == 0) m_strRedirectedURL = L""; if(m_bstrResponseHeaders.Length() == 0) m_bstrResponseHeaders = L""; fPathToSave = L""; if( (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { //Extra headers + redirect m_Events->Fire_FileDownloadEx(m_Uid, fUrl, fFileName, fFileExt, fFileSize, m_bstrResponseHeaders, m_strRedirectedURL, &m_SendProgressEvent, &m_vboolCancelDL, &fPathToSave); //fPathToSave would be a path/filename.ext //Cancel? if(m_vboolCancelDL == VARIANT_TRUE) { CancelDL(); return S_OK; } } //Set up fullpath for download if(fPathToSave.Length() > 0) { fFullSavePath = fPathToSave; } else { if(fFileName.Length() > 0) fFullSavePath = fFileName; //Save in the same dir as client exe else fFullSavePath = L"UNKNOWN"; //Desparate??? } } else if( ulStatusCode == BINDSTATUS_REDIRECTING) { m_fRedirect = TRUE; m_strRedirectedURL.Empty(); m_strRedirectedURL.AppendBSTR(W2BSTR(szStatusText)); } else if( (ulStatusCode == BINDSTATUS_DOWNLOADINGDATA) && (m_SendProgressEvent == VARIANT_TRUE) && (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { long lprogress = static_cast<long>(ulProgress); long lprogressmax = static_cast<long>(ulProgressMax); m_Events->Fire_OnFileDLProgress(m_Uid, fUrl, lprogress, lprogressmax, &m_vboolCancelDL); } else if( (ulStatusCode == BINDSTATUS_ENDDOWNLOADDATA) && (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { m_Events->Fire_OnFileDLEndDownload(m_Uid, fUrl, fFullSavePath); } //else, pass to previous BSCB coming from IDownloadManager::Download if(m_pPrevBSCB) { //Need to do this otherwise a filedownload dlg wil be displayed //as we are downloading the file. //Interestingly, according to MSDN, //BINDSTATUS_CONTENTDISPOSITIONATTACH is declared obsolete???? if(ulStatusCode == BINDSTATUS_CONTENTDISPOSITIONATTACH) return S_OK; m_pPrevBSCB->OnProgress(ulProgress, ulProgressMax, ulStatusCode, szStatusText); } if(m_vboolCancelDL == VARIANT_TRUE) { CancelDL(); } return S_OK; //Other status codes which may or may not fire //depending on whatever MS feels like.... // case BINDSTATUS_SENDINGREQUEST: // case BINDSTATUS_CONNECTING: // case BINDSTATUS_USINGCACHEDCOPY: // case BINDSTATUS_CACHEFILENAMEAVAILABLE: // case BINDSTATUS_FINDINGRESOURCE:; // case BINDSTATUS_BEGINDOWNLOADCOMPONENTS: // case BINDSTATUS_INSTALLINGCOMPONENTS: // case BINDSTATUS_ENDDOWNLOADCOMPONENTS: // case BINDSTATUS_CLASSIDAVAILABLE: // case BINDSTATUS_MIMETYPEAVAILABLE: //.............. } //This function is called regardless of success or failer in dl STDMETHODIMP WBBSCBFileDL::OnStopBinding(HRESULT hresult,LPCWSTR szError) { if(m_pBinding) { m_pBinding->Release(); m_pBinding = NULL; } //Notify the client that we are done //If client has not cancelled during actual dl via OnProgress if( (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { if((hresult) && (szError)) { //One of //INET_E_INVALID_URL //INET_E_RESOURCE_NOT_FOUND //..... USES_CONVERSION; CTmpBuffer buff(MAX_PATH); buff += W2CT(szError); buff += _T(" Error Number = "); buff.Appendlong(static_cast<long>(hresult)); CComBSTR sMsg; sMsg.Append(buff); m_Events->Fire_OnFileDLDownloadError(m_Uid, fUrl, sMsg); } else if(m_bCancelled == TRUE) //set to true in CancelDL method { //Cancelled by client or errors in OnDataAvailable method m_Events->Fire_OnFileDLEndDownload(m_Uid, fUrl, fFullSavePath); } m_Events->RemoveBSCBFromDLArr(m_Uid); } if( (m_pPrevBSCB) && (m_pBindCtx) ) { //Register PrevBSCB and release our pointers LPOLESTR oParam = L"_BSCB_Holder_"; m_pBindCtx->RegisterObjectParam(oParam, reinterpret_cast<IUnknown*>(m_pPrevBSCB)); m_pPrevBSCB->Release(); m_pPrevBSCB = NULL; m_pBindCtx->Release(); m_pBindCtx = NULL; //Decrease our ref count, so when release is called //we delete this object --m_cRef; } //URLmon.dll will call release on this object, so says MSDN return S_OK; } STDMETHODIMP WBBSCBFileDL::GetBindInfo(DWORD *grfBINDF, BINDINFO * pbindinfo) { if (pbindinfo==NULL || pbindinfo->cbSize==0 || grfBINDF==NULL) return E_INVALIDARG; //Set up bind flags *grfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; //*grfBINDF |= BINDF_IGNORESECURITYPROBLEM; // Set up the BINDINFO data structure // pbindinfo->cbSize = sizeof(BINDINFO); //Clear and setup DWORD cbSize = pbindinfo->cbSize = sizeof(BINDINFO); memset(pbindinfo,0,cbSize); pbindinfo->cbSize = cbSize; //BINDVERB_GET, //BINDVERB_POST, //BINDVERB_PUT, //BINDVERB_CUSTOM pbindinfo->dwBindVerb = BINDVERB_GET; pbindinfo->szExtraInfo = NULL; //The stgmedData member of the BINDINFO structure should be set //to TYMED_NULL for the GET operation. memset(&pbindinfo->stgmedData, 0, TYMED_NULL); //BINDINFOF_URLENCODESTGMEDDATA = 0 //BINDINFOF_URLENCODEDEXTRAINFO = 1 pbindinfo->grfBindInfoF = 0; //BSTR specifying a protocol-specific custom action to be performed //during the bind operation (only if dwBindVerb is set to BINDVERB_CUSTOM) pbindinfo->szCustomVerb = NULL; //Reserved. Must be set to 0 pbindinfo->dwOptions = 0; pbindinfo->dwOptionsFlags = 0; pbindinfo->dwReserved = 0; return S_OK; } STDMETHODIMP WBBSCBFileDL::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC* pformatetc, STGMEDIUM* pstgmed) { HRESULT hr = S_OK; //First call here if (BSCF_FIRSTDATANOTIFICATION & grfBSCF) { // Cache the incoming Stream if (m_pstm == NULL && pstgmed->tymed == TYMED_ISTREAM) { //Get a local copy of the stream m_pstm = pstgmed->pstm; if (m_pstm) { m_pstm->AddRef(); if(fFullSavePath.Length() > 0) { USES_CONVERSION; hFile = CreateFile(OLE2T(fFullSavePath), GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { goto Error; } if(m_vboolResuming == VARIANT_TRUE) { //Move pointer to the end of file, if we have anything //#define INVALID_SET_FILE_POINTER ((DWORD)-1) if (SetFilePointer(hFile, 0, NULL, FILE_END) == ((DWORD)-1)) { goto Error; } } } else { goto Error; } } } } // If there is some data to be read then go ahead and read it if (m_pstm && dwSize > m_cbOld) { DWORD dwRead = dwSize - m_cbOld; // Minimum amount available that hasn't been read DWORD dwActuallyRead = 0; // Placeholder for amount read during this pull DWORD dwWritten = 0; //WriteFile if (dwRead > 0) do { //BYTE* pBytes = NULL; //pBytes = new BYTE[dwRead + 1]); //if(pBytes == NULL) goto Error; //Servers serve non Unicode content LPSTR pNewstr = new char[dwRead + 1]; if (!pNewstr) { //E_OUTOFMEMORY //vbLog(_T("E_OUTOFMEMORY"),_T("WBBSCBFileDL::OnDataAvailable")); goto Error; } //hr= m_pstm->Read(pBytes, dwRead, &dwActuallyRead); hr = m_pstm->Read(pNewstr, dwRead, &dwActuallyRead); //pBytes[dwActuallyRead] = 0; pNewstr[dwActuallyRead] = '\0'; // If we really read something then lets write it to file if (dwActuallyRead > 0) { m_cbOld += dwActuallyRead; //WriteFile(hFile, pBytes, dwActuallyRead, &dwWritten, NULL); WriteFile(hFile, pNewstr, dwActuallyRead, &dwWritten, NULL); } //delete[] pBytes; delete[] pNewstr; } while (!(hr == E_PENDING || hr == S_FALSE) && SUCCEEDED(hr)); } // Clean up if (BSCF_LASTDATANOTIFICATION & grfBSCF) { if (m_pstm) { m_pstm->Release(); m_pstm = NULL; if(hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } } hr = S_OK; // If it was the last data then we should return S_OK as we just finished reading everything } return hr; Error: //Just cancel //We will notify client in OnStopBinding, since hresult //will have a value CancelDL(); return S_FALSE; } STDMETHODIMP WBBSCBFileDL::OnObjectAvailable(REFIID riid,IUnknown* punk) { return E_NOTIMPL; } STDMETHODIMP WBBSCBFileDL::BeginningTransaction( LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR *pszAdditionalHeaders) { // Here's our opportunity to add headers if (!pszAdditionalHeaders) { return E_POINTER; } *pszAdditionalHeaders = NULL; USES_CONVERSION; m_vboolResuming = VARIANT_FALSE; m_vboolCancelDL = VARIANT_FALSE; CComBSTR sAddClientHeaders(L""); CComBSTR sHeaders; fUrl.Empty(); fUrl = szURL; if(szHeaders) sHeaders = szHeaders; else sHeaders = L""; // //Fire the event if( (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { m_Events->Fire_OnFileDLBeginningTransaction( m_Uid, fUrl, sHeaders, &sAddClientHeaders, &m_vboolResuming, &m_vboolCancelDL); if(m_vboolCancelDL == VARIANT_TRUE) CancelDL(); } //See if we were send extra headers from IDownloadManager::Download method if(m_strDLManExtraHeaders.Length() > 0) { sAddClientHeaders += m_strDLManExtraHeaders; } //Add additional headers if(sAddClientHeaders.Length() > 0) { //Set additional headers LPWSTR wszAdditionalHeaders = (LPWSTR)CoTaskMemAlloc((sAddClientHeaders.Length()+1) *sizeof(WCHAR)); if (wszAdditionalHeaders) { //Copy wcscpy(wszAdditionalHeaders, OLE2W(sAddClientHeaders)); wszAdditionalHeaders[sAddClientHeaders.Length()] = (WCHAR)NULL; //Give URLmon a handle to our header *pszAdditionalHeaders = wszAdditionalHeaders; } } return S_OK; } STDMETHODIMP WBBSCBFileDL::OnResponse( DWORD dwResponseCode, LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR *pszAdditionalRequestHeaders) { if (!pszAdditionalRequestHeaders) { return E_POINTER; } *pszAdditionalRequestHeaders = NULL; if( (m_hwndClient != NULL) && (::IsWindow(m_hwndClient)) ) { USES_CONVERSION; CTmpBuffer buff(MAX_PATH*2); buff = W2CT(szResponseHeaders); if (szRequestHeaders) { //buff += _T("(Repeat request)\r\n"); buff += W2CT(szRequestHeaders); } m_vboolCancelDL = VARIANT_FALSE; //Fire event m_Events->Fire_OnFileDLResponse(m_Uid, fUrl, (long)(dwResponseCode), T2BSTR(buff), &m_vboolCancelDL); if(m_vboolCancelDL == VARIANT_TRUE) CancelDL(); } return S_OK; } bool WBBSCBFileDL::CancelDL(void) { m_bCancelled = TRUE; if (m_pstm) { m_pstm->Release(); m_pstm = NULL; } if(hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } if(m_pBinding) { m_pBinding->Abort(); } return true; } bool WBBSCBFileDL::IsDownloading(void) { return (m_pBinding) ? true : false; } ////////////////////////////////////////////////////////////// //CTmpBuffer ////////////////////////////////////////////////////////////// CTmpBuffer::CTmpBuffer() { InitLocalResources(); AllocateBuffer(STARTUP_TEMP_BUFFER); } CTmpBuffer::CTmpBuffer(LPCTSTR strText) { InitLocalResources(); Append(strText); } CTmpBuffer::CTmpBuffer(UINT iSize) { InitLocalResources(); AllocateBuffer(iSize); } CTmpBuffer::~CTmpBuffer() { ClearLocalResources(); } void CTmpBuffer::ResetBuffer() { if( (m_Buffer) && (m_BufferLen > 0) && (m_Allocated == true) ) { //Mark the beginning and end m_Buffer[m_BufferLen] = _T('\0'); m_Buffer[0] = _T('\0'); } m_BufferTextLen = 0; } //Allocate buffer UINT CTmpBuffer::AllocateBuffer(UINT nsize) { if(nsize < 1) return 0; //Attempting to increase storage if( (m_Buffer) && (m_Allocated == true) ) { LPTSTR tempbuffer = (LPTSTR)malloc((m_BufferLen+nsize+1) * sizeof(TCHAR)); if(tempbuffer == NULL) return -1; //Adjust actual size of buffer m_BufferLen += nsize; tempbuffer[m_BufferLen] = _T('\0'); //Copy what we have (m_BufferTextLen = actual number of characters in the buffer) if(m_BufferTextLen > 0) memcpy(tempbuffer, m_Buffer, m_BufferTextLen * sizeof(TCHAR)); tempbuffer[m_BufferTextLen] = _T('\0'); //Free current buffer and reassign free(m_Buffer); m_Buffer = tempbuffer; } else { //First time, just allocate m_Buffer = (LPTSTR)malloc( (nsize+1) * sizeof(TCHAR)); if(m_Buffer == NULL) return -1; m_BufferLen = nsize; m_Buffer[m_BufferLen] = _T('\0'); m_Buffer[0] = _T('\0'); //No text in the buffer m_BufferTextLen = 0; } m_Allocated = true; return m_BufferLen; } //Append a string UINT CTmpBuffer::Append(LPCTSTR strText, UINT iMaxLen) { if( (strText == NULL) || (*strText == _T('\0')) ) return 0; UINT nappend = 0; if(iMaxLen > 0) nappend = iMaxLen; else nappend = _tcslen(strText); if(nappend == 0) return 0; //Get actual buffer len + len of new text //to compare with the total buffer len UINT newlen = m_BufferTextLen + nappend; //Check if( (m_Buffer == NULL) || (m_Allocated == false) ) { AllocateBuffer(newlen); } //Still have room if(m_BufferLen >= newlen) { //Just copy data memcpy(m_Buffer+m_BufferTextLen, strText, nappend * sizeof(TCHAR)); } else { //Create a new storage + nGrowSize for the next strText LPTSTR tempbuffer = (LPTSTR)malloc( (newlen+1) * sizeof(TCHAR)); if(tempbuffer == NULL) return 0; m_BufferLen = newlen; tempbuffer[m_BufferLen] = _T('\0'); //Copy from buffer first and then the actual data memcpy(tempbuffer, m_Buffer, m_BufferTextLen * sizeof(TCHAR)); memcpy(tempbuffer+m_BufferTextLen, strText, nappend * sizeof(TCHAR)); //Empty buffer and reassign free(m_Buffer); m_Buffer = tempbuffer; } //Adjust actual number of text in buffer m_BufferTextLen = newlen; //Mark the end of actual text appended m_Buffer[m_BufferTextLen] = _T('\0'); return newlen; } //Append a BSTR UINT CTmpBuffer::AppendBSTR(BSTR strText, UINT iMaxLen) { if(strText == NULL) return 0; UINT dwChars = ::SysStringLen(strText); LPTSTR pLocal = (LPTSTR)malloc( (dwChars+1) * sizeof(TCHAR)); if(pLocal == NULL) return 0; pLocal[dwChars] = _T('\0'); #ifdef UNICODE lstrcpyn(pLocal, strText, dwChars); #else WideCharToMultiByte(CP_ACP, 0, strText, -1, pLocal, dwChars, NULL, NULL); #endif UINT iRet = Append(pLocal, iMaxLen); free(pLocal); return iRet; } //Append an int value UINT CTmpBuffer::Appendint(int iNumber, int radix) { TCHAR tmp[50]; #ifdef UNICODE _itow(iNumber, tmp, radix); #else _itoa(iNumber, tmp, radix); #endif return Append(tmp); } //Append a long value UINT CTmpBuffer::Appendlong(long lNumber, int radix) { TCHAR tmp[50]; #ifdef UNICODE _ltow(lNumber, tmp, radix); #else _ltoa(lNumber, tmp, radix); #endif return Append(tmp); } UINT CTmpBuffer::AppendGUID(REFGUID src) { OLECHAR wszBuff[39]; int i = StringFromGUID2(src, wszBuff, 39); TCHAR szBuff[39]; #ifdef UNICODE lstrcpyn(szBuff, wszBuff, 39); #else WideCharToMultiByte(CP_ACP, 0, wszBuff, -1, szBuff, 39, NULL, NULL); #endif return Append((LPCTSTR)szBuff); } UINT CTmpBuffer::AppendResStr(UINT nID, UINT iMaxLen) { TCHAR sz[RES_BUFFER_SIZE]; int nCount = sizeof(sz) / sizeof(sz[0]); // UINT nLen = ::LoadString(m_hInst, nID, sz, sizeof(sz)/sizeof(TCHAR)); UINT nLen = ::LoadString(m_hInst, nID, sz, nCount); UINT iRet = 0; if(nLen == 0) return iRet; //All string was read else need to read entire string //by increasing buffer size and trying again. //if (nCount - nLen > CHAR_FUDGE) iRet = Append( (LPCTSTR)sz, iMaxLen ); return iRet; } //Accessors TCHAR* CTmpBuffer::GetString(void) { return m_Buffer; } UINT CTmpBuffer::ReleaseString(void) { UINT iRet = 0; if(m_Buffer) { iRet = _tcslen(m_Buffer); if (iRet > 0) { m_BufferLen = iRet; m_BufferTextLen = iRet; m_Buffer[m_BufferTextLen] = _T('\0'); } } return iRet; } LPCTSTR CTmpBuffer::GetBuffer(void) const { return m_Buffer; } UINT CTmpBuffer::GetBufferLen(void) const { return m_BufferLen; } UINT CTmpBuffer::GetBufferTextLen(void) const { return m_BufferTextLen; } TCHAR CTmpBuffer::GetAt(int nIndex) { if((UINT)nIndex < m_BufferLen) return m_Buffer[nIndex]; else return 0; } void CTmpBuffer::SetAt(int nIndex, TCHAR ch) { if((UINT)nIndex < m_BufferLen) m_Buffer[nIndex] = ch; } TCHAR CTmpBuffer::operator[] (int nIndex) { if((UINT)nIndex < m_BufferLen) return m_Buffer[nIndex]; else return 0; } CTmpBuffer& CTmpBuffer::operator=(const CTmpBuffer& src) { //We don't destroy any buffers allocated ResetBuffer(); Append(src); return *this; } CTmpBuffer& CTmpBuffer::operator=(const LPCTSTR src) { ResetBuffer(); Append(src); return *this; } CTmpBuffer& CTmpBuffer::operator+=(const CTmpBuffer& strSrc) { Append(strSrc); return *this; } CTmpBuffer& CTmpBuffer::operator+=(const LPCTSTR strSrc) { Append(strSrc); return *this; } CTmpBuffer& CTmpBuffer::operator=(const UINT nID) { ResetBuffer(); AppendResStr(nID); return *this; } CTmpBuffer& CTmpBuffer::operator+=(const UINT nID) { AppendResStr(nID); return *this; } void CTmpBuffer::InitLocalResources() { m_cRef = 1; m_Buffer = NULL; m_BufferLen = 0; m_BufferTextLen = 0; m_Allocated = false; #if (_ATL_VER >= 0x0700) m_hInst = ATL::_AtlBaseModule.GetResourceInstance(); #else //#if (_ATL_VER == 0x0300) m_hInst = _Module.GetResourceInstance(); #endif } void CTmpBuffer::ClearLocalResources() { if( (m_Buffer) && (m_BufferLen > 0) && (m_Allocated == true) ) free(m_Buffer); m_Buffer = NULL; m_BufferLen = 0; m_BufferTextLen = 0; m_Allocated = false; } //////////////////////////////////////////////////////////////////////////////////////// //WBPassthruSink //Monitor and/or cancel every request and responde //WB makes, including images, sounds, scripts, etc //////////////////////////////////////////////////////////////////////////////////////// HRESULT WBPassthruSink::OnStart(LPCWSTR szUrl, IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo, DWORD grfPI, DWORD dwReserved, IInternetProtocol* pTargetProtocol) { HRESULT hr = BaseClass::OnStart(szUrl, pOIProtSink, pOIBindInfo, grfPI, dwReserved, pTargetProtocol); //Initialize our variables m_pEvents = NULL; m_hwndIEServer = 0; m_strUrl.Empty(); m_strRedirUrl.Empty(); m_strRedirHeaders.Empty(); //Find the instance of WB and IWB (host) CComPtr<IWindowForBindingUI> objWindowForBindingUI; HRESULT hret = QueryServiceFromClient(&objWindowForBindingUI); if( (SUCCEEDED(hret)) && (objWindowForBindingUI) ) { HWND hwndIEServer = NULL; //Should return InternetExplorerServer HWND objWindowForBindingUI->GetWindow(IID_IHttpSecurity, &hwndIEServer); //From here we can find the ATL window hosting this instance of our control //and have it fire an event for the form/dlg hosting this instance of our control if( (hwndIEServer) && (::IsWindow(hwndIEServer)) ) { m_hwndIEServer = (long)hwndIEServer; int i = 0; int isize = gCtrlInstances.GetSize(); for(i = 0; i < isize; i++) { CcsDLMan *pDLMan = reinterpret_cast<CcsDLMan*>(gCtrlInstances[i]); if( (pDLMan) && (pDLMan->m_IEServerHwnd == hwndIEServer) ) { m_pEvents = pDLMan; break; } } } } //This is available for the primary connection (once per request) //and not for images,... // QueryServiceFromClient(&spBSCB); // if(spBscb) return hr; } STDMETHODIMP WBPassthruSink::Switch( /* [in] */ PROTOCOLDATA *pProtocolData) { ATLASSERT(m_spInternetProtocolSink != 0); /* From Igor Tandetnik "[email protected]" " Beware multithreading. URLMon has this nasty habit of spinning worker threads, not even bothering to initialize COM on them, and calling APP methods on those threads. If you try to raise COM events directly from such a thread, bad things happen (random crashes, events being lost). You are only guaranteed to be on the main STA thread in two cases. First, in methods of interfaces that were obtained with IServiceProvider, such as IHttpNegotiage::BeginningTransaction or IAuthenticate::Authenticate. Second, you can call IInternetProtocolSink::Switch with PD_FORCE_SWITCH flag in PROTOCOLDATA::grfFlags, eventually URLMon will turn around and call IInternetProtocol::Continue on the main thread. Or, if you happen to have a window handy that was created on the main thread, you can post yourself a message. " */ //if( (pProtocolData->grfFlags & PD_FORCE_SWITCH) != PD_FORCE_SWITCH) if( (pProtocolData->grfFlags & PD_FORCE_SWITCH) == 0) pProtocolData->grfFlags |= PD_FORCE_SWITCH; return m_spInternetProtocolSink ? m_spInternetProtocolSink->Switch(pProtocolData) : E_UNEXPECTED; } STDMETHODIMP WBPassthruSink::BeginningTransaction(LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR *pszAdditionalHeaders) { if (pszAdditionalHeaders) { *pszAdditionalHeaders = 0; } CComPtr<IHttpNegotiate> spHttpNegotiate; QueryServiceFromClient(&spHttpNegotiate); HRESULT hr = spHttpNegotiate ? spHttpNegotiate->BeginningTransaction(szURL, szHeaders, dwReserved, pszAdditionalHeaders) : S_OK; USES_CONVERSION; if(szURL) m_strUrl.AppendBSTR(W2BSTR(szURL)); else m_strUrl = L""; m_strRedirUrl = L""; CComBSTR strRequestHeaders; //Get raw request headers and send them to client CComPtr<IWinInetHttpInfo> spWinInetHttpInfo; HRESULT hrTemp = m_spTargetProtocol->QueryInterface(IID_IWinInetHttpInfo, reinterpret_cast<void**>(&spWinInetHttpInfo)); if(SUCCEEDED(hrTemp)) { DWORD size = 0; DWORD flags = 0; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, 0, &size, &flags, 0); if(SUCCEEDED(hrTemp)) { LPSTR pbuf = new char[size+1]; pbuf[size] = '\0'; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, pbuf, &size, &flags, 0); if(SUCCEEDED(hrTemp)) { //\r\n\r\n\0 Get rid of extra if( (size > 5) && (pbuf[size-1] == '\n') && (pbuf[size-2] == '\r') && (pbuf[size-3] == '\n') && (pbuf[size-4] == '\r') ) { pbuf[size-1] = '\0'; pbuf[size-2] = '\0'; } //pbuf should contain all request headers strRequestHeaders.Append(pbuf); } else strRequestHeaders = L""; } else strRequestHeaders = L""; } else strRequestHeaders = L""; //Additional Client headers CComBSTR strAddHttpHeaders; if(szHeaders) { //Accept-Encoding: gzip, deflate strRequestHeaders += W2BSTR(szHeaders); strRequestHeaders.Append(_T("\r\n")); } if( pszAdditionalHeaders && *pszAdditionalHeaders) { //Referer: http://www.google.ca/ //Accept-Language: en-ca strAddHttpHeaders = W2BSTR(*pszAdditionalHeaders); strRequestHeaders += strAddHttpHeaders; } //Fire event if( m_pEvents ) { VARIANT_BOOL bcancel = VARIANT_FALSE; CComBSTR strTempHeaders(L""); m_pEvents->Fire_ProtocolHandlerOnBeginTransaction(m_hwndIEServer, m_strUrl, strRequestHeaders, &strTempHeaders, &bcancel); if(bcancel == VARIANT_TRUE) return E_ABORT; //Did client add any of their headers if(strTempHeaders.Length() > 0) { strTempHeaders += strAddHttpHeaders; if(strTempHeaders.Length() > 0) { LPWSTR wszAdditionalHeaders = (LPWSTR)CoTaskMemAlloc((strTempHeaders.Length()+1) *sizeof(WCHAR)); if(wszAdditionalHeaders) { //Free what we had CoTaskMemFree(*pszAdditionalHeaders); wcscpy(wszAdditionalHeaders, OLE2W(strTempHeaders)); wszAdditionalHeaders[strTempHeaders.Length()] = (WCHAR)NULL; *pszAdditionalHeaders = wszAdditionalHeaders; } } } } return hr; } STDMETHODIMP WBPassthruSink::OnResponse(DWORD dwResponseCode, LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR *pszAdditionalRequestHeaders) { if (pszAdditionalRequestHeaders) { *pszAdditionalRequestHeaders = 0; } CComPtr<IHttpNegotiate> spHttpNegotiate; QueryServiceFromClient(&spHttpNegotiate); HRESULT hr = spHttpNegotiate ? spHttpNegotiate->OnResponse(dwResponseCode, szResponseHeaders, szRequestHeaders, pszAdditionalRequestHeaders) : S_OK; USES_CONVERSION; CTmpBuffer buff(MAX_PATH*2); buff = W2CT(szResponseHeaders); if (szRequestHeaders) { //buff += _T("(Repeat request)\r\n"); buff += W2CT(szRequestHeaders); if (SUCCEEDED(hr) && pszAdditionalRequestHeaders && *pszAdditionalRequestHeaders) { buff += W2CT(*pszAdditionalRequestHeaders); } } if( m_pEvents ) { VARIANT_BOOL bcancel = VARIANT_FALSE; //Fire event m_pEvents->Fire_ProtocolHandlerOnResponse(m_hwndIEServer, m_strUrl, T2BSTR(buff), m_strRedirUrl, m_strRedirHeaders, &bcancel); if(bcancel == VARIANT_TRUE) return m_spTargetProtocol->Abort(E_ABORT,0); if(m_strRedirUrl.Length() > 0) { m_strUrl.Empty(); m_strUrl = m_strRedirUrl; } } return hr; } STDMETHODIMP WBPassthruSink::ReportProgress(ULONG ulStatusCode, LPCWSTR szStatusText) { ATLASSERT(m_spInternetProtocolSink != 0); HRESULT hr = m_spInternetProtocolSink ? m_spInternetProtocolSink->ReportProgress(ulStatusCode, szStatusText) : S_OK; if(ulStatusCode == BINDSTATUS_REDIRECTING) { USES_CONVERSION; //Get redirected URL m_strRedirUrl.Empty(); if(szStatusText) m_strRedirUrl.AppendBSTR(W2BSTR(szStatusText)); else m_strRedirUrl = L""; //To get redirect headers during a redirect //No OnResponse is fired for a redirect m_strRedirHeaders.Empty(); //Get raw request headers and send them to client /* Client applications can call QueryInterface on the IBinding interface to get a pointer to the IWinInetHttpInfo interface after your implementation of the IBindStatusCallback::OnProgress method has been called. */ CComPtr<IWinInetHttpInfo> spWinInetHttpInfo; HRESULT hrTemp = m_spTargetProtocol->QueryInterface(IID_IWinInetHttpInfo, reinterpret_cast<void**>(&spWinInetHttpInfo)); if(SUCCEEDED(hrTemp)) { DWORD size = 0; DWORD flags = 0; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, 0, &size, &flags, 0); if(SUCCEEDED(hrTemp)) { LPSTR pbuf = new char[size+1]; pbuf[size] = '\0'; hrTemp = spWinInetHttpInfo->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, pbuf, &size, &flags, 0); if(SUCCEEDED(hrTemp)) { //\r\n\r\n\0 Get rid of extra if( (size > 5) && (pbuf[size-1] == '\n') && (pbuf[size-2] == '\r') && (pbuf[size-3] == '\n') && (pbuf[size-4] == '\r') ) { pbuf[size-1] = '\0'; pbuf[size-2] = '\0'; } //pbuf should contain all request headers m_strRedirHeaders.Append(pbuf); } else m_strRedirHeaders = L""; } else m_strRedirHeaders = L""; } else m_strRedirHeaders = L""; } return hr; } //////////////////////////////////////////////////////////////////////////////////////////////// // HOOK CALLBACK IMPLEMENTATION //////////////////////////////////////////////////////////////////////////////////////////////// static LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_KEYBOARD].hhook, nCode, wParam, lParam); if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_KEYBOARD].hwndTarget) && (::IsWindow(wbhookdata[H_KEYBOARD].hwndTarget)) ) { DWORD dwresult = 0; //UINT umsg = WM_KEYDOWN; ////wParam = virtual-key code //// Reference: WM_KEYDOWN on MSDN //if (lParam & 0x80000000) // check bit 31 for up/down //{ // umsg = WM_KEYUP; //} //else //{ // if (lParam & 0x40000000) // check bit 30 for previous up/down // umsg = WM_KEY_REPEAT; // It was pressed down before this key-down event, so it's a key-repeat for sure // else // umsg = WM_KEYDOWN; //} //always returns 1 ::SendMessageTimeout(wbhookdata[H_KEYBOARD].hwndTarget, wbhookdata[H_KEYBOARD].uiHookMsgID , //sending our own registered message wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); //Check dwresult, return value from client, default 0, allow hook to continue long lret = (long)dwresult; //if return value is greater than 0 then cancel if(lret > 0) return lret; //TCHAR tmp[50]; //#ifdef UNICODE // _ltow(lret, tmp, 10); //#else // _ltoa(lret, tmp, 10); //#endif //MessageBox(GetDesktopWindow(), tmp, _T("KeyboardProc RETURN VALUE"),MB_OK); } //Default processing return CallNextHookEx(wbhookdata[H_KEYBOARD].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_MOUSE].hhook, nCode, wParam, lParam); //LPMOUSEHOOKSTRUCT pMsg = (LPMOUSEHOOKSTRUCT)lParam; //wParam one of WM_xxx(LBUTTONDOWN, LBUTTONDOWN, MOUSEMOVE, NCMOUSEMOVE, MOUSEWHEEL, ...) if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_MOUSE].hwndTarget) && (::IsWindow(wbhookdata[H_MOUSE].hwndTarget)) ) { DWORD dwresult = 0; ::SendMessageTimeout(wbhookdata[H_MOUSE].hwndTarget, wbhookdata[H_MOUSE].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } //Default processingfgt return CallNextHookEx(wbhookdata[H_MOUSE].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_KEYBOARD_LL].hhook, nCode, wParam, lParam); //LPKBDLLHOOKSTRUCT pMsg = (LPKBDLLHOOKSTRUCT)lParam; //wParam one of WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_KEYBOARD_LL].hwndTarget) && (::IsWindow(wbhookdata[H_KEYBOARD_LL].hwndTarget)) ) { DWORD dwresult = 0; ::SendMessageTimeout(wbhookdata[H_KEYBOARD_LL].hwndTarget, wbhookdata[H_KEYBOARD_LL].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } //Default processinghgok return CallNextHookEx(wbhookdata[H_KEYBOARD_LL].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_CALLWNDPROC].hhook, nCode, wParam, lParam); //wParam: Specifies whether the message was sent by the current thread. //If the message was sent by the current thread, it is nonzero; otherwise, it is zero //LPCWPSTRUCT lpcp = (LPCWPSTRUCT)wParam if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_CALLWNDPROC].hwndTarget) && (::IsWindow(wbhookdata[H_CALLWNDPROC].hwndTarget)) ) { DWORD dwresult = 0; ::SendMessageTimeout(wbhookdata[H_CALLWNDPROC].hwndTarget, wbhookdata[H_CALLWNDPROC].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } //Default processing return CallNextHookEx(wbhookdata[H_CALLWNDPROC].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_CBT].hhook, nCode, wParam, lParam); if( (nCode) && (lParam) && (wbhookdata[H_CBT].hwndTarget) && (::IsWindow(wbhookdata[H_CBT].hwndTarget)) ) { DWORD dwresult = 0; nCode_CBTProc = nCode; //nCode //HCBT_ACTIVATE //HCBT_CLICKSKIPPED //HCBT_CREATEWND //HCBT_DESTROYWND //HCBT_KEYSKIPPED //HCBT_MINMAX //HCBT_MOVESIZE //HCBT_QS //HCBT_SETFOCUS //HCBT_SYSCOMMAND //lParam and wParam depend on nCode ::SendMessageTimeout(wbhookdata[H_CBT].hwndTarget, wbhookdata[H_CBT].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } //Default processing return CallNextHookEx(wbhookdata[H_CBT].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_GETMESSAGE].hhook, nCode, wParam, lParam); //LPMSG msg = (LPMSG)lParam //wParam = PM_NOREMOVE or PM_REMOVE if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_GETMESSAGE].hwndTarget) && (::IsWindow(wbhookdata[H_GETMESSAGE].hwndTarget)) ) { DWORD dwresult = 0; ::SendMessageTimeout(wbhookdata[H_GETMESSAGE].hwndTarget, wbhookdata[H_GETMESSAGE].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } //Default processing return CallNextHookEx(wbhookdata[H_GETMESSAGE].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK MessageProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_MSGFILTER].hhook, nCode, wParam, lParam); if( (nCode) && (lParam) && (wbhookdata[H_MSGFILTER].hwndTarget) && (::IsWindow(wbhookdata[H_MSGFILTER].hwndTarget)) ) { DWORD dwresult = 0; nCode_MessageProc = nCode; //nCode //MSGF_DDEMGR //MSGF_DIALOGBOX //MSGF_MENU //MSGF_SCROLLBAR //LPMSG msg = (LPMSG)lParam; //wParam is not used ::SendMessageTimeout(wbhookdata[H_MSGFILTER].hwndTarget, wbhookdata[H_MSGFILTER].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_MSGFILTER].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_MOUSE_LL].hhook, nCode, wParam, lParam); if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_MOUSE_LL].hwndTarget) && (::IsWindow(wbhookdata[H_MOUSE_LL].hwndTarget)) ) { DWORD dwresult = 0; //wParam, one of WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, //WM_MOUSEWHEEL, WM_RBUTTONDOWN, or WM_RBUTTONUP. //LPMSLLHOOKSTRUCT msg = (LPMSLLHOOKSTRUCT)lParam ::SendMessageTimeout(wbhookdata[H_MOUSE_LL].hwndTarget, wbhookdata[H_MOUSE_LL].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_MOUSE_LL].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK ForegroundIdleProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_GETMESSAGE].hhook, nCode, wParam, lParam); if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_FOREGROUNDIDLE].hwndTarget) && (::IsWindow(wbhookdata[H_FOREGROUNDIDLE].hwndTarget)) ) { DWORD dwresult = 0; //wParam and lParam are not used ::SendMessageTimeout(wbhookdata[H_FOREGROUNDIDLE].hwndTarget, wbhookdata[H_FOREGROUNDIDLE].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_FOREGROUNDIDLE].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK CallWndRetProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_CALLWNDPROCRET].hhook, nCode, wParam, lParam); if( (nCode == HC_ACTION) && (lParam) && (wbhookdata[H_CALLWNDPROCRET].hwndTarget) && (::IsWindow(wbhookdata[H_CALLWNDPROCRET].hwndTarget)) ) { DWORD dwresult = 0; //wParam, Specifies whether the message is sent by the current process. //If the message is sent by the current process, it is nonzero; otherwise, it is NULL. //LPCWPRETSTRUCT msg = (LPCWPRETSTRUCT)lParam; ::SendMessageTimeout(wbhookdata[H_CALLWNDPROCRET].hwndTarget, wbhookdata[H_CALLWNDPROCRET].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_CALLWNDPROCRET].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK SysMsgProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_SYSMSGFILTER].hhook, nCode, wParam, lParam); if( (nCode) && (lParam) && (wbhookdata[H_SYSMSGFILTER].hwndTarget) && (::IsWindow(wbhookdata[H_SYSMSGFILTER].hwndTarget)) ) { DWORD dwresult = 0; nCode_SysMsgProc = nCode; //nCode //MSGF_DIALOGBOX //MSGF_MENU //MSGF_SCROLLBAR //wParam is not used //LPMSG msg = (LPMSG)lParam ::SendMessageTimeout(wbhookdata[H_SYSMSGFILTER].hwndTarget, wbhookdata[H_SYSMSGFILTER].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_SYSMSGFILTER].hhook, nCode, wParam, lParam); } static LRESULT CALLBACK ShellProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) // do not process message return CallNextHookEx(wbhookdata[H_SHELL].hhook, nCode, wParam, lParam); if( (nCode) && (lParam) && (wbhookdata[H_SHELL].hwndTarget) && (::IsWindow(wbhookdata[H_SHELL].hwndTarget)) ) { DWORD dwresult = 0; nCode_ShellProc = nCode; //contents of wParam and lParam depend on nCode ::SendMessageTimeout(wbhookdata[H_SHELL].hwndTarget, wbhookdata[H_SHELL].uiHookMsgID , wParam, lParam, SMTO_ABORTIFHUNG, 500, &dwresult); long lret = (long)dwresult; if(lret > 0) return lret; } return CallNextHookEx(wbhookdata[H_SHELL].hhook, nCode, wParam, lParam); }
[ [ [ 1, 2368 ] ] ]
e5862ac7a9b1794722f2a8dbcf88993fa420b96b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/GeometryUtilities/Mesh/Utils/NormalCalculator/hkNormalCalculator.h
e05ac9526fd4b353aa31b310d4000752409cedcc
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
5,534
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_NORMAL_CALCULATOR_H #define HK_NORMAL_CALCULATOR_H /// A set of utilities for working out normals for triangles given by indexed vertices class hkNormalCalculator { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA, hkNormalCalculator ); /// Calculates smoothing groups /// cosSmoothingAngle - is the cos of the maximum angle between triangle normals to allow smoothing /// /// The calculateSmoothingGroups method takes a set of positions, a triangle list and an 'smoothing angle' which the angle across /// an edge between shared faces must be less than for there to be smoothing between the triangles. The actual smoothing /// factor is calculated as the dot product between the normals of two faces sharing an edge. It will therefore be 1 if the /// triangles are facing in the same direction, 0 if at 90 degree, -1 if at 180 degrees. Therefore the cos of the angle between /// the normals is the actual threshold (ie. the value has to be greater than the specified value for there to be smoothing /// between the triangles). /// /// The method returns the results in the two arrays, triangleIndicesOut and numTrianglesOut. TriangleIndidicesOut holds the indices /// of triangles (not the vertices) which are shared. The numTrianglesOut holds the number of triangles in each shared group. The /// groups indices are held contiguously in triangleIndicesOut. Ie the first n indices in triangleIndicesOut belong to the first group (n being numTriangles[0]) /// the next groups triangles indices will directly follow with the amount held in numTrianglesOut[1] and so forth. static void HK_CALL calculateSmoothingGroups(const hkArray<hkVector4>& positions, const hkUint16* triangleList, int numTriangles, hkReal cosSoothingAngle, hkArray<int>& triangleIndicesOut, hkArray<int>& numTrianglesOut); /// Calculates how to smooth the geometry /// cosSmoothingAngle - is the cos of the maximum angle between triangle normals to allow smoothing /// /// calculatedSmoothedGeometry uses the calculateSmoothingGroups and calculateNormals methods to produce normals taking into account the smoothing angle. /// The method returns vertices and normals such that they are not shared where needed (because there isn't smoothing). The originalIndicesOut array holds /// the indices from the original positioned that the output normals and vertices out came from. This could be used for finding the texture coordinates to /// apply from the original geometry. static void HK_CALL calculateSmoothedGeometry(const hkArray<hkVector4>& positions, const hkUint16* triangleList, int numTriangles, hkReal cosSoothingAngle, hkArray<hkVector4>& verticesOut, hkArray<hkVector4>& normalsOut, hkArray<hkUint16>& triangleIndicesOut, hkArray<hkUint16>& originalIndicesOut); /// Normalizes all of the normals in the array normals static void HK_CALL normalize(hkArray<hkVector4>& normals); /// The calculateNormals method takes the positions of vertices, a triangle list and will return the normals at those positions /// (ie there will always be output the same amount of normals as positions). The normals produced will be calculated to /// produce lighting that is smooth across the surface. Vertex indices are used to identify if an edge is shared - not the /// position of the vertex. static void HK_CALL calculateNormals(const hkArray<hkVector4>& positions, const hkUint16* triangleList, int numTriangles, hkArray<hkVector4>& normals); /// Given triangles as in \a triangleIndices, the vertex \a positions and \a normals, compute the tangent frames in \a tangentsOut and \a binormalsOut such that the frames are aligned to the S-T directions of the \a texCoords. static void HK_CALL calculateTangentSpaces(const hkArray<hkVector4>& positions, const hkArray<hkVector4>& normals, const hkArray<hkVector4>& texCoords, const hkArray<hkUint16>& triangleIndices, hkArray<hkVector4>& tangentsOut, hkArray<hkVector4>& binormalsOut); }; #endif // HK_NORMAL_CALCULATOR_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 74 ] ] ]
7dd5b2f67d425356689e0ca68810dc6db8065d0d
ce0622a0f49dd0ca172db04efdd9484064f20973
/tools/GameList/Common/AtgSyncTaskQueue.h
d7e71b4860508ca988da7e6d418137bb4f8e0fb3
[]
no_license
maninha22crazy/xboxplayer
a78b0699d4002058e12c8f2b8c83b1cbc3316500
e9ff96899ad8e8c93deb3b2fe9168239f6a61fe1
refs/heads/master
2020-12-24T18:42:28.174670
2010-03-14T13:57:37
2010-03-14T13:57:37
56,190,024
1
0
null
null
null
null
UTF-8
C++
false
false
2,740
h
//-------------------------------------------------------------------------------------- // AtgSyncTaskQueue.h // // Synchronous task-queue implementation // // Xbox Advanced Technology Group. // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #pragma once #include <algorithm> #include "AtgTasks.h" #include <queue> #include <vector> namespace ATG { //------------------------------------------------------------------------ // Name: class TaskQueue // Desc: Single threaded task queue class that uses a AtgPriorityQueue // for its queue //------------------------------------------------------------------------ class TaskQueue { public: TaskQueue() { } ~TaskQueue() { } //------------------------------------------------------------------------ // Name: Push() // Desc: Pushes a task to the queue //------------------------------------------------------------------------ void Push(const TaskData& t) { // Add T to queue; ATG::DebugSpew( "TaskQueue: Pushing 0x%08x...\n", t.dwMessage ); m_queue.push(t); } //------------------------------------------------------------------------ // Name: Push() // Desc: Pops a task from the queue //------------------------------------------------------------------------ bool Pop(TaskData* t_out) { bool fRet = false; if( m_queue.size() ) { // Get front of queue const TaskData& t = m_queue.front(); // Pop off front of queue m_queue.pop(); // Copy data to in/out param *t_out = t; ATG::DebugSpew( "TaskQueue: Popping 0x%08x...\n", t.dwMessage ); fRet = true; } return fRet; } //------------------------------------------------------------------------ // Name: IsEmpty() // Desc: Returns true if queue is empty; otherwise false //------------------------------------------------------------------------ bool IsEmpty() { bool fEmpty = true; if( m_queue.size() ) { fEmpty = false; } return fEmpty; } //------------------------------------------------------------------------ // Name: Initialize() // Desc: Public task queue initialization function //------------------------------------------------------------------------ DWORD Initialize() { return ERROR_SUCCESS; } private: std::queue<TaskData> m_queue; }; }
[ "goohome@343f5ee6-a13e-11de-ba2c-3b65426ee844" ]
[ [ [ 1, 101 ] ] ]
68985a30a633d63b4d35c3a7062165ab1261838b
5a39be53de11cddb52af7d0b70b56ef94cc52d35
/doc/P3相关工具包/ChiAnalyzer/Utility/ContextStat.h
8418b5b2509c32f54891051aba690437747effdf
[]
no_license
zchn/jsepku
2b76eb5d118f86a5c942a9f4ec25a5adae24f802
8290fef5ff8abaf62cf050cead489dc7d44efa5f
refs/heads/master
2016-09-10T19:44:23.882210
2008-01-01T07:32:13
2008-01-01T07:32:13
33,052,475
0
0
null
null
null
null
GB18030
C++
false
false
3,030
h
//此部分代码使用 计算所汉语词法分析系统 ICTCLAS // //此部分代码为免费使用 版权保护 // //特在此特别申明 // // //Author: Kevin Zhang (张华平); Qun Liu(刘群) // //Inst. of Computing Tech., Chinese Academy of Sciences // //Email: [email protected] // //Tel: +86-10-88455001/5/7 to 714 ////////////////////////////////////////////////////////////////////// //ICTCLAS简介:计算所汉语词法分析系统ICTCLAS(Institute of Computing Technology, Chinese Lexical Analysis System), // 功能有:中文分词;词性标注;未登录词识别。 // 分词正确率高达97.58%(973专家评测结果), // 未登录词识别召回率均高于90%,其中中国人名的识别召回率接近98%; // 处理速度为31.5Kbytes/s。 //著作权: Copyright?2002-2005中科院计算所 职务著作权人:张华平 刘群 //遵循协议:自然语言处理开放资源许可证1.0 //Email: [email protected] //Homepage:www.nlp.org.cn;mtgroup.ict.ac.cn /**************************************************************************** * * Copyright (c) 2000, 2001 * Machine Group * Software Research Lab. * Institute of Computing Tech. * Chinese Academy of Sciences * All rights reserved. * * This file is the confidential and proprietary property of * Institute of Computing Tech. and the posession or use of this file requires * a written license from the author. * Filename: ContextStat.h * Abstract: * * interface for the CContextStat class. * Author: Kevin Zhang * ([email protected]) * Date: 2002-1-24 * * Notes: * * ****************************************************************************/ #if !defined(AFX_CONTEXTSTAT_H__DA515FDC_F8F9_48F6_B25D_D2B91011528B__INCLUDED_) #define AFX_CONTEXTSTAT_H__DA515FDC_F8F9_48F6_B25D_D2B91011528B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 struct tagContext{ int nKey;//The key word int **aContextArray;//The context array int *aTagFreq;//The total number a tag appears int nTotalFreq;//The total number of all the tags struct tagContext *next;//The chain pointer to next Context }; typedef struct tagContext MYCONTEXT,*PMYCONTEXT; class CContextStat { public: bool SetTableLen(int nTableLe); int GetFrequency(int nKey,int nSymbol); double GetContextPossibility(int nKey,int nPrev,int nCur); bool Load(char *sFilename); bool Save(char *sFilename); bool Add(int nKey,int nPrevSymbol,int nCurrentSymbol,int nFrequency); bool SetSymbol(int *nSymbol); CContextStat(); virtual ~CContextStat(); private: int m_nTableLen; int *m_pSymbolTable; PMYCONTEXT m_pContext; int m_nCategory; protected: bool GetItem(int nKey,PMYCONTEXT *pItemRet); }; #endif // !defined(AFX_CONTEXTSTAT_H__DA515FDC_F8F9_48F6_B25D_D2B91011528B__INCLUDED_)
[ "joyanlj@702d1322-cd41-0410-9eed-0fefee27d168" ]
[ [ [ 1, 86 ] ] ]
2387d64b45f16ff158ff3b51cefb39ffa69b34cd
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/test/dijkstra_heap_performance.cpp
5ff6dbabac105d2b6c4893c48adb4ffea000b817
[ "Artistic-2.0", "LicenseRef-scancode-public-domain", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
5,221
cpp
// Copyright 2004 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Andrew Lumsdaine #ifndef BOOST_GRAPH_DIJKSTRA_TESTING_DIETMAR # define BOOST_GRAPH_DIJKSTRA_TESTING #endif #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/test/minimal.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/lexical_cast.hpp> #include <boost/random/uniform_real.hpp> #include <boost/timer.hpp> #include <vector> #include <iostream> #include <iterator> #include <utility> #include <boost/random/uniform_int.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/erdos_renyi_generator.hpp> #include <boost/type_traits/is_base_and_derived.hpp> #include <boost/type_traits/is_same.hpp> using namespace boost; #ifdef BOOST_GRAPH_DIJKSTRA_TESTING_DIETMAR struct show_events_visitor : dijkstra_visitor<> { template<typename Vertex, typename Graph> void discover_vertex(Vertex v, const Graph&) { std::cerr << "on_discover_vertex(" << v << ")\n"; } template<typename Vertex, typename Graph> void examine_vertex(Vertex v, const Graph&) { std::cerr << "on_discover_vertex(" << v << ")\n"; } }; template<typename Graph, typename Kind> void run_test(const Graph& g, const char* name, Kind kind, const std::vector<double>& correct_distances) { std::vector<double> distances(num_vertices(g)); std::cout << "Running Dijkstra's with " << name << "..."; std::cout.flush(); timer t; dijkstra_heap_kind = kind; dijkstra_shortest_paths(g, vertex(0, g), distance_map(&distances[0]). visitor(show_events_visitor())); double run_time = t.elapsed(); std::cout << run_time << " seconds.\n"; BOOST_TEST(distances == correct_distances); if (distances != correct_distances) { std::cout << "Expected: "; std::copy(correct_distances.begin(), correct_distances.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << "\nReceived: "; std::copy(distances.begin(), distances.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; } } #endif int test_main(int argc, char* argv[]) { unsigned n = (argc > 1? lexical_cast<unsigned>(argv[1]) : 10000u); unsigned m = (argc > 2? lexical_cast<unsigned>(argv[2]) : 10*n); int seed = (argc > 3? lexical_cast<int>(argv[3]) : 1); // Build random graph typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, double> > Graph; std::cout << "Generating graph..."; std::cout.flush(); minstd_rand gen(seed); double p = double(m)/(double(n)*double(n)); Graph g(erdos_renyi_iterator<minstd_rand, Graph>(gen, n, p), erdos_renyi_iterator<minstd_rand, Graph>(), n); std::cout << n << " vertices, " << num_edges(g) << " edges.\n"; uniform_real<double> rand01(0.0, 1.0); graph_traits<Graph>::edge_iterator ei, ei_end; for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) put(edge_weight, g, *ei, rand01(gen)); std::vector<double> binary_heap_distances(n); std::vector<double> relaxed_heap_distances(n); // Run binary heap version std::cout << "Running Dijkstra's with binary heap..."; std::cout.flush(); timer t; #ifdef BOOST_GRAPH_DIJKSTRA_TESTING_DIETMAR dijkstra_heap_kind = dijkstra_binary_heap; #else dijkstra_relaxed_heap = false; #endif dijkstra_shortest_paths(g, vertex(0, g), distance_map(&binary_heap_distances[0])); double binary_heap_time = t.elapsed(); std::cout << binary_heap_time << " seconds.\n"; // Run relaxed heap version std::cout << "Running Dijkstra's with relaxed heap..."; std::cout.flush(); t.restart(); #ifdef BOOST_GRAPH_DIJKSTRA_TESTING_DIETMAR dijkstra_heap_kind = dijkstra_relaxed_heap; #else dijkstra_relaxed_heap = true; #endif dijkstra_shortest_paths(g, vertex(0, g), distance_map(&relaxed_heap_distances[0])); double relaxed_heap_time = t.elapsed(); std::cout << relaxed_heap_time << " seconds.\n" << "Speedup = " << (binary_heap_time / relaxed_heap_time) << ".\n"; // Verify that the results are equivalent BOOST_CHECK(binary_heap_distances == relaxed_heap_distances); #ifdef BOOST_GRAPH_DIJKSTRA_TESTING_DIETMAR run_test(g, "d-ary heap (d=2)", dijkstra_d_heap_2, binary_heap_distances); run_test(g, "d-ary heap (d=3)", dijkstra_d_heap_3, binary_heap_distances); run_test(g, "Fibonacci heap", dijkstra_fibonacci_heap, binary_heap_distances); run_test(g, "Lazy Fibonacci heap", dijkstra_lazy_fibonacci_heap, binary_heap_distances); run_test(g, "Pairing heap", dijkstra_pairing_heap, binary_heap_distances); run_test(g, "Splay heap", dijkstra_splay_heap, binary_heap_distances); #endif return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 149 ] ] ]
673517079ba087be57ea7ede43f3fddadc718803
2d9d1f5c83af20faf3b9206be68d18af1ad44e04
/Tugas Besar/Job/main_race.cpp
b6efe00c91ade9e9946888537c0eeb112b770457
[]
no_license
akbargumbira/dunnotactic
3f8f09ef1ef1e880b2c60e9710d4f244ab073fd7
05c3dd12b38a9f24d23a87db708d3963403f928b
refs/heads/master
2021-01-17T12:08:29.864145
2010-05-12T12:34:52
2010-05-12T12:34:52
33,938,420
0
0
null
null
null
null
UTF-8
C++
false
false
3,989
cpp
#include <iostream> #include <string> #include <vector> #include <stdlib.h> #include "Knight.h" #include "Archer.h" #include "Mage.h" #include "Sage.h" #include "Warrior.h" #include "Assassin.h" using namespace std; vector<Job *> Player; vector<Job *> Enemy; vector<Job *>::iterator i; Job * obj_job; Job * obj_job2; int main (){ try { Player.push_back(new Archer ("human")); Player.push_back(new Knight("orc")); i = Player.begin(); obj_job = *i; obj_job->SetName("Terra"); i = Player.begin()+1; obj_job = *i; obj_job->SetName("Amaterasu"); cout<<"Status masing - masing :"<<endl<<endl; i = Player.begin(); obj_job = *i; cout<<obj_job->GetName()<<" / "<< obj_job->GetJobName()<<" / "<<obj_job->GetRaceName()<<endl; cout<<"HP = "<< obj_job->GetHP ()<< "/"<<obj_job->GetHPDefault ()<< " SP = "<< obj_job->GetSP ()<< "/"<<obj_job->GetSPDefault ()<<endl; cout<<"Attack point = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Defense point = "<< obj_job->GetDefensePoint ()<<endl; cout<<"Attack point = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Accuracy = "<< obj_job->GetAcc()<<endl; cout<<"Evade = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Range Move = "<< obj_job->GetRangeMove ()<<endl; cout<<"Range Attck = "<< obj_job->GetRangeAttack ()<<endl<<endl; cout<<"Special = "<< obj_job->ShowSpecialArray()<<endl<<endl; i = Player.begin()+1; obj_job = *i; cout<<obj_job->GetName()<<" / "<< obj_job->GetJobName()<<" / "<<obj_job->GetRaceName()<<endl; cout<<"HP = "<< obj_job->GetHP ()<< "/"<<obj_job->GetHPDefault ()<< " SP = "<< obj_job->GetSP ()<< "/"<<obj_job->GetSPDefault ()<<endl; cout<<"Attack point = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Defense point = "<< obj_job->GetDefensePoint ()<<endl; cout<<"Attack point = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Accuracy = "<< obj_job->GetAcc()<<endl; cout<<"Evade = "<< obj_job->GetAttackPoint ()<<endl; cout<<"Range Move = "<< obj_job->GetRangeMove ()<<endl; cout<<"Range Attck = "<< obj_job->GetRangeAttack ()<<endl<<endl; cout<<"Special = "<< obj_job->ShowSpecialArray()<<endl<<endl<<endl; i = Player.begin(); obj_job = *i; i = Player.begin()+1; obj_job2 = *i; cout<<"Terra Attack Amaterasu"<<endl; obj_job->Attack (*obj_job2); cout<<endl<<"Status Terra"<<endl; cout<<obj_job->GetName()<<" / "<< obj_job->GetJobName()<<" / "<<obj_job->GetRaceName()<<endl; cout<<"HP = "<< obj_job->GetHP ()<< "/"<<obj_job->GetHPDefault ()<< " SP = "<< obj_job->GetSP ()<< "/"<<obj_job->GetSPDefault ()<<endl<<endl; cout<<endl<<"Status Amaterasu"<<endl; cout<<obj_job2->GetName()<<" / "<< obj_job2->GetJobName()<<" / "<<obj_job2->GetRaceName()<<endl; cout<<"HP = "<< obj_job2->GetHP ()<< "/"<<obj_job2->GetHPDefault ()<< " SP = "<< obj_job2->GetSP ()<< "/"<<obj_job2->GetSPDefault ()<<endl<<endl; cout<<"Terra Mengisi SP 100"<<endl; obj_job->SetSP(100); cout<<obj_job->GetName()<<" / "<< obj_job->GetJobName()<<" / "<<obj_job->GetRaceName()<<endl; cout<<"HP = "<< obj_job->GetHP ()<< "/"<<obj_job->GetHPDefault ()<< " SP = "<< obj_job->GetSP ()<< "/"<<obj_job->GetSPDefault ()<<endl<<endl; cout<<"Terra Special Amaterasu"<<endl; obj_job->SetAttackTurn(false); //obj_job->Special(1,*obj_job2); cout<<endl<<"Terra wait"<<endl; cout<<"Status Terra"<<endl; cout<<obj_job->GetName()<<" / "<< obj_job->GetJobName()<<" / "<<obj_job->GetRaceName()<<endl; cout<<"HP = "<< obj_job->GetHP ()<< "/"<<obj_job->GetHPDefault ()<< " SP = "<< obj_job->GetSP ()<< "/"<<obj_job->GetSPDefault ()<<endl<<endl; cout<<endl<<"Status Amaterasu"<<endl; cout<<obj_job2->GetName()<<" / "<< obj_job2->GetJobName()<<" / "<<obj_job2->GetRaceName()<<endl; cout<<"HP = "<< obj_job2->GetHP ()<< "/"<<obj_job2->GetHPDefault ()<< " SP = "<< obj_job2->GetSP ()<< "/"<<obj_job2->GetSPDefault ()<<endl<<endl; obj_job->Wait(); obj_job->Status(); } catch (const char* e) { cout << e << endl; } return 0;}
[ "Ir1.kingdom@683c1cbb-0ac3-0733-434b-7841ce19f6b5", "rezanachmad@683c1cbb-0ac3-0733-434b-7841ce19f6b5" ]
[ [ [ 1, 18 ], [ 21, 21 ], [ 24, 24 ], [ 31, 31 ], [ 57, 57 ], [ 62, 62 ], [ 71, 71 ], [ 86, 86 ], [ 93, 99 ] ], [ [ 19, 20 ], [ 22, 23 ], [ 25, 30 ], [ 32, 56 ], [ 58, 61 ], [ 63, 70 ], [ 72, 85 ], [ 87, 92 ] ] ]
f27de8549be992064127749e4b5ae4cf79311244
fb16850c6d70f89751d75413b9c16a7a72821c39
/src/modules/timer/sdl/Timer.cpp
faf7e1bdbde56cadfc8686bba261aa3848ff6e9e
[ "Zlib" ]
permissive
tst2005/love
b5e852cc538c957e773cdf14f76d71263887f066
bdec6facdf6054d24c89bea10b1f6146d89da11f
refs/heads/master
2021-01-15T12:36:17.510573
2010-05-23T22:30:38
2010-05-23T22:30:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
cpp
/** * Copyright (c) 2006-2010 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #include <common/config.h> #ifdef LOVE_WINDOWS # include <windows.h> # include <time.h> #else # include <sys/time.h> #endif #include "Timer.h" namespace love { namespace timer { namespace sdl { Timer::Timer() : time_init(0), currTime(0), prevFpsUpdate(0), fps(0), fpsUpdateFrequency(1), frames(0), dt(0) { // Init the SDL timer system. if(SDL_InitSubSystem(SDL_INIT_TIMER) < 0) throw Exception(SDL_GetError()); } Timer::~Timer() { // Quit SDL timer. SDL_QuitSubSystem(SDL_INIT_TIMER); } const char * Timer::getName() const { return "love.timer.sdl"; } void Timer::step() { // Frames rendered frames++; // "Current" time is previous time by now. prevTime = currTime; // Get ticks from SDL currTime = SDL_GetTicks(); // Convert to number of seconds dt = (currTime - prevTime)/1000.0f; // Update FPS? if((currTime - prevFpsUpdate)/1000.0f > fpsUpdateFrequency) { fps = frames/fpsUpdateFrequency; prevFpsUpdate = currTime; frames = 0; } } void Timer::sleep(int ms) { if(ms > 0) SDL_Delay(ms); } float Timer::getDelta() const { return dt; } float Timer::getFPS() const { return fps; } float Timer::getTime() const { return (SDL_GetTicks() - time_init)/1000.0f; } float Timer::getMicroTime() const { #ifdef LOVE_WINDOWS __int64 ticks, freq; LARGE_INTEGER temp; QueryPerformanceCounter(&temp); ticks = temp.QuadPart; QueryPerformanceFrequency(&temp); freq = temp.QuadPart; __int64 secs = ticks/freq; __int64 usecs = static_cast<__int64>((ticks%freq)/(freq/1000000.0f)); return secs%86400 + usecs/1000000.0f; #else timeval t; gettimeofday(&t, NULL); return t.tv_sec%86400 + t.tv_usec/1000000.0f; #endif } } // sdl } // timer } // love
[ "none@none", "[email protected]" ]
[ [ [ 1, 18 ], [ 42, 43 ], [ 60, 77 ], [ 112, 112 ] ], [ [ 19, 41 ], [ 44, 59 ], [ 78, 111 ], [ 113, 123 ] ] ]
3e73dd3ccc597fc4ed34b0a0c8808c245a948a07
a5f2b47a82ea38742471c701cc5218d112166d5b
/xmlParser.cpp
384b66217e5e56ffe80841b84721f0dbd4a4029b
[]
no_license
BlaatSchaapArchive/blaatbot2009
621dacd1ca236a733c7971bad600a933c188661c
6d833a931914bfc4c16a1697131e9f69607dc872
refs/heads/master
2021-05-30T00:40:42.431969
2009-10-07T13:18:39
2009-10-07T13:18:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
109,509
cpp
/** **************************************************************************** * <P> XML.c - implementation file for basic XML parser written in ANSI C++ * for portability. It works by using recursion and a node tree for breaking * down the elements of an XML document. </P> * * @version V2.39 * @author Frank Vanden Berghen * * NOTE: * * If you add "#define STRICT_PARSING", on the first line of this file * the parser will see the following XML-stream: * <a><b>some text</b><b>other text </a> * as an error. Otherwise, this tring will be equivalent to: * <a><b>some text</b><b>other text</b></a> * * NOTE: * * If you add "#define APPROXIMATE_PARSING" on the first line of this file * the parser will see the following XML-stream: * <data name="n1"> * <data name="n2"> * <data name="n3" /> * as equivalent to the following XML-stream: * <data name="n1" /> * <data name="n2" /> * <data name="n3" /> * This can be useful for badly-formed XML-streams but prevent the use * of the following XML-stream (problem is: tags at contiguous levels * have the same names): * <data name="n1"> * <data name="n2"> * <data name="n3" /> * </data> * </data> * * NOTE: * * If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file * the "openFileHelper" function will always display error messages inside the * console instead of inside a message-box-window. Message-box-windows are * available on windows 9x/NT/2000/XP/Vista only. * * Copyright (c) 2002, Frank Vanden Berghen * All rights reserved. * * The following license terms apply to projects that are in some way related to * the "BlaatSchaap project", including applications * using "BlaatSchaap project" and tools developed * for enhancing "BlaatSchaap project". All other projects * (not related to "BlaatSchaap project") have to use this * code under the Aladdin Free Public License (AFPL) * See the file "AFPL-license.txt" for more informations about the AFPL license. * (see http://www.artifex.com/downloads/doc/Public.htm for detailed AFPL terms) * * 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 Frank Vanden Berghen 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 Frank Vanden Berghen ``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 <copyright holder> 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. * **************************************************************************** */ #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #include "xmlParser.h" #ifdef _XMLWINDOWS //#ifdef _DEBUG //#define _CRTDBG_MAP_ALLOC //#include <crtdbg.h> //#endif #define WIN32_LEAN_AND_MEAN #include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files // to have "MessageBoxA" to display error messages for openFilHelper #endif #include <memory.h> #include <assert.h> #include <stdio.h> #include <string.h> #include <stdlib.h> XMLCSTR XMLNode::getVersion() { return _CXML("v2.39"); } void freeXMLString(XMLSTR t){if(t)free(t);} static XMLNode::XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8; static char guessWideCharChars=1, dropWhiteSpace=1, removeCommentsInMiddleOfText=1; inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; } // You can modify the initialization of the variable "XMLClearTags" below // to change the clearTags that are currently recognized by the library. // The number on the second columns is the length of the string inside the // first column. The "<!DOCTYPE" declaration must be the second in the list. // The "<!--" declaration must be the third in the list. typedef struct { XMLCSTR lpszOpen; int openTagLen; XMLCSTR lpszClose;} ALLXMLClearTag; static ALLXMLClearTag XMLClearTags[] = { { _CXML("<![CDATA["),9, _CXML("]]>") }, { _CXML("<!DOCTYPE"),9, _CXML(">") }, { _CXML("<!--") ,4, _CXML("-->") }, { _CXML("<PRE>") ,5, _CXML("</PRE>") }, // { _CXML("<Script>") ,8, _CXML("</Script>")}, { NULL ,0, NULL } }; // You can modify the initialization of the variable "XMLEntities" below // to change the character entities that are currently recognized by the library. // The number on the second columns is the length of the string inside the // first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized. typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity; static XMLCharacterEntity XMLEntities[] = { { _CXML("&amp;" ), 5, _CXML('&' )}, { _CXML("&lt;" ), 4, _CXML('<' )}, { _CXML("&gt;" ), 4, _CXML('>' )}, { _CXML("&quot;"), 6, _CXML('\"')}, { _CXML("&apos;"), 6, _CXML('\'')}, { NULL , 0, '\0' } }; // When rendering the XMLNode to a string (using the "createXMLString" function), // you can ask for a beautiful formatting. This formatting is using the // following indentation character: #define INDENTCHAR _CXML('\t') // The following function parses the XML errors into a user friendly string. // You can edit this to change the output language of the library to something else. XMLCSTR XMLNode::getError(XMLError xerror) { switch (xerror) { case eXMLErrorNone: return _CXML("No error"); case eXMLErrorMissingEndTag: return _CXML("Warning: Unmatched end tag"); case eXMLErrorNoXMLTagFound: return _CXML("Warning: No XML tag found"); case eXMLErrorEmpty: return _CXML("Error: No XML data"); case eXMLErrorMissingTagName: return _CXML("Error: Missing start tag name"); case eXMLErrorMissingEndTagName: return _CXML("Error: Missing end tag name"); case eXMLErrorUnmatchedEndTag: return _CXML("Error: Unmatched end tag"); case eXMLErrorUnmatchedEndClearTag: return _CXML("Error: Unmatched clear tag end"); case eXMLErrorUnexpectedToken: return _CXML("Error: Unexpected token found"); case eXMLErrorNoElements: return _CXML("Error: No elements found"); case eXMLErrorFileNotFound: return _CXML("Error: File not found"); case eXMLErrorFirstTagNotFound: return _CXML("Error: First Tag not found"); case eXMLErrorUnknownCharacterEntity:return _CXML("Error: Unknown character entity"); case eXMLErrorCharacterCodeAbove255: return _CXML("Error: Character code above 255 is forbidden in MultiByte char mode."); case eXMLErrorCharConversionError: return _CXML("Error: unable to convert between WideChar and MultiByte chars"); case eXMLErrorCannotOpenWriteFile: return _CXML("Error: unable to open file for writing"); case eXMLErrorCannotWriteFile: return _CXML("Error: cannot write into file"); case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _CXML("Warning: Base64-string length is not a multiple of 4"); case eXMLErrorBase64DecodeTruncatedData: return _CXML("Warning: Base64-string is truncated"); case eXMLErrorBase64DecodeIllegalCharacter: return _CXML("Error: Base64-string contains an illegal character"); case eXMLErrorBase64DecodeBufferTooSmall: return _CXML("Error: Base64 decode output buffer is too small"); }; return _CXML("Unknown"); } ///////////////////////////////////////////////////////////////////////// // Here start the abstraction layer to be OS-independent // ///////////////////////////////////////////////////////////////////////// // Here is an abstraction layer to access some common string manipulation functions. // The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0, // Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++. // If you plan to "port" the library to a new system/compiler, all you have to do is // to edit the following lines. #ifdef XML_NO_WIDE_CHAR char myIsTextWideChar(const void *b, int len) { return FALSE; } #else #if defined (UNDER_CE) || !defined(_XMLWINDOWS) char myIsTextWideChar(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode { #ifdef sun // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer. if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE; #endif const wchar_t *s=(const wchar_t*)b; // buffer too small: if (len<(int)sizeof(wchar_t)) return FALSE; // odd length test if (len&1) return FALSE; /* only checks the first 256 characters */ len=mmin(256,len/sizeof(wchar_t)); // Check for the special byte order: if (*((unsigned short*)s) == 0xFFFE) return TRUE; // IS_TEXT_UNICODE_REVERSE_SIGNATURE; if (*((unsigned short*)s) == 0xFEFF) return TRUE; // IS_TEXT_UNICODE_SIGNATURE // checks for ASCII characters in the UNICODE stream int i,stats=0; for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++; if (stats>len/2) return TRUE; // Check for UNICODE NULL chars for (i=0; i<len; i++) if (!s[i]) return TRUE; return FALSE; } #else char myIsTextWideChar(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); }; #endif #endif #ifdef _XMLWINDOWS // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0 #ifdef _XMLWIDECHAR wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce) { int i; if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,NULL,0); else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,NULL,0); if (i<0) return NULL; wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR)); if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,d,i); else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,d,i); d[i]=0; return d; } static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return _wfopen(filename,mode); } static inline int xstrlen(XMLCSTR c) { return (int)wcslen(c); } static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _wcsnicmp(c1,c2,l);} static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _wcsicmp(c1,c2); } static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); } static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); } #else char *myWideCharToMultiByte(const wchar_t *s) { UINT codePage=CP_ACP; if (characterEncoding==XMLNode::char_encoding_UTF8) codePage=CP_UTF8; int i=(int)WideCharToMultiByte(codePage, // code page 0, // performance and mapping flags s, // wide-character string -1, // number of chars in string NULL, // buffer for new string 0, // size of buffer NULL, // default for unmappable chars NULL // set when default char used ); if (i<0) return NULL; char *d=(char*)malloc(i+1); WideCharToMultiByte(codePage, // code page 0, // performance and mapping flags s, // wide-character string -1, // number of chars in string d, // buffer for new string i, // size of buffer NULL, // default for unmappable chars NULL // set when default char used ); d[i]=0; return d; } static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); } static inline int xstrlen(XMLCSTR c) { return (int)strlen(c); } #ifdef __BORLANDC__ static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strnicmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return stricmp(c1,c2); } #else static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); } #endif static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);} static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); } static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); } #endif #else // for gcc and CC #ifdef XML_NO_WIDE_CHAR char *myWideCharToMultiByte(const wchar_t *s) { return NULL; } #else char *myWideCharToMultiByte(const wchar_t *s) { const wchar_t *ss=s; int i=(int)wcsrtombs(NULL,&ss,0,NULL); if (i<0) return NULL; char *d=(char *)malloc(i+1); wcsrtombs(d,&s,i,NULL); d[i]=0; return d; } #endif #ifdef _XMLWIDECHAR wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce) { const char *ss=s; int i=(int)mbsrtowcs(NULL,&ss,0,NULL); if (i<0) return NULL; wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t)); mbsrtowcs(d,&s,i,NULL); d[i]=0; return d; } int xstrlen(XMLCSTR c) { return wcslen(c); } #ifdef sun // for CC #include <widec.h> static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);} static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); } #else // for gcc static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);} static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); } #endif static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); } static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); } static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { char *filenameAscii=myWideCharToMultiByte(filename); FILE *f; if (mode[0]==_CXML('r')) f=fopen(filenameAscii,"rb"); else f=fopen(filenameAscii,"wb"); free(filenameAscii); return f; } #else static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); } static inline int xstrlen(XMLCSTR c) { return strlen(c); } static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);} static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);} static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); } static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); } static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); } #endif static inline int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);} #endif /////////////////////////////////////////////////////////////////////////////// // the "xmltoc,xmltob,xmltoi,xmltol,xmltof,xmltoa" functions // /////////////////////////////////////////////////////////////////////////////// // These 6 functions are not used inside the XMLparser. // There are only here as "convenience" functions for the user. // If you don't need them, you can delete them without any trouble. #ifdef _XMLWIDECHAR #ifdef _XMLWINDOWS // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0 char xmltob(XMLCSTR t,int v){ if (t&&(*t)) return (char)_wtoi(t); return v; } int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return _wtoi(t); return v; } long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return _wtol(t); return v; } double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; } #else #ifdef sun // for CC #include <widec.h> char xmltob(XMLCSTR t,int v){ if (t) return (char)wstol(t,NULL,10); return v; } int xmltoi(XMLCSTR t,int v){ if (t) return (int)wstol(t,NULL,10); return v; } long xmltol(XMLCSTR t,long v){ if (t) return wstol(t,NULL,10); return v; } #else // for gcc char xmltob(XMLCSTR t,int v){ if (t) return (char)wcstol(t,NULL,10); return v; } int xmltoi(XMLCSTR t,int v){ if (t) return (int)wcstol(t,NULL,10); return v; } long xmltol(XMLCSTR t,long v){ if (t) return wcstol(t,NULL,10); return v; } #endif double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; } #endif #else char xmltob(XMLCSTR t,char v){ if (t&&(*t)) return (char)atoi(t); return v; } int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return atoi(t); return v; } long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return atol(t); return v; } double xmltof(XMLCSTR t,double v){ if (t&&(*t)) return atof(t); return v; } #endif XMLCSTR xmltoa(XMLCSTR t,XMLCSTR v){ if (t) return t; return v; } XMLCHAR xmltoc(XMLCSTR t,XMLCHAR v){ if (t&&(*t)) return *t; return v; } ///////////////////////////////////////////////////////////////////////// // the "openFileHelper" function // ///////////////////////////////////////////////////////////////////////// // Since each application has its own way to report and deal with errors, you should modify & rewrite // the following "openFileHelper" function to get an "error reporting mechanism" tailored to your needs. XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag) { // guess the value of the global parameter "characterEncoding" // (the guess is based on the first 200 bytes of the file). FILE *f=xfopen(filename,_CXML("rb")); if (f) { char bb[205]; int l=(int)fread(bb,1,200,f); setGlobalOptions(guessCharEncoding(bb,l),guessWideCharChars,dropWhiteSpace,removeCommentsInMiddleOfText); fclose(f); } // parse the file XMLResults pResults; XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults); // display error message (if any) if (pResults.error != eXMLErrorNone) { // create message char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_CXML(""); if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; } sprintf(message, #ifdef _XMLWIDECHAR "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s" #else "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s" #endif ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3); // display message #if defined(_XMLWINDOWS) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_) MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST); #else printf("%s",message); #endif exit(255); } return xnode; } ///////////////////////////////////////////////////////////////////////// // Here start the core implementation of the XMLParser library // ///////////////////////////////////////////////////////////////////////// // You should normally not change anything below this point. #ifndef _XMLWIDECHAR // If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte. // If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes). // If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes). // This table is used as lookup-table to know the length of a character (in byte) based on the // content of the first byte of the character. // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ). static const char XML_utf8ByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte 4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid }; static const char XML_legacyByteTable[256] = { 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }; static const char XML_sjisByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 }; static const char XML_gb2312ByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0 }; static const char XML_gbk_big5_ByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0 }; static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8" #endif XMLNode XMLNode::emptyXMLNode; XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL}; XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL}; // Enumeration used to decipher what type a token is typedef enum XMLTokenTypeTag { eTokenText = 0, eTokenQuotedText, eTokenTagStart, /* "<" */ eTokenTagEnd, /* "</" */ eTokenCloseTag, /* ">" */ eTokenEquals, /* "=" */ eTokenDeclaration, /* "<?" */ eTokenShortHandClose, /* "/>" */ eTokenClear, eTokenError } XMLTokenType; // Main structure used for parsing XML typedef struct XML { XMLCSTR lpXML; XMLCSTR lpszText; int nIndex,nIndexMissigEndTag; enum XMLError error; XMLCSTR lpEndTag; int cbEndTag; XMLCSTR lpNewElement; int cbNewElement; int nFirst; } XML; typedef struct { ALLXMLClearTag *pClr; XMLCSTR pStr; } NextToken; // Enumeration used when parsing attributes typedef enum Attrib { eAttribName = 0, eAttribEquals, eAttribValue } Attrib; // Enumeration used when parsing elements to dictate whether we are currently // inside a tag typedef enum Status { eInsideTag = 0, eOutsideTag } Status; XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const { if (!d) return eXMLErrorNone; FILE *f=xfopen(filename,_CXML("wb")); if (!f) return eXMLErrorCannotOpenWriteFile; #ifdef _XMLWIDECHAR unsigned char h[2]={ 0xFF, 0xFE }; if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile; if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration()))) { if (!fwrite(L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40,1,f)) return eXMLErrorCannotWriteFile; } #else if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration()))) { if (characterEncoding==char_encoding_UTF8) { // header so that windows recognize the file as UTF-8: unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile; encoding="utf-8"; } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS"; if (!encoding) encoding="ISO-8859-1"; if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile; } else { if (characterEncoding==char_encoding_UTF8) { unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile; } } #endif int i; XMLSTR t=createXMLString(nFormat,&i); if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile; if (fclose(f)!=0) return eXMLErrorCannotWriteFile; free(t); return eXMLErrorNone; } // Duplicate a given string. XMLSTR stringDup(XMLCSTR lpszData, int cbData) { if (lpszData==NULL) return NULL; XMLSTR lpszNew; if (cbData==-1) cbData=(int)xstrlen(lpszData); lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR)); if (lpszNew) { memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR)); lpszNew[cbData] = (XMLCHAR)NULL; } return lpszNew; } XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source) { XMLSTR dd=dest; XMLCHAR ch; XMLCharacterEntity *entity; while ((ch=*source)) { entity=XMLEntities; do { if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; } entity++; } while(entity->s); #ifdef _XMLWIDECHAR *(dest++)=*(source++); #else switch(XML_ByteTable[(unsigned char)ch]) { case 4: *(dest++)=*(source++); case 3: *(dest++)=*(source++); case 2: *(dest++)=*(source++); case 1: *(dest++)=*(source++); } #endif out_of_loop1: ; } *dest=0; return dd; } // private (used while rendering): int ToXMLStringTool::lengthXMLString(XMLCSTR source) { int r=0; XMLCharacterEntity *entity; XMLCHAR ch; while ((ch=*source)) { entity=XMLEntities; do { if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; } entity++; } while(entity->s); #ifdef _XMLWIDECHAR r++; source++; #else ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch; #endif out_of_loop1: ; } return r; } ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); } void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; } XMLSTR ToXMLStringTool::toXML(XMLCSTR source) { int l=lengthXMLString(source)+1; if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); } return toXMLUnSafe(buf,source); } // private: XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML) { // This function is the opposite of the function "toXMLString". It decodes the escape // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters // &,",',<,>. This function is used internally by the XML Parser. All the calls to // the XML library will always gives you back "decoded" strings. // // in: string (s) and length (lo) of string // out: new allocated string converted from xml if (!s) return NULL; int ll=0,j; XMLSTR d; XMLCSTR ss=s; XMLCharacterEntity *entity; while ((lo>0)&&(*s)) { if (*s==_CXML('&')) { if ((lo>2)&&(s[1]==_CXML('#'))) { s+=2; lo-=2; if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; } while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++; if (*s!=_CXML(';')) { pXML->error=eXMLErrorUnknownCharacterEntity; return NULL; } s++; lo--; } else { entity=XMLEntities; do { if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; } entity++; } while(entity->s); if (!entity->s) { pXML->error=eXMLErrorUnknownCharacterEntity; return NULL; } } } else { #ifdef _XMLWIDECHAR s++; lo--; #else j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1; #endif } ll++; } d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR)); s=d; while (ll-->0) { if (*ss==_CXML('&')) { if (ss[1]==_CXML('#')) { ss+=2; j=0; if ((*ss==_CXML('X'))||(*ss==_CXML('x'))) { ss++; while (*ss!=_CXML(';')) { if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0'); else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10; else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10; else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;} ss++; } } else { while (*ss!=_CXML(';')) { if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0'); else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;} ss++; } } #ifndef _XMLWIDECHAR if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;} #endif (*d++)=(XMLCHAR)j; ss++; } else { entity=XMLEntities; do { if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; } entity++; } while(entity->s); } } else { #ifdef _XMLWIDECHAR *(d++)=*(ss++); #else switch(XML_ByteTable[(unsigned char)*ss]) { case 4: *(d++)=*(ss++); ll--; case 3: *(d++)=*(ss++); ll--; case 2: *(d++)=*(ss++); ll--; case 1: *(d++)=*(ss++); } #endif } } *d=0; return (XMLSTR)s; } #define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r'))) // private: char myTagCompare(XMLCSTR cclose, XMLCSTR copen) // !!!! WARNING strange convention&: // return 0 if equals // return 1 if different { if (!cclose) return 1; int l=(int)xstrlen(cclose); if (xstrnicmp(cclose, copen, l)!=0) return 1; const XMLCHAR c=copen[l]; if (XML_isSPACECHAR(c)|| (c==_CXML('/' ))|| (c==_CXML('<' ))|| (c==_CXML('>' ))|| (c==_CXML('=' ))) return 0; return 1; } // Obtain the next character from the string. static inline XMLCHAR getNextChar(XML *pXML) { XMLCHAR ch = pXML->lpXML[pXML->nIndex]; #ifdef _XMLWIDECHAR if (ch!=0) pXML->nIndex++; #else pXML->nIndex+=XML_ByteTable[(unsigned char)ch]; #endif return ch; } // Find the next token in a string. // pcbToken contains the number of characters that have been read. static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType) { NextToken result; XMLCHAR ch; XMLCHAR chTemp; int indexStart,nFoundMatch,nIsText=FALSE; result.pClr=NULL; // prevent warning // Find next non-white space character do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch); if (ch) { // Cache the current string pointer result.pStr = &pXML->lpXML[indexStart]; // First check whether the token is in the clear tag list (meaning it // does not need formatting). ALLXMLClearTag *ctag=XMLClearTags; do { if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0) { result.pClr=ctag; pXML->nIndex+=ctag->openTagLen-1; *pType=eTokenClear; return result; } ctag++; } while(ctag->lpszOpen); // If we didn't find a clear tag then check for standard tokens switch(ch) { // Check for quotes case _CXML('\''): case _CXML('\"'): // Type of token *pType = eTokenQuotedText; chTemp = ch; // Set the size nFoundMatch = FALSE; // Search through the string to find a matching quote while((ch = getNextChar(pXML))) { if (ch==chTemp) { nFoundMatch = TRUE; break; } if (ch==_CXML('<')) break; } // If we failed to find a matching quote if (nFoundMatch == FALSE) { pXML->nIndex=indexStart+1; nIsText=TRUE; break; } // 4.02.2002 // if (FindNonWhiteSpace(pXML)) pXML->nIndex--; break; // Equals (used with attribute values) case _CXML('='): *pType = eTokenEquals; break; // Close tag case _CXML('>'): *pType = eTokenCloseTag; break; // Check for tag start and tag end case _CXML('<'): // Peek at the next character to see if we have an end tag '</', // or an xml declaration '<?' chTemp = pXML->lpXML[pXML->nIndex]; // If we have a tag end... if (chTemp == _CXML('/')) { // Set the type and ensure we point at the next character getNextChar(pXML); *pType = eTokenTagEnd; } // If we have an XML declaration tag else if (chTemp == _CXML('?')) { // Set the type and ensure we point at the next character getNextChar(pXML); *pType = eTokenDeclaration; } // Otherwise we must have a start tag else { *pType = eTokenTagStart; } break; // Check to see if we have a short hand type end tag ('/>'). case _CXML('/'): // Peek at the next character to see if we have a short end tag '/>' chTemp = pXML->lpXML[pXML->nIndex]; // If we have a short hand end tag... if (chTemp == _CXML('>')) { // Set the type and ensure we point at the next character getNextChar(pXML); *pType = eTokenShortHandClose; break; } // If we haven't found a short hand closing tag then drop into the // text process // Other characters default: nIsText = TRUE; } // If this is a TEXT node if (nIsText) { // Indicate we are dealing with text *pType = eTokenText; while((ch = getNextChar(pXML))) { if XML_isSPACECHAR(ch) { indexStart++; break; } else if (ch==_CXML('/')) { // If we find a slash then this maybe text or a short hand end tag // Peek at the next character to see it we have short hand end tag ch=pXML->lpXML[pXML->nIndex]; // If we found a short hand end tag then we need to exit the loop if (ch==_CXML('>')) { pXML->nIndex--; break; } } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('='))) { pXML->nIndex--; break; } } } *pcbToken = pXML->nIndex-indexStart; } else { // If we failed to obtain a valid character *pcbToken = 0; *pType = eTokenError; result.pStr=NULL; } return result; } XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName) { if (!d) { free(lpszName); return NULL; } if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName); d->lpszName=lpszName; return lpszName; } // private: XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; } XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration) { d=(XMLNodeData*)malloc(sizeof(XMLNodeData)); d->ref_count=1; d->lpszName=NULL; d->nChild= 0; d->nText = 0; d->nClear = 0; d->nAttribute = 0; d->isDeclaration = isDeclaration; d->pParent = pParent; d->pChild= NULL; d->pText= NULL; d->pClear= NULL; d->pAttribute= NULL; d->pOrder= NULL; updateName_WOSD(lpszName); } XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); } XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); } #define MEMORYINCREASE 50 static inline void myFree(void *p) { if (p) free(p); } static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem) { if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); } if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem); // if (!p) // { // printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220); // } return p; } // private: XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype) { if (index<0) return -1; int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i; } // private: // update "order" information when deleting a content of a XMLNode int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index) { int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t); memmove(o+i, o+i+1, (n-i)*sizeof(int)); for (;i<n;i++) if ((o[i]&3)==(int)t) o[i]-=4; // We should normally do: // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int)); // but we skip reallocation because it's too time consuming. // Anyway, at the end, it will be free'd completely at once. return i; } void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype) { // in: *_pos is the position inside d->pOrder ("-1" means "EndOf") // out: *_pos is the index inside p p=myRealloc(p,(nc+1),memoryIncrease,size); int n=d->nChild+d->nText+d->nClear; d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int)); int pos=*_pos,*o=d->pOrder; if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; } int i=pos; memmove(o+i+1, o+i, (n-i)*sizeof(int)); while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++; if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; } o[i]=o[pos]; for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4; *_pos=pos=o[pos]>>2; memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size); return p; } // Add a child node to the given element. XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos) { if (!lpszName) return emptyXMLNode; d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild); d->pChild[pos].d=NULL; d->pChild[pos]=XMLNode(d,lpszName,isDeclaration); d->nChild++; return d->pChild[pos]; } // Add an attribute to an element. XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev) { if (!lpszName) return &emptyXMLAttribute; if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; } int nc=d->nAttribute; d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute)); XMLAttribute *pAttr=d->pAttribute+nc; pAttr->lpszName = lpszName; pAttr->lpszValue = lpszValuev; d->nAttribute++; return pAttr; } // Add text to the element. XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos) { if (!lpszValue) return NULL; if (!d) { myFree(lpszValue); return NULL; } d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText); d->pText[pos]=lpszValue; d->nText++; return lpszValue; } // Add clear (unformatted) text to the element. XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos) { if (!lpszValue) return &emptyXMLClear; if (!d) { myFree(lpszValue); return &emptyXMLClear; } d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear); XMLClear *pNewClear=d->pClear+pos; pNewClear->lpszValue = lpszValue; if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen; if (!lpszClose) lpszClose=XMLClearTags->lpszClose; pNewClear->lpszOpenTag = lpszOpen; pNewClear->lpszCloseTag = lpszClose; d->nClear++; return pNewClear; } // private: // Parse a clear (unformatted) type node. char XMLNode::parseClearTag(void *px, void *_pClear) { XML *pXML=(XML *)px; ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear); int cbTemp=0; XMLCSTR lpszTemp=NULL; XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex]; static XMLCSTR docTypeEnd=_CXML("]>"); // Find the closing tag // Seems the <!DOCTYPE need a better treatment so lets handle it if (pClear.lpszOpen==XMLClearTags[1].lpszOpen) { XMLCSTR pCh=lpXML; while (*pCh) { if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; } else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; } #ifdef _XMLWIDECHAR pCh++; #else pCh+=XML_ByteTable[(unsigned char)(*pCh)]; #endif } } else lpszTemp=xstrstr(lpXML, pClear.lpszClose); if (lpszTemp) { // Cache the size and increment the index cbTemp = (int)(lpszTemp - lpXML); pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose); // Add the clear node to the current element addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1); return 0; } // If we failed to find the end tag pXML->error = eXMLErrorUnmatchedEndClearTag; return 1; } void XMLNode::exactMemory(XMLNodeData *d) { if (d->pOrder) d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int)); if (d->pChild) d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode)); if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute)); if (d->pText) d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR)); if (d->pClear) d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear)); } char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr) { XML *pXML=(XML *)pa; XMLCSTR lpszText=pXML->lpszText; if (!lpszText) return 0; if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++; int cbText = (int)(tokenPStr - lpszText); if (!cbText) { pXML->lpszText=NULL; return 0; } if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; } if (!cbText) { pXML->lpszText=NULL; return 0; } XMLSTR lpt=fromXMLString(lpszText,cbText,pXML); if (!lpt) return 1; pXML->lpszText=NULL; if (removeCommentsInMiddleOfText && d->nText && d->nClear) { // if the previous insertion was a comment (<!-- -->) AND // if the previous previous insertion was a text then, delete the comment and append the text int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder; if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNodeText)) { int i=o[n]>>2; if (d->pClear[i].lpszOpenTag==XMLClearTags[2].lpszOpen) { deleteClear(i); i=o[n-1]>>2; n=xstrlen(d->pText[i]); int n2=xstrlen(lpt)+1; d->pText[i]=(XMLSTR)realloc((void*)d->pText[i],(n+n2)*sizeof(XMLCHAR)); if (!d->pText[i]) return 1; memcpy((void*)(d->pText[i]+n),lpt,n2*sizeof(XMLCHAR)); free(lpt); return 0; } } } addText_priv(MEMORYINCREASE,lpt,-1); return 0; } // private: // Recursively parse an XML element. int XMLNode::ParseXMLElement(void *pa) { XML *pXML=(XML *)pa; int cbToken; enum XMLTokenTypeTag xtype; NextToken token; XMLCSTR lpszTemp=NULL; int cbTemp=0; char nDeclaration; XMLNode pNew; enum Status status; // inside or outside a tag enum Attrib attrib = eAttribName; assert(pXML); // If this is the first call to the function if (pXML->nFirst) { // Assume we are outside of a tag definition pXML->nFirst = FALSE; status = eOutsideTag; } else { // If this is not the first call then we should only be called when inside a tag. status = eInsideTag; } // Iterate through the tokens in the document for(;;) { // Obtain the next token token = GetNextToken(pXML, &cbToken, &xtype); if (xtype != eTokenError) { // Check the current status switch(status) { // If we are outside of a tag definition case eOutsideTag: // Check what type of token we obtained switch(xtype) { // If we have found text or quoted text case eTokenText: case eTokenCloseTag: /* '>' */ case eTokenShortHandClose: /* '/>' */ case eTokenQuotedText: case eTokenEquals: break; // If we found a start tag '<' and declarations '<?' case eTokenTagStart: case eTokenDeclaration: // Cache whether this new element is a declaration or not nDeclaration = (xtype == eTokenDeclaration); // If we have node text then add this to the element if (maybeAddTxT(pXML,token.pStr)) return FALSE; // Find the name of the tag token = GetNextToken(pXML, &cbToken, &xtype); // Return an error if we couldn't obtain the next token or // it wasnt text if (xtype != eTokenText) { pXML->error = eXMLErrorMissingTagName; return FALSE; } // If we found a new element which is the same as this // element then we need to pass this back to the caller.. #ifdef APPROXIMATE_PARSING if (d->lpszName && myTagCompare(d->lpszName, token.pStr) == 0) { // Indicate to the caller that it needs to create a // new element. pXML->lpNewElement = token.pStr; pXML->cbNewElement = cbToken; return TRUE; } else #endif { // If the name of the new element differs from the name of // the current element we need to add the new element to // the current one and recurse pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1); while (!pNew.isEmpty()) { // Callself to process the new node. If we return // FALSE this means we dont have any more // processing to do... if (!pNew.ParseXMLElement(pXML)) return FALSE; else { // If the call to recurse this function // evented in a end tag specified in XML then // we need to unwind the calls to this // function until we find the appropriate node // (the element name and end tag name must // match) if (pXML->cbEndTag) { // If we are back at the root node then we // have an unmatched end tag if (!d->lpszName) { pXML->error=eXMLErrorUnmatchedEndTag; return FALSE; } // If the end tag matches the name of this // element then we only need to unwind // once more... if (myTagCompare(d->lpszName, pXML->lpEndTag)==0) { pXML->cbEndTag = 0; } return TRUE; } else if (pXML->cbNewElement) { // If the call indicated a new element is to // be created on THIS element. // If the name of this element matches the // name of the element we need to create // then we need to return to the caller // and let it process the element. if (myTagCompare(d->lpszName, pXML->lpNewElement)==0) { return TRUE; } // Add the new element and recurse pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1); pXML->cbNewElement = 0; } else { // If we didn't have a new element to create pNew = emptyXMLNode; } } } } break; // If we found an end tag case eTokenTagEnd: // If we have node text then add this to the element if (maybeAddTxT(pXML,token.pStr)) return FALSE; // Find the name of the end tag token = GetNextToken(pXML, &cbTemp, &xtype); // The end tag should be text if (xtype != eTokenText) { pXML->error = eXMLErrorMissingEndTagName; return FALSE; } lpszTemp = token.pStr; // After the end tag we should find a closing tag token = GetNextToken(pXML, &cbToken, &xtype); if (xtype != eTokenCloseTag) { pXML->error = eXMLErrorMissingEndTagName; return FALSE; } pXML->lpszText=pXML->lpXML+pXML->nIndex; // We need to return to the previous caller. If the name // of the tag cannot be found we need to keep returning to // caller until we find a match if (myTagCompare(d->lpszName, lpszTemp) != 0) #ifdef STRICT_PARSING { pXML->error=eXMLErrorUnmatchedEndTag; pXML->nIndexMissigEndTag=pXML->nIndex; return FALSE; } #else { pXML->error=eXMLErrorMissingEndTag; pXML->nIndexMissigEndTag=pXML->nIndex; pXML->lpEndTag = lpszTemp; pXML->cbEndTag = cbTemp; } #endif // Return to the caller exactMemory(d); return TRUE; // If we found a clear (unformatted) token case eTokenClear: // If we have node text then add this to the element if (maybeAddTxT(pXML,token.pStr)) return FALSE; if (parseClearTag(pXML, token.pClr)) return FALSE; pXML->lpszText=pXML->lpXML+pXML->nIndex; break; default: break; } break; // If we are inside a tag definition we need to search for attributes case eInsideTag: // Check what part of the attribute (name, equals, value) we // are looking for. switch(attrib) { // If we are looking for a new attribute case eAttribName: // Check what the current token type is switch(xtype) { // If the current type is text... // Eg. 'attribute' case eTokenText: // Cache the token then indicate that we are next to // look for the equals lpszTemp = token.pStr; cbTemp = cbToken; attrib = eAttribEquals; break; // If we found a closing tag... // Eg. '>' case eTokenCloseTag: // We are now outside the tag status = eOutsideTag; pXML->lpszText=pXML->lpXML+pXML->nIndex; break; // If we found a short hand '/>' closing tag then we can // return to the caller case eTokenShortHandClose: exactMemory(d); pXML->lpszText=pXML->lpXML+pXML->nIndex; return TRUE; // Errors... case eTokenQuotedText: /* '"SomeText"' */ case eTokenTagStart: /* '<' */ case eTokenTagEnd: /* '</' */ case eTokenEquals: /* '=' */ case eTokenDeclaration: /* '<?' */ case eTokenClear: pXML->error = eXMLErrorUnexpectedToken; return FALSE; default: break; } break; // If we are looking for an equals case eAttribEquals: // Check what the current token type is switch(xtype) { // If the current type is text... // Eg. 'Attribute AnotherAttribute' case eTokenText: // Add the unvalued attribute to the list addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL); // Cache the token then indicate. We are next to // look for the equals attribute lpszTemp = token.pStr; cbTemp = cbToken; break; // If we found a closing tag 'Attribute >' or a short hand // closing tag 'Attribute />' case eTokenShortHandClose: case eTokenCloseTag: // If we are a declaration element '<?' then we need // to remove extra closing '?' if it exists pXML->lpszText=pXML->lpXML+pXML->nIndex; if (d->isDeclaration && (lpszTemp[cbTemp-1]) == _CXML('?')) { cbTemp--; if (d->pParent && d->pParent->pParent) xtype = eTokenShortHandClose; } if (cbTemp) { // Add the unvalued attribute to the list addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL); } // If this is the end of the tag then return to the caller if (xtype == eTokenShortHandClose) { exactMemory(d); return TRUE; } // We are now outside the tag status = eOutsideTag; break; // If we found the equals token... // Eg. 'Attribute =' case eTokenEquals: // Indicate that we next need to search for the value // for the attribute attrib = eAttribValue; break; // Errors... case eTokenQuotedText: /* 'Attribute "InvalidAttr"'*/ case eTokenTagStart: /* 'Attribute <' */ case eTokenTagEnd: /* 'Attribute </' */ case eTokenDeclaration: /* 'Attribute <?' */ case eTokenClear: pXML->error = eXMLErrorUnexpectedToken; return FALSE; default: break; } break; // If we are looking for an attribute value case eAttribValue: // Check what the current token type is switch(xtype) { // If the current type is text or quoted text... // Eg. 'Attribute = "Value"' or 'Attribute = Value' or // 'Attribute = 'Value''. case eTokenText: case eTokenQuotedText: // If we are a declaration element '<?' then we need // to remove extra closing '?' if it exists if (d->isDeclaration && (token.pStr[cbToken-1]) == _CXML('?')) { cbToken--; } if (cbTemp) { // Add the valued attribute to the list if (xtype==eTokenQuotedText) { token.pStr++; cbToken-=2; } XMLSTR attrVal=(XMLSTR)token.pStr; if (attrVal) { attrVal=fromXMLString(attrVal,cbToken,pXML); if (!attrVal) return FALSE; } addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal); } // Indicate we are searching for a new attribute attrib = eAttribName; break; // Errors... case eTokenTagStart: /* 'Attr = <' */ case eTokenTagEnd: /* 'Attr = </' */ case eTokenCloseTag: /* 'Attr = >' */ case eTokenShortHandClose: /* "Attr = />" */ case eTokenEquals: /* 'Attr = =' */ case eTokenDeclaration: /* 'Attr = <?' */ case eTokenClear: pXML->error = eXMLErrorUnexpectedToken; return FALSE; break; default: break; } } } } // If we failed to obtain the next token else { if ((!d->isDeclaration)&&(d->pParent)) { #ifdef STRICT_PARSING pXML->error=eXMLErrorUnmatchedEndTag; #else pXML->error=eXMLErrorMissingEndTag; #endif pXML->nIndexMissigEndTag=pXML->nIndex; } maybeAddTxT(pXML,pXML->lpXML+pXML->nIndex); return FALSE; } } } // Count the number of lines and columns in an XML string. static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults) { XMLCHAR ch; assert(lpXML); assert(pResults); struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE }; pResults->nLine = 1; pResults->nColumn = 1; while (xml.nIndex<nUpto) { ch = getNextChar(&xml); if (ch != _CXML('\n')) pResults->nColumn++; else { pResults->nLine++; pResults->nColumn=1; } } } // Parse XML and return the root element. XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults) { if (!lpszXML) { if (pResults) { pResults->error=eXMLErrorNoElements; pResults->nLine=0; pResults->nColumn=0; } return emptyXMLNode; } XMLNode xnode(NULL,NULL,FALSE); struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE }; // Create header element xnode.ParseXMLElement(&xml); enum XMLError error = xml.error; if (!xnode.nChildNode()) error=eXMLErrorNoXMLTagFound; if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node // If no error occurred if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag)||(error==eXMLErrorNoXMLTagFound)) { XMLCSTR name=xnode.getName(); if (tag&&(*tag)&&((!name)||(xstricmp(name,tag)))) { xnode=xnode.getChildNode(tag); if (xnode.isEmpty()) { if (pResults) { pResults->error=eXMLErrorFirstTagNotFound; pResults->nLine=0; pResults->nColumn=0; } return emptyXMLNode; } } } else { // Cleanup: this will destroy all the nodes xnode = emptyXMLNode; } // If we have been given somewhere to place results if (pResults) { pResults->error = error; // If we have an error if (error!=eXMLErrorNone) { if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag; // Find which line and column it starts on. CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults); } } return xnode; } XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults) { if (pResults) { pResults->nLine=0; pResults->nColumn=0; } FILE *f=xfopen(filename,_CXML("rb")); if (f==NULL) { if (pResults) pResults->error=eXMLErrorFileNotFound; return emptyXMLNode; } fseek(f,0,SEEK_END); int l=ftell(f),headerSz=0; if (!l) { if (pResults) pResults->error=eXMLErrorEmpty; fclose(f); return emptyXMLNode; } fseek(f,0,SEEK_SET); unsigned char *buf=(unsigned char*)malloc(l+4); l=fread(buf,1,l,f); fclose(f); buf[l]=0;buf[l+1]=0;buf[l+2]=0;buf[l+3]=0; #ifdef _XMLWIDECHAR if (guessWideCharChars) { if (!myIsTextWideChar(buf,l)) { XMLNode::XMLCharEncoding ce=XMLNode::char_encoding_legacy; if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) { headerSz=3; ce=XMLNode::char_encoding_UTF8; } XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),ce); free(buf); buf=(unsigned char*)b2; headerSz=0; } else { if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2; if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2; } } #else if (guessWideCharChars) { if (myIsTextWideChar(buf,l)) { if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2; if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2; char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz)); free(buf); buf=(unsigned char*)b2; headerSz=0; } else { if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3; } } #endif if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; } XMLNode x=parseString((XMLSTR)(buf+headerSz),tag,pResults); free(buf); return x; } static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; } // private: // Creates an user friendly XML string from a given element with // appropriate white space and carriage returns. // // This recurses through all subnodes then adds contents of the nodes to the // string. int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat) { int nResult = 0; int cb=nFormat<0?0:nFormat; int cbElement; int nChildFormat=-1; int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear; int i,j; if ((nFormat>=0)&&(nElementI==1)&&(pEntry->nText==1)&&(!pEntry->isDeclaration)) nFormat=-2; assert(pEntry); #define LENSTR(lpsz) (lpsz ? xstrlen(lpsz) : 0) // If the element has no name then assume this is the head node. cbElement = (int)LENSTR(pEntry->lpszName); if (cbElement) { // "<elementname " if (lpszMarker) { if (cb) charmemset(lpszMarker, INDENTCHAR, cb); nResult = cb; lpszMarker[nResult++]=_CXML('<'); if (pEntry->isDeclaration) lpszMarker[nResult++]=_CXML('?'); xstrcpy(&lpszMarker[nResult], pEntry->lpszName); nResult+=cbElement; lpszMarker[nResult++]=_CXML(' '); } else { nResult+=cbElement+2+cb; if (pEntry->isDeclaration) nResult++; } // Enumerate attributes and add them to the string XMLAttribute *pAttr=pEntry->pAttribute; for (i=0; i<pEntry->nAttribute; i++) { // "Attrib cb = (int)LENSTR(pAttr->lpszName); if (cb) { if (lpszMarker) xstrcpy(&lpszMarker[nResult], pAttr->lpszName); nResult += cb; // "Attrib=Value " if (pAttr->lpszValue) { cb=(int)ToXMLStringTool::lengthXMLString(pAttr->lpszValue); if (lpszMarker) { lpszMarker[nResult]=_CXML('='); lpszMarker[nResult+1]=_CXML('"'); if (cb) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+2],pAttr->lpszValue); lpszMarker[nResult+cb+2]=_CXML('"'); } nResult+=cb+3; } if (lpszMarker) lpszMarker[nResult] = _CXML(' '); nResult++; } pAttr++; } if (pEntry->isDeclaration) { if (lpszMarker) { lpszMarker[nResult-1]=_CXML('?'); lpszMarker[nResult]=_CXML('>'); } nResult++; if (nFormat!=-1) { if (lpszMarker) lpszMarker[nResult]=_CXML('\n'); nResult++; } } else // If there are child nodes we need to terminate the start tag if (nElementI) { if (lpszMarker) lpszMarker[nResult-1]=_CXML('>'); if (nFormat>=0) { if (lpszMarker) lpszMarker[nResult]=_CXML('\n'); nResult++; } } else nResult--; } // Calculate the child format for when we recurse. This is used to // determine the number of spaces used for prefixes. if (nFormat!=-1) { if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1; else nChildFormat=nFormat; } // Enumerate through remaining children for (i=0; i<nElementI; i++) { j=pEntry->pOrder[i]; switch((XMLElementType)(j&3)) { // Text nodes case eNodeText: { // "Text" XMLCSTR pChild=pEntry->pText[j>>2]; cb = (int)ToXMLStringTool::lengthXMLString(pChild); if (cb) { if (nFormat>=0) { if (lpszMarker) { charmemset(&lpszMarker[nResult],INDENTCHAR,nFormat+1); ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+nFormat+1],pChild); lpszMarker[nResult+nFormat+1+cb]=_CXML('\n'); } nResult+=cb+nFormat+2; } else { if (lpszMarker) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult], pChild); nResult += cb; } } break; } // Clear type nodes case eNodeClear: { XMLClear *pChild=pEntry->pClear+(j>>2); // "OpenTag" cb = (int)LENSTR(pChild->lpszOpenTag); if (cb) { if (nFormat!=-1) { if (lpszMarker) { charmemset(&lpszMarker[nResult], INDENTCHAR, nFormat+1); xstrcpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag); } nResult+=cb+nFormat+1; } else { if (lpszMarker)xstrcpy(&lpszMarker[nResult], pChild->lpszOpenTag); nResult += cb; } } // "OpenTag Value" cb = (int)LENSTR(pChild->lpszValue); if (cb) { if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszValue); nResult += cb; } // "OpenTag Value CloseTag" cb = (int)LENSTR(pChild->lpszCloseTag); if (cb) { if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszCloseTag); nResult += cb; } if (nFormat!=-1) { if (lpszMarker) lpszMarker[nResult] = _CXML('\n'); nResult++; } break; } // Element nodes case eNodeChild: { // Recursively add child nodes nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat); break; } default: break; } } if ((cbElement)&&(!pEntry->isDeclaration)) { // If we have child entries we need to use long XML notation for // closing the element - "<elementname>blah blah blah</elementname>" if (nElementI) { // "</elementname>\0" if (lpszMarker) { if (nFormat >=0) { charmemset(&lpszMarker[nResult], INDENTCHAR,nFormat); nResult+=nFormat; } lpszMarker[nResult]=_CXML('<'); lpszMarker[nResult+1]=_CXML('/'); nResult += 2; xstrcpy(&lpszMarker[nResult], pEntry->lpszName); nResult += cbElement; lpszMarker[nResult]=_CXML('>'); if (nFormat == -1) nResult++; else { lpszMarker[nResult+1]=_CXML('\n'); nResult+=2; } } else { if (nFormat>=0) nResult+=cbElement+4+nFormat; else if (nFormat==-1) nResult+=cbElement+3; else nResult+=cbElement+4; } } else { // If there are no children we can use shorthand XML notation - // "<elementname/>" // "/>\0" if (lpszMarker) { lpszMarker[nResult]=_CXML('/'); lpszMarker[nResult+1]=_CXML('>'); if (nFormat != -1) lpszMarker[nResult+2]=_CXML('\n'); } nResult += nFormat == -1 ? 2 : 3; } } return nResult; } #undef LENSTR // Create an XML string // @param int nFormat - 0 if no formatting is required // otherwise nonzero for formatted text // with carriage returns and indentation. // @param int *pnSize - [out] pointer to the size of the // returned string not including the // NULL terminator. // @return XMLSTR - Allocated XML string, you must free // this with free(). XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const { if (!d) { if (pnSize) *pnSize=0; return NULL; } XMLSTR lpszResult = NULL; int cbStr; // Recursively Calculate the size of the XML string if (!dropWhiteSpace) nFormat=0; nFormat = nFormat ? 0 : -1; cbStr = CreateXMLStringR(d, 0, nFormat); // Alllocate memory for the XML string + the NULL terminator and // create the recursively XML string. lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR)); CreateXMLStringR(d, lpszResult, nFormat); lpszResult[cbStr]=_CXML('\0'); if (pnSize) *pnSize = cbStr; return lpszResult; } int XMLNode::detachFromParent(XMLNodeData *d) { XMLNode *pa=d->pParent->pChild; int i=0; while (((void*)(pa[i].d))!=((void*)d)) i++; d->pParent->nChild--; if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode)); else { free(pa); d->pParent->pChild=NULL; } return removeOrderElement(d->pParent,eNodeChild,i); } XMLNode::~XMLNode() { if (!d) return; d->ref_count--; emptyTheNode(0); } void XMLNode::deleteNodeContent() { if (!d) return; if (d->pParent) { detachFromParent(d); d->pParent=NULL; d->ref_count--; } emptyTheNode(1); } void XMLNode::emptyTheNode(char force) { XMLNodeData *dd=d; // warning: must stay this way! if ((dd->ref_count==0)||force) { if (d->pParent) detachFromParent(d); int i; XMLNode *pc; for(i=0; i<dd->nChild; i++) { pc=dd->pChild+i; pc->d->pParent=NULL; pc->d->ref_count--; pc->emptyTheNode(force); } myFree(dd->pChild); for(i=0; i<dd->nText; i++) free((void*)dd->pText[i]); myFree(dd->pText); for(i=0; i<dd->nClear; i++) free((void*)dd->pClear[i].lpszValue); myFree(dd->pClear); for(i=0; i<dd->nAttribute; i++) { free((void*)dd->pAttribute[i].lpszName); if (dd->pAttribute[i].lpszValue) free((void*)dd->pAttribute[i].lpszValue); } myFree(dd->pAttribute); myFree(dd->pOrder); myFree((void*)dd->lpszName); dd->nChild=0; dd->nText=0; dd->nClear=0; dd->nAttribute=0; dd->pChild=NULL; dd->pText=NULL; dd->pClear=NULL; dd->pAttribute=NULL; dd->pOrder=NULL; dd->lpszName=NULL; dd->pParent=NULL; } if (dd->ref_count==0) { free(dd); d=NULL; } } XMLNode& XMLNode::operator=( const XMLNode& A ) { // shallow copy if (this != &A) { if (d) { d->ref_count--; emptyTheNode(0); } d=A.d; if (d) (d->ref_count) ++ ; } return *this; } XMLNode::XMLNode(const XMLNode &A) { // shallow copy d=A.d; if (d) (d->ref_count)++ ; } XMLNode XMLNode::deepCopy() const { if (!d) return XMLNode::emptyXMLNode; XMLNode x(NULL,stringDup(d->lpszName),d->isDeclaration); XMLNodeData *p=x.d; int n=d->nAttribute; if (n) { p->nAttribute=n; p->pAttribute=(XMLAttribute*)malloc(n*sizeof(XMLAttribute)); while (n--) { p->pAttribute[n].lpszName=stringDup(d->pAttribute[n].lpszName); p->pAttribute[n].lpszValue=stringDup(d->pAttribute[n].lpszValue); } } if (d->pOrder) { n=(d->nChild+d->nText+d->nClear)*sizeof(int); p->pOrder=(int*)malloc(n); memcpy(p->pOrder,d->pOrder,n); } n=d->nText; if (n) { p->nText=n; p->pText=(XMLCSTR*)malloc(n*sizeof(XMLCSTR)); while(n--) p->pText[n]=stringDup(d->pText[n]); } n=d->nClear; if (n) { p->nClear=n; p->pClear=(XMLClear*)malloc(n*sizeof(XMLClear)); while (n--) { p->pClear[n].lpszCloseTag=d->pClear[n].lpszCloseTag; p->pClear[n].lpszOpenTag=d->pClear[n].lpszOpenTag; p->pClear[n].lpszValue=stringDup(d->pClear[n].lpszValue); } } n=d->nChild; if (n) { p->nChild=n; p->pChild=(XMLNode*)malloc(n*sizeof(XMLNode)); while (n--) { p->pChild[n].d=NULL; p->pChild[n]=d->pChild[n].deepCopy(); p->pChild[n].d->pParent=p; } } return x; } XMLNode XMLNode::addChild(XMLNode childNode, int pos) { XMLNodeData *dc=childNode.d; if ((!dc)||(!d)) return childNode; if (!dc->lpszName) { // this is a root node: todo: correct fix int j=pos; while (dc->nChild) { addChild(dc->pChild[0],j); if (pos>=0) j++; } return childNode; } if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++; dc->pParent=d; // int nc=d->nChild; // d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode)); d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild); d->pChild[pos].d=dc; d->nChild++; return childNode; } void XMLNode::deleteAttribute(int i) { if ((!d)||(i<0)||(i>=d->nAttribute)) return; d->nAttribute--; XMLAttribute *p=d->pAttribute+i; free((void*)p->lpszName); if (p->lpszValue) free((void*)p->lpszValue); if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; } } void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); } void XMLNode::deleteAttribute(XMLCSTR lpszName) { int j=0; getAttribute(lpszName,&j); if (j) deleteAttribute(j-1); } XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,int i) { if (!d) { if (lpszNewValue) free(lpszNewValue); if (lpszNewName) free(lpszNewName); return NULL; } if (i>=d->nAttribute) { if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue); return NULL; } XMLAttribute *p=d->pAttribute+i; if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue); p->lpszValue=lpszNewValue; if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; }; return p; } XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute) { if (oldAttribute) return updateAttribute_WOSD((XMLSTR)newAttribute->lpszValue,(XMLSTR)newAttribute->lpszName,oldAttribute->lpszName); return addAttribute_WOSD((XMLSTR)newAttribute->lpszName,(XMLSTR)newAttribute->lpszValue); } XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,XMLCSTR lpszOldName) { int j=0; getAttribute(lpszOldName,&j); if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1); else { if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue); else return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue); } } int XMLNode::indexText(XMLCSTR lpszValue) const { if (!d) return -1; int i,l=d->nText; if (!lpszValue) { if (l) return 0; return -1; } XMLCSTR *p=d->pText; for (i=0; i<l; i++) if (lpszValue==p[i]) return i; return -1; } void XMLNode::deleteText(int i) { if ((!d)||(i<0)||(i>=d->nText)) return; d->nText--; XMLCSTR *p=d->pText+i; free((void*)*p); if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; } removeOrderElement(d,eNodeText,i); } void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); } XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, int i) { if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; } if (i>=d->nText) return addText_WOSD(lpszNewValue); XMLCSTR *p=d->pText+i; if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; } return lpszNewValue; } XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue) { if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; } int i=indexText(lpszOldValue); if (i>=0) return updateText_WOSD(lpszNewValue,i); return addText_WOSD(lpszNewValue); } void XMLNode::deleteClear(int i) { if ((!d)||(i<0)||(i>=d->nClear)) return; d->nClear--; XMLClear *p=d->pClear+i; free((void*)p->lpszValue); if (d->nClear) memmove(p,p+1,(d->nClear-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; } removeOrderElement(d,eNodeClear,i); } int XMLNode::indexClear(XMLCSTR lpszValue) const { if (!d) return -1; int i,l=d->nClear; if (!lpszValue) { if (l) return 0; return -1; } XMLClear *p=d->pClear; for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i; return -1; } void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); } void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); } XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, int i) { if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; } if (i>=d->nClear) return addClear_WOSD(lpszNewContent); XMLClear *p=d->pClear+i; if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; } return p; } XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, XMLCSTR lpszOldValue) { if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; } int i=indexClear(lpszOldValue); if (i>=0) return updateClear_WOSD(lpszNewContent,i); return addClear_WOSD(lpszNewContent); } XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP) { if (oldP) return updateClear_WOSD((XMLSTR)newP->lpszValue,(XMLSTR)oldP->lpszValue); return NULL; } int XMLNode::nChildNode(XMLCSTR name) const { if (!d) return 0; int i,j=0,n=d->nChild; XMLNode *pc=d->pChild; for (i=0; i<n; i++) { if (xstricmp(pc->d->lpszName, name)==0) j++; pc++; } return j; } XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const { if (!d) return emptyXMLNode; int i=0,n=d->nChild; if (j) i=*j; XMLNode *pc=d->pChild+i; for (; i<n; i++) { if (!xstricmp(pc->d->lpszName, name)) { if (j) *j=i+1; return *pc; } pc++; } return emptyXMLNode; } XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const { if (!d) return emptyXMLNode; if (j>=0) { int i=0; while (j-->0) getChildNode(name,&i); return getChildNode(name,&i); } int i=d->nChild; while (i--) if (!xstricmp(name,d->pChild[i].d->lpszName)) break; if (i<0) return emptyXMLNode; return getChildNode(i); } XMLNode XMLNode::getChildNodeByPath(XMLCSTR _path, char createMissing, XMLCHAR sep) { XMLSTR path=stringDup(_path); XMLNode x=getChildNodeByPathNonConst(path,createMissing,sep); if (path) free(path); return x; } XMLNode XMLNode::getChildNodeByPathNonConst(XMLSTR path, char createIfMissing, XMLCHAR sep) { if ((!path)||(!(*path))) return *this; XMLNode xn,xbase=*this; XMLCHAR *tend1,sepString[2]; sepString[0]=sep; sepString[1]=0; tend1=xstrstr(path,sepString); while(tend1) { *tend1=0; xn=xbase.getChildNode(path); *tend1=sep; if (xn.isEmpty()) { if (createIfMissing) xn=xbase.addChild(path); else return XMLNode::emptyXMLNode; } xbase=xn; path=tend1+1; tend1=xstrstr(path,sepString); } xn=xbase.getChildNode(path); if (xn.isEmpty()&&createIfMissing) xn=xbase.addChild(path); return xn; } XMLElementPosition XMLNode::positionOfText (int i) const { if (i>=d->nText ) i=d->nText-1; return findPosition(d,i,eNodeText ); } XMLElementPosition XMLNode::positionOfClear (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); } XMLElementPosition XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); } XMLElementPosition XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); } XMLElementPosition XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); } XMLElementPosition XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); } XMLElementPosition XMLNode::positionOfChildNode(XMLNode x) const { if ((!d)||(!x.d)) return -1; XMLNodeData *dd=x.d; XMLNode *pc=d->pChild; int i=d->nChild; while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild); return -1; } XMLElementPosition XMLNode::positionOfChildNode(XMLCSTR name, int count) const { if (!name) return positionOfChildNode(count); int j=0; do { getChildNode(name,&j); if (j<0) return -1; } while (count--); return findPosition(d,j-1,eNodeChild); } XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const { int i=0,j; if (k) i=*k; XMLNode x; XMLCSTR t; do { x=getChildNode(name,&i); if (!x.isEmpty()) { if (attributeValue) { j=0; do { t=x.getAttribute(attributeName,&j); if (t&&(xstricmp(attributeValue,t)==0)) { if (k) *k=i; return x; } } while (t); } else { if (x.isAttributeSet(attributeName)) { if (k) *k=i; return x; } } } } while (!x.isEmpty()); return emptyXMLNode; } // Find an attribute on an node. XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const { if (!d) return NULL; int i=0,n=d->nAttribute; if (j) i=*j; XMLAttribute *pAttr=d->pAttribute+i; for (; i<n; i++) { if (xstricmp(pAttr->lpszName, lpszAttrib)==0) { if (j) *j=i+1; return pAttr->lpszValue; } pAttr++; } return NULL; } char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const { if (!d) return FALSE; int i,n=d->nAttribute; XMLAttribute *pAttr=d->pAttribute; for (i=0; i<n; i++) { if (xstricmp(pAttr->lpszName, lpszAttrib)==0) { return TRUE; } pAttr++; } return FALSE; } XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const { if (!d) return NULL; int i=0; while (j-->0) getAttribute(name,&i); return getAttribute(name,&i); } XMLNodeContents XMLNode::enumContents(int i) const { XMLNodeContents c; if (!d) { c.etype=eNodeNULL; return c; } if (i<d->nAttribute) { c.etype=eNodeAttribute; c.attrib=d->pAttribute[i]; return c; } i-=d->nAttribute; c.etype=(XMLElementType)(d->pOrder[i]&3); i=(d->pOrder[i])>>2; switch (c.etype) { case eNodeChild: c.child = d->pChild[i]; break; case eNodeText: c.text = d->pText[i]; break; case eNodeClear: c.clear = d->pClear[i]; break; default: break; } return c; } XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName; } int XMLNode::nText() const { if (!d) return 0; return d->nText; } int XMLNode::nChildNode() const { if (!d) return 0; return d->nChild; } int XMLNode::nAttribute() const { if (!d) return 0; return d->nAttribute; } int XMLNode::nClear() const { if (!d) return 0; return d->nClear; } int XMLNode::nElement() const { if (!d) return 0; return d->nAttribute+d->nChild+d->nText+d->nClear; } XMLClear XMLNode::getClear (int i) const { if ((!d)||(i>=d->nClear )) return emptyXMLClear; return d->pClear[i]; } XMLAttribute XMLNode::getAttribute (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; } XMLCSTR XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszName; } XMLCSTR XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszValue; } XMLCSTR XMLNode::getText (int i) const { if ((!d)||(i>=d->nText )) return NULL; return d->pText[i]; } XMLNode XMLNode::getChildNode (int i) const { if ((!d)||(i>=d->nChild )) return emptyXMLNode; return d->pChild[i]; } XMLNode XMLNode::getParentNode ( ) const { if ((!d)||(!d->pParent )) return emptyXMLNode; return XMLNode(d->pParent); } char XMLNode::isDeclaration ( ) const { if (!d) return 0; return d->isDeclaration; } char XMLNode::isEmpty ( ) const { return (d==NULL); } XMLNode XMLNode::emptyNode ( ) { return XMLNode::emptyXMLNode; } XMLNode XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, XMLElementPosition pos) { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); } XMLNode XMLNode::addChild_WOSD(XMLSTR lpszName, char isDeclaration, XMLElementPosition pos) { return addChild_priv(0,lpszName,isDeclaration,pos); } XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue) { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); } XMLAttribute *XMLNode::addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValuev) { return addAttribute_priv(0,lpszName,lpszValuev); } XMLCSTR XMLNode::addText(XMLCSTR lpszValue, XMLElementPosition pos) { return addText_priv(0,stringDup(lpszValue),pos); } XMLCSTR XMLNode::addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos) { return addText_priv(0,lpszValue,pos); } XMLClear *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos) { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); } XMLClear *XMLNode::addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos) { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); } XMLCSTR XMLNode::updateName(XMLCSTR lpszName) { return updateName_WOSD(stringDup(lpszName)); } XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute) { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); } XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i) { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); } XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName) { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); } XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, int i) { return updateText_WOSD(stringDup(lpszNewValue),i); } XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue) { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); } XMLClear *XMLNode::updateClear(XMLCSTR lpszNewContent, int i) { return updateClear_WOSD(stringDup(lpszNewContent),i); } XMLClear *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue) { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); } XMLClear *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP) { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); } char XMLNode::setGlobalOptions(XMLCharEncoding _characterEncoding, char _guessWideCharChars, char _dropWhiteSpace, char _removeCommentsInMiddleOfText) { guessWideCharChars=_guessWideCharChars; dropWhiteSpace=_dropWhiteSpace; removeCommentsInMiddleOfText=_removeCommentsInMiddleOfText; #ifdef _XMLWIDECHAR if (_characterEncoding) characterEncoding=_characterEncoding; #else switch(_characterEncoding) { case char_encoding_UTF8: characterEncoding=_characterEncoding; XML_ByteTable=XML_utf8ByteTable; break; case char_encoding_legacy: characterEncoding=_characterEncoding; XML_ByteTable=XML_legacyByteTable; break; case char_encoding_ShiftJIS: characterEncoding=_characterEncoding; XML_ByteTable=XML_sjisByteTable; break; case char_encoding_GB2312: characterEncoding=_characterEncoding; XML_ByteTable=XML_gb2312ByteTable; break; case char_encoding_Big5: case char_encoding_GBK: characterEncoding=_characterEncoding; XML_ByteTable=XML_gbk_big5_ByteTable; break; default: return 1; } #endif return 0; } XMLNode::XMLCharEncoding XMLNode::guessCharEncoding(void *buf,int l, char useXMLEncodingAttribute) { #ifdef _XMLWIDECHAR return (XMLCharEncoding)0; #else if (l<25) return (XMLCharEncoding)0; if (guessWideCharChars&&(myIsTextWideChar(buf,l))) return (XMLCharEncoding)0; unsigned char *b=(unsigned char*)buf; if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return char_encoding_UTF8; // Match utf-8 model ? XMLCharEncoding bestGuess=char_encoding_UTF8; int i=0; while (i<l) switch (XML_utf8ByteTable[b[i]]) { case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ? case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ? case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ? case 1: i++; break; case 0: i=l; } if (!useXMLEncodingAttribute) return bestGuess; // if encoding is specified and different from utf-8 than it's non-utf8 // otherwise it's utf-8 char bb[201]; l=mmin(l,200); memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0" bb[l]=0; b=(unsigned char*)strstr(bb,"encoding"); if (!b) return bestGuess; b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return bestGuess; b++; while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return bestGuess; b++; while XML_isSPACECHAR(*b) b++; if ((xstrnicmp((char*)b,"utf-8",5)==0)|| (xstrnicmp((char*)b,"utf8",4)==0)) { if (bestGuess==char_encoding_legacy) return char_encoding_error; return char_encoding_UTF8; } if ((xstrnicmp((char*)b,"shiftjis",8)==0)|| (xstrnicmp((char*)b,"shift-jis",9)==0)|| (xstrnicmp((char*)b,"sjis",4)==0)) return char_encoding_ShiftJIS; if (xstrnicmp((char*)b,"GB2312",6)==0) return char_encoding_GB2312; if (xstrnicmp((char*)b,"Big5",4)==0) return char_encoding_Big5; if (xstrnicmp((char*)b,"GBK",3)==0) return char_encoding_GBK; return char_encoding_legacy; #endif } #undef XML_isSPACECHAR ////////////////////////////////////////////////////////// // Here starts the base64 conversion functions. // ////////////////////////////////////////////////////////// static const char base64Fillchar = _CXML('='); // used to mark partial words at the end // this lookup table defines the base64 encoding XMLCSTR base64EncodeTable=_CXML("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); // Decode Table gives the index of any valid base64 character in the Base64 table] // 96: '=' - 97: space char - 98: illegal char - 99: end of string const unsigned char base64DecodeTable[] = { 99,98,98,98,98,98,98,98,98,97, 97,98,98,97,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //00 -29 98,98,97,98,98,98,98,98,98,98, 98,98,98,62,98,98,98,63,52,53, 54,55,56,57,58,59,60,61,98,98, //30 -59 98,96,98,98,98, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 15,16,17,18,19,20,21,22,23,24, //60 -89 25,98,98,98,98,98,98,26,27,28, 29,30,31,32,33,34,35,36,37,38, 39,40,41,42,43,44,45,46,47,48, //90 -119 49,50,51,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //120 -149 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //150 -179 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //180 -209 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //210 -239 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98 //240 -255 }; XMLParserBase64Tool::~XMLParserBase64Tool(){ freeBuffer(); } void XMLParserBase64Tool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; } int XMLParserBase64Tool::encodeLength(int inlen, char formatted) { unsigned int i=((inlen-1)/3*4+4+1); if (formatted) i+=inlen/54; return i; } XMLSTR XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, char formatted) { int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j; alloc(i*sizeof(XMLCHAR)); XMLSTR curr=(XMLSTR)buf; for(i=0;i<eLen;i++) { // Copy next three bytes into lower 24 bits of int, paying attention to sign. j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3; // Encode the int into four chars *(curr++)=base64EncodeTable[ j>>18 ]; *(curr++)=base64EncodeTable[(j>>12)&0x3f]; *(curr++)=base64EncodeTable[(j>> 6)&0x3f]; *(curr++)=base64EncodeTable[(j )&0x3f]; if (formatted) { if (!k) { *(curr++)=_CXML('\n'); k=18; } k--; } } eLen=inlen-eLen*3; // 0 - 2. if (eLen==1) { *(curr++)=base64EncodeTable[ inbuf[0]>>2 ]; *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F]; *(curr++)=base64Fillchar; *(curr++)=base64Fillchar; } else if (eLen==2) { j=(inbuf[0]<<8)|inbuf[1]; *(curr++)=base64EncodeTable[ j>>10 ]; *(curr++)=base64EncodeTable[(j>> 4)&0x3f]; *(curr++)=base64EncodeTable[(j<< 2)&0x3f]; *(curr++)=base64Fillchar; } *(curr++)=0; return (XMLSTR)buf; } unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe) { if (xe) *xe=eXMLErrorNone; int size=0; unsigned char c; //skip any extra characters (e.g. newlines or spaces) while (*data) { #ifdef _XMLWIDECHAR if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; } #endif c=base64DecodeTable[(unsigned char)(*data)]; if (c<97) size++; else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; } data++; } if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4; if (size==0) return 0; do { data--; size--; } while(*data==base64Fillchar); size++; return (unsigned int)((size*3)/4); } unsigned char XMLParserBase64Tool::decode(XMLCSTR data, unsigned char *buf, int len, XMLError *xe) { if (xe) *xe=eXMLErrorNone; int i=0,p=0; unsigned char d,c; for(;;) { #ifdef _XMLWIDECHAR #define BASE64DECODE_READ_NEXT_CHAR(c) \ do { \ if (data[i]>255){ c=98; break; } \ c=base64DecodeTable[(unsigned char)data[i++]]; \ }while (c==97); \ if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; } #else #define BASE64DECODE_READ_NEXT_CHAR(c) \ do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97); \ if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; } #endif BASE64DECODE_READ_NEXT_CHAR(c) if (c==99) { return 2; } if (c==96) { if (p==(int)len) return 2; if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } BASE64DECODE_READ_NEXT_CHAR(d) if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } if (p==(int)len) { if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; } buf[p++]=(unsigned char)((c<<2)|((d>>4)&0x3)); BASE64DECODE_READ_NEXT_CHAR(c) if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } if (p==(int)len) { if (c==96) return 2; if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; } if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } buf[p++]=(unsigned char)(((d<<4)&0xf0)|((c>>2)&0xf)); BASE64DECODE_READ_NEXT_CHAR(d) if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } if (p==(int)len) { if (d==96) return 2; if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; } if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; } buf[p++]=(unsigned char)(((c<<6)&0xc0)|d); } } #undef BASE64DECODE_READ_NEXT_CHAR void XMLParserBase64Tool::alloc(int newsize) { if ((!buf)&&(newsize)) { buf=malloc(newsize); buflen=newsize; return; } if (newsize>buflen) { buf=realloc(buf,newsize); buflen=newsize; } } unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe) { if (xe) *xe=eXMLErrorNone; unsigned int len=decodeSize(data,xe); if (outlen) *outlen=len; if (!len) return NULL; alloc(len+1); if(!decode(data,(unsigned char*)buf,len,xe)){ return NULL; } return (unsigned char*)buf; }
[ "a-v-s@4cf8d54c-4f4b-0410-90c1-e2b051bf5457" ]
[ [ [ 1, 2888 ] ] ]
ee6934fc53260113ac0ebec34959580a88af048e
6e6a5795695595e18aa732ab0973d17936ebed84
/objects/Wall.cpp
446c10c0d07c6d6fbc1ebdb26421e83cb3b4d2bb
[]
no_license
nhocki/Ray-Tracer
18aadf47b8050247c6778d2b68fb5d381d3f6916
49cdccefbf7249873a142db0f6c7ccfea267c400
refs/heads/master
2021-01-19T10:27:01.517118
2009-05-14T11:36:09
2009-05-14T11:36:09
186,298
2
1
null
null
null
null
UTF-8
C++
false
false
2,001
cpp
#include "Wall.h" Wall::Wall() { //Wall(Vector3(-20.0f, 0.0f, 20.0f), Vector3(20.0f, 0.0f, -20.0f), Vector3(20.0f, 0.0f, 20.0f), Color(1,1,1), Color(1,1,1), Color(1,1,1), 1); } Wall:: Wall(Vector3 min, Vector3 max, Vector3 other, Material mat, bool em, bool inf) :Object((min+max)/2, mat, em) { Wall::min = min; Wall::max = max; infinite = inf; Vector3 u = min - other; Vector3 v = max - other; Vector3 n = v.cross(u).normalize(); a = n[0], b = n[1], c = n[2]; d = -(a*min[0] + b*min[1] + c*min[2]); } Wall:: Wall(Vector3 min, Vector3 max, Vector3 other, Material mat, Texture tex, bool em, bool inf) :Object((min+max)/2, mat, tex, em) { Wall::min = min; Wall::max = max; infinite = infinite; Vector3 u = min - other; Vector3 v = max - other; Vector3 n = v.cross(u).normalize(); a = n[0], b = n[1], c = n[2]; d = -(a*min[0] + b*min[1] + c*min[2]); } /* Get the plane ecuation components */ double Wall::getA(void){return a;} double Wall::getB(void){return b;} double Wall::getC(void){return c;} double Wall::getD(void){return d;} Vector3 Wall::getNorm(Vector3 &p) { Vector3 n(a,b,c); n.normalize(); return n; } /* A point wiil never be inside a plane */ bool Wall::isInside(Vector3 &point) { return false; } /* Gets the color in the specified object point * Used for textures only */ Color Wall::getColor(Vector3 &p) { return tex.getColor((p[0]-min[0])/14, (p[2]-min[2])/12); } /* Intersection between a ray and a plane If there is no intersection it returns -1 */ double Wall::rayIntersection(Ray &ray) { Vector3 n(a,b,c); double dot = n.dot(ray.getDir()); if(dot >= 0)return -1; double t = -(d + n.dot(ray.getOrigin()))/dot; Vector3 p = ray.getPoint(t); if(infinite || (p >= min && p <= max)) return t; return -1; }
[ "[email protected]", "alejandro@pelaez-desktop.(none)" ]
[ [ [ 1, 6 ], [ 9, 11 ], [ 13, 13 ], [ 16, 18 ], [ 33, 33 ], [ 35, 44 ], [ 46, 46 ], [ 66, 71 ], [ 74, 75 ], [ 77, 80 ], [ 83, 84 ], [ 86, 86 ] ], [ [ 7, 8 ], [ 12, 12 ], [ 14, 15 ], [ 19, 32 ], [ 34, 34 ], [ 45, 45 ], [ 47, 65 ], [ 72, 73 ], [ 76, 76 ], [ 81, 82 ], [ 85, 85 ] ] ]
d5693f0f481559fefc49629da6dc27cbb0831160
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSFacet.hpp
c9ae6660f16aa9da3b11a0c1dfe1c180898ac8e6
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
4,957
hpp
/* * Copyright 2003,2004 The Apache Software Foundation. * * 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. */ /* * $Log: XSFacet.hpp,v $ * Revision 1.7 2004/09/08 13:56:08 peiyongz * Apache License Version 2.0 * * Revision 1.6 2003/12/01 23:23:26 neilg * fix for bug 25118; thanks to Jeroen Witmond * * Revision 1.5 2003/11/21 17:29:53 knoaman * PSVI update * * Revision 1.4 2003/11/14 22:47:53 neilg * fix bogus log message from previous commit... * * Revision 1.3 2003/11/14 22:33:30 neilg * Second phase of schema component model implementation. * Implement XSModel, XSNamespaceItem, and the plumbing necessary * to connect them to the other components. * Thanks to David Cargill. * * Revision 1.2 2003/11/06 15:30:04 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #if !defined(XSFACET_HPP) #define XSFACET_HPP #include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * This represents all Schema Facet components with the exception * of Enumeration and Pattern Facets, which are represented by the * XSMultiValueFacet interface. * This is *always* owned by the validator /parser object from which * it is obtained. */ // forward declarations class XSAnnotation; class XMLPARSER_EXPORT XSFacet : public XSObject { public: // Constructors and Destructor // ----------------------------------------------------------------------- /** @name Constructors */ //@{ /** * The default constructor * * @param facetKind * @param lexicalValue * @param isFixed * @param annot * @param xsModel * @param manager The configurable memory manager */ XSFacet ( XSSimpleTypeDefinition::FACET facetKind , const XMLCh* const lexicalValue , bool isFixed , XSAnnotation* const annot , XSModel* const xsModel , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); //@}; /** @name Destructor */ //@{ ~XSFacet(); //@} //--------------------- /** @name XSFacet methods */ //@{ /** * @return An indication as to the facet's type; see <code>XSSimpleTypeDefinition::FACET</code> */ XSSimpleTypeDefinition::FACET getFacetKind() const; /** * @return Returns a value of a constraining facet. */ const XMLCh *getLexicalFacetValue() const; /** * Check whether a facet value is fixed. */ bool isFixed() const; /** * @return an annotation */ XSAnnotation *getAnnotation() const; //@} //---------------------------------- /** methods needed by implementation */ //@{ //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XSFacet(const XSFacet&); XSFacet & operator=(const XSFacet &); protected: // ----------------------------------------------------------------------- // data members // ----------------------------------------------------------------------- XSSimpleTypeDefinition::FACET fFacetKind; bool fIsFixed; const XMLCh* fLexicalValue; XSAnnotation* fAnnotation; }; inline XSSimpleTypeDefinition::FACET XSFacet::getFacetKind() const { return fFacetKind; } inline const XMLCh* XSFacet::getLexicalFacetValue() const { return fLexicalValue; } inline bool XSFacet::isFixed() const { return fIsFixed; } inline XSAnnotation* XSFacet::getAnnotation() const { return fAnnotation; } XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 174 ] ] ]
6396bbc97240008557cbb8d7f22d6251da65ee7c
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/graphics/viewport.h
3002b9b17e852ebdbcab48690ed5cd5139227063
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
612
h
/* * viewport.h * * Created on: 5.8.2011 * Author: akin */ #ifndef VIEWPORT_H_ #define VIEWPORT_H_ #include <glm/glm> namespace ice { class Viewport { protected: glm::mat4x4 projection; glm::mat4x4 model; public: Viewport(); virtual ~Viewport(); glm::mat4x4& getProjectionMatrix(); glm::mat4x4& getModelMatrix(); // Lenses: void setOrtho( float width , float height , float near , float far ); void setFrustum( float left , float right , float bottom , float top , float near , float far ); }; } /* namespace ice */ #endif /* VIEWPORT_H_ */
[ "akin@lich" ]
[ [ [ 1, 32 ] ] ]
82b3a477f56d2a2eb17590df144f78e91f960bda
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/madalien.h
1ebed6a169acaf93a01d3aa01d61bbc0e3b63f20
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,280
h
/*************************************************************************** Mad Alien (c) 1980 Data East Corporation Original driver by Norbert Kehrer (February 2004) ***************************************************************************/ #include "sound/discrete.h" #define MADALIEN_MAIN_CLOCK XTAL_10_595MHz class madalien_state : public driver_device { public: madalien_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } UINT8 *m_shift_hi; UINT8 *m_shift_lo; UINT8 *m_videoram; UINT8 *m_charram; UINT8 *m_video_flags; UINT8 *m_video_control; UINT8 *m_scroll; UINT8 *m_edge1_pos; UINT8 *m_edge2_pos; UINT8 *m_headlight_pos; tilemap_t *m_tilemap_fg; tilemap_t *m_tilemap_edge1[4]; tilemap_t *m_tilemap_edge2[4]; bitmap_t *m_headlight_bitmap; }; /*----------- defined in video/madalien.c -----------*/ MACHINE_CONFIG_EXTERN( madalien_video ); WRITE8_HANDLER( madalien_videoram_w ); WRITE8_HANDLER( madalien_charram_w ); /*----------- defined in audio/madalien.c -----------*/ DISCRETE_SOUND_EXTERN( madalien ); /* Discrete Sound Input Nodes */ #define MADALIEN_8910_PORTA NODE_01 #define MADALIEN_8910_PORTB NODE_02
[ "Mike@localhost" ]
[ [ [ 1, 52 ] ] ]
930963d23a34bcd57e7394626c14a1b055eb3630
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/include/Door.h
edc708f36a2fb92d0225e15111077fc187212750
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
2,650
h
/*============================================================================= Door.h Author: Matt King =============================================================================*/ #ifndef GAME_OBJECT_DOOR_H #define GAME_OBJECT_SENSOR_H #include "GameObjectOgreBox2D.h" #include "AppStateManager.hpp" #include "AnimationBlender.h" /// The Door object moves the game between AppStates. class Door : public GameObjectOgreBox2D { friend class DoorCreator; public: /// Creates the Box2D and Ogre representation for the door. Door(Ogre::String name, bool isEntrance, b2Vec2 position): GameObjectOgreBox2D(name, 0, 0) { stateName_ = "PhysicsState"; GameObject::Initialize(); gameObjectType_ = GOType_Door; if(isEntrance) { entity_ = GAMEFRAMEWORK->sceneManager->createEntity(objectName_ + "_Door" , "start.mesh"); } else { entity_ = GAMEFRAMEWORK->sceneManager->createEntity(objectName_ + "_Door" , "exit.mesh"); } Ogre::AxisAlignedBox box = entity_->getBoundingBox(); Ogre::Vector3 size = box.getSize(); b2BodyDef bdef; bdef.position.Set(position.x, position.y + size.y / 2.0); b2PolygonShape boxShape; boxShape.SetAsBox(size.z / 2.0, size.y / 2.0); b2FixtureDef fd; fd.shape = &boxShape; fd.isSensor = true; body_ = world_->CreateBody(&bdef); body_->SetUserData(this); body_->CreateFixture(&fd); sceneNode_ = sceneManager_->getRootSceneNode()->createChildSceneNode(); sceneNode_->attachObject(entity_); sceneNode_->yaw(Ogre::Degree(-90)); sceneNode_->setPosition(position.x, position.y,-1); animationBlender_ = new AnimationBlender(entity_); animationBlender_->Initialize("open", false); isEntrance_ = isEntrance; isOpening_ = false; } virtual ~Door(){} /// Updates the animation blender for the Door. bool Update(double timeSinceLastFrame) { if(isOpening_ && animationBlender_->complete_ == false) { animationBlender_->AddTime(timeSinceLastFrame); } else if(isOpening_ && animationBlender_->complete_) { if(isEntrance_) { GAMEFRAMEWORK->appStateManager->pushAppState(stateName_); } else { GAMEFRAMEWORK->appStateManager->popStateAfterNextUpdate(); } isOpening_ = false; animationBlender_->Initialize("open", false); } return true; } /// Sets the AnimationBlender to open. void OpenDoor() { animationBlender_->Blend("open", AnimationBlender::BlendSwitch, 0, false); isOpening_ = true; } private: bool isOpening_; bool isEntrance_; Ogre::String stateName_; }; #endif
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 115 ] ] ]
d62fc99b2507bdf7613182dcc291373843fd2e18
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/battlera.h
72ce516d6d5f57cd3e4d3d0e62056af09c6fb31d
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
h
class battlera_state : public driver_device { public: battlera_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } int m_control_port_select; int m_msm5205next; int m_toggle; int m_HuC6270_registers[20]; int m_VDC_register; int m_vram_ptr; UINT8 *m_HuC6270_vram; UINT8 *m_vram_dirty; bitmap_t *m_tile_bitmap; bitmap_t *m_front_bitmap; UINT32 m_tile_dirtyseq; int m_current_scanline; int m_inc_value; int m_irq_enable; int m_rcr_enable; int m_sb_enable; int m_bb_enable; int m_bldwolf_vblank; UINT8 m_blank_tile[32]; }; /*----------- defined in video/battlera.c -----------*/ SCREEN_UPDATE( battlera ); VIDEO_START( battlera ); INTERRUPT_GEN( battlera_interrupt ); READ8_HANDLER( HuC6270_register_r ); WRITE8_HANDLER( HuC6270_register_w ); //READ8_HANDLER( HuC6270_data_r ); WRITE8_HANDLER( HuC6270_data_w ); WRITE8_HANDLER( battlera_palette_w ); READ8_HANDLER( HuC6270_debug_r ); WRITE8_HANDLER( HuC6270_debug_w );
[ "Mike@localhost" ]
[ [ [ 1, 42 ] ] ]
9e7f14c316e5dc64a1a9a1f774ab750cdb312c30
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/math/tools/impl/spline_impl.hh
42b90e02ea80e0b8500a725265ddcb795dd198fb
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,205
hh
QM_NAMESPACE2(math) inline unsigned cubic_spline::coef(qm_real x, qm_real& u, qm_real& h, qm_real& a, qm_real& b, qm_real& c, qm_real& d) const { if(!m_ready) this->noConst().evaluate(false); unsigned i = this->search(x); if(i == 0) i = 1; else if(i >= this->size()) i = this->size() - 1; h = xval(i) - xval(i-1); qm_real y = yval(i) - yval(i-1); qm_real xm = x - xval(i-1); qm_real h2 = h*h; u = xm/h; a = yval(i-1); b = y - h2*(2*kval(i-1) + kval(i))/6.; c = 0.5*h2*kval(i-1); d = h2*(kval(i) - kval(i-1))/6; if(x <= this->front()) { if(m_lower_extrapolation == 1) c = 0; d = 0; } else if(x >= this->back()) { if(m_upper_extrapolation == 1) { a += b + c + d; b += 2.*c + 3.*d; u = (x - xval(i))/h; c = 0; } d = 0; } return i; } inline qm_real cubic_spline::value(qm_real x) const { qm_real u,h,a,b,c,d; this->coef(x,u,h,a,b,c,d); return a + u*(b + u*(c + d*u)); } inline qm_real cubic_spline::der1(qm_real x) const { qm_real u,h,a,b,c,d; this->coef(x,u,h,a,b,c,d); return (b + u*(2*c + 3*d*u))/h; } inline qm_real cubic_spline::der2(qm_real x) const { qm_real u,h,a,b,c,d; this->coef(x,u,h,a,b,c,d); return (2*c + 6*d*u)/(h*h); } inline const cubic_spline::qmat_type& cubic_spline::sensitivity() const { if(!m_ready || !m_sens_ready) this->noConst().evaluate(true); return m_sens; } inline void cubic_spline::evaluate_two_points() { if(m_lowerBound == definedFirstDerivative && m_upperBound == definedFirstDerivative) { set_kval(0,m_lowerDer); set_kval(1,m_upperDer); } else { qm_real h = xval(1) - xval(0); qm_real y = yval(1) - yval(0); if(m_lowerBound == definedFirstDerivative) { set_kval(0,m_lowerDer); set_kval(1,0.5*(3*y/h - m_lowerDer)); } else if(m_upperBound == definedFirstDerivative) { set_kval(0,0.5*(3*y/h - m_upperDer)); set_kval(1,m_upperDer); } else { set_kval(0,y/h); set_kval(1,y/h); } } } inline void cubic_spline::evaluate(bool evasens) { typedef qmatrix<qm_real,tridiagonal> triadiag_mat; unsigned np = this->size(); QM_REQUIRE(np>=2,"There must be at least 2 support points in cubic spline"); qm_real h2,h1,h2i,h1i,y2,y1,kv,mk; if(np == 2) { set_kval(0,0); set_kval(1,0); if(evasens) { m_sens.resize(2,2); m_sens.fill(0); } return; } else if(np == 3) { h1 = xval(1) - xval(0); h2 = xval(2) - xval(1); h1i = 1.0/h1; h2i = 1.0/h2; y1 = (yval(1) - yval(0))*h1i; y2 = (yval(2) - yval(1))*h2i; mk = 3./(h1+h2); kv = mk*(y2 - y1); set_kval(0,0); set_kval(1,kv); set_kval(2,0); if(evasens) { m_sens.resize(3,3); m_sens.fill(0); m_sens(1,0) = mk*h1i; m_sens(1,1) =-mk*(h2i+h1i); m_sens(1,2) = mk*h2i; } return; } // unsigned ist = 0; unsigned ien = np-1; if(m_lowerBound != definedFirstDerivative) ist++; if(m_upperBound != definedFirstDerivative) ien--; unsigned N = ien - ist + 1; triadiag_mat A(N),B(np); qmatrix<qm_real> bi(N),xv(N); unsigned i0,i1,i,j,k; // Internal domain for(i=1;i<np-1;i++) { j = i - ist; h1 = xval(i) - xval(i-1); h2 = xval(i+1) - xval(i); h1i = 1.0/h1; h2i = 1.0/h2; y1 = (yval(i) - yval(i-1))*h1i; y2 = (yval(i+1) - yval(i))*h2i; A(j,j) = 2*(h1 + h2); bi(j) = 6*(y2 - y1); B(i,i) =-6*(h1i+h2i); B(i,i-1) = 6*h1i; B(i,i+1) = 6*h2i; if(j>0) A(j,j-1) = h1; if(j<N-1) A(j,j+1) = h2; } /// Lower boundary if(m_lowerBound == definedFirstDerivative) { h1 = xval(1) - xval(0); y1 = (yval(1) - yval(0))/h1; A(0,0) = 2*h1; A(0,1) = h1; B(0,0) =-6.0/h1; B(0,1) =-B(0,0); bi(0) = 6*(y1 - m_lowerDer); } /// Upper boundary if(m_upperBound == definedFirstDerivative) { h1 = xval(np-1) - xval(np-2); y1 = (yval(np-1) - yval(np-2))/h1; A(N-1,N-1) = 2*h1; A(N-1,N-2) = h1; B(np-1,np-1) = 6.0/h1; B(np-1,np-2) =-B(np-1,np-1); bi(N-1) = 6*(y1 - m_upperDer); } if(!m_ready) { linalg<qm_real>::solve(A,bi,xv).check(); for(j=0;j<N;j++) { i = j + ist; set_kval(i,xv(j)); } } if(evasens) { m_sens.resize(np,np); m_sens.fill(0); // Evaluate sensitivities of second derivatives at knots point with resepct knot values // The ith row of this matrix contains // dK_i/d_y_0 dK_i/d_y_1 ..... dK_i/d_y_n // Loop around the all the support points for(unsigned i=0;i<np;i++) { i0 = i; i1 = i; if(i>0) i0--; if(i<np-1) i1++; for(unsigned j=0;j<N;j++) { k = j + ist; if(k>=i0 && k<=i1) bi(j) = B(k,i); else bi(j) = 0; } linalg<qm_real>::solve(A,bi,xv); for(unsigned j=0;j<N;j++) { m_sens(j+ist,i) = xv(j); } } m_sens_ready = true; } m_ready = true; } // Evaluate the sensitivity of the spline value at x with respect the values of knots y_i, i=0,..,n inline qm_real cubic_spline::dvdy(qm_real x, qmatrix<qm_real>& der) const { this->sensitivity(); qm_real u,h,a,b,c,d; unsigned j = this->coef(x,u,h,a,b,c,d); qm_real mm = h*h*u/6; qm_real m0 =-mm*(2 + u*(u - 3)); qm_real m1 =-mm*(1 - u*u); der(j-1) += 1 - u; der(j) += u; for(unsigned i=0;i<this->size();i++) der(i) += m0*m_sens(j-1,i) + m1*m_sens(j,i); return a + u*(b + u*(c + d*u)); } inline qm_real spline1d::value(qm_real x) const { if(!m_ready) this->noConst().evaluate(); qm_real a,b,c,d; int n = this->size() - 1; if(x >= this->back()) { a = xval(n) - xval(n-1); b = (yval(n) - yval(n-1))/a; return yval(n) + (b + a*kval(n-1)/6.0 + a*kval(n)/3.0)*(x - xval(n)); } else if(x <= this->front()) { a = xval(1) - xval(0); b = (yval(1) - yval(0))/a; return yval(0) + (b - a*kval(0)/3.0 - a*kval(1)/6.0)*(x - xval(0)); } int i = this->getCoef(x,a,b,c,d); return a*yval(i-1)+b*yval(i)+c*kval(i-1)+d*kval(i); } inline qm_real spline1d::der1(qm_real x) const { if(!m_ready) this->noConst().evaluate(); qm_real a,b,c,d; int n = this->size() - 1; if(x >= this->back()) { a = xval(n) - xval(n-1); b = (yval(n) - yval(n-1))/a; return b + a*kval(n-1)/6.0 + a*kval(n)/3.0; } else if(x <= this->front()) { a = xval(1) - xval(0); b = (yval(1) - yval(0))/a; return b - a*kval(0)/3.0 - a*kval(1)/6.0; } int i = this->search(x); qm_real h = xval(i) - xval(i-1); qm_real u = (x - xval(i-1))/h; qm_real k0 = kval(i-1); qm_real k1 = kval(i); b = (yval(i) - yval(i-1))/h - h*(2*k0 + k1)/6; c = 0.5*h*k0; d = h*(k1 - k0)/6; return b + u*(2*c + 3*d*u); } inline qm_int spline1d::getCoef(qm_real x, qm_real& a, qm_real& b, qm_real& c, qm_real& d) const { qm_int j = this->search(x); this->coef(j,x,a,b,c,d); return j; } inline void spline1d::coef(qm_int i, qm_real x, qm_real& A, qm_real& B, qm_real& C, qm_real& D) const { qm_real h = xval(i) - xval(i-1); qm_real h0 = x - xval(i-1); qm_real b = h0/h; qm_real hs = h*h/6; A = 1 - b; B = b; C = A * (A * A - 1) * hs; D = B * (B * B - 1) * hs; } inline unsigned spline1d::dimension(unsigned& ist, unsigned& np) const { np = this->size(); ist = 0; if(!np) return 0; // unsigned ien = np-1; if(m_lowerBound == zeroSecondDerivative || m_lowerBound == zeroThirdDerivative) ist++; if(m_upperBound == zeroSecondDerivative || m_upperBound == zeroThirdDerivative) ien--; // int n = ien - ist + 1; if(n <= 0) return 0; else return n; } inline spline1d::qmat_type spline1d::lhs() const { unsigned ist,np; unsigned N = this->dimension(ist,np); qmat_type A(N); qmatrix<qm_real> bi(N); evaluate_matrices(A,bi,ist,np); return A; } inline void spline1d::evaluate(bool evalder) { unsigned ist,np; unsigned Nt = this->size(); QM_REQUIRE(Nt>=2,"Spline must have at least two support points"); if(Nt == 2) { set_kval(0,0); set_kval(1,0); } else { unsigned N = this->dimension(ist,np); qmat_type A(N); qmatrix<qm_real> bi(N),xv(N); evaluate_matrices(A,bi,ist,np); linalg<qm_real>::solve(A,bi,xv).check(); for(unsigned j=0;j<N;j++) { unsigned i = j + ist; set_kval(i,xv(j)); } if(m_lowerBound == zeroThirdDerivative) set_kval(0,kval(1)); if(m_upperBound == zeroThirdDerivative) set_kval(np-1,kval(np-2)); } m_ready = true; } inline void spline1d::evaluate_matrices(spline1d::qmat_type& A, qmatrix<qm_real>& bi, unsigned ist, unsigned np) const { qm_real h0,h1,y0,y1; // unsigned N = A.rows(); for(unsigned j=0;j<N;j++) { unsigned i = j + ist; // h0 = 0; y0 = 0; h1 = 0; y1 = 0; // if(i > 0) { h0 = xval(i) - xval(i-1); y0 =(yval(i) - yval(i-1))/h0; } if(i < np - 1) { h1 = xval(i+1) - xval(i); y1 =(yval(i+1) - yval(i))/h1; } // A(j,j) = 2.0*(h0 + h1); if(j>0) A(j,j-1) = h0; if(j < N-1) A(j,j+1) = h1; bi(j) = 6.0*(y1 - y0); // // DefinedFirstDerivative corrections if(i == 0 && m_lowerBound == definedFirstDerivative) bi(j) -= 6.0 * m_lowerDer; if(i == np-1 && m_upperBound == definedFirstDerivative) bi(j) += 6.0 * m_upperDer; // // ZeroThirdDerivative corrections if(j==0 && m_lowerBound == zeroThirdDerivative) A(j,j) += h0; if(j==N-1 && m_upperBound == zeroThirdDerivative) A(j,j) += h1; } // /* double a,b,c,d; for(int i=1;i<np;i++) { IntegraCoef(i, m_xval(i), out a, out b, out c, out d); m_kval(i, 1) = m_kval(i-1,1) + a * m_yval(i-1) + b * m_yval(i) + c * m_kval(i-1, 0) + d * m_kval(i, 0); } // if(evalDer) { m_kder = new RealMatrix(np,np); // for(int i = 0; i < np; i++) { int j = i - ist; Bi.SetValue(0); double h0 = 0; double h1 = 0; if(i > 0) { h0 = 6.0 / (m_xval(i) - m_xval(i - 1)); if(j > 0) Bi(j-1) = h0; } if(i<np-1) { h1 = 6.0/(m_xval(i+1) - m_xval(i)); if(j<n-1) Bi(j+1) = h1; } if(j>=0 && j<n) Bi(j) = - h0 - h1; // xv = Tri.Thomas(Bi); for(int k=0;k<n;k++) m_kder(k+ist,i) = xv(k); } } */ // } /* inline void lspline1d::evaluate(bool evalder) { unsigned np = this->size(); std::vector<unsigned> vec; vec.push_back(0); for(unsigned i=1;i<np-1;i++) { y0 = yval(i) - yval(i-1); y1 = yval(i+1) - yval(i); if(y0*y1 <= 0) vec.push_back(i); } vec.push_back(np-1); unsigned ist,np; unsigned N = this->dimension(ist,np); qmat_type A(N); qmatrix<qm_real> bi(N),xv(N); evaluate_matrices(A,bi,ist,np); linalg<qm_real>::solve(A,bi,xv).check(); for(unsigned j=0;j<N;j++) { unsigned i = j + ist; set_kval(i,xv(j)); } if(m_lowerBound == zeroThirdDerivative) set_kval(0,kval(1)); if(m_upperBound == zeroThirdDerivative) set_kval(np-1,kval(np-2)); m_ready = true; } */ QM_NAMESPACE_END2
[ [ [ 1, 457 ] ] ]
b6ad8dbdef65d67b489e2d257a1ac82d5e0d7246
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/SmartWires/SystemUtils/DataXMLSaver.h
176f0ebe724eb5b01a583f85709ba2a8ad881551
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
7,676
h
// DataXMLSaver.h: interface for the CDataXMLSaver class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_DATAXMLSAVER_H__969B3E6A_56E6_471A_83C3_153683EDB494__INCLUDED_) #define AFX_DATAXMLSAVER_H__969B3E6A_56E6_471A_83C3_153683EDB494__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <comdef.h> #ifndef _NO_XMLHOTKEYSUPPORT #include "hotkeys.h" #endif enum{ XMLNoConversion =0x0001, XMLRNConversion =0x0002, XMLTrimSpaces =0x0004, XMLAsAttribute =0x0008, XMLWithStartCR =0x0010, XMLWithEndCR =0x0020, XMLNoLTGTConv =0x0040, XMLJScriptConv =0x0080, QT_FORWARD2 =0x0100, }; void SubstEnvVariables(CString& sText); CString GetPathFolder(const char* szFile); BOOL isFileExist(const char* szFile); BOOL isFileIExist(const char* szFile); BOOL isFolder(const char* szFile); BOOL PreparePathForWrite(const char* szPath); DWORD GetFileSize(const char* szFileName); BOOL ReadFile(const char* sStartDir, CString& sFileContent, BOOL bAloowWPTextExtensions=0); BOOL ReadFile(const char* szFileName, wchar_t*& wszFileContent);// Вызывающая сторона должна очистить строку!!! BOOL SaveFile(const char* sStartDir, const char* sFileContent); BOOL AppendFile(const char* sStartDir, const char* sFileContent); BOOL ReadFileCashed(const char* szFileName, CString& sFileContent); BOOL ClearReadFileCash(); BOOL IsFileUnicode(const char* szFileName); BOOL ReadFileToBuffer(const char* sStartDir, LPVOID hGlobalBuffer, DWORD dwFileSize); CString PackToString(const char* szData, DWORD dwDataSize); BOOL PackFromString(const char* szData, DWORD dwDataSize, HGLOBAL& hGlobal, long lAllocParams=-1); CString UnescapeString(const char* szString); CString EscapeString(const char* szString,BOOL bUseExUnicod=1, CString sDelims="\\/:?&%=", int* iExtCounts2=0, int* iExtCounts4=0); CString EscapeString(const WCHAR* szString); CString EscapeString2(const char* szString,CString sAddChars="\\/:?&%='\""); CString EscapeStringSP(const char* szString); CString EscapeSlashes(const char* szString); CString EscapeStringUTF8(const WCHAR* szString); CString EscapeString3(const char* szString); char HexCode(const char* szRawValue); int ReverseFind(CString& sSource, const char* szWhat,int iFrom=0); int CountChars(CString& sSource, const char* szWhat,int iFrom,int iTo); void ArithReplace(CString& sWho, const char* szWhat, const char* szWith); class CDataXMLSaver { BOOL bFileLoaded; BOOL m_bRead; BOOL m_bDataSaved; BOOL m_bAppendMode; CString m_sRoot; CString m_sSource; FILE* m_pFile; CString m_sFileName; public: void Init(); CDataXMLSaver(const char* pString=""); CDataXMLSaver(const char* szFile, const char* szRoot, BOOL bRead, BOOL bAppendMode=FALSE); virtual ~CDataXMLSaver(); BOOL SetAsSaved(BOOL bRes); CString GetSourceFile(){return m_sFileName;}; CString GetSource(); void SetSource(const char* szSource=""); CString GetResult(); BOOL CryptBody(CString sTag="crypted"); BOOL UncryptBody(CString sTag="crypted"); void SetRoot(const char* szRootName); BOOL SaveDataIntoSource(const char* szFile=NULL); BOOL LoadDataToSource(const char* szFile); BOOL IsFileLoaded(){return bFileLoaded;}; CString getValue(const char* szKey); BOOL getValue(const char* szKey,int& iParam, int iDefault=0); BOOL getValue(const char* szKey,DWORD& iParam, DWORD iDefault=0); BOOL getValue(const char* szKey,long& lParam, long lDefault=0); BOOL getValue(const char* szKey,double& dParam, double dDefault=0); BOOL getValue(const char* szKey,COleDateTime& dt, COleDateTime dtDefault=COleDateTime::GetCurrentTime()); BOOL getValue(const char* szKey,CString& sParam, const char* sDefault="", DWORD dwOptions=0); BOOL putValue(const char* szKey,int iParam); BOOL putValue(const char* szKey,DWORD iParam); BOOL putValue(const char* szKey,long lParam); BOOL putValue(const char* szKey,double dParam); BOOL putValue(const char* szKey,const char* sParam, DWORD dwOptions=0); BOOL putValue(const char* szKey,COleDateTime dt); static CString OleDate2Str(COleDateTime dt); static COleDateTime Str2OleDate(CString dt); static BOOL StripInstringPart(const char* szStart, const char* szEnd, CString& szString, int* iFrom=0, BOOL bIgnoreCase=0, int iStartOffset=0); static BOOL ReplaceInstringPart(const char* szStart, const char* szEnd, const char* szWith, CString& szString, int* iFrom=0); static CString GetInstringPart(const char* szStart, const char* szEnd, const char* szString, int& iFrom, DWORD dwOptions=0, const char* szStringOriginal=0); static void GetInstringPartArray(CStringArray& arr, const char* szStart, const char* szEnd, const char* szString, DWORD dwOptions=0, const char* szStringOriginal=0); static CString GetInstringPart(const char* szStart, const char* szEnd, const char* szString, DWORD dwOptions=0, int* iFrom=NULL); static CString GetInstringPart(const char* szStart, const char* szString, DWORD dwOptions=0, int* iFrom=NULL); static CString GetInstringPartGreedly(const char* szStart, const char* szEnd, const char* szString, DWORD dwOptions=0, int* iFrom=NULL); static CString GetInstringPartGreedly(const char* szStart, const char* szEnd, const char* szString, int& iFrom, DWORD dwOptions=0); static void Str2Xml(CString& sRes, DWORD dwFlags=0); static void Xml2Str(CString& sRes, DWORD dwFlags=0); #ifdef IPV6_HOTKEYS #define _INCLUDE_IPV6_HOTKEYS_IN_XMLSAVER BOOL putValue(const char* szKey,CIHotkey lParam); BOOL getValue(const char* szKey,CIHotkey& lParam, CIHotkey lDefault=0); #else #pragma message("--- H: XML Data saver: hotkey support disabled ---") #endif }; CString GetStringHash(const char* szName); class CCritSectionLock:public CSingleLock { BOOL bLocked; CSyncObject* m_pObject; public: BOOL Init(CSyncObject* pObject, BOOL bInitialLock = FALSE); CCritSectionLock(CSyncObject* pObject, BOOL bInitialLock = FALSE); CCritSectionLock(CSyncObject& pObject, BOOL bInitialLock = FALSE); ~CCritSectionLock(); }; class CBase64XXX { public: CBase64XXX(BOOL bUseWierd); virtual ~CBase64XXX(); // Override the base class mandatory functions virtual CString Decode( LPCTSTR szDecoding, int nSize = -1, char* szOutputDirect=NULL); virtual CString Encode( LPCTSTR szEncoding, int nSize = -1); static int b64get_encode_buffer_size(int l,int q) { int ret; ret = l*2;//(l/3)*4; if (l%3!=0) ret +=4; if (q!=0) { ret += (ret/(q*4)); // if (ret%(q/4)!=0) ret ++; // Add space for trailing \n } return ret; } protected: void write_bits( UINT nBits, int nNumBts, LPTSTR szOutput, int& lp ); UINT read_bits( int nNumBits, int* pBitsRead, int& lp ); int m_nInputSize; int m_nBitsRemaining; ULONG m_lBitStorage; LPCTSTR m_szInput; static int m_nMask[]; CString m_sBase64Alphabet; private: }; CString TrimChars(const char* szIn, const char* szCharsR=" ", const char* szCharsL=" "); BOOL BlockTag(const char* szTag); BOOL DeEntitize(CString& sBodyText); BOOL StripTags(CString& sBodyText); DWORD atolx(const char* szStr); CString getURLHost(CString sTagValue, BOOL bToLast=0); int b64encode(const char *from,char *to,int length,int quads); BOOL IsExecutableFile(const char* szCommand); void AddToTextCab(CString& sCabContent,CString sFileToAdd,CString sBase); BOOL ExtractFromTextCab(CString& sCabContent,CString sBase); BOOL SaveBuffer(const char* sStartDir, void* sFileContent, DWORD dwSize); #endif // !defined(AFX_DATAXMLSAVER_H__969B3E6A_56E6_471A_83C3_153683EDB494__INCLUDED_)
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 173 ] ] ]
ed8c9ab93e1069b2d1fd7e07b1487fc1d60df222
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/node/nflip_main.cc
3a043b0962698c1cfe9eced35ddbc6697ac9e86a
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,862
cc
#define N_IMPLEMENTS nFlipFlop //------------------------------------------------------------------- // nflip_main.cc // (C) 1998 Andre Weissflog //------------------------------------------------------------------- #include "gfx/nscenegraph2.h" #include "gfx/nchannelcontext.h" #include "node/nflipflop.h" nNebulaScriptClass(nFlipFlop, "nvisnode"); //------------------------------------------------------------------- // nFlipFlop() // 09-Dec-98 floh created //------------------------------------------------------------------- nFlipFlop::nFlipFlop() { this->keyarray_size = 8; this->num_keys = 0; this->keyarray = new nObjectKey[this->keyarray_size]; if (!this->keyarray) n_error("Out of mem!"); // beim Speichern muessen zuerst die Child-Objekte, DANN // unser eigener Status gespeichert werden this->SetFlags(N_FLAG_SAVEUPSIDEDOWN); } //------------------------------------------------------------------- // ~nFlipFlop() // 09-Dec-98 floh created // 24-Apr-99 floh + keine Loeschschutz mehr fuer Subobjekte //------------------------------------------------------------------- nFlipFlop::~nFlipFlop() { if (this->keyarray) delete[] this->keyarray; } //------------------------------------------------------------------- // getKey() // 09-Dec-98 floh created //------------------------------------------------------------------- nObjectKey *nFlipFlop::getKey(void) { if (this->num_keys < this->keyarray_size) { return &(this->keyarray[this->num_keys++]); } else { // Keyarray muss reallokiert werden ulong new_size = this->keyarray_size * 2; nObjectKey *new_array = new nObjectKey[new_size]; if (new_array) { memcpy(new_array,this->keyarray,this->keyarray_size*sizeof(nObjectKey)); delete[] this->keyarray; this->keyarray = new_array; this->keyarray_size = new_size; return &(this->keyarray[this->num_keys++]); } else { n_error("Out of mem!"); return NULL; } } } //------------------------------------------------------------------- // AddKey() // 09-Dec-98 floh created // 24-Apr-99 floh kein Loeschschutz mehr fuer // Sub-Objekte //------------------------------------------------------------------- bool nFlipFlop::AddKey(float time, const char *name) { n_assert(name); nVisNode *c; c = (nVisNode *) this->Find(name); if (c) { nObjectKey *k = this->getKey(); if (k) { k->Set(time,c); return true; } } else { n_printf("nFlipFlop::AddKey(): Child object %s not found!\n",name); } return false; } //------------------------------------------------------------------- // Attach() // Attach() wird nur an das per Timestamp gueltige // Objekt weitergegeben. // 20-Apr-99 floh created // 25-May-99 floh + nicht mehr auf GlobalTime hardgecodet // + TimeScale-Support // 30-Sep-99 floh + clampt im OneShot-Modus t auf den gueltigen // Wertebereich // 27-Jun-01 floh + new scene graph stuff // 24-Jul-01 floh + some corrections to prevent illegal array accesses //------------------------------------------------------------------- bool nFlipFlop::Attach(nSceneGraph2 *sceneGraph) { n_assert(sceneGraph); // selectively route Attach() to subobjects if (this->num_keys > 1) { // WE DO NOT CALL nVisNode::Attach() BECAUSE WE NEED TO // SELECTIVELY ROUTE Attach() TO OUR CHILDREN, THAT'S WHY // SOME OF THE nVisNode::Attach() FUNCTIONALITY NEEDS // TO BE "EMULATED" float tscale = this->scale; float min_t = this->keyarray[0].t * tscale; float max_t = this->keyarray[this->num_keys-1].t * tscale; if (max_t > 0.0) { nChannelContext* chnContext = sceneGraph->GetChannelContext(); n_assert(chnContext); float t = this->ComputeTime(chnContext->GetChannel1f(this->localChannelIndex), min_t, max_t); int i = 0; if (n_neqz(this->keyarray[0].t)) { n_error("Object '%s' 1st keyframe > 0.0f!\n",this->GetFullName().c_str()); } while ((this->keyarray[i].t * tscale) <= t) i++; n_assert((i > 0) && (i < this->num_keys)); nObjectKey *k = &(this->keyarray[i-1]); k->o->Attach(sceneGraph); } } return true; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 133 ] ] ]
c23edb624d5bf49b3b5b87b56f6325b7e3b3d95b
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelController/src/Hardware.cpp
c9c543b4e57006d0e0bd326f1888b1becde7ee9a
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,212
cpp
#include "WheelControllerStableHeaders.h" #include "Hardware.h" #include "MsgHandler.h" using namespace Orz; #include <orz/View_SingleChip/SingleChipManager.h> MsgHandler handler; void Hardware::received(bool isReceived) { ORZ_LOG_TRACE_MESSAGE("call Hardware::received(bool isReceived)"); Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x12); Orz::MsgBuffer msg; if(isReceived) msg.push_back(0x01); else msg.push_back(0x00); Orz::MsgBuffer out = handler.encode(head, msg); //Orz::SingleChipManager::getSingleton().write(out); } void Hardware::answerTime(int second) { ORZ_LOG_TRACE_MESSAGE("call Hardware::answerTime(int second)"); Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x11); Orz::MsgBuffer msg; msg.push_back(static_cast<unsigned char>(second)); Orz::MsgBuffer out = handler.encode(head, msg); // Orz::SingleChipManager::getSingleton().write(out); } void Hardware::actionTwo(void) { Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x18); Orz::MsgBuffer msg; Orz::MsgBuffer out = handler.encode(head, msg); //Orz::SingleChipManager::getSingleton().write(out); std::cout<<"F5"<<std::endl; } void Hardware::actionThree(void) { Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x14); Orz::MsgBuffer msg; Orz::MsgBuffer out = handler.encode(head, msg); // Orz::SingleChipManager::getSingleton().write(out); std::cout<<"F6"<<std::endl; } void Hardware::actionOne(void) { Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x18); Orz::MsgBuffer msg; Orz::MsgBuffer out = handler.encode(head, msg); // Orz::SingleChipManager::getSingleton().write(out); std::cout<<"F4"<<std::endl; } void Hardware::answerState(unsigned char state) { Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x13); Orz::MsgBuffer msg; msg.push_back(state); Orz::MsgBuffer out = handler.encode(head, msg); // Orz::SingleChipManager::getSingleton().write(out); } void Hardware::setup(int p0, int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { ORZ_LOG_NORMAL_MESSAGE(boost::format("Hardware::setup(%1%,%2%,%3%,%4%,%5%,%6%,%7%,%8%,%9%)") %p0 %p1 %p2 %p3 %p4 %p5 %p6 %p7 %p8); Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x18); Orz::MsgBuffer msg; Orz::MsgBuffer out = handler.encode(head, msg); out.push_back(p0); out.push_back(p1); out.push_back(p2); out.push_back(p3); out.push_back(p4); out.push_back(p5); out.push_back(p6); out.push_back(p7); out.push_back(p8); // Orz::SingleChipManager::getSingleton().write(out); } void Hardware::pushPassword(int password) { Orz::MsgBuffer head; head.push_back(0); head.push_back(0); head.push_back(0x15); Orz::MsgBuffer msg; for(int i =0; i<9; ++i) { int n = password%10; password /=10; msg.push_back(n); } Orz::MsgBuffer out = handler.encode(head, msg); // Orz::SingleChipManager::getSingleton().write(out); }
[ [ [ 1, 151 ] ] ]
4136f58a585624563a92fb2f599f5f3af6f5e8fc
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/series.hpp
4bd688b5cfcb4f6a0a9ccbb734f52068df35953a
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
33,065
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'Series.pas' rev: 6.00 #ifndef SeriesHPP #define SeriesHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <TeeProcs.hpp> // Pascal unit #include <TeCanvas.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Chart.hpp> // Pascal unit #include <TeEngine.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Series { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TSeriesPointerStyle { psRectangle, psCircle, psTriangle, psDownTriangle, psCross, psDiagCross, psStar, psDiamond, psSmallDot }; #pragma option pop typedef TSeriesPointerStyle __fastcall (__closure *TOnGetPointerStyle)(Teengine::TChartSeries* Sender, int ValueIndex); class DELPHICLASS TSeriesPointer; class PASCALIMPLEMENTATION TSeriesPointer : public Classes::TPersistent { typedef Classes::TPersistent inherited; private: bool FDark3D; bool FDraw3D; Chart::TChartBrush* FBrush; int FHorizSize; bool FInflateMargins; Teengine::TChartSeries* FOwner; Tecanvas::TChartPen* FPen; TSeriesPointerStyle FStyle; int FVertSize; bool FVisible; void __fastcall CheckPointerSize(int Value); void __fastcall SetDark3D(bool Value); void __fastcall SetDraw3D(bool Value); void __fastcall SetBrush(Chart::TChartBrush* Value); void __fastcall SetHorizSize(int Value); void __fastcall SetInflateMargins(bool Value); void __fastcall SetPen(Tecanvas::TChartPen* Value); void __fastcall SetStyle(TSeriesPointerStyle Value); void __fastcall SetVertSize(int Value); void __fastcall SetVisible(bool Value); protected: void __fastcall SetBooleanProperty(bool &Variable, bool Value); void __fastcall SetIntegerProperty(int &Variable, int Value); public: bool AllowChangeSize; __fastcall TSeriesPointer(Teengine::TChartSeries* AOwner); __fastcall virtual ~TSeriesPointer(void); virtual void __fastcall Assign(Classes::TPersistent* Source); void __fastcall CalcHorizMargins(int &LeftMargin, int &RightMargin); void __fastcall CalcVerticalMargins(int &TopMargin, int &BottomMargin); void __fastcall Change3D(bool Value); void __fastcall ChangeHorizSize(int NewSize); void __fastcall ChangeStyle(TSeriesPointerStyle NewStyle); void __fastcall ChangeVertSize(int NewSize); void __fastcall Draw(int px, int py, Graphics::TColor ColorValue, TSeriesPointerStyle AStyle); void __fastcall DrawLegendShape(Graphics::TColor AColor, const Types::TRect &Rect, bool DrawPen); void __fastcall DrawPointer(bool Is3D, int px, int py, int tmpHoriz, int tmpVert, Graphics::TColor ColorValue, TSeriesPointerStyle AStyle); void __fastcall PrepareCanvas(Graphics::TColor ColorValue); __property Teengine::TChartSeries* ParentSeries = {read=FOwner}; __published: __property Chart::TChartBrush* Brush = {read=FBrush, write=SetBrush}; __property bool Dark3D = {read=FDark3D, write=SetDark3D, default=1}; __property bool Draw3D = {read=FDraw3D, write=SetDraw3D, default=1}; __property int HorizSize = {read=FHorizSize, write=SetHorizSize, default=4}; __property bool InflateMargins = {read=FInflateMargins, write=SetInflateMargins, nodefault}; __property Tecanvas::TChartPen* Pen = {read=FPen, write=SetPen}; __property TSeriesPointerStyle Style = {read=FStyle, write=SetStyle, nodefault}; __property int VertSize = {read=FVertSize, write=SetVertSize, default=4}; __property bool Visible = {read=FVisible, write=SetVisible, nodefault}; }; class DELPHICLASS TCustomSeries; typedef void __fastcall (__closure *TSeriesClickPointerEvent)(TCustomSeries* Sender, int ValueIndex, int X, int Y); class PASCALIMPLEMENTATION TCustomSeries : public Teengine::TChartSeries { typedef Teengine::TChartSeries inherited; private: Graphics::TBrushStyle FAreaBrush; Graphics::TColor FAreaColor; Tecanvas::TChartPen* FAreaLinesPen; bool FClickableLine; bool FDark3D; bool FDrawArea; bool FDrawLine; bool FInvertedStairs; Graphics::TBrushStyle FLineBrush; int FLineHeight; Tecanvas::TChartPen* FLinePen; TSeriesPointer* FPointer; bool FStairs; TSeriesClickPointerEvent FOnClickPointer; TOnGetPointerStyle FOnGetPointerStyle; int BottomPos; int OldBottomPos; int OldX; int OldY; Graphics::TColor OldColor; double tmpDark3DRatio; void __fastcall SetAreaBrush(Graphics::TBrushStyle Value); void __fastcall SetAreaColor(Graphics::TColor Value); void __fastcall SetAreaLinesPen(Tecanvas::TChartPen* Value); void __fastcall SetBrushProperty(Graphics::TBrushStyle &ABrush, Graphics::TBrushStyle Value); void __fastcall SetDark3D(bool Value); void __fastcall SetDrawArea(bool Value); void __fastcall SetInvertedStairs(bool Value); void __fastcall SetLineBrush(Graphics::TBrushStyle Value); void __fastcall SetLineHeight(int Value); void __fastcall SetLinePen(Tecanvas::TChartPen* Value); void __fastcall SetPointer(TSeriesPointer* Value); void __fastcall SetStairs(bool Value); protected: virtual bool __fastcall ClickedPointer(int ValueIndex, int tmpX, int tmpY, int x, int y); virtual void __fastcall DrawMark(int ValueIndex, const AnsiString St, Teengine::TSeriesMarkPosition* APosition); virtual void __fastcall DrawPointer(int AX, int AY, Graphics::TColor AColor, int ValueIndex); virtual void __fastcall DrawValue(int ValueIndex); Graphics::TColor __fastcall GetAreaBrushColor(Graphics::TColor AColor); void __fastcall LinePrepareCanvas(Tecanvas::TCanvas3D* tmpCanvas, Graphics::TColor tmpColor); public: __fastcall virtual TCustomSeries(Classes::TComponent* AOwner); __fastcall virtual ~TCustomSeries(void); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual void __fastcall CalcHorizMargins(int &LeftMargin, int &RightMargin); virtual void __fastcall CalcVerticalMargins(int &TopMargin, int &BottomMargin); virtual int __fastcall Clicked(int x, int y); virtual void __fastcall DrawLegendShape(int ValueIndex, const Types::TRect &Rect); virtual AnsiString __fastcall GetEditorClass(); virtual int __fastcall GetOriginPos(int ValueIndex); __property Graphics::TBrushStyle AreaBrush = {read=FAreaBrush, write=SetAreaBrush, default=0}; __property Graphics::TColor AreaColor = {read=FAreaColor, write=SetAreaColor, default=536870912}; __property Tecanvas::TChartPen* AreaLinesPen = {read=FAreaLinesPen, write=SetAreaLinesPen}; __property bool ClickableLine = {read=FClickableLine, write=FClickableLine, nodefault}; __property bool Dark3D = {read=FDark3D, write=SetDark3D, default=1}; __property bool DrawArea = {read=FDrawArea, write=SetDrawArea, default=0}; __property bool InvertedStairs = {read=FInvertedStairs, write=SetInvertedStairs, default=0}; __property Graphics::TBrushStyle LineBrush = {read=FLineBrush, write=SetLineBrush, default=0}; __property int LineHeight = {read=FLineHeight, write=SetLineHeight, default=0}; __property Tecanvas::TChartPen* LinePen = {read=FLinePen, write=SetLinePen}; __property TSeriesClickPointerEvent OnClickPointer = {read=FOnClickPointer, write=FOnClickPointer}; __property TSeriesPointer* Pointer = {read=FPointer, write=SetPointer}; __property bool Stairs = {read=FStairs, write=SetStairs, default=0}; __published: __property TOnGetPointerStyle OnGetPointerStyle = {read=FOnGetPointerStyle, write=FOnGetPointerStyle}; }; class DELPHICLASS TLineSeries; class PASCALIMPLEMENTATION TLineSeries : public TCustomSeries { typedef TCustomSeries inherited; public: __fastcall virtual TLineSeries(Classes::TComponent* AOwner); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual void __fastcall PrepareLegendCanvas(int ValueIndex, Graphics::TColor &BackColor, Graphics::TBrushStyle &BrushStyle); __published: __property Dark3D = {default=1}; __property InvertedStairs = {default=0}; __property LineBrush = {default=0}; __property LineHeight = {default=0}; __property LinePen ; __property Pointer ; __property Stairs = {default=0}; __property XValues ; __property YValues ; public: #pragma option push -w-inl /* TCustomSeries.Destroy */ inline __fastcall virtual ~TLineSeries(void) { } #pragma option pop }; class DELPHICLASS TPointSeries; class PASCALIMPLEMENTATION TPointSeries : public TCustomSeries { typedef TCustomSeries inherited; protected: virtual void __fastcall SetColorEachPoint(bool Value); public: __fastcall virtual TPointSeries(Classes::TComponent* AOwner); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual AnsiString __fastcall GetEditorClass(); virtual void __fastcall PrepareForGallery(bool IsEnabled); __published: __property Pointer ; __property XValues ; __property YValues ; __property OnClickPointer ; public: #pragma option push -w-inl /* TCustomSeries.Destroy */ inline __fastcall virtual ~TPointSeries(void) { } #pragma option pop }; #pragma option push -b- enum TMultiArea { maNone, maStacked, maStacked100 }; #pragma option pop class DELPHICLASS TAreaSeries; class PASCALIMPLEMENTATION TAreaSeries : public TCustomSeries { typedef TCustomSeries inherited; private: TMultiArea FMultiArea; void __fastcall SetMultiArea(TMultiArea Value); int __fastcall InternalCalcStackedYPos(int ValueIndex, double Value); public: __fastcall virtual TAreaSeries(Classes::TComponent* AOwner); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual void __fastcall CalcZOrder(void); virtual int __fastcall CalcYPos(int ValueIndex); virtual AnsiString __fastcall GetEditorClass(); virtual int __fastcall GetOriginPos(int ValueIndex); virtual void __fastcall PrepareLegendCanvas(int ValueIndex, Graphics::TColor &BackColor, Graphics::TBrushStyle &BrushStyle); virtual double __fastcall MaxYValue(void); virtual double __fastcall MinYValue(void); __published: __property AreaBrush = {default=0}; __property AreaColor = {default=536870912}; __property AreaLinesPen ; __property Dark3D = {default=1}; __property DrawArea = {default=0}; __property InvertedStairs = {default=0}; __property LinePen ; __property TMultiArea MultiArea = {read=FMultiArea, write=SetMultiArea, default=0}; __property Pointer ; __property Stairs = {default=0}; __property XValues ; __property YValues ; public: #pragma option push -w-inl /* TCustomSeries.Destroy */ inline __fastcall virtual ~TAreaSeries(void) { } #pragma option pop }; class DELPHICLASS BarException; class PASCALIMPLEMENTATION BarException : public Sysutils::Exception { typedef Sysutils::Exception inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall BarException(const AnsiString Msg) : Sysutils::Exception(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall BarException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall BarException(int Ident)/* overload */ : Sysutils::Exception(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall BarException(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall BarException(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall BarException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall BarException(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall BarException(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~BarException(void) { } #pragma option pop }; #pragma option push -b- enum TMultiBar { mbNone, mbSide, mbStacked, mbStacked100 }; #pragma option pop #pragma option push -b- enum TBarStyle { bsRectangle, bsPyramid, bsInvPyramid, bsCilinder, bsEllipse, bsArrow, bsRectGradient }; #pragma option pop class DELPHICLASS TCustomBarSeries; typedef void __fastcall (__closure *TGetBarStyleEvent)(TCustomBarSeries* Sender, int ValueIndex, TBarStyle &TheBarStyle); class PASCALIMPLEMENTATION TCustomBarSeries : public Teengine::TChartSeries { typedef Teengine::TChartSeries inherited; private: bool FAutoBarSize; bool FAutoMarkPosition; Chart::TChartBrush* FBarBrush; Tecanvas::TChartPen* FBarPen; TBarStyle FBarStyle; int FBarWidthPercent; bool FDark3D; TMultiBar FMultiBar; int FOffsetPercent; bool FSideMargins; bool FUseOrigin; double FOrigin; TGetBarStyleEvent FOnGetBarStyle; #pragma pack(push, 1) Types::TRect FBarBounds; #pragma pack(pop) void __fastcall CalcBarWidth(void); virtual int __fastcall InternalCalcMarkLength(int ValueIndex) = 0 ; void __fastcall SetAutoBarSize(bool Value); void __fastcall SetAutoMarkPosition(bool Value); void __fastcall SetBarWidthPercent(int Value); void __fastcall SetOffsetPercent(int Value); void __fastcall SetBarStyle(TBarStyle Value); void __fastcall SetDark3d(bool Value); void __fastcall SetUseOrigin(bool Value); void __fastcall SetSideMargins(bool Value); void __fastcall SetBarPen(Tecanvas::TChartPen* Value); void __fastcall SetBarBrush(Chart::TChartBrush* Value); void __fastcall SetOrigin(const double Value); void __fastcall SetMultiBar(TMultiBar Value); void __fastcall SetOtherMultiBar(void); void __fastcall AdjustGradientRectPen(Types::TRect &R); int __fastcall BarOrderPos(void); int __fastcall BarSeriesCount(void); double __fastcall MaxMandatoryValue(const double Value, Teengine::TChartValueList* AList); double __fastcall MinMandatoryValue(const double Value); void __fastcall InternalApplyBarMargin(int &MarginA, int &MarginB); protected: int FCustomBarSize; int IBarSize; virtual bool __fastcall InternalClicked(int ValueIndex, const Types::TPoint &APoint); int __fastcall InternalGetOriginPos(int ValueIndex, int DefaultOrigin); void __fastcall SetCustomBarSize(int Value); public: Graphics::TColor NormalBarColor; __fastcall virtual TCustomBarSeries(Classes::TComponent* AOwner); __fastcall virtual ~TCustomBarSeries(void); int __fastcall AddBar(const double AValue, const AnsiString ALabel, Graphics::TColor AColor); int __fastcall ApplyBarOffset(int Position); virtual void __fastcall Assign(Classes::TPersistent* Source); int __fastcall BarMargin(void); void __fastcall BarRectangle(Graphics::TColor BarColor, int ALeft, int ATop, int ARight, int ABottom); int __fastcall CalcMarkLength(int ValueIndex); virtual void __fastcall CalcZOrder(void); virtual int __fastcall Clicked(int x, int y); virtual void __fastcall DrawLegendShape(int ValueIndex, const Types::TRect &Rect); TBarStyle __fastcall GetBarStyle(int ValueIndex); virtual AnsiString __fastcall GetEditorClass(); virtual int __fastcall NumSampleValues(void); virtual double __fastcall PointOrigin(int ValueIndex, bool SumAll); virtual void __fastcall PrepareForGallery(bool IsEnabled); virtual void __fastcall PrepareLegendCanvas(int ValueIndex, Graphics::TColor &BackColor, Graphics::TBrushStyle &BrushStyle); void __fastcall SetPenBrushBar(Graphics::TColor BarColor); __property Types::TRect BarBounds = {read=FBarBounds}; __published: __property bool AutoBarSize = {read=FAutoBarSize, write=SetAutoBarSize, default=0}; __property bool AutoMarkPosition = {read=FAutoMarkPosition, write=SetAutoMarkPosition, default=1}; __property Chart::TChartBrush* BarBrush = {read=FBarBrush, write=SetBarBrush}; __property Tecanvas::TChartPen* BarPen = {read=FBarPen, write=SetBarPen}; __property TBarStyle BarStyle = {read=FBarStyle, write=SetBarStyle, default=0}; __property int BarWidthPercent = {read=FBarWidthPercent, write=SetBarWidthPercent, default=70}; __property bool Dark3D = {read=FDark3D, write=SetDark3d, default=1}; __property TMultiBar MultiBar = {read=FMultiBar, write=SetMultiBar, default=1}; __property int OffsetPercent = {read=FOffsetPercent, write=SetOffsetPercent, default=0}; __property bool SideMargins = {read=FSideMargins, write=SetSideMargins, default=1}; __property bool UseYOrigin = {read=FUseOrigin, write=SetUseOrigin, default=1}; __property double YOrigin = {read=FOrigin, write=SetOrigin}; __property XValues ; __property YValues ; __property TGetBarStyleEvent OnGetBarStyle = {read=FOnGetBarStyle, write=FOnGetBarStyle}; }; class DELPHICLASS TBarSeries; class PASCALIMPLEMENTATION TBarSeries : public TCustomBarSeries { typedef TCustomBarSeries inherited; private: virtual int __fastcall InternalCalcMarkLength(int ValueIndex); protected: virtual void __fastcall DrawValue(int ValueIndex); virtual void __fastcall DrawMark(int ValueIndex, const AnsiString St, Teengine::TSeriesMarkPosition* APosition); public: virtual bool __fastcall InternalClicked(int ValueIndex, const Types::TPoint &APoint); virtual void __fastcall CalcHorizMargins(int &LeftMargin, int &RightMargin); virtual void __fastcall CalcVerticalMargins(int &TopMargin, int &BottomMargin); virtual int __fastcall CalcXPos(int ValueIndex); virtual int __fastcall CalcYPos(int ValueIndex); virtual void __fastcall DrawBar(int BarIndex, int StartPos, int EndPos); virtual bool __fastcall DrawSeriesForward(int ValueIndex); virtual bool __fastcall DrawValuesForward(void); int __fastcall GetOriginPos(int ValueIndex); virtual double __fastcall MaxYValue(void); virtual double __fastcall MinYValue(void); __property int BarWidth = {read=IBarSize, nodefault}; __published: __property int CustomBarWidth = {read=FCustomBarSize, write=SetCustomBarSize, default=0}; public: #pragma option push -w-inl /* TCustomBarSeries.Create */ inline __fastcall virtual TBarSeries(Classes::TComponent* AOwner) : TCustomBarSeries(AOwner) { } #pragma option pop #pragma option push -w-inl /* TCustomBarSeries.Destroy */ inline __fastcall virtual ~TBarSeries(void) { } #pragma option pop }; class DELPHICLASS THorizBarSeries; class PASCALIMPLEMENTATION THorizBarSeries : public TCustomBarSeries { typedef TCustomBarSeries inherited; private: virtual int __fastcall InternalCalcMarkLength(int ValueIndex); protected: virtual void __fastcall DrawValue(int ValueIndex); virtual void __fastcall DrawMark(int ValueIndex, const AnsiString St, Teengine::TSeriesMarkPosition* APosition); public: virtual bool __fastcall InternalClicked(int ValueIndex, const Types::TPoint &APoint); virtual void __fastcall CalcHorizMargins(int &LeftMargin, int &RightMargin); virtual void __fastcall CalcVerticalMargins(int &TopMargin, int &BottomMargin); virtual int __fastcall CalcXPos(int ValueIndex); virtual int __fastcall CalcYPos(int ValueIndex); virtual void __fastcall DrawBar(int BarIndex, int StartPos, int EndPos); virtual bool __fastcall DrawSeriesForward(int ValueIndex); virtual bool __fastcall DrawValuesForward(void); virtual void __fastcall FillSampleValues(int NumValues); int __fastcall GetOriginPos(int ValueIndex); virtual Teengine::TChartValueList* __fastcall MandatoryValueList(void); virtual double __fastcall MaxXValue(void); virtual double __fastcall MinXValue(void); __property int BarHeight = {read=IBarSize, nodefault}; __published: __property int CustomBarHeight = {read=FCustomBarSize, write=SetCustomBarSize, default=0}; public: #pragma option push -w-inl /* TCustomBarSeries.Create */ inline __fastcall virtual THorizBarSeries(Classes::TComponent* AOwner) : TCustomBarSeries(AOwner) { } #pragma option pop #pragma option push -w-inl /* TCustomBarSeries.Destroy */ inline __fastcall virtual ~THorizBarSeries(void) { } #pragma option pop }; class DELPHICLASS TCircledSeries; class PASCALIMPLEMENTATION TCircledSeries : public Teengine::TChartSeries { typedef Teengine::TChartSeries inherited; private: bool FCircled; int FRotationAngle; int FCustomXRadius; int FCustomYRadius; int FXRadius; int FYRadius; Graphics::TColor FCircleBackColor; double IRotDegree; int FCircleWidth; int FCircleHeight; int FCircleXCenter; int FCircleYCenter; #pragma pack(push, 1) Types::TRect FCircleRect; #pragma pack(pop) void __fastcall SetCircleBackColor(Graphics::TColor Value); void __fastcall SetCustomXRadius(int Value); void __fastcall SetCustomYRadius(int Value); void __fastcall SetCircled(bool Value); void __fastcall SetOtherCustomRadius(bool IsXRadius, int Value); protected: void __fastcall AdjustCircleRect(void); Graphics::TColor __fastcall CalcCircleBackColor(void); void __fastcall CalcRadius(void); virtual void __fastcall DoBeforeDrawValues(void); virtual void __fastcall SetActive(bool Value); virtual void __fastcall SetParentChart(Teengine::TCustomAxisPanel* Value); void __fastcall SetRotationAngle(int Value); public: __fastcall virtual TCircledSeries(Classes::TComponent* AOwner); __fastcall virtual ~TCircledSeries(void); void __fastcall AngleToPos(const double Angle, const double AXRadius, const double AYRadius, int &X, int &Y); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual bool __fastcall AssociatedToAxis(Teengine::TCustomChartAxis* Axis); double __fastcall PointToAngle(int x, int y); virtual void __fastcall PrepareLegendCanvas(int ValueIndex, Graphics::TColor &BackColor, Graphics::TBrushStyle &BrushStyle); void __fastcall Rotate(int Angle); virtual void __fastcall SetParentProperties(bool EnableParentProps); virtual bool __fastcall UseAxis(void); __property int XRadius = {read=FXRadius, nodefault}; __property int YRadius = {read=FYRadius, nodefault}; __property int CircleXCenter = {read=FCircleXCenter, nodefault}; __property int CircleYCenter = {read=FCircleYCenter, nodefault}; __property int CircleWidth = {read=FCircleWidth, nodefault}; __property int CircleHeight = {read=FCircleHeight, nodefault}; __property Types::TRect CircleRect = {read=FCircleRect}; __property Graphics::TColor CircleBackColor = {read=FCircleBackColor, write=SetCircleBackColor, default=536870912}; __property int RotationAngle = {read=FRotationAngle, write=SetRotationAngle, default=0}; __published: __property bool Circled = {read=FCircled, write=SetCircled, default=0}; __property int CustomXRadius = {read=FCustomXRadius, write=SetCustomXRadius, default=0}; __property int CustomYRadius = {read=FCustomYRadius, write=SetCustomYRadius, default=0}; }; class DELPHICLASS PieException; class PASCALIMPLEMENTATION PieException : public Teeprocs::ChartException { typedef Teeprocs::ChartException inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall PieException(const AnsiString Msg) : Teeprocs::ChartException(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall PieException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Teeprocs::ChartException(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall PieException(int Ident)/* overload */ : Teeprocs::ChartException(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall PieException(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Teeprocs::ChartException(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall PieException(const AnsiString Msg, int AHelpContext) : Teeprocs::ChartException(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall PieException(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Teeprocs::ChartException(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall PieException(int Ident, int AHelpContext)/* overload */ : Teeprocs::ChartException(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall PieException(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Teeprocs::ChartException(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~PieException(void) { } #pragma option pop }; #pragma pack(push, 1) struct TPieAngle { double StartAngle; double MidAngle; double EndAngle; } ; #pragma pack(pop) typedef DynamicArray<TPieAngle > TPieAngles; class DELPHICLASS TExplodedSlices; class PASCALIMPLEMENTATION TExplodedSlices : public Classes::TList { typedef Classes::TList inherited; public: int operator[](int Index) { return Value[Index]; } private: void __fastcall SetValue(int Index, int Value); int __fastcall GetValue(int Index); public: Teengine::TChartSeries* OwnerSeries; __property int Value[int Index] = {read=GetValue, write=SetValue/*, default*/}; public: #pragma option push -w-inl /* TList.Destroy */ inline __fastcall virtual ~TExplodedSlices(void) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TExplodedSlices(void) : Classes::TList() { } #pragma option pop }; #pragma option push -b- enum TPieOtherStyle { poNone, poBelowPercent, poBelowValue }; #pragma option pop class DELPHICLASS TPieOtherSlice; class PASCALIMPLEMENTATION TPieOtherSlice : public Classes::TPersistent { typedef Classes::TPersistent inherited; private: TPieOtherStyle FStyle; AnsiString FText; double FValue; Teengine::TChartSeries* FOwner; void __fastcall SetStyle(TPieOtherStyle Value); void __fastcall SetText(const AnsiString Value); void __fastcall SetValue(const double Value); public: __fastcall TPieOtherSlice(Teengine::TChartSeries* AOwner); virtual void __fastcall Assign(Classes::TPersistent* Source); __published: __property TPieOtherStyle Style = {read=FStyle, write=SetStyle, default=0}; __property AnsiString Text = {read=FText, write=SetText}; __property double Value = {read=FValue, write=SetValue}; public: #pragma option push -w-inl /* TPersistent.Destroy */ inline __fastcall virtual ~TPieOtherSlice(void) { } #pragma option pop }; class DELPHICLASS TPieSeries; class PASCALIMPLEMENTATION TPieSeries : public TCircledSeries { typedef TCircledSeries inherited; private: bool FDark3d; TExplodedSlices* FExplodedSlice; int FExplodeBiggest; Tecanvas::TChartPen* FPiePen; TPieOtherSlice* FOtherSlice; bool FUsePatterns; void __fastcall DisableRotation(void); void __fastcall SetUsePatterns(bool Value); void __fastcall SetDark3d(bool Value); Teengine::TChartValueList* __fastcall GetPieValues(void); void __fastcall SetPieValues(Teengine::TChartValueList* Value); void __fastcall SetExplodeBiggest(int Value); void __fastcall SetPiePen(Tecanvas::TChartPen* Value); void __fastcall SetOtherSlice(TPieOtherSlice* Value); void __fastcall CalcExplodeBiggest(void); void __fastcall CalcExplodedOffset(int ValueIndex, int &OffsetX, int &OffsetY); protected: DynamicArray<TPieAngle > FAngles; int IniX; int IniY; int EndX; int EndY; bool IsExploded; void __fastcall CalcAngles(void); void __fastcall CalcExplodedRadius(int ValueIndex, int &AXRadius, int &AYRadius); virtual void __fastcall DoBeforeDrawChart(void); virtual void __fastcall DrawAllValues(void); virtual void __fastcall DrawPie(int ValueIndex); virtual void __fastcall DrawValue(int ValueIndex); virtual void __fastcall DrawMark(int ValueIndex, const AnsiString St, Teengine::TSeriesMarkPosition* APosition); virtual void __fastcall ClearLists(void); public: __fastcall virtual TPieSeries(Classes::TComponent* AOwner); __fastcall virtual ~TPieSeries(void); int __fastcall AddPie(const double AValue, const AnsiString ALabel, Graphics::TColor AColor); virtual void __fastcall Assign(Classes::TPersistent* Source); bool __fastcall BelongsToOtherSlice(int ValueIndex); int __fastcall CalcClickedPie(int x, int y); virtual int __fastcall CalcXPos(int ValueIndex); virtual int __fastcall Clicked(int x, int y); virtual int __fastcall CountLegendItems(void); virtual void __fastcall FillSampleValues(int NumValues); virtual void __fastcall GalleryChanged3D(bool Is3D); virtual AnsiString __fastcall GetEditorClass(); virtual int __fastcall LegendToValueIndex(int LegendIndex); virtual double __fastcall MaxXValue(void); virtual double __fastcall MinXValue(void); virtual double __fastcall MaxYValue(void); virtual double __fastcall MinYValue(void); virtual int __fastcall NumSampleValues(void); virtual void __fastcall PrepareForGallery(bool IsEnabled); virtual void __fastcall PrepareLegendCanvas(int ValueIndex, Graphics::TColor &BackColor, Graphics::TBrushStyle &BrushStyle); virtual void __fastcall SwapValueIndex(int a, int b); __property TPieAngles Angles = {read=FAngles}; __property TExplodedSlices* ExplodedSlice = {read=FExplodedSlice}; __published: __property CircleBackColor = {default=536870912}; __property ColorEachPoint = {default=1}; __property bool Dark3D = {read=FDark3d, write=SetDark3d, default=1}; __property int ExplodeBiggest = {read=FExplodeBiggest, write=SetExplodeBiggest, default=0}; __property TPieOtherSlice* OtherSlice = {read=FOtherSlice, write=SetOtherSlice}; __property Tecanvas::TChartPen* PiePen = {read=FPiePen, write=SetPiePen}; __property Teengine::TChartValueList* PieValues = {read=GetPieValues, write=SetPieValues}; __property RotationAngle = {default=0}; __property bool UsePatterns = {read=FUsePatterns, write=SetUsePatterns, default=0}; }; class DELPHICLASS TFastLineSeries; class PASCALIMPLEMENTATION TFastLineSeries : public Teengine::TChartSeries { typedef Teengine::TChartSeries inherited; private: bool FAutoRepaint; Tecanvas::TChartPen* FLinePen; int OldX; int OldY; void __fastcall SetLinePen(Tecanvas::TChartPen* Value); protected: virtual void __fastcall DrawValue(int ValueIndex); virtual void __fastcall DrawAllValues(void); virtual void __fastcall SetSeriesColor(Graphics::TColor AColor); void __fastcall PrepareCanvas(void); virtual void __fastcall DrawMark(int ValueIndex, const AnsiString St, Teengine::TSeriesMarkPosition* APosition); public: __fastcall virtual TFastLineSeries(Classes::TComponent* AOwner); __fastcall virtual ~TFastLineSeries(void); virtual void __fastcall Assign(Classes::TPersistent* Source); virtual int __fastcall Clicked(int x, int y); virtual void __fastcall DrawLegendShape(int ValueIndex, const Types::TRect &Rect); virtual AnsiString __fastcall GetEditorClass(); virtual void __fastcall NotifyNewValue(Teengine::TChartSeries* Sender, int ValueIndex); __published: __property bool AutoRepaint = {read=FAutoRepaint, write=FAutoRepaint, default=1}; __property Tecanvas::TChartPen* LinePen = {read=FLinePen, write=SetLinePen}; __property XValues ; __property YValues ; }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE double TwoPi; extern PACKAGE double HalfPi; extern PACKAGE double PiDegree; } /* namespace Series */ using namespace Series; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // Series
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 800 ] ] ]
715d998867836af4b30eb1f21026598f9c957361
14a00dfaf0619eb57f1f04bb784edd3126e10658
/lab6/AdaptiveLoopSubdivisionMesh.h
031cfde25a8de1e13172ea6e061b68a1b0d723a2
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,244
h
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Söderström ([email protected]) * *************************************************************************************************/ #ifndef __ADAPTIVE_LOOP_SUBDIVISION_MESH_H__ #define __ADAPTIVE_LOOP_SUBDIVISION_MESH_H__ #include "LoopSubdivisionMesh.h" #include "Util.h" #include <limits> /*! \brief Adaptive Subdivision mesh that is based on the Loop scheme */ class AdaptiveLoopSubdivisionMesh : public LoopSubdivisionMesh { public: AdaptiveLoopSubdivisionMesh(const HalfEdgeMesh & m, unsigned int s); AdaptiveLoopSubdivisionMesh(); ~AdaptiveLoopSubdivisionMesh(); //! Subdivides the mesh uniformly one step virtual bool subdivide(); //! Subdivides the mesh adaptivly one step. The angle is given in degrees, not radians virtual bool subdivide(float flatAngle); private: //! Method that ensures that boundaries between subdivided and not subdivided triangles match void treatFlatFaces(HalfEdgeMesh& subDivMesh); //! Classify triangles as flat or not flat void findFlatTriangles(float flatAngle); //! Calculate the number of flat neighbours to each triangle. Flatness 3 is assigned to all flat triangles. void calculateDegreeOfFlatness(); //! Finds the face index of the three faces neighbour to "face". void findTriangleNeighbours(const Face& face, unsigned int& neighbourIndex1, unsigned int& neighbourIndex2, unsigned int& neighbourIndex3); //! Finds which edge belonging to face 1 that is shared with face 2 //! Returns the array index of that edge unsigned int findSharedEdge(const Face& face1, const Face& face2); //! Returns true if the vertex with index "vertexIndex" is shared by a triangle that has been subdivided bool isSharedBySubdividedTriangle(unsigned int vertexIndex); std::vector<bool> mFaceIsFlat; std::vector<unsigned int> mFlatness; }; #endif
[ "onnepoika@da195381-492e-0410-b4d9-ef7979db4686", "jpjorge@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 1 ], [ 12, 22 ], [ 27, 27 ], [ 30, 30 ], [ 33, 33 ], [ 37, 37 ], [ 40, 40 ], [ 43, 43 ], [ 46, 46 ], [ 50, 50 ], [ 53, 53 ], [ 56, 58 ] ], [ [ 2, 11 ], [ 23, 26 ], [ 28, 29 ], [ 31, 32 ], [ 34, 36 ], [ 38, 39 ], [ 41, 42 ], [ 44, 45 ], [ 47, 49 ], [ 51, 52 ], [ 54, 55 ] ] ]
15279506d6a2da672d61c1ee686e2be20f364a86
a2ba072a87ab830f5343022ed11b4ac365f58ef0
/ urt-bumpy-q3map2 --username [email protected]/libs/typesystem.cpp
8e6b6d39c28cc57a54d1e83ced2459138faea8b8
[]
no_license
Garey27/urt-bumpy-q3map2
7d0849fc8eb333d9007213b641138e8517aa092a
fcc567a04facada74f60306c01e68f410cb5a111
refs/heads/master
2021-01-10T17:24:51.991794
2010-06-22T13:19:24
2010-06-22T13:19:24
43,057,943
0
0
null
null
null
null
UTF-8
C++
false
false
29
cpp
#include "typesystem.h"
[ [ [ 1, 3 ] ] ]
73f8b615f12fac5d8953386279429d6c1c7fcbcc
fac8de123987842827a68da1b580f1361926ab67
/src/input/InputEngine.cpp
ba7f96d915c9b670e78c9dc881df6725a628000c
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
#include "input/InputEngine.h" #ifdef _USRDLL BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif //........................................................................................ InputEngine::InputEngine() { this->threadFrequency = 60; this->threadPriority = THREAD_PRIORITY_NORMAL; this->directInput = NULL; } //........................................................................................ InputEngine::~InputEngine( void ) { stop(); if(directInput) { directInput->Release(); directInput = NULL; } } //........................................................................................ bit InputEngine::init( HINSTANCE hInstance,HWND hWnd,u32 freq,u32 priority ) { this->appInstance = hInstance; this->wndHandle = hWnd; this->threadFrequency = freq; this->threadPriority = priority; bit result = true; if (FAILED (DirectInput8Create(appInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**) &directInput, NULL))) { result = false; } if(result) { result &= mouse.init(this,appInstance,wndHandle,directInput,threadFrequency,threadPriority); result &= keyboard.init(this,appInstance,wndHandle,directInput,threadFrequency,threadPriority); //result &= mouse.init(this,appInstance,wndHandle,directInput,15,THREAD_PRIORITY_LOWEST); //result &= keyboard.init(this,appInstance,wndHandle,directInput,15,THREAD_PRIORITY_LOWEST); } return result; } //........................................................................................ void InputEngine::start() { mouse.start(); keyboard.start(); } //........................................................................................ void InputEngine::stop() { mouse.stop(); keyboard.stop(); }
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 79 ] ] ]
be1df677cc4ed935cfae828d9d37181c35d5d169
a92598d0a8a2e92b424915d2944212f2f13e7506
/PtRPG/libs/cocos2dx/textures/CCTextureCache.cpp
6da79fe445b8a9e8d36c8d7b0b2fe5c547fd1661
[ "MIT" ]
permissive
peteo/RPG_Learn
0cc4facd639bd01d837ac56cf37a07fe22c59211
325fd1802b14e055732278f3d2d33a9577608c39
refs/heads/master
2021-01-23T11:07:05.050645
2011-12-12T08:47:27
2011-12-12T08:47:27
2,299,148
2
0
null
null
null
null
UTF-8
C++
false
false
17,279
cpp
/**************************************************************************** Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <stack> #include <string> #include <cctype> #include "CCTextureCache.h" #include "CCTexture2D.h" #include "ccMacros.h" #include "CCData.h" #include "CCDirector.h" #include "platform/platform.h" #include "CCFileUtils.h" #include "CCImage.h" #include "support/ccUtils.h" namespace cocos2d { class CCAsyncObject : CCObject { public: fpAsyncCallback m_pfnCallback; CCObject* m_pTarget; std::string * m_pData; public: CCAsyncObject(); ~CCAsyncObject() { CCLOGINFO("cocos2d: deallocing CCAsyncObject."); CC_SAFE_DELETE(m_pTarget); CC_SAFE_DELETE(m_pData); } }; // implementation CCTextureCache // TextureCache - Alloc, Init & Dealloc static CCTextureCache *g_sharedTextureCache; CCTextureCache * CCTextureCache::sharedTextureCache() { if (!g_sharedTextureCache) g_sharedTextureCache = new CCTextureCache(); return g_sharedTextureCache; } CCTextureCache::CCTextureCache() { CCAssert(g_sharedTextureCache == NULL, "Attempted to allocate a second instance of a singleton."); m_pTextures = new CCMutableDictionary<std::string, CCTexture2D*>(); m_pDictLock = new CCLock(); m_pContextLock = new CCLock(); } CCTextureCache::~CCTextureCache() { CCLOGINFO("cocos2d: deallocing CCTextureCache."); CC_SAFE_RELEASE(m_pTextures); CC_SAFE_DELETE(m_pDictLock); CC_SAFE_DELETE(m_pContextLock); } void CCTextureCache::purgeSharedTextureCache() { CC_SAFE_RELEASE_NULL(g_sharedTextureCache); } char * CCTextureCache::description() { char *ret = new char[100]; sprintf(ret, "<CCTextureCache | Number of textures = %u>", m_pTextures->count()); return ret; } // TextureCache - Add Images /* @todo EAGLContext void CCTextureCache::addImageWithAsyncObject(CCAsyncObject* async) { CCAutoreleasePool *autoreleasepool = [[CCAutoreleasePool alloc] init]; // textures will be created on the main OpenGL context // it seems that in SDK 2.2.x there can't be 2 threads creating textures at the same time // the lock is used for this purpose: issue #472 [contextLock lock]; if( auxEAGLcontext == nil ) { auxEAGLcontext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[[[[CCDirector sharedDirector] openGLView] context] sharegroup]]; if( ! auxEAGLcontext ) CCLOG(@"cocos2d: TextureCache: Could not create EAGL context"); } if( [EAGLContext setCurrentContext:auxEAGLcontext] ) { // load / create the texture CCTexture2D *tex = [self addImage:async.data]; // The callback will be executed on the main thread [async.target performSelectorOnMainThread:async.selector withObject:tex waitUntilDone:NO]; [EAGLContext setCurrentContext:nil]; } else { CCLOG(@"cocos2d: TetureCache: EAGLContext error"); } [contextLock unlock]; [autoreleasepool release]; }*/ /* @todo selector, NSThread void CCTextureCache::addImageAsync(const char* filename, CCObject *target, fpAsyncCallback func) { CCAssert(filename != NULL , "TextureCache: fileimage MUST not be nill"); // optimization CCTexture2D * tex; if ( (tex = m_pTextures->objectForKey(filename)) ) { target-> } if( (tex=[textures objectForKey: filename] ) ) { [target performSelector:selector withObject:tex]; return; } // schedule the load CCAsyncObject *asyncObject = [[CCAsyncObject alloc] init]; asyncObject.selector = selector; asyncObject.target = target; asyncObject.data = filename; [NSThread detachNewThreadSelector:@selector(addImageWithAsyncObject:) toTarget:self withObject:asyncObject]; [asyncObject release]; }*/ CCTexture2D * CCTextureCache::addImage(const char * path) { CCAssert(path != NULL, "TextureCache: fileimage MUST not be NULL"); CCTexture2D * texture = NULL; // Split up directory and filename // MUTEX: // Needed since addImageAsync calls this method from a different thread m_pDictLock->lock(); // remove possible -HD suffix to prevent caching the same image twice (issue #1040) std::string pathKey = path; CCFileUtils::ccRemoveHDSuffixFromFile(pathKey); pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str()); texture = m_pTextures->objectForKey(pathKey); std::string fullpath = pathKey; // (CCFileUtils::fullPathFromRelativePath(path)); if( ! texture ) { std::string lowerCase(path); for (unsigned int i = 0; i < lowerCase.length(); ++i) { lowerCase[i] = tolower(lowerCase[i]); } // all images are handled by UIImage except PVR extension that is handled by our own handler do { if (std::string::npos != lowerCase.find(".pvr")) { texture = this->addPVRImage(fullpath.c_str()); } // Issue #886: TEMPORARY FIX FOR TRANSPARENT JPEGS IN IOS4 else if (std::string::npos != lowerCase.find(".jpg") || std::string::npos != lowerCase.find(".jpeg")) { CCImage image; CCFileData data(fullpath.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); CC_BREAK_IF(! image.initWithImageData((void*)pBuffer, nSize, CCImage::kFmtJpg)); texture = new CCTexture2D(); texture->initWithImage(&image); if( texture ) { #if CC_ENABLE_CACHE_TEXTTURE_DATA // cache the texture file name VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtJpg); #endif m_pTextures->setObject(texture, pathKey); // autorelease prevents possible crash in multithreaded environments texture->autorelease(); } else { CCLOG("cocos2d: Couldn't add image:%s in CCTextureCache", path); } } else { // prevents overloading the autorelease pool CCImage image; CCFileData data(fullpath.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); CC_BREAK_IF(! image.initWithImageData((void*)pBuffer, nSize, CCImage::kFmtPng)); texture = new CCTexture2D(); texture->initWithImage(&image); if( texture ) { #if CC_ENABLE_CACHE_TEXTTURE_DATA // cache the texture file name VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtPng); #endif m_pTextures->setObject(texture, pathKey); // autorelease prevents possible crash in multithreaded environments texture->autorelease(); } else { CCLOG("cocos2d: Couldn't add image:%s in CCTextureCache", path); } } } while (0); } m_pDictLock->unlock(); return texture; } #ifdef CC_SUPPORT_PVRTC CCTexture2D* CCTextureCache::addPVRTCImage(const char* path, int bpp, bool hasAlpha, int width) { CCAssert(path != NULL, "TextureCache: fileimage MUST not be nill"); CCAssert( bpp==2 || bpp==4, "TextureCache: bpp must be either 2 or 4"); CCTexture2D * texture; std::string temp(path); CCFileUtils::ccRemoveHDSuffixFromFile(temp); if ( (texture = m_pTextures->objectForKey(temp)) ) { return texture; } // Split up directory and filename std::string fullpath( CCFileUtils::fullPathFromRelativePath(path) ); CCData * data = CCData::dataWithContentsOfFile(fullpath); texture = new CCTexture2D(); if( texture->initWithPVRTCData(data->bytes(), 0, bpp, hasAlpha, width, (bpp==2 ? kCCTexture2DPixelFormat_PVRTC2 : kCCTexture2DPixelFormat_PVRTC4))) { m_pTextures->setObject(texture, temp); texture->autorelease(); } else { CCLOG("cocos2d: Couldn't add PVRTCImage:%s in CCTextureCache",path); } CC_SAFE_DELETE(data); return texture; } #endif // CC_SUPPORT_PVRTC CCTexture2D * CCTextureCache::addPVRImage(const char* path) { CCAssert(path != NULL, "TextureCache: fileimage MUST not be nill"); CCTexture2D * tex; std::string key(path); // remove possible -HD suffix to prevent caching the same image twice (issue #1040) CCFileUtils::ccRemoveHDSuffixFromFile(key); if( (tex = m_pTextures->objectForKey(key)) ) { return tex; } // Split up directory and filename std::string fullpath = CCFileUtils::fullPathFromRelativePath(key.c_str()); tex = new CCTexture2D(); if( tex->initWithPVRFile(fullpath.c_str()) ) { m_pTextures->setObject(tex, key); tex->autorelease(); } else { CCLOG("cocos2d: Couldn't add PVRImage:%s in CCTextureCache",key.c_str()); } return tex; } /* @todo CGImageRef -(CCTexture2D*) addCGImage: (CGImageRef) imageref forKey: (string & )key { CCAssert(imageref != nil, @"TextureCache: image MUST not be nill"); CCTexture2D * tex = nil; // If key is nil, then create a new texture each time if( key && (tex=[textures objectForKey: key] ) ) { return tex; } // prevents overloading the autorelease pool UIImage *image = [[UIImage alloc] initWithCGImage:imageref]; tex = [[CCTexture2D alloc] initWithImage: image]; [image release]; if(tex && key) [textures setObject: tex forKey:key]; else CCLOG(@"cocos2d: Couldn't add CGImage in CCTextureCache"); return [tex autorelease]; }*/ CCTexture2D* CCTextureCache::addUIImage(CCImage *image, const char *key) { CCAssert(image != NULL && key != NULL, "TextureCache: image MUST not be nill"); CCTexture2D * texture = NULL; std::string forKey = key; m_pDictLock->lock(); do { // If key is nil, then create a new texture each time if((texture = m_pTextures->objectForKey(forKey))) { break; } // prevents overloading the autorelease pool texture = new CCTexture2D(); texture->initWithImage(image); if(texture) { m_pTextures->setObject(texture, forKey); texture->autorelease(); } else { CCLOG("cocos2d: Couldn't add UIImage in CCTextureCache"); } } while (0); m_pDictLock->unlock(); return texture; } // TextureCache - Remove void CCTextureCache::removeAllTextures() { m_pTextures->removeAllObjects(); } void CCTextureCache::removeUnusedTextures() { std::vector<std::string> keys = m_pTextures->allKeys(); std::vector<std::string>::iterator it; for (it = keys.begin(); it != keys.end(); ++it) { CCTexture2D *value = m_pTextures->objectForKey(*it); if (value->retainCount() == 1) { CCLOG("cocos2d: CCTextureCache: removing unused texture: %s", (*it).c_str()); m_pTextures->removeObjectForKey(*it); } } } void CCTextureCache::removeTexture(CCTexture2D* texture) { if( ! texture ) return; std::vector<std::string> keys = m_pTextures->allKeysForObject(texture); for (unsigned int i = 0; i < keys.size(); i++) { m_pTextures->removeObjectForKey(keys[i]); } } void CCTextureCache::removeTextureForKey(const char *textureKeyName) { if (textureKeyName == NULL) { return; } string fullPath = CCFileUtils::fullPathFromRelativePath(textureKeyName); m_pTextures->removeObjectForKey(fullPath); } CCTexture2D* CCTextureCache::textureForKey(const char* key) { std::string strKey = CCFileUtils::fullPathFromRelativePath(key); return m_pTextures->objectForKey(strKey); } void CCTextureCache::reloadAllTextures() { #if CC_ENABLE_CACHE_TEXTTURE_DATA VolatileTexture::reloadAllTextures(); #endif } void CCTextureCache::dumpCachedTextureInfo() { unsigned int count = 0; unsigned int totalBytes = 0; vector<string> keys = m_pTextures->allKeys(); vector<string>::iterator iter; for (iter = keys.begin(); iter != keys.end(); iter++) { CCTexture2D *tex = m_pTextures->objectForKey(*iter); unsigned int bpp = tex->bitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; CCLOG("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", (*iter).c_str(), (long)tex->retainCount(), (long)tex->getName(), (long)tex->getPixelsWide(), (long)tex->getPixelsHigh(), (long)bpp, (long)bytes / 1024); } CCLOG("cocos2d: CCTextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); } #if CC_ENABLE_CACHE_TEXTTURE_DATA std::list<VolatileTexture*> VolatileTexture::textures; bool VolatileTexture::isReloading = false; VolatileTexture::VolatileTexture(CCTexture2D *t) : texture(t) , m_eCashedImageType(kInvalid) , m_pTextureData(NULL) , m_PixelFormat(kTexture2DPixelFormat_RGBA8888) , m_strFileName("") , m_FmtImage(CCImage::kFmtPng) , m_alignment(CCTextAlignmentCenter) , m_strFontName("") , m_strText("") , m_fFontSize(0.0f) { m_size = CCSizeMake(0, 0); textures.push_back(this); } VolatileTexture::~VolatileTexture() { textures.remove(this); } void VolatileTexture::addImageTexture(CCTexture2D *tt, const char* imageFileName, CCImage::EImageFormat format) { if (isReloading) return; VolatileTexture *vt = 0; std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *v = *i++; if (v->texture == tt) { vt = v; break; } } if (!vt) vt = new VolatileTexture(tt); vt->m_eCashedImageType = kImageFile; vt->m_strFileName = imageFileName; vt->m_FmtImage = format; } void VolatileTexture::addDataTexture(CCTexture2D *tt, void* data, CCTexture2DPixelFormat pixelFormat, CCSize contentSize) { if (isReloading) return; VolatileTexture *vt = 0; std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *v = *i++; if (v->texture == tt) { vt = v; break; } } if (!vt) vt = new VolatileTexture(tt); vt->m_eCashedImageType = kImageData; vt->m_pTextureData = data; vt->m_PixelFormat = pixelFormat; vt->m_TextureSize = contentSize; } void VolatileTexture::addStringTexture(CCTexture2D *tt, const char* text, CCSize dimensions, CCTextAlignment alignment, const char *fontName, float fontSize) { if (isReloading) return; VolatileTexture *vt = 0; std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *v = *i++; if (v->texture == tt) { vt = v; break; } } if (!vt) vt = new VolatileTexture(tt); vt->m_eCashedImageType = kString; vt->m_size = dimensions; vt->m_strFontName = fontName; vt->m_alignment = alignment; vt->m_fFontSize = fontSize; vt->m_strText = text; } void VolatileTexture::removeTexture(CCTexture2D *t) { std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *vt = *i++; if (vt->texture == t) { delete vt; break; } } } void VolatileTexture::reloadAllTextures() { isReloading = true; CCLOG("reload all texture"); std::list<VolatileTexture *>::iterator i = textures.begin(); while( i != textures.end() ) { VolatileTexture *vt = *i++; switch (vt->m_eCashedImageType) { case kImageFile: { CCImage image; CCFileData data(vt->m_strFileName.c_str(), "rb"); unsigned long nSize = data.getSize(); unsigned char* pBuffer = data.getBuffer(); if (image.initWithImageData((void*)pBuffer, nSize, vt->m_FmtImage)) { vt->texture->initWithImage(&image); } } break; case kImageData: { unsigned int nPOTWide, nPOTHigh; nPOTWide = ccNextPOT((int)vt->m_TextureSize.width); nPOTHigh = ccNextPOT((int)vt->m_TextureSize.height); vt->texture->initWithData(vt->m_pTextureData, vt->m_PixelFormat, nPOTWide, nPOTHigh, vt->m_TextureSize); } break; case kString: { vt->texture->initWithString(vt->m_strText.c_str(), vt->m_size, vt->m_alignment, vt->m_strFontName.c_str(), vt->m_fFontSize); } break; default: break; } } isReloading = false; } #endif // CC_ENABLE_CACHE_TEXTTURE_DATA }//namespace cocos2d
[ [ [ 1, 656 ] ] ]
0bc74b4096bfa292a110a886977c647bed83ceae
b90f7dce513fd3d13bab0b8769960dea901d4f3b
/game_client/game_client/AbstractApplication.cpp
947ff341e4bbe3459c3a372787369166e21372e6
[]
no_license
lasti15/easygametools
f447052cd4c42609955abd76b4c8571422816b11
0b819c957077a4eeaf9a2492772040dafdfca4c3
refs/heads/master
2021-01-10T09:14:52.182154
2011-03-09T01:51:51
2011-03-09T01:51:51
55,684,684
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
#include "AbstractApplication.h" using namespace ROG; const Logger* AbstractApplication::log = Logger::getLogger("AbstractApplication"); AbstractApplication::AbstractApplication(const char* appName) { strncpy(this->appName, appName, 254); Thread::addThreadEventListener(this); } AbstractApplication::~AbstractApplication() { Thread::removeThreadEventListener(this); } //TODO: do something useful with this void AbstractApplication::threadEvent(Object<ThreadEvent> evt) { switch (evt->getEventType()) { case THR_STARTED: log->info("Thread Started"); break; case THR_STOPPED: log->info("Thread Stopped"); break; case THR_DESTROYED: log->info("Thread Destroyed"); break; case THR_EXCEPTION: log->info("Thread Exception"); break; } } const void AbstractApplication::runGame() { run(); }
[ [ [ 1, 52 ] ] ]
f68fb5acb2bc72b05dba9b06ead2ad3887948862
9e590d76ad900ef940486ccda8633bd79c6acd4e
/ki2key/Common.hpp
a4651151bb54e28643955c7d5aa2e1c77836bae8
[ "BSD-2-Clause" ]
permissive
szk/Ki2Key
f66ec830e61d14ddf3c42ac469cd88da2dcf9e03
9498f32df419f94acbbecdffefbef25dc083eecf
refs/heads/master
2020-05-16T23:11:19.061205
2011-12-07T15:45:21
2011-12-07T15:45:21
1,168,628
0
0
null
null
null
null
UTF-8
C++
false
false
5,730
hpp
/* * Copyright (c) 2011, Tatsuhiko Suzuki * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef COMMON_HPP__ #define COMMON_HPP__ #pragma warning( disable : 4995 ) #include <stdio.h> #include <math.h> #include <float.h> #include <cmath> #include <string> #include <iostream> #include <sstream> #include <map> #include <list> #include <vector> #include <stack> typedef char Char; typedef unsigned char uChar; typedef short Int16; typedef unsigned short uInt16; typedef int Int32; typedef unsigned int uInt32; typedef float Float32; #ifdef _WIN32_WINDOWS typedef std::wstring Str; typedef std::wstringstream Strstream; #else typedef std::string Str; typedef std::stringstream Strstream; #endif // _WIN32_WINDOWS #define CREDIT "Copyright (c) 2011, Tatsuhiko Suzuki\r\nhttp://vram.org/" #define APPNAME "Ki2Key" #define APPVERSION "alpha 2" #define SETTING_FILENAME "ki2key.xml" #define S_AREA_WIDTH 640 #define S_AREA_HEIGHT 480 #define MAX_DEPTH 10000 #define MAX_USERS 15 #define GESTURE_TIMEOUT 10 #define TILE_WIDTH 50 #define TILE_HEIGHT 50 #define LV_BK_RGB RGB(255, 255, 255) #define LV_GST_RGB RGB(128, 0, 96) #define LV_TGT_RGB RGB(0, 128, 0) #define LV_CMD_RGB RGB(0, 0, 128) #define YES "Yes" #define NO "No" extern const Str INIT_GESTURE; extern const Str INIT_TARGET; extern const Str INIT_COMMAND; extern const Str GST_UP; extern const Str GST_DOWN; extern const Str GST_RIGHT; extern const Str GST_LEFT; extern const Str GST_STAY; typedef struct RGB24 { unsigned char red; // 8bit unsigned char green; unsigned char blue; } RGB24; typedef struct RGB32 { unsigned char red; // 8bit unsigned char green; unsigned char blue; unsigned char alpha; } RGB32; typedef struct Pos48 { Int16 x; // 16bit Int16 y; Int16 z; } Pos48; enum UserRequest { UR_GUI_SET_GESTURE, UR_GUI_SET_TARGET, UR_GUI_SET_COMMAND, UR_GUI_DO_ACTION, UR_CAM_GESTURE, UR_CAM_VALUE, UR_NONE, UR_NUM, }; typedef unsigned short Depth16; // 16bit extern Str lasterr_str; #define ERR_DEV_SENSOR 0x00000001 #define ERR_DEV_VIEW 0x00000002 #define ERR_DEV_SENDER 0x00000004 #define ERR_DEV_KEY 0x00000008 #define ERR_OS_SENSOR 0x00000010 #define ERR_OS_VIEW 0x00000020 #define ERR_OS_SENDER 0x00000040 #define ERR_OS_KEY 0x00000080 #define PI 3.14159265358979323846 #define RADIAN(i) (((i) * PI) / 180) #define DIGREE(i) (((i) * 180) / PI) #define DEL(i) { if ((i) != NULL) { delete (i); (i) = NULL; } } #define DEL_ARRAY(i) { if ((i) != NULL) { delete[] (i); (i) = NULL; } } void OutputDebugStr( LPCSTR pszFormat, ...); class Pos3D { public: Pos3D(Float32 x_ = 0, Float32 y_ = 0, Float32 z_ = 0) { v[0] = x_, v[1] = y_, v[2] = z_; } virtual ~Pos3D(void) {} inline void set(Float32 x_, Float32 y_, Float32 z_) { v[0] = x_; v[1] = y_; v[2] = z_; } inline const Float32* get_v(void) const { return v; } inline const Float32 get_x(void) const { return v[0]; } inline const Float32 get_y(void) const { return v[1]; } inline const Float32 get_z(void) const { return v[2]; } inline const bool operator==(const Pos3D& rhs_) const { return rhs_.v[0] == v[0] && rhs_.v[1] == v[1] && rhs_.v[2] == v[2]; } inline const bool operator!=(const Pos3D& rhs_) const { return rhs_.v[0] != v[0] || rhs_.v[1] != v[1] || rhs_.v[2] != v[2]; } inline Pos3D& operator+=(const Pos3D& rhs_) { v[0] += rhs_.v[0]; v[1] += rhs_.v[1]; v[2] += rhs_.v[2]; return *this; } inline Pos3D& operator-=(const Pos3D& rhs_) { v[0] -= rhs_.v[0]; v[1] -= rhs_.v[1]; v[2] -= rhs_.v[2]; return *this; } inline Pos3D operator+(const Pos3D& rhs_) const { Pos3D val(*this); val += rhs_; return val; } inline Pos3D operator-(const Pos3D& rhs_) const { Pos3D val(*this); val -= rhs_; return val; } inline void debug() const { OutputDebugStr("%f, %f, %f", v[0], v[1], v[2]); } private: Float32 v[3]; }; #endif
[ [ [ 1, 193 ] ] ]
d0a1c892277b6490c655672ae3a2862c0711311d
d64ed1f7018aac768ddbd04c5b465c860a6e75fa
/ii_FreePcb.h
37edc3e52a5e991ad84a29723664c035a517115d
[]
no_license
roc2/archive-freepcb-codeproject
68aac46d19ac27f9b726ea7246cfc3a4190a0136
cbd96cd2dc81a86e1df57b86ce540cf7c120c282
refs/heads/master
2020-03-25T00:04:22.712387
2009-06-13T04:36:32
2009-06-13T04:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
748
h
#pragma once #include "inheritable_item.h" class CII_FreePcb : public CInheritableInfo { public: // This is a list of all inheritable item IDs used in the project enum EInheritableItemIds { E_II_TRACE_WIDTH, E_II_VIA_WIDTH, E_II_VIA_HOLE, E_II_CA_CLEARANCE }; enum EStatus { // Remember, these are negative so normal enum // counting order won't work here. E_AUTO_CALC = CInheritableInfo::E__STATUS_USER, E_USE_DEF_FROM_WIDTH = E_AUTO_CALC-1, }; public: CII_FreePcb() {} CII_FreePcb(CInheritableInfo const &from) : CInheritableInfo(from) {} CII_FreePcb(CII_FreePcb const &from) : CInheritableInfo(from) {} public: static CString GetItemText(Item const &item); };
[ "jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314" ]
[ [ [ 1, 32 ] ] ]
79cc5350bc1bd51106e3e80d4870aab7f2e1c746
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMAttrMapImpl.hpp
b1674d6fafbd260d88b79ab24d0a39b16c3161bd
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
4,044
hpp
#ifndef DOMAttrMapImpl_HEADER_GUARD_ #define DOMAttrMapImpl_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * 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. */ /* * $Id: DOMAttrMapImpl.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMNamedNodeMap.hpp> XERCES_CPP_NAMESPACE_BEGIN class DOMNodeVector; class DOMNode; class CDOM_EXPORT DOMAttrMapImpl : public DOMNamedNodeMap { protected: DOMNodeVector* fNodes; DOMNode* fOwnerNode; // the node this map belongs to virtual void cloneContent(const DOMAttrMapImpl *srcmap); bool readOnly(); // revisit. Look at owner node read-only. private: bool attrDefaults; public: DOMAttrMapImpl(DOMNode *ownerNod); // revisit. This "copy" constructor is used for cloning an Element with Attributes, // and for setting up default attributes. It's probably not right // for one or the other or both. DOMAttrMapImpl(DOMNode *ownerNod, const DOMAttrMapImpl *defaults); DOMAttrMapImpl(); virtual ~DOMAttrMapImpl(); virtual DOMAttrMapImpl *cloneAttrMap(DOMNode *ownerNode); virtual bool hasDefaults(); virtual void hasDefaults(bool value); virtual int findNamePoint(const XMLCh *name) const; virtual int findNamePoint(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMNode* removeNamedItemAt(XMLSize_t index); virtual void setReadOnly(bool readOnly, bool deep); virtual XMLSize_t getLength() const; virtual DOMNode* item(XMLSize_t index) const; virtual DOMNode* getNamedItem(const XMLCh *name) const; virtual DOMNode* setNamedItem(DOMNode *arg); virtual DOMNode* removeNamedItem(const XMLCh *name); virtual DOMNode* getNamedItemNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMNode* setNamedItemNS(DOMNode *arg); virtual DOMNode* removeNamedItemNS(const XMLCh *namespaceURI, const XMLCh *localName); void reconcileDefaultAttributes(const DOMAttrMapImpl* defaults); void moveSpecifiedAttributes(DOMAttrMapImpl* srcmap); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMAttrMapImpl(const DOMAttrMapImpl &); DOMAttrMapImpl & operator = (const DOMAttrMapImpl &); }; // --------------------------------------------------------------------------- // DOMAttrMapImpl: Getters & Setters // --------------------------------------------------------------------------- inline bool DOMAttrMapImpl::hasDefaults() { return attrDefaults; } inline void DOMAttrMapImpl::hasDefaults(bool value) { attrDefaults = value; } XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 114 ] ] ]
d9e80d9f30720731300900adcedfca51b7978df9
8a8873b129313b24341e8fa88a49052e09c3fa51
/src/FileBrowser.cpp
08fe3b1ea390f00d9b5964e34868113d8a8c0b38
[]
no_license
flaithbheartaigh/wapbrowser
ba09f7aa981d65df810dba2156a3f153df071dcf
b0d93ce8517916d23104be608548e93740bace4e
refs/heads/master
2021-01-10T11:29:49.555342
2010-03-08T09:36:03
2010-03-08T09:36:03
50,261,329
1
0
null
null
null
null
UTF-8
C++
false
false
13,200
cpp
/* ============================================================================ Name : FileBrowser.cpp Author : 浮生若茶 Version : Copyright : Your copyright notice Description : CFileBrowser implementation ============================================================================ */ #include <coemain.h> #include <bautils.h> #ifdef __SERIES60_3X__ #include <akniconutils.h> #endif #include "FileBrowser.h" #include "FileBrowserObserver.h" #include "Window.h" #include "MainEngine.h" #include "ControlFactory.h" #include "BitmapFactory.h" #include "ScreenLayout.h" #include "Graphic.h" #include "ListBox.h" #include "PreDefine.h" #include "TypeDefine.h" #include "cocobmp.h" #include "CoCoPreDefine.h" _LIT(KCDriver, "C:"); _LIT(KEDriver, "E:"); _LIT(KZDriver, "Z:"); _LIT(KBackslash, "\\"); CFileBrowser::CFileBrowser(CMainEngine& aMainEngine,MFileBrowserObserver& aFileBrowserObserver,TInt aBrowserType) : CControl(EFileBrowser) , iMainEngine(aMainEngine) , iObserver(aFileBrowserObserver) , iBrowserType(aBrowserType) , iFs(CCoeEnv::Static()->FsSession()) , iLeftCommond(KCmdEventNull) , iRightCommand(KCmdEventNull) { SetCleanUpObserver(&aMainEngine); iHasButton = ETrue; } CFileBrowser::~CFileBrowser() { delete iListBox; delete iDesArray; delete iSaveAsBmp; delete iTitleText; } CFileBrowser* CFileBrowser::NewLC(CMainEngine& aMainEngine,MFileBrowserObserver& aFileBrowserObserver,TInt aBrowserType) { CFileBrowser* self = new (ELeave)CFileBrowser(aMainEngine,aFileBrowserObserver,aBrowserType); CleanupStack::PushL(self); self->ConstructL(); return self; } CFileBrowser* CFileBrowser::NewL(CMainEngine& aMainEngine,MFileBrowserObserver& aFileBrowserObserver,TInt aBrowserType) { CFileBrowser* self=CFileBrowser::NewLC(aMainEngine,aFileBrowserObserver,aBrowserType); CleanupStack::Pop(); // self; return self; } void CFileBrowser::ConstructL() { //iTitleText = aTitleText.AllocL(); if(EBrowserFolders == iBrowserType) { iTitleText =iMainEngine.GetDesById(ECoCoTestRes_SelectFolder).AllocL(); } else { iTitleText = iMainEngine.GetDesById(ECoCoTestRes_SelectFile).AllocL(); } iDesArray = new (ELeave) CDesCArrayFlat(10); InitBitmaps(); InitRootDir(); } ////////////////////////////////////////////////////////////////////////// //From CControl ////////////////////////////////////////////////////////////////////////// void CFileBrowser::Draw(CGraphic& aGraphic)const { ASSERT(iListBox); ASSERT(iTitleText); aGraphic.BitBlt(iStartPoint,iSaveAsBmp); //aGraphic.SetPenColor(KRgbBlack); aGraphic.SetPenColor(KSelectedTextColor); aGraphic.SetPenStyle(CGraphicsContext::ESolidPen); aGraphic.DrawText(iStartPoint + iTextPoint,*iTitleText); iListBox->Draw(aGraphic); } TBool CFileBrowser::KeyEventL(TInt aKeyCode) { ASSERT(iListBox); TBool keyResult = iListBox->KeyEventL(aKeyCode); if(!keyResult) { keyResult = ETrue; switch(aKeyCode) { case EKeyDevice0: DoConfirm(); break; case EKeyLeftArrow: ReadParentDir(); break; case EKeyRightArrow: case EKeyDevice3: //DoReadSub(); ReadSub(); break; case EKeyDevice1: DoCancel(); break; default: keyResult = EFalse; break; } } return ETrue; //屏蔽底层操作 } TBool CFileBrowser::HandleCommandL(TInt aCommand) { ASSERT(iListBox); return iListBox->HandleCommandL(aCommand); } void CFileBrowser::SizeChanged(const TRect& aScreenRect) { ASSERT(iListBox); iListBox->SizeChanged(aScreenRect); } const TDesC& CFileBrowser::LeftButton() const { return iMainEngine.GetDesById(ETurkeyTextRes_Ok); } const TDesC& CFileBrowser::RightButton() const { return iMainEngine.GetDesById(ETurkeyTextRes_Cancel); } ////////////////////////////////////////////////////////////////////////// //public ////////////////////////////////////////////////////////////////////////// void CFileBrowser::SetPath(const TDesC& aFilePath) { ASSERT(BaflUtils::PathExists(iFs,aFilePath)); iCurrentPath.Zero(); iCurrentPath.Append(aFilePath); iMainEngine.WriteLog16(iCurrentPath); InitDirList(iCurrentPath); } void CFileBrowser::SetTitle(const TDesC& aTitleText) { delete iTitleText; iTitleText = NULL; iTitleText = aTitleText.AllocL(); } void CFileBrowser::SetCommandType(TInt aLeftCommand,TInt aRightCommand) { iLeftCommond = aLeftCommand; iRightCommand = aRightCommand; } ////////////////////////////////////////////////////////////////////////// //private ////////////////////////////////////////////////////////////////////////// void CFileBrowser::DoConfirm() { if(EBrowserFolders == iBrowserType) { HBufC* tempFilePath = GetFileOrPathLC(); iMainEngine.WriteLog16(*tempFilePath); ASSERT(BaflUtils::PathExists(iFs,*tempFilePath)); MFileBrowserObserver& observer = iObserver; TInt command = iLeftCommond; CleanupSelf(); observer.DoFileEvent(*tempFilePath,command); CleanupStack::PopAndDestroy(); //tempFilePath } else { ReadSub(); } } void CFileBrowser::DoCancel() { HBufC* tempFilePath = GetFileOrPathLC(); MFileBrowserObserver& observer = iObserver; TInt command = iRightCommand; CleanupSelf(); observer.DoFileEvent(*tempFilePath,command); CleanupStack::PopAndDestroy(); //tempFilePath } void CFileBrowser::InitRootDir() { ASSERT(iDesArray && iDesArray->Count() == 0); iCurrentPath.Zero(); iMainEngine.WriteLog16(iCurrentPath); //iDesArray->Reset(); iDesArray->AppendL(KCDriver); iFolderNum++; #ifndef __WINS__ iDesArray->AppendL(KEDriver); iFolderNum++; #endif if(EBroswerFiles == iBrowserType) { iDesArray->AppendL(KZDriver); iFolderNum++; } InitListBox(); } //如何处理空列表?? //即空文件夹的情况 void CFileBrowser::ReadSub() { HBufC* tempFilePath = GetFileOrPathLC(); if(EBroswerFiles == iBrowserType) { if(BaflUtils::FileExists(iFs,*tempFilePath)) //是一个文件 { MFileBrowserObserver& observer = iObserver; TInt command = iLeftCommond; CleanupSelf(); observer.DoFileEvent(*tempFilePath,iLeftCommond); } else { ASSERT(BaflUtils::PathExists(iFs,*tempFilePath)); InitDirList(*tempFilePath); } } else { ASSERT(BaflUtils::PathExists(iFs,*tempFilePath)); InitDirList(*tempFilePath); } CleanupStack::PopAndDestroy(); //tempFilePath } void CFileBrowser::ReadParentDir() { if(iCurrentPath.Length() == 0) //当前路径为空时说明为根目录 { //什么都不做 } else { if(iCurrentPath.Length() == 3) //根目录的子目录 { InitRootDir(); } else { iMainEngine.WriteLog16(iCurrentPath); iCurrentPath = ParseParentPath(iCurrentPath); iMainEngine.WriteLog16(iCurrentPath); InitDirList(iCurrentPath); iMainEngine.WriteLog16(iCurrentPath); } } } //-------------------------------------------------------------------------- //InitDirList //若某目录为空,则不改变当前文件列表 //-------------------------------------------------------------------------- void CFileBrowser::InitDirList(const TDesC& aFilePath) { iMainEngine.WriteLog16(_L("CFileBrowser::InitDirList")); iMainEngine.WriteLog16(aFilePath); ASSERT(BaflUtils::PathExists(iFs,aFilePath)); ASSERT(iDesArray && iDesArray->Count() == 0); RFs& fs = CCoeEnv::Static()->FsSession(); CDir* dir = NULL; fs.GetDir(aFilePath, KEntryAttNormal|KEntryAttDir, ESortByName, dir); ASSERT(dir); TFileName tFilePath; if(dir->Count() > 0) { iFolderNum = 0; iFileNum = 0; for (TInt i = 0 ; i < dir->Count() ; i++) { const TEntry& entry = (*dir)[i]; iMainEngine.WriteLog16(entry.iName); if (entry.IsDir()) { //卞涛增加对是否可访问的文件夹做判断,防止出现没有访问权限的文件夹 tFilePath.Zero(); tFilePath.Append(aFilePath); if(aFilePath.Right(1).Compare(_L("\\"))!=0) { tFilePath.Append(_L("\\")); } tFilePath.Append(entry.iName); tFilePath.Append(_L("\\")); TBool tempIsFolder; TInt err = BaflUtils::IsFolder(iFs,tFilePath,tempIsFolder); if(err==KErrNone) { iDesArray->AppendL(entry.iName); iFolderNum++; } } } if(EBroswerFiles == iBrowserType) { for (TInt i = 0 ; i < dir->Count() ; i++) { const TEntry& entry = (*dir)[i]; if (!entry.IsDir()) { if(entry.IsSystem()||entry.IsHidden()) continue; iDesArray->AppendL(entry.iName); iFileNum++; } } } if(iDesArray->Count() > 0) { iCurrentPath = aFilePath; /* iMainEngine.WriteLog16(aFilePath); iCurrentPath.Zero(); iCurrentPath.Append(aFilePath); iMainEngine.WriteLog16(iCurrentPath); iMainEngine.WriteLog16(aFilePath); */ InitListBox(); } } iMainEngine.WriteLog16(_L("CFileBrowser::InitDirList End")); } void CFileBrowser::InitListBox() { delete iListBox; iListBox = NULL; iListBox = iMainEngine.ControlFactory().CreateListBox(iListBoxRect); iListBox->SetTextColor(KRgbBlack,KRgbBlack); iMainEngine.CurWindow()->RemoveControl(iListBox); for (TInt i = 0 ; i < iDesArray->Count() ; i++) { const CFbsBitmap* icon = NULL; const CFbsBitmap* iconMask = NULL; const TDesC& fileName = (*iDesArray)[i]; if(i < iFolderNum) { icon = iMainEngine.GetBitmapFactory().GetFileTypeIcon(EFileTypeFile); iconMask = iMainEngine.GetBitmapFactory().GetFileTypeIconMask(EFileTypeFile); } else { const CFbsBitmap* iconBitmap = NULL; const CFbsBitmap* iconBitmapMask = NULL; iMainEngine.GetFileTypeIcon(fileName,iconBitmap,iconBitmapMask); } iListBox->AppendL(CNormalListBoxItem::NewL(fileName,icon,iconMask)); } iListBox->Layout(); iDesArray->Reset(); } HBufC* CFileBrowser::GetFileOrPathLC() const { ASSERT(iListBox); iMainEngine.WriteLog16(iCurrentPath); CNormalListBoxItem& curListItem = (CNormalListBoxItem&)(iListBox->CurItem()); //const TDesC& curFileName = curListItem.GetText();2版本手机长度有问题 TFileName curFileName; curFileName.Copy(curListItem.GetText()); iMainEngine.WriteLog16(curFileName); TInt length = iCurrentPath.Length() + curFileName.Length() + KBackslash.iTypeLength; HBufC* tempFilePath = HBufC::NewLC(length); tempFilePath->Des().Append(iCurrentPath); if(curFileName.Right(1).Compare(_L(":"))!=0||iCurrentPath.Length()==0) tempFilePath->Des().Append(curFileName); if(tempFilePath->Right(1).Compare(_L("\\"))!=0) tempFilePath->Des().Append(KBackslash); iMainEngine.WriteLog16(*tempFilePath); TBool curIsFolder = EFalse; TInt err = BaflUtils::IsFolder(iFs,*tempFilePath,curIsFolder); if(KErrNone == err) { if(curIsFolder) { if(tempFilePath->Right(1).Compare(_L("\\"))!=0) tempFilePath->Des().Append(KBackslash); ASSERT(BaflUtils::PathExists(iFs,*tempFilePath)); } else { ASSERT(BaflUtils::FileExists(iFs,*tempFilePath)); } } else { switch(err) { case KErrNotFound: //根目录 tempFilePath->Des().Append(KBackslash); iMainEngine.WriteLog16(*tempFilePath); ASSERT(BaflUtils::PathExists(iFs,*tempFilePath)); break; default: iMainEngine.WriteLog16(*tempFilePath); iMainEngine.WriteLog16(_L("CFileBrowser::GetFileOrPathLC err = %d"),err); ASSERT(EFalse); break; } } return tempFilePath; } void CFileBrowser::InitBitmaps() { iSaveAsBmp = iMainEngine.GetBitmapFactory().GetBitmap(EMbmCocobmpSaveas); const CScreenLayout& screenLayout = iMainEngine.ScreenLayout(); iBmpSize = iSaveAsBmp->SizeInPixels(); //上下左右居中 TRect clientRect = screenLayout.GetClientRect(); iStartPoint = clientRect.iTl; iStartPoint.iX += (clientRect.Width() - iBmpSize.iWidth)/2; iStartPoint.iY += (clientRect.Height() - iBmpSize.iHeight)/2; iLineHeight = screenLayout.LineHeight(); TPoint listPoint; screenLayout.GetSaveAsPos(iTextPoint,listPoint); iListBoxRect = iSaveAsBmp->SizeInPixels(); iListBoxRect.Move(iStartPoint); iListBoxRect.iTl.iY += listPoint.iY; TInt innerMargin = screenLayout.InnerMargin(); iListBoxRect.Shrink(innerMargin,innerMargin); } //-------------------------------------------------------------------------- //ParseParentPath,该方法的实现比较曲折,不直观 //-------------------------------------------------------------------------- TFileName CFileBrowser::ParseParentPath(const TDesC& aPath) const { //return UtilityTools::ParseParentPath(aPath); ASSERT(BaflUtils::PathExists(iFs,aPath)); HBufC* tempPath = HBufC::NewLC(aPath.Length() - 1); tempPath->Des().Append(aPath.Left(aPath.Length() - 1)); //去掉最后一个反斜杠 TParse parse; parse.Set(*tempPath,NULL,NULL); const TDesC& curFolder = parse.NameAndExt(); TFileName newPath; TInt length = tempPath->Length() - curFolder.Length(); newPath.Append(tempPath->Left(length)); //去掉当前文件夹名称 CleanupStack::PopAndDestroy(); return newPath; }
[ "sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f" ]
[ [ [ 1, 510 ] ] ]
b0d5d5bce92aa194998696ecffdbe7191e2fa1e2
61352a7371397524fe7dcfab838de40d502c3c9a
/client/Headers/CorbaClasses/IRemoteObserverObject.h
e5cc8bd208a0560f1552bba38b72d9b7276b3668
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,651
h
#ifndef IREMOTEOBSERVEROBJECT_H #define IREMOTEOBSERVEROBJECT_H #include "RemoteObserverData.h" #include "IRemoteObserver.h" #include <iostream> #include <vector> #include <log4cxx/logger.h> #include <log4cxx/level.h> /// /// @author Mateusz Kołodziejczyk /// @date 10.01.2009 /// /// @brief Interfejs ktory implementuja klasy namistek udostapnianych przez klienta /// /// Rejestruje i wyrejestrowuje obiekty obserwatorw \; posiada metode Notify ktora /// wywoluje metode Refresh na kazdym obserwatorze w koleksji obserwatorow (ktora /// takze znajduje sie w tej klasie) /// class IRemoteObserverObject { private: /// /// kolekcji obserwatorow, czyli obiektow klasy IRemoteObserver /// std::vector<IRemoteObserver *> RemoteObserversList; // logger log4cxx::LoggerPtr logger; public: /// /// konstruktor /// IRemoteObserverObject() { logger = log4cxx::LoggerPtr(log4cxx::Logger::getLogger("IRemoteObjects")); logger->setLevel(LOGLEVEL); } /// /// destruktor /// virtual ~IRemoteObserverObject() { } /// /// wyrejestrowuje danego obserwatora /// virtual int UnregisterObserv(); /// /// @param [in] observer obiekt obserwatora /// /// rejestruje obserwatora observer /// virtual int RegisterObserv(IRemoteObserver * observer); /// /// @param [in] objectData dane /// /// wywoluje metode Refresh na kazdym obserwatorze z kolekcji RemoteObserversList /// virtual void Notify(RemoteObserverData objectData); }; //end class IRemoteObserverObject #endif
[ "coutoPL@c118a9a8-d993-11dd-9042-6d746b85d38b", "w.grzeskowiak@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 42 ], [ 44, 75 ] ], [ [ 43, 43 ] ] ]
d44898e1ef23aed3b1610109ef852d1a61243677
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/FileSystem/Node.h
253f06b4c8f471230ea46ad2b27503068d8a1a48
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
703
h
#ifndef __FILESYSTEM_NODE_H__ #define __FILESYSTEM_NODE_H__ #include <boost/intrusive_ptr.hpp> #include "../Utility/referenced.hpp" namespace slon { namespace filesystem { class Node : public Referenced { public: enum TYPE { FILE, DIRECTORY }; public: virtual TYPE getType() const = 0; virtual const char* getPath() const = 0; virtual const char* getName() const = 0; /** Dump node content to the system */ virtual void flush() = 0; virtual ~Node() {} }; typedef boost::intrusive_ptr<Node> node_ptr; typedef boost::intrusive_ptr<const Node> const_node_ptr; } // namespace filesystem } // namespace slon #endif // __FILESYSTEM_NODE_H__
[ "devnull@localhost" ]
[ [ [ 1, 39 ] ] ]
02a323e88d9a1b7b963aa14f861f99e1eabe9b90
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/CtrlEx/TabItem_Cake.h
381e54a6eeafe2c52b0b39b600a278708f6f0820
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
267
h
#pragma once #include "CxImage\xImage.h" #include "TabItem_Normal.h" class CTabItem_Cake : public CTabItem_Normal { public: CTabItem_Cake(void); ~CTabItem_Cake(void); virtual int GetDesireLength(void){return 36;} virtual void Paint(CDC* pDC); };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 14 ] ] ]
81e3dfcc5a4564934b81f002205b29efff3afb05
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/core/src/SaveGameFileWriter.cpp
7f87044288616f60f90fb162724e920efbddc891
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,956
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" #include "SaveGameFileWriter.h" #include "SaveGameManager.h" #include <XmlProcessor.h> #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMAttr.hpp> #include <xercesc/dom/DOMElement.hpp> #include <Properties.h> #ifdef __APPLE__ # include <CEGUI/CEGUIPropertyHelper.h> #else # include <CEGUIPropertyHelper.h> #endif #include <CoreSubsystem.h> #include <ContentModule.h> #include <TimeSource.h> #include <ctime> using namespace XERCES_CPP_NAMESPACE; using namespace Ogre; namespace rl { void SaveGameFileWriter::buildSaveGameFile(rl::SaveGameFile *file) { initializeXml(); XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); mImplementation = DOMImplementationRegistry::getDOMImplementation(tempStr); mTarget = file->getFormatTarget(); mWriter = static_cast<DOMImplementationLS*>(mImplementation)->createDOMWriter(); mDocument = static_cast<DOMImplementation*>(mImplementation)->createDocument(0, XMLString::transcode("SaveGameFile"), 0); if (mWriter->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true)) mWriter->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (mWriter->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) mWriter->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true); mDocument->setNodeValue(XMLString::transcode("SaveGameFile")); //Set name of document root node setAttributeValueAsString(mDocument->getDocumentElement(), "SaveGameFormatVersion", "0.8"); setAttributeValueAsInteger(mDocument->getDocumentElement(), "Engineversion", CoreSubsystem::getSingleton().getEngineBuildNumber()); DOMElement* header = appendChildElement(mDocument, mDocument->getDocumentElement(), "header"); PropertyRecordPtr headerSet = file->getAllProperties(); for (PropertyRecord::PropertyRecordMap::const_iterator it_header = headerSet->begin(); it_header != headerSet->end(); it_header++) { this->processProperty(header, PropertyEntry(it_header->first.c_str(), it_header->second)); } mWriter->writeNode(mTarget, *mDocument); mWriter->release(); delete mDocument; shutdownXml(); } //void SaveGameFileWriter::buildSaveGameFile(SaveGameFile *file, const SaveGameDataOrderMap &map) //{ // //@toto: build // initializeXml(); // XMLCh tempStr[100]; // XMLString::transcode("LS", tempStr, 99); // mImplementation = DOMImplementationRegistry::getDOMImplementation(tempStr); // mWriter = static_cast<DOMImplementationLS*>(mImplementation)->createDOMWriter(); // mTarget = file->getFormatTarget(); // mDocument = static_cast<DOMImplementation*>(mImplementation)->createDocument(0, XMLString::transcode("SaveGameFile"), 0); // if (mWriter->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true)) // mWriter->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true); // if (mWriter->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) // mWriter->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true); // mDocument->setNodeValue(XMLString::transcode("SaveGameFile")); //Set name of document root node // //Write SaveGameVersion // setAttributeValueAsString(mDocument->getDocumentElement(), "SaveGameFormatVersion", "0.5"); // setAttributeValueAsInteger(mDocument->getDocumentElement(), "Engineversion", CoreSubsystem::getSingleton().getEngineBuildNumber()); // //Write modul of save game // DOMElement* header = appendChildElement(mDocument, mDocument->getDocumentElement(), "header"); // // PropertyRecordPtr headerSet = file->getAllProperties(); // for (PropertyRecord::PropertyRecordMap::const_iterator it_header = headerSet->begin(); it_header != headerSet->end(); it_header++) // { // this->processProperty(header, PropertyEntry(it_header->first.c_str(), it_header->second)); // } // ////Write globals // //DOMElement* globals = appendChildElement(mDocument, mDocument->getDocumentElement(), "globals"); // //DOMElement* gameTime = appendChildElement(mDocument, globals, "gametime"); // //TimeSource* gameTimeSource = TimeSourceManager::getSingleton().getTimeSource(TimeSource::GAMETIME); // //setAttributeValueAsInteger(gameTime, "milliseconds", gameTimeSource->getClock()); // for(SaveGameDataOrderMap::const_iterator data_iter = map.begin(); data_iter != map.end(); data_iter++) // { // data_iter->second->writeData(this); // } // mWriter->writeNode(mTarget, *mDocument); // mWriter->release(); // delete mDocument; // delete mTarget; // shutdownXml(); //} //void SaveGameFileWriter::writeEachProperty(SaveGameData* data, const rl::PropertyMap &map) //{ // DOMElement* saveElem = appendChildElement(getDocument(), getDocument()->getDocumentElement(), data->getXmlNodeIdentifier().c_str()); // XmlPropertyWriter::writeEachPropertyToElem(saveElem, map); //} }
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 147 ] ] ]
fcc3c08ef8e6f4e234b80a9ae32f994216668741
7de2602528b71826dd1ac1c164129e3cb5b2f8ec
/ofxOsc/oscpack/ip/posix/UdpSocket.cpp
cbc82bb1cfbcdc136d3b37488554fee79e524191
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
010175/switchboard
7214e369290e016f31ee7cd76af390bd44ff543b
5fe201c395e71f4c61c501cb9040c442dbc9c736
refs/heads/master
2021-01-20T10:46:07.677384
2011-09-21T13:33:16
2011-09-21T13:33:16
1,266,372
1
0
null
null
null
null
UTF-8
C++
false
false
15,782
cpp
/* oscpack -- Open Sound Control packet manipulation library http://www.audiomulch.com/~rossb/oscpack Copyright (c) 2004-2005 Ross Bencina <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../UdpSocket.h" #include <vector> #include <algorithm> #include <stdexcept> #include <assert.h> #include <signal.h> #include <math.h> #include <errno.h> #include <string.h> // for memset #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> // for sockaddr_in #include "../PacketListener.h" #include "../TimerListener.h" #if defined(__APPLE__) && !defined(_SOCKLEN_T) // pre system 10.3 didn have socklen_t typedef ssize_t socklen_t; #endif static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint ) { memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); sockAddr.sin_family = AF_INET; sockAddr.sin_addr.s_addr = (endpoint.address == IpEndpointName::ANY_ADDRESS) ? INADDR_ANY : htonl( endpoint.address ); sockAddr.sin_port = (endpoint.port == IpEndpointName::ANY_PORT) ? 0 : htons( endpoint.port ); } static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr ) { return IpEndpointName( (sockAddr.sin_addr.s_addr == INADDR_ANY) ? IpEndpointName::ANY_ADDRESS : ntohl( sockAddr.sin_addr.s_addr ), (sockAddr.sin_port == 0) ? IpEndpointName::ANY_PORT : ntohs( sockAddr.sin_port ) ); } class UdpSocket::Implementation{ bool isBound_; bool isConnected_; int socket_; struct sockaddr_in connectedAddr_; struct sockaddr_in sendToAddr_; public: Implementation() : isBound_( false ) , isConnected_( false ) , socket_( -1 ) { if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == -1 ){ throw std::runtime_error("unable to create udp socket\n"); } int on=1; setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, (char*)&on, sizeof(on)); memset( &sendToAddr_, 0, sizeof(sendToAddr_) ); sendToAddr_.sin_family = AF_INET; } ~Implementation() { if (socket_ != -1) close(socket_); } IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const { assert( isBound_ ); // first connect the socket to the remote server struct sockaddr_in connectSockAddr; SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint ); if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) { throw std::runtime_error("unable to connect udp socket\n"); } // get the address struct sockaddr_in sockAddr; memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); socklen_t length = sizeof(sockAddr); if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) { throw std::runtime_error("unable to getsockname\n"); } if( isConnected_ ){ // reconnect to the connected address if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { throw std::runtime_error("unable to connect udp socket\n"); } }else{ // unconnect from the remote address struct sockaddr_in unconnectSockAddr; memset( (char *)&unconnectSockAddr, 0, sizeof(unconnectSockAddr ) ); unconnectSockAddr.sin_family = AF_UNSPEC; // address fields are zero int connectResult = connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr)); if ( connectResult < 0 && errno != EAFNOSUPPORT ) { throw std::runtime_error("unable to un-connect udp socket\n"); } } return IpEndpointNameFromSockaddr( sockAddr ); } void Connect( const IpEndpointName& remoteEndpoint ) { SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint ); if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { throw std::runtime_error("unable to connect udp socket\n"); } isConnected_ = true; } void Send( const char *data, int size ) { assert( isConnected_ ); send( socket_, data, size, 0 ); } void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) { sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address ); sendToAddr_.sin_port = htons( remoteEndpoint.port ); sendto( socket_, data, size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) ); } void Bind( const IpEndpointName& localEndpoint ) { struct sockaddr_in bindSockAddr; SockaddrFromIpEndpointName( bindSockAddr, localEndpoint ); if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) { throw std::runtime_error("unable to bind udp socket\n"); } isBound_ = true; } bool IsBound() const { return isBound_; } int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) { assert( isBound_ ); struct sockaddr_in fromAddr; socklen_t fromAddrLen = sizeof(fromAddr); int result = recvfrom(socket_, data, size, 0, (struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen); if( result < 0 ) return 0; remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr); remoteEndpoint.port = ntohs(fromAddr.sin_port); return result; } int Socket() { return socket_; } }; UdpSocket::UdpSocket() { impl_ = new Implementation(); } UdpSocket::~UdpSocket() { delete impl_; } IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const { return impl_->LocalEndpointFor( remoteEndpoint ); } void UdpSocket::Connect( const IpEndpointName& remoteEndpoint ) { impl_->Connect( remoteEndpoint ); } void UdpSocket::Send( const char *data, int size ) { impl_->Send( data, size ); } void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) { impl_->SendTo( remoteEndpoint, data, size ); } void UdpSocket::Bind( const IpEndpointName& localEndpoint ) { impl_->Bind( localEndpoint ); } bool UdpSocket::IsBound() const { return impl_->IsBound(); } int UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) { return impl_->ReceiveFrom( remoteEndpoint, data, size ); } struct AttachedTimerListener{ AttachedTimerListener( int id, int p, TimerListener *tl ) : initialDelayMs( id ) , periodMs( p ) , listener( tl ) {} int initialDelayMs; int periodMs; TimerListener *listener; }; static bool CompareScheduledTimerCalls( const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs ) { return lhs.first < rhs.first; } SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0; extern "C" /*static*/ void InterruptSignalHandler( int ); /*static*/ void InterruptSignalHandler( int ) { multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak(); signal( SIGINT, SIG_DFL ); } class SocketReceiveMultiplexer::Implementation{ std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_; std::vector< AttachedTimerListener > timerListeners_; volatile bool break_; int breakPipe_[2]; // [0] is the reader descriptor and [1] the writer double GetCurrentTimeMs() const { struct timeval t; gettimeofday( &t, 0 ); return ((double)t.tv_sec*1000.) + ((double)t.tv_usec / 1000.); } public: Implementation() { if( pipe(breakPipe_) != 0 ) throw std::runtime_error( "creation of asynchronous break pipes failed\n" ); } ~Implementation() { close( breakPipe_[0] ); close( breakPipe_[1] ); } void AttachSocketListener( UdpSocket *socket, PacketListener *listener ) { assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() ); // we don't check that the same socket has been added multiple times, even though this is an error socketListeners_.push_back( std::make_pair( listener, socket ) ); } void DetachSocketListener( UdpSocket *socket, PacketListener *listener ) { std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ); assert( i != socketListeners_.end() ); socketListeners_.erase( i ); } void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) { timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) ); } void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) { timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) ); } void DetachPeriodicTimerListener( TimerListener *listener ) { std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); while( i != timerListeners_.end() ){ if( i->listener == listener ) break; ++i; } assert( i != timerListeners_.end() ); timerListeners_.erase( i ); } void Run() { break_ = false; // configure the master fd_set for select() fd_set masterfds, tempfds; FD_ZERO( &masterfds ); FD_ZERO( &tempfds ); // in addition to listening to the inbound sockets we // also listen to the asynchronous break pipe, so that AsynchronousBreak() // can break us out of select() from another thread. FD_SET( breakPipe_[0], &masterfds ); int fdmax = breakPipe_[0]; for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); i != socketListeners_.end(); ++i ){ if( fdmax < i->second->impl_->Socket() ) fdmax = i->second->impl_->Socket(); FD_SET( i->second->impl_->Socket(), &masterfds ); } // configure the timer queue double currentTimeMs = GetCurrentTimeMs(); // expiry time ms, listener std::vector< std::pair< double, AttachedTimerListener > > timerQueue_; for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); i != timerListeners_.end(); ++i ) timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) ); std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); const int MAX_BUFFER_SIZE = 4098; char *data = new char[ MAX_BUFFER_SIZE ]; IpEndpointName remoteEndpoint; struct timeval timeout; while( !break_ ){ tempfds = masterfds; struct timeval *timeoutPtr = 0; if( !timerQueue_.empty() ){ double timeoutMs = timerQueue_.front().first - GetCurrentTimeMs(); if( timeoutMs < 0 ) timeoutMs = 0; // 1000000 microseconds in a second timeout.tv_sec = (long)(timeoutMs * .001); timeout.tv_usec = (long)((timeoutMs - (timeout.tv_sec * 1000)) * 1000); timeoutPtr = &timeout; } if( select( fdmax + 1, &tempfds, 0, 0, timeoutPtr ) < 0 && errno != EINTR ){ if (!break_) throw std::runtime_error("select failed\n"); else break; } if ( FD_ISSET( breakPipe_[0], &tempfds ) ){ // clear pending data from the asynchronous break pipe char c; ssize_t ret; ret = read( breakPipe_[0], &c, 1 ); } if( break_ ) break; for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); i != socketListeners_.end(); ++i ){ if( FD_ISSET( i->second->impl_->Socket(), &tempfds ) ){ int size = i->second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE ); if( size > 0 ){ i->first->ProcessPacket( data, size, remoteEndpoint ); if( break_ ) break; } } } // execute any expired timers currentTimeMs = GetCurrentTimeMs(); bool resort = false; for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin(); i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){ i->second.listener->TimerExpired(); if( break_ ) break; i->first += i->second.periodMs; resort = true; } if( resort ) std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); } delete [] data; } void Break() { break_ = true; } void AsynchronousBreak() { break_ = true; // Send a termination message to the asynchronous break pipe, so select() will return ssize_t ret; ret = write( breakPipe_[1], "!", 1 ); } }; SocketReceiveMultiplexer::SocketReceiveMultiplexer() { impl_ = new Implementation(); } SocketReceiveMultiplexer::~SocketReceiveMultiplexer() { delete impl_; } void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener ) { impl_->AttachSocketListener( socket, listener ); } void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener ) { impl_->DetachSocketListener( socket, listener ); } void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) { impl_->AttachPeriodicTimerListener( periodMilliseconds, listener ); } void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) { impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ); } void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener ) { impl_->DetachPeriodicTimerListener( listener ); } void SocketReceiveMultiplexer::Run() { impl_->Run(); } void SocketReceiveMultiplexer::RunUntilSigInt() { assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */ multiplexerInstanceToAbortWithSigInt_ = this; signal( SIGINT, InterruptSignalHandler ); impl_->Run(); signal( SIGINT, SIG_DFL ); multiplexerInstanceToAbortWithSigInt_ = 0; } void SocketReceiveMultiplexer::Break() { impl_->Break(); } void SocketReceiveMultiplexer::AsynchronousBreak() { impl_->AsynchronousBreak(); }
[ [ [ 1, 551 ] ] ]
3fc136448a44d7ee05f64e2f61e5c048cdad0422
880e5a47c23523c8e5ba1602144ea1c48c8c8f9a
/CommonLibSrc/Streams/CInputOutputStream.hpp
ad4abb38091e9e9e8990965ad30cd28b39a7a275
[]
no_license
kfazi/Engine
050cb76826d5bb55595ecdce39df8ffb2d5547f8
0cedfb3e1a9a80fd49679142be33e17186322290
refs/heads/master
2020-05-20T10:02:29.050190
2010-02-11T17:45:42
2010-02-11T17:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
333
hpp
#ifndef COMMON_INPUT_OUTPUT_STREAM_HPP #define COMMON_INPUT_OUTPUT_STREAM_HPP #include "../Internal.hpp" #include "CInputStream.hpp" #include "COutputStream.hpp" namespace Common { class CInputOutputStream: public CInputStream, public COutputStream { }; } #endif /* COMMON_INPUT_OUTPUT_STREAM_HPP */ /* EOF */
[ [ [ 1, 19 ] ] ]
e6dc3d68dbfdb9d566b644b1c13fabbf5f610e51
b6a6fa4324540b94fb84ee68de3021a66f5efe43
/SCS/LIB/Image.h
f55906b77aca8de55949fd2e5dcddbeb18adb0b9
[]
no_license
southor/duplo-scs
dbb54061704f8a2ec0514ad7d204178bfb5a290e
403cc209039484b469d602b6752f66b9e7c811de
refs/heads/master
2021-01-20T10:41:22.702098
2010-02-25T16:44:39
2010-02-25T16:44:39
34,623,992
0
0
null
null
null
null
UTF-8
C++
false
false
8,629
h
#include "Base.h" #ifndef _IMAGE_ #define _IMAGE_ class Image { protected: int w; int h; double *pixels1; double *pixels2; double *pixels3; int PixelPos(int x, int y, int w); //void PutPixels(TSG_Pixel* source, TSG_Pixel* target, int length); //void CopyPixels(TSG_Pixel* source, TSG_Pixel* target, int length); //void CopyPixelsBW(TSG_Pixel* source, TSG_Pixel* target, int length); public: //TSG_Image(int w, int h, void* pixels = NULL); //TSG_Image(const TSG_Image* Image); //TSG_Image(); // NULL-image Image(char* filename); ~Image(); int Width(); int Height(); bool Inside(int x, int y); int Size(); //void DrawToImageQ(const int &srcx, const int &srcy, const int &srcw, const int &srch, // TSG_Image* trgimage, const int &trgx, const int &trgy); //void DrawToImage(TSG_Image* trgimage, const int &trgx, const int &trgy); //void DrawToImageQ(TSG_Image* trgimage, const int &trgx, const int &trgy); //void Scroll(int x, int y); //void Clear(char r, char g, char b, char t); double getValue1(int x, int y); double getValue2(int x, int y); double getValue3(int x, int y); }; // METHODS // ----------------- protected methods -------------------- inline int Image::PixelPos(int x, int y, int w) { return (x+w*y); } /* void TSG_Image::PutPixels(TSG_Pixel* source, TSG_Pixel* target, int length) { for(int i=0;i<length;i++) { (target+i)->Get(*(source+i)); } } void TSG_Image::CopyPixels(TSG_Pixel* source, TSG_Pixel* target, int length) { for(int i=0;i<length;i++) { *(target+i) = *(source+i); } } void TSG_Image::CopyPixelsBW(TSG_Pixel* source, TSG_Pixel* target, int length) { for(int i=length-1;i>=0;i=i-1) { *(target+i) = *(source+i); } } */ // ----------------- constructor methods -------------------- /* TSG_Image::TSG_Image(int w, int h, void* pixels) : TSG_Rect(w, h) { this->pixels = (TSG_Pixel*)pixels; if (pixels == NULL) this->pixels = new TSG_Pixel[w*h]; } TSG_Image::TSG_Image(const TSG_Image* Image) : TSG_Rect(Image->w, Image->h) { this->pixels = new TSG_Pixel[w*h]; CopyPixels(Image->pixels, this->pixels, w*h); } TSG_Image::TSG_Image() : TSG_Rect(0, 0) { this->pixels = NULL; } */ // LoadBmp Image::Image(char* filename) { long in; int i; std::ifstream ImageFile; if(filename != NULL) ImageFile.open((const char*)filename, std::ios::binary); //ifstream ImageFile((const char*)filename,ios::binary); //double* pixels = NULL; for(i=0;i<18;i++) { ImageFile.read((char*)&in,sizeof(char)); } // read width ImageFile.read((char*)&w,sizeof(int)); // read height ImageFile.read((char*)&h,sizeof(int)); for(i=0;i<28;i++) { ImageFile.read((char*)&in,sizeof(char)); } pixels1 = new double[w*h]; pixels2 = new double[w*h]; pixels3 = new double[w*h]; unsigned char v1, v2, v3; //ImageFile.read((char*)&v1,sizeof(char)); //ImageFile.read((char*)&v1,sizeof(char)); //ImageFile.read((char*)&v1,sizeof(char)); int x; for(int y=0;y<h;y=y+1) { //ImageFile.read((char*)&v1,sizeof(char)); //ImageFile.read((char*)&v1,sizeof(char)); for(x=0;x<w;x=x+1) { i = (y*w+x); // In a bitmap file: BGR // Reading to memory as: RGB ImageFile.read((char*)&v2,sizeof(char)); ImageFile.read((char*)&v3,sizeof(char)); ImageFile.read((char*)&v1,sizeof(char)); //cout << (unsigned int)v1 << " " << (unsigned int)v2 << " " << (unsigned int)v3 << endl; *(pixels1+i) = ((double)v1/256.0); *(pixels2+i) = ((double)v2/256.0); *(pixels3+i) = ((double)v3/256.0); //cout << *(pixels+i) << " "; //ImageFile.read((char*)(pixels+i+3),sizeof(char)); //if ((*(pixels+i+0) == 255) && (*(pixels+i+1) == 255) && (*(pixels+i+2) == 255)) *(pixels+i+3) = 255; //else *(pixels+i+3) = 0; } //ImageFile.read((char*)&v1,sizeof(char)); //ImageFile.read((char*)&v2,sizeof(char)); //ImageFile.read((char*)&v3,sizeof(char)); } ImageFile.close(); //this->pixels = (TSG_Pixel*)pixels; } // destructor method Image::~Image() { delete pixels1; delete pixels2; delete pixels3; } // --------------------- Public methods ------------------------------ inline int Image::Width() { return w; } inline int Image::Height() { return h; } inline bool Image::Inside(int x, int y) { return (Between(x,0,w) && Between(y,0,h)); } inline int Image::Size() { return w*h; } /* void TSG_Image::DrawToImageQ(const int &srcx, const int &srcy, const int &srcw, const int &srch, TSG_Image* trgimage, const int &trgx, const int &trgy) // can only handle correct areas { for(int row=0;row<srch;row++) { PutPixels(this->pixels+PixelPos(srcx,srcy+row,this->w),trgimage->pixels+PixelPos(trgx,trgy+row,trgimage->w),srcw); } } void TSG_Image::DrawToImage(TSG_Image* trgimage, const int &trgx, const int &trgy) { bool draw = true; // boolean to store if draw should be done or not int srcx, srcw; // sourcex (the xposition in this image where to draw from) int srcy, srch; // ----------- Check X -------------- if (trgx < 0) //Left corner is left of inside { if (trgx+this->w < 0) //right corner is left of inside { draw = false; } else if (trgx+this->w > trgimage->w) //Right corner is right of inside { srcx = trgx*(-1); srcw = trgimage->w; } else // Right corner is inside { srcx = trgx*(-1); srcw = this->w-srcx; } } else if (trgx > trgimage->w) // Left corner is right of inside { draw = false; } else // Left corner is inside { if (trgx+this->w > trgimage->w) // right corner is right of inside { srcx = 0; srcw = trgimage->w-trgx; } else //right corner is inside { srcx = 0; srcw = this->w; } } // ---------- Check Y --------------- if (trgy < 0) //Bottom is below { if (trgy+this->h < 0) //top is below { draw = false; } else if (trgy+this->h > trgimage->h) //top is above { srcy = trgy*(-1); srch = trgimage->h; } else // top is inside { srcy = trgy*(-1); srcw = this->h-srcy; } } else if (trgy > trgimage->h) // bottom is above { draw = false; } else // bottom is inside { if (trgy+this->h > trgimage->h) // top is above { srcy = 0; srch = trgimage->h-trgy; } else //top is inside { srcy = 0; srch = this->h; } } if (draw) DrawToImageQ(srcx,srcy,srcw,srch,trgimage,trgx+srcx,trgy+srcy); } void TSG_Image::DrawToImageQ(TSG_Image* trgimage, const int &trgx, const int &trgy) { for(int row=0;row<this->h;row++) { PutPixels(this->pixels+PixelPos(0,row,this->w),trgimage->pixels+PixelPos(trgx,trgy+row,trgimage->w),this->w); } } void TSG_Image::Scroll(int x, int y) { int srcx, srcw; int srcy, srch; int trgx, trgy; int row; if (x<0) { //scroll left srcx = x*(-1); srcw = this->w-srcx; trgx = 0; if (y<0) { //scroll down srcy = y*(-1); srch = this->h-srcy; trgy = 0; for(row=0;row<srch;row++) { CopyPixels(this->pixels+PixelPos(srcx,srcy+row,this->w),this->pixels+PixelPos(trgx,trgy+row,this->w),srcw); } } else { //scroll up srcy = 0; srch = this->h-y; trgy = y; for(row=srch-1;row>=0;row=row-1) { CopyPixels(this->pixels+PixelPos(srcx,srcy+row,this->w),this->pixels+PixelPos(trgx,trgy+row,this->w),srcw); } } } else { //scroll right srcx = 0; srcw = this->w-x; trgx = x; if (y<0) { //scroll down srcy = y*(-1); srch = this->h-srcy; trgy = 0; for(row=0;row<srch;row++) { CopyPixelsBW(this->pixels+PixelPos(srcx,srcy+row,this->w),this->pixels+PixelPos(trgx,trgy+row,this->w),srcw); } } else { //scroll up srcy = 0; srch = this->h-y; trgy = y; for(row=srch-1;row>=0;row=row-1) { CopyPixelsBW(this->pixels+PixelPos(srcx,srcy+row,this->w),this->pixels+PixelPos(trgx,trgy+row,this->w),srcw); } } } } void TSG_Image::Clear(char r, char g, char b, char t) { int size = Size(); for (int i=0;i<size;i++) { (pixels+i)->red = r; (pixels+i+1)->blue = g; (pixels+i+2)->green = b; (pixels+i+3)->transp = t; } } */ inline double Image::getValue1(int x, int y) { return *(pixels1+PixelPos(x,y,w)); } inline double Image::getValue2(int x, int y) { return *(pixels2+PixelPos(x,y,w)); } inline double Image::getValue3(int x, int y) { return *(pixels3+PixelPos(x,y,w)); } #endif
[ "t.soderberg8@2b3d9118-3c8b-11de-9b50-8bb2048eb44c" ]
[ [ [ 1, 396 ] ] ]
5ddc2e8f889a2a927e43e10e45a065872d6e9841
699746171f662df8923b8894e5178126285beb2d
/Software/C++/applis/tablette-cpp/caveOsgViewer/VRPNClientManager.h
38c3db5ac7897080c17e730bfab047135eae97f6
[]
no_license
iurnah/tesis
4793b539bec676255e0f880dc6524b1e70b78394
652d6096e53a56123408d325921981b0ff6c39fd
refs/heads/master
2021-01-24T19:51:48.438405
2011-06-27T11:44:23
2011-06-27T11:44:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
h
#pragma once #include <vrpn_Tracker.h> #include <vrpn_Button.h> #include <vrpn_Analog.h> #include <vrpn_Text.h> #include <osg/vec3> #include <osg/quat> #include <map> #include <string> #include "Annotation.h" class CVRPNClientManager { public: struct Tracker { int id; osg::Vec3 crtPos; osg::Quat crtQuat; osg::Vec3 firstPos; osg::Quat firstQuat; }; CVRPNClientManager(void); ~CVRPNClientManager(void); void init(const std::string& vrpnName); void run(); void setVerbose(bool verbose); bool isVerbose() const; // Tracker handling void addOrUpdateTracker(int id, const osg::Vec3& pos, const osg::Quat& q); void removeAllTracker(); int getTrackerCount() const; Tracker* getTracker(int i) const; Tracker* getTrackerFromId(int id) const; // Button handling void addOrUpdateButton(int id, bool value); void removeAllButton(); int getButtonCount() const; bool getButton(int i) const; bool getButtonFromId(int id, bool& status) const; // Analog channels handling void updateAnalog(const vrpn_ANALOGCB& t); void removeAllAnalog(); int getAnalogCount() const; double getAnalog(int i) const; double getAnalogFromId(int id) const; //Manage annotations bool copyLastAnnotation(Annotation* annotation); bool copyGoToAnnotation(Annotation* annotation); void CVRPNClientManager::updateAnnotation(Annotation* annotation); void setNewGoToAnnotationCommand(); bool theresNewAnnotation(); bool theresNewGoToAnnotationCommand(); void printText(); std::vector<Annotation> annotations; private: struct cprInt { bool operator()(int s1, int s2) const { return s1 < s2; } }; vrpn_Tracker_Remote* m_trackerRemote; vrpn_Analog_Remote* m_analogRemote; vrpn_Button_Remote* m_buttonRemote; vrpn_Text_Receiver* m_textReceiver; std::map<int, Tracker*, cprInt> m_vrpnTrackerCallbackMap; std::map<int, bool> m_vrpnButtonCallbackMap; vrpn_ANALOGCB m_vrpnAnalogCallbackMap; struct Annotation lastAnnotation; bool newAnnotation; bool goToAnnotation; bool m_verbose; }; // callback void VRPN_CALLBACK handle_tracker(void* userData, const vrpn_TRACKERCB t);
[ [ [ 1, 90 ] ] ]
f8ce4df5d89afb303444ea0412b23c9360d8311b
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/include/mp4util.h
518e5297640046994403bf57a9cc7819364a7017
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
7,494
h
/* * The contents of this file are subject to the Mozilla Public * 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2001. All Rights Reserved. * * Contributor(s): * Dave Mackie [email protected] */ #ifndef __MP4_UTIL_INCLUDED__ #define __MP4_UTIL_INCLUDED__ #include <assert.h> #define vsnprintf(a, b, c, d) 0 #define errno 0 #ifndef ASSERT #ifdef NDEBUG #define ASSERT(expr) #else #define ASSERT(expr) \ if (!(expr)) { \ fflush(stdout); \ assert((expr)); \ } #endif #endif #ifdef NDEBUG #define WARNING(expr) #else #define WARNING(expr) \ if (expr) { \ fflush(stdout); \ fprintf(stderr, "Warning (%s) in %s at line %u\n", \ __STRING(expr), __FILE__, __LINE__); \ } #endif #define VERBOSE(exprverbosity, verbosity, expr) \ if (((exprverbosity) & (verbosity)) == (exprverbosity)) { expr; } #define VERBOSE_ERROR(verbosity, expr) \ VERBOSE(MP4_DETAILS_ERROR, verbosity, expr) #define VERBOSE_WARNING(verbosity, expr) \ VERBOSE(MP4_DETAILS_WARNING, verbosity, expr) #define VERBOSE_READ(verbosity, expr) \ VERBOSE(MP4_DETAILS_READ, verbosity, expr) #define VERBOSE_READ_TABLE(verbosity, expr) \ VERBOSE((MP4_DETAILS_READ | MP4_DETAILS_TABLE), verbosity, expr) #define VERBOSE_READ_SAMPLE(verbosity, expr) \ VERBOSE((MP4_DETAILS_READ | MP4_DETAILS_SAMPLE), verbosity, expr) #define VERBOSE_READ_HINT(verbosity, expr) \ VERBOSE((MP4_DETAILS_READ | MP4_DETAILS_HINT), verbosity, expr) #define VERBOSE_WRITE(verbosity, expr) \ VERBOSE(MP4_DETAILS_WRITE, verbosity, expr) #define VERBOSE_WRITE_TABLE(verbosity, expr) \ VERBOSE((MP4_DETAILS_WRITE | MP4_DETAILS_TABLE), verbosity, expr) #define VERBOSE_WRITE_SAMPLE(verbosity, expr) \ VERBOSE((MP4_DETAILS_WRITE | MP4_DETAILS_SAMPLE), verbosity, expr) #define VERBOSE_WRITE_HINT(verbosity, expr) \ VERBOSE((MP4_DETAILS_WRITE | MP4_DETAILS_HINT), verbosity, expr) #define VERBOSE_FIND(verbosity, expr) \ VERBOSE(MP4_DETAILS_FIND, verbosity, expr) #define VERBOSE_ISMA(verbosity, expr) \ VERBOSE(MP4_DETAILS_ISMA, verbosity, expr) #define VERBOSE_EDIT(verbosity, expr) \ VERBOSE(MP4_DETAILS_EDIT, verbosity, expr) inline void Indent(FILE* pFile, u_int8_t depth) { fprintf(pFile, "%*c", depth, ' '); } static inline void MP4Printf(const char* fmt, ...) #ifndef _WIN32 __attribute__((format(__printf__, 1, 2))) #endif ; static inline void MP4Printf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); // TBD API call to set error_msg_func instead of just printf vprintf(fmt, ap); va_end(ap); } class MP4Error { public: MP4Error() { m_errno = 0; m_errstring = NULL; m_where = NULL; m_free = 0; } ~MP4Error() { if (m_free != 0) { free((void *)m_errstring); } } MP4Error(int err, const char* where = NULL) { m_errno = err; m_errstring = NULL; m_where = where; m_free = 0; } MP4Error(const char *format, const char *where, ...) { char *string; m_errno = 0; string = (char *)malloc(512); m_where = where; if (string) { va_list ap; va_start(ap, where); vsnprintf(string, 512, format, ap); va_end(ap); m_errstring = string; m_free = 1; } else { m_errstring = format; m_free = 0; } } MP4Error(int err, const char* format, const char* where, ...) { char *string; m_errno = err; string = (char *)malloc(512); m_where = where; if (string) { va_list ap; va_start(ap, where); vsnprintf(string, 512, format, ap); va_end(ap); m_errstring = string; m_free = 1; } else { m_errstring = format; m_free = 0; } } void Print(FILE* pFile = stderr); int m_free; int m_errno; const char* m_errstring; const char* m_where; }; void MP4HexDump( u_int8_t* pBytes, u_int32_t numBytes, FILE* pFile = stdout, u_int8_t indent = 0); inline void* MP4Malloc(size_t size) { if (size == 0) return NULL; void* p = malloc(size); if (p == NULL && size > 0) { throw new MP4Error(errno); } return p; } inline void* MP4Calloc(size_t size) { if (size == 0) return NULL; return memset(MP4Malloc(size), 0, size); } inline char* MP4Stralloc(const char* s1) { char* s2 = (char*)MP4Malloc(strlen(s1) + 1); strcpy(s2, s1); return s2; } #ifdef _WIN32 inline wchar_t* MP4Stralloc(const wchar_t* s1) { wchar_t* s2 = (wchar_t*)MP4Malloc((wcslen(s1) + 1)*sizeof(wchar_t)); wcscpy(s2, s1); return s2; } #endif inline void* MP4Realloc(void* p, u_int32_t newSize) { // workaround library bug if (p == NULL && newSize == 0) { return NULL; } p = realloc(p, newSize); if (p == NULL && newSize > 0) { throw new MP4Error(errno); } return p; } inline void MP4Free(void* p) { if (p == NULL) return; free(p); } inline u_int32_t STRTOINT32(const char* s) { #ifdef WORDS_BIGENDIAN return (*(u_int32_t *)s); #else return htonl(*(uint32_t *)s); #endif #if 0 return (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3]; #endif } inline void INT32TOSTR(u_int32_t i, char* s) { #ifdef WORDS_BIGENDIAN *(uint32_t *)s = i; s[4] = 0; #else s[0] = ((i >> 24) & 0xFF); s[1] = ((i >> 16) & 0xFF); s[2] = ((i >> 8) & 0xFF); s[3] = (i & 0xFF); s[4] = 0; #endif } #ifdef SIMON_CHANGED inline MP4Timestamp MP4GetAbsTimestamp() { SYSTEMTIME sys_time; MP4Timestamp ret; GetSystemTime(&sys_time); ret = ((sys_time.wYear - 1904) * 365 + 20) * 24 * 60 * 60; return ret; } #else inline MP4Timestamp MP4GetAbsTimestamp() { struct timeval tv; gettimeofday(&tv, NULL); MP4Timestamp ret; ret = tv.tv_sec; ret += 2082844800; return ret; // MP4 start date is 1/1/1904 // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60 } #endif u_int64_t MP4ConvertTime(u_int64_t t, u_int32_t oldTimeScale, u_int32_t newTimeScale); bool MP4NameFirstMatches(const char* s1, const char* s2); bool MP4NameFirstIndex(const char* s, u_int32_t* pIndex); char* MP4NameFirst(const char *s); const char* MP4NameAfterFirst(const char *s); char* MP4ToBase16(const u_int8_t* pData, u_int32_t dataSize); char* MP4ToBase64(const u_int8_t* pData, u_int32_t dataSize); const char* MP4NormalizeTrackType(const char* type, uint32_t verbosity); #endif /* __MP4_UTIL_INCLUDED__ */
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 285 ] ] ]
aaa0681ccac0d2764505f6b4deed193b4100c5c2
04fec4cbb69789d44717aace6c8c5490f2cdfa47
/include/wx/msw/dialog.h
bb408bf12b9a6a7bf99d62809beb032533bfe504
[]
no_license
aaryanapps/whiteTiger
04f39b00946376c273bcbd323414f0a0b675d49d
65ed8ffd530f20198280b8a9ea79cb22a6a47acd
refs/heads/master
2021-01-17T12:07:15.264788
2010-10-11T20:20:26
2010-10-11T20:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,521
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/msw/dialog.h // Purpose: wxDialog class // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: dialog.h 40687 2006-08-19 22:56:11Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_DIALOG_H_ #define _WX_DIALOG_H_ #include "wx/panel.h" extern WXDLLEXPORT_DATA(const wxChar) wxDialogNameStr[]; class WXDLLEXPORT wxDialogModalData; #if wxUSE_TOOLBAR && (defined(__SMARTPHONE__) || defined(__POCKETPC__)) class WXDLLEXPORT wxToolBar; extern WXDLLEXPORT_DATA(const wxChar) wxToolBarNameStr[]; #endif // Dialog boxes class WXDLLEXPORT wxDialog : public wxDialogBase { public: wxDialog() { Init(); } // full ctor wxDialog(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = wxDialogNameStr) { Init(); (void)Create(parent, id, title, pos, size, style, name); } bool Create(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = wxDialogNameStr); virtual ~wxDialog(); // return true if we're showing the dialog modally virtual bool IsModal() const { return m_modalData != NULL; } // show the dialog modally and return the value passed to EndModal() virtual int ShowModal(); // may be called to terminate the dialog with the given return code virtual void EndModal(int retCode); // we treat dialog toolbars specially under Windows CE #if wxUSE_TOOLBAR && defined(__POCKETPC__) // create main toolbar by calling OnCreateToolBar() virtual wxToolBar* CreateToolBar(long style = -1, wxWindowID winid = wxID_ANY, const wxString& name = wxToolBarNameStr); // return a new toolbar virtual wxToolBar *OnCreateToolBar(long style, wxWindowID winid, const wxString& name ); // get the main toolbar wxToolBar *GetToolBar() const { return m_dialogToolBar; } #endif // wxUSE_TOOLBAR && __POCKETPC__ // implementation only from now on // ------------------------------- // override some base class virtuals virtual bool Show(bool show = true); virtual void Raise(); #ifdef __POCKETPC__ // Responds to the OK button in a PocketPC titlebar. This // can be overridden, or you can change the id used for // sending the event with SetAffirmativeId. Returns false // if the event was not processed. virtual bool DoOK(); #endif // Windows callbacks WXLRESULT MSWWindowProc(WXUINT message, WXWPARAM wParam, WXLPARAM lParam); #if WXWIN_COMPATIBILITY_2_6 // use the other ctor wxDEPRECATED( wxDialog(wxWindow *parent, const wxString& title, bool modal, int x = wxDefaultCoord, int y = wxDefaultCoord, int width = 500, int height = 500, long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = wxDialogNameStr) ); // just call Show() or ShowModal() wxDEPRECATED( void SetModal(bool flag) ); // use IsModal() wxDEPRECATED( bool IsModalShowing() const ); #endif // WXWIN_COMPATIBILITY_2_6 protected: // find the window to use as parent for this dialog if none has been // specified explicitly by the user // // may return NULL wxWindow *FindSuitableParent() const; // common part of all ctors void Init(); private: wxWindow* m_oldFocus; bool m_endModalCalled; // allow for closing within InitDialog #if wxUSE_TOOLBAR && defined(__POCKETPC__) wxToolBar* m_dialogToolBar; #endif // this pointer is non-NULL only while the modal event loop is running wxDialogModalData *m_modalData; DECLARE_DYNAMIC_CLASS(wxDialog) DECLARE_NO_COPY_CLASS(wxDialog) }; #endif // _WX_DIALOG_H_
[ [ [ 1, 140 ] ] ]
4beb2373ad6950b26554f33cb888b32e3e9de080
85a9c10b0847d7e09c42b7c124722bd1d1b4ee1b
/Unit1.cpp
100a27500bed327a84a9963ddfda20904f4d9a8a
[]
no_license
abcolor/mean-shift-tracker
7b1638fee9f33aa2b961859722c5618573ca2868
0ed134114733d61be28c65a3b19a55b37ef6aa7f
refs/heads/master
2021-01-20T11:51:32.864853
2011-09-20T17:36:06
2011-09-20T17:36:06
2,423,960
0
1
null
null
null
null
UTF-8
C++
false
false
3,640
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { camera = new TVideoCapture(PanelCamera->Handle, 30); tracker = 0; imgOutput->Canvas->Pen->Width = 2; imgOutput->Canvas->Pen->Color = clRed; imgOutput->Canvas->Brush->Style = bsClear; imgOutput->Canvas->Brush->Style = bsClear; imgOutput->Canvas->Pen->Width = 2; imgOutput->Canvas->Pen->Color = clYellow; } //--------------------------------------------------------------------------- void __fastcall TForm1::btnConnectClick(TObject *Sender) { camera->connect(comboCameraDevice->ItemIndex); btnSource->Enabled = true; btnFormat->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::btnSourceClick(TObject *Sender) { camera->source(); } //--------------------------------------------------------------------------- void __fastcall TForm1::btnFormatClick(TObject *Sender) { if(btnDetection->Caption == "Stop") btnDetectionClick(Form1); camera->format(); } //--------------------------------------------------------------------------- void __fastcall TForm1::btnDetectionClick(TObject *Sender) { if(btnDetection->Caption == "Start") { btnDetection->Caption = "Stop"; camera->enableOnFrameCallback(1); } else { btnDetection->Caption = "Start"; camera->enableOnFrameCallback(0); } } //--------------------------------------------------------------------------- void TForm1::processInputFrame(byte *frame) { camera->drawFrame(imgOutput, frame); if(tracker) { CGRect box = tracker->inputFrame(frame); Rectangle(imgOutput->Canvas->Handle, box.origin.x, box.origin.y, box.origin.x + box.size.width, box.origin.y + box.size.height); imgOutput->Repaint(); } } //--------------------------------------------------------------------------- void __fastcall TForm1::imgOutputMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { shpSelectObj->Left = X; shpSelectObj->Top = Y; shpSelectObj->Width = 0; shpSelectObj->Height = 0; shpSelectObj->Visible = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::imgOutputMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if(shpSelectObj->Visible) { shpSelectObj->Width = X - shpSelectObj->Left; shpSelectObj->Height = Y - shpSelectObj->Top; } } //--------------------------------------------------------------------------- void __fastcall TForm1::imgOutputMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { shpSelectObj->Visible = false; CGRect rect; rect.origin.x = shpSelectObj->Left + (shpSelectObj->Width>>1); rect.origin.y = shpSelectObj->Top + (shpSelectObj->Height>>1); rect.size.width = shpSelectObj->Width; rect.size.height = shpSelectObj->Height; if(tracker) delete tracker; tracker = new MeanShiftTracker(rect); } //---------------------------------------------------------------------------
[ [ [ 1, 114 ] ] ]
66693793bd1588403f1c4e94b35f27876deb3b0d
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/GuiLib/GuiLib/GuiControlBar.cpp
76584a2d24fc200b6cb09778feba95cf6027da1e
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
68,339
cpp
/**************************************************************************** * * * GuiToolKit * * (MFC extension) * * Created by Francisco Campos G. www.beyondata.com [email protected] * *--------------------------------------------------------------------------* * * * This program is free software;so you are free to use it any of your * * applications (Freeware, Shareware, Commercial),but leave this header * * intact. * * * * These files are provided "as is" without warranty of any kind. * * * * GuiToolKit is forever FREE CODE !!!!! * * * *--------------------------------------------------------------------------* * Created by: Francisco Campos G. * * Bug Fixes and improvements : (Add your name) * * -Francisco Campos * * * ****************************************************************************/ // GuiControlBar.cpp : implementation file #include "stdafx.h" #include "GuiControlBar.h" #include "GuiDockContext.h" #include "GuiDrawLayer.h" #include "GuiToolBarWnd.h" #include "menuBar.h" #include "GuiMDIFrame.h" #include "GuiFrameWnd.h" #include "GuiMiniFrameWnd.h" #define GUI_SCROLLON 10 #define GUI_SCROLLOFF 11 #define GUI_NUMITER 5 #define HTPIN 323 // CGuiControlBar #pragma warning( disable : 4244 ) IMPLEMENT_DYNAMIC(CGuiControlBar, CControlBar) CGuiControlBar::CGuiControlBar() { nGapGripper=20; m_bActive=FALSE; m_bOldActive=FALSE; m_sizeMinFloating=m_sizeVert=m_sizeHorz=CSize(200,100); m_sizeMinFloating1=m_sizeMinFloating; m_sizeHorzt=CSize(200,100); m_sizeVertt=CSize(600,100); m_pos=0; m_Last=0; m_bTracking=FALSE; m_rcBorder=CRect(0,0,0,0); m_rcOldBorder=CRect(0,0,0,0); m_ptOld=CPoint(0,0); m_sizeMinV=CSize(28,28); m_sizeMinH=CSize(28,28); m_Initialize=FALSE; m_First=-1; m_bForcepaint=FALSE; m_stateBtn=NORMAL; m_stateAHBtn=NORMAL; m_bSupportMultiView=FALSE; m_MenuContext=NULL; m_StyleDisplay=GUISTYLE_XP; m_clrFondo=GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); m_bAutoHide=FALSE; Porc=0.0; m_bComplete=TRUE; m_IsLoadDocking=TRUE; m_hIcon=NULL; } CGuiControlBar::~CGuiControlBar() { } BEGIN_MESSAGE_MAP(CGuiControlBar, CControlBar) ON_WM_CREATE() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_NCLBUTTONDOWN() ON_WM_NCRBUTTONDOWN() ON_WM_NCLBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_NCPAINT() ON_WM_NCCALCSIZE() ON_WM_WINDOWPOSCHANGED() ON_WM_PAINT() ON_WM_LBUTTONDBLCLK() ON_WM_NCLBUTTONDBLCLK() ON_WM_NCHITTEST() ON_WM_SETCURSOR() ON_WM_SIZE() ON_WM_NCMOUSEMOVE() ON_WM_TIMER() ON_COMMAND(ID_GUI_SHOWTITLE, OnShowTitle) ON_WM_SYSCOLORCHANGE() END_MESSAGE_MAP() // CGuiControlBar message handlers void CGuiControlBar::OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL /*bDisableIfNoHndler*/) { CWnd* pFocus = GetFocus(); m_bOldActive=(pFocus->GetSafeHwnd() && IsChild(pFocus)); m_bForcepaint=TRUE; if (!m_bActive && m_bOldActive) OnActiveWindow(); m_bForcepaint=FALSE; } void CGuiControlBar::OnSysColorChange( ) { m_clrFondo=GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); CControlBar::OnSysColorChange( ); } BOOL CGuiControlBar::Create(LPCTSTR lpszWindowName, DWORD dwStyle,CWnd* pParentWnd, UINT nID) { // TODO: Add your specialized code here and/or call the base class //gran parte del codigo se tomo como guia de clases MFC ASSERT_VALID(pParentWnd); // must have a parent //en esta linea se verifica que la ventana debe disponer de un estilo fijo o dinamico //pero no los dos.el estilo Dynamic permite cambiar el tamaño dela ventana mientras flota //pero no cuando esta docking, el estilo fijo determina las columnas en que se disponen los //componentes y permance asi. ASSERT(!((dwStyle & CBRS_SIZE_FIXED) && (dwStyle & CBRS_SIZE_DYNAMIC))); // save the style //en dwStyle debe asignarse un tipo de alineación por ejemplo CBRS_TOP,etc de lo contrario //se generase un ASSERT al acambiar el Style dwStyle|=CBRS_TOP; m_dwStyle = (dwStyle & CBRS_ALL);//save the original style dwStyle &= ~CBRS_ALL; //en la siguiente instruccion el proposito que se busca es evitar el parpadeo //cuando se refresca la ventana. //WS_CLIPCHILDREN : recorta el area de las ventanas hijas cuando se dibuja sobre // la ventana que la contiene. //WS_CLIPSIBLING : cuando se recibe el mensaje paint se recorta el area de las otras ventanas // hijas superpuestas, que estan fuera de la region. dwStyle |= WS_CLIPSIBLINGS|WS_CLIPCHILDREN; pMf=pParentWnd; //con el estilo CS_DBLCLKS, lo que se busca es que al recibir un doble clic //la ventana reaccione,ojo el problema es que esto lo hace solo con el area cliente. LPCTSTR lpszClassName=::AfxRegisterWndClass(CS_DBLCLKS, ::LoadCursor(NULL,IDC_ARROW), ::GetSysColorBrush(COLOR_BTNFACE), NULL); //poque no se llama a CControlBar::Create, bueno, da igual llamar a cualquiera, CWnd o CControlBar //esto debido a que CControlbar se deriva de CWnd y porque ademas CControlBar no sobrecarga el //metodo Create, nosotros si porque tenemos que particularizar, cosas. BOOL bResp= CWnd::Create(lpszClassName, lpszWindowName, dwStyle, CRect(0,0,0,0), pParentWnd, nID); if (!bResp) return FALSE; return TRUE; } int CGuiControlBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CControlBar::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here //aqui es cuando llamamos a nuestra clase CGuiDockContext, de esta manera //sobrecargamos el clase original que para nuestros propositos no nos sirve. //porque ?, bueno porque me interesa que no se pegen las toolbar en el interior //de las ventanas. if (m_pDockContext==NULL) m_pDockContext=new CGuiDockContext(this); ASSERT(m_pDockContext); m_CloseBtn.SetData(6,_T("Close")); m_CloseBtn.SetImageList(IDB_GUI_DOCKBAR,9,10,RGB(255,0,255)); m_AutoHideBtn.SetData(12,_T("Auto Hide")); m_AutoHideBtn.SetImageList(IDB_GUI_DOCKBAR,9,15,RGB(255,0,255)); return 0; } void CGuiControlBar::OnShowTitle() { ActiveCaption(); SendMessage(WM_NCPAINT); } CSize CGuiControlBar::CalcWinPos() { POSITION pos = m_pDockSite->m_listControlBars.GetHeadPosition(); DWORD dwDockStyle = m_dwDockStyle; dwDockStyle &= CBRS_ALIGN_ANY|CBRS_FLOAT_MULTI; CRect rect; GetWindowRect(&rect); while (pos != NULL) { CDockBar* pDockBar = (CDockBar*)m_pDockSite->m_listControlBars.GetNext(pos); if (pDockBar->IsDockBar() && pDockBar->IsWindowVisible() && (pDockBar->m_dwStyle & dwDockStyle & CBRS_ALIGN_ANY) && (!pDockBar->m_bFloating || (dwDockStyle & pDockBar->m_dwStyle & CBRS_FLOAT_MULTI))) { CRect rectBar; pDockBar->GetWindowRect(&rectBar); if (rectBar.Width() == 0) rectBar.right++; if (rectBar.Height() == 0) rectBar.bottom++; if (rectBar.IntersectRect(rectBar, rect)) { int nSize=pDockBar->m_arrBars.GetSize(); int iCont=0; UINT m_nDockBarID; for (int i=0;i <nSize; i++) { m_nDockBarID = pDockBar->GetDlgCtrlID(); CControlBar* pBar; pBar = (CControlBar*) pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; iCont++; } m_pDockSite->GetControlBar(m_nDockBarID)->GetWindowRect(rectBar); if((pDockBar->m_dwStyle & dwDockStyle) ==CBRS_ALIGN_LEFT) { if (iCont==0) return CSize(m_sizeMinFloating.cx,(rectBar.Height()-4)); else if(iCont>0) return CSize(m_sizeMinFloating.cx,(rectBar.Height()/iCont)); } else { if (iCont==0) return CSize((rectBar.Width()-4),m_sizeMinFloating.cy); else if(iCont>0) return CSize((rectBar.Width()/iCont),m_sizeMinFloating.cy); } } } } /* if (i==1) return CSize(m_sizeMinFloating.cx,(rcWin.Height()-4)); else if(i>1) return CSize(m_sizeMinFloating.cx,(rcWin.Height()/i)); else*/ return m_sizeMinFloating; } //esta funcion calcula el tamaño horizontal de la ventana,no importa si esta //docking a izquierda o derecha o arriba o abajo.Debemos disponer de un espacio equitativo entre todas //ventanas que se encuentren docking ya sea en una fila o columna. CSize CGuiControlBar::CalcFixedLayout(BOOL bStretch, BOOL bHorz) { //la funcion original toma el ancho o alto dependiendo del sentido que nos //indica bHorz. ASSERT_VALID(this); //se modifica esta rutina para que se ajuste correctamente las ventanas docking if (IsFloating()) return m_sizeMinFloating;//CalcWinPos(); else { //si bStrerch es TRUE significa que esta ventana no se puede hacer //Docking if (bStretch) { if (bHorz) return CSize(32767, m_sizeHorz.cy); else return CSize(m_sizeVert.cx, 32767); } } int Len=GetHiWid(); //call from GuiDockContext if (Len==0) { if (IsHorz()) return m_sizeHorz; else return m_sizeVert; } int nWidth = GetWidthMax(); int nMinSpace=0;//minimo espacio requerido con lo tamaños normales int nMinimo=0; //minimo espacio de los tamaños minimos int nRealBars=0; int m_First=GetFirstPos(); for (int nPos = m_First; nPos <= m_Last; nPos++) { CGuiControlBar* pBar = GetGuiControlBar(nPos,TRUE); if (pBar== NULL) continue; if (!pBar->IsVisible()) continue; if (!pBar->IsKindOf(RUNTIME_CLASS(CGuiControlBar))) { CPoint pt(GetMessagePos()); CGuiFrameWnd* mFrame=(CGuiFrameWnd*)m_pDockSite; if (IsLeft()) mFrame->DockControlBar(pBar,mFrame->m_dockLeft); if(IsTop()) mFrame->DockControlBar(pBar,mFrame->m_dockTop); if(IsBottom()) mFrame->DockControlBar(pBar,mFrame->m_dockBottom); if(IsRight()) mFrame->DockControlBar(pBar,mFrame->m_dockRight); continue; } if (IsVert()) pBar->m_sizeVert.cx=nWidth; else pBar->m_sizeHorz.cy=nWidth; //todas se hacen con el mismo ancho nMinSpace+=IsVert() ? pBar->m_sizeVert.cy:pBar->m_sizeHorz.cx; //minimo espacio para alinear las barras nRealBars++; //cuantas barras realmente existen } //si el tamaño de las barras en la fila es mayor que //el espacio disponible, luego la solucion salomonica es //repartir el espacio entre todas. if (nRealBars == 1 ) { if (bHorz) return m_sizeHorz= CSize(Len,m_sizeHorz.cy); else return m_sizeVert=CSize(m_sizeVert.cx,Len); } int niDif=(Len-nMinSpace);//sVert()?8:2); if (abs(niDif) !=0) { BOOL bGrow=FALSE; if (niDif > 0) bGrow=TRUE; niDif=abs(niDif); while(niDif > 0) { for (int nPos = m_First; nPos <= m_Last; nPos++) { CGuiControlBar* pBar = GetGuiControlBar(nPos); if (pBar== NULL) continue; if(IsVert()) { if(bGrow) pBar->m_sizeVert.cy+=1; else { if (pBar->m_sizeVert.cy-1 < 26) { niDif--; //bug fixed continue; } pBar->m_sizeVert.cy-=1; } } else { if(bGrow) pBar->m_sizeHorz.cx+=1; else { if (pBar->m_sizeHorz.cx-1 < 26) { niDif--; //bug fixed continue; } pBar->m_sizeHorz.cx-=1; } } niDif--; if(niDif==0) break; } } } //--reubicar las ventanas, sin esta rutina nada funciona RecalWindowPos(); if (IsHorz()) return m_sizeHorz; else return m_sizeVert; } //esta rutina dispone de la posición en el Dockbar de la pila de ventanas void CGuiControlBar::RecalWindowPos() { int m_First=GetFirstPos(); int m_Last=GetLastPos(); int m_This=m_pDockBar->FindBar(this); AFX_SIZEPARENTPARAMS layout; layout.hDWP =::BeginDeferWindowPos( m_Last); CRect rcWin=GetDockRect(); int m_VertPos=0; for(int i=m_First; i<= m_Last; i++) { CGuiControlBar* pBar = GetGuiControlBar(i); if (pBar == NULL) continue; CRect rcBar; pBar->GetWindowRect(rcBar); rcBar.OffsetRect(-rcWin.TopLeft()); if (IsVert()) { if (i==m_First) { rcBar.top=0; } else rcBar.top=m_VertPos; } else { if (i==m_First) rcBar.left=0; else rcBar.left=m_VertPos; } //AfxRepositionWindow(&layout,pBar->m_hWnd,&rcBar); if (IsVert()) rcBar.bottom=m_VertPos+pBar->m_sizeVert.cy; else rcBar.right=m_VertPos+pBar->m_sizeHorz.cx; pBar->MoveWindow(rcBar,TRUE); if (IsVert()) m_VertPos+=rcBar.Height(); else m_VertPos+=rcBar.Width(); } ASSERT( layout.hDWP != NULL ); if( layout.hDWP != NULL ) { VERIFY( ::EndDeferWindowPos(layout.hDWP) ); } //m_pDockSite->DelayRecalcLayout(); } CRect CGuiControlBar::GetDockRect() { CRect rcWin; if(!m_bAutoHide) { if (IsVert()) if (IsLeft()) { m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_LEFT)->GetWindowRect(rcWin); CRect rc11; m_pDockSite->GetControlBar(CBRS_ALIGN_LEFT)->GetWindowRect(rc11); } else m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_RIGHT)->GetWindowRect(rcWin); else if(IsBottom()) m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_BOTTOM)->GetWindowRect(rcWin); else m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_TOP)->GetWindowRect(rcWin); } else { if (IsHideVert()) if (IsHideLeft()) { m_pDockSite->GetControlBar(CBRS_ALIGN_LEFT)->GetWindowRect(rcWin); CRect rc11; m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_LEFT)->GetWindowRect(rc11); } else m_pDockSite->GetControlBar(CBRS_ALIGN_RIGHT)->GetWindowRect(rcWin); else if(IsHideBottom()) m_pDockSite->GetControlBar(CBRS_ALIGN_BOTTOM)->GetWindowRect(rcWin); else m_pDockSite->GetControlBar(CBRS_ALIGN_TOP)->GetWindowRect(rcWin); } return rcWin; } CRect CGuiControlBar::GetDockRectBck() { CRect rcWin=CRect(0,0,0,0); if (m_nLastAlingDockingBck==AFX_IDW_DOCKBAR_LEFT) m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_LEFT)->GetWindowRect(rcWin); else if(m_nLastAlingDockingBck==AFX_IDW_DOCKBAR_RIGHT) m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_RIGHT)->GetWindowRect(rcWin); else if(m_nLastAlingDockingBck==AFX_IDW_DOCKBAR_BOTTOM) m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_BOTTOM)->GetWindowRect(rcWin); else if(m_nLastAlingDockingBck==AFX_IDW_DOCKBAR_TOP) m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_TOP)->GetWindowRect(rcWin); return rcWin; } int CGuiControlBar::GetWidthMax() { m_pos=m_pDockBar->FindBar(this); m_Last=GetLastPos(); int nWidth=0; for (int nPos = GetFirstPos(); nPos <= m_Last; nPos++) { CGuiControlBar* pBar = GetGuiControlBar(nPos); if (pBar== NULL) continue; nWidth=max(nWidth,IsVert() ? pBar->m_sizeVert.cx:pBar->m_sizeHorz.cy); } return nWidth; } CGuiControlBar* CGuiControlBar::GetGuiControlBar(int nPos,BOOL bAll) const { CGuiControlBar* pResult = (CGuiControlBar*)m_pDockBar->m_arrBars[nPos]; if (bAll==FALSE) { if (HIWORD(pResult) == NULL) return NULL; else if (!pResult->IsVisible()) return NULL; else if (!pResult->IsKindOf(RUNTIME_CLASS(CGuiControlBar))) return NULL; } else { if (HIWORD(pResult) == NULL) return NULL; } return pResult; } //En esta función se calcula el tamaño de la ventana cuando esta flotando //y gestionar cuando el mouse es presionado en las esquinas. //#define HTTOPLEFT 13 //#define HTTOPRIGHT 14 //#define HTBOTTOMLEFT 16 //#define HTBOTTOMRIGHT 17 CSize CGuiControlBar::CalcDynamicLayout(int nLength, DWORD nMode) { // m_pDockSite->DelayRecalcLayout(); if (IsFloating() && !m_bAutoHide) { // Enable diagonal arrow cursor for resizing //m_sizeVert=m_sizeHorz=CSize(200,200); GetParent()->GetParent()->ModifyStyle(MFS_4THICKFRAME/*|WS_CAPTION*/,0); } if (nMode & (LM_HORZDOCK | LM_VERTDOCK) ) { m_pDockSite->DelayRecalcLayout(); //obligar a reposicionar la ventana, de lo contrario cuando vuelva de un doble click //desde la ventana CMiniFrameWnd queda sin area cliente if (!m_bAutoHide) { SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED|SWP_NOREDRAW); } return CControlBar::CalcDynamicLayout(nLength, nMode); } if (nMode & LM_MRUWIDTH && !m_bAutoHide) return m_sizeMinFloating; if (nMode & LM_COMMIT && !m_bAutoHide) return m_sizeMinFloating ; if (m_bAutoHide) { CRect rcW; CRect rcC; CRect rcFrameClient; GetClientRect(rcC); if (m_nLastAlingDocking ==CBRS_ALIGN_LEFT) { m_pDockSite->GetControlBar(CBRS_ALIGN_LEFT)->GetWindowRect(rcW); m_sizeMinFloating.cy=rcW.Height(); } if (m_nLastAlingDocking == CBRS_ALIGN_RIGHT) { m_pDockSite->GetControlBar(CBRS_ALIGN_RIGHT)->GetWindowRect(rcW); m_sizeMinFloating.cy=rcW.Height(); } if (m_nLastAlingDocking == CBRS_ALIGN_TOP) { m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_TOP)->GetWindowRect(rcW); m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_TOP)->GetWindowRect(rcFrameClient); m_sizeMinFloating.cx=rcFrameClient.Width(); } if (m_nLastAlingDocking == CBRS_ALIGN_BOTTOM) { m_pDockSite->GetControlBar(CBRS_ALIGN_BOTTOM)->GetWindowRect(rcW); m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_BOTTOM)->GetWindowRect(rcFrameClient); m_sizeMinFloating.cx=rcFrameClient.Width(); } return m_sizeMinFloating; } if (IsFloating() && !m_bAutoHide) { CRect rcWin; POINT cpt; GetCursorPos(&cpt); GetParent()->GetParent()->GetWindowRect(&rcWin); int nXOffset=0;int nYOffset=0; switch (m_pDockContext->m_nHitTest) { //------------------------------------------------------------------ case HTLEFT: m_pDockContext->m_rectFrameDragHorz= rcWin; m_pDockContext->m_rectFrameDragHorz.left = cpt.x; m_sizeMinFloating.cx = max(rcWin.right - cpt.x,32)-4 ; m_sizeMinFloating.cy = max((rcWin.bottom -rcWin.top)-nGapGripper-5,32)+2 ; return m_sizeMinFloating; break; case HTTOP: m_pDockContext->m_rectFrameDragHorz=rcWin; m_pDockContext->m_rectFrameDragHorz.top = cpt.y; m_sizeMinFloating.cx = max(rcWin.right-rcWin.left-2,32)-4 ; m_sizeMinFloating.cy = max((rcWin.bottom -nGapGripper-cpt.y-3),32) ; return m_sizeMinFloating; break; case HTRIGHT: m_pDockContext->m_rectFrameDragHorz=rcWin; m_pDockContext->m_rectFrameDragHorz.right = cpt.x; m_sizeMinFloating.cy = max(rcWin.bottom -rcWin.top-nGapGripper-3,32) ; m_sizeMinFloating.cx = max(cpt.x-rcWin.left-4,32); return m_sizeMinFloating; break; case HTBOTTOM: m_pDockContext->m_rectFrameDragHorz=rcWin; m_sizeMinFloating.cy = max(cpt.y-rcWin.top -nGapGripper-3,32) ; m_sizeMinFloating.cx = max(rcWin.right-rcWin.left-2,32)-4 ; m_pDockContext->m_rectFrameDragHorz.bottom = cpt.y-4; return m_sizeMinFloating; break; case HTTOPLEFT: //--------------------------------------------------------- //En este caso crece la ventana a izquierda y hacia arriba //izquierda incrementa cx y top incrementa cy m_sizeMinFloating.cx = max(rcWin.right - cpt.x,32)-3 ; m_sizeMinFloating.cy = max(rcWin.bottom -nGapGripper-cpt.y,32)-2 ; m_pDockContext->m_rectFrameDragHorz.top = cpt.y-1; m_pDockContext->m_rectFrameDragHorz.left = cpt.x-2; return m_sizeMinFloating; break; case HTTOPRIGHT: m_sizeMinFloating.cx = max(cpt.x-rcWin.left,32)-4 ; m_sizeMinFloating.cy = max(rcWin.bottom -nGapGripper-cpt.y,32)-2 ; m_pDockContext->m_rectFrameDragHorz.top = cpt.y-1; m_pDockContext->m_rectFrameDragHorz.right = cpt.x-2; return m_sizeMinFloating; break; case HTBOTTOMLEFT: m_sizeMinFloating.cx = max(rcWin.right - cpt.x,32)-4; m_sizeMinFloating.cy = max(cpt.y-rcWin.top -nGapGripper,32)-2 ; m_pDockContext->m_rectFrameDragHorz.top = rcWin.top; m_pDockContext->m_rectFrameDragHorz.bottom = cpt.y-1; m_pDockContext->m_rectFrameDragHorz.left = cpt.x-2; return m_sizeMinFloating; break; case HTBOTTOMRIGHT: m_sizeMinFloating.cx = max(cpt.x-rcWin.left,32); m_sizeMinFloating.cy = max(cpt.y-rcWin.top -nGapGripper,32) ; m_pDockContext->m_rectFrameDragHorz.top = rcWin.top; m_pDockContext->m_rectFrameDragHorz.bottom = cpt.y+1; m_pDockContext->m_rectFrameDragHorz.right = cpt.x+2; return m_sizeMinFloating; break; } } if(nMode & LM_LENGTHY) m_sizeMinFloating.cy = max(nLength,32); else m_sizeMinFloating.cx = max(nLength,32); return m_sizeMinFloating; } void CGuiControlBar::ScrollOff() { ScrollOnEfect(FALSE); GetDockingFrame()->ShowControlBar(this, FALSE, FALSE); } void CGuiControlBar::ScrollOn() { m_sizeMinFloating1=m_sizeMinFloating; GetDockingFrame()->ShowControlBar(this, TRUE, TRUE); if (m_nLastAlingDocking ==CBRS_ALIGN_LEFT || m_nLastAlingDocking == CBRS_ALIGN_RIGHT) { m_nSizeMed= m_sizeMinFloating.cx/GUI_NUMITER; m_sizeMinFloating.cx=0; } else { m_nSizeMed= m_sizeMinFloating.cy/GUI_NUMITER; m_sizeMinFloating.cy=0; } ScrollOnEfect(TRUE); } void CGuiControlBar::ScrollOnEfect(BOOL on) { CRect rcW; CRect rcC; CRect rcFrameClient; CRect rcWinScroll; GetClientRect(rcC); GetWindowRect(rcWinScroll); CDockBar* pDockBar = m_pDockBar; CMiniDockFrameWnd* pDockFrame = (CMiniDockFrameWnd*)pDockBar->GetParent(); CFrameWnd* pFrame = reinterpret_cast<CFrameWnd*>(AfxGetMainWnd()); CRect rc1; m_bComplete=FALSE; long iWidth80; long iWidth20; long iGUI_NUMITER=GUI_NUMITER; if (IsHideVert()) { iWidth80=m_sizeMinFloating1.cx/iGUI_NUMITER; iWidth20=m_sizeMinFloating1.cx/iGUI_NUMITER; } else { iWidth80=m_sizeMinFloating1.cy/iGUI_NUMITER; iWidth20=m_sizeMinFloating1.cy/iGUI_NUMITER; } for(int i=0; i< iGUI_NUMITER; i++) { if (IsHideVert()) { if (IsHideLeft()) m_pDockSite->GetControlBar(CBRS_ALIGN_LEFT)->GetWindowRect(rcW); else m_pDockSite->GetControlBar(CBRS_ALIGN_RIGHT)->GetWindowRect(rcW); } else { if(IsHideBottom()) { m_pDockSite->GetControlBar(CBRS_ALIGN_BOTTOM)->GetWindowRect(rcW); m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_BOTTOM)->GetWindowRect(rcFrameClient); m_sizeMinFloating.cx=rcFrameClient.Width(); } else { m_pDockSite->GetControlBar(CBRS_ALIGN_TOP)->GetWindowRect(rcW); m_pDockSite->GetControlBar(AFX_IDW_DOCKBAR_TOP)->GetWindowRect(rcFrameClient); m_sizeMinFloating.cx=rcFrameClient.Width(); } } if (on) { if (IsHideVert()) m_sizeMinFloating.cx+=(long)iWidth80; else m_sizeMinFloating.cy+=(long)iWidth80; } else { if (IsHideVert()) m_sizeMinFloating.cx-=(long)iWidth80; else m_sizeMinFloating.cy-=(long)iWidth80; } if (IsHideVert()) m_sizeMinFloating.cy=rcW.Height()-(rcW.Height()+m_pDockSite->GetControlBar(CBRS_ALIGN_TOP)->IsVisible()?24:0); if (IsHideVert()) { if (IsHideLeft()) rc1.left=rcW.right+24; else rc1.left=rcW.left-(m_sizeMinFloating.cx+26); rc1.top=rcW.top; rc1.right=rc1.left+m_sizeMinFloating.cx; rc1.bottom=rc1.top+m_sizeMinFloating.cy; } else { if (IsHideBottom()) rc1.top=rcW.top-(m_sizeMinFloating.cy+26); else rc1.top=rcW.bottom+26; rc1.left=rcFrameClient.left; rc1.right=rc1.left+m_sizeMinFloating.cx; rc1.bottom=rc1.top+m_sizeMinFloating.cy; } pDockFrame->SetWindowPos(reinterpret_cast<CWnd*>(HWND_TOP),rc1.left,rc1.top, rc1.Width(),rc1.Height(),SWP_HIDEWINDOW); CRect rcInvalidateClient(rc1); MapWindowPoints(NULL,&rcInvalidateClient); pDockFrame->RecalcLayout(TRUE); pDockFrame->UpdateWindow(); pDockFrame->SetWindowPos(reinterpret_cast<CWnd*>(HWND_TOP), rc1.left,rc1.top, rc1.Width(),rc1.Height(), SWP_SHOWWINDOW|SWP_NOACTIVATE); RedrawWindow(&rcInvalidateClient,NULL, RDW_UPDATENOW); if(!on) { pFrame->RecalcLayout(TRUE); pFrame->UpdateWindow(); pFrame->RedrawWindow(&rcInvalidateClient,NULL,RDW_UPDATENOW); } //Sleep(10); } m_bComplete=TRUE; m_sizeMinFloating=m_sizeMinFloating1; if (!on) { pDockFrame->SetWindowPos(reinterpret_cast<CWnd*>(HWND_TOP),rc1.left,rc1.top, rc1.Width(),rc1.Height(),SWP_HIDEWINDOW); } else { pDockFrame->RecalcLayout(TRUE); pDockFrame->UpdateWindow(); } } void CGuiControlBar::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if (nIDEvent == 1) { if (m_stateBtn==NORMAL) return; CRect rc; CPoint pt(GetMessagePos()); CRect rcT=m_rcCloseBtn; ClientToScreen(rcT); pt.y+=23; pt.x+=5; if (!rcT.PtInRect(pt)) { m_stateBtn=NORMAL; KillTimer(1); SendMessage(WM_NCPAINT); } } if (nIDEvent == 2) { if (m_stateAHBtn==NORMAL) return; CRect rc; CPoint pt(GetMessagePos()); CRect rcT=m_rcAutoHideBtn; ClientToScreen(rcT); pt.y+=23; pt.x+=5; if (!rcT.PtInRect(pt)) { m_stateAHBtn=NORMAL; KillTimer(2); SendMessage(WM_NCPAINT); } } CControlBar::OnTimer(nIDEvent); } void CGuiControlBar::OnLButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if(m_pDockBar != NULL) { ActiveCaption(); // m_pDockContext->ToggleDocking(); } else CWnd::OnLButtonDblClk(nFlags, point); } void CGuiControlBar::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_pDockBar != NULL) { // start the drag ClientToScreen(&point); // m_pDockContext->StartDrag(point); } else CControlBar::OnLButtonDown(nFlags, point); } void CGuiControlBar::OnRButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_pDockBar != NULL) { // start the drag ReleaseCapture(); m_pDockSite->UnlockWindowUpdate(); } else CControlBar::OnLButtonDown(nFlags, point); } void CGuiControlBar::OnMouseMove( UINT nHitTest, CPoint point) { if(m_bTracking) { if (GetCapture() != this) { //StopTracking(FALSE); m_bTracking=FALSE; } OnInvertTracker(m_rcBorder); //nuevos tamaños de la ventana if (IsVert() || IsHideVert()) { if (m_SideMove==HTLEFT || m_SideMove==HTRIGHT) { m_rcBorder.left=point.x; m_rcBorder.right=m_rcBorder.left+4; } else { m_rcBorder.top=point.y+26; m_rcBorder.bottom=m_rcBorder.top+4; } } else { if (m_SideMove==HTBOTTOM || m_SideMove==HTTOP) { m_rcBorder.top=point.y+26; m_rcBorder.bottom=m_rcBorder.top+4; } else { m_rcBorder.left=point.x; m_rcBorder.right=m_rcBorder.left+4; } } //-------------------------------------------------- //se hacen iguales todos los tamaños //if(!m_bAutoHide) { ClientToScreen(&point); m_pDockSite->ScreenToClient(&point); } m_ptActualPos=point; OnInvertTracker(m_rcBorder); //SetEqualWidth(); //----------------------------------------------- } } //depende de la posicion se hace igual el tamanio del ancho o alto void CGuiControlBar::SetEqualWidth() { int nFirstPos=GetFirstPos(); for (int nPos = nFirstPos; nPos <= m_Last; nPos++) { CGuiControlBar* pBar = GetGuiControlBar(nPos); if (pBar== NULL) continue; if (IsHorz()) pBar->m_sizeHorz.cy=m_sizeHorz.cy;//rcDockBar.Height(); else pBar->m_sizeVert.cx=m_sizeVert.cx; } } int CGuiControlBar::GetHiWid() { CRect rcWin; CMenuDockBar* pDock=(CMenuDockBar*)m_pDockBar; rcWin=pDock->m_rectLayout; //the real size if(IsVert()) return rcWin.Height(); else return rcWin.Width(); } //espero que funcione el truco //la idea es trabajar con coordenadas screen las dimensiones de los bordes del //dockBar, mas no con los movimientos internos. void CGuiControlBar::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CPoint ptTemp=point; ClientToScreen(&ptTemp); CRect rcFrame; CDockBar* pDockBar = m_pDockBar; BOOL isMDI=FALSE; if (GetParentFrame()->IsKindOf(RUNTIME_CLASS(CGuiMDIFrame))) isMDI=TRUE; if (m_bAutoHide) { if (isMDI) ((CGuiMDIFrame*)GetParentFrame())->GetParent()->GetClientRect(rcFrame); else ((CGuiFrameWnd*)GetParentFrame())->GetParent()->GetClientRect(rcFrame); } else { if (isMDI) ((CGuiMDIFrame*)GetParentFrame())->GetClientRect(rcFrame); else ((CGuiFrameWnd*)GetParentFrame())->GetClientRect(rcFrame); } if (m_bTracking) { ReleaseCapture(); m_bTracking=FALSE; OnInvertTracker(m_rcBorder); m_pDockSite->UnlockWindowUpdate(); if (ptTemp ==m_ptStartPos) return; if (IsVert()) { if (m_SideMove==HTLEFT) m_sizeVert.cx-=point.x; else if(m_SideMove==HTRIGHT) m_sizeVert.cx=point.x; else if(m_SideMove==HTTOP) AjustReDinSize(point); } else if (IsHorz()) { if (m_SideMove==HTBOTTOM) { if (point.y < 0) m_sizeHorz.cy+=abs(point.y); else m_sizeHorz.cy=point.y; } else if (m_SideMove==HTTOP) { if (point.y < 0) m_sizeHorz.cy+=abs(point.y)-12; else m_sizeHorz.cy-=abs(point.y)+12; } else if (m_SideMove==HTRIGHT) AjustReDinSize(point); } if (IsHideVert()== TRUE) { if (IsHideRight()) { if(point.x<0) m_sizeMinFloating.cx+=abs(point.x); else m_sizeMinFloating.cx-=point.x; if (m_sizeMinFloating.cx < (rcFrame.Width()-50) && m_sizeMinFloating.cx > 20) m_sizeMinFloating1=m_sizeMinFloating; else { m_sizeMinFloating=m_sizeMinFloating1; return; } CRect rc1; CMiniDockFrameWnd* pDockFrame = (CMiniDockFrameWnd*)pDockBar->GetParent(); pDockFrame->GetWindowRect(rc1); if(point.x<0) rc1.right+=point.x; else rc1.right-=point.x; ClientToScreen(&point); pDockFrame->SetWindowPos(reinterpret_cast<CWnd*>(HWND_TOP),point.x-5,rc1.top, rc1.Width(),rc1.Height(),NULL); } else { m_sizeMinFloating.cx=point.x+8; if (m_sizeMinFloating.cx < (rcFrame.Width()-50) && m_sizeMinFloating.cx > 20) m_sizeMinFloating1=m_sizeMinFloating; else m_sizeMinFloating=m_sizeMinFloating1; m_sizeMinFloating1=m_sizeMinFloating; GetParentFrame()->RecalcLayout(TRUE); } return ; } if (IsHideTop() || IsHideBottom()) { if(IsHideTop()) { m_sizeMinFloating.cy=point.y+25; if (m_sizeMinFloating.cy < (rcFrame.Height()-100) && m_sizeMinFloating.cy > 20) m_sizeMinFloating1=m_sizeMinFloating; else { m_sizeMinFloating=m_sizeMinFloating1; return; } m_pDockSite->RecalcLayout(); GetParentFrame()->RecalcLayout(TRUE); } else { if(point.y<0) m_sizeMinFloating.cy+=abs(point.y); else m_sizeMinFloating.cy-=point.y; if (m_sizeMinFloating.cy < (rcFrame.Height()-100) && m_sizeMinFloating.cy > 20) m_sizeMinFloating1=m_sizeMinFloating; else { m_sizeMinFloating=m_sizeMinFloating1; return ; } CRect rc1; CDockBar* pDockBar = m_pDockBar; CMiniDockFrameWnd* pDockFrame = (CMiniDockFrameWnd*)pDockBar->GetParent(); pDockFrame->GetWindowRect(rc1); if(point.y<0) rc1.top+=abs(point.y); else rc1.top-=point.y; ClientToScreen(&point); //m_sizeMinFloating.cx=rc1.Width(); //GetDockingFrame()->FloatControlBar(this,rc1.TopLeft()); pDockFrame->SetWindowPos(reinterpret_cast<CWnd*>(HWND_TOP),rc1.left,point.y, rc1.Width(),rc1.Height(),NULL); } return; } if (!m_bAutoHide) SetEqualWidth(); } if(!m_bAutoHide) m_pDockSite->RecalcLayout(); } //ajusta las ventanas a redimencionarlas verticalmente //se decrementa las anteriores ventanas a la actual y se //incrementan las posteriores. void CGuiControlBar::AjustReDinSize(CPoint point) { int nFirstPos=GetFirstPos(); int nLastPos=GetLastPos(); int m_ThisPos=m_pDockBar->FindBar(this); ClientToScreen(&point); //si la diferencia es negativa esta barra crece la anterior a esta disminuye int nDif=0; BOOL bGrow=FALSE; if (IsVert()) { nDif=m_ptStartPos.y- point.y; if (nDif > 0) bGrow=TRUE; if (bGrow) m_sizeVert.cy+=abs(nDif)+4; else m_sizeVert.cy-=abs(nDif); if (nFirstPos == m_ThisPos) return; } else { nDif=m_ptStartPos.x- point.x; if (nDif < 0) bGrow=TRUE; if (bGrow) m_sizeHorz.cx+=abs(nDif); else m_sizeHorz.cx-=abs(nDif); if (nLastPos == m_ThisPos) return; } if (IsVert()) AjustVert(bGrow,nDif); else AjustHorz(bGrow,nDif); RecalWindowPos(); } void CGuiControlBar::AjustVert(BOOL bGrow,int nDif) { int nFirstPos=GetFirstPos(); int nLastPos=GetLastPos(); int m_ThisPos=m_pDockBar->FindBar(this); if(m_SideMove==HTTOP) { //Esta ventana crece las anteriores reducen su tamaño if (bGrow) { for (int i=m_ThisPos-1; i > 0; i--) { CGuiControlBar* pBar = GetGuiControlBar(i); if (pBar== NULL) return; if(IsVert()) { if (pBar->m_sizeVert.cy-abs(nDif) < pBar->m_sizeMinV.cy) { pBar->m_sizeVert.cy=pBar->m_sizeMinV.cy; continue; } else { pBar->m_sizeVert.cy-=abs(nDif); break; } } }//for }//bGrow else //este disminuye la anterior crece { if (m_ThisPos-1 > 0) { CGuiControlBar* pBar = GetGuiControlBar(m_ThisPos-1); if (pBar== NULL) return; pBar->m_sizeVert.cy+=abs(nDif); if(m_sizeVert.cy > m_sizeMinV.cy) return; else pBar->m_sizeVert.cy-=m_sizeMinV.cy; } for (int i=m_ThisPos+1; i >= m_Last; i++) { CGuiControlBar* pBar = GetGuiControlBar(i); if (pBar== NULL) return; if(IsVert()) { if (pBar->m_sizeVert.cy-abs(nDif) < pBar->m_sizeMinV.cy) continue; else { pBar->m_sizeVert.cy-=abs(nDif); return; } } }//for } } } void CGuiControlBar::AjustHorz(BOOL bGrow,int nDif) { int nFirstPos=GetFirstPos(); int nLastPos=GetLastPos(); int m_ThisPos=m_pDockBar->FindBar(this); if(m_SideMove==HTRIGHT) { //Esta ventana crece las anteriores reducen su tamaño if (bGrow) { for (int i=m_ThisPos+1; i <= nLastPos; i++) { CGuiControlBar* pBar = GetGuiControlBar(i); if (pBar== NULL) return; if(IsHorz()) { if (pBar->m_sizeHorz.cx-abs(nDif) < pBar->m_sizeMinH.cx) { pBar->m_sizeHorz.cx=pBar->m_sizeMinH.cx; continue; } else { pBar->m_sizeHorz.cx-=abs(nDif); break; } } }//for }//bGrow else //este disminuye la anterior crece { if (m_ThisPos+1 <= m_Last) { CGuiControlBar* pBar = GetGuiControlBar(m_ThisPos+1); if (pBar== NULL) return; pBar->m_sizeHorz.cx+=abs(nDif); if(m_sizeHorz.cx > m_sizeMinH.cx) return; else pBar->m_sizeHorz.cx+=abs(nDif); } for (int i=m_ThisPos-1; i >0; i--) { CGuiControlBar* pBar = GetGuiControlBar(i); if (pBar== NULL) return; if(IsHorz()) { if (pBar->m_sizeHorz.cx-abs(nDif) < pBar->m_sizeMinH.cx) continue; else { pBar->m_sizeHorz.cx-=abs(nDif); return; } } }//for } } } //---------------------------------------------------- //OnActiveWindow retira o asigna el foco a la ventana void CGuiControlBar::OnActiveWindow() { POSITION pos = m_pDockSite->m_listControlBars.GetHeadPosition(); while (pos != NULL) { CDockBar* pDockBar = (CDockBar*)m_pDockSite->m_listControlBars.GetNext(pos); if (pDockBar->IsDockBar() && pDockBar->IsWindowVisible() && (!pDockBar->m_bFloating || m_bAutoHide)) { int nNumBars=(int)pDockBar->m_arrBars.GetSize(); for(int i=0; i< nNumBars;i++) { CGuiControlBar* pBar = (CGuiControlBar*) pDockBar->m_arrBars[i]; if (HIWORD(pBar) == NULL) continue; if (!pBar->IsVisible()) continue; if (!pBar->IsKindOf(RUNTIME_CLASS(CGuiControlBar))) continue; if (pBar != this) { pBar->m_bOldActive=FALSE; pBar->m_bActive=FALSE; pBar->m_bForcepaint=TRUE; pBar->SendMessage(WM_NCPAINT); pBar->m_bForcepaint=FALSE; } else { m_bOldActive=m_bActive; m_bActive=TRUE; m_bForcepaint=TRUE; SendMessage(WM_NCPAINT); m_bForcepaint=FALSE; } } } } } void CGuiControlBar::ActiveCaption() { CWnd* pFocus=SetFocus(); if(pFocus->GetSafeHwnd()) IsChild(pFocus); m_bForcepaint=TRUE; OnActiveWindow(); m_bForcepaint=FALSE; } void CGuiControlBar::OnNcRButtonDown(UINT nHitTest, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_bTracking /*|| IsFloating()*/) return; // ScreenToScreen (&point); CMenu m_menu; if (m_MenuContext!=NULL) { m_menu.LoadMenu(m_MenuContext); CMenu* m_SubMenu = m_menu.GetSubMenu(0); m_SubMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_VERTICAL, point.x, point.y-2, AfxGetMainWnd()); Invalidate(); UpdateWindow(); } CWnd::OnNcLButtonDown(nHitTest, point); } void CGuiControlBar::OnNcLButtonDown(UINT nHitTest, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_bTracking /*|| IsFloating()*/) return; m_ptStartPos=point; if( nHitTest == HTCAPTION || nHitTest == HTCLOSE || nHitTest == HTPIN) ActiveCaption(); //---------para el boton---- if( nHitTest == HTCLOSE) { m_stateBtn=PRESS; SendMessage(WM_NCPAINT); /*SetTimer(1,100,0); CRect rc; CGuiMiniFrameWnd* p = new CGuiMiniFrameWnd; if (!p->Create(this,this,CRect(100,100,300,400), _T("Title"),300)) { }*/ return; } if( nHitTest == HTPIN) { m_stateAHBtn=PRESS; SendMessage(WM_NCPAINT); /*SetTimer(1,100,0); CRect rc; CGuiMiniFrameWnd* p = new CGuiMiniFrameWnd; if (!p->Create(this,this,CRect(100,100,300,400), _T("Title"),300)) { }*/ return; } //-------------------------- if (m_pDockBar != NULL ) { if (HTCAPTION == nHitTest && !m_bAutoHide) { m_pDockContext->StartDrag(point); m_sizeHorzt=m_sizeHorz; m_sizeVertt=m_sizeVert; } if(!m_bTracking) { if(m_rcBorder.PtInRect(point)) { m_pDockSite->LockWindowUpdate(); OnInvertTracker(m_rcBorder); m_ptStartPos=point; SetCapture(); SetFocus(); m_bTracking=TRUE; m_sizeHorzt=m_sizeHorz; m_sizeVertt=m_sizeVert; } } } //other bug fixed // CWnd::OnNcLButtonDown(nHitTest, point); } void CGuiControlBar::InitAutoHide() { if (m_bAutoHide==TRUE) { m_stateBtn=NORMAL; m_sizeMinFloatingBck=m_sizeMinFloating; Porc=0.0; KillTimer(1); CGuiMDIFrame* pB=(CGuiMDIFrame*)pMf; pB->FloatControlBar(this,CPoint(400,400)); if(IsHideRight()) { m_nLastAlingDocking=CBRS_ALIGN_RIGHT; pB->m_dockHideRight.AddToolBars(this); } if(IsHideLeft()) { m_nLastAlingDocking=CBRS_ALIGN_LEFT; pB->m_dockHideLeft.AddToolBars(this); } if(IsHideTop()) { m_nLastAlingDocking=CBRS_ALIGN_TOP; pB->m_dockHideTop.AddToolBars(this); } if(IsHideBottom()) { m_nLastAlingDocking=CBRS_ALIGN_BOTTOM; pB->m_dockHideBottom.AddToolBars(this); } GetDockingFrame()->ShowControlBar(this, FALSE, FALSE); GetDockingFrame()->FloatControlBar(this,CPoint(400,400)); GetParent()->GetParent()->ModifyStyle(WS_CAPTION,0); } else m_IsLoadDocking=FALSE; } void CGuiControlBar::OnNcLButtonUp(UINT nHitTest, CPoint point) { // TODO: Add your message handler code here and/or call default CRect rc; //------------------ para el boton CRect rcT=m_rcCloseBtn; ClientToScreen(rcT); point.y+=23; point.x+=5; if (rcT.PtInRect(point)) { if (m_stateBtn ==PRESS) { m_stateBtn=NORMAL; KillTimer(1); if (m_bAutoHide) { m_bAutoHide=FALSE; GetParent()->GetParent()->ModifyStyle(WS_CAPTION,1); CGuiMDIFrame* pB; CGuiFrameWnd* pB1; BOOL isMDI=FALSE; if (pMf->IsKindOf(RUNTIME_CLASS(CGuiMDIFrame))) isMDI=TRUE; if (isMDI) pB=(CGuiMDIFrame*)pMf; else pB1= (CGuiFrameWnd*)pMf; if(m_nLastAlingDocking==CBRS_ALIGN_RIGHT) { if (isMDI) { pB->m_dockHideRight.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_RIGHT); } else { pB1->m_dockHideRight.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_RIGHT); } } if(m_nLastAlingDocking==CBRS_ALIGN_LEFT) { if (isMDI) { pB->m_dockHideLeft.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_LEFT); } else { pB1->m_dockHideLeft.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_LEFT); } } if(m_nLastAlingDocking==CBRS_ALIGN_TOP) { if (isMDI) { pB->m_dockHideTop.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_TOP); } else { pB1->m_dockHideTop.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_TOP); } } if(m_nLastAlingDocking==CBRS_ALIGN_BOTTOM) { if (isMDI) { pB->m_dockHideBottom.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_BOTTOM); } else { pB1->m_dockHideBottom.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_BOTTOM); } } m_nLastAlingDocking=0; // SendMessage(WM_NCLBUTTONDBLCLK); } //-------------------------------------------------------------- GetDockingFrame()->ShowControlBar(this, FALSE, FALSE); } SendMessage(WM_NCPAINT); m_pDockSite->RecalcLayout(); return; } //ojo guardar el aling de la ventana rcT=m_rcAutoHideBtn; ClientToScreen(rcT); if (rcT.PtInRect(point)) { if (m_stateAHBtn ==PRESS) { if (m_bAutoHide) { CGuiMDIFrame* pB; CGuiFrameWnd* pB1; BOOL isMDI=FALSE; m_bAutoHide=FALSE; m_sizeMinFloating=m_sizeMinFloatingBck; GetParent()->GetParent()->ModifyStyle(WS_CAPTION,1); pB=(CGuiMDIFrame*)pMf; if (pMf->IsKindOf(RUNTIME_CLASS(CGuiMDIFrame))) isMDI=TRUE; if (isMDI) pB=(CGuiMDIFrame*)pMf; else pB1= (CGuiFrameWnd*)pMf; if(m_nLastAlingDocking==CBRS_ALIGN_RIGHT) { if (isMDI) { pB->m_dockHideRight.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_RIGHT); } else { pB1->m_dockHideRight.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_RIGHT); } } if(m_nLastAlingDocking==CBRS_ALIGN_LEFT) { if (isMDI) { pB->m_dockHideLeft.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_LEFT); } else { pB1->m_dockHideLeft.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_LEFT); } } if(m_nLastAlingDocking==CBRS_ALIGN_TOP) { if (isMDI) { pB->m_dockHideTop.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_TOP); } else { pB1->m_dockHideTop.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_TOP); } } if(m_nLastAlingDocking==CBRS_ALIGN_BOTTOM) { if (isMDI) { pB->m_dockHideBottom.DeleteToolBars(this); pB->DockControlBar(this, AFX_IDW_DOCKBAR_BOTTOM); } else { pB1->m_dockHideBottom.DeleteToolBars(this); pB1->DockControlBar(this, AFX_IDW_DOCKBAR_BOTTOM); } } GetDockingFrame()->ShowControlBar(this, TRUE, TRUE); m_nLastAlingDocking=0; // SendMessage(WM_NCLBUTTONDBLCLK); } else { m_sizeMinFloatingBck=m_sizeMinFloating; m_stateBtn=NORMAL; m_bAutoHide=TRUE; Porc=0.0; KillTimer(1); CGuiMDIFrame* pB; CGuiFrameWnd* pB1; pMf=GetParentFrame(); BOOL isMDI=FALSE; if (pMf->IsKindOf(RUNTIME_CLASS(CGuiMDIFrame))) isMDI=TRUE; if (isMDI) pB=(CGuiMDIFrame*)pMf; else pB1= (CGuiFrameWnd*)pMf; if(IsRight()) { m_nLastAlingDocking=CBRS_ALIGN_RIGHT; if (isMDI) pB->m_dockHideRight.AddToolBars(this); else pB1->m_dockHideRight.AddToolBars(this); } if(IsLeft()) { m_nLastAlingDocking=CBRS_ALIGN_LEFT; if (isMDI) pB->m_dockHideLeft.AddToolBars(this); else pB1->m_dockHideLeft.AddToolBars(this); } if(IsTop()) { m_nLastAlingDocking=CBRS_ALIGN_TOP; if (isMDI) pB->m_dockHideTop.AddToolBars(this); else pB1->m_dockHideTop.AddToolBars(this); } if(IsBottom()) { m_nLastAlingDocking=CBRS_ALIGN_BOTTOM; if (isMDI) pB->m_dockHideBottom.AddToolBars(this); else pB1->m_dockHideBottom.AddToolBars(this); } // if (isMDI) { GetDockingFrame()->ShowControlBar(this, FALSE, FALSE); GetDockingFrame()->FloatControlBar(this,CPoint(400,400)); } /* else { pB1->ShowControlBar(this, FALSE, FALSE); pB1->FloatControlBar(this,CPoint(400,400)); }*/ GetParent()->GetParent()->ModifyStyle(WS_CAPTION,0); } } SendMessage(WM_NCPAINT); m_pDockSite->RecalcLayout(); return; } //-------------------para el boton m_pDockSite->RecalcLayout(); } void CGuiControlBar::OnNcPaint() { // TODO: Add your message handler code here // Do not call CControlBar::OnNcPaint() for painting messages // Tomo la misma rutina que se desarrolla para la clase // CGuiToolBarWnd. CRect rcWindow; CRect rcClient; CWindowDC dc(this); CDC m_dc; //contexto de dispositivo en memoria CBitmap m_bitmap; //la idea es tomar el area de la ventana y area cliente , luego debemos //igualar el area de coordenadas de ventana al cliente GetWindowRect(&rcWindow); GetClientRect(&rcClient); ScreenToClient(rcWindow); rcClient.OffsetRect(-rcWindow.TopLeft()); rcWindow.OffsetRect(-rcWindow.TopLeft()); m_dc.CreateCompatibleDC(&dc); m_bitmap.CreateCompatibleBitmap(&dc,rcWindow.Width(),rcWindow.Height()); CBitmap *m_OldBitmap=m_dc.SelectObject(&m_bitmap); //aqui debe utilizarse la brocha que define GuiDrawLayer, si no hacemos la siguiente //linea usted vera un horrible color negro, a cambio del dibujo. CBrush cb; cb.CreateSolidBrush(m_clrFondo); m_dc.FillRect(rcWindow, &cb); DrawGripper(&m_dc,&rcWindow); dc.IntersectClipRect(rcWindow); dc.ExcludeClipRect(rcClient);//asi evitamos el parpadeo dc.BitBlt(rcWindow.left,rcWindow.top,rcWindow.Width(),rcWindow.Height(),&m_dc,0,0,SRCCOPY); //ReleaseDC(&dc); //TODO--PAUL //::ReleaseDC(m_hWnd, dc.Detach()); m_dc.SelectObject(m_OldBitmap); m_bitmap.DeleteObject(); m_dc.DeleteDC(); } void CGuiControlBar::DrawGripper(CDC* pDC,CRect* rc) { CRect gripper = rc; gripper.top =3; gripper.left+=4; if (IsVert()) gripper.right-=!IsFloating()?!IsRight()?6:3:2; else gripper.right-=3; if(m_StyleDisplay == GUISTYLE_XP) gripper.bottom =gripper.top +nGapGripper-3; if(m_StyleDisplay == GUISTYLE_2003) gripper.bottom =gripper.top +nGapGripper+1; //si la ventana esta activa pintamos el caption o el area del titulo de color azul if (m_bAutoHide) m_bActive=FALSE; else if (IsFloating() ) m_bActive=TRUE; if(!m_bActive) { if (m_StyleDisplay == GUISTYLE_2003) { CGradient M(CSize(gripper.Width(),gripper.Height())); M.PrepareVertical(pDC,m_StyleDisplay); M.Draw(pDC,4,0,0,0,gripper.Width(),gripper.Height(),SRCCOPY); } if (m_StyleDisplay == GUISTYLE_XP) { CPen cp(PS_SOLID,1,::GetSysColor(COLOR_BTNSHADOW)); CPen* cpold=pDC->SelectObject(&cp); //linea superior pDC->MoveTo(gripper.left+1,gripper.top); pDC->LineTo(gripper.right,gripper.top); //linea izquierda pDC->MoveTo(gripper.left,gripper.top+1); pDC->LineTo(gripper.left,gripper.bottom); //linea inferior pDC->MoveTo(gripper.left+1,gripper.bottom); pDC->LineTo(gripper.right,gripper.bottom); //linea derecha pDC->MoveTo(gripper.right,gripper.top+1); pDC->LineTo(gripper.right,gripper.bottom); pDC->SelectObject(cpold); } } else { if (m_StyleDisplay == GUISTYLE_XP) { CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_ACTIVECAPTION));//GuiDrawLayer::GetRGBCaptionXP()); pDC->FillRect(gripper,&cb); cb.DeleteObject(); } if (m_StyleDisplay == GUISTYLE_2003) { CGradient M(CSize(gripper.Width(),gripper.Height())); M.PrepareCaption(pDC,m_StyleDisplay); M.Draw(pDC,4,0,0,0,gripper.Width(),gripper.Height(),SRCCOPY); } } if(m_StyleDisplay == GUISTYLE_2003) //no es XP { CRect rcWin=gripper; //rcWin.left= gripper.left; rcWin.top+=5; rcWin.left+=5; rcWin.right=rcWin.left+2; rcWin.bottom-=4; CRect rcBlack; for (int i=0; i < rcWin.Height(); i+=4) { CRect rcWindow; CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_BTNHIGHLIGHT)); rcWindow=rcWin; rcWindow.top=rcWin.top+i; rcWindow.bottom=rcWindow.top+2; pDC->FillRect(rcWindow,&cb); rcBlack=rcWindow; rcBlack.left-=1; rcBlack.top=(rcWin.top+i)-1; rcBlack.bottom=rcBlack.top+2; rcBlack.right=rcBlack.left+2; cb.DeleteObject(); cb.CreateSolidBrush(GuiDrawLayer::GetRGBColorShadow(m_StyleDisplay)); pDC->FillRect(rcBlack,&cb); } } gripper.DeflateRect(1, 1); CString m_caption; GetWindowText(m_caption); CFont m_cfont; m_cfont.CreateFont(-11,0,0,0,400,0,0,0,0,1,2,1,34,_T("Verdana")); CFont* m_fontOld=pDC->SelectObject(&m_cfont); int nMode = pDC->SetBkMode(TRANSPARENT); CString m_cadBreak=m_caption; CSize SizeCad=pDC->GetTextExtent(m_cadBreak,m_cadBreak.GetLength()); CRect rCText=gripper; rCText.top=6; rCText.bottom =rCText.top+14; int cont=m_cadBreak.GetLength(); if (SizeCad.cx > (gripper.Width()-30)) { while(cont > 1 ) { CString m_scadtemp=m_cadBreak+"..."; CSize coor=pDC->GetTextExtent(m_scadtemp,m_scadtemp.GetLength()); if(coor.cx > (gripper.Width()-30)) { m_cadBreak=m_cadBreak.Left(m_cadBreak.GetLength()-1); } else break; cont--; } m_cadBreak+=_T("..."); } if (gripper.Width() > 0 ) if (!m_bActive) pDC->TextOut(rCText.left+8,rCText.top,m_cadBreak); else { if (GuiDrawLayer::m_Style == GUISTYLE_XP) pDC->SetTextColor(RGB(255,255,255)); pDC->TextOut(rCText.left+8,rCText.top,m_cadBreak); } //CRect gripper; //------------------------------------------------ GetWindowRect( gripper ); ScreenToClient( gripper ); gripper.OffsetRect( -gripper.left, -gripper.top ); gripper.left=gripper.right-20; gripper.right-=7; gripper.top+=6; gripper.bottom=gripper.top+13; m_rcAutoHideBtn=gripper; m_rcAutoHideBtn.right-=14; m_rcAutoHideBtn.left-=14; m_rcCloseBtn=gripper; //m_rcCloseBtn.left-=4; //ClientToScreen(m_rcCloseBtn); if(!m_bAutoHide) m_AutoHideBtn.SetData(12,_T("Auto Hide")); else m_AutoHideBtn.SetData(14,_T("Auto Hide")); m_CloseBtn.Paint(pDC,m_stateBtn,gripper,NULL_BRUSH,m_bActive && GuiDrawLayer::m_Style != GUISTYLE_2003); m_AutoHideBtn.Paint(pDC,m_stateAHBtn,m_rcAutoHideBtn,NULL_BRUSH,m_bActive && GuiDrawLayer::m_Style != GUISTYLE_2003); //------------------------------------------------ pDC->SetBkMode(nMode); pDC->SelectObject(m_fontOld); } //en esta función se calcula el area cliente que podra ser utilizado //por ventanas que deriven esta clase. void CGuiControlBar::OnNcCalcSize(BOOL /*bCalcValidRects*/, NCCALCSIZE_PARAMS* lpncsp) { // adjust non-client area for border space lpncsp->rgrc[0].left +=!IsFloating() || m_bAutoHide ?5:2; lpncsp->rgrc[0].top +=!IsFloating() || m_bAutoHide ?nGapGripper+3:3; if (IsVert()) lpncsp->rgrc[0].right -=!IsFloating() || m_bAutoHide?!IsRight()?5:2:2; else lpncsp->rgrc[0].right -=3; lpncsp->rgrc[0].bottom -=!IsFloating()||m_bAutoHide?3:2; } //Aqui la idea es verificar que si se da clic sobre otra ventana de este tipo //automaticamente emita un mensaje eliminando el caption que la identifica como //ventana default. void CGuiControlBar::OnWindowPosChanged(WINDOWPOS* lpwndpos) { CRect rc; GetClientRect(rc); nDockBarAling = GetParent()->GetDlgCtrlID(); if(!IsFloating()) m_nLastAlingDockingBck=nDockBarAling; //envie un recalculo del area cliente solo si el tamaño ha sido //cambiado, de lo contrario permanezca igual lpwndpos->flags |= SWP_FRAMECHANGED; CControlBar::OnWindowPosChanged(lpwndpos); CWnd* pWnd = GetWindow(GW_CHILD); if (!m_bSupportMultiView) { if (pWnd != NULL) { pWnd->MoveWindow(rc); ASSERT(pWnd->GetWindow(GW_HWNDNEXT) == NULL); } } else { while (pWnd != NULL) { if (pWnd->IsWindowVisible()) { pWnd->MoveWindow(rc); break; } pWnd=pWnd->GetWindow(GW_HWNDNEXT); } } } //este conjunto de clases nos indican el estado de la ventana //en un momento determinado BOOL CGuiControlBar::IsHideVert() { if (m_nLastAlingDocking ==CBRS_ALIGN_LEFT || m_nLastAlingDocking == CBRS_ALIGN_RIGHT) return TRUE; return FALSE; } BOOL CGuiControlBar::IsHideLeft() { if (m_nLastAlingDocking ==CBRS_ALIGN_LEFT) return TRUE; return FALSE; } BOOL CGuiControlBar::IsHideRight() { if (m_nLastAlingDocking == CBRS_ALIGN_RIGHT) return TRUE; return FALSE; } BOOL CGuiControlBar::IsHideTop() { if (m_nLastAlingDocking == CBRS_ALIGN_TOP) return TRUE; return FALSE; } BOOL CGuiControlBar::IsHideBottom() { if (m_nLastAlingDocking == CBRS_ALIGN_BOTTOM) return TRUE; return FALSE; } BOOL CGuiControlBar::IsLeft() { if (nDockBarAling == AFX_IDW_DOCKBAR_LEFT) return TRUE; return FALSE; } BOOL CGuiControlBar::IsRight() { if (nDockBarAling == AFX_IDW_DOCKBAR_RIGHT) return TRUE; return FALSE; } BOOL CGuiControlBar::IsTop() { if (nDockBarAling == AFX_IDW_DOCKBAR_TOP) return TRUE; return FALSE; } BOOL CGuiControlBar::IsBottom() { if (nDockBarAling == AFX_IDW_DOCKBAR_BOTTOM) return TRUE; return FALSE; } BOOL CGuiControlBar::IsVert() { if (IsLeft() || IsRight()) return TRUE; return FALSE; } BOOL CGuiControlBar::IsHorz() { if (IsTop() || IsBottom()) return TRUE; return FALSE; } BOOL CGuiControlBar::IsFloating() { if (nDockBarAling == AFX_IDW_DOCKBAR_FLOAT) return TRUE; return FALSE; } void CGuiControlBar::OnPaint() { CPaintDC dc(this); // device context for painting m_pDockSite->RecalcLayout();//si quita esto se tiene problemas // TODO: Add your message handler code here // Do not call CControlBar::OnPaint() for painting messages } UINT CGuiControlBar::OnNcHitTest(CPoint point) { // TODO: Add your message handler code here and/or call default CRect rcWindow; //no se convierte las coordenadas de pantalla porque el punto //entregado por esta función esta dado en el mismo sentido. GetWindowRect(rcWindow); int it=0; // if (IsFloating()) // return CControlBar::OnNcHitTest(point); CRect rcT=m_rcCloseBtn; ClientToScreen(rcT); CPoint pt=point; pt.y+=23; pt.x+=5; //pt.Offset(-rcT.left,-rcT.top); if (rcT.PtInRect(pt)) return HTCLOSE; rcT=m_rcAutoHideBtn; ClientToScreen(rcT); pt=point; pt.y+=23; pt.x+=5; if (rcT.PtInRect(pt)) return HTPIN; CRect rcTemp; for (int i=0; i< 4; i++) { rcTemp=rcWindow; if (i== 0) //left { it= rcTemp.left; it+=4; rcTemp.right=it; m_rcBorder=rcTemp; if (rcTemp.PtInRect(point)) if(IsLegal(HTLEFT)) return m_SideMove=HTLEFT; } if (i==1) //top { it= rcTemp.top; it+=4; rcTemp.bottom=it; m_rcBorder=rcTemp; if (rcTemp.PtInRect(point)) if(IsLegal(HTTOP)) return m_SideMove=HTTOP ; } if (i==2) //right { it= rcTemp.right; it-=4; rcTemp.left=it; m_rcBorder=rcTemp; if (rcTemp.PtInRect(point)) if (IsLegal(HTRIGHT)) return m_SideMove=HTRIGHT; } if (i==3) //bottom { it= rcTemp.bottom; it-=4; rcTemp.top=it; m_rcBorder=rcTemp; if (rcTemp.PtInRect(point)) if (IsLegal(HTBOTTOM))return m_SideMove=HTBOTTOM; } } it=0; rcTemp=rcWindow; it= rcTemp.top+nGapGripper; rcTemp.bottom=it; if (rcTemp.PtInRect(point)) { SetCursor(::LoadCursor(NULL,IDC_ARROW)); return m_SideMove=HTCAPTION; } return CControlBar::OnNcHitTest(point); } //----------------------------------------------------------- //aqui se verifica que las coordenadas de cambio de tamaño //sean las correctas BOOL CGuiControlBar::IsLegal(UINT uAlin) { m_First=GetFirstPos(); // if (IsFloating()) return FALSE; switch(uAlin) { case HTLEFT: if(!m_bAutoHide) { if (IsHorz() && m_pos >0 && (m_pos != m_Last && m_pos != m_First)) return TRUE; if (IsVert() && m_pos <= m_Last && IsRight() ) return TRUE; } else { if (!IsHideVert() && m_pos >0 && (m_pos != m_Last && m_pos != m_First)) return TRUE; if (IsHideVert() && m_pos <= m_Last && IsHideRight() ) return TRUE; } return FALSE; break; case HTTOP: if(!m_bAutoHide) { if (m_pos != m_First && IsVert()) return TRUE; if (IsHorz() && m_pos <= m_Last && IsBottom() ) return TRUE; } else { if (m_pos != m_First && IsHideVert()) return TRUE; if (!IsHideVert() && m_pos <= m_Last && IsHideBottom() ) return TRUE; } return FALSE; break; case HTRIGHT: if(!m_bAutoHide) { if (m_pos <= m_Last && IsVert() && IsLeft() ) return TRUE; if (IsHorz() && m_pos >0 && m_pos != m_Last) return TRUE; } else { if (m_pos <= m_Last && IsHideVert() && IsHideLeft() ) return TRUE; if (!IsHideVert() && m_pos >0 && m_pos != m_Last) return TRUE; } return FALSE; case HTBOTTOM: if(!m_bAutoHide) { if ((m_pos != m_Last && m_pos != m_First) && IsHorz() && IsBottom()) return TRUE; if (m_pos <= m_Last && IsHorz() && IsTop()) return TRUE; } else { if ((m_pos != m_Last && m_pos != m_First) && !IsHideVert() && IsHideBottom()) return TRUE; if (m_pos <= m_Last && !IsHideVert() && IsHideTop()) return TRUE; } //if (IsVert() && m_pos >0 ) return TRUE; return FALSE; break; } return FALSE; } //---------------------------------------------- //debemos obtener cuantas barras existen en esta columnas //porque si intentamos obtener el conteo con la funciones de dockbar //siempre obtendremos nuestra actual barra mas otra de otra fila, por lo que //el conteo es incorrecto, luego despues de nuestra barra la siguiente nula //es el final de esta fila. int CGuiControlBar::GetLastPos() { int nNumBars=(int)m_pDockBar->m_arrBars.GetSize(); int m_pos=m_pDockBar->FindBar(this); for(int i=m_pos+1; i< nNumBars;i++) { if (m_pDockBar->m_arrBars[i]== NULL) return i-1; } return -1; } //-------------------------------------------- //esta rutina funciona algo parecido a la anterior //con la diferencia que ahora se parte desde la posicion //que indetifica m_pos hacia atraz hasta encontrar el nulo int CGuiControlBar::GetFirstPos() { int m_pos=m_pDockBar->FindBar(this); for(int i=m_pos; i>=0;i--) { if (m_pDockBar->m_arrBars[i]== NULL) return i+1; } return -1; } //------------------------------------------------------------------------ BOOL CGuiControlBar::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // TODO: Add your message handler code here and/or call default if (IsFloating() && !m_bAutoHide) return 0; CPoint ptCursor; ::GetCursorPos (&ptCursor); if(nHitTest == HTLEFT ||nHitTest == HTRIGHT) SetCursor(AfxGetApp ()->LoadCursor (AFX_IDC_HSPLITBAR)); else if(nHitTest == HTTOP ||nHitTest == HTBOTTOM) SetCursor(AfxGetApp ()->LoadCursor (AFX_IDC_VSPLITBAR)); else return CControlBar::OnSetCursor(pWnd, nHitTest, message); return 1; } void CGuiControlBar::OnInvertTracker(const CRect& rect) { ASSERT_VALID(this); ASSERT(!rect.IsRectEmpty()); CRect rcWin=GetDockRect(); CDC *pDC = m_pDockSite->GetDCEx(NULL, DCX_WINDOW|DCX_CACHE|DCX_LOCKWINDOWUPDATE); CRect rcBar; GetWindowRect(rcBar); if (m_bAutoHide) rcWin=rcBar; if (IsVert()|| IsHideVert()) //el sentido de las barras es vertical { if (m_SideMove==HTLEFT || m_SideMove==HTRIGHT) //el mouse esta en el borde izquierdo o derecho { rcWin.OffsetRect(-rect.left,-rect.top); rcWin.top+=10; rcWin.left=rect.left+2; rcWin.right=rect.right+2; } else //el mouse esta el borde de arriba pero de una barra vertical { rcBar.OffsetRect(-rect.TopLeft()); rcBar.OffsetRect(CPoint(0,9)); rcWin=rcBar; if (IsLeft() || IsRight()) //a la izquierda { rcWin.top=rect.top; rcWin.bottom=rect.bottom; } // } } else //el sentido de las barras es horizontal { if (m_SideMove==HTTOP || m_SideMove==HTBOTTOM) //el mouse esta en el borde de arriba o abajo { rcWin.OffsetRect(-rect.left,-rect.top); rcWin.top=rect.top-2; rcWin.bottom=rect.bottom; } else //el mouse esta en el borde derecho { rcBar.OffsetRect(-rect.TopLeft()); rcBar.OffsetRect(CPoint(0,8)); rcWin=rcBar; if ((IsBottom()|| IsHideBottom()) || (IsTop()|| IsHideTop())) //abajo { rcWin.left=rect.left+2; rcWin.right=rect.right+2; } } } ClientToScreen(&rcWin); m_pDockSite->ScreenToClient(&rcWin); // invert the brush pattern (looks just like frame window sizing) CBrush* pBrush = CDC::GetHalftoneBrush(); HBRUSH hOldBrush = NULL; if (pBrush != NULL) hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject); pDC->PatBlt(rcWin.left, rcWin.top, rcWin.Width(), rcWin.Height(), PATINVERT); if (hOldBrush != NULL) SelectObject(pDC->m_hDC, hOldBrush); m_pDockSite->ReleaseDC(pDC); } /*void CGuiControlBar::OnInvertTracker(const CRect& rect) { ASSERT_VALID(this); ASSERT(!rect.IsRectEmpty()); CRect rcWin=GetDockRect(); CDC *pDC = m_pDockSite->GetDCEx(NULL, DCX_WINDOW|DCX_CACHE|DCX_LOCKWINDOWUPDATE); CRect rcBar; GetParent()->GetWindowRect(rcBar); if (m_bAutoHide) rcWin=rcBar; if (IsVert()|| IsHideVert()) //el sentido de las barras es vertical { if (m_SideMove==HTLEFT || m_SideMove==HTRIGHT) //el mouse esta en el borde izquierdo o derecho { rcWin.OffsetRect(-rect.left,-rect.top); rcWin.top+=10; rcWin.left=rect.left+2; rcWin.right=rect.right+2; } else //el mouse esta el borde de arriba pero de una barra vertical { rcBar.OffsetRect(-rect.TopLeft()); rcBar.OffsetRect(CPoint(0,9)); rcWin=rcBar; if (IsLeft() || IsRight()) //a la izquierda { rcWin.top=rect.top; rcWin.bottom=rect.bottom; } // } } else //el sentido de las barras es horizontal { if (m_SideMove==HTTOP || m_SideMove==HTBOTTOM) //el mouse esta en el borde de arriba o abajo { rcWin.OffsetRect(-rect.left,-rect.top); rcWin.top=rect.top-2; rcWin.bottom=rect.bottom-2; } else //el mouse esta en el borde derecho { rcBar.OffsetRect(-rect.TopLeft()); rcBar.OffsetRect(CPoint(0,8)); rcWin=rcBar; if ((IsBottom()|| IsHideBottom()) || (IsTop()|| IsHideTop())) //abajo { rcWin.left=rect.left+2; rcWin.right=rect.right+2; } } } ClientToScreen(&rcWin); GetParentFrame()->ScreenToClient(&rcWin); // invert the brush pattern (looks just like frame window sizing) CBrush* pBrush = CDC::GetHalftoneBrush(); HBRUSH hOldBrush = NULL; if (pBrush != NULL) hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject); pDC->PatBlt(rcWin.left, rcWin.top, rcWin.Width(), rcWin.Height(), PATINVERT); if (hOldBrush != NULL) SelectObject(pDC->m_hDC, hOldBrush); m_pDockSite->ReleaseDC(pDC); } */ void CGuiControlBar::OnSize(UINT nType, int cx, int cy) { // CControlBar::OnSize(nType, cx, cy); CWnd* pWnd = GetWindow(GW_CHILD); if (!m_bSupportMultiView) { if (pWnd != NULL) { pWnd->MoveWindow(0, 0, cx, cy); ASSERT(pWnd->GetWindow(GW_HWNDNEXT) == NULL); } } else { while (pWnd != NULL) { if (pWnd->IsWindowVisible()) { pWnd->MoveWindow(0, 0, cx, cy); break; } pWnd=pWnd->GetWindow(GW_HWNDNEXT); } } // TODO: Add your message handler code here } void CGuiControlBar::SetColorFondo(COLORREF clrFondo) { m_clrFondo=clrFondo; } //enum State{NORMAL=0,OVER=1,PRESS=2}; void CGuiControlBar::LoadStateBar(CString sProfile) { CWinApp* pApp = AfxGetApp(); TCHAR szSection[256] = {0}; wsprintf(szSection, _T("%s-Bar%d"),sProfile,GetDlgCtrlID()); m_sizeHorz.cx=pApp->GetProfileInt(szSection, _T("sizeHorz.cx"),200 ); m_sizeHorz.cy=pApp->GetProfileInt(szSection, _T("sizeHorz.cy"),100 ); m_sizeVert.cx=pApp->GetProfileInt(szSection, _T("sizeVert.cx"),200 ); m_sizeVert.cy=pApp->GetProfileInt(szSection, _T("sizeVert.cy"),100 ); m_bAutoHide=pApp->GetProfileInt(szSection, _T("AutoHide"),0 ); m_nLastAlingDocking=pApp->GetProfileInt(szSection, _T("Aling"),0 ); if (m_bAutoHide) InitAutoHide(); else m_nLastAlingDocking=0; } void CGuiControlBar::SaveBar(CString sProfile) { CWinApp* pApp = AfxGetApp(); TCHAR szSection[256] = {0}; wsprintf(szSection, _T("%s-Bar%d"), sProfile,GetDlgCtrlID()); pApp->WriteProfileString(szSection, NULL, NULL); pApp->WriteProfileInt(szSection, _T("sizeHorz.cx"), m_sizeHorz.cx); pApp->WriteProfileInt(szSection, _T("sizeHorz.cy"), m_sizeHorz.cy); pApp->WriteProfileInt(szSection, _T("sizeVert.cx"), m_sizeVert.cx); pApp->WriteProfileInt(szSection, _T("sizeVert.cy"), m_sizeVert.cy); pApp->WriteProfileInt(szSection, _T("AutoHide"), m_bAutoHide); pApp->WriteProfileInt(szSection, _T("Aling"), m_nLastAlingDocking); } void CGuiControlBar::OnNcMouseMove(UINT nHitTest, CPoint point) { // TODO: Add your message handler code here and/or call default if (nHitTest == HTCLOSE) if (m_stateBtn != NORMAL) return; if (nHitTest == HTPIN) if (m_stateAHBtn != NORMAL) return; if (nHitTest == HTCLOSE) { m_stateBtn=OVER; SetTimer(1,100,0); } if (nHitTest == HTPIN) { m_stateAHBtn=OVER; SetTimer(2,100,0); } SendMessage(WM_NCPAINT); CControlBar::OnNcMouseMove(nHitTest, point); } void CGuiControlBar::OnNcLButtonDblClk(UINT nFlags, CPoint point) { if(m_pDockBar != NULL && !m_bAutoHide) { m_pDockContext->ToggleDocking(); m_rcOldBorder=CRect(0,0,0,0); } }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 2792 ] ] ]
1e925b9c7e58215e2c83fe4d37c78075021d8bba
b6bad03a59ec436b60c30fc793bdcf687a21cf31
/som2416/wince5/nand.cpp
a5f4863e6c84e3103a5506c94964ed4d44887bf4
[]
no_license
blackfa1con/openembed
9697f99b12df16b1c5135e962890e8a3935be877
3029d7d8c181449723bb16d0a73ee87f63860864
refs/heads/master
2021-01-10T14:14:39.694809
2010-12-16T03:20:27
2010-12-16T03:20:27
52,422,065
0
0
null
null
null
null
GB18030
C++
false
false
66,871
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft end-user // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. // If you did not accept the terms of the EULA, you are not authorized to use // this source code. For a copy of the EULA, please see the LICENSE.RTF on your // install media. // extern "C" { #include <windows.h> #include <bsp.h> #include "loader.h" #include <fmd.h> #include <VFLBuffer.h> #include <WMRTypes.h> #include <VFL.h> #include <FIL.h> #include "DisplaySample_320_240.h" //[david.modify] 2008-05-30 14:23 #include "eboot_inc_david.h" extern DWORD g_ImageType; extern UCHAR g_TOC[SECTOR_SIZE]; extern const PTOC g_pTOC; extern DWORD g_dwTocEntry; extern PBOOT_CFG g_pBootCfg; extern BOOL g_bBootMediaExist; extern MultiBINInfo g_BINRegionInfo; extern DWORD g_dwImageStartBlock; extern BOOL g_bWaitForConnect; // Is there a SmartMedia card on this device? // MLC low level test function // by dodan2 061102 extern UINT32 MLC_Read_RAW(UINT32 nBank, UINT32 nPpn, UINT8 *pMBuf, UINT8 *pSBuf); extern UINT32 MLC_Write_RAW(UINT32 nBank, UINT32 nPpn, UINT8 *pMBuf, UINT8 *pSBuf); extern UINT32 MLC_Erase_RAW(UINT32 nBank, UINT32 nBlock); extern void _Read_512Byte(UINT8* pBuf); extern void _Read_512Byte_Unaligned(UINT8* pBuf); extern void _Write_512Byte(UINT8* pBuf); extern void _Write_512Byte_Unaligned(UINT8* pBuf); } BOOL WriteBlock(DWORD dwBlock, LPBYTE pbBlock, PSectorInfo pSectorInfoTable); BOOL ReadBlock(DWORD dwBlock, LPBYTE pbBlock, PSectorInfo pSectorInfoTable); #define WMRBUFSIZE (8192 + 256) // the maximum size of 2-plane data for 4KByte/Page NAND flash Device extern DWORD g_dwLastWrittenLoc; // Defined in bootpart.lib extern PSectorInfo g_pSectorInfoBuf; extern FlashInfo g_FlashInfo; static UCHAR toc[SECTOR_SIZE]; extern BOOL IsValidMBRSector(); extern BOOL CreateMBR(); extern UCHAR WMRBuf[]; // Define a dummy SetKMode function to satisfy the NAND FMD. // DWORD SetKMode (DWORD fMode) { return(1); } void BootConfigPrint(void) { EdbgOutputDebugString( "BootCfg { \r\n"); EdbgOutputDebugString( " ConfigFlags: 0x%x\r\n", g_pBootCfg->ConfigFlags); EdbgOutputDebugString( " BootDelay: 0x%x\r\n", g_pBootCfg->BootDelay); EdbgOutputDebugString( " ImageIndex: %d \r\n", g_pBootCfg->ImageIndex); EdbgOutputDebugString( " IP: %s\r\n", inet_ntoa(g_pBootCfg->EdbgAddr.dwIP)); EdbgOutputDebugString( " MAC Address: %B:%B:%B:%B:%B:%B\r\n", g_pBootCfg->EdbgAddr.wMAC[0] & 0x00FF, g_pBootCfg->EdbgAddr.wMAC[0] >> 8, g_pBootCfg->EdbgAddr.wMAC[1] & 0x00FF, g_pBootCfg->EdbgAddr.wMAC[1] >> 8, g_pBootCfg->EdbgAddr.wMAC[2] & 0x00FF, g_pBootCfg->EdbgAddr.wMAC[2] >> 8); EdbgOutputDebugString( " Port: %s\r\n", inet_ntoa(g_pBootCfg->EdbgAddr.wPort)); EdbgOutputDebugString( " SubnetMask: %s\r\n", inet_ntoa(g_pBootCfg->SubnetMask)); EdbgOutputDebugString( "}\r\n"); } // Set default boot configuration values static void BootConfigInit(DWORD dwIndex) { EdbgOutputDebugString("+BootConfigInit\r\n"); g_pBootCfg = &g_pTOC->BootCfg; memset(g_pBootCfg, 0, sizeof(BOOT_CFG)); g_pBootCfg->ImageIndex = dwIndex; g_pBootCfg->ConfigFlags = BOOT_TYPE_MULTISTAGE | CONFIG_FLAGS_DEBUGGER; g_pBootCfg->BootDelay = CONFIG_BOOTDELAY_DEFAULT; g_pBootCfg->SubnetMask = inet_addr("255.255.255.0"); DPNOK( g_pBootCfg->BootDelay); EdbgOutputDebugString("-BootConfigInit\r\n"); return; } void ID_Print(DWORD i) { DWORD j; EdbgOutputDebugString("ID[%u] {\r\n", i); EdbgOutputDebugString(" dwVersion: 0x%x\r\n", g_pTOC->id[i].dwVersion); EdbgOutputDebugString(" dwSignature: 0x%x\r\n", g_pTOC->id[i].dwSignature); EdbgOutputDebugString(" String: '%s'\r\n", g_pTOC->id[i].ucString); EdbgOutputDebugString(" dwImageType: 0x%x\r\n", g_pTOC->id[i].dwImageType); EdbgOutputDebugString(" dwTtlSectors: 0x%x\r\n", g_pTOC->id[i].dwTtlSectors); EdbgOutputDebugString(" dwLoadAddress: 0x%x\r\n", g_pTOC->id[i].dwLoadAddress); EdbgOutputDebugString(" dwJumpAddress: 0x%x\r\n", g_pTOC->id[i].dwJumpAddress); EdbgOutputDebugString(" dwStoreOffset: 0x%x\r\n", g_pTOC->id[i].dwStoreOffset); for (j = 0; j < MAX_SG_SECTORS; j++) { if ( !g_pTOC->id[i].sgList[j].dwLength ) break; EdbgOutputDebugString(" sgList[%u].dwSector: 0x%x\r\n", j, g_pTOC->id[i].sgList[j].dwSector); EdbgOutputDebugString(" sgList[%u].dwLength: 0x%x\r\n", j, g_pTOC->id[i].sgList[j].dwLength); } EdbgOutputDebugString("}\r\n"); } void TOC_Print(void) { int i; EdbgOutputDebugString("TOC {\r\n"); EdbgOutputDebugString("dwSignature: 0x%x\r\n", g_pTOC->dwSignature); BootConfigPrint( ); for (i = 0; i < MAX_TOC_DESCRIPTORS; i++) { if ( !VALID_IMAGE_DESCRIPTOR(&g_pTOC->id[i]) ) break; ID_Print(i); } // Print out Chain Information EdbgOutputDebugString("chainInfo.dwLoadAddress: 0X%X\r\n", g_pTOC->chainInfo.dwLoadAddress); EdbgOutputDebugString("chainInfo.dwFlashAddress: 0X%X\r\n", g_pTOC->chainInfo.dwFlashAddress); EdbgOutputDebugString("chainInfo.dwLength: 0X%X\r\n", g_pTOC->chainInfo.dwLength); EdbgOutputDebugString("}\r\n"); } // init the TOC to defaults BOOL TOC_Init(DWORD dwEntry, DWORD dwImageType, DWORD dwImageStart, DWORD dwImageLength, DWORD dwLaunchAddr) { DWORD dwSig = 0; EdbgOutputDebugString("TOC_Init: dwEntry:%u, dwImageType: 0x%x, dwImageStart: 0x%x, dwImageLength: 0x%x, dwLaunchAddr: 0x%x\r\n", dwEntry, dwImageType, dwImageStart, dwImageLength, dwLaunchAddr); if (0 == dwEntry) { EdbgOutputDebugString("\r\n*** WARNING: TOC_Init blasting Eboot ***\r\n"); return FALSE; } switch (dwImageType) { case IMAGE_TYPE_LOADER: dwSig = IMAGE_EBOOT_SIG; break; case IMAGE_TYPE_RAMIMAGE: dwSig = IMAGE_RAM_SIG; break; default: EdbgOutputDebugString("ERROR: OEMLaunch: unknown image type: 0x%x \r\n", dwImageType); return FALSE; } memset(g_pTOC, 0, sizeof(g_TOC)); // init boof cfg BootConfigInit(dwEntry); // update our index g_dwTocEntry = dwEntry; // debugger enabled? g_bWaitForConnect = (g_pBootCfg->ConfigFlags & CONFIG_FLAGS_DEBUGGER) ? TRUE : FALSE; // init TOC... // g_pTOC->dwSignature = TOC_SIGNATURE; // init TOC entry for Eboot // Those are hard coded numbers from boot.bib g_pTOC->id[0].dwVersion = (EBOOT_VERSION_MAJOR << 16) | EBOOT_VERSION_MINOR; g_pTOC->id[0].dwSignature = IMAGE_EBOOT_SIG; memcpy(g_pTOC->id[0].ucString, "eboot.nb0", sizeof("eboot.nb0")+1); // NUll terminate g_pTOC->id[0].dwImageType = IMAGE_TYPE_RAMIMAGE; g_pTOC->id[0].dwLoadAddress = EBOOT_RAM_IMAGE_BASE; g_pTOC->id[0].dwJumpAddress = EBOOT_RAM_IMAGE_BASE; g_pTOC->id[0].dwTtlSectors = FILE_TO_SECTOR_SIZE(EBOOT_RAM_IMAGE_SIZE); // 1 contigious segment g_pTOC->id[0].sgList[0].dwSector = BLOCK_TO_SECTOR(EBOOT_BLOCK); g_pTOC->id[0].sgList[0].dwLength = g_pTOC->id[0].dwTtlSectors; // init the TOC entry g_pTOC->id[dwEntry].dwVersion = 0x001; g_pTOC->id[dwEntry].dwSignature = dwSig; memset(g_pTOC->id[dwEntry].ucString, 0, IMAGE_STRING_LEN); g_pTOC->id[dwEntry].dwImageType = dwImageType; g_pTOC->id[dwEntry].dwLoadAddress = dwImageStart; g_pTOC->id[dwEntry].dwJumpAddress = dwLaunchAddr; g_pTOC->id[dwEntry].dwStoreOffset = 0; g_pTOC->id[dwEntry].dwTtlSectors = FILE_TO_SECTOR_SIZE(dwImageLength); // 1 contigious segment g_pTOC->id[dwEntry].sgList[0].dwSector = BLOCK_TO_SECTOR(g_dwImageStartBlock); g_pTOC->id[dwEntry].sgList[0].dwLength = g_pTOC->id[dwEntry].dwTtlSectors; TOC_Print(); return TRUE; } // // Retrieve TOC from Nand. // BOOL TOC_Read(void) { LowFuncTbl *pLowFuncTbl; DWORD dwBlock; INT32 nRet; UINT8 *pSBuf; EdbgOutputDebugString("TOC_Read\r\n"); if ( !g_bBootMediaExist ) { EdbgOutputDebugString("TOC_Read ERROR: no boot media\r\n"); return FALSE; } pLowFuncTbl = FIL_GetFuncTbl(); pSBuf = WMRBuf + BYTES_PER_MAIN_SUPAGE; dwBlock = TOC_BLOCK; while(1) { if (dwBlock == (TOC_BLOCK+TOC_BLOCK_SIZE+TOC_BLOCK_RESERVED)) { OALMSG(TRUE, (TEXT("TOC_Read Failed !!!\r\n"))); OALMSG(TRUE, (TEXT("Too many Bad Block\r\n"))); return FALSE; } IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuLEFT_PLANE_BITMAP, NULL, pSBuf, TRUE32, FALSE32); IS_CHECK_SPARE_ECC = TRUE32; if (pSBuf[0] == 0xff) { nRet = pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK, 0x01, enuLEFT_PLANE_BITMAP, (UINT8 *)g_pTOC, NULL, FALSE32, FALSE32); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Read Error @ %d Block %d Page, Skipped\r\n"), dwBlock, 0)); dwBlock++; continue; } else { break; } } else { OALMSG(TRUE, (TEXT("Bad Block %d Skipped\r\n"), dwBlock)); dwBlock++; continue; } } // is it a valid TOC? if ( !VALID_TOC(g_pTOC) ) { EdbgOutputDebugString("TOC_Read ERROR: INVALID_TOC Signature: 0x%x\r\n", g_pTOC->dwSignature); return FALSE; } // update our boot config g_pBootCfg = &g_pTOC->BootCfg; // update our index g_dwTocEntry = g_pBootCfg->ImageIndex; // debugger enabled? g_bWaitForConnect = (g_pBootCfg->ConfigFlags & CONFIG_FLAGS_DEBUGGER) ? TRUE : FALSE; // cache image type g_ImageType = g_pTOC->id[g_dwTocEntry].dwImageType; EdbgOutputDebugString("-TOC_Read\r\n"); return TRUE; } // // Store TOC to Nand // BUGBUG: only uses 1 sector for now. // BOOL TOC_Write(void) { LowFuncTbl *pLowFuncTbl; DWORD dwBlock; INT32 nRet; UINT8 *pSBuf; UINT32 nSyncRet; EdbgOutputDebugString("+TOC_Write\r\n"); if ( !g_bBootMediaExist ) { EdbgOutputDebugString("TOC_Write WARN: no boot media\r\n"); return FALSE; } // is it a valid TOC? if ( !VALID_TOC(g_pTOC)) { EdbgOutputDebugString("TOC_Write ERROR: INVALID_TOC Signature: 0x%x\r\n", g_pTOC->dwSignature); return FALSE; } // is it a valid image descriptor? if ( !VALID_IMAGE_DESCRIPTOR(&g_pTOC->id[g_dwTocEntry]) ) { EdbgOutputDebugString("TOC_Write ERROR: INVALID_IMAGE[%u] Signature: 0x%x\r\n", g_dwTocEntry, g_pTOC->id[g_dwTocEntry].dwSignature); return FALSE; } pLowFuncTbl = FIL_GetFuncTbl(); memset(WMRBuf, '\0', WMRBUFSIZE); pSBuf = WMRBuf + BYTES_PER_MAIN_SUPAGE; dwBlock = TOC_BLOCK; while(1) { if (dwBlock == (TOC_BLOCK+TOC_BLOCK_SIZE+TOC_BLOCK_RESERVED)) { OALMSG(TRUE, (TEXT("TOC_Write Failed !!!\r\n"))); OALMSG(TRUE, (TEXT("Too many Bad Block\r\n"))); return FALSE; } IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuLEFT_PLANE_BITMAP, NULL, pSBuf, TRUE32, FALSE32); IS_CHECK_SPARE_ECC = TRUE32; if (pSBuf[0] == 0xff) { pLowFuncTbl->Erase(0, dwBlock, enuLEFT_PLANE_BITMAP); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if ( nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Erase Error @ %d block, Skipped\r\n"), dwBlock)); goto MarkAndSkipBadBlock; } pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK, 0x01, enuLEFT_PLANE_BITMAP, (UINT8 *)g_pTOC, NULL); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d Block %d Page, Skipped\r\n"), dwBlock, 0)); goto MarkAndSkipBadBlock; } nRet = pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK, 0x01, enuLEFT_PLANE_BITMAP, toc, NULL, FALSE32, FALSE32); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Read Error @ %d Block %d Page, Skipped\r\n"), dwBlock, 0)); goto MarkAndSkipBadBlock; } if (0 != memcmp(toc, (UINT8 *)g_pTOC, SECTOR_SIZE)) { OALMSG(TRUE, (TEXT("[ERR] Verify Error @ %d Block %d Page, Skipped\r\n"), dwBlock, 0)); goto MarkAndSkipBadBlock; } OALMSG(TRUE, (TEXT("[OK] Write %d th Block Success\r\n"), dwBlock)); break; MarkAndSkipBadBlock: pLowFuncTbl->Erase(0, dwBlock, enuLEFT_PLANE_BITMAP); memset(pSBuf, 0x0, BYTES_PER_SPARE_PAGE); IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuLEFT_PLANE_BITMAP, NULL, pSBuf); IS_CHECK_SPARE_ECC = TRUE32; dwBlock++; continue; } else { OALMSG(TRUE, (TEXT("Bad Block %d Skipped\r\n"), dwBlock)); dwBlock++; continue; } } EdbgOutputDebugString("-TOC_Write\r\n"); return TRUE; } extern DWORD g_dwMBRSectorNum; /* @func BOOL | WriteOSImageToBootMedia | Stores the image cached in RAM to the Boot Media. The image may be comprised of one or more BIN regions. @rdesc TRUE = Success, FALSE = Failure. @comm @xref */ BOOL WriteOSImageToBootMedia(DWORD dwImageStart, DWORD dwImageLength, DWORD dwLaunchAddr) { BYTE nCount; DWORD dwNumExts; PXIPCHAIN_SUMMARY pChainInfo = NULL; EXTENSION *pExt = NULL; DWORD dwBINFSPartLength = 0; HANDLE hPart; DWORD dwStoreOffset; DWORD dwMaxRegionLength[BL_MAX_BIN_REGIONS] = {0}; DWORD dwChainStart, dwChainLength; DWORD dwBlock; DWORD nBlockNum; // DWORD checksum = 0; // Initialize the variables dwChainStart = dwChainLength = 0; OALMSG(OAL_FUNC, (TEXT("+WriteOSImageToBootMedia\r\n"))); OALMSG(TRUE, (TEXT("+WriteOSImageToBootMedia: g_dwTocEntry =%d, ImageStart: 0x%x, ImageLength: 0x%x, LaunchAddr:0x%x\r\n"), g_dwTocEntry, dwImageStart, dwImageLength, dwLaunchAddr)); if ( !g_bBootMediaExist ) { OALMSG(OAL_ERROR, (TEXT("ERROR: WriteOSImageToBootMedia: device doesn't exist.\r\n"))); return(FALSE); } if (g_ImageType == IMAGE_TYPE_RAMIMAGE) { g_dwMBRSectorNum = BLOCK_TO_SECTOR(IMAGE_START_BLOCK); OALMSG(TRUE, (TEXT("g_dwMBRSectorNum = 0x%x\r\n"), g_dwMBRSectorNum)); dwBlock = IMAGE_START_BLOCK; //by hmseo - 20061124 This block is to MBR // dwImageStart += dwLaunchAddr; // dwImageLength = dwImageLength; //step loader can support 4k bytes only. NO SuperIPL case is 16K....... 3 Block } RETAILMSG(1,(TEXT("Erase Block from 0x%x, to 0x%x \n"), dwBlock, SPECIAL_AREA_START + SPECIAL_AREA_SIZE - 1)); for (nBlockNum = dwBlock ; nBlockNum < SPECIAL_AREA_START + SPECIAL_AREA_SIZE; nBlockNum++) { if (!FMD_EraseBlock(nBlockNum)) { return(FALSE); } } if ( !VALID_TOC(g_pTOC) ) { OALMSG(OAL_WARN, (TEXT("WARN: WriteOSImageToBootMedia: INVALID_TOC\r\n"))); if ( !TOC_Init(g_dwTocEntry, g_ImageType, dwImageStart, dwImageLength, dwLaunchAddr) ) { OALMSG(OAL_ERROR, (TEXT("ERROR: INVALID_TOC\r\n"))); return(FALSE); } } // Look in the kernel region's extension area for a multi-BIN extension descriptor. // This region, if found, details the number, start, and size of each BIN region. // for (nCount = 0, dwNumExts = 0 ; (nCount < g_BINRegionInfo.dwNumRegions); nCount++) { // Does this region contain nk.exe and an extension pointer? // pExt = (EXTENSION *)GetKernelExtPointer(g_BINRegionInfo.Region[nCount].dwRegionStart, g_BINRegionInfo.Region[nCount].dwRegionLength ); if ( pExt != NULL) { // If there is an extension pointer region, walk it until the end. // while (pExt) { DWORD dwBaseAddr = g_BINRegionInfo.Region[nCount].dwRegionStart; pExt = (EXTENSION *)OEMMapMemAddr(dwBaseAddr, (DWORD)pExt); OALMSG(OAL_INFO, (TEXT("INFO: OEMLaunch: Found chain extenstion: '%s' @ 0x%x\r\n"), pExt->name, dwBaseAddr)); if ((pExt->type == 0) && !strcmp(pExt->name, "chain information")) { pChainInfo = (PXIPCHAIN_SUMMARY) OEMMapMemAddr(dwBaseAddr, (DWORD)pExt->pdata); dwNumExts = (pExt->length / sizeof(XIPCHAIN_SUMMARY)); OALMSG(OAL_INFO, (TEXT("INFO: OEMLaunch: Found 'chain information' (pChainInfo=0x%x Extensions=0x%x).\r\n"), (DWORD)pChainInfo, dwNumExts)); break; } pExt = (EXTENSION *)pExt->pNextExt; } } else { // Search for Chain region. Chain region doesn't have the ROMSIGNATURE set DWORD dwRegionStart = g_BINRegionInfo.Region[nCount].dwRegionStart; DWORD dwSig = *(LPDWORD) OEMMapMemAddr(dwRegionStart, dwRegionStart + ROM_SIGNATURE_OFFSET); if ( dwSig != ROM_SIGNATURE) { // It is the chain dwChainStart = dwRegionStart; dwChainLength = g_BINRegionInfo.Region[nCount].dwRegionLength; OALMSG(TRUE, (TEXT("Found the Chain region: StartAddress: 0x%X; Length: 0x%X\n"), dwChainStart, dwChainLength)); } } } // Determine how big the Total BINFS partition needs to be to store all of this. // if (pChainInfo && dwNumExts == g_BINRegionInfo.dwNumRegions) // We're downloading all the regions in a multi-region image... { DWORD i; OALMSG(TRUE, (TEXT("Writing multi-regions\r\n"))); for (nCount = 0, dwBINFSPartLength = 0 ; nCount < dwNumExts ; nCount++) { dwBINFSPartLength += (pChainInfo + nCount)->dwMaxLength; OALMSG(OAL_ERROR, (TEXT("BINFSPartMaxLength[%u]: 0x%x, TtlBINFSPartLength: 0x%x \r\n"), nCount, (pChainInfo + nCount)->dwMaxLength, dwBINFSPartLength)); // MultiBINInfo does not store each Regions MAX length, and pChainInfo is not in any particular order. // So, walk our MultiBINInfo matching up pChainInfo to find each regions MAX Length for (i = 0; i < dwNumExts; i++) { if ( g_BINRegionInfo.Region[i].dwRegionStart == (DWORD)((pChainInfo + nCount)->pvAddr) ) { dwMaxRegionLength[i] = (pChainInfo + nCount)->dwMaxLength; OALMSG(TRUE, (TEXT("dwMaxRegionLength[%u]: 0x%x \r\n"), i, dwMaxRegionLength[i])); break; } } } } else // A single BIN file or potentially a multi-region update (but the partition's already been created in this latter case). { dwBINFSPartLength = g_BINRegionInfo.Region[0].dwRegionLength; OALMSG(TRUE, (TEXT("Writing single region/multi-region update, dwBINFSPartLength: %u \r\n"), dwBINFSPartLength)); } OALMSG(TRUE, (TEXT("dwBlock = %d \n"), dwBlock)); // Open/Create the BINFS partition where images are stored. This partition starts immediately after the MBR on the Boot Media and its length is // determined by the maximum image size (or sum of all maximum sizes in a multi-region design). // Parameters are LOGICAL sectors. // hPart = BP_OpenPartition( (dwBlock)*(PAGES_PER_SUBLK)*(SECTORS_PER_SUPAGE), //SECTOR_TO_BLOCK_SIZE(FILE_TO_SECTOR_SIZE(dwBINFSPartLength))*PAGES_PER_BLOCK, // align to block //(dwBINFSPartLength/SECTOR_SIZE)+1, SECTOR_TO_BLOCK_SIZE(FILE_TO_SECTOR_SIZE(dwBINFSPartLength))*SECTORS_PER_SUBLK + (IMAGE_START_BLOCK+1)*SECTORS_PER_SUBLK, // hmseo for whimory... +1 is for MBR PART_BINFS, TRUE, PART_OPEN_ALWAYS); if (hPart == INVALID_HANDLE_VALUE ) { OALMSG(OAL_ERROR, (TEXT("ERROR: WriteOSImageToBootMedia: Failed to open/create partition.\r\n"))); return(FALSE); } for (nCount = 0, dwStoreOffset = 0; nCount < g_BINRegionInfo.dwNumRegions ; nCount++) { DWORD dwRegionStart = (DWORD)OEMMapMemAddr(0, g_BINRegionInfo.Region[nCount].dwRegionStart); DWORD dwRegionLength = g_BINRegionInfo.Region[nCount].dwRegionLength; // No concern about Multiple XIP // nCount = 0; OALMSG(TRUE, (TEXT("nCount = %d \n"), nCount)); // Media byte offset where image region is stored. dwStoreOffset += nCount ? dwMaxRegionLength[nCount-1] : 0; // dwStoreOffset = 0; // Set the file pointer (byte indexing) to the correct offset for this particular region. // if ( !BP_SetDataPointer(hPart, dwStoreOffset + (dwBlock+1)*BYTES_PER_SECTOR*SECTORS_PER_SUBLK) ) { OALMSG(OAL_ERROR, (TEXT("ERROR: StoreImageToBootMedia: Failed to set data pointer in partition (offset=0x%x).\r\n"), dwStoreOffset)); return(FALSE); } // Write the region to the BINFS partition. // if ( !BP_WriteData(hPart, (LPBYTE)dwRegionStart, dwRegionLength) ) { EdbgOutputDebugString("ERROR: StoreImageToBootMedia: Failed to write region to BINFS partition (start=0x%x, length=0x%x).\r\n", dwRegionStart, dwRegionLength); return(FALSE); } // update our TOC? // if ((g_pTOC->id[g_dwTocEntry].dwLoadAddress == g_BINRegionInfo.Region[nCount].dwRegionStart) && g_pTOC->id[g_dwTocEntry].dwTtlSectors == FILE_TO_SECTOR_SIZE(dwRegionLength) ) { g_pTOC->id[g_dwTocEntry].dwStoreOffset = dwStoreOffset; g_pTOC->id[g_dwTocEntry].dwJumpAddress = 0; // Filled upon return to OEMLaunch g_pTOC->id[g_dwTocEntry].dwImageType = g_ImageType; g_pTOC->id[g_dwTocEntry].sgList[0].dwSector = FILE_TO_SECTOR_SIZE(g_dwLastWrittenLoc); g_pTOC->id[g_dwTocEntry].sgList[0].dwLength = g_pTOC->id[g_dwTocEntry].dwTtlSectors; // copy Kernel Region to SDRAM for jump // memcpy((void*)g_pTOC->id[g_dwTocEntry].dwLoadAddress, (void*)dwRegionStart, dwRegionLength); OALMSG(TRUE, (TEXT("Updateded TOC!\r\n"))); } else if( (dwChainStart == g_BINRegionInfo.Region[nCount].dwRegionStart) && (dwChainLength == g_BINRegionInfo.Region[nCount].dwRegionLength)) { // Update our TOC for Chain region g_pTOC->chainInfo.dwLoadAddress = dwChainStart; g_pTOC->chainInfo.dwFlashAddress = FILE_TO_SECTOR_SIZE(g_dwLastWrittenLoc); g_pTOC->chainInfo.dwLength = FILE_TO_SECTOR_SIZE(dwMaxRegionLength[nCount]); OALMSG(TRUE, (TEXT("Written Chain Region to the Flash\n"))); OALMSG(TRUE, (TEXT("LoadAddress = 0x%X; FlashAddress = 0x%X; Length = 0x%X\n"), g_pTOC->chainInfo.dwLoadAddress, g_pTOC->chainInfo.dwFlashAddress, g_pTOC->chainInfo.dwLength)); OALMSG(TRUE, (TEXT(" memcpy : g_pTOC->chainInfo.dwLoadAddress = 0x%X; dwRegionStart = 0x%X; dwRegionLength = 0x%X\n"), g_pTOC->chainInfo.dwLoadAddress, dwRegionStart, dwRegionLength)); // Now copy it to the SDRAM // by hmseo.... ???? 061125 //memcpy((void *)g_pTOC->chainInfo.dwLoadAddress, (void *)dwRegionStart, dwRegionLength); } } OALMSG(TRUE, (TEXT("-WriteOSImageToBootMedia\r\n"))); return(TRUE); } /* @func BOOL | ReadKernelRegionFromBootMedia | BinFS support. Reads the kernel region from Boot Media into RAM. The kernel region is fixed up to run from RAM and this is done just before jumping to the kernel entry point. @rdesc TRUE = Success, FALSE = Failure. @comm @xref */ BOOL ReadOSImageFromBootMedia() { OALMSG(OAL_FUNC, (TEXT("+ReadOSImageFromBootMedia\r\n"))); OALMSG(TRUE, (TEXT("+ReadOSImageFromBootMedia\r\n"))); if (!g_bBootMediaExist) { OALMSG(OAL_ERROR, (TEXT("ERROR: ReadOSImageFromBootMedia: device doesn't exist.\r\n"))); return(FALSE); } if ( !VALID_TOC(g_pTOC) ) { OALMSG(OAL_ERROR, (TEXT("ERROR: ReadOSImageFromBootMedia: INVALID_TOC\r\n"))); return(FALSE); } if ( !VALID_IMAGE_DESCRIPTOR(&g_pTOC->id[g_dwTocEntry]) ) { OALMSG(OAL_ERROR, (TEXT("ReadOSImageFromBootMedia: ERROR_INVALID_IMAGE_DESCRIPTOR: 0x%x\r\n"), g_pTOC->id[g_dwTocEntry].dwSignature)); return FALSE; } if ( !OEMVerifyMemory(g_pTOC->id[g_dwTocEntry].dwLoadAddress, sizeof(DWORD)) || !OEMVerifyMemory(g_pTOC->id[g_dwTocEntry].dwJumpAddress, sizeof(DWORD)) || !g_pTOC->id[g_dwTocEntry].dwTtlSectors ) { OALMSG(OAL_ERROR, (TEXT("ReadOSImageFromBootMedia: ERROR_INVALID_ADDRESS: (address=0x%x, sectors=0x%x, launch address=0x%x)...\r\n"), g_pTOC->id[g_dwTocEntry].dwLoadAddress, g_pTOC->id[g_dwTocEntry].dwTtlSectors, g_pTOC->id[g_dwTocEntry].dwJumpAddress)); return FALSE; } { DWORD dwStartPage, dwNumPage, dwPage; Buffer InBuf; DWORD dwRegionStart = (DWORD)((g_pTOC->id[g_dwTocEntry].dwLoadAddress) | CACHED_TO_UNCACHED_OFFSET); DWORD dwRegionLength = SECTOR_TO_FILE_SIZE(g_pTOC->id[g_dwTocEntry].dwTtlSectors); dwStartPage = (IMAGE_START_BLOCK+1)*(PAGES_PER_SUBLK); dwNumPage = (dwRegionLength-1)/BYTES_PER_MAIN_SUPAGE+1; OALMSG(TRUE, (TEXT("Read OS image to BootMedia \r\n"))); OALMSG(TRUE, (TEXT("ImageLength = %d Byte, dwRegionStart : %08x \r\n"), dwRegionLength,dwRegionStart)); OALMSG(TRUE, (TEXT("Start Page = %d, End Page = %d, Page Count = %d\r\n"), dwStartPage, dwStartPage+dwNumPage-1, dwNumPage)); InBuf.pData = (unsigned char *)dwRegionStart; InBuf.pSpare = NULL; InBuf.nBank = 0; if ( TWO_PLANE_PROGRAM == TRUE32 ) { InBuf.nBitmap = FULL_SECTOR_BITMAP_PAGE; } else { InBuf.nBitmap = LEFT_SECTOR_BITMAP_PAGE; } InBuf.eStatus = BUF_AUX; // No need to sync for (dwPage = dwStartPage; dwPage < dwStartPage+dwNumPage; dwPage++) { if (VFL_Read(dwPage, &InBuf, FALSE32) != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] VFL Read Error @ %d page\r\n"), dwPage)); OALMSG(TRUE, (TEXT("Read OS image to BootMedia Failed !!!\r\n"))); while(1); } InBuf.pData += BYTES_PER_MAIN_SUPAGE; if (dwPage%PAGES_PER_BLOCK == (PAGES_PER_BLOCK-1)) OALMSG(TRUE, (TEXT("."))); } OALMSG(TRUE, (TEXT("\r\nRead OS image to BootMedia Success \r\n"))); } OALMSG(OAL_FUNC, (TEXT("_ReadOSImageFromBootMedia\r\n"))); return(TRUE); } BOOL ReadBlock(DWORD dwBlock, LPBYTE pbBlock, PSectorInfo pSectorInfoTable) { #if 0 for (int iSector = 0; iSector < g_FlashInfo.wSectorsPerBlock; iSector++) { if (!FMD_ReadSector(dwBlock * g_FlashInfo.wSectorsPerBlock + iSector, pbBlock, pSectorInfoTable, 1)) return FALSE; if (pbBlock) pbBlock += g_FlashInfo.wDataBytesPerSector; if (pSectorInfoTable) pSectorInfoTable++; } #else if (!FMD_ReadSector(dwBlock * g_FlashInfo.wSectorsPerBlock, pbBlock, /*pSectorInfoTable*/NULL, g_FlashInfo.wSectorsPerBlock)) // hmseo-061028 return FALSE; #endif return TRUE; } BOOL WriteBlock(DWORD dwBlock, LPBYTE pbBlock, PSectorInfo pSectorInfoTable) { #if 0 for (int iSector = 0; iSector < g_FlashInfo.wSectorsPerBlock; iSector++) { if (!FMD_WriteSector(dwBlock * g_FlashInfo.wSectorsPerBlock + iSector, pbBlock, /*pSectorInfoTable*/NULL, 1)) // hmseo-061028 return FALSE; if (pbBlock) pbBlock += g_FlashInfo.wDataBytesPerSector; if (pSectorInfoTable) pSectorInfoTable++; } #else if (!FMD_WriteSector(dwBlock * g_FlashInfo.wSectorsPerBlock, pbBlock, /*pSectorInfoTable*/NULL, g_FlashInfo.wSectorsPerBlock)) // hmseo-061028 return FALSE; #endif return TRUE; } static UCHAR WMRBuf[WMRBUFSIZE]; static UCHAR BadInfoBuf[4096+128]; BOOL WriteRawImageToBootMedia(DWORD dwImageStart, DWORD dwImageLength, DWORD dwLaunchAddr) { LowFuncTbl *pLowFuncTbl; UINT32 dwStartPage, dwNumPage, dwPage; UINT32 dwStartBlock, dwNumBlock, dwBlock; UINT32 dwPageOffset; INT32 nRet; BOOL32 bIsBadBlock = FALSE32; UINT32 nSyncRet; LPBYTE pbBuffer; OALMSG(OAL_FUNC, (TEXT("+WriteRawImageToBootMedia\r\n"))); if ( !g_bBootMediaExist ) { OALMSG(OAL_ERROR, (TEXT("ERROR: WriteRawImageToBootMedia: device doesn't exist.\r\n"))); return(FALSE); } if (g_ImageType == IMAGE_TYPE_LOADER) { UINT8 *pMBuf; UINT8 *pSBuf; pbBuffer = OEMMapMemAddr(dwImageStart, dwImageStart); dwStartBlock = EBOOT_BLOCK; dwNumBlock = (dwImageLength-1)/(BYTES_PER_MAIN_SUPAGE*PAGES_PER_BLOCK)+1; if ( !VALID_TOC(g_pTOC) ) { OALMSG(OAL_WARN, (TEXT("WARN: WriteRawImageToBootMedia: INVALID_TOC\r\n"))); if ( !TOC_Init(g_dwTocEntry, g_ImageType, dwImageStart, dwImageLength, dwLaunchAddr) ) { OALMSG(OAL_ERROR, (TEXT("ERROR: INVALID_TOC\r\n"))); return(FALSE); } } OALMSG(TRUE, (TEXT("Write Eboot image to BootMedia \r\n"))); OALMSG(TRUE, (TEXT("ImageLength = %d Byte \r\n"), dwImageLength)); OALMSG(TRUE, (TEXT("Start Block = %d, End Block = %d, Block Count = %d\r\n"), dwStartBlock, dwStartBlock+dwNumBlock-1, dwNumBlock)); pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; dwBlock = dwStartBlock; while(dwNumBlock > 0) { if (dwBlock == (EBOOT_BLOCK+EBOOT_BLOCK_SIZE+EBOOT_BLOCK_RESERVED)) { OALMSG(TRUE, (TEXT("Write RAW image to BootMedia Failed !!!\r\n"))); OALMSG(TRUE, (TEXT("Too many Bad Block\r\n"))); return(FALSE); } IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuBOTH_PLANE_BITMAP, NULL, pSBuf, TRUE32, FALSE32); IS_CHECK_SPARE_ECC = TRUE32; if (TWO_PLANE_PROGRAM == TRUE32) { if (pSBuf[0] == 0xff && pSBuf[BYTES_PER_SPARE_PAGE] == 0xff) bIsBadBlock = TRUE32; } else { if (pSBuf[0] == 0xff) bIsBadBlock = TRUE32; } if (bIsBadBlock) { pLowFuncTbl->Erase(0, dwBlock, enuBOTH_PLANE_BITMAP); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if ( nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Erase Error @ %d block, Skipped\r\n"), dwBlock)); goto MarkAndSkipBadBlock; } for (dwPageOffset=0; dwPageOffset<PAGES_PER_BLOCK; dwPageOffset++) { pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK+dwPageOffset, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pbBuffer+BYTES_PER_MAIN_SUPAGE*dwPageOffset, NULL); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } nRet = pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+dwPageOffset, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pMBuf, NULL, FALSE32, FALSE32); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Read Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } if (0 != memcmp(pbBuffer+BYTES_PER_MAIN_SUPAGE*dwPageOffset, pMBuf, BYTES_PER_MAIN_SUPAGE)) { OALMSG(TRUE, (TEXT("[ERR] Verify Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } } OALMSG(TRUE, (TEXT("[OK] Write %d th Block Success\r\n"), dwBlock)); dwBlock++; dwNumBlock--; pbBuffer += BYTES_PER_MAIN_SUPAGE*PAGES_PER_BLOCK; continue; MarkAndSkipBadBlock: pLowFuncTbl->Erase(0, dwBlock, enuBOTH_PLANE_BITMAP); memset(pSBuf, 0x0, BYTES_PER_SPARE_SUPAGE); IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuBOTH_PLANE_BITMAP, NULL, pSBuf); IS_CHECK_SPARE_ECC = TRUE32; dwBlock++; continue; } else { OALMSG(TRUE, (TEXT("Bad Block %d Skipped\r\n"), dwBlock)); dwBlock++; continue; } } OALMSG(TRUE, (TEXT("Write Eboot image to BootMedia Success\r\n"))); } else if (g_ImageType == IMAGE_TYPE_STEPLDR) { BOOL bFormatted = FALSE; UINT32 nSctBitmap; UINT32 nBufCnt; UINT32 nCnt; pLowFuncTbl = FIL_GetFuncTbl(); nRet = pLowFuncTbl->Read(0, PAGES_PER_BLOCK - 1, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, WMRBuf, WMRBuf+BYTES_PER_MAIN_SUPAGE, TRUE32, TRUE32); if (nRet == FIL_SUCCESS_CLEAN || nRet == FIL_U_ECC_ERROR) // WMR Not formatted { bFormatted = FALSE; } else { OALMSG(TRUE, (TEXT("VFL Already Formatted\r\n"))); nRet = pLowFuncTbl->Read(0, PAGES_PER_BLOCK-2, LEFT_SECTOR_BITMAP_PAGE, enuLEFT_PLANE_BITMAP, BadInfoBuf, NULL, FALSE32, FALSE32); if (nRet == FIL_SUCCESS) { bFormatted = TRUE; } else { OALMSG(TRUE, (TEXT("VFL Formatted... But There is no Initial Bad Block Infomation -> Clear VFL Signiture\r\n"))); bFormatted = FALSE; } } pbBuffer = OEMMapMemAddr(dwImageStart, dwImageStart); dwStartPage = 0; dwNumPage = (dwImageLength)/(BYTES_PER_MAIN_PAGE)+((dwImageLength%BYTES_PER_MAIN_PAGE)? 1 : 0); if (SECTORS_PER_PAGE == 8) dwNumPage++; // page No. 0 and 1 use only 2KByte/Page, so add 1 page. OALMSG(TRUE, (TEXT("Write Steploader (NBL1+NBL2) image to BootMedia dwNumPage : %d \r\n"),dwNumPage)); OALMSG(TRUE, (TEXT("ImageLength = %d Byte \r\n"), dwImageLength)); OALMSG(TRUE, (TEXT("Start Page = %d, End Page = %d, Page Count = %d\r\n"), dwStartPage, dwStartPage+dwNumPage-1, dwNumPage)); for (dwPage = dwStartPage, nCnt = 0; nCnt < dwNumPage; nCnt++) { if (dwPage < 2 || IS_SLC) { if(BYTES_PER_MAIN_PAGE == 2048)//for 2Kpage { nSctBitmap = 0xf; nBufCnt = BYTES_PER_SECTOR*4; } else if(BYTES_PER_MAIN_PAGE == 4096)//for 4Kpage { nSctBitmap = 0xff; nBufCnt = BYTES_PER_SECTOR*8; } } else { nSctBitmap = LEFT_SECTOR_BITMAP_PAGE; nBufCnt = BYTES_PER_MAIN_PAGE; } if (dwPage%PAGES_PER_BLOCK == 0) { pLowFuncTbl->Erase(0, dwPage/PAGES_PER_BLOCK, enuBOTH_PLANE_BITMAP); if (pLowFuncTbl->Sync(0, &nSyncRet) != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Erase Error @ %d block\r\n"), dwPage/PAGES_PER_BLOCK)); OALMSG(TRUE, (TEXT("Write Steploader image to BootMedia Failed !!!\r\n"))); return FALSE; } } OALMSG(OAL_FUNC, (TEXT(" dwPage = 0x%x, pbBuffer = 0x%x \r\n"), dwPage, pbBuffer)); if (dwPage < PAGES_PER_BLOCK-2) { pLowFuncTbl->Steploader_Write(0, dwPage, nSctBitmap, enuLEFT_PLANE_BITMAP, pbBuffer, NULL); // pLowFuncTbl->Write(0, dwPage, nSctBitmap, enuLEFT_PLANE_BITMAP, pbBuffer, NULL); } else { OALMSG(TRUE, (TEXT("Cannot Write image on page %d (Reserved area) !!!\r\n"), dwPage)); return FALSE; } if (pLowFuncTbl->Sync(0, &nSyncRet) != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d page\r\n"), dwPage)); OALMSG(TRUE, (TEXT("Write Steploader image to BootMedia Failed !!!\r\n"))); return FALSE; } // write pages with 0, 1 and 6 to PAGES_PER_BLOCK-3 dwPage++; if(BYTES_PER_MAIN_PAGE == 2048)//for 2Kpage { if (IS_MLC && dwPage >= 4 && dwPage < 10) dwPage = 10; //for 8K Stepping stone } else if(BYTES_PER_MAIN_PAGE == 4096)//for 4Kpage { if (IS_MLC && dwPage >= 2 && dwPage < 10) dwPage = 10; //for 8K Stepping stone } pbBuffer += nBufCnt; } // Write WMR Data (last page of block 0) if (bFormatted) { pLowFuncTbl->Write(0, PAGES_PER_BLOCK-2, LEFT_SECTOR_BITMAP_PAGE, enuLEFT_PLANE_BITMAP, BadInfoBuf, NULL); if (pLowFuncTbl->Sync(0, &nSyncRet) != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d page\r\n"), PAGES_PER_BLOCK-2)); OALMSG(TRUE, (TEXT("Write Steploader image to BootMedia Failed !!!\r\n"))); return FALSE; } else { pLowFuncTbl->Write(0, PAGES_PER_BLOCK-1, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, WMRBuf, WMRBuf+BYTES_PER_MAIN_SUPAGE); if (pLowFuncTbl->Sync(0, &nSyncRet) != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d page\r\n"), PAGES_PER_BLOCK-1)); OALMSG(TRUE, (TEXT("Write Steploader image to BootMedia Failed !!!\r\n"))); return FALSE; } } } OALMSG(TRUE, (TEXT("Write Steploader image to BootMedia Success\r\n"))); } if (g_ImageType == IMAGE_TYPE_LOADER) { g_pTOC->id[0].dwLoadAddress = dwImageStart; g_pTOC->id[0].dwJumpAddress = 0; g_pTOC->id[0].dwTtlSectors = FILE_TO_SECTOR_SIZE(dwImageLength); g_pTOC->id[0].sgList[0].dwSector = BLOCK_TO_SECTOR(EBOOT_BLOCK); g_pTOC->id[0].sgList[0].dwLength = g_pTOC->id[0].dwTtlSectors; } OALMSG(OAL_FUNC, (TEXT("_WriteRawImageToBootMedia\r\n"))); return TRUE; } //================================================== //[david.modify] 2008-05-07 17:55 // 增加一函数,可以直接写BLOCK0IMG.NB0, EBOOT.BIN文件到NAND上 //================================ extern "C" BOOL g_bDownloadImage ; void MLC_TEST_DAVID() { DWORD dwImageStart, dwImageLength, dwLaunchAddr; BOOL bRet = 0; UINT32 u32Tmp[4]={0}; UINT8 u8Temp; dwImageStart = FLSCACHE_VIRTADDR; dwImageLength = 0x20000; dwLaunchAddr = 0x0; while(1){ EPRINT("block0img==0; eboot.nb0==80038000\r\n"); EPRINT ( "1)write block0img.nb0 (0x%x) \r\n", STEPLDR_RAM_IMAGE_BASE); EPRINT ( "2)write eboot.nb0 (0x%x) \r\n", EBOOT_RAM_IMAGE_BASE ); // EPRINT ( "3)write nk.nb0 (0x%x) \r\n", OS_RAM_IMAGE_BASE ); // EPRINT ( "4)write nk.nb0 (OEMLaunch) (0x%x) \r\n", OS_RAM_IMAGE_BASE ); EPRINT ( "0)exit \r\n"); EPRINT ( "Please select: "); u8Temp = ReadSerialByte(); if('0'==u8Temp) { return; } else if('1'==u8Temp){ scanf_david("dwImageStart= %x:\r\n", &u32Tmp[0]); scanf_david("dwImageLength= %x:\r\n", &u32Tmp[1]); scanf_david("dwLaunchAddr= %x:\r\n", &u32Tmp[2]); dwImageStart = u32Tmp[0]; // 0 - 写 IMAGE_TYPE_STEPLDR dwImageLength = u32Tmp[1]; dwLaunchAddr = u32Tmp[2]; DPNOK(dwImageStart); DPNOK(dwImageLength); DPNOK(dwLaunchAddr); g_ImageType = IMAGE_TYPE_STEPLDR; EPRINT ( "1-WriteRawImageToBootMedia, 0-cancel\r\n "); u8Temp = ReadSerialByte(); if('1'==u8Temp) { bRet = WriteRawImageToBootMedia(dwImageStart, dwImageLength, dwLaunchAddr); DPNOK(bRet); } } else if('2'==u8Temp){ scanf_david("dwImageStart= %x:\r\n", &u32Tmp[0]); scanf_david("dwImageLength= %x:\r\n", &u32Tmp[1]); scanf_david("dwLaunchAddr= %x:\r\n", &u32Tmp[2]); dwImageStart = u32Tmp[0]; // 0 - 写 IMAGE_TYPE_STEPLDR dwImageLength = u32Tmp[1]; dwLaunchAddr = u32Tmp[2]; DPNOK(dwImageStart); DPNOK(dwImageLength); DPNOK(dwLaunchAddr); g_ImageType = IMAGE_TYPE_LOADER; EPRINT ( "1-WriteRawImageToBootMedia, 0-cancel\r\n "); u8Temp = ReadSerialByte(); if('1'==u8Temp) { bRet = WriteRawImageToBootMedia(dwImageStart, dwImageLength, dwLaunchAddr); DPNOK(bRet); } } else if('3'==u8Temp){ scanf_david("dwImageStart= %x:\r\n", &u32Tmp[0]); scanf_david("dwImageLength= %x:\r\n", &u32Tmp[1]); scanf_david("dwLaunchAddr= %x:\r\n", &u32Tmp[2]); dwImageStart = u32Tmp[0]; // 0 - 写 IMAGE_TYPE_STEPLDR dwImageLength = u32Tmp[1]; dwLaunchAddr = u32Tmp[2]; DPNOK(dwImageStart); DPNOK(dwImageLength); DPNOK(dwLaunchAddr); g_ImageType = IMAGE_TYPE_RAMIMAGE; EPRINT ( "1-WriteOSImageToBootMedia, 0-cancel\r\n "); u8Temp = ReadSerialByte(); if('1'==u8Temp) { bRet = WriteOSImageToBootMedia(dwImageStart, dwImageLength, dwLaunchAddr); DPNOK(bRet); } }else if('4'==u8Temp){ scanf_david("dwImageStart= %x:\r\n", &u32Tmp[0]); scanf_david("dwImageLength= %x:\r\n", &u32Tmp[1]); scanf_david("dwLaunchAddr= %x:\r\n", &u32Tmp[2]); dwImageStart = u32Tmp[0]; // 0 - 写 IMAGE_TYPE_STEPLDR dwImageLength = u32Tmp[1]; dwLaunchAddr = u32Tmp[2]; DPNOK(dwImageStart); DPNOK(dwImageLength); DPNOK(dwLaunchAddr); g_ImageType = IMAGE_TYPE_RAMIMAGE; EPRINT ( "1-OEMLaunch, 0-cancel\r\n "); u8Temp = ReadSerialByte(); if('1'==u8Temp) { // (5) final call to launch the image. never returned DPNOK(g_ImageType); g_bDownloadImage = TRUE; g_pBootCfg->ConfigFlags|=TARGET_TYPE_NAND; OEMLaunch (dwImageStart, dwImageLength, dwLaunchAddr, (const ROMHDR *)0); } } } } static DWORD GetDecimalNumber(void) { DWORD dwNumber = 0; int InChar = 0; while(!((InChar == 0x0d) || (InChar == 0x0a))) { InChar = OEMReadDebugByte(); if (InChar != OEM_DEBUG_COM_ERROR && InChar != OEM_DEBUG_READ_NODATA) { if ((InChar >= '0' && InChar <= '9')) { dwNumber = dwNumber*10; dwNumber = dwNumber+(InChar-'0'); OEMWriteDebugByte((BYTE)InChar); } else if (InChar == 8) // If it's a backspace, back up. { dwNumber = dwNumber/10; OEMWriteDebugByte((BYTE)InChar); } } } OEMWriteDebugByte('\n'); OEMWriteDebugByte('\r'); return dwNumber; } static void MLC_Print_Page_Data(unsigned char *pMBuf, unsigned char *pSBuf) { unsigned int i, j; if (pMBuf != NULL) { OALMSG(TRUE, (TEXT("Main Data\r\n"))); for (j = 0; j < SECTORS_PER_PAGE; j++) { OALMSG(TRUE, (TEXT("================================================= Sector %d\n"), j)); for (i = (BYTES_PER_SECTOR * j); i < (BYTES_PER_SECTOR * (j+1)); i++) { OALMSG(TRUE, (TEXT("%02x "), pMBuf[i])); if (i%BYTES_PER_SPARE == 15) OALMSG(TRUE, (TEXT("\n"))); } } #if 1 if (TWO_PLANE_PROGRAM == TRUE32) { for (j = SECTORS_PER_PAGE; j < (SECTORS_PER_PAGE * 2); j++) { OALMSG(TRUE, (TEXT("================================================= Sector %d\n"), j)); for (i = (BYTES_PER_SECTOR * j); i < (BYTES_PER_SECTOR * (j+1)); i++) { OALMSG(TRUE, (TEXT("%02x "), pMBuf[i])); if (i%BYTES_PER_SPARE == 15) OALMSG(TRUE, (TEXT("\n"))); } } } #endif OALMSG(TRUE, (TEXT("=================================================\n"))); } if (pSBuf != NULL) { OALMSG(TRUE, (TEXT("Spare Data\n"))); for (i = 0; i < BYTES_PER_SPARE_PAGE; i++) { OALMSG(TRUE, (TEXT("%02x "), pSBuf[i])); if (i%BYTES_PER_SPARE == 15) OALMSG(TRUE, (TEXT("\n"))); } #if 1 if (TWO_PLANE_PROGRAM == TRUE32) { for (i = BYTES_PER_SPARE_PAGE; i < BYTES_PER_SPARE_SUPAGE; i++) { OALMSG(TRUE, (TEXT("%02x "), pSBuf[i])); if (i%BYTES_PER_SPARE == 15) OALMSG(TRUE, (TEXT("\n"))); } } #endif OALMSG(TRUE, (TEXT("=================================================\n"))); } } static void MLC_FIL_Erase_Test(void) { DWORD dwNum; LowFuncTbl *pLowFuncTbl; UINT32 nSyncRet; pLowFuncTbl = FIL_GetFuncTbl(); while(1) { OALMSG(TRUE, (TEXT("\r\n FIL Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" Block Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum > 0 && dwNum < SUBLKS_TOTAL) { pLowFuncTbl->Erase(0, dwNum, enuBOTH_PLANE_BITMAP); if (pLowFuncTbl->Sync(0, &nSyncRet)) { OALMSG(TRUE, (TEXT(" FIL Erase Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" FIL Erase Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Block Number ! You can erase 1~%d block \r\n"), SUBLKS_TOTAL-1)); } } } static void MLC_FIL_Write_Test(void) { DWORD dwNum; UINT32 iCnt; unsigned char *pMBuf; unsigned char *pSBuf; LowFuncTbl *pLowFuncTbl; UINT32 nSyncRet; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; memcpy((void *)pMBuf, (void *)prayer16bpp, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); for (iCnt=0; iCnt<BYTES_PER_SPARE_SUPAGE; iCnt++) { pSBuf[iCnt] = iCnt; } while(1) { OALMSG(TRUE, (TEXT("\r\n FIL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; // else if (dwNum >= PAGES_PER_BLOCK && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) //[david.modify] 2008-05-07 15:44 else if (dwNum >= 0 && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { s2450IOP->GPFDAT |= (1<<7); pLowFuncTbl->Write(0, dwNum, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pMBuf, pSBuf); s2450IOP->GPFDAT &= ~(1<<7); if (pLowFuncTbl->Sync(0, &nSyncRet)) { OALMSG(TRUE, (TEXT(" FIL Write Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" FIL Write Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can write %d~%d page \r\n"), PAGES_PER_BLOCK, (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } static void MLC_FIL_Read_Test(void) { DWORD dwNum; unsigned char *pMBuf; unsigned char *pSBuf; LowFuncTbl *pLowFuncTbl; INT32 nRet; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; while(1) { OALMSG(TRUE, (TEXT("\r\n FIL Read Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); memset((void *)pMBuf, 0xff, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= 0 && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { s2450IOP->GPFDAT |= (1<<7); nRet = pLowFuncTbl->Read(0, dwNum, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pMBuf, pSBuf, 1, 0); s2450IOP->GPFDAT &= ~(1<<7); if (nRet) { OALMSG(TRUE, (TEXT(" FIL Read Fail \r\n"))); MLC_Print_Page_Data(pMBuf, pSBuf); } else { OALMSG(TRUE, (TEXT(" FIL Read Success \r\n"))); MLC_Print_Page_Data(pMBuf, pSBuf); } } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can read 0~%d page \r\n"), (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } static void MLC_VFL_Erase_Test(void) { DWORD dwNum; while(1) { OALMSG(TRUE, (TEXT("\r\n VFL Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" Block Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum > 0 && dwNum < BLOCKS_PER_BANK) { VFL_Erase(dwNum); if (VFL_Sync()) { OALMSG(TRUE, (TEXT(" VFL Erase Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" VFL Erase Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Block Number ! You can erase 1~%d block \r\n"), BLOCKS_PER_BANK-1)); } } } static void MLC_VFL_Write_Test(void) { DWORD dwNum; UINT32 iCnt; unsigned char *pMBuf; unsigned char *pSBuf; Buffer InBuf; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; memcpy((void *)pMBuf, (void *)prayer16bpp, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); for (iCnt=0; iCnt<BYTES_PER_SPARE_SUPAGE; iCnt++) { pSBuf[iCnt] = iCnt; } while(1) { OALMSG(TRUE, (TEXT("\r\n VFL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= PAGES_PER_BLOCK && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { InBuf.nBitmap = FULL_SECTOR_BITMAP_PAGE; InBuf.eStatus = BUF_AUX; InBuf.pData = pMBuf; InBuf.pSpare = pSBuf; s2450IOP->GPFDAT |= (1<<7); VFL_Write(dwNum, &InBuf); s2450IOP->GPFDAT &= ~(1<<7); if (VFL_Sync()) { OALMSG(TRUE, (TEXT(" VFL Write Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" VFL Write Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can write %d~%d page \r\n"), PAGES_PER_BLOCK, (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } static void MLC_VFL_Read_Test(void) { DWORD dwNum; unsigned char *pMBuf; unsigned char *pSBuf; LowFuncTbl *pLowFuncTbl; Buffer InBuf; INT32 nRet; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; while(1) { OALMSG(TRUE, (TEXT("\r\n VFL Read Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= PAGES_PER_BLOCK && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { memset((void *)pMBuf, 0xff, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); InBuf.nBitmap = FULL_SECTOR_BITMAP_PAGE; InBuf.eStatus = BUF_AUX; InBuf.pData = pMBuf; InBuf.pSpare = pSBuf; s2450IOP->GPFDAT |= (1<<7); nRet = VFL_Read(dwNum, &InBuf, 0); s2450IOP->GPFDAT &= ~(1<<7); if (nRet) { OALMSG(TRUE, (TEXT(" VFL Read Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" VFL Read Success \r\n"))); MLC_Print_Page_Data(pMBuf, pSBuf); } } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can read %d~%d page \r\n"), PAGES_PER_BLOCK-1, (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } #define FTL_TEST 0 #if FTL_TEST #include <FTL.h> static void MLC_FTL_Write_Test(void) { DWORD dwNum; UINT32 iCnt; unsigned char *pMBuf; unsigned char *pSBuf; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; memcpy((void *)pMBuf, (void *)prayer16bpp, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); for (iCnt=0; iCnt<BYTES_PER_SPARE_SUPAGE; iCnt++) { pSBuf[iCnt] = iCnt; } while(1) { OALMSG(TRUE, (TEXT("\r\n FTL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" Sector Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= 0 && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { s2450IOP->GPFDAT |= (1<<7); FTL_Write(dwNum, 16, pMBuf); s2450IOP->GPFDAT &= ~(1<<7); if (VFL_Sync()) { OALMSG(TRUE, (TEXT(" FTL Write Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" FTL Write Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Sector Number ! You can write 0~%d sector \r\n"), (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } static void MLC_FTL_Read_Test(void) { DWORD dwNum; unsigned char *pMBuf; unsigned char *pSBuf; LowFuncTbl *pLowFuncTbl; UINT32 nRet; volatile S3C2450_IOPORT_REG *s2450IOP = (S3C2450_IOPORT_REG *)OALPAtoVA(S3C2450_BASE_REG_PA_IOPORT, FALSE); pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; while(1) { OALMSG(TRUE, (TEXT("\r\n FTL Read Test \r\n"))); OALMSG(TRUE, (TEXT(" Sector Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= 0 && dwNum < (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1)) { memset((void *)pMBuf, 0xff, BYTES_PER_MAIN_SUPAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_SUPAGE); s2450IOP->GPFDAT |= (1<<7); nRet = FTL_Read(dwNum, 16, pMBuf); s2450IOP->GPFDAT &= ~(1<<7); if (nRet) { OALMSG(TRUE, (TEXT(" FTL Read Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" FTL Read Success \r\n"))); MLC_Print_Page_Data(pMBuf, pSBuf); } } else { OALMSG(TRUE, (TEXT(" Wrong Sector Number ! You can read 0~%d sector \r\n"), (BLOCKS_PER_BANK*PAGES_PER_SUBLK-1))); } } } #endif static void MLC_RAW_Erase_Test(void) { DWORD dwNum; DWORD endblock = BANKS_TOTAL*BLOCKS_PER_BANK*(TWO_PLANE_PROGRAM+1); while(1) { OALMSG(TRUE, (TEXT("\r\n RAW Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" Block Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum > 0 && dwNum < endblock) { if (MLC_Erase_RAW(0, dwNum)) { OALMSG(TRUE, (TEXT(" RAW Erase Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" RAW Erase Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Block Number ! You can erase 1~%d block \r\n"), endblock-1)); } } } static void MLC_RAW_Write_Test(void) { DWORD dwNum; UINT32 iCnt; DWORD endblock = BANKS_TOTAL*BLOCKS_PER_BANK*(TWO_PLANE_PROGRAM+1); unsigned char *pMBuf; unsigned char *pSBuf; pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_PAGE; memcpy((void *)pMBuf, (void *)prayer16bpp, BYTES_PER_MAIN_PAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_PAGE); for (iCnt=0; iCnt<BYTES_PER_SPARE_PAGE; iCnt++) { pSBuf[iCnt] = iCnt; } while(1) { OALMSG(TRUE, (TEXT("\r\n RAW Write Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= (PAGES_PER_BLOCK*2) && dwNum < (endblock*PAGES_PER_BLOCK)) { if (MLC_Write_RAW(0, dwNum, pMBuf, pSBuf)) { OALMSG(TRUE, (TEXT(" RAW Write Fail \r\n"))); } else { OALMSG(TRUE, (TEXT(" RAW Write Success \r\n"))); } } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can write %d~%d page \r\n"), PAGES_PER_BLOCK*2, endblock*PAGES_PER_BLOCK-1)); } } } static void MLC_RAW_Read_Test(void) { DWORD dwNum; DWORD endblock = BANKS_TOTAL*BLOCKS_PER_BANK*(TWO_PLANE_PROGRAM+1); unsigned char *pMBuf; unsigned char *pSBuf; pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_PAGE; while(1) { OALMSG(TRUE, (TEXT("\r\n RAW Read Test \r\n"))); OALMSG(TRUE, (TEXT(" Page Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum >= 0 && dwNum < (endblock*PAGES_PER_BLOCK)) { memset((void *)pMBuf, 0xff, BYTES_PER_MAIN_PAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE); MLC_Read_RAW(0, dwNum, pMBuf, pSBuf); MLC_Print_Page_Data(pMBuf, pSBuf); } else { OALMSG(TRUE, (TEXT(" Wrong Page Number ! You can read 0~%d page \r\n"), endblock*PAGES_PER_BLOCK-1)); } } } static void MLC_RAW_Find_MBR_Test(void) { DWORD dwNum; DWORD endblock = BANKS_TOTAL*BLOCKS_PER_BANK*(TWO_PLANE_PROGRAM+1); unsigned char *pMBuf; unsigned char *pSBuf; unsigned char uLoc; pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_PAGE; for (dwNum=0; dwNum<(endblock*PAGES_PER_BLOCK-1); dwNum++) { uLoc = 0x0; if (dwNum%PAGES_PER_BLOCK == 0) OALMSG(TRUE, (TEXT("."), dwNum)); memset((void *)pMBuf, 0xff, BYTES_PER_MAIN_PAGE); memset((void *)pSBuf, 0xff, BYTES_PER_SPARE_PAGE); MLC_Read_RAW(0, dwNum, pMBuf, pSBuf); if ((WMRBuf[0] == 0xe9) && (WMRBuf[1] == 0xfd) && (WMRBuf[2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR-1] == 0xaa)) uLoc = 0x1; if ((WMRBuf[BYTES_PER_SECTOR+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*2-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*2-1] == 0xaa)) uLoc = 0x2; if ((WMRBuf[BYTES_PER_SECTOR*2+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*2+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*2+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*3-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*3-1] == 0xaa)) uLoc = 0x4; if ((WMRBuf[BYTES_PER_SECTOR*3+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*3+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*3+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*4-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*4-1] == 0xaa)) uLoc = 0x8; if ((WMRBuf[BYTES_PER_SECTOR*4+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*4+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*4+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*5-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*5-1] == 0xaa)) uLoc = 0x10; if ((WMRBuf[BYTES_PER_SECTOR*5+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*5+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*5+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*6-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*6-1] == 0xaa)) uLoc = 0x20; if ((WMRBuf[BYTES_PER_SECTOR*6+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*6+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*6+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*7-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*7-1] == 0xaa)) uLoc = 0x40; if ((WMRBuf[BYTES_PER_SECTOR*7+0] == 0xe9) && (WMRBuf[BYTES_PER_SECTOR*7+1] == 0xfd) && (WMRBuf[BYTES_PER_SECTOR*7+2] == 0xff) && (WMRBuf[BYTES_PER_SECTOR*8-2] == 0x55) && (WMRBuf[BYTES_PER_SECTOR*8-1] == 0xaa)) uLoc = 0x80; if (uLoc & 0xff) { OALMSG(TRUE, (TEXT("\r\nMBR is found on Page %d (%x)\r\n"), dwNum, uLoc)); MLC_Print_Page_Data(pMBuf, pSBuf); } } } static void MLC_Mark_BadBlock_Test(void) { DWORD dwNum; LowFuncTbl *pLowFuncTbl; UINT32 nSyncRet; pLowFuncTbl = FIL_GetFuncTbl(); while(1) { OALMSG(TRUE, (TEXT("\r\n Mark Bad Block \r\n"))); OALMSG(TRUE, (TEXT(" Block Number [99999999 to exit] = "))); dwNum = GetDecimalNumber(); if (dwNum == 99999999) break; else if (dwNum > 0 && dwNum < (SUBLKS_TOTAL*BANKS_TOTAL*(TWO_PLANE_PROGRAM+1))) { pLowFuncTbl->Erase(0, dwNum, enuBOTH_PLANE_BITMAP); if (pLowFuncTbl->Sync(0, &nSyncRet)) { OALMSG(TRUE, (TEXT(" FIL Erase Fail \r\n"))); return; } memset(WMRBuf, 0x00, BYTES_PER_SPARE_SUPAGE); IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Write(0, dwNum*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x00, enuBOTH_PLANE_BITMAP, NULL, WMRBuf); IS_CHECK_SPARE_ECC = TRUE32; OALMSG(TRUE, (TEXT(" Mark Bad Block Success \r\n"))); } else { OALMSG(TRUE, (TEXT(" Wrong Block Number ! You can mark 1~%d block \r\n"), SUBLKS_TOTAL-1)); } } } void MLC_LowLevelTest(void) { int iNum; while (1) { OALMSG(TRUE, (TEXT("\r\n====================\r\n"))); OALMSG(TRUE, (TEXT(" MLC Low Level Test \r\n"))); OALMSG(TRUE, (TEXT(" 1. FIL Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" 2. FIL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" 3. FIL Read Test \r\n"))); OALMSG(TRUE, (TEXT(" 4. VFL Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" 5. VFL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" 6. VFL Read Test \r\n"))); OALMSG(TRUE, (TEXT(" 7. RAW Erase Test \r\n"))); OALMSG(TRUE, (TEXT(" 8. RAW Write Test \r\n"))); OALMSG(TRUE, (TEXT(" 9. RAW Read Test \r\n"))); OALMSG(TRUE, (TEXT(" 10. Mark Bad Block \r\n"))); OALMSG(TRUE, (TEXT(" 11. Find MBR Page \r\n"))); #if FTL_TEST OALMSG(TRUE, (TEXT(" 12. FTL Write Test \r\n"))); OALMSG(TRUE, (TEXT(" 13. FTL Read Test \r\n"))); #endif OALMSG(TRUE, (TEXT(" 14. MLC_TEST_DAVID \r\n"))); OALMSG(TRUE, (TEXT(" 0. Exit Test \r\n"))); OALMSG(TRUE, (TEXT("====================\r\n"))); OALMSG(TRUE, (TEXT("Select : "))); iNum = GetDecimalNumber(); if (iNum == 0) break; else if (iNum == 1) MLC_FIL_Erase_Test(); else if (iNum == 2) MLC_FIL_Write_Test(); else if (iNum == 3) MLC_FIL_Read_Test(); else if (iNum == 4) MLC_VFL_Erase_Test(); else if (iNum == 5) MLC_VFL_Write_Test(); else if (iNum == 6) MLC_VFL_Read_Test(); else if (iNum == 7) MLC_RAW_Erase_Test(); else if (iNum == 8) MLC_RAW_Write_Test(); else if (iNum == 9) MLC_RAW_Read_Test(); else if (iNum == 10) MLC_Mark_BadBlock_Test(); else if (iNum == 11) MLC_RAW_Find_MBR_Test(); #if FTL_TEST else if (iNum == 12) MLC_FTL_Write_Test(); else if (iNum == 13) MLC_FTL_Read_Test(); #endif //[david.modify] 2008-05-07 18:32 else if (iNum == 14) MLC_TEST_DAVID(); else OALMSG(TRUE, (TEXT("Wrong selection\r\n"))); } } //[david.modify] 2008-10-22 17:25 // 增加FLASH参数管理功能 //============================================================================================================ //[david.modify] 2008-09-27 10:34 //增加一函数,专门可以读写LOGO区 //LOGO区使用BMP 565格式 // 如果是320x240,则所需要大小约为=320x240x2=150K Bytes // 如果是480x272,则所需要大小约为=480x272x2=261120 Bytes = 255K Bytes // 1个BLOCK是256KB,这样LOGO区,只用1个BLOCK就可以保存了 //================================================== // 仿TOC去写 UINT8 *g_pu8Logo=NULL; // 指向BMP内存 #define ONE_BLOCK_SIZE (256*1024) BOOL BLOCK_Write(UINT32 u32BlockSn, UINT8* pu8Logo, UINT32* pu32Bytes) { LowFuncTbl *pLowFuncTbl; UINT32 dwStartPage, dwNumPage, dwPage; UINT32 dwStartBlock, dwNumBlock, dwBlock; UINT32 dwPageOffset; INT32 nRet; BOOL32 bIsBadBlock = FALSE32; UINT32 nSyncRet; LPBYTE pbBuffer; UINT32 u32PagesPerBlock=0; DPNOK(0); if ( !g_bBootMediaExist ) { OALMSG(OAL_ERROR, (TEXT("ERROR: WriteRawImageToBootMedia: device doesn't exist.\r\n"))); return(FALSE); } // if (g_ImageType == IMAGE_TYPE_LOG0) { UINT8 *pMBuf; UINT8 *pSBuf; pbBuffer = pu8Logo; // dwStartBlock = LOGO_START_BLOCK; dwStartBlock = u32BlockSn; dwNumBlock = (*pu32Bytes-1)/(BYTES_PER_MAIN_SUPAGE*PAGES_PER_BLOCK)+1; DPNOK(dwStartBlock); DPNOK(dwNumBlock); if(dwNumBlock>1) { DPSTR("ERR: LOGO>1 BLOCK"); DPNOK(dwNumBlock); return (FALSE); } pLowFuncTbl = FIL_GetFuncTbl(); pMBuf = WMRBuf; pSBuf = WMRBuf+BYTES_PER_MAIN_SUPAGE; dwBlock = dwStartBlock; while(dwNumBlock > 0) { // if (dwBlock >=IMAGE_START_BLOCK) if (dwBlock >u32BlockSn) { DPNOK(dwBlock); return(FALSE); } IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuBOTH_PLANE_BITMAP, NULL, pSBuf, TRUE32, FALSE32); IS_CHECK_SPARE_ECC = TRUE32; if (TWO_PLANE_PROGRAM == TRUE32) { if (pSBuf[0] == 0xff && pSBuf[BYTES_PER_SPARE_PAGE] == 0xff) bIsBadBlock = TRUE32; } else { if (pSBuf[0] == 0xff) bIsBadBlock = TRUE32; } if (bIsBadBlock) { pLowFuncTbl->Erase(0, dwBlock, enuBOTH_PLANE_BITMAP); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if ( nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Erase Error @ %d block, Skipped\r\n"), dwBlock)); goto MarkAndSkipBadBlock; } //[david.modify] 2008-11-12 14:59 // 因为是使用enuBOTH_PLANE_BITMAP模式,所以要除以2 // PAGES_PER_BLOCK = 128, // u32PagesPerBlock = PAGES_PER_BLOCK / 2; u32PagesPerBlock= ONE_BLOCK_SIZE/BYTES_PER_MAIN_SUPAGE; DPNOK(u32PagesPerBlock); for (dwPageOffset=0; dwPageOffset<u32PagesPerBlock; dwPageOffset++) { pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK+dwPageOffset, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pbBuffer+BYTES_PER_MAIN_SUPAGE*dwPageOffset, NULL); nRet = pLowFuncTbl->Sync(0, &nSyncRet); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Write Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } nRet = pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+dwPageOffset, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pMBuf, NULL, FALSE32, FALSE32); if (nRet != FIL_SUCCESS) { OALMSG(TRUE, (TEXT("[ERR] FIL Read Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } if (0 != memcmp(pbBuffer+BYTES_PER_MAIN_SUPAGE*dwPageOffset, pMBuf, BYTES_PER_MAIN_SUPAGE)) { OALMSG(TRUE, (TEXT("[ERR] Verify Error @ %d Block %d Page, Skipped\r\n"), dwBlock, dwPageOffset)); goto MarkAndSkipBadBlock; } } OALMSG(TRUE, (TEXT("[OK] Write %d th Block Success\r\n"), dwBlock)); dwBlock++; dwNumBlock--; pbBuffer += BYTES_PER_MAIN_SUPAGE*u32PagesPerBlock; continue; MarkAndSkipBadBlock: pLowFuncTbl->Erase(0, dwBlock, enuBOTH_PLANE_BITMAP); memset(pSBuf, 0x0, BYTES_PER_SPARE_SUPAGE); IS_CHECK_SPARE_ECC = FALSE32; pLowFuncTbl->Write(0, dwBlock*PAGES_PER_BLOCK+PAGES_PER_BLOCK-1, 0x0, enuBOTH_PLANE_BITMAP, NULL, pSBuf); IS_CHECK_SPARE_ECC = TRUE32; dwBlock++; continue; } else { OALMSG(TRUE, (TEXT("Bad Block %d Skipped\r\n"), dwBlock)); dwBlock++; continue; } } OALMSG(TRUE, (TEXT("Write Eboot image to BootMedia Success\r\n"))); } return TRUE; } // // Retrieve TOC from Nand. // BOOL BLOCK_Read(UINT32 u32BlockSn, UINT8* pu8Logo, UINT32* pu32Bytes) { LowFuncTbl *pLowFuncTbl; DWORD dwBlock, dwPageOffset; INT32 nRet; UINT8 *pSBuf; unsigned char *pMBuf; UINT32 u32PagesPerBlock=0; DPNOK(pu8Logo); DPNOK(*pu32Bytes); if ( !g_bBootMediaExist ) { EdbgOutputDebugString("ERROR: no boot media\r\n"); return FALSE; } //[david.modify] 2008-09-27 11:45 //缓冲区要大于1个BLOCK的大小 #if 0 if((*pu32Bytes)<(BYTES_PER_MAIN_SUPAGE*PAGES_PER_BLOCK)){ DPNOK(*pu32Bytes); return FALSE; } #endif pLowFuncTbl = FIL_GetFuncTbl(); pSBuf = WMRBuf + BYTES_PER_MAIN_SUPAGE; // dwBlock = LOGO_START_BLOCK; dwBlock = u32BlockSn; pMBuf = pu8Logo; //[david.modify] 2008-11-12 11:37 // 对于1G NAND: PAGES_PER_BLOCK=0X80 BYTES_PER_MAIN_SUPAGE=0x1000 // 对于2G NAND: PAGES_PER_BLOCK=0X80 BYTES_PER_MAIN_SUPAGE=0x2000 // 对于4G NAND: PAGES_PER_BLOCK=0X80 BYTES_PER_MAIN_SUPAGE=0x2000 DPNOK(PAGES_PER_BLOCK); DPNOK(BYTES_PER_MAIN_SUPAGE); //[david.modify] 2008-11-12 14:59 // 因为是使用enuBOTH_PLANE_BITMAP模式,所以要除以2 // PAGES_PER_BLOCK = 128, // u32PagesPerBlock = PAGES_PER_BLOCK / 2; u32PagesPerBlock= ONE_BLOCK_SIZE/BYTES_PER_MAIN_SUPAGE; DPNOK(u32PagesPerBlock); for (dwPageOffset=0; dwPageOffset<u32PagesPerBlock; dwPageOffset++) { pMBuf=pu8Logo+BYTES_PER_MAIN_SUPAGE*dwPageOffset; nRet = pLowFuncTbl->Read(0, dwBlock*PAGES_PER_BLOCK+dwPageOffset, FULL_SECTOR_BITMAP_PAGE, enuBOTH_PLANE_BITMAP, pMBuf, NULL, FALSE32, FALSE32); if (nRet) { DPSTR(" FIL Read Fail \r\n"); } else { // DPSTR(" FIL Read Success \r\n"); // DPNOK(pMBuf); // PrintMsg((UINT32)pMBuf, 0x40, sizeof(UINT8)); } } return TRUE; } BOOL LOGO_Write(UINT8* pu8Logo, UINT32* pu32Bytes) { UINT32 u32BlockSn=LOGO_START_BLOCK; return BLOCK_Write(u32BlockSn, pu8Logo, pu32Bytes); } BOOL LOGO_Read(UINT8* pu8Logo, UINT32* pu32Bytes) { UINT32 u32BlockSn=LOGO_START_BLOCK; return BLOCK_Read(u32BlockSn, pu8Logo, pu32Bytes); }
[ [ [ 1, 2173 ] ] ]
d9e3572a2a833c69e76d3ff60a7a4c84a999ac8c
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/wspr/ws_thread.h
84f6744cdc48502c8fccf0c803e06f814a3dd0de
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
452
h
#pragma once #include "ws_type.h" class ws_runnable { public: WS_VFUNC( ws_result, ThreadProc )(void) = 0; }; class ws_thread { protected: ws_thread(void); public: static ws_thread * StartThread(ws_runnable * pRun); static void Sleep(ws_long millis); static ws_int GetCurrentThreadId(void); public: WS_VIRTUAL_DESTRUCTOR( ws_thread ); WS_VFUNC(ws_int,GetPriority)(void) = 0; };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 25 ] ] ]
f635b787c4ef22f35bbb3cfe4aaf733d00ae7710
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Dispatch/BroadPhase/hkpTypedBroadPhaseHandle.h
23aa5275bf6a79bd875052f0ae594e3c847d0d38
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,014
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_TYPED_BROAD_PHASE_HANDLE #define HK_TYPED_BROAD_PHASE_HANDLE #include <Physics/Internal/Collide/BroadPhase/hkpBroadPhaseHandle.h> #include <Physics/Collide/Agent/Collidable/hkpCollidableQualityType.h> /// An hkpBroadPhaseHandle with a type. hkpCollidable has a member of type hkpTypedBroadPhaseHandle. /// If you use the Havok dynamics lib then /// type can be hkpWorldObject::BROAD_PHASE_ENTITY for entities or hkpWorldObject::BROAD_PHASE_PHANTOM for phantoms. /// Also you can use /// - hkpRigidBody* hkGetRigidBody( hkpCollidable* collidable ) /// - hkpPhantom* hkGetPhantom(hkpCollidable* collidable) class hkpTypedBroadPhaseHandle : public hkpBroadPhaseHandle { public: #if !defined(HK_PLATFORM_SPU) HK_DECLARE_REFLECTION(); HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CDINFO, hkpTypedBroadPhaseHandle); ///Creates a new hkpTypedBroadPhaseHandle of the specified type ///Make sure to call setowner before using this handle. HK_FORCE_INLINE hkpTypedBroadPhaseHandle( int type ); ///Creates a new hkpTypedBroadPhaseHandle of the specified type HK_FORCE_INLINE hkpTypedBroadPhaseHandle( void* owner, int type ); ///Gets the type. The possible types are defined in hkpWorldObject::BroadPhaseType. HK_FORCE_INLINE int getType() const; ///Gets the owner of this handle HK_FORCE_INLINE void setOwner(void* o); ///Gets the owner of this handle HK_FORCE_INLINE void* getOwner() const; ///Gets the collision filter info. This is an identifying value used by collision filters /// - for example, if a group filter is used, this value would encode a collision group and a system group HK_FORCE_INLINE hkUint32 getCollisionFilterInfo() const; ///Sets the collision filter info. This is an identifying value used by collision filters /// - for example, if a group filter is used, this value would encode a collision group and a system group HK_FORCE_INLINE void setCollisionFilterInfo( hkUint32 info ); hkpTypedBroadPhaseHandle( class hkFinishLoadedObjectFlag flag ) : hkpBroadPhaseHandle(flag) {} #endif protected: enum { OFFSET_INVALID = 127 }; inline void setType( int type ); friend class hkpBroadPhaseBorder; // it overrides the type of its owned phantoms hkInt8 m_type; // would have padding of 8 here anyway, so keep at 8 and assert if owner more than +/-128 bytes away hkInt8 m_ownerOffset; // +nosave public: /// The quality of the object, /// You should use the hkpCollisionDispatcher to get the hkpCollisionQualityInfo hkUint16 m_objectQualityType; hkUint32 m_collisionFilterInfo; }; #if !defined(HK_PLATFORM_SPU) # include <Physics/Collide/Dispatch/BroadPhase/hkpTypedBroadPhaseHandle.inl> #endif #endif // HK_TYPED_BROAD_PHASE_HANDLE /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 97 ] ] ]