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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0142b867daa3053e890e52e5c4ad9ecfea0d9a96 | c768f2f50a48d573f169f5bb3657a6f6b0747f6a | /MobileApp/ResultScreen.cpp | 2903bea660c506a7ac469097e01191545f4bc7e4 | [] | no_license | FransUrbo/LastBerakning | 2340e9521791e7abf93b63f625700633be0c8c48 | 69d4c3a1add527d6349d4c55e8d09be005e5954e | refs/heads/master | 2021-01-10T20:25:51.054155 | 2010-04-24T17:42:33 | 2010-04-24T17:42:33 | 2,987,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,652 | cpp | /*
* ResultScreen.cpp
*
* Code to do the actuall calculations!
*
* $Id: ResultScreen.cpp,v 1.14 2010-04-24 11:54:57 turbo Exp $
*/
#include <conprint.h> /* lprintfln() */
#include <MAUtil/String.h>
#include <MAUtil/util.h>
#include "screen.h"
#include "EditBoxScreen.h"
#include "ResultScreen.h"
#include "ScreenTransition.h"
#include "Language.h"
#include "Util.h"
ResultScreen::ResultScreen(MainScreen *previous) : previous(previous) {
Label *label;
ListBox *field;
/* Create the main work/text area */
mainLayout = createMainLayout(LANG_ERASE, LANG_BACK);
listBox = (ListBox*) mainLayout->getChildren()[FIRSTCHILD];
label = createLabel(LANG_RESULT_HEADER, (FONTHEIGHT*2));
listBox->add(label);
listBox->setEnabled(false);
/* ---------------------------------- */
label = createLabel(LANG_RESULT_MAXGROSS, (FONTHEIGHT*7)-(PADDING*8));
field = new ListBox( 0, (FONTHEIGHT*2)-(PADDING*4), label->getWidth()-PADDING*2, label->getHeight(),
label, ListBox::LBO_VERTICAL, ListBox::LBA_NONE, false);
createTextFields(previous->result_weight, field);
listBox->add(label);
/* ---------------------------------- */
label = createLabel(LANG_RESULT_MAXLOAD, (FONTHEIGHT*7)-(PADDING*9));
field = new ListBox( 0, FONTHEIGHT-PADDING, label->getWidth()-PADDING*2, label->getHeight(),
label, ListBox::LBO_VERTICAL, ListBox::LBA_NONE, false);
createTextFields(previous->result_load, field);
listBox->add(label);
/* ---------------------------------- */
listBox->setWrapping(WRAPPING);
this->setMain(mainLayout);
}
ResultScreen::~ResultScreen() {
}
void ResultScreen::show() {
listBox->getChildren()[listBox->getSelectedIndex()]->setSelected(true);
Screen::show();
}
void ResultScreen::hide() {
listBox->getChildren()[listBox->getSelectedIndex()]->setSelected(false);
Screen::hide();
}
void ResultScreen::keyPressEvent(int keyCode, int nativeCode) {
#if DEBUG >= 2
lprintfln("Index: %d", listBox->getSelectedIndex());
#endif
switch(keyCode) {
case MAK_HASH:
// Hash (#) key - ask the moblet to close the application
maExit(0);
break;
case MAK_LEFT:
case MAK_SOFTRIGHT:
#if DEBUG >= 2
lprintfln("Showing previous screen...");
#endif
ScreenTransition::makeTransition(this, previous, -1, 400);
break;
case MAK_UP:
#if DEBUG >= 2
lprintfln("selectPreviousItem()");
#endif
listBox->selectPreviousItem();
break;
case MAK_DOWN:
#if DEBUG >= 1
lprintfln("selectNextItem()");
#endif
listBox->selectNextItem();
break;
}
#if DEBUG >= 2
lprintfln("keyPressEvent() done...");
#endif
}
void ResultScreen::createTextFields(double value[3][3], Widget *parent) {
String prefix;
char valstr[64];
for(int bk = 0; bk < 3; bk++) {
prefix = LANG_LOAD_CLASS;
prefix += integerToString(bk+1);
#if DEBUG >= 0
lprintfln("%s%d => %02.02Lf + %02.02Lf = %02.02Lf",
prefix.c_str(), bk+1, value[TRUCK][bk], value[TRAILER][bk], value[TRAIN][bk]);
#endif
sprintf(valstr, "%02.02Lf + %02.02Lf = %02.02Lf",
value[TRUCK][bk], value[TRAILER][bk], value[TRAIN][bk]);
createTextField(prefix.c_str(), valstr, parent);
}
}
void ResultScreen::createTextField(const char *leader, const char *value, Widget *parent)
{
Label *label;
String string;
string += leader;
string += ": ";
string += value;
#if DEBUG >= 1
lprintfln("createTextField(): string='%s'", string.c_str());
#endif
label = new Label(0, 0, scrWidth-PADDING*2, RADIOHEIGHT*2, parent, string, 0, gFont);
label->setMultiLine(true);
label->setSkin(false);
}
| [
"turbo"
] | [
[
[
1,
139
]
]
] |
1d30500277a651d3acca1837bf5676d711489af1 | 197ac28d1481843225f35aff4aa85f1909ef36bf | /mcucpp/MSP430/timera2.h | d1be23a1c9c513f1bae3a8d48cdb8643a8a9de59 | [
"BSD-3-Clause"
] | permissive | xandroalmeida/Mcucpp | 831e1088eb38dfcf65bfb6fb3205d4448666983c | 6fc5c8d5b9839ade60b3f57acc78a0ed63995fca | refs/heads/master | 2020-12-24T12:13:53.497692 | 2011-11-21T15:36:03 | 2011-11-21T15:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,531 | h |
#pragma once
#ifndef _MSP43_TIMER_H
#define _MSP43_TIMER_H
namespace Timers
{
class Timer0
{
public:
typedef unsigned short DataT;
static const unsigned short MaxValue = 0xffff;
enum ClockDivider
{
DivStop = 0,
Div1 = ID_0,
Div2 = ID_1,
Div4 = ID_2,
Div8 = ID_3
};
enum {ClockDividerMask = ~Div8};
enum ClockSrc
{
ExtRising = TASSEL_0,
AuxClock = TASSEL_1,
MainClock = TASSEL_2,
ExtFailing = TASSEL_3
};
enum {ClockSrcMask = ~ExtFailing};
enum TimerMode
{
Normal = MC_2,
ClearOnMatch0 = MC_1,
UpDown = MC_3
};
enum {TimerModeMask = ~UpDown};
template<unsigned Number> struct Divider;
static void Set(DataT val)
{
TAR = val;
}
static DataT Get()
{
return TAR;
}
static void Stop()
{
TACTL = 0;
}
static void Clear()
{
TACTL |= TACLR;
}
static void Start(ClockDivider divider, ClockSrc clockSrc = MainClock, TimerMode mode = Normal)
{
TACTL = (TACTL & (ClockDividerMask | ClockSrcMask | TimerModeMask))
| divider | clockSrc | mode;
}
static void EnableInterrupt()
{
TACTL |= TAIE;
}
static bool IsInterrupt()
{
return TACTL & TAIFG;
}
static void ClearInterruptFlag()
{
TACTL |= TAIFG;
}
static void SetMode(TimerMode mode)
{
TACTL = (TACTL & TimerModeMask) | mode;
}
template<int number> class OutputCompare;
template<int number> class InputCapture;
};
template<> struct Timer0::Divider <0> { static const ClockDivider value = Div1; enum {Div = 1}; };
template<> struct Timer0::Divider <1> { static const ClockDivider value = Div2; enum {Div = 2}; };
template<> struct Timer0::Divider <2> { static const ClockDivider value = Div4; enum {Div = 4}; };
template<> struct Timer0::Divider <3> { static const ClockDivider value = Div8; enum {Div = 8}; };
template<> class Timer0::OutputCompare<0>
{
public:
enum OutputMode
{
OutNone = OUTMOD_0,
OutSet = OUTMOD_1,
OutTogleReset = OUTMOD_2,
OutSetReset = OUTMOD_3,
OutTogle = OUTMOD_4,
OutReset = OUTMOD_5,
OutTogleSet = OUTMOD_6,
OutResetSet = OUTMOD_7
};
enum {OutputModeMask = ~OutResetSet};
static void Set(DataT val)
{
TACCR0 = val;
}
static DataT Get()
{
return TACCR0;
}
static void EnableInterrupt()
{
TACCTL0 |= CCIE;
}
static bool IsInterrupt()
{
return TACCTL0 & CCIFG;
}
static void ClearInterruptFlag()
{
TACCTL0 |= CCIFG;
}
static void SetMode(OutputMode mode)
{
TACCTL0 = (TACCTL0 & OutputModeMask) | mode;
}
};
template<> class Timer0::OutputCompare<1>
{
public:
enum OutputMode
{
OutNone = OUTMOD_0,
OutSet = OUTMOD_1,
OutTogleReset = OUTMOD_2,
OutSetReset = OUTMOD_3,
OutTogle = OUTMOD_4,
OutReset = OUTMOD_5,
OutTogleSet = OUTMOD_6,
OutResetSet = OUTMOD_7
};
enum {OutputModeMask = ~OutResetSet};
static void Set(DataT val)
{
TACCR1 = val;
}
static DataT Get()
{
return TACCR1;
}
static void EnableInterrupt()
{
TACCTL1 |= CCIE;
}
static bool IsInterrupt()
{
return TACCTL1 & CCIFG;
}
static void ClearInterruptFlag()
{
TACCTL1 |= CCIFG;
}
static void SetMode(OutputMode mode)
{
TACCTL1 = (TACCTL1 & OutputModeMask) | mode;
}
};
}
#endif | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
13
],
[
15,
24
],
[
36,
41
],
[
43,
69
],
[
71,
81
],
[
83,
86
],
[
88,
198
]
],
[
[
14,
14
],
[
25,
35
],
[
42,
42
],
[
70,
70
],
[
82,
82
],
[
87,
87
]
]
] |
575d00d8661abfc554e6f329400569b42350d83c | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/HovercraftUniverse/BasePhantom.h | a65cc76c0b60672b066cac0951137aacde001302 | [] | no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | h | #ifndef BASEPHANTOM_H
#define BASEPHANTOM_H
#include <Physics/Dynamics/Phantom/hkpSimpleShapePhantom.h>
namespace HovUni {
class BasePhantom : public hkpSimpleShapePhantom
{
public:
BasePhantom( const hkpShape *shape, const hkTransform &transform );
~BasePhantom(void);
//virtual void addOverlappingCollidable (hkpCollidable *collidable);
//virtual void removeOverlappingCollidable (hkpCollidable *collidable);
};
}
#endif
| [
"pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
23
]
]
] |
7e65a41c4474a8f989f1af5b6d7e66ccae78984e | 0b7226783e4b70944b4e66ae21eee9a3a0394e81 | /src/Independent/Code/FSCompiledCode.cpp | beae26eff95a2bd34b6f14b472d3b100b2c40b3a | [] | no_license | LittleEngineer/fridgescript | 061e3d3f0d17d8c0c0b8e089a3254c56edfa74e6 | 55b2e6bab63e826291b8d14f24c40f413f895e54 | refs/heads/master | 2021-01-10T16:52:37.530928 | 2009-09-06T10:58:21 | 2009-09-06T10:58:21 | 46,175,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | /*
This file is part of FridgeScript.
FridgeScript 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 3 of the License, or
(at your option) any later version.
FridgeScript 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 FridgeScript. If not, see <http://www.gnu.org/licenses/>
*/
// main header
#include <Core/FridgeScript.h>
#include <Code/FSCompiledCode.h>
#include <Variable/FSVariable.h>
void FSCompiledCode::SetupVariableStack(Simple::Stack<FSVariable*>* v)
{
for(u_int i = 0; i < v->GetCount(); ++i)
{
vars.Push((*v)[i]);
}
}
void FSCompiledCode::SetupConstantStack(Simple::Stack<float>* v)
{
for(u_int i = 0; i < v->GetCount(); ++i)
{
consts.Push((*v)[i]);
}
} | [
"jheriko@78b37d4e-3566-11de-a9fe-ad1e22fc3a8a"
] | [
[
[
1,
38
]
]
] |
29ff317ba937d18b1076254980808f27d064acd4 | 075043812c30c1914e012b52c60bc3be2cfe49cc | /src/SDLGUIlibTests/Logger.cpp | 4be0d3d9cffb1efb3a031a50ab29b6b91a16f688 | [] | no_license | Luke-Vulpa/Shoko-Rocket | 8a916d70bf777032e945c711716123f692004829 | 6f727a2cf2f072db11493b739cc3736aec40d4cb | refs/heads/master | 2020-12-28T12:03:14.055572 | 2010-02-28T11:58:26 | 2010-02-28T11:58:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | cpp | #include "stdafx.h"
#include "Logger.h"
Logger::Logger(std::string _filename)
{
output_.open(_filename.c_str(), std::ios::trunc);
}
Logger::~Logger(void)
{
output_.close();
}
Logger& Logger::ErrorOut()
{
static Logger logger("ErrorLog.txt");
return logger;
}
Logger& Logger::DiagnosticOut()
{
static Logger logger("Diagnostic.txt");
return logger;
}
Logger& Logger::operator <<( int i )
{
output_ << i;
printf("%d", i);
return *this;
}
Logger& Logger::operator <<( float i )
{
output_ << i;
printf("%f", i);
return *this;
}
Logger& Logger::operator <<( double i )
{
output_ << i;
printf("%e", i);
return *this;
}
Logger& Logger::operator <<( std::string i )
{
output_ << i;
printf("%s", i.c_str());
return *this;
}
Logger& Logger::operator <<(Vector3f v)
{
output_ << "(" << v.x << "," << v.y << "," << v.z << ")";
printf("(%f,%f,%f)", v.x, v.y, v.z);
return *this;
}
Logger& Logger::operator <<(Vector2f v)
{
output_ << "(" << v.x << "," << v.y << ")";
printf("(%f,%f)", v.x, v.y);
return *this;
} | [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
9c1c88b63099e762f65dc277b1972138ee73866d | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /engine/hyGC.cpp | 6d9db99f1156441abd7bda884c8fde76abc2837b | [
"MIT"
] | permissive | ysei/Hayat | 74cc1e281ae6772b2a05bbeccfcf430215cb435b | b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0 | refs/heads/master | 2020-12-11T09:07:35.606061 | 2011-08-01T12:38:39 | 2011-08-01T12:38:39 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 21,249 | cpp | /* -*- coding: sjis-dos; -*- */
/*
* copyright 2010 FUKUZAWA Tadashi. All rights reserved.
*/
#include "hyGC.h"
#include "hyMemPool.h"
#include "hyObject.h"
#include "hyVarTable.h"
#include "hyThread.h"
#include "hyThreadManager.h"
#include "hyCodeManager.h"
#include "hyBytecode.h"
#include "hyContext.h"
#include "hyDebug.h"
#ifdef HMD__MEM_CHECK
#define DEBUG_CHECK_MEMORY(p) HMD_DEBUG_ASSERT(p->check())
#else
#define DEBUG_CHECK_MEMORY(p) ((void)0)
#endif
using namespace Hayat::Common;
using namespace Hayat::Engine;
GC::Phase_e GC::m_phase = GC::PHASE_SWEPT;
Context* GC::m_finalizeContext = NULL;
GC::SubPhase_e GC::m_subPhase;
bool GC::m_subPhase_end;
hys32 GC::m_num_gcobj = 0;
hys32 GC::m_num_perPart_inc = 0;
hys32 GC::m_num_unmark_part = 20;
hys32 GC::m_num_sweep_part = 20;
CellIterator GC::m_itr;
Value* GC::m_pValArray;
hys32 GC::m_arrIdx;
hys32 GC::m_arrIdx_2;
hys32 GC::m_countdown_inc = 0;
#ifndef EXACT_FREEMEMSIZE
size_t GC::m_freeSize;
#endif
#ifdef HY_ENABLE_BYTECODE_RELOAD
BMap<const HClass*,const HClass*>* GC::pGenerationMap = NULL;
#endif
//============================================================
// GC
//============================================================
static hyu32 m_INIT_FC_STACKSIZE = 32;
static hyu32 m_INIT_FC_FRAMESTACKSIZE = 8;
void GC::initialize(void)
{
// sweepに必要なメモリを最初に割当てておく
m_finalizeContext = gMemPool->allocT<Context>(1, "GcFC");
m_finalizeContext->initialize(m_INIT_FC_STACKSIZE, m_INIT_FC_FRAMESTACKSIZE);
m_phase = PHASE_SWEPT;
m_num_gcobj = 0;
m_num_unmark_part = 20;
m_num_sweep_part = 20;
m_countdown_inc = 0;
#ifdef HY_ENABLE_BYTECODE_RELOAD
pGenerationMap = NULL;
#endif
Debug::printMarkTreeOff();
}
void GC::finalize(void)
{
if (m_finalizeContext != NULL) {
gMemPool->free(m_finalizeContext);
m_finalizeContext = NULL;
}
}
// void GC::unmark(void)
// {
// DEBUG_CHECK_MEMORY(gMemPool);
// m_num_gcobj = 0;
// CellIterator last = gMemPool->end();
// for (CellIterator itr = gMemPool->begin(); itr < last; itr++) {
// MemCell* cell = *itr;
// if (cell->isGCObject()) {
// ((Object*)cell)->m_unmark();
// ++m_num_gcobj;
// }
// }
// DEBUG_CHECK_MEMORY(gMemPool);
// gCodeManager.clearCodeUsingFlag();
// }
void GC::startUnmarkIncremental(void)
{
HMD_DEBUG_ASSERT(m_phase == PHASE_SWEPT);
m_num_perPart_inc = m_num_gcobj / m_num_unmark_part;
if (m_num_perPart_inc < MIN_NUM_PERPART_INC)
m_num_perPart_inc = MIN_NUM_PERPART_INC;
m_phase = PHASE_UNMARKING;
m_num_gcobj = 0;
m_itr = gMemPool->begin();
m_subPhase_end = false;
}
void GC::unmarkIncremental(void)
{
hys32 countdown = m_num_perPart_inc;
CellIterator last = gMemPool->end();
for ( ; m_itr < last; m_itr++) {
MemCell* cell = *m_itr;
if (cell->isGCObject()) {
((Object*)cell)->m_unmark();
++m_num_gcobj;
}
if (--countdown <= 0) {
gMemPool->registerCellIterator(&m_itr);
return;
}
}
gCodeManager.clearCodeUsingFlag();
gCodeManager.unmarkStringBox();
gMemPool->registerCellIterator(NULL);
m_subPhase_end = true;
}
#ifdef HY_ENABLE_BYTECODE_RELOAD
void GC::genClass(const HClass** pHClassPtr)
{
const HClass** pp = pGenerationMap->find(*pHClassPtr);
if (pp != NULL) {
//HMD__PRINTF_FK("genClass %x(%s) -> %x(%s)\n",*pHClassPtr,(*pHClassPtr)->name(),*pp,(*pp)->name());
*pHClassPtr = *pp;
}
}
#endif
void GC::markValue(Value& val)
{
Debug::incMarkTreeLevel();
if (val.type == HC_REF) {
markObjP(&(val.objPtr));
} else if (val.type == HC_INDIRECT_REF) {
markObjP(&(val.objPtr));
//HMD_PRINTF("mark indirect %x\n",val.ptrData);
} else if (val.type->symCheck(HSym_List)) {
markList((ValueList*) val.ptrData);
#ifdef HY_ENABLE_BYTECODE_RELOAD
} else if (val.type == HC_String) {
// バイトコードの文字列テーブルを参照している
gCodeManager.markString((const char**)&(val.ptrData));
} else if (val.type == HC_Class) {
if (pGenerationMap != NULL)
genClass((const HClass**)(&(val.ptrData)));
} else {
if (pGenerationMap != NULL)
genClass(&(val.type));
}
#endif
Debug::decMarkTreeLevel();
}
void GC::markObj(Object* obj)
{
#ifdef HY_ENABLE_RELOCATE_OBJECT
const HClass* pClass = obj->type();
if (pClass == HC_RELOCATED_OBJ) {
obj = *(Object**)obj->field(0);
}
#ifdef HY_ENABLE_BYTECODE_RELOAD
else if (pGenerationMap != NULL) {
const HClass** pNew = pGenerationMap->find(pClass);
if (pNew != NULL) {
obj = obj->classGeneration(*pNew);
}
}
#endif
#endif
((MemCell*)obj)->printMarkNode();
obj->m_GC_mark();
}
void GC::markObjP(Object** pObj)
{
if (*pObj == NULL) return;
#ifdef HY_ENABLE_RELOCATE_OBJECT
const HClass* pClass = (*pObj)->type();
if (pClass == HC_RELOCATED_OBJ) {
*pObj = *(Object**)(*pObj)->field(0);
}
#ifdef HY_ENABLE_BYTECODE_RELOAD
else if (pGenerationMap != NULL) {
const HClass** pNew = pGenerationMap->find(pClass);
if (pNew != NULL) {
*pObj = (*pObj)->classGeneration(*pNew);
}
}
#endif
#endif
((MemCell*)*pObj)->printMarkNode();
(*pObj)->m_GC_mark();
}
void GC::markList(ValueList* p)
{
for ( ; p != NULL; p = p->tail()) {
Object::fromCppObj(p)->markSelfOnly();
((MemCell*)Object::fromCppObj(p))->printMarkNode();
GC::markValue(p->head());
}
}
// void GC::markAll(void)
// {
// DEBUG_CHECK_MEMORY(gMemPool);
// // グローバル変数
// gGlobalVar.m_GC_mark();
// // 全バイトコード → トップレベル定数・クラス変数
// gCodeManager.m_GC_mark();
// // スレッド → 全インスタンス
// ThreadManager::m_GC_mark();
// #ifdef HY_ENABLE_BYTECODE_RELOAD
// // reloadされた古いバイトコード
// //gCodeManager.m_GC_mark_replacedBytecodes();
// #endif
// DEBUG_CHECK_MEMORY(gMemPool);
// }
void GC::copyMarkFlag(Object* newObj, Value& orgVal)
{
Object* orgObj = NULL;
if (orgVal.type == HC_REF) {
orgObj = orgVal.objPtr;
} else if (orgVal.type == HC_INDIRECT_REF) {
orgObj = orgVal.objPtr;
} else if (orgVal.type->symCheck(HSym_List)) {
if (orgVal.ptrData != NULL)
orgObj = Object::fromCppObj((ValueList*) orgVal.ptrData);
}
bool flag;
if (orgObj == NULL) {
flag = true;
} else {
flag = orgObj->isMarked();
}
//HMD_PRINTF("copyMark flag=%s org=%x new=%x\n", flag ? "true" : "false",orgObj,newObj);
if (flag)
newObj->m_mark();
else
newObj->m_unmark();
}
void GC::m_writeBarrier(const Value& val)
{
// 手抜き実装: その場でマークしてしまう
// 本来は新Objectなら記録しておいてGCフェーズにてやるべきだろうが、
// 新旧Objectの判定などにコストがかかりそうなので手を抜いた。
markValue(const_cast<Value&>(val));
}
// void GC::sweep()
// {
// DEBUG_CHECK_MEMORY(gMemPool);
// ThreadManager::m_sweep(); // 終了スレッドを削除
// int freeSize = 0;
// #ifdef HMD_DEBUG
// gMemPool->m_maxFreeCellSize = 0;
// #endif
// CellIterator last = gMemPool->end();
// for (CellIterator itr = gMemPool->begin(); itr < last; itr++) {
// MemCell* cell = *itr;
// if (cell->isGCObject()) {
// if (! ((Object*)cell)->isMarked()) {
// #ifdef TEST__CPPUNIT
// // (HClass*)2000 以下はテスト用の仮クラス
// if ((hyu32)((Object*)cell)->type() > 2000)
// #endif
// {
// HMD__PRINTF_GC("GC collect obj %x %s size %x\n", cell, ((Object*)cell)->type()->name(), cell->size());
// ((Object*)cell)->m_finalize(m_finalizeContext);
// }
// #ifdef TEST__CPPUNIT
// else {
// HMD__PRINTF_GC("GC collect obj %x size %x\n", cell, cell->size());
// }
// #endif
// gMemPool->free(cell);
// }
// }
// if (cell->m_bFree()) {
// size_t size = cell->size();
// #ifndef EXACT_FREEMEMSIZE
// freeSize += size;
// #endif
// #ifdef HMD_DEBUG
// if (gMemPool->m_maxFreeCellSize < size)
// gMemPool->m_maxFreeCellSize = size;
// #endif
// }
// }
// gCodeManager.deleteUnnecessaryBytecode();
// #ifdef EXACT_FREEMEMSIZE
// freeSize = 0;
// last = gMemPool->end();
// for (CellIterator itr = gMemPool->begin(); itr < last; itr++) {
// MemCell* cell = *itr;
// if (cell->m_bFree())
// freeSize += cell->size();
// }
// #endif
// gMemPool->m_freeCellSizeTotal = freeSize;
// DEBUG_CHECK_MEMORY(gMemPool);
// }
void GC::startSweepIncremental(void)
{
#ifndef EXACT_FREEMEMSIZE
m_freeSize = 0;
#endif
m_itr = gMemPool->begin();
m_num_perPart_inc = m_num_gcobj / m_num_sweep_part;
if (m_num_perPart_inc < MIN_NUM_PERPART_INC)
m_num_perPart_inc = MIN_NUM_PERPART_INC;
m_subPhase_end = false;
}
void GC::sweepIncremental_1(void)
{
ThreadManager::m_sweep(); // 終了スレッドを削除
}
void GC::sweepIncremental_2(void)
{
hys32 countdown = m_num_perPart_inc;
CellIterator last = gMemPool->end();
for ( ; m_itr < last; m_itr++) {
if (countdown-- <= 0) {
gMemPool->registerCellIterator(&m_itr);
return;
}
MemCell* cell = *m_itr;
if (cell->isGCObject()) {
if (! ((Object*)cell)->isMarked()) {
#ifdef TEST__CPPUNIT
// (HClass*)2000 以下はテスト用の仮クラス
if ((hyu32)((Object*)cell)->type() > 2000)
#endif
{
HMD__PRINTF_GC("GC collect obj %x %s size %x\n", cell, ((Object*)cell)->type()->name(), cell->size());
((Object*)cell)->m_finalize(m_finalizeContext);
}
#ifdef TEST__CPPUNIT
else {
HMD__PRINTF_GC("GC collect obj %x size %x\n", cell, cell->size());
}
#endif
gMemPool->free(cell);
}
}
if (cell->m_bFree()) {
size_t size = cell->size();
#ifndef EXACT_FREEMEMSIZE
m_freeSize += size;
#endif
#ifdef HMD_DEBUG
if (gMemPool->m_maxFreeCellSize < size)
gMemPool->m_maxFreeCellSize = size;
#endif
}
}
gCodeManager.sweepStringBox();
gMemPool->registerCellIterator(NULL);
m_subPhase_end = true;
}
void GC::sweepIncremental_3(void)
{
gCodeManager.deleteUnnecessaryBytecode();
#ifdef EXACT_FREEMEMSIZE
int freeSize = 0;
CellIterator last = gMemPool->end();
for (CellIterator itr = gMemPool->begin(); itr < last; itr++) {
MemCell* cell = *itr;
if (cell->m_bFree())
freeSize += cell->size();
}
gMemPool->m_freeCellSizeTotal = freeSize;
#else
gMemPool->m_freeCellSizeTotal = m_freeSize;
#endif
DEBUG_CHECK_MEMORY(gMemPool);
m_subPhase_end = true;
}
// void GC::step(void)
// {
// switch (m_phase) {
// case PHASE_SWEPT:
// case PHASE_UNMARKING:
// // HMD__PRINTF_GC("********** ummark\n");
// unmark();
// m_phase = PHASE_UNMARKED;
// break;
// case PHASE_UNMARKED:
// case PHASE_MARKING:
// // HMD__PRINTF_GC("********** mark\n");
// markAll();
// m_phase = PHASE_MARKED;
// break;
// case PHASE_MARKED:
// case PHASE_SWEEPING:
// // HMD__PRINTF_GC("********** sweep\n");
// sweep();
// m_phase = PHASE_SWEPT;
// break;
// }
// }
void GC::incremental(void)
{
switch (m_phase) {
case PHASE_SWEPT:
startUnmarkIncremental();
m_phase = PHASE_UNMARKING;
m_subPhase_end = false;
// not break
case PHASE_UNMARKING:
unmarkIncremental();
if (m_subPhase_end)
m_phase = PHASE_UNMARKED;
break;
case PHASE_UNMARKED:
m_phase = PHASE_MARKING;
m_subPhase = SUBPHASE_GLOBAL;
gGlobalVar.startMarkIncremental();
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("gGlobalVar mark\n");
#endif
m_subPhase_end = false;
// not break
case PHASE_MARKING:
switch (m_subPhase) {
case SUBPHASE_GLOBAL:
gGlobalVar.markIncremental();
if (m_subPhase_end) {
m_subPhase = SUBPHASE_CODEMANAGER;
gCodeManager.startMarkIncremental();
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("gCodeManager mark\n");
#endif
m_subPhase_end = false;
}
break;
case SUBPHASE_CODEMANAGER:
gCodeManager.markIncremental();
if (m_subPhase_end) {
m_subPhase = SUBPHASE_CODEMANAGER_2;
gCodeManager.startMarkIncremental_2();
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("gCodeManager mark 2\n");
#endif
m_subPhase_end = false;
}
break;
case SUBPHASE_CODEMANAGER_2:
gCodeManager.markIncremental_2();
if (m_subPhase_end) {
m_subPhase = SUBPHASE_THREAD;
ThreadManager::startMarkIncremental();
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("ThreadManager mark\n");
#endif
m_subPhase_end = false;
}
break;
case SUBPHASE_THREAD:
ThreadManager::markIncremental();
if (m_subPhase_end) {
DEBUG_CHECK_MEMORY(gMemPool);
m_subPhase = SUBPHASE_CODEMANAGER_3;
}
break;
case SUBPHASE_CODEMANAGER_3:
// スタック上のオブジェクトに write barrier を仕掛けると動作が
// 重いので、markフェーズの最後にまとめて改めてスタック上の
// オブジェクトをマークする事で write barrier しなくても
// 良い様にした。
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("gCodeManager mark all stack\n");
#endif
gCodeManager.markAllStack();
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("ThreadManager mark all stack\n");
#endif
ThreadManager::markAllStack();
m_phase = PHASE_MARKED;
#ifdef HMD__DEBUG_MARK_TREE
if (Debug::isPrintMarkTreeOn())
HMD_PRINTF("mark end.\n");
#endif
break;
default:
HMD_FATAL_ERROR("unknown GC subphase %d", m_subPhase);
}
break;
case PHASE_MARKED:
startSweepIncremental();
m_phase = PHASE_SWEEPING;
m_subPhase = SUBPHASE_SWEEP_1;
m_subPhase_end = false;
// not break
case PHASE_SWEEPING:
switch (m_subPhase) {
case SUBPHASE_SWEEP_1:
sweepIncremental_1();
m_subPhase = SUBPHASE_SWEEP_2;
break;
case SUBPHASE_SWEEP_2:
sweepIncremental_2();
if (m_subPhase_end) {
m_subPhase = SUBPHASE_SWEEP_3;
m_subPhase_end = false;
}
break;
case SUBPHASE_SWEEP_3:
sweepIncremental_3();
if (m_subPhase_end) {
m_phase = PHASE_SWEPT;
gMemPool->calcAlertAbsorbLevel();
Debug::printMarkTreeOff();
}
break;
default:
HMD_FATAL_ERROR("unknown GC subphase %d", m_subPhase);
}
break;
default:
HMD_FATAL_ERROR("unknown GC phase %d", m_phase);
}
}
void GC::unmark(void)
{
m_phase = PHASE_SWEPT;
while (m_phase != PHASE_UNMARKED)
incremental();
}
void GC::markAll(void)
{
m_phase = PHASE_UNMARKED;
while (m_phase != PHASE_MARKED)
incremental();
}
void GC::sweep(void)
{
m_phase = PHASE_MARKED;
while (m_phase != PHASE_SWEPT)
incremental();
}
void GC::full(void)
{
// incremental()を何回も呼ばないように変数の値を一時的に差し替え
hys32 unmark_part_bak = m_num_unmark_part;
hys32 sweep_part_bak = m_num_sweep_part;
m_num_unmark_part = 1;
m_num_sweep_part = 1;
m_num_perPart_inc = 0x7fffffff;
m_phase = PHASE_SWEPT;
gMemPool->registerCellIterator(NULL);
startUnmarkIncremental();
do {
incremental();
} while (m_phase != PHASE_SWEPT);
m_num_unmark_part = unmark_part_bak;
m_num_sweep_part = sweep_part_bak;
}
void GC::coalesce(void)
{
HMD_ASSERT(m_phase != PHASE_UNMARKING && m_phase != PHASE_SWEEPING);
DEBUG_CHECK_MEMORY(gMemPool);
gMemPool->coalesce();
DEBUG_CHECK_MEMORY(gMemPool);
}
int GC::countCellsUsing(const MemPool* pool)
{
if (pool == NULL)
pool = gMemPool;
CellIterator last = pool->end();
int count = 0;
for (CellIterator itr = pool->begin(); itr < last; itr++) {
MemCell* cell = *itr;
if (!cell->m_bFree()) {
++count;
/*
if (cell->isGCObject()) {
HMD_PRINTF("%s ",((Object*)cell)->type()->name());
} else {
HMD_PRINTF("[%x] ",cell);
}
*/
}
}
//HMD_PRINTF("\n");
return count;
}
int GC::countObjects(const MemPool* pool)
{
if (pool == NULL)
pool = gMemPool;
CellIterator last = pool->end();
int count = 0;
for (CellIterator itr = pool->begin(); itr < last; itr++) {
MemCell* cell = *itr;
if (!cell->m_bFree()) {
if (cell->isGCObject()) {
++count;
//HMD_PRINTF("%s ",((Object*)cell)->type()->name());
} else {
//HMD_PRINTF("[%x] ",cell);
}
}
}
//HMD_PRINTF("\n");
return count;
}
void GC::printGCMark(Value& val)
{
Object* obj = NULL;
if (val.type == HC_REF) {
obj = val.objPtr;
} else if (val.type == HC_INDIRECT_REF) {
obj = val.objPtr;
} else if (val.type->symCheck(HSym_List)) {
if (val.ptrData != NULL)
obj = Object::fromCppObj((ValueList*) val.ptrData);
}
if (obj == NULL) {
HMD_PRINTF("(N)");
} else {
HMD_PRINTF(obj->isMarked() ? "(M)" : "(U)");
//HMD_PRINTF(":%x",obj);
}
}
const char* GC::getPhaseStr(void)
{
const char* str = NULL;
switch (m_phase) {
case PHASE_UNMARKING:
str = "[unmarking]";
break;
case PHASE_UNMARKED:
str = "[unmarked]";
break;
case PHASE_MARKING:
switch (m_subPhase) {
case SUBPHASE_GLOBAL: str = "[marking:global]"; break;
case SUBPHASE_CODEMANAGER: str = "[marking:codeManager]"; break;
case SUBPHASE_CODEMANAGER_2: str = "[marking:codeManager2]"; break;
case SUBPHASE_CODEMANAGER_3: str = "[marking:codeManager3]"; break;
case SUBPHASE_THREAD: str = "[marking:thread]"; break;
default:;
}
break;
case PHASE_MARKED:
str = "[marked]";
break;
case PHASE_SWEEPING:
str = "[sweeping]";
switch (m_subPhase) {
case SUBPHASE_SWEEP_1: str = "[sweeping:sweep1]"; break;
case SUBPHASE_SWEEP_2: str = "[sweeping:sweep2]"; break;
case SUBPHASE_SWEEP_3: str = "[sweeping:sweep3]"; break;
default:;
}
break;
case PHASE_SWEPT:
str = "[swept]";
break;
default:;
}
return str;
}
void GC::printGCPhase(void)
{
const char* str = getPhaseStr();
if (str == NULL) {
HMD_FATAL_ERROR("unknown GC phase %d:%d", m_phase, m_subPhase);
}
HMD_PRINTF("%s\n", str);
}
| [
"[email protected]"
] | [
[
[
1,
753
]
]
] |
497106967c8085d7abb7e4a014c90ee074f2da74 | de2b54a7b68b8fa5d9bdc85bc392ef97dadc4668 | /TrackerOnFann21/ConfigurationHandler/ConfigHandler.h | abeb89db1a16534bcd3ea6b8649840a0881e0a55 | [] | no_license | kumarasn/tracker | 8c7c5b828ff93179078cea4db71f6894a404f223 | a3e5d30a3518fe3836f007a81050720cef695345 | refs/heads/master | 2021-01-10T07:57:09.306936 | 2009-04-17T15:02:16 | 2009-04-17T15:02:16 | 55,039,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | /*
* ConfigHandler.h
*
* Created on: 05-feb-2009
* Author: Timpa
*/
#ifndef CONFIGHANDLER_H_
#define CONFIGHANDLER_H_
#include "stdio.h"
#include "iostream.h"
class ConfigHandler {
public:
ConfigHandler();
virtual ~ConfigHandler();
bool openConfigFile(std::string);
std::string getTrackerNetFile();
std::string getGestureNetFile();
float getGestureThreshold();
};
#endif /* CONFIGHANDLER_H_ */
| [
"latesisdegrado@048d8772-f3ab-11dd-a8e2-f7cb3c35fcff"
] | [
[
[
1,
30
]
]
] |
c64903e7d3b66f5ac4c2b85a4c23f8534c22467f | 698f3c3f0e590424f194a4c138ed9706eb28b34f | /Classes/PlayingScene.h | 058e995404e282b8f2b9e184c11af00abe6981f6 | [] | no_license | nghepop/super-fashion-puzzle-cocos2d-x | 16b3a86072a6758fc2547b9e177bbfeebed82681 | 5e8d8637e3cf70b4ec45256347ccf7b350c11bce | refs/heads/master | 2021-01-10T06:28:10.028735 | 2011-12-03T23:49:16 | 2011-12-03T23:49:16 | 44,685,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,953 | h | #ifndef __playingscene_h__
#define __playingscene_h__
#include "cocos2d.h"
//#include "UIntegerLabel.h"
#include "BackgroundGirls.h"
#include "Board.h"
#include "TimeBar.h"
using namespace cocos2d;
typedef enum {
STARTING_STATE_GS,
READY,
PLAYING, // uses a nested state chart
PAUSED,
PAUSE_BY_LOCK,
GAME_OVER,
ENDING_STATE_GS
} GameState;
class Board;
class PlayingScene : public CCScene
{
public:
PlayingScene(void){};
~PlayingScene(void);
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init(void);
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::CCScene* scene(void);
// implement the "static node()" method manually
LAYER_NODE_FUNC(PlayingScene);
Board* m_board;
CCSprite* m_readySprite;
CCSprite* m_gameOverSprite;
CCSprite* m_girlTransition; // used when current girl have to be changed
CCSprite* m_score_and_level_sprite;
//UIntegerLabel* m_scoreLabel;
//UIntegerLabel* m_levelLabel;
TimeBar* m_timeBar;
BackgroundGirls* m_backgroundGirls;
CCMenu* m_pauseMenu;
bool m_playedTooMuch;
// vars for "game" FSM
GameState m_state;
public:
void onEnter(void);
void onExit(void);
void onEnterTransitionDidFinish(void);
void pauseButtonPressed(CCObject* pSender);
void readySequenceFinished(CCObject* pSender);
void playReadySoundFX(CCObject* pSender);
void timeUp(void);
void gameOverAnmationFinished(void);
void reset(void);
void onResume(void);
bool isPlaying(void);
unsigned int getLevel(void);
void checkGameLayout();
void applicationWillResginActive(void);
void playedTooMuch(void);
// Game FSM managment
void changeGameState( GameState state);
void onEnterGameState( GameState state);
void onExitGameState( GameState state);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
22d54162c696fa88df9a9f043af4d9f8a3cd1bcc | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/samples/waveidl/idl.cpp | 28a206715bad4a6d72aaa1622763ad27a9008117 | [
"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 | 19,970 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Sample: IDL oriented preprocessor
http://www.boost.org/
Copyright (c) 2001-2007 Hartmut Kaiser. 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)
=============================================================================*/
#include "idl.hpp" // global configuration
#include <boost/assert.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
///////////////////////////////////////////////////////////////////////////////
// Include Wave itself
#include <boost/wave.hpp>
///////////////////////////////////////////////////////////////////////////////
// Include the lexer related stuff
#include <boost/wave/cpplexer/cpp_lex_token.hpp> // token type
#include "idllexer/idl_lex_iterator.hpp" // lexer type
///////////////////////////////////////////////////////////////////////////////
// include lexer specifics, import lexer names
//
#if BOOST_WAVE_SEPARATE_LEXER_INSTANTIATION == 0
#include "idllexer/idl_re2c_lexer.hpp"
#endif
///////////////////////////////////////////////////////////////////////////////
// include the grammar definitions, if these shouldn't be compiled separately
// (ATTENTION: _very_ large compilation times!)
//
#if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION == 0
#include <boost/wave/grammars/cpp_intlit_grammar.hpp>
#include <boost/wave/grammars/cpp_chlit_grammar.hpp>
#include <boost/wave/grammars/cpp_grammar.hpp>
#include <boost/wave/grammars/cpp_expression_grammar.hpp>
#include <boost/wave/grammars/cpp_predef_macros_grammar.hpp>
#include <boost/wave/grammars/cpp_defined_grammar.hpp>
#endif
///////////////////////////////////////////////////////////////////////////////
// import required names
using namespace boost::spirit;
using std::string;
using std::pair;
using std::vector;
using std::getline;
using std::ifstream;
using std::cout;
using std::cerr;
using std::endl;
using std::ostream;
using std::istreambuf_iterator;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
///////////////////////////////////////////////////////////////////////////////
// print the current version
int print_version()
{
typedef boost::wave::idllexer::lex_iterator<
boost::wave::cpplexer::lex_token<> >
lex_iterator_type;
typedef boost::wave::context<std::string::iterator, lex_iterator_type>
context_type;
string version (context_type::get_version_string());
cout
<< version.substr(1, version.size()-2) // strip quotes
<< " (" << IDL_VERSION_DATE << ")" // add date
<< endl;
return 0; // exit app
}
///////////////////////////////////////////////////////////////////////////////
// print the copyright statement
int print_copyright()
{
char const *copyright[] = {
"",
"Sample: IDL oriented preprocessor",
"Based on: Wave, A Standard conformant C++ preprocessor library",
"It is hosted by http://www.boost.org/.",
"",
"Copyright (c) 2001-2006 Hartmut Kaiser, 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)",
0
};
for (int i = 0; 0 != copyright[i]; ++i)
cout << copyright[i] << endl;
return 0; // exit app
}
///////////////////////////////////////////////////////////////////////////////
namespace cmd_line_util {
// Additional command line parser which interprets '@something' as an
// option "config-file" with the value "something".
pair<string, string> at_option_parser(string const&s)
{
if ('@' == s[0])
return std::make_pair(string("config-file"), s.substr(1));
else
return pair<string, string>();
}
// class, which keeps include file information read from the command line
class include_paths {
public:
include_paths() : seen_separator(false) {}
vector<string> paths; // stores user paths
vector<string> syspaths; // stores system paths
bool seen_separator; // command line contains a '-I-' option
// Function which validates additional tokens from command line.
static void
validate(boost::any &v, vector<string> const &tokens)
{
if (v.empty())
v = boost::any(include_paths());
include_paths *p = boost::any_cast<include_paths>(&v);
BOOST_ASSERT(p);
// Assume only one path per '-I' occurrence.
string t = tokens[0];
if (t == "-") {
// found -I- option, so switch behaviour
p->seen_separator = true;
}
else if (p->seen_separator) {
// store this path as a system path
p->syspaths.push_back(t);
}
else {
// store this path as an user path
p->paths.push_back(t);
}
}
};
// Read all options from a given config file, parse and add them to the
// given variables_map
void read_config_file_options(string const &filename,
po::options_description const &desc, po::variables_map &vm,
bool may_fail = false)
{
ifstream ifs(filename.c_str());
if (!ifs.is_open()) {
if (!may_fail) {
cerr << filename
<< ": command line warning: config file not found"
<< endl;
}
return;
}
vector<string> options;
string line;
while (std::getline(ifs, line)) {
// skip empty lines
string::size_type pos = line.find_first_not_of(" \t");
if (pos == string::npos)
continue;
// skip comment lines
if ('#' != line[pos])
options.push_back(line);
}
if (options.size() > 0) {
using namespace boost::program_options::command_line_style;
po::store(po::command_line_parser(options)
.options(desc).style(unix_style).run(), vm);
po::notify(vm);
}
}
// predicate to extract all positional arguments from the command line
struct is_argument {
bool operator()(po::option const &opt)
{
return (opt.position_key == -1) ? true : false;
}
};
///////////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
//
// Special validator overload, which allows to handle the -I- syntax for
// switching the semantics of an -I option.
//
///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace program_options {
void validate(boost::any &v, std::vector<std::string> const &s,
cmd_line_util::include_paths *, int)
{
cmd_line_util::include_paths::validate(v, s);
}
}} // namespace boost::program_options
///////////////////////////////////////////////////////////////////////////////
// do the actual preprocessing
int
do_actual_work (std::string file_name, po::variables_map const &vm)
{
// current file position is saved for exception handling
boost::wave::util::file_position_type current_position;
try {
// process the given file
ifstream instream(file_name.c_str());
string instring;
if (!instream.is_open()) {
cerr << "waveidl: could not open input file: " << file_name << endl;
return -1;
}
instream.unsetf(std::ios::skipws);
#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
// this is known to be very slow for large files on some systems
copy (istream_iterator<char>(instream),
istream_iterator<char>(),
inserter(instring, instring.end()));
#else
instring = string(istreambuf_iterator<char>(instream.rdbuf()),
istreambuf_iterator<char>());
#endif
// This sample uses the lex_token type predefined in the Wave library, but
// but uses a custom lexer type.
typedef boost::wave::idllexer::lex_iterator<
boost::wave::cpplexer::lex_token<> >
lex_iterator_type;
typedef boost::wave::context<std::string::iterator, lex_iterator_type>
context_type;
// The C++ preprocessor iterators shouldn't be constructed directly. They
// are to be generated through a boost::wave::context<> object. This
// boost::wave::context object is additionally to be used to initialize and
// define different parameters of the actual preprocessing.
// The preprocessing of the input stream is done on the fly behind the
// scenes during iteration over the context_type::iterator_type stream.
context_type ctx (instring.begin(), instring.end(), file_name.c_str());
// add include directories to the system include search paths
if (vm.count("sysinclude")) {
vector<string> const &syspaths =
vm["sysinclude"].as<vector<string> >();
vector<string>::const_iterator end = syspaths.end();
for (vector<string>::const_iterator cit = syspaths.begin();
cit != end; ++cit)
{
ctx.add_sysinclude_path((*cit).c_str());
}
}
// add include directories to the include search paths
if (vm.count("include")) {
cmd_line_util::include_paths const &ip =
vm["include"].as<cmd_line_util::include_paths>();
vector<string>::const_iterator end = ip.paths.end();
for (vector<string>::const_iterator cit = ip.paths.begin();
cit != end; ++cit)
{
ctx.add_include_path((*cit).c_str());
}
// if on the command line was given -I- , this has to be propagated
if (ip.seen_separator)
ctx.set_sysinclude_delimiter();
// add system include directories to the include path
vector<string>::const_iterator sysend = ip.syspaths.end();
for (vector<string>::const_iterator syscit = ip.syspaths.begin();
syscit != sysend; ++syscit)
{
ctx.add_sysinclude_path((*syscit).c_str());
}
}
// add additional defined macros
if (vm.count("define")) {
vector<string> const ¯os = vm["define"].as<vector<string> >();
vector<string>::const_iterator end = macros.end();
for (vector<string>::const_iterator cit = macros.begin();
cit != end; ++cit)
{
ctx.add_macro_definition(*cit);
}
}
// add additional predefined macros
if (vm.count("predefine")) {
vector<string> const &predefmacros =
vm["predefine"].as<vector<string> >();
vector<string>::const_iterator end = predefmacros.end();
for (vector<string>::const_iterator cit = predefmacros.begin();
cit != end; ++cit)
{
ctx.add_macro_definition(*cit, true);
}
}
// undefine specified macros
if (vm.count("undefine")) {
vector<string> const &undefmacros =
vm["undefine"].as<vector<string> >();
vector<string>::const_iterator end = undefmacros.end();
for (vector<string>::const_iterator cit = undefmacros.begin();
cit != end; ++cit)
{
ctx.remove_macro_definition((*cit).c_str(), true);
}
}
// open the output file
std::ofstream output;
if (vm.count("output")) {
// try to open the file, where to put the preprocessed output
string out_file (vm["output"].as<string>());
output.open(out_file.c_str());
if (!output.is_open()) {
cerr << "waveidl: could not open output file: " << out_file
<< endl;
return -1;
}
}
else {
// output the preprocessed result to std::cout
output.copyfmt(cout);
output.clear(cout.rdstate());
static_cast<std::basic_ios<char> &>(output).rdbuf(cout.rdbuf());
}
// analyze the input file
context_type::iterator_type first = ctx.begin();
context_type::iterator_type last = ctx.end();
// loop over all generated tokens outputing the generated text
while (first != last) {
// print out the string representation of this token (skip comments)
using namespace boost::wave;
// store the last known good token position
current_position = (*first).get_position();
token_id id = token_id(*first);
if (T_CPPCOMMENT == id || T_NEWLINE == id) {
// C++ comment tokens contain the trailing newline
output << endl;
}
else if (id != T_CCOMMENT) {
// print out the current token value
output << (*first).get_value();
}
++first; // advance to the next token
}
}
catch (boost::wave::cpp_exception const& e) {
// some preprocessing error
cerr
<< e.file_name() << "(" << e.line_no() << "): "
<< e.description() << endl;
return 1;
}
catch (boost::wave::cpplexer::lexing_exception const& e) {
// some lexing error
cerr
<< e.file_name() << "(" << e.line_no() << "): "
<< e.description() << endl;
return 2;
}
catch (std::exception const& e) {
// use last recognized token to retrieve the error position
cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "exception caught: " << e.what()
<< endl;
return 3;
}
catch (...) {
// use last recognized token to retrieve the error position
cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "unexpected exception caught." << endl;
return 4;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// main entry point
int
main (int argc, char *argv[])
{
try {
// analyze the command line options and arguments
// declare the options allowed from the command line only
po::options_description desc_cmdline ("Options allowed on the command line only");
desc_cmdline.add_options()
("help,h", "print out program usage (this message)")
("version,v", "print the version number")
("copyright,c", "print out the copyright statement")
("config-file", po::value<vector<string> >(),
"specify a config file (alternatively: @filepath)")
;
// declare the options allowed on command line and in config files
po::options_description desc_generic ("Options allowed additionally in a config file");
desc_generic.add_options()
("output,o", "specify a file to use for output instead of stdout")
("include,I", po::value<cmd_line_util::include_paths>()->composing(),
"specify an additional include directory")
("sysinclude,S", po::value<vector<string> >()->composing(),
"specify an additional system include directory")
("define,D", po::value<vector<string> >()->composing(),
"specify a macro to define (as macro[=[value]])")
("predefine,P", po::value<vector<string> >()->composing(),
"specify a macro to predefine (as macro[=[value]])")
("undefine,U", po::value<vector<string> >()->composing(),
"specify a macro to undefine")
;
// combine the options for the different usage schemes
po::options_description desc_overall_cmdline;
po::options_description desc_overall_cfgfile;
desc_overall_cmdline.add(desc_cmdline).add(desc_generic);
desc_overall_cfgfile.add(desc_generic);
// parse command line and store results
using namespace boost::program_options::command_line_style;
po::parsed_options opts = po::parse_command_line(argc, argv,
desc_overall_cmdline, unix_style, cmd_line_util::at_option_parser);
po::variables_map vm;
po::store(opts, vm);
po::notify(vm);
// Try to find a waveidl.cfg in the same directory as the executable was
// started from. If this exists, treat it as a wave config file
fs::path filename(argv[0], fs::native);
filename = filename.branch_path() / "waveidl.cfg";
cmd_line_util::read_config_file_options(filename.string(),
desc_overall_cfgfile, vm, true);
// if there is specified at least one config file, parse it and add the
// options to the main variables_map
if (vm.count("config-file")) {
vector<string> const &cfg_files =
vm["config-file"].as<vector<string> >();
vector<string>::const_iterator end = cfg_files.end();
for (vector<string>::const_iterator cit = cfg_files.begin();
cit != end; ++cit)
{
// parse a single config file and store the results
cmd_line_util::read_config_file_options(*cit,
desc_overall_cfgfile, vm);
}
}
// ... act as required
if (vm.count("help")) {
po::options_description desc_help (
"Usage: waveidl [options] [@config-file(s)] file");
desc_help.add(desc_cmdline).add(desc_generic);
cout << desc_help << endl;
return 1;
}
if (vm.count("version")) {
return print_version();
}
if (vm.count("copyright")) {
return print_copyright();
}
// extract the arguments from the parsed command line
vector<po::option> arguments;
std::remove_copy_if(opts.options.begin(), opts.options.end(),
inserter(arguments, arguments.end()), cmd_line_util::is_argument());
// if there is no input file given, then exit
if (0 == arguments.size() || 0 == arguments[0].value.size()) {
cerr << "waveidl: no input file given, "
<< "use --help to get a hint." << endl;
return 5;
}
// preprocess the given input file
return do_actual_work(arguments[0].value[0], vm);
}
catch (std::exception const& e) {
cout << "waveidl: exception caught: " << e.what() << endl;
return 6;
}
catch (...) {
cerr << "waveidl: unexpected exception caught." << endl;
return 7;
}
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
537
]
]
] |
16c215743d51dc3e53363c36eb2b0c8d04199963 | 718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1 | /soft micros/Codigo/codigo portable/Timer/Timer.cpp | 96a43f6f965a690a72e4f4eb232d2ed85fb9b7ea | [] | no_license | jonyMarino/microsdhacel | affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca | 66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3 | refs/heads/master | 2020-05-18T19:53:51.301695 | 2011-05-30T20:40:24 | 2011-05-30T20:40:24 | 34,532,512 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 5,197 | cpp | #include "Timer.hpp"
#include "stddef.h"
#include "stdtypes.h"
#include "BaseTimers.hpp"
#pragma DATA_SEG Timer_DATA
#pragma CODE_SEG Timer_CODE
#pragma CONST_SEG DEFAULT
BaseTimers *Timer::baseTimerDefault=NULL;
void Timer::setBaseTimerDefault(BaseTimers& b){
baseTimerDefault = &b;
}
/*
** ===================================================================
** Method : Timer_Construct
** Description : Metodo para setear los
** valores de configuración del contador
** ===================================================================
*/
Timer::Timer(ulong tiempo){
baseTimer = baseTimerDefault;
ulong cuenta = baseTimer->getCuenta();
this->tiempo= tiempo;
this->next_cuenta=cuenta+tiempo;
if(cuenta >= this->next_cuenta)
this->of=TRUE;
else
this->of=FALSE;
baseTimer->add(this);
}
/*
** ===================================================================
** Method : Timer_Destruct
** Description : Metodo para destruir el Timer
** ===================================================================
*/
Timer::~Timer(){
stop();
}
/*
** ===================================================================
** Method : setBaseTimer
** Description : setea la entrada de ticks del timer
** ===================================================================
*/
void Timer::setBaseTimer(BaseTimers * base){
if(baseTimer)
baseTimer->moveOut(this);
baseTimer = base;
}
/*
** ===================================================================
** Method : Timer_OnTime
** Description : Evento al llegar al tiempo fijado
** ===================================================================
*/
void Timer::onTime(){
stop();
}
/*
** ===================================================================
** Method : comparar
** Description :
** ===================================================================
*/
void Timer::comparar(){
bool comp;
ulong cuentaTmp = baseTimer->getCuenta();
ulong nextCuentaTmp = this->next_cuenta;
ulong tiempoTmp = this->tiempo;
if(this->of)
comp= cuentaTmp <= nextCuentaTmp;
else
comp= cuentaTmp >= nextCuentaTmp;
if (comp ){
int error = cuentaTmp - nextCuentaTmp;
error = (error<0)?-error:error;
nextCuentaTmp += error + tiempoTmp;
baseTimer->lockInc();
this->next_cuenta=nextCuentaTmp;
baseTimer->unlockInc();
if(cuentaTmp >= nextCuentaTmp){
this->of=TRUE;
}
onTime();
}
}
/*
** ===================================================================
** Method : Timer_getCuenta
** Description : Regresa la cuenta actual que se resetea al llegar al tiempo
** ===================================================================
*/
ulong Timer::getCuenta(){
ulong cuentaTmp;
ulong nextCuentaTmp;
ulong tiempoTmp;
if(isFinished())
return 0;
cuentaTmp = this->baseTimer->getCuenta();
nextCuentaTmp = this->next_cuenta;
tiempoTmp = this->tiempo;
return cuentaTmp - (nextCuentaTmp - tiempoTmp);
}
/*
** ===================================================================
** Method : Timer_isfinish
** Description : Indica si ya termino la cuenta
** ===================================================================
*/
uchar Timer::isFinished(){
if(this->baseTimer)
return !this->baseTimer->contains(this);
return TRUE;
}
/*
** ===================================================================
** Method : Timer_Restart
** Description : Reinicia la cuenta del tiempo
** ===================================================================
*/
void Timer::restart(){
ulong cuenta = this->baseTimer->getCuenta();
baseTimer->lockInc();
this->next_cuenta= cuenta + this->tiempo ;
baseTimer->unlockInc();
if(cuenta >= this->next_cuenta)
this->of=TRUE;
else
this->of=FALSE;
if(isFinished())
baseTimer->add(this);
}
/*
** ===================================================================
** Method : Timer_setTime
** Description : Setea un tiempo nuevo y reinicia la cuenta del tiempo
** ===================================================================
*/
void Timer::setTime(ulong tiempo){
baseTimer->lockInc();
this->tiempo=tiempo;
baseTimer->unlockInc();
restart();
}
/*
** ===================================================================
** Method : Timer_getTime
** Description : Obtiene el tiempo a alcanzar
** ===================================================================
*/
ulong Timer::getTime(){
return tiempo;
}
/*
** ===================================================================
** Method : Timer_Stop
** Description : Detiene la cuenta del timer
** ===================================================================
*/
void Timer::stop(){
baseTimer->moveOut(this);
}
#pragma CODE_SEG Timer_CODE
| [
"nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549",
"jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549"
] | [
[
[
1,
89
],
[
93,
189
]
],
[
[
90,
92
]
]
] |
5e644e71a3c86dd72e13b6c04aa05bc00ebbc9a2 | 42b578d005c2e8870a03fe02807e5607fec68f40 | /src/pathname.cc | 51a2da9f0fd783741b9f3f27e20c5049fcb4fb78 | [
"MIT"
] | permissive | hylom/xom | e2b02470cd984d0539ded408d13f9945af6e5f6f | a38841cfe50c3e076b07b86700dfd01644bf4d4a | refs/heads/master | 2021-01-23T02:29:51.908501 | 2009-10-30T08:41:30 | 2009-10-30T08:41:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,376 | cc | #include "ed.h"
#include "pathname.h"
#include "dyn-handle.h"
#include "environ.h"
#include <io.h>
#include <math.h>
#include "except.h"
#include "mman.h"
#include <winioctl.h>
#include "thread.h"
#include "xstrlist.h"
#include "vwin32.h"
static lisp
file_error_condition (int e)
{
switch (e)
{
case ERROR_FILE_NOT_FOUND:
return QCfile_not_found;
case ERROR_PATH_NOT_FOUND:
return QCpath_not_found;
case ERROR_ACCESS_DENIED:
return QCaccess_denied;
case ERROR_INVALID_DRIVE:
return QCinvalid_drive;
case ERROR_CURRENT_DIRECTORY:
return QCcurrent_directory;
case ERROR_NOT_SAME_DEVICE:
return QCnot_same_device;
case ERROR_WRITE_PROTECT:
return QCwrite_protected;
case ERROR_BAD_UNIT:
return QCbad_unit;
case ERROR_NOT_READY:
return QCdevice_not_ready;
case ERROR_SHARING_VIOLATION:
return QCsharing_violation;
case ERROR_LOCK_VIOLATION:
return QClock_violation;
case ERROR_WRONG_DISK:
return QCwrong_disk;
case ERROR_FILE_EXISTS:
case ERROR_ALREADY_EXISTS:
return QCfile_exists;
case ERROR_DIR_NOT_EMPTY:
return QCnot_empty;
default:
return QCfile_error;
}
}
void
file_error (message_code c, lisp path)
{
FEfile_error (c, path);
}
void
file_error (message_code c)
{
FEfile_error (c, Qnil);
}
void
file_error (int e, lisp path)
{
FEwin32_file_error (xsymbol_value (file_error_condition (e)), e, path);
}
void
file_error (int e)
{
FEwin32_file_error (xsymbol_value (file_error_condition (e)), e);
}
static Char *
skip_device_or_host (const Char *p, const Char *pe)
{
if (dir_separator_p (*p) && dir_separator_p (p[1]))
{
// skip hostname
for (p += 2; p < pe && !dir_separator_p (*p); p++)
;
// skip shared name
if (p < pe)
for (p++; p < pe && !dir_separator_p (*p); p++)
;
}
else if (alpha_char_p (*p) && p[1] == ':')
p += 2;
return (Char *)p;
}
static Char *
copy_Chars (Char *b, const Char *p, const Char *pe)
{
int l = pe - p;
bcopy (p, b, l);
return b + l;
}
static char devdirs[26][PATH_MAX];
int
set_device_dir (const char *path, int f)
{
if (!WINFS::SetCurrentDirectory (path))
return 0;
if (f || xsymbol_value (Vauto_update_per_device_directory) != Qnil)
{
char curdir[PATH_MAX];
if (GetCurrentDirectory (sizeof curdir, curdir)
&& alpha_char_p (*curdir & 255) && curdir[1] == ':')
strcpy (devdirs[_char_downcase (*curdir) - 'a'], curdir + 2);
}
return 1;
}
const char *
get_device_dir (int c)
{
return devdirs[c];
}
static Char *
get_device_dir (Char *b, const Char *p, int l)
{
if (l == 2 && alpha_char_p (*p) && p[1] == ':'
&& *devdirs[_char_downcase (*p) - 'a'])
return s2w (b, devdirs[_char_downcase (*p) - 'a']);
char buf[PATH_MAX + 1], path[PATH_MAX + 1], *tem;
w2s (buf, p, l);
if (WINFS::GetFullPathName (buf, sizeof path, path, &tem))
{
Char *be = s2w (b, path);
return copy_Chars (b, skip_device_or_host (b, be), be);
}
return b;
}
static void
parse_name_simple (pathname &path, const Char *p, const Char *pe)
{
path.dev = p;
path.deve = skip_device_or_host (p, pe);
path.trail = path.deve;
path.traile = pe;
}
static void
parse_name (pathname &path, const Char *p, const Char *pe)
{
const Char *t = skip_device_or_host (p, pe);
if (t == p)
path.dev = path.deve = 0;
else
{
path.dev = p;
path.deve = t;
p = t;
}
path.trail = p;
path.traile = pe;
pe--;
const Char *pe2 = pe - 1;
while (p < pe)
{
while (p < pe && dir_separator_p (*p))
{
p++;
if (dir_separator_p (*p)) // `//' or `\\'
path.trail = p;
else if (*p == '~' && (p == pe || dir_separator_p (p[1])))
{
path.trail = p;
p++;
}
else if (p <= pe2 && alpha_char_p (*p) && p[1] == ':')
{
path.dev = p;
p += 2;
path.deve = p;
path.trail = p;
}
}
while (p < pe && !dir_separator_p (*p))
p++;
}
}
int
parse_namestring (pathbuf_t buf, const Char *name, int nl, const Char *defalt, int dl)
{
pathname path, tem;
parse_name (path, name, name + nl);
const Char *trail = path.trail;
const Char *traile = path.traile;
if (trail < traile && *trail == '~'
&& (trail + 1 == traile || dir_separator_p (trail[1])))
{
lisp home = xsymbol_value (Qhome_dir);
parse_name_simple (tem, xstring_contents (home),
xstring_contents (home) + xstring_length (home));
path.dev = tem.dev;
path.deve = tem.deve;
if (trail + 1 == traile)
path.trail = traile;
else
path.trail += 2;
trail = tem.trail;
traile = tem.traile;
}
if (path.dev == path.deve)
path.dev = 0;
Char *b = buf;
Char *root;
int abs = trail < traile && dir_separator_p (*trail);
if (path.dev && abs)
{
b = root = copy_Chars (b, path.dev, path.deve);
b = copy_Chars (b, trail, traile);
}
else
{
parse_name_simple (tem, defalt, defalt + dl);
if (!path.dev)
{
path.dev = tem.dev;
path.deve = tem.deve;
}
b = root = copy_Chars (b, path.dev, path.deve);
if (!abs)
{
int l = path.deve - path.dev;
if (tem.deve - tem.dev == l && !memicmp (path.dev, tem.dev, sizeof *path.dev * l))
b = copy_Chars (b, tem.trail, tem.traile);
else
b = get_device_dir (b, path.dev, l);
if (b == buf || !dir_separator_p (b[-1]))
*b++ = SEPCHAR;
b = copy_Chars (b, trail, traile);
}
else
b = copy_Chars (b, trail, traile);
}
if (trail != path.trail)
{
if (b == buf || !dir_separator_p (b[-1]))
*b++ = SEPCHAR;
b = copy_Chars (b, path.trail, path.traile);
}
*b = 0;
Char *p = root, *pe = b;
b = root;
while (p < pe)
{
if (dir_separator_p (*p))
{
if (p[1] == '.')
{
if (!p[2] || dir_separator_p (p[2]))
{
p += 2;
continue;
}
else if (p[2] == '.' && (!p[3] || dir_separator_p (p[3])))
{
for (; b > root && !dir_separator_p (b[-1]); b--)
;
if (b != root)
b--;
p += 3;
continue;
}
}
}
*b++ = *p++;
}
if (b == root)
*b++ = SEPCHAR;
else if (b > root + 1 && dir_separator_p (b[-1]))
b--;
if (b[-1] == '.')
{
for (p = b - 1; p > root && p[-1] == '.'; p--)
;
if (p[-1] != SEPCHAR)
for (const Char *q = p; q > root;)
{
Char c = *--q;
if (c == SEPCHAR)
{
b = p;
break;
}
if (c == '*' || c == '?')
break;
}
}
return b - buf;
}
void
map_backsl_to_sl (Char *p, int l)
{
for (int i = 0; i < l; i++, p++)
if (*p == '\\')
*p = '/';
}
static void
coerce_to_pathname (lisp &pathname, pathbuf_t buf, const Char *&b, int &l)
{
if (stringp (pathname))
{
if (xstring_length (pathname) >= WPATH_MAX)
FEsimple_error (Epath_name_too_long, pathname);
l = parse_namestring (buf, xstring_contents (pathname), xstring_length (pathname), b, l);
if (l >= WPATH_MAX)
FEsimple_error (Epath_name_too_long, pathname);
map_backsl_to_sl (buf, l);
b = buf;
}
else if (streamp (pathname) && file_stream_p (pathname)
&& stringp (xfile_stream_pathname (pathname)))
{
pathname = xfile_stream_pathname (pathname);
b = xstring_contents (pathname);
l = xstring_length (pathname);
}
else
FEtype_error (pathname, Qpathname);
}
static lisp
default_directory ()
{
if (selected_window ())
{
Buffer *bp = selected_buffer ();
if (bp)
return bp->ldirectory;
}
return xsymbol_value (Qdefault_dir);
}
static lisp
coerce_to_pathname (lisp pathname, pathbuf_t buf, const Char *&b, const Char *&be)
{
lisp d = default_directory ();
b = xstring_contents (d);
int l = xstring_length (d);
coerce_to_pathname (pathname, buf, b, l);
be = b + l;
return pathname;
}
lisp
Fmerge_pathnames (lisp pathname, lisp defaults)
{
lisp d = default_directory ();
const Char *b = xstring_contents (d);
int l = xstring_length (d);
pathbuf_t buf1, buf2;
if (defaults && defaults != Qnil)
coerce_to_pathname (defaults, buf1, b, l);
coerce_to_pathname (pathname, buf2, b, l);
if (b != buf2)
return pathname;
if (stringp (pathname)
&& l == xstring_length (pathname)
&& !bcmp (b, xstring_contents (pathname), l))
return pathname;
return make_string (b, l);
}
lisp
Fnamestring (lisp name)
{
return Fmerge_pathnames (name, 0);
}
static int
has_trail_slash_p (lisp pathname, int dot)
{
if (stringp (pathname) && xstring_length (pathname))
{
const Char *p = xstring_contents (pathname);
if (dir_separator_p (p[xstring_length (pathname) - 1]))
return 1;
if (dot && p[xstring_length (pathname) - 1] == '.'
&& (xstring_length (pathname) == 1
|| dir_separator_p (p[xstring_length (pathname) - 2])))
return 1;
}
return 0;
}
lisp
Fappend_trail_slash (lisp pathname)
{
check_string (pathname);
if (has_trail_slash_p (pathname, 0))
return pathname;
lisp p = make_string (xstring_length (pathname) + 1);
bcopy (xstring_contents (pathname), xstring_contents (p), xstring_length (pathname));
xstring_contents (p) [xstring_length (pathname)] = SEPCHAR;
return p;
}
lisp
Fremove_trail_slash (lisp pathname)
{
check_string (pathname);
if (!has_trail_slash_p (pathname, 0))
return pathname;
return make_string (xstring_contents (pathname), xstring_length (pathname) - 1);
}
lisp
Ffile_namestring (lisp pathname)
{
if (has_trail_slash_p (pathname, 1))
return make_string ("");
pathbuf_t buf;
const Char *p0, *pe;
pathname = coerce_to_pathname (pathname, buf, p0, pe);
for (const Char *p = pe; p > p0; p--)
if (p[-1] == SEPCHAR)
return make_string (p, pe - p);
return pathname;
}
lisp
Fdirectory_namestring (lisp pathname)
{
int dirp = has_trail_slash_p (pathname, 1);
pathbuf_t buf;
const Char *p0, *pe;
pathname = coerce_to_pathname (pathname, buf, p0, pe);
if (dirp && p0 != pe)
{
if (p0 != buf)
bcopy (p0, buf, pe - p0);
Char *be = buf + (pe - p0);
if (!dir_separator_p (be[-1]))
*be++ = '/';
if (stringp (pathname)
&& be - buf == xstring_length (pathname)
&& !bcmp (buf, xstring_contents (pathname), xstring_length (pathname)))
return pathname;
return make_string (buf, be - buf);
}
for (const Char *p = pe; p > p0; p--)
if (p[-1] == SEPCHAR)
return make_string (p0, p - p0);
return make_string ("");
}
lisp
Fpathname_host (lisp pathname)
{
pathbuf_t buf;
const Char *p0, *pe;
pathname = coerce_to_pathname (pathname, buf, p0, pe);
if (pe - p0 < 3)
return Qnil;
if (*p0 != SEPCHAR || p0[1] != SEPCHAR)
return Qnil;
p0 += 2;
for (const Char *p = p0; p < pe && *p != SEPCHAR; p++)
;
if (p == p0)
return Qnil;
return make_string (p0, p - p0);
}
lisp
Fpathname_device (lisp pathname)
{
pathbuf_t buf;
const Char *p, *pe;
pathname = coerce_to_pathname (pathname, buf, p, pe);
if (pe - p < 2)
return Qnil;
if (alpha_char_p (*p) && p[1] == ':')
return make_string (*p, 1);
return Qnil;
}
lisp
Fpathname_directory (lisp pathname)
{
pathbuf_t buf;
const Char *p, *pe;
pathname = coerce_to_pathname (pathname, buf, p, pe);
lisp dirs = Qnil;
if (p + 3 <= pe && *p == SEPCHAR && p[1] == SEPCHAR)
for (p += 2; p < pe && *p != SEPCHAR; p++)
;
else if (p + 2 <= pe && alpha_char_p (*p) && p[1] == ':')
p += 2;
while (p < pe)
{
const Char *p0 = p;
for (; p < pe && *p != SEPCHAR; p++)
;
if (p == pe)
break;
if (p != p0)
dirs = xcons (make_string (p0, p - p0), dirs);
p++;
}
return Fnreverse (dirs);
}
static const Char *
pathname_name_type (lisp pathname, pathbuf_t buf,
const Char *&name, const Char *&name_e,
const Char *&type, const Char *&type_e)
{
const Char *p0, *pe;
pathname = coerce_to_pathname (pathname, buf, p0, pe);
for (const Char *p = pe; p > p0; p--)
if (p[-1] == SEPCHAR)
break;
for (const Char *dot = p; dot < pe && *dot == '.'; dot++)
;
for (const Char *p2 = pe; p2 > dot; p2--)
if (p2[-1] == '.')
break;
name = p;
name_e = p2 == dot ? pe : p2 - 1;
type = p2 != dot ? p2 : pe;
type_e = pe;
return p0;
}
lisp
Fpathname_name (lisp pathname)
{
pathbuf_t buf;
const Char *name, *name_e, *type, *type_e;
pathname_name_type (pathname, buf, name, name_e, type, type_e);
return name == name_e ? Qnil : make_string (name, name_e - name);
}
lisp
Fpathname_type (lisp pathname)
{
pathbuf_t buf;
const Char *name, *name_e, *type, *type_e;
pathname_name_type (pathname, buf, name, name_e, type, type_e);
return type == type_e ? Qnil : make_string (type, type_e - type);
}
char *
pathname2cstr (lisp pathname, char *buf)
{
pathbuf_t tem;
const Char *p, *pe;
pathname = coerce_to_pathname (pathname, tem, p, pe);
return w2s (buf, p, pe - p);
}
static int
file_attributes (lisp pathname)
{
char path[PATH_MAX + 1];
pathname2cstr (pathname, path);
return WINFS::GetFileAttributes (path);
}
lisp
Ffile_exist_p (lisp file)
{
int x = file_attributes (file);
return boole (x != -1);
}
lisp
Ffile_readable_p (lisp file)
{
int x = file_attributes (file);
return boole (!(x & FILE_ATTRIBUTE_DIRECTORY));
}
lisp
Ffile_writable_p (lisp file)
{
int x = file_attributes (file);
return boole (!(x & (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_SYSTEM
| FILE_ATTRIBUTE_READONLY)));
}
lisp
Ffile_executable_p (lisp file)
{
/*NOTYET*/
return Qnil;
}
lisp
Ffile_directory_p (lisp file)
{
int x = file_attributes (file);
return boole (x != -1 && x & FILE_ATTRIBUTE_DIRECTORY);
}
int
special_file_p (const char *path)
{
HANDLE h = WINFS::CreateFile (path, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (h == INVALID_HANDLE_VALUE)
return 0;
int dev = GetFileType (h) != FILE_TYPE_DISK;
CloseHandle (h);
return dev;
}
lisp
Fspecial_file_p (lisp file)
{
char path[PATH_MAX + 1];
pathname2cstr (file, path);
return boole (special_file_p (path));
}
lisp
Fvalid_path_p (lisp file)
{
int x = file_attributes (file);
if (x != -1)
return Qt;
return boole (GetLastError () == ERROR_FILE_NOT_FOUND);
}
lisp
Fcheck_valid_pathname (lisp path)
{
int x = file_attributes (path);
if (x != -1)
return Qt;
int e = GetLastError ();
if (e != ERROR_FILE_NOT_FOUND)
file_error (e, path);
return Qnil;
}
lisp
Ftruename (lisp pathname)
{
char path[PATH_MAX + 1], truename[PATH_MAX + 1];
pathname2cstr (pathname, path);
if (WINFS::GetFileAttributes (path) == -1)
file_error (GetLastError (), pathname);
map_sl_to_backsl (path);
char *sl = 0;
if (alpha_char_p (*path & 0xff) && path[1] == ':' && path[2] == '\\')
sl = path + 2;
else if (*path == '\\' && path[1] == '\\')
{
sl = jindex (path + 2, '\\');
if (sl)
sl = jindex (sl + 1, '\\');
}
if (!sl)
sl = jindex (path, '\\');
if (!sl)
strcpy (truename, path);
else
{
sl++;
memcpy (truename, path, sl - path);
char *t = truename + (sl - path);
while (1)
{
char *p = jindex (sl, '\\');
if (p)
*p = 0;
WIN32_FIND_DATA fd;
if (WINFS::get_file_data (path, fd))
t = stpcpy (t, fd.cFileName);
else if (p)
memcpy (t, sl, p - sl);
else
strcpy (t, sl);
if (!p)
break;
*p = '\\';
sl = p + 1;
*t++ = '\\';
}
*t = 0;
}
map_backsl_to_sl (truename);
Char w[PATH_MAX + 1];
int l = s2w (w, truename) - w;
if (stringp (pathname) && l == xstring_length (pathname)
&& !bcmp (w, xstring_contents (pathname), l))
return pathname;
return make_string (w, l);
}
lisp
Fuser_homedir_pathname ()
{
return xsymbol_value (Qhome_dir);
}
int
match_suffixes (const char *name, lisp ignores)
{
int l = strlen (name);
for (; consp (ignores); ignores = xcdr (ignores))
{
lisp x = xcar (ignores);
if (!stringp (x))
continue;
if (xstring_length (x) <= l
&& strequal (name + l - xstring_length (x), xstring_contents (x)))
return 1;
}
return 0;
}
lisp
Ffile_system_supports_long_file_name_p (lisp path)
{
pathbuf_t buf;
const Char *p, *pe;
coerce_to_pathname (path, buf, p, pe);
if (pe - p < 2)
return Qnil;
Char *t = skip_device_or_host (p, pe);
if (p != buf)
bcopy (p, buf, t - p);
t = buf + (t - p);
*t++ = SEPCHAR;
char cbuf[PATH_MAX + 1];
w2s (cbuf, buf, t - buf);
DWORD maxl, flags;
return boole (WINFS::GetVolumeInformation (cbuf, 0, 0, 0, &maxl, &flags, 0, 0) && maxl > 12);
}
lisp
Fpath_equal (lisp lpath1, lisp lpath2)
{
char path1[PATH_MAX + 1], path2[PATH_MAX + 1];
pathname2cstr (lpath1, path1);
pathname2cstr (lpath2, path2);
return boole (same_file_p (path1, path2));
}
static int
sub_dirp_by_name (const char *dir, const char *parent)
{
int dl = strlen (dir);
const char *de = find_last_slash (dir);
if (de && !de[1])
dl--;
int pl = strlen (parent);
const char *pe = find_last_slash (parent);
if (pe && !pe[1])
pl--;
if (dl < pl)
return 0;
if (_memicmp (dir, parent, pl))
return 0;
return !dir[pl] || dir[pl] == '/';
}
int
sub_directory_p (char *dir, const char *parent)
{
if (sub_dirp_by_name (dir, parent))
{
DWORD a = WINFS::GetFileAttributes (dir);
if (a == -1 || !(a & FILE_ATTRIBUTE_DIRECTORY))
return 0;
a = WINFS::GetFileAttributes (parent);
if (a == -1 || !(a & FILE_ATTRIBUTE_DIRECTORY))
return 0;
return 1;
}
dyn_handle dh (WINFS::CreateFile (parent, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
if (!dh.valid ())
return 0;
BY_HANDLE_FILE_INFORMATION info;
info.dwFileAttributes = 0;
GetFileInformationByHandle (dh, &info);
if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
return 0;
while (1)
{
HANDLE h = WINFS::CreateFile (dir, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (h == INVALID_HANDLE_VALUE)
return 0;
BY_HANDLE_FILE_INFORMATION i;
i.dwFileAttributes = 0;
GetFileInformationByHandle (h, &i);
CloseHandle (h);
if (!(i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
return 0;
if (i.dwVolumeSerialNumber == info.dwVolumeSerialNumber
&& i.nFileIndexHigh == info.nFileIndexHigh
&& i.nFileIndexLow == info.nFileIndexLow)
return 1;
char *sl = find_last_slash (dir);
if (!sl)
return 0;
if (!sl[1])
{
*sl = 0;
sl = find_last_slash (dir);
if (!sl)
return 0;
}
sl[1] = 0;
if (!find_last_slash (dir))
return 1;
}
}
lisp
Fsub_directory_p (lisp ldir, lisp lparent)
{
char dir[PATH_MAX + 1], parent[PATH_MAX + 1];
pathname2cstr (ldir, dir);
pathname2cstr (lparent, parent);
return boole (sub_directory_p (dir, parent));
}
lisp
Fcompile_file_pathname (lisp pathname)
{
pathbuf_t buf;
const Char *name, *name_e, *type, *type_e;
const Char *p0 = pathname_name_type (pathname, buf, name, name_e, type, type_e);
if (name == name_e)
return Qnil;
int l = type_e - p0;
if (p0 != buf)
bcopy (p0, buf, l);
Char *b = buf + l;
if (type_e - type == 1 && (*type == 'l' || *type == 'L'))
*b++ = *type == 'l' ? 'c' : 'C';
else
{
if (type == type_e)
*b++ = '.';
else if (Ffile_system_supports_long_file_name_p (pathname) == Qnil)
b -= type_e - type;
else
*b++ = '.';
*b++ = 'l';
*b++ = 'c';
}
return make_string (buf, b - buf);
}
lisp
Ffind_load_path (lisp filename)
{
static const char *const ext[] = {".lc", ".l", "", 0};
check_string (filename);
if (xstring_length (filename) >= WPATH_MAX)
FEsimple_error (Epath_name_too_long, filename);
char file[PATH_MAX + 1];
w2s (file, filename);
for (const char *const *e = ext; *e; e++)
for (lisp p = xsymbol_value (Vload_path); consp (p); p = xcdr (p))
{
lisp x = xcar (p);
if (stringp (x) && xstring_length (x) < WPATH_MAX)
{
char path[PATH_MAX * 2 + 1];
pathname2cstr (x, path);
int l = strlen (path);
if (l && path[l - 1] != SEPCHAR)
path[l++] = SEPCHAR;
strcpy (stpcpy (path + l, file), *e);
DWORD a = WINFS::GetFileAttributes (path);
if (a != DWORD (-1) && !(a & FILE_ATTRIBUTE_DIRECTORY))
return make_string (path);
}
}
return Qnil;
}
void
FileTime::file_modtime (lisp filename, int dir_ok)
{
char path[PATH_MAX + 1];
pathname2cstr (filename, path);
WIN32_FIND_DATA fd;
if (!WINFS::get_file_data (path, fd)
|| (!dir_ok && fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
clear ();
else
{
dwLowDateTime = fd.ftLastWriteTime.dwLowDateTime;
dwHighDateTime = fd.ftLastWriteTime.dwHighDateTime;
}
}
lisp
Fcwd ()
{
return xsymbol_value (Qdefault_dir);
}
lisp
Fmake_temp_file_name (lisp lprefix, lisp lsuffix, lisp dir, lisp dirp)
{
char temp[PATH_MAX + 1], prefix[32], suffix[32];
if (lprefix == Qnil)
lprefix = 0;
if (lprefix)
{
check_string (lprefix);
if (xstring_length (lprefix) > 10)
FEsimple_error (Eprefix_too_long, lprefix);
w2s (prefix, lprefix);
}
if (lsuffix == Qnil)
lsuffix = 0;
if (lsuffix)
{
check_string (lsuffix);
if (xstring_length (lsuffix) > 10)
FEsimple_error (Esuffix_too_long, lsuffix);
w2s (suffix, lsuffix);
}
if (dir && dir != Qnil)
{
if (Ffile_directory_p (dir) == Qnil)
file_error (Enot_a_directory, dir);
pathname2cstr (dir, temp);
}
else if (!GetTempPath (sizeof temp, temp))
file_error (Ecannot_make_temp_file_name);
char *sl = find_last_slash (temp);
if (!sl)
file_error (Ecannot_make_temp_file_name);
if (sl[1])
strcat (sl, "/");
if (!make_temp_file_name (temp, lprefix ? prefix : 0, lsuffix ? suffix : 0,
0, dirp && dirp != Qnil))
file_error (Ecannot_make_temp_file_name);
map_backsl_to_sl (temp);
return make_string (temp);
}
lisp
Ffile_write_time (lisp file)
{
FileTime t (file, 1);
if (t.voidp ())
return Qnil;
#if 1
return file_time_to_universal_time (t);
#else
SYSTEMTIME st;
FileTimeToSystemTime (&t, &st);
return decoded_time_to_universal_time (st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, 0);
#endif
}
lisp
Fset_file_write_time (lisp lpath, lisp lutc)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
decoded_time dt;
dt.timezone = dt.daylight = 0;
decode_universal_time (lutc, &dt);
SYSTEMTIME st;
st.wYear = dt.year;
st.wMonth = dt.mon;
st.wDay = dt.day;
st.wHour = dt.hour;
st.wMinute = dt.min;
st.wSecond = dt.sec;
st.wMilliseconds = 0;
FILETIME ft;
SystemTimeToFileTime (&st, &ft);
dyn_handle w (WINFS::CreateFile (path, GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, 0));
if (!w.valid () || !SetFileTime (w, 0, 0, &ft))
file_error (GetLastError (), lpath);
return Qt;
}
lisp
Ffile_newer_than_file_p (lisp file1, lisp file2)
{
FileTime t1 (file1, 1), t2 (file2, 1);
if (t1.voidp ())
return Qnil;
if (t2.voidp ())
return Qt;
return boole (t1 > t2);
}
static lisp
exist_option (lisp option, lisp keys)
{
lisp x = find_keyword (option, keys);
if (x == Qnil)
x = Kerror;
else if (x != Kskip && x != Kerror)
FEprogram_error ((option == Kif_exists
? Einvalid_if_exists_option
: Einvalid_if_does_not_exist_option),
x);
return x;
}
static lisp
access_denied_option (lisp keys)
{
lisp x = find_keyword (Kif_access_denied, keys);
if (x == Qnil)
x = Kerror;
else if (x != Kerror && x != Kforce && x != Kskip)
FEprogram_error (Einvalid_if_access_denied_option, x);
return x;
}
static DWORD
solve_access_denied (lisp access_denied, const char *path, lisp lpath)
{
if (access_denied == Kskip)
return DWORD (-1);
if (access_denied == Kforce)
{
DWORD atr = WINFS::GetFileAttributes (path);
if (atr == -1)
file_error (GetLastError (), lpath);
if (!(atr & (FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_SYSTEM)))
file_error (ERROR_ACCESS_DENIED, lpath);
if (!WINFS::SetFileAttributes (path, (atr & ~(FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_SYSTEM))))
file_error (GetLastError (), lpath);
return atr;
}
else
file_error (ERROR_ACCESS_DENIED, lpath);
return 0; // not reached
}
lisp
Fdelete_file (lisp name, lisp keys)
{
char buf[PATH_MAX + 10];
pathname2cstr (name, buf);
lisp not_exist = exist_option (Kif_does_not_exist, keys);
lisp access_denied = access_denied_option (keys);
if (find_keyword_bool (Krecycle, keys))
{
typedef int (WINAPI *SHFILEOPERATION)(SHFILEOPSTRUCT *);
SHFILEOPERATION f = (SHFILEOPERATION)GetProcAddress (GetModuleHandle ("shell32"),
"SHFileOperation");
if (!f)
FEsimple_error (ESHFileOperation_not_supported);
map_sl_to_backsl (buf);
buf[strlen (buf) + 1] = 0;
SHFILEOPSTRUCT fs = {0};
fs.wFunc = FO_DELETE;
fs.pFrom = buf;
#ifndef FOF_NOERRORUI
#define FOF_NOERRORUI 0x0400
#endif
fs.fFlags = (FOF_ALLOWUNDO | FOF_FILESONLY | FOF_NOCONFIRMATION
| FOF_NOERRORUI | FOF_SILENT);
if ((*f)(&fs))
FEfile_error (Edelete_failed, name);
}
else
{
if (!WINFS::DeleteFile (buf))
{
int e = GetLastError ();
if (e == ERROR_ACCESS_DENIED)
{
DWORD atr = solve_access_denied (access_denied, buf, name);
if (atr == -1)
return Qnil;
if (WINFS::DeleteFile (buf))
return Qt;
e = GetLastError ();
WINFS::SetFileAttributes (buf, atr);
}
if (e == ERROR_FILE_NOT_FOUND && not_exist == Kskip)
return Qnil;
file_error (e, name);
}
}
return Qt;
}
static int
copyn (char *d, const char *s, int n, int l)
{
if (n < l)
l = check_kanji2 (s, n) ? n - 1 : n;
memcpy (d, s, l);
d[l] = 0;
return l;
}
static void
rename_short_name (const char *fpath, const char *tname, const char *longname)
{
char temppath[PATH_MAX + 1], tempname[PATH_MAX + 1], realpath[PATH_MAX + 1];
int l = tname - fpath;
memcpy (temppath, fpath, l);
temppath[l] = 0;
map_sl_to_backsl (temppath);
memcpy (realpath, fpath, l);
strcpy (realpath + l, longname);
if (!GetTempFileName (temppath, "xyz", 0, tempname))
return;
if (!WINFS::DeleteFile (tempname)
|| !WINFS::MoveFile (realpath, tempname))
return;
HANDLE h = WINFS::CreateFile (fpath, GENERIC_READ, 0, 0, CREATE_NEW,
FILE_ATTRIBUTE_ARCHIVE, 0);
if (h != INVALID_HANDLE_VALUE)
{
int r = WINFS::MoveFile (tempname, realpath);
CloseHandle (h);
WINFS::DeleteFile (fpath);
if (r)
return;
}
if (WINFS::MoveFile (tempname, realpath))
return;
if (WINFS::MoveFile (tempname, fpath)
&& WINFS::MoveFile (fpath, realpath))
return;
char buf[PATH_MAX * 3];
map_backsl_to_sl (tempname);
sprintf (buf, get_message_string (Erename_failed), tempname, realpath);
MsgBox (get_active_window (), buf, TitleBarString,
MB_OK | MB_ICONEXCLAMATION,
xsymbol_value (Vbeep_on_error) != Qnil);
}
static void
check_short_names (const char *from_path, const char *to_path)
{
if (xsymbol_value (Vrename_alternate_file_name) == Qnil)
return;
WIN32_FIND_DATA from_fd, to_fd;
if (!WINFS::get_file_data (to_path, to_fd))
return;
if (!*to_fd.cAlternateFileName
|| strcaseeq (to_fd.cFileName, to_fd.cAlternateFileName))
return;
if (!WINFS::get_file_data (from_path, from_fd))
return;
if (*from_fd.cAlternateFileName
&& !strcaseeq (from_fd.cFileName, from_fd.cAlternateFileName))
return;
if (!strcaseeq (from_fd.cFileName, to_fd.cAlternateFileName))
return;
const char *sf = find_last_slash (from_path);
if (!sf || !strcaseeq (sf + 1, from_fd.cFileName))
return;
const char *st = find_last_slash (to_path);
if (!st || !strcaseeq (st + 1, to_fd.cAlternateFileName))
return;
rename_short_name (to_path, st + 1, to_fd.cFileName);
}
enum
{
OFW_OK1,
OFW_OK2,
OFW_SKIP,
OFW_BAD
};
class safe_write_handle: public dyn_handle
{
int sw_complete;
int sw_delete_if_fail;
DWORD sw_atr;
char sw_path[PATH_MAX + 1];
public:
safe_write_handle (lisp);
~safe_write_handle ();
void set_org_atr (DWORD atr) {sw_atr = atr;}
void complete () {sw_complete = 1;}
int open_for_write (lisp, int, int &);
const char *path () const {return sw_path;}
int ensure_room (LONG, LONG);
};
safe_write_handle::safe_write_handle (lisp path)
: sw_complete (0), sw_delete_if_fail (0), sw_atr (DWORD (-1))
{
pathname2cstr (path, sw_path);
}
safe_write_handle::~safe_write_handle ()
{
if (!sw_complete && valid ())
{
if (sw_atr != -1)
WINFS::SetFileAttributes (sw_path, sw_atr);
if (sw_delete_if_fail)
{
close ();
WINFS::DeleteFile (sw_path);
}
}
}
int
safe_write_handle::open_for_write (lisp if_exists, int open_mode, int &e)
{
sw_delete_if_fail = 0;
fix (WINFS::CreateFile (sw_path, GENERIC_WRITE, 0, 0, open_mode,
FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN, 0));
if (valid ())
{
if (open_mode == OPEN_EXISTING)
;
else if (open_mode != OPEN_ALWAYS
|| GetLastError () != ERROR_ALREADY_EXISTS)
sw_delete_if_fail = 1;
return OFW_OK1;
}
e = GetLastError ();
if (if_exists == Kskip)
return ((e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS)
? OFW_SKIP : OFW_BAD);
if (if_exists != Knewer || e != ERROR_FILE_NOT_FOUND)
return OFW_BAD;
fix (WINFS::CreateFile (sw_path, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN, 0));
if (valid ())
{
sw_delete_if_fail = 1;
return OFW_OK2;
}
e = GetLastError ();
return OFW_BAD;
}
int
safe_write_handle::ensure_room (LONG hi, LONG lo)
{
if (SetFilePointer (*this, lo, &hi, FILE_BEGIN) == -1)
{
int e = GetLastError ();
if (e != NO_ERROR)
return e;
}
if (!SetEndOfFile (*this))
return GetLastError ();
sw_delete_if_fail = 1;
if (SetFilePointer (*this, 0, 0, FILE_BEGIN) == -1)
return GetLastError ();
return NO_ERROR;
}
lisp
Fcopy_file (lisp from_name, lisp to_name, lisp keys)
{
char fromf[PATH_MAX + 1];
pathname2cstr (from_name, fromf);
safe_write_handle w (to_name);
check_short_names (fromf, w.path ());
lisp if_exists = find_keyword (Kif_exists, keys);
if (if_exists == Qnil)
if_exists = Kerror;
int copy_attrib = find_keyword_bool (Kcopy_attributes, keys, 1);
int open_mode;
if (if_exists == Kerror)
open_mode = CREATE_NEW;
else if (if_exists == Koverwrite)
open_mode = OPEN_ALWAYS;
else if (if_exists == Kskip)
open_mode = CREATE_NEW;
else if (if_exists == Knewer)
open_mode = OPEN_EXISTING;
else
FEprogram_error (Einvalid_if_exists_option, if_exists);
lisp access_denied = access_denied_option (keys);
dyn_handle r (WINFS::CreateFile (fromf, GENERIC_READ, FILE_SHARE_READ, 0,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0));
if (!r.valid ())
{
r.fix (WINFS::CreateFile (fromf, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0));
if (!r.valid ())
file_error (GetLastError (), from_name);
}
int e;
int ofw = w.open_for_write (if_exists, open_mode, e);
if (ofw == OFW_BAD && e == ERROR_ACCESS_DENIED)
{
DWORD atr = solve_access_denied (access_denied, w.path (), to_name);
if (atr == -1)
return Qnil;
w.set_org_atr (atr);
ofw = w.open_for_write (if_exists, open_mode, e);
}
switch (ofw)
{
case OFW_OK1:
if (if_exists == Knewer)
{
FILETIME tr, tw;
if (!GetFileTime (r, 0, 0, &tr))
file_error (GetLastError (), from_name);
if (!GetFileTime (w, 0, 0, &tw))
file_error (GetLastError (), to_name);
if (CompareFileTime (&tr, &tw) <= 0)
return Qnil;
}
break;
case OFW_OK2:
break;
case OFW_SKIP:
return Qnil;
default:
file_error (e, to_name);
}
DWORD hi, lo;
lo = GetFileSize (r, &hi);
if (lo == -1 && (e = GetLastError ()) != NO_ERROR)
file_error (e, from_name);
e = w.ensure_room (hi, lo);
if (e != NO_ERROR)
file_error (e, to_name);
while (1)
{
DWORD nread, nwrite;
char buf[0x10000];
if (!ReadFile (r, buf, sizeof buf, &nread, 0))
file_error (GetLastError (), from_name);
if (!WriteFile (w, buf, nread, &nwrite, 0))
file_error (GetLastError (), to_name);
if (nread != nwrite)
file_error (Ewrite_error, to_name);
if (nread < sizeof buf)
break;
}
if (!SetEndOfFile (w))
file_error (GetLastError (), to_name);
w.complete ();
if (copy_attrib)
{
FILETIME t;
if (GetFileTime (r, 0, 0, &t))
SetFileTime (w, 0, 0, &t);
DWORD atr = WINFS::GetFileAttributes (fromf);
if (atr != -1)
WINFS::SetFileAttributes (w.path (), atr);
}
return Qt;
}
lisp
Frename_file (lisp from_name, lisp to_name, lisp keys)
{
char fromf[PATH_MAX + 1], tof[PATH_MAX + 1];
pathname2cstr (from_name, fromf);
pathname2cstr (to_name, tof);
check_short_names (fromf, tof);
lisp if_exists = find_keyword (Kif_exists, keys);
if (if_exists == Qnil)
if_exists = Kerror;
if (if_exists != Kerror && if_exists != Koverwrite
&& if_exists != Kskip && if_exists != Knewer)
FEprogram_error (Einvalid_if_exists_option, if_exists);
lisp access_denied = access_denied_option (keys);
while (1)
{
if (WINFS::MoveFile (fromf, tof))
return Qt;
int e = GetLastError ();
switch (e)
{
case ERROR_ALREADY_EXISTS:
case ERROR_FILE_EXISTS:
if (if_exists == Kerror)
file_error (e, to_name);
if (if_exists == Kskip)
return Qnil;
if (if_exists == Knewer)
{
dyn_handle f (WINFS::CreateFile (fromf, 0, 0, 0, OPEN_EXISTING, 0, 0));
if (!f.valid ())
file_error (GetLastError (), from_name);
dyn_handle t (WINFS::CreateFile (tof, 0, 0, 0, OPEN_EXISTING, 0, 0));
if (!t.valid ())
file_error (GetLastError (), to_name);
FILETIME tf, tt;
if (!GetFileTime (f, 0, 0, &tf))
file_error (GetLastError (), from_name);
if (!GetFileTime (t, 0, 0, &tt))
file_error (GetLastError (), to_name);
if (CompareFileTime (&tf, &tt) <= 0)
return Qnil;
}
if (!WINFS::DeleteFile (tof))
{
e = GetLastError ();
DWORD atr = WINFS::GetFileAttributes (tof);
if (atr != DWORD (-1) && atr & FILE_ATTRIBUTE_DIRECTORY)
file_error (ERROR_ACCESS_DENIED, to_name);
if (e != ERROR_ACCESS_DENIED)
file_error (e, to_name);
atr = solve_access_denied (access_denied, tof, to_name);
if (atr == -1)
return Qnil;
if (!WINFS::DeleteFile (tof))
{
e = GetLastError ();
WINFS::SetFileAttributes (tof, atr);
file_error (e, to_name);
}
}
break;
default:
{
dyn_handle f (WINFS::CreateFile (fromf, GENERIC_READ | GENERIC_WRITE, 0, 0,
OPEN_EXISTING, 0, 0));
if (!f.valid ())
file_error (e, from_name);
file_error (e, to_name);
}
}
}
}
static int
mkdirhier (char *path, int exists_ok)
{
if (WINFS::CreateDirectory (path, 0))
return 1;
if (exists_ok)
{
DWORD a = WINFS::GetFileAttributes (path);
if (a != -1 && a & FILE_ATTRIBUTE_DIRECTORY)
return 1;
}
else
{
int e = GetLastError ();
if (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS)
return 0;
}
map_sl_to_backsl (path);
for (char *p = path; (p = jindex (p, '\\')); *p++ = '\\')
{
*p = 0;
WINFS::CreateDirectory (path, 0);
}
if (WINFS::CreateDirectory (path, 0))
return 1;
DWORD a = WINFS::GetFileAttributes (path);
return a != -1 && a & FILE_ATTRIBUTE_DIRECTORY;
}
lisp
Fcreate_directory (lisp dirname, lisp keys)
{
char name[PATH_MAX + 1];
pathname2cstr (dirname, name);
lisp if_exists = exist_option (Kif_exists, keys);
if (!mkdirhier (name, if_exists == Kskip))
{
int e = GetLastError ();
if (!e)
e = ERROR_FILE_EXISTS;
file_error (e, dirname);
}
return Qt;
}
lisp
Fdelete_directory (lisp dirname, lisp keys)
{
char name[PATH_MAX + 1];
pathname2cstr (dirname, name);
lisp not_exist = exist_option (Kif_does_not_exist, keys);
lisp access_denied = access_denied_option (keys);
if (!WINFS::RemoveDirectory (name))
{
int e = GetLastError ();
if (e == ERROR_ACCESS_DENIED)
{
DWORD atr = solve_access_denied (access_denied, name, dirname);
if (atr == -1)
return Qnil;
if (WINFS::RemoveDirectory (name))
return Qt;
e = GetLastError ();
WINFS::SetFileAttributes (name, atr);
}
if (e == ERROR_FILE_NOT_FOUND && not_exist == Kskip)
return Qnil;
file_error (e, dirname);
}
return Qt;
}
static lisp
map_sl (lisp path, Char from, Char to)
{
check_string (path);
Char *p0 = (Char *)alloca (xstring_length (path) * sizeof *p0);
bcopy (xstring_contents (path), p0, xstring_length (path));
int f = 0;
for (Char *p = p0, *pe = p0 + xstring_length (path); p < pe; p++)
if (*p == from)
{
*p = to;
f = 1;
}
return f ? make_string (p0, xstring_length (path)) : path;
}
lisp
Fmap_slash_to_backslash (lisp path)
{
return map_sl (path, '/', '\\');
}
lisp
Fmap_backslash_to_slash (lisp path)
{
return map_sl (path, '\\', '/');
}
static void
wnet_error ()
{
DWORD e = GetLastError ();
if (e == ERROR_SUCCESS)
return;
if (e != ERROR_EXTENDED_ERROR)
FEsimple_win32_error (e);
char n[1024], d[1024];
*n = 0, *d = 0;
WNetGetLastError (&e, d, sizeof d, n, sizeof n);
FEnetwork_error (make_string (n), make_string (d));
}
lisp
Fnetwork_connect_dialog ()
{
if (WNetConnectionDialog (get_active_window (), RESOURCETYPE_DISK) == NO_ERROR)
return Qt;
wnet_error ();
return Qnil;
}
lisp
Fnetwork_disconnect_dialog ()
{
if (WNetDisconnectDialog (get_active_window (), RESOURCETYPE_DISK) == NO_ERROR)
return Qt;
wnet_error ();
return Qnil;
}
lisp
Fget_file_attributes (lisp lpath)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
DWORD atr = WINFS::GetFileAttributes (path);
if (atr == -1)
file_error (GetLastError (), lpath);
return make_fixnum (atr);
}
#define VALID_FILE_ATTRIBUTES \
(FILE_ATTRIBUTE_ARCHIVE \
| FILE_ATTRIBUTE_NORMAL \
| FILE_ATTRIBUTE_HIDDEN \
| FILE_ATTRIBUTE_READONLY \
| FILE_ATTRIBUTE_SYSTEM)
lisp
Fset_file_attributes (lisp lpath, lisp latr)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
DWORD atr = fixnum_value (latr) & VALID_FILE_ATTRIBUTES;
if (!WINFS::SetFileAttributes (path, atr))
file_error (GetLastError (), lpath);
return Qt;
}
lisp
Fmodify_file_attributes (lisp lpath, lisp lon, lisp loff)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
DWORD on = fixnum_value (lon) & VALID_FILE_ATTRIBUTES;
DWORD off = ((loff && loff != Qnil)
? (fixnum_value (loff) & VALID_FILE_ATTRIBUTES) : 0);
DWORD atr = WINFS::GetFileAttributes (path);
if (atr == -1)
file_error (GetLastError (), lpath);
if (!WINFS::SetFileAttributes (path, (atr & ~off) | on))
file_error (GetLastError (), lpath);
return Qt;
}
int
strict_get_file_data (const char *path, WIN32_FIND_DATA &fd)
{
for (const u_char *p = (const u_char *)path; *p;)
{
if (SJISP (*p) && p[1])
p += 2;
else
{
if (*p == '?' || *p == '*')
{
SetLastError (ERROR_INVALID_NAME);
return 0;
}
p++;
}
}
return WINFS::get_file_data (path, fd);
}
lisp
Ffile_length (lisp lpath)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
WIN32_FIND_DATA fd;
if (!strict_get_file_data (path, fd))
return Qnil;
large_int i;
i.hi = fd.nFileSizeHigh;
i.lo = fd.nFileSizeLow;
return make_integer (i);
}
struct gdu
{
int recursive;
double nbytes;
double blocks;
u_long blocksize;
int nfiles;
int ndirs;
};
static void
get_disk_usage (char *path, gdu *du)
{
QUIT;
int l = strlen (path);
if (l >= PATH_MAX)
return;
char *pe = path + l;
*pe = '*';
pe[1] = 0;
WIN32_FIND_DATA fd;
HANDLE h = WINFS::FindFirstFile (path, &fd);
if (h != INVALID_HANDLE_VALUE)
{
find_handle fh (h);
do
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (!du->recursive
|| (*fd.cFileName == '.'
&& (!fd.cFileName[1]
|| (fd.cFileName[1] == '.' && !fd.cFileName[2]))))
continue;
du->ndirs++;
strcpy (stpcpy (pe, fd.cFileName), "/");
get_disk_usage (path, du);
}
else
{
double size = ((fd.nFileSizeHigh
* double (1 << (sizeof (DWORD) * 4))
* double (1 << (sizeof (DWORD) * 4)))
+ fd.nFileSizeLow);
du->nbytes += size;
du->blocks += ceil (size / du->blocksize);
du->nfiles++;
}
}
while (WINFS::FindNextFile (h, &fd));
}
}
lisp
Fget_disk_usage (lisp dirname, lisp recursive)
{
char path[PATH_MAX * 2];
pathname2cstr (dirname, path);
char *p = jrindex (path, '/');
if (p && p[1])
strcat (p, "/");
gdu du;
bzero (&du, sizeof du);
WINFS::SetCurrentDirectory (path);
DWORD SectorsPerCluster;
DWORD BytesPerSector;
DWORD FreeClusters;
DWORD Clusters;
int f = WINFS::GetDiskFreeSpace (0, &SectorsPerCluster, &BytesPerSector,
&FreeClusters, &Clusters);
int e = GetLastError ();
WINFS::SetCurrentDirectory (sysdep.curdir);
if (!f)
file_error (e, dirname);
if (!recursive)
recursive = Qnil;
du.recursive = recursive == Qt;
du.blocksize = SectorsPerCluster * BytesPerSector;
if (!du.blocksize)
du.blocksize = 1024;
if (recursive == Qnil || recursive == Qt)
get_disk_usage (path, &du);
lisp block = make_fixnum (du.blocksize);
multiple_value::value (1) =
number_multiply (make_integer (long_to_large_int (Clusters)), block);
multiple_value::value (2) =
number_multiply (make_integer (long_to_large_int (FreeClusters)), block);
multiple_value::value (3) =
number_multiply (make_integer (double_to_bignum_rep (du.blocks)), block);
multiple_value::value (4) = make_integer (double_to_bignum_rep (du.nbytes));
multiple_value::value (5) = make_fixnum (du.ndirs);
multiple_value::value (6) = make_fixnum (du.nfiles);
multiple_value::count () = 7;
return block;
}
lisp
Fformat_drive (lisp ldrive, lisp lquick)
{
int drive;
if (!ldrive || ldrive == Qnil)
drive = 0;
else if (charp (ldrive))
{
Char c = xchar_code (ldrive);
if (lower_char_p (c))
drive = c - 'a';
else if (upper_char_p (c))
drive = c - 'A';
else
FErange_error (ldrive);
}
else
{
drive = fixnum_value (ldrive);
if (drive < 0 || drive >= 26)
FErange_error (ldrive);
}
HMODULE shell = GetModuleHandle ("shell32.dll");
if (!shell)
FEsimple_win32_error (GetLastError ());
int (__stdcall *fmt)(HWND, int, int, int) =
(int (__stdcall *)(HWND, int, int, int))GetProcAddress (shell, "SHFormatDrive");
if (!fmt)
FEsimple_win32_error (GetLastError ());
HWND hwnd = get_active_window ();
HWND focus = GetFocus ();
int f = (*fmt)(hwnd, drive, 0, lquick && lquick != Qnil);
EnableWindow (hwnd, 1);
SetFocus (focus);
return boole (!f);
}
lisp
Fcompare_file (lisp file1, lisp file2)
{
char path1[PATH_MAX + 1], path2[PATH_MAX + 1];
pathname2cstr (file1, path1);
pathname2cstr (file2, path2);
mapf mf1, mf2;
if (!mf1.open (path1))
file_error (GetLastError (), file1);
if (!mf2.open (path2))
file_error (GetLastError (), file2);
if (mf1.size () != mf2.size ())
return Qnil;
lisp r = Qnil;
try
{
r = boole (!memcmp (mf1.base (), mf2.base (), mf1.size ()));
}
catch (Win32Exception &e)
{
if (e.code == EXCEPTION_IN_PAGE_ERROR)
FEsimple_win32_error (ERROR_FILE_CORRUPT);
throw e;
}
return r;
}
lisp
Ffile_property (lisp lpath)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
map_sl_to_backsl (path);
HMODULE shell = GetModuleHandle ("shell32.dll");
if (!shell)
FEsimple_win32_error (GetLastError ());
int (__stdcall *ex)(SHELLEXECUTEINFO *) =
(int (__stdcall *)(SHELLEXECUTEINFO *))GetProcAddress (shell, "ShellExecuteExA");
if (!ex)
FEsimple_win32_error (GetLastError ());
SHELLEXECUTEINFO sei;
bzero (&sei, sizeof sei);
sei.cbSize = sizeof sei;
sei.lpFile = path;
sei.lpVerb = "properties";
sei.fMask = SEE_MASK_INVOKEIDLIST;
if (!(*ex)(&sei))
FEsimple_win32_error (GetLastError ());
return Qt;
}
#define LOCK_TIMEOUT 10000
#define LOCK_RETRIES 20
#ifndef FILE_DEVICE_MASS_STORAGE
#define FILE_DEVICE_MASS_STORAGE 0x0000002d
#endif
#ifndef IOCTL_STORAGE_BASE
#define IOCTL_STORAGE_BASE FILE_DEVICE_MASS_STORAGE
#endif
#ifndef IOCTL_STORAGE_MEDIA_REMOVAL
#define IOCTL_STORAGE_MEDIA_REMOVAL \
CTL_CODE (IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
#ifndef IOCTL_STORAGE_EJECT_MEDIA
#define IOCTL_STORAGE_EJECT_MEDIA \
CTL_CODE (IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
static lisp
eject_media_winnt (int drive, int type)
{
int flags = 0;
switch (type)
{
default:
file_error (ERROR_BAD_DEVICE);
case DRIVE_REMOVABLE:
flags = GENERIC_READ | GENERIC_WRITE;
break;
case DRIVE_CDROM:
flags = GENERIC_READ;
break;
}
char dev[] = "\\\\.\\x:";
dev[4] = char (drive);
dyn_handle h (CreateFile (dev, flags, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, 0, 0));
if (!h.valid ())
file_error (GetLastError ());
DWORD nbytes;
for (int retry = 0;; retry++)
{
if (DeviceIoControl (h, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &nbytes, 0))
break;
if (retry == LOCK_RETRIES)
file_error (GetLastError ());
Sleep (LOCK_TIMEOUT / LOCK_RETRIES);
}
if (!DeviceIoControl (h, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, &nbytes, 0))
file_error (GetLastError ());
PREVENT_MEDIA_REMOVAL pmr;
pmr.PreventMediaRemoval = 0;
if (!DeviceIoControl (h, IOCTL_STORAGE_MEDIA_REMOVAL,
&pmr, sizeof pmr, 0, 0, &nbytes, 0))
file_error (GetLastError ());
if (!DeviceIoControl (h, IOCTL_STORAGE_EJECT_MEDIA, 0, 0, 0, 0, &nbytes, 0))
file_error (GetLastError ());
return Qt;
}
static const u_char fat32_devcat[] = {0x48, 0x08};
static int
win9x_lock_logical_volume (HANDLE hvwin32, int drive, int lock_level, int perm)
{
for (int i = 0; i < numberof (fat32_devcat); i++)
{
DIOC_REGISTERS regs = {0};
regs.reg_EAX = 0x440d;
regs.reg_EBX = MAKEWORD (drive, lock_level);
regs.reg_ECX = MAKEWORD (0x4a, fat32_devcat[i]);
regs.reg_EDX = perm;
DWORD nbytes;
if (DeviceIoControl (hvwin32, VWIN32_DIOC_DOS_IOCTL,
®s, sizeof regs, ®s, sizeof regs,
&nbytes, 0)
&& !(regs.reg_Flags & X86_CARRY_FLAG))
return 1;
}
return 0;
}
static int
win9x_unlock_logical_volume (HANDLE hvwin32, int drive)
{
for (int i = 0; i < numberof (fat32_devcat); i++)
{
DIOC_REGISTERS regs = {0};
regs.reg_EAX = 0x440d;
regs.reg_EBX = drive;
regs.reg_ECX = MAKEWORD (0x6A, fat32_devcat[i]);
DWORD nbytes;
if (DeviceIoControl (hvwin32, VWIN32_DIOC_DOS_IOCTL,
®s, sizeof regs, ®s, sizeof regs,
&nbytes, 0)
&& !(regs.reg_Flags & X86_CARRY_FLAG))
return 1;
}
return 0;
}
static int
win9x_unlock_media (HANDLE hvwin32, int drive)
{
DIOC_REGISTERS regs = {0};
PARAMBLOCK pb;
pb.bOperation = 2;
pb.bNumLocks = 0;
regs.reg_EAX = 0x440d;
regs.reg_EBX = drive;
regs.reg_ECX = MAKEWORD (0x48, 0x08);
regs.reg_EDX = DWORD (&pb);
DWORD nbytes;
if (!DeviceIoControl (hvwin32, VWIN32_DIOC_DOS_IOCTL,
®s, sizeof regs, ®s, sizeof regs,
&nbytes, 0)
|| (regs.reg_Flags & X86_CARRY_FLAG
&& regs.reg_EAX != 0x01 && regs.reg_EAX != 0xb0))
return 0;
for (int i = 0; i < pb.bNumLocks; ++i)
{
pb.bOperation = 1;
regs.reg_EAX = 0x440d;
regs.reg_EBX = drive;
regs.reg_ECX = MAKEWORD (0x48, 0x08);
regs.reg_EDX = DWORD (&pb);
if (!DeviceIoControl (hvwin32, VWIN32_DIOC_DOS_IOCTL,
®s, sizeof regs, ®s, sizeof regs,
&nbytes, 0)
|| regs.reg_Flags & X86_CARRY_FLAG)
return 0;
}
return 1;
}
static int
win9x_eject_media (HANDLE hvwin32, int drive)
{
DIOC_REGISTERS regs = {0};
regs.reg_EAX = 0x440d;
regs.reg_EBX = drive;
regs.reg_ECX = MAKEWORD (0x49, 0x08);
DWORD nbytes;
return (DeviceIoControl (hvwin32, VWIN32_DIOC_DOS_IOCTL,
®s, sizeof regs, ®s, sizeof regs,
&nbytes, 0)
&& !(regs.reg_Flags & X86_CARRY_FLAG));
}
static lisp
eject_media_win9x (int drive)
{
dyn_handle hvwin32 (CreateFile ("\\\\.\\vwin32", 0, 0, 0, 0,
FILE_FLAG_DELETE_ON_CLOSE, 0));
if (!hvwin32.valid ())
file_error (GetLastError ());
drive = char_upcase (drive) - ('A' - 1);
int e = 0;
if (!win9x_lock_logical_volume (hvwin32, drive, 0, 0))
e = ERROR_DRIVE_LOCKED;
else
{
if (!win9x_unlock_media (hvwin32, drive))
e = ERROR_UNABLE_TO_LOCK_MEDIA;
else if (!win9x_eject_media (hvwin32, drive))
e = ERROR_UNABLE_TO_UNLOAD_MEDIA;
win9x_unlock_logical_volume (hvwin32, drive);
}
if (e)
file_error (e);
return Qt;
}
lisp
Feject_media (lisp ldrive)
{
check_char (ldrive);
if (!alpha_char_p (xchar_code (ldrive)))
file_error (ERROR_INVALID_DRIVE);
char root[] = "x:\\";
root[0] = char (xchar_code (ldrive));
int type = GetDriveType (root);
switch (type)
{
default:
file_error (ERROR_BAD_DEVICE);
case DRIVE_REMOVABLE:
case DRIVE_CDROM:
break;
}
return (sysdep.WinNTp ()
? eject_media_winnt (xchar_code (ldrive), type)
: eject_media_win9x (xchar_code (ldrive)));
}
class list_net_resources: public worker_thread
{
protected:
int m_error;
int m_nomem;
int m_pair;
xstring_pair_list m_list;
list_net_resources (int pair)
: m_error (NO_ERROR), m_nomem (0), m_pair (pair) {}
virtual void thread_main ();
virtual void doit () = 0;
public:
void signal_error () const;
lisp make_list ();
};
void
list_net_resources::thread_main ()
{
try
{
doit ();
}
catch (nonlocal_jump &)
{
m_nomem = 1;
}
}
void
list_net_resources::signal_error () const
{
if (m_nomem)
FEstorage_error ();
if (m_error != NO_ERROR)
FEsimple_win32_error (m_error);
}
lisp
list_net_resources::make_list ()
{
if (!start ())
FEsimple_win32_error (GetLastError ());
if (!wait ())
FEquit ();
signal_error ();
return m_list.make_list (m_pair);
}
class list_servers: public list_net_resources
{
protected:
virtual void doit () {list (0);}
int list (NETRESOURCE *);
public:
list_servers (int pair) : list_net_resources (pair) {}
};
int
list_servers::list (NETRESOURCE *r0)
{
HANDLE h;
m_error = WINFS::WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, r0, &h);
if (m_error != NO_ERROR)
return 0;
wnet_enum_handle weh (h);
while (!interrupted ())
{
NETRESOURCE rb[8192];
DWORD nent = DWORD (-1), size = sizeof rb;
m_error = WNetEnumResource (h, &nent, rb, &size);
if (m_error == ERROR_NO_MORE_ITEMS)
{
m_error = NO_ERROR;
return 1;
}
if (m_error != NO_ERROR)
return 0;
NETRESOURCE *r = rb;
for (DWORD i = 0; i < nent && !interrupted (); i++, r++)
switch (r->dwDisplayType)
{
case RESOURCEDISPLAYTYPE_GENERIC:
case RESOURCEDISPLAYTYPE_DOMAIN:
case RESOURCEDISPLAYTYPE_NETWORK:
if (r->dwUsage & RESOURCEUSAGE_CONTAINER)
list (r);
break;
case RESOURCEDISPLAYTYPE_SERVER:
if (r->lpRemoteName)
m_list.add (r->lpRemoteName + 2,
m_pair && r->lpComment ? r->lpComment : "");
break;
}
}
return 0;
}
lisp
Flist_servers (lisp comment_p)
{
worker_thread_helper <list_servers> ls
(new list_servers (comment_p && comment_p != Qnil));
return ls->make_list ();
}
class list_server_resources: public list_net_resources
{
protected:
virtual void doit ();
public:
list_server_resources (lisp lserver, int pair);
~list_server_resources () {delete m_server;}
private:
char *m_server;
};
list_server_resources::list_server_resources (lisp lserver, int pair)
: list_net_resources (pair)
{
check_string (lserver);
m_server = new char [xstring_length (lserver) * 2 + 3];
m_server[0] = '\\';
m_server[1] = '\\';
w2s (m_server + 2, lserver);
}
void
list_server_resources::doit ()
{
int l = strlen (m_server) + 1;
NETRESOURCE r;
r.dwScope = RESOURCE_GLOBALNET;
r.dwType = RESOURCETYPE_ANY;
r.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
r.dwUsage = RESOURCEUSAGE_CONTAINER;
r.lpLocalName = 0;
r.lpRemoteName = m_server;
r.lpComment = "";
r.lpProvider = 0;
HANDLE h;
m_error = WINFS::WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, &r, &h);
if (m_error != NO_ERROR)
return;
wnet_enum_handle weh (h);
while (!interrupted ())
{
NETRESOURCE rb[8192];
DWORD nent = DWORD (-1), size = sizeof rb;
m_error = WNetEnumResource (h, &nent, rb, &size);
if (m_error == ERROR_NO_MORE_ITEMS)
{
m_error = NO_ERROR;
return;
}
if (m_error != NO_ERROR)
return;
NETRESOURCE *r = rb;
for (DWORD i = 0; i < nent && !interrupted (); i++, r++)
switch (r->dwDisplayType)
{
case RESOURCEDISPLAYTYPE_SHARE:
if (r->lpRemoteName)
m_list.add (r->lpRemoteName + l,
m_pair && r->lpComment ? r->lpComment : "");
break;
}
}
}
lisp
Flist_server_resources (lisp lserver, lisp comment_p)
{
worker_thread_helper <list_server_resources>
ls (new list_server_resources (lserver, comment_p && comment_p != Qnil));
return ls->make_list ();
}
lisp
Fset_per_device_directory (lisp lpath)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
if (!set_device_dir (path, 1))
file_error (GetLastError (), lpath);
WINFS::SetCurrentDirectory (sysdep.curdir);
return Qt;
}
lisp
Fget_short_path_name (lisp lpath)
{
char path[PATH_MAX + 1], spath[PATH_MAX + 1];
pathname2cstr (lpath, path);
map_sl_to_backsl (path);
if (!GetShortPathName (path, spath, PATH_MAX))
file_error (GetLastError (), lpath);
map_backsl_to_sl (spath);
if (stringp (lpath) && xstring_length (lpath)
&& dir_separator_p (xstring_contents (lpath)[xstring_length (lpath) - 1]))
{
char *sl = find_last_slash (spath);
if (sl && sl[1])
strcat (sl, "/");
}
return make_string (spath);
}
lisp
make_file_info (const WIN32_FIND_DATA &fd)
{
large_int sz;
sz.hi = fd.nFileSizeHigh;
sz.lo = fd.nFileSizeLow;
return make_list (make_fixnum (fd.dwFileAttributes),
//file_time_to_universal_time (fd.ftCreationTime),
//file_time_to_universal_time (fd.ftLastAccessTime),
file_time_to_universal_time (fd.ftLastWriteTime),
make_integer (sz),
(*fd.cAlternateFileName
? make_string (fd.cAlternateFileName)
: Qnil),
0);
}
lisp
Fget_file_info (lisp lpath)
{
char path[PATH_MAX + 1];
pathname2cstr (lpath, path);
WIN32_FIND_DATA fd;
if (!strict_get_file_data (path, fd))
file_error (GetLastError (), lpath);
return make_file_info (fd);
}
char *
root_path_name (char *buf, const char *path)
{
if (*path && path[1] == ':')
{
buf[0] = path[0];
buf[1] = ':';
buf[2] = '\\';
buf[3] = 0;
}
else
{
strcpy (buf, path);
map_sl_to_backsl (buf);
if (*buf == '\\')
{
if (buf[1] == '\\')
{
char *p = jindex (buf + 2, '\\');
if (p)
{
char *p2 = jindex (p + 1, '\\');
if (p2)
p2[1] = 0;
else
strcat (p + 1, "\\");
}
}
else
buf[1] = 0;
}
}
return buf;
}
| [
"[email protected]"
] | [
[
[
1,
2444
]
]
] |
790b8066dc3530187a3c2ea274e39aaeb9a32b74 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/Item.cpp | 118ffb6f7958c833280d92b5afe80bf90bbbf383 | [] | 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 | UHC | C++ | false | false | 21,822 | cpp | #include "stdafx.h"
#include "defineObj.h"
#include "CreateObj.h"
#if __VER >= 11 // __SYS_IDENTIFY
#include "randomoption.h"
#ifdef __WORLDSERVER
#include "ticket.h"
#endif // __WORLDSERVER
#endif // __SYS_IDENTIFY
#include "serialnumber.h"
#if __VER >= 9
#include "definetext.h"
#endif //
BOOL IsUsableItem( CItemBase* pItem )
{
if( pItem == NULL )
return FALSE;
if( pItem->GetExtra() == 0 )
return TRUE;
else
return FALSE; // 거래중이거나 개인 상점에 올린 아이템은 사용할 수 없다.
}
BOOL IsUsingItem( CItemBase* pItem )
{
if( pItem == NULL )
return FALSE;
if( pItem->GetExtra() != 0 )
return TRUE;
else
return FALSE; // .
}
//////////////////////////////////////////////////////////////////////
// CItemBase
//////////////////////////////////////////////////////////////////////
CItemBase::CItemBase()
{
m_szItemText[0] = '\0';
m_dwItemId = 0;
m_dwObjId = NULL_ID;
m_dwObjIndex = NULL_ID;
m_nExtra = 0;
m_nCost = 0;
m_liSerialNumber = 0;
SetTexture( NULL );
}
void CItemBase::Empty()
{
m_szItemText[0] = '\0';
m_dwItemId = 0;
m_nExtra = 0;
SetTexture( NULL );
}
ItemProp* CItemBase::GetProp()
{
return prj.GetItemProp( m_dwItemId );
}
CItemBase& CItemBase::operator = ( CItemBase& ib )
{
_tcscpy( m_szItemText, ib.m_szItemText );
m_dwItemId = ib.m_dwItemId ;
m_liSerialNumber = ib.m_liSerialNumber;
#ifdef __CLIENT
m_pTexture = ib.m_pTexture;
#endif
return *this;
}
void CItemBase::SetTexture()
{
#ifdef __CLIENT
ItemProp* pProp =GetProp();
if (!pProp)
{
LPCTSTR szErr = Error("CItemBase::SetTexture GetProp() NULL Return %d", m_dwItemId);
ADDERRORMSG( szErr );
}
#if __VER >= 9 // __PET_0410
CString strIcon = pProp->szIcon;
if( pProp->dwItemKind3 == IK3_EGG )
{
BYTE nLevel = 0;
if( ( (CItemElem*)this )->m_pPet )
nLevel = ( (CItemElem*)this )->m_pPet->GetLevel();
switch( nLevel )
{
case PL_D:
case PL_C:
strIcon.Replace( ".", "_00." );
break;
case PL_B:
case PL_A:
strIcon.Replace( ".", "_01." );
break;
case PL_S:
strIcon.Replace( ".", "_02." );
break;
}
}
m_pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, strIcon ), 0xffff00ff );
#else // __PET_0410
m_pTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_ITEM, GetProp()->szIcon), 0xffff00ff );
#endif // __PET_0410
#endif
}
//
// 아이템 가격을 계산해서 리턴한다.
// -1을 리턴하면 처리해선 안된다.
//
int CItemBase::GetCost( void )
{
ItemProp *pProp = GetProp();
if( pProp == NULL )
return -1;
if( pProp->dwCost == 0xFFFFFFFF )
return -1;
CItemElem *pItemElem = (CItemElem *)this;
int nCost;
if( pItemElem->GetAbilityOption() )
{
//INT((아이템가격+아이템가격*(0.1+(아이템강화레벨*아이템강화레벨)/18))
nCost = (int)( pProp->dwCost + pProp->dwCost * ( 0.1f + ( pItemElem->GetAbilityOption() * pItemElem->GetAbilityOption() ) / 18.0f ) );
}
else
{
nCost = (int)pProp->dwCost;
}
return nCost;
}
#if __VER >= 11 // __GUILDCOMBATCHIP
DWORD CItemBase::GetChipCost()
{
ItemProp *pProp = GetProp();
if( pProp == NULL )
return -1;
if( pProp->dwReferValue1 == 0xFFFFFFFF )
return -1;
return pProp->dwReferValue1;
}
#endif // __GUILDCOMBATCHIP
// 퀘스트 아이템인가?
BOOL CItemBase::IsQuest()
{
ItemProp* p = GetProp();
if( p->dwItemKind3 == IK3_QUEST )
{
if( ::GetLanguage() == LANG_JAP )
{
if( p->dwID == II_SYS_SYS_QUE_REDSOCKS ) // 예외
return FALSE;
}
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////////
// CItemElem - 아이템 하나하나의 요소를 말한다.
//////////////////////////////////////////////////////////////////////
/*
1 ~ 99
100 ~ 유저 지정 로고
아이템에 로고 번호.
*/
CItemElem::CItemElem()
{
m_idGuild = 0;
m_nItemNum = 1;
m_nAbilityOption = 0;
m_nRepairNumber = 0;
m_nHitPoint = -1;
m_nRepair = 0;
m_byFlag = 0;
#ifdef __CLIENT
m_bRepair = FALSE;
#endif // __CLIENT
m_bItemResist = SAI79::NO_PROP;
m_nResistAbilityOption = 0;
m_nResistSMItemId = 0;
#ifdef __WORLDSERVER
m_bQuery = FALSE;
#endif // __WORLDSERVER
// memset( &m_piercingInfo, 0, sizeof(m_piercingInfo) );
m_bCharged = FALSE;
m_dwKeepTime = 0;
#if __VER >= 11 // __SYS_IDENTIFY
m_iRandomOptItemId = 0;
#else // __SYS_IDENTIFY
m_nRandomOptItemId = 0;
#endif // __SYS_IDENTIFY
// mulcom BEGIN100405 각성 보호의 두루마리
m_n64NewRandomOption = 0;
// mulcom END100405 각성 보호의 두루마리
/*
#ifdef __XPET2
m_nMaxLevel = 0;
m_nLevel = 0;
m_dwHungry = 0;
m_dwFeeling = 0;
#endif // xPet2
*/
/*
#ifdef __GIFTBOX0213
#ifdef __WORLDSERVER
m_nQueryGiftbox = 0;
#endif // __WORLDSERVER
#endif // __GIFTBOX0213
*/
#if __VER >= 9 // __PET_0410
m_pPet = NULL;
#endif // __PET_0410
#if __VER >= 15 // __PETVIS
m_bTranformVisPet = FALSE;
#endif // __PETVIS
}
CItemElem::~CItemElem()
{
#if __VER >= 9 // __PET_0410
SAFE_DELETE( m_pPet );
#endif // __PET_0410
}
void CItemElem::Empty( void )
{
CItemBase::Empty();
#if __VER >= 9
SAFE_DELETE( m_pPet );
#endif // __PET_0410
m_piercing.Clear();
}
// 돈의 양을 얻는다.
int CItemElem::GetGold()
{
ASSERT( GetProp()->dwItemKind1 == IK1_GOLD );
return m_nHitPoint; // int형으로 돈을 버리게 하기 위해서 이 변수를 사용
}
void CItemElem::UseItem()
{
if( GetProp()->bPermanence != TRUE )
m_nItemNum--;
}
CItemElem& CItemElem::operator =( CItemElem & ie )
{
CItemBase::operator =( ie );
SetTexture( ie.GetTexture() );
m_nItemNum = ie.m_nItemNum;
m_nRepairNumber = ie.m_nRepairNumber;
m_nHitPoint = ie.m_nHitPoint;
m_nRepair = ie.m_nRepair;
m_byFlag = ie.m_byFlag;
m_nAbilityOption = ie.m_nAbilityOption;
m_idGuild = ie.m_idGuild;
m_bItemResist = ie.m_bItemResist;
m_nResistAbilityOption = ie.m_nResistAbilityOption;
m_nResistSMItemId = ie.m_nResistSMItemId;
m_dwKeepTime = ie.m_dwKeepTime;
m_piercing = ie.m_piercing;
m_bCharged = ie.m_bCharged;
#if __VER >= 11 // __SYS_IDENTIFY
m_iRandomOptItemId = ie.GetRandomOptItemId();
#else // __SYS_IDENTIFY
m_nRandomOptItemId = ie.m_nRandomOptItemId;
#endif // __SYS_IDENTIFY
// mulcom BEGIN100405 각성 보호의 두루마리
m_n64NewRandomOption = ie.GetNewRandomOption();
// mulcom END100405 각성 보호의 두루마리
#if __VER >= 9 // __PET_0410
SAFE_DELETE( m_pPet );
if( ie.m_pPet )
{
m_pPet = new CPet;
*m_pPet = *ie.m_pPet;
}
#endif // __PET_0410
#if __VER >= 15 // __PETVIS
m_bTranformVisPet = ie.m_bTranformVisPet;
#endif // __PETVIS
return *this;
}
// 유료아이템인가?
BOOL CItemElem::IsCharged()
{
if( m_bCharged == 1 || m_nResistSMItemId != 0 )
return TRUE;
return FALSE;
}
void CItemElem::GetPiercingAvail( PPIERCINGAVAIL pPiercingAvail )
{
int i; for( i = 0; i < GetPiercingSize(); i++ )
{
PPIERCINGAVAIL ptr = CPiercingAvail::GetInstance()->GetPiercingAvail( GetPiercingItem( i ) );
if( ptr )
{
int j; for( j = 0; j < ptr->nSize; j++ )
{
int nFind = -1;
for( int k = 0; k < pPiercingAvail->nSize; k++ )
{
if( pPiercingAvail->anDstParam[k] == ptr->anDstParam[j] )
{
nFind = k;
break;
}
}
if( nFind < 0 )
nFind = pPiercingAvail->nSize++;
pPiercingAvail->anDstParam[nFind] = ptr->anDstParam[j];
pPiercingAvail->anAdjParam[nFind] += ptr->anAdjParam[j];
}
}
}
}
// 주사위로 제련 가능한 아이템 종류
BOOL CItemElem::IsDiceRefineryAble( ItemProp* pProp )
{
if( !pProp )
return FALSE;
if( pProp->dwItemKind2 == IK2_ARMOR ||
pProp->dwItemKind2 == IK2_WEAPON_MAGIC ||
pProp->dwItemKind2 == IK2_WEAPON_DIRECT ||
pProp->dwItemKind2 == IK2_ARMORETC )
return TRUE;
return FALSE;
}
// 카드로 제련 가능한 아이템 종류
BOOL CItemElem::IsEleRefineryAble( ItemProp* pProp )
{
if( !pProp )
return FALSE;
if( pProp->dwItemKind3 == IK3_SUIT ||
pProp->dwItemKind2 == IK2_WEAPON_MAGIC ||
pProp->dwItemKind2 == IK2_WEAPON_DIRECT )
return TRUE;
return FALSE;
}
#if __VER >= 15 // __15_5TH_ELEMENTAL_SMELT_SAFETY
BOOL CItemElem::IsElementalCard( const DWORD dwItemID )
{
switch( dwItemID )
{
case II_GEN_MAT_ELE_FLAME: case II_GEN_MAT_ELE_RIVER: case II_GEN_MAT_ELE_GENERATOR: case II_GEN_MAT_ELE_DESERT: case II_GEN_MAT_ELE_CYCLON:
return TRUE;
default:
return FALSE;
}
}
#endif // __15_5TH_ELEMENTAL_SMELT_SAFETY
BOOL CItemElem::IsBinds( void )
{
ItemProp* pProperty = GetProp();
if( m_dwKeepTime && pProperty->dwItemKind2 != IK2_WARP )
return TRUE;
if( (pProperty->dwFlag & IP_FLAG_BINDS) == IP_FLAG_BINDS )
return TRUE;
if( IsFlag( CItemElem::binds ) )
return TRUE;
#if __VER >= 11 // __SYS_IDENTIFY
if( g_xRandomOptionProperty->GetRandomOptionSize( GetRandomOptItemId() ) > 0
&& ( g_xRandomOptionProperty->GetRandomOptionKind( this ) == CRandomOptionProperty::eBlessing || g_xRandomOptionProperty->GetRandomOptionKind( this ) == CRandomOptionProperty::eEatPet ) )
return TRUE;
if( GetLevelDown() < 0 )
return TRUE;
#endif // __SYS_IDENTIFY
return FALSE;
}
BOOL CItemElem::IsUndestructable( void )
{
ItemProp* pProperty = GetProp();
if( (pProperty->dwFlag & IP_FLAG_UNDESTRUCTABLE ) == IP_FLAG_UNDESTRUCTABLE )
return TRUE;
return FALSE;
}
BOOL CItemElem::IsLogable( void )
{
if( GetProp()->nLog != -1 || GetRandomOptItemId() != 0 )
return TRUE;
return FALSE;
}
#ifndef __VM_0820
#ifndef __MEM_TRACE
#ifdef __WORLDSERVER
#ifdef __VM_0819
CItemPool* CItem::m_pPool = new CItemPool( 512, "CItem" );
#else // __VM_0819
CItemPool* CItem::m_pPool = new CItemPool( 512 );
#endif // __VM_0819
#else // __WORLDSERVER
#ifdef __VM_0819
CItemPool* CItem::m_pPool = new CItemPool( 128, "CItem" );
#else // __VM_0819
CItemPool* CItem::m_pPool = new CItemPool( 128 );
#endif // __VM_0819
#endif // __WORLDSERVER
#endif // __MEM_TRACE
#endif // __VM_0820
//////////////////////////////////////////////////////////////////////
// CItem - 이것은 게임 월드 상에 실제로 등장하는 오브젝트 아이템이다.
//////////////////////////////////////////////////////////////////////
CItem::CItem()
{
m_dwType = OT_ITEM;
m_pItemBase = NULL;
m_idHolder = 0;
m_idOwn = NULL_ID;
m_dwDropTime = 0;
m_bDropMob = 0;
m_dwDropTime = timeGetTime();
#ifdef __CLIENT
m_fGroundY = 0;
m_vDelta.x = m_vDelta.y = m_vDelta.z = 0;
#endif //__CLIENT
#ifdef __EVENT_MONSTER
m_IdEventMonster = NULL_ID;
#endif // __EVENT_MONSTER
}
void CItem::SetOwner( OBJID id )
{
m_idOwn = id; // 이 아이템의 소유가 pAttacker(어태커)꺼란걸 표시.
m_dwDropTime = ::timeGetTime(); // 드랍 했을당시의 시간을 기록함.
m_bDropMob = TRUE; // 몹이 죽어서 떨군 돈은 표시를 해둠.
}
CItem::~CItem()
{
SAFE_DELETE( m_pItemBase );
if( GetWorld() )
{
#if !defined(__CLIENT)
#ifdef __LAYER_1021
GetWorld()->m_respawner.Increment( GetRespawn(), m_nRespawnType, FALSE, GetLayer() );
#else // __LAYER_1021
GetWorld()->m_respawner.Increment( GetRespawn(), m_nRespawnType, FALSE );
#endif // __LAYER_1021
#endif
}
}
BOOL CItem::Read( CFileIO* pFile )
{
CObj::Read( pFile );
return TRUE;
}
#ifdef __CLIENT
// 아이템을 생성시킬땐 이것을 불러줘야 중력에 의해 떨어진다.
void CItem::SetDelta( float fGroundY, D3DXVECTOR3 &vDelta )
{
m_fGroundY = fGroundY;
m_vDelta = vDelta;
}
#endif // __CLIENT
void CItem::Process()
{
CCtrl::Process();
#ifdef __CLIENT
AddAngle( 0.5f );
D3DXVECTOR3 vPos = GetPos();
//--- 비행몹에게 떨어진 좌표는 이처리를 해선 안된다.
if( m_fGroundY ) // 이게 0이면 중력처리를 해선 안된다.
{
if( vPos.y > m_fGroundY ) // 공중에 떠있느냐?
{
m_vDelta.y -= 0.0075f; // 이동벡터에 중력 벡터 더함.
}
else
{
vPos.y = m_fGroundY; // 바닥에 닿은 상태면 지면좌표와 동일하게 맞춤.
m_vDelta.x = m_vDelta.y = m_vDelta.z = 0; // 이동벡터는 없어짐. 튀기게 하려면 이렇게 하면 안된다.
SetPos( vPos ); // 최종 좌표 세팅.
}
// 이동벡터가 없으면 더해줄필요 없다.
if( m_vDelta.x == 0 && m_vDelta.y == 0 && m_vDelta.z == 0 )
{
// 현재 좌표가 변경될 필요 없다.
}
else
{
m_vDelta.x = m_vDelta.z = 0; // 여기에 값 넣지말것.
vPos += m_vDelta; // 이동 벡터를 더함.
SetPos( vPos );
}
}
#endif // __CLIENT
#ifdef __WORLDSERVER
if( g_eLocal.GetState( EVE_SCHOOL ) )
return;
if( (int)g_tmCurrent - (int)m_dwDropTime > MIN( 3 ) )
Delete();
#endif // __WORLDSERVER
}
void CItem::Render( LPDIRECT3DDEVICE9 pd3dDevice )
{
#ifndef __WORLDSERVER
ItemProp *pItemProp = GetProp();
if( pItemProp && pItemProp->nReflect > 0 )
{
// 주의!!! : m_pModel이 CModelObject라는것을 가정하고 한것이다. 아니라면 이렇게 쓰면 안된다.
((CModelObject*)m_pModel)->SetEffect( 0, XE_REFLECT );
}
CObj::Render( pd3dDevice );
if( xRandom( 50 ) == 1 )
CreateSfx( pd3dDevice, XI_GEN_ITEM_SHINE01, GetPos() );
#endif
}
void CItem::RenderName( LPDIRECT3DDEVICE9 pd3dDevice, CD3DFont* pFont, DWORD dwColor )
{
#ifndef __WORLDSERVER
// 월드 좌표를 스크린 좌표로 프로젝션 한다.
D3DXVECTOR3 vOut, vPos = GetPos(), vPosHeight;
D3DVIEWPORT9 vp;
const BOUND_BOX* pBB = m_pModel->GetBBVector();
pd3dDevice->GetViewport( &vp );
D3DXMATRIX matTrans;
D3DXMATRIX matWorld;
D3DXMatrixIdentity(&matWorld);
D3DXMatrixTranslation( &matTrans, vPos.x, vPos.y, vPos.z );
D3DXMatrixMultiply( &matWorld, &matWorld, &m_matScale );
D3DXMatrixMultiply( &matWorld, &matWorld, &m_matRotation );
D3DXMatrixMultiply( &matWorld, &matWorld, &matTrans );
vPosHeight = pBB->m_vPos[0];
vPosHeight.x = 0;
vPosHeight.z = 0;
D3DXVec3Project( &vOut, &vPosHeight, &vp, &GetWorld()->m_matProj,
&GetWorld()->m_pCamera->m_matView, &matWorld);
vOut.x -= pFont->GetTextExtent( m_pItemBase->GetProp()->szName ).cx / 2;
pFont->DrawText( vOut.x + 1, vOut.y + 1, 0xff000000, m_pItemBase->GetProp()->szName );
pFont->DrawText( vOut.x, vOut.y, dwColor, m_pItemBase->GetProp()->szName );
return;
#endif // __WORLDSERVER
}
void CItemBase::SetSerialNumber( void )
{
m_liSerialNumber = CSerialNumber::GetInstance()->Get();
}
CString CItemElem::GetName( void )
{
ItemProp* pProp = GetProp();
CString strName = pProp->szName;
#if __VER >= 9
if( pProp->dwItemKind3 == IK3_EGG && m_pPet /*&& m_pPet->GetLevel() > PL_EGG*/ )
{
MoverProp* pMoverProp = prj.GetMoverProp( m_pPet->GetIndex() );
if( pMoverProp )
{
#ifdef __PET_1024
if( m_pPet->HasName() )
strName.Format( prj.GetText( TID_GAME_CAGE_STRING ), m_pPet->GetName() );
else
#endif // __PET_1024
strName.Format( prj.GetText( TID_GAME_CAGE_STRING ), pMoverProp->szName );
}
}
/*
else if( pProp->IsUltimate() )
{
int nFind = strName.Find( "@", 0 );
if( nFind > -1 )
strName.Delete( nFind - 1, 2 );
}
*/
#endif //
return strName;
}
enum { eNoLevelDown, e5LevelDown, e10LevelDown, };
int GetLevelDown( void ); // 64|63
void SetLevelDown( int i );
#if __VER >= 11 // __SYS_IDENTIFY
int CItemElem::GetLevelDown( void )
{
if( m_iRandomOptItemId & 0x8000000000000000 )
return -10;
else if( m_iRandomOptItemId & 0x4000000000000000 )
return -5;
return 0;
}
void CItemElem::SetLevelDown( int i )
{
// 0x8000000000000000
// 0x4000000000000000
m_iRandomOptItemId &= ~0xC000000000000000;
if( i == e5LevelDown )
m_iRandomOptItemId |= 0x4000000000000000;
else if( i == e10LevelDown )
m_iRandomOptItemId |= 0x8000000000000000;
}
DWORD CItemElem::GetLimitLevel( void )
{
if( GetProp()->dwLimitLevel1 == 0xFFFFFFFF )
return 0xFFFFFFFF;
int nLimitLevel = static_cast<int>( GetProp()->dwLimitLevel1 ) + GetLevelDown();
if( nLimitLevel < 0 )
nLimitLevel = 0;
return (DWORD)nLimitLevel;
}
#endif // __SYS_IDENTIFY
#if __VER >= 14 // __NEW_ITEM_LIMIT_LEVEL
BOOL CItemElem::IsLimitLevel( CMover* pMover )
{
if( pMover->GetJobType() >= JTYPE_MASTER && pMover->GetJobType() > pMover->GetJobType( GetProp()->dwItemJob ) )
return FALSE;
if( (DWORD)( pMover->GetLevel() ) >= GetLimitLevel() )
return FALSE;
return TRUE;
}
#endif // __NEW_ITEM_LIMIT_LEVEL
#if __VER >= 12 // __EXT_PIERCING
// bSize는 피어싱 사이즈를 늘릴 수 있는지 검사할 때 TRUE값을 setting 한다.
// bSize를 TRUE로 할 경우 dwTagetItemKind3는 NULL_ID로 한다.
BOOL CItemElem::IsPierceAble( DWORD dwTargetItemKind3, BOOL bSize )
{
if( !GetProp() )
return FALSE;
int nPiercedSize = GetPiercingSize();
if( bSize ) // 피어싱 사이즈를 늘리는 경우
nPiercedSize++;
if( GetProp()->dwItemKind3 == IK3_SUIT )
{
if( nPiercedSize <= MAX_PIERCING_SUIT )
{
if( dwTargetItemKind3 == NULL_ID )
return TRUE;
else if( dwTargetItemKind3 == IK3_SOCKETCARD )
return TRUE;
}
}
else if( GetProp()->dwItemKind3 == IK3_SHIELD
|| GetProp()->dwItemKind2 == IK2_WEAPON_DIRECT
|| GetProp()->dwItemKind2 == IK2_WEAPON_MAGIC
)
{
if( nPiercedSize <= MAX_PIERCING_WEAPON )
{
if( dwTargetItemKind3 == NULL_ID )
return TRUE;
else if( dwTargetItemKind3 == IK3_SOCKETCARD2 )
return TRUE;
}
}
#if __VER >= 15 // __PETVIS
else if( IsVisPet() )
{
if( nPiercedSize <= MAX_VIS )
{
if( dwTargetItemKind3 == NULL_ID )
return TRUE;
else if( dwTargetItemKind3 == IK3_VIS )
return TRUE;
}
}
#endif // __PETVIS
return FALSE;
}
#endif // __EXT_PIERCING
#if __VER >= 11
#ifdef __WORLDSERVER
BOOL CItemElem::IsActiveTicket( DWORD dwItemId )
{
if( !IsFlag( expired ) && GetProp()->dwItemKind3 == IK3_TICKET && m_dwKeepTime > 0 )
{
TicketProp* pProp1 = CTicketProperty::GetInstance()->GetTicketProp( m_dwItemId );
TicketProp* pProp2 = CTicketProperty::GetInstance()->GetTicketProp( dwItemId );
return ( pProp1->dwWorldId == pProp2->dwWorldId );
}
return FALSE;
}
#endif // __WORLDSERVER
BOOL IsNeedTarget( ItemProp* pProp )
{ // 아이템을 사용하기 위해 더블 클릭 했을 때
// 커서가 바뀌면서 인벤토리 내 다른 아이템 클릭이 필요한 아이템인가?
#if __VER >= 12 // __PET_0519
// 아이템 식별자 추가가 번거로와 속성 확인으로 변경
return( pProp->dwExeTarget == EXT_ITEM );
#else // __PET_0519
switch( pProp->dwID )
{
case II_SYS_SYS_SCR_AWAKE:
case II_SYS_SYS_SCR_BLESSEDNESS:
case II_SYS_SYS_SCR_BLESSEDNESS02:
case II_SYS_SYS_SCR_LEVELDOWN01:
case II_SYS_SYS_SCR_LEVELDOWN02:
case II_SYS_SYS_SCR_AWAKECANCEL:
case II_SYS_SYS_SCR_AWAKECANCEL02:
case II_SYS_SYS_QUE_PETRESURRECTION02_S:
case II_SYS_SYS_QUE_PETRESURRECTION02_A:
case II_SYS_SYS_QUE_PETRESURRECTION02_B:
// case II_SYS_SYS_SCR_PETAWAKE:
// case II_SYS_SYS_SCR_PETAWAKECANCEL:
return TRUE;
default:
return FALSE;
}
#endif // __PET_0519
}
#endif // __VER
BOOL CItemElem::IsEgg()
{
if( !IsPet() )
return FALSE;
return ( !m_pPet || m_pPet->GetLevel() == PL_EGG );
}
#if __VER >= 15 // __PETVIS
void CItemElem::SetSwapVisItem( int nPos1, int nPos2 )
{
int nSize = GetPiercingSize();
if( nPos1 >= nSize || nPos2 >= nSize )
return;
DWORD dwTempId = GetPiercingItem( nPos1 );
time_t tmTemp = GetVisKeepTime( nPos1 );
SetPiercingItem( nPos1, GetPiercingItem( nPos2 ) );
SetVisKeepTime( nPos1, GetVisKeepTime( nPos2 ) );
SetPiercingItem( nPos2, dwTempId );
SetVisKeepTime( nPos2, tmTemp );
}
DWORD CItemElem::GetVisPetSfxId()
{
int nLevel = 0;
for( int i=0; i<GetPiercingSize(); i++ )
{
ItemProp* pProp = prj.GetItemProp( GetPiercingItem( i ) );
if( pProp && pProp->dwAbilityMax > (DWORD)( nLevel ) )
nLevel = pProp->dwAbilityMax;
}
switch( nLevel )
{
case 1: return XI_BUFFPET_GRADE1;
case 2: return XI_BUFFPET_GRADE2;
case 3: return XI_BUFFPET_GRADE3;
}
return NULL_ID;
}
#endif // __PETVIS
// mulcom BEGIN100405 각성 보호의 두루마리
__int64 CItemElem::GetNewRandomOption()
{
return m_n64NewRandomOption;
}
__int64* CItemElem::GetNewRandomOptionPtr()
{
return &m_n64NewRandomOption;
}
void CItemElem::ResetNewRandomOption()
{
m_n64NewRandomOption = 0;
return;
}
void CItemElem::SelectNewRandomOption()
{
m_iRandomOptItemId = (( m_iRandomOptItemId & 0xC0000000000000FF ) | m_n64NewRandomOption );
return;
}
bool CItemElem::SelectRandomOption( BYTE bySelectFlag )
{
bool bRetValue = true;
if( bySelectFlag == _AWAKE_OLD_VALUE )
{
ResetNewRandomOption();
}
else if( bySelectFlag == _AWAKE_NEW_VALUE )
{
SelectNewRandomOption();
ResetNewRandomOption();
}
else
{
WriteLog( "bySelectFlag is invalid value. bySelectFlag : [%d]", (int)( bySelectFlag ) );
bRetValue = false;
}
return bRetValue;
}
// mulcom END100405 각성 보호의 두루마리
//////////////////////////////////////////////////////////////////////////////// | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
888
]
]
] |
110b254aec038d5cd7894eb7b65d4ee00f958339 | e947bc69d8ee60ab0f1ccf28c9943027fa43f397 | /YJOptionDlg.cpp | 90fe0d46fca884b571b1c68d8c21bb15aa05185b | [] | no_license | losywee/yjui | fc33d8034d707a6663afef6cb8b55b1483992fc5 | caeea083b91597f7f3c46cb9e69dcb009258649a | refs/heads/master | 2021-01-10T07:35:15.909900 | 2010-04-01T09:14:23 | 2010-04-01T09:14:23 | 45,093,947 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,767 | cpp | // YJOptionDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "YJOptionDlg.h"
#include "Shared/Preferences.h"
#define TREE_MARGIN_TOP 10
#define TREE_MARGIN_BOTTOM 45
#define TREE_MARGIN_LEFT 10
#define TREE_WIDTH 120
#define GROUP_BOX_MARGIN_TOP TREE_MARGIN_TOP
#define GROUP_BOX_MARGIN_BOTTOM TREE_MARGIN_BOTTOM
#define GROUP_BOX_MARGIN_LEFT (TREE_MARGIN_LEFT + TREE_WIDTH + 10)
#define GROUP_BOX_MARGIN_RIGHT 10
#define PAGE_MARGIN_TOP (GROUP_BOX_MARGIN_TOP + 15)
#define PAGE_MARGIN_BOTTOM (GROUP_BOX_MARGIN_BOTTOM + 10)
#define PAGE_MARGIN_LEFT (GROUP_BOX_MARGIN_LEFT + 10)
#define PAGE_MARGIN_RIGHT (GROUP_BOX_MARGIN_RIGHT + 10)
// CYJOptionDlg 对话框
IMPLEMENT_DYNAMIC(CYJOptionDlg, CDialog)
CYJOptionDlg::CYJOptionDlg(UINT nIDResource,CWnd* pParent /*=NULL*/)
: CDialog(nIDResource, pParent)
{
m_aPages.RemoveAll();
}
CYJOptionDlg::~CYJOptionDlg()
{
}
void CYJOptionDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CYJOptionDlg, CDialog)
//{{AFX_MSG_MAP
//}}AFX_MSG_MAP
ON_MESSAGE(WM_PAGE_CHANGED,OnPageChanged)
END_MESSAGE_MAP()
HTREEITEM CYJOptionDlg::FindItem(CString strPath, BOOL bCreate/* = TRUE*/)
{
ASSERT(m_ctrlLeftTree.GetSafeHwnd());
HTREEITEM hCurrent = m_ctrlLeftTree.GetRootItem();
int index;
bool bIsFound = true;
while (true)
{
CString strTitle;
if ((index = strPath.Find('\\')) != -1)
{
strTitle = strPath.Left(index + 1);
strPath = strPath.Right(strPath.GetLength() - index -1);
}
else if (!strPath.IsEmpty())
{
strTitle = strPath;
strPath = "";
}
else
{
break;
}
if (bIsFound)
{
bool found = false;
do
{
if (m_ctrlLeftTree.GetItemText(hCurrent).CompareNoCase(strTitle) == 0)
{
found = true;
break;
}
} while ((hCurrent = m_ctrlLeftTree.GetNextSiblingItem(hCurrent)) != NULL);
if (found)
continue;
if (!bCreate)
return NULL;
else
bIsFound = false;
}
if (!bIsFound)
{
hCurrent = m_ctrlLeftTree.InsertItem(strTitle,hCurrent);
}
}
return hCurrent;
}
BOOL CYJOptionDlg::AddPage(CYJOptionPageBase* pPage, UINT nIDResource, CString strPagePath)
{
if (!m_ctrlLeftTree.GetSafeHwnd())
return FALSE;
pPage->Create(nIDResource,this);
m_aPages.Add(pPage);
m_ctrlLeftTree.SetItemData(FindItem(strPagePath),(LPARAM)pPage);
pPage->ShowWindow(SW_HIDE);
pPage->MoveWindow(&m_rtPageRect);
return TRUE;
}
void CYJOptionDlg::SetTreeCtrl(UINT nIDResource)
{
m_ctrlLeftTree.SubclassDlgItem(nIDResource,this);
m_ctrlLeftTree.MoveWindow(&m_rtTreeRect);
}
void CYJOptionDlg::SetGroupBox(UINT nIDResourse)
{
m_ctrlGroupBox.SubclassDlgItem(nIDResourse,this);
m_ctrlGroupBox.MoveWindow(&m_rtGroupBoxRect);
}
BOOL CYJOptionDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CRect rtClientRect;
GetClientRect(&rtClientRect);
m_rtTreeRect.SetRect(TREE_MARGIN_LEFT,TREE_MARGIN_TOP,TREE_MARGIN_LEFT + TREE_WIDTH,rtClientRect.bottom - TREE_MARGIN_BOTTOM);
m_rtGroupBoxRect.SetRect(GROUP_BOX_MARGIN_LEFT,GROUP_BOX_MARGIN_TOP,rtClientRect.right - GROUP_BOX_MARGIN_RIGHT,rtClientRect.bottom - GROUP_BOX_MARGIN_BOTTOM);
m_rtPageRect.top = PAGE_MARGIN_TOP;
m_rtPageRect.bottom = rtClientRect.bottom - PAGE_MARGIN_BOTTOM;
m_rtPageRect.left = PAGE_MARGIN_LEFT;
m_rtPageRect.right = rtClientRect.right - PAGE_MARGIN_RIGHT;
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
BOOL CYJOptionDlg::SelectPage(CString strPagePath)
{
HTREEITEM hItem;
if ((hItem = FindItem(strPagePath,FALSE)) != NULL)
{
m_ctrlLeftTree.Select(hItem,TVGN_CARET);
return TRUE;
}
return FALSE;
}
LRESULT CYJOptionDlg::OnPageChanged(WPARAM wParam, LPARAM lParam)
{
HTREEITEM hItem = (HTREEITEM)wParam;
if (!hItem)
return 0;
m_ctrlGroupBox.SetWindowText(m_ctrlLeftTree.GetItemText(hItem));
return 0;
}
void CYJOptionDlg::OnOK()
{
SavePreferences();
CDialog::OnOK();
}
void CYJOptionDlg::LoadPreferences()
{
if (m_aPages.GetSize() > 0)
{
CPreferences prefs;
for (int i = 0;i<m_aPages.GetSize();i++)
{
CYJOptionPageBase* pPage = m_aPages[i];
if (pPage && pPage->GetSafeHwnd())
{
pPage->LoadPreferences(prefs);
pPage->UpdateData(FALSE);
}
}
}
}
void CYJOptionDlg::SavePreferences()
{
if (m_aPages.GetSize() > 0)
{
CPreferences prefs;
for (int i = 0;i<m_aPages.GetSize();i++)
{
CYJOptionPageBase* pPage = m_aPages[i];
if (pPage && pPage->GetSafeHwnd())
{
pPage->UpdateData();
pPage->SavePreferences(prefs);
}
}
}
}
| [
"Caiyj.84@3d1e88fc-ca97-11de-9d4f-f947ee5921c8"
] | [
[
[
1,
217
]
]
] |
ad3eec3b493a5f91f99065c9536c584bde35f847 | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/moaicore/MOAIGfxQuadDeck2D.cpp | d4e9603cde8bad44717d085b98602f63dd2101da | [] | no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,975 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIDeckRemapper.h>
#include <moaicore/MOAIGfxQuadDeck2D.h>
#include <moaicore/MOAIGrid.h>
#include <moaicore/MOAILogMessages.h>
#include <moaicore/MOAIProp.h>
#include <moaicore/MOAITexture.h>
#include <moaicore/MOAITransformBase.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name reserve
@text Set capacity of quad deck.
@in MOAIGfxQuadDeck2D self
@in number nQuads
@out nil
*/
int MOAIGfxQuadDeck2D::_reserve ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "UN" )
u32 total = state.GetValue < u32 >( 2, 0 );
self->mQuads.Init ( total );
for ( u32 i = 0; i < total; ++i ) {
USGLQuad& quad = self->mQuads [ i ];
quad.SetVerts ( -0.5f, -0.5f, 0.5f, 0.5f );
quad.SetUVs ( 0.0f, 1.0f, 1.0f, 0.0f );
}
return 0;
}
//----------------------------------------------------------------//
/** @name setQuad
@text Set model space quad given a valid deck index. Vertex order is
clockwise from upper left (xMin, yMax)
@in MOAIGfxQuadDeck2D self
@in number idx Index of the quad.
@in number x0
@in number y0
@in number x1
@in number y1
@in number x2
@in number y2
@in number x3
@in number y3
@out nil
*/
int MOAIGfxQuadDeck2D::_setQuad ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "UNNNNNNNNN" )
u32 idx = state.GetValue < u32 >( 2, 1 ) - 1;
MOAI_CHECK_INDEX ( idx, self->mQuads.Size ())
if ( idx < self->mQuads.Size ()) {
USQuad quad;
quad.mV [ 0 ].mX = state.GetValue < float >( 3, 0.0f );
quad.mV [ 0 ].mY = state.GetValue < float >( 4, 0.0f );
quad.mV [ 1 ].mX = state.GetValue < float >( 5, 0.0f );
quad.mV [ 1 ].mY = state.GetValue < float >( 6, 0.0f );
quad.mV [ 2 ].mX = state.GetValue < float >( 7, 0.0f );
quad.mV [ 2 ].mY = state.GetValue < float >( 8, 0.0f );
quad.mV [ 3 ].mX = state.GetValue < float >( 9, 0.0f );
quad.mV [ 3 ].mY = state.GetValue < float >( 10, 0.0f );
self->mQuads [ idx ].SetVerts ( quad.mV [ 0 ], quad.mV [ 1 ], quad.mV [ 2 ], quad.mV [ 3 ]);
}
return 0;
}
//----------------------------------------------------------------//
/** @name setRect
@text Set model space quad given a valid deck index and a rect.
@in MOAIGfxQuadDeck2D self
@in number idx Index of the quad.
@in number xMin
@in number yMin
@in number xMax
@in number yMax
@out nil
*/
int MOAIGfxQuadDeck2D::_setRect ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "UNNNNN" )
u32 idx = state.GetValue < u32 >( 2, 1 ) - 1;
MOAI_CHECK_INDEX ( idx, self->mQuads.Size ())
float x0 = state.GetValue < float >( 3, 0.0f );
float y0 = state.GetValue < float >( 4, 0.0f );
float x1 = state.GetValue < float >( 5, 0.0f );
float y1 = state.GetValue < float >( 6, 0.0f );
if ( idx < self->mQuads.Size ()) {
self->mQuads [ idx ].SetVerts ( x0, y0, x1, y1 );
}
return 0;
}
//----------------------------------------------------------------//
/** @name setTexture
@text Set or load a texture for this deck.
@in MOAIGfxQuadDeck2D self
@in variant texture A MOAITexture, a MOAIDataBuffer or a path to a texture file
@opt number transform Any bitwise combination of MOAITexture.QUANTIZE, MOAITexture.TRUECOLOR, MOAITexture.PREMULTIPLY_ALPHA
@out MOAITexture texture
*/
int MOAIGfxQuadDeck2D::_setTexture ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "U" )
self->mTexture = MOAITexture::AffirmTexture ( state, 2 );
if ( self->mTexture ) {
self->mTexture->PushLuaUserdata ( state );
return 1;
}
return 0;
}
//----------------------------------------------------------------//
/** @name setUVQuad
@text Set UV space quad given a valid deck index. Vertex order is
clockwise from upper left (xMin, yMax)
@in MOAIGfxQuadDeck2D self
@in number idx Index of the quad.
@in number x0
@in number y0
@in number x1
@in number y1
@in number x2
@in number y2
@in number x3
@in number y3
@out nil
*/
int MOAIGfxQuadDeck2D::_setUVQuad ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "UNNNNNNNNN" )
u32 idx = state.GetValue < u32 >( 2, 1 ) - 1;
MOAI_CHECK_INDEX ( idx, self->mQuads.Size ())
if ( idx < self->mQuads.Size ()) {
USQuad quad;
quad.mV [ 0 ].mX = state.GetValue < float >( 3, 0.0f );
quad.mV [ 0 ].mY = state.GetValue < float >( 4, 0.0f );
quad.mV [ 1 ].mX = state.GetValue < float >( 5, 0.0f );
quad.mV [ 1 ].mY = state.GetValue < float >( 6, 0.0f );
quad.mV [ 2 ].mX = state.GetValue < float >( 7, 0.0f );
quad.mV [ 2 ].mY = state.GetValue < float >( 8, 0.0f );
quad.mV [ 3 ].mX = state.GetValue < float >( 9, 0.0f );
quad.mV [ 3 ].mY = state.GetValue < float >( 10, 0.0f );
self->mQuads [ idx ].SetUVs ( quad.mV [ 0 ], quad.mV [ 1 ], quad.mV [ 2 ], quad.mV [ 3 ]);
}
return 0;
}
//----------------------------------------------------------------//
/** @name setUVRect
@text Set UV space quad given a valid deck index and a rect.
@in MOAIGfxQuadDeck2D self
@in number idx Index of the quad.
@in number xMin
@in number yMin
@in number xMax
@in number yMax
@out nil
*/
int MOAIGfxQuadDeck2D::_setUVRect ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIGfxQuadDeck2D, "UNNNNN" )
u32 idx = state.GetValue < u32 >( 2, 1 ) - 1;
MOAI_CHECK_INDEX ( idx, self->mQuads.Size ())
float u0 = state.GetValue < float >( 3, 0.0f );
float v0 = state.GetValue < float >( 4, 0.0f );
float u1 = state.GetValue < float >( 5, 0.0f );
float v1 = state.GetValue < float >( 6, 0.0f );
if ( idx < self->mQuads.Size ()) {
self->mQuads [ idx ].SetUVs ( u0, v0, u1, v1 );
}
return 0;
}
//================================================================//
// MOAIGfxQuadDeck2D
//================================================================//
//----------------------------------------------------------------//
bool MOAIGfxQuadDeck2D::Bind () {
USDrawBuffer& drawBuffer = USDrawBuffer::Get ();
if ( !drawBuffer.SetTexture ( this->mTexture )) return false;
USGLQuad::BindVertexFormat ( drawBuffer );
return true;
}
//----------------------------------------------------------------//
void MOAIGfxQuadDeck2D::DrawPatch ( u32 idx, float xOff, float yOff, float xScale, float yScale ) {
u32 size = this->mQuads.Size ();
if ( size ) {
idx = ( idx - 1 ) % size;
this->mQuads [ idx ].Draw ( xOff, yOff, xScale, yScale );
}
}
//----------------------------------------------------------------//
USRect MOAIGfxQuadDeck2D::GetBounds ( u32 idx, MOAIDeckRemapper* remapper ) {
u32 size = this->mQuads.Size ();
if ( size ) {
idx = remapper ? remapper->Remap ( idx ) : idx;
idx = ( idx - 1 ) % size;
USGLQuad& quad = this->mQuads [ idx ];
return quad.GetVtxBounds ();
}
USRect rect;
rect.Init ( 0.0f, 0.0f, 0.0f, 0.0f );
return rect;
}
//----------------------------------------------------------------//
MOAIGfxQuadDeck2D::MOAIGfxQuadDeck2D () {
RTTI_SINGLE ( MOAIDeck2D )
this->SetContentMask ( MOAIProp::CAN_DRAW );
}
//----------------------------------------------------------------//
MOAIGfxQuadDeck2D::~MOAIGfxQuadDeck2D () {
}
//----------------------------------------------------------------//
void MOAIGfxQuadDeck2D::RegisterLuaClass ( USLuaState& state ) {
MOAIDeck2D::RegisterLuaClass ( state );
}
//----------------------------------------------------------------//
void MOAIGfxQuadDeck2D::RegisterLuaFuncs ( USLuaState& state ) {
MOAIDeck2D::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "reserve", _reserve },
{ "setQuad", _setQuad },
{ "setRect", _setRect },
{ "setTexture", _setTexture },
{ "setUVQuad", _setUVQuad },
{ "setUVRect", _setUVRect },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAIGfxQuadDeck2D::ScaleScreenCoords ( float xScale, float yScale ) {
u32 total = this->mQuads.Size ();
for ( u32 i = 0; i < total; ++i ) {
this->mQuads [ i ].ScaleVerts ( xScale, yScale );
}
}
//----------------------------------------------------------------//
void MOAIGfxQuadDeck2D::ScaleUVCoords ( float xScale, float yScale ) {
u32 total = this->mQuads.Size ();
for ( u32 i = 0; i < total; ++i ) {
this->mQuads [ i ].ScaleUVs ( xScale, yScale );
}
}
//----------------------------------------------------------------//
STLString MOAIGfxQuadDeck2D::ToString () {
STLString repr ( MOAIDeck::ToString () );
PRETTY_PRINT ( repr, mTexture )
return repr;
}
| [
"Patrick@agile.(none)"
] | [
[
[
1,
303
]
]
] |
ebce0b4cd01781079d15b04e43b86ee9d38ecfdc | 1493997bb11718d3c18c6632b6dd010535f742f5 | /freetype/example1.cpp | 0c9bbfaedd3dff5ac305d3a0e54161e5e5d70043 | [] | no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,266 | cpp | // example1.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "example1.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE g_hinst; // current instance
TCHAR g_title[MAX_LOADSTRING]; // The title bar text
TCHAR g_window_class[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
typedef struct { BYTE* ptr; int len; LONG width; LONG height; } Bitmap;
// this is really sad, i have to do it manaully
HBITMAP CreateGrayscaleDIB(Bitmap* bits)
{
struct { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[256]; } bmi;
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = bits->width;
bmi.bmiHeader.biHeight = -bits->height; // bitmap will be "top-down"
//bmi.bmiHeader.biHeight = bits->height; // bitmap will be "bottom-up"
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 8;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
bmi.bmiHeader.biXPelsPerMeter = 0;
bmi.bmiHeader.biYPelsPerMeter = 0;
bmi.bmiHeader.biClrUsed = 0;//256;
bmi.bmiHeader.biClrImportant = 0;//256;
// set grayscale color map
memset(bmi.bmiColors, 0, sizeof(bmi.bmiColors));
for (int i = 0; i < 256; i++)
{
bmi.bmiColors[ i ].rgbRed = i;
bmi.bmiColors[ i ].rgbGreen = i;
bmi.bmiColors[ i ].rgbBlue = i;
}
HBITMAP hbitmap = ::CreateDIBSection(NULL, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)(&bits->ptr), NULL, 0);
assert (hbitmap);
bits->len = bits->width * bits->height;
return hbitmap;
}
// freetype drawing code
#include <ft2build.h>
#include FT_FREETYPE_H
FT_Face g_font_face;
struct { char* ptr; size_t len; } g_text;
HDC g_memdc = NULL;
HGDIOBJ g_prevobj = NULL;
HBITMAP g_hbitmap = NULL;
Bitmap g_bitmap;
const int FONTSIZE = 24;
int OnCreate(HWND hWnd)
{
FT_Error error;
g_text.ptr = "#FreeType 2 library test.";
g_text.len = strlen(g_text.ptr);
// initialize freetype library
FT_Library library;
error = FT_Init_FreeType(&library);
if (error) return -1;
// load a typeface
char font_path[1024];
::ExpandEnvironmentStringsA("%SystemRoot%/fonts/arial.ttf", font_path, 1024-1);
error = FT_New_Face(library, font_path, 0, &g_font_face);
if (error) return -1;
// get current DPI
DEVMODE dev_mode;
dev_mode.dmSize = sizeof (DEVMODE);
::EnumDisplaySettingsEx(NULL, ENUM_CURRENT_SETTINGS, &dev_mode, 0);
WORD& dpi = dev_mode.dmLogPixels;
// set font size in points, using current DPI
error = FT_Set_Char_Size(g_font_face, FONTSIZE*64,0, dpi,0);
if (error) return -1;
g_memdc = ::CreateCompatibleDC(GetDC(hWnd));
g_bitmap.height = g_font_face->max_advance_height;
g_bitmap.width = g_font_face->max_advance_width;
g_hbitmap = CreateGrayscaleDIB(&g_bitmap);
g_prevobj = ::SelectObject(g_memdc, g_hbitmap);
assert (g_prevobj && HGDI_ERROR != g_prevobj);
return 0;
}
void OnDestroy()
{
::SelectObject(g_memdc, g_prevobj);
::DeleteObject(g_hbitmap);
::DeleteDC(g_memdc);
}
void OnDrawWindow(HDC hdc)
{
FT_Error error;
int pen_x = 0;
for (unsigned int i = 0; i < g_text.len; i++)
{
FT_UInt glyph_index = FT_Get_Char_Index(g_font_face, g_text.ptr[i]);
assert (glyph_index);
error = FT_Load_Glyph(g_font_face, // handle to face object
glyph_index, // glyph index
FT_LOAD_RENDER); // load flags
assert (!error);
//error = FT_Render_Glyph(g_font_face->glyph, // glyph slot
// FT_RENDER_MODE_NORMAL); // render mode
//assert (!error);
int& glyph_pitch = g_font_face->glyph->bitmap.pitch;
int& glyph_height = g_font_face->glyph->bitmap.rows;
int& glyph_width = g_font_face->glyph->bitmap.width;
int& glyph_bearing_x = g_font_face->glyph->bitmap_left;
int& glyph_bearing_y = g_font_face->glyph->bitmap_top;
int glyph_advance = g_font_face->glyph->advance.x / 64;
int hori_advance = g_font_face->glyph->metrics.horiAdvance / 64;
int vert_advance = g_font_face->glyph->metrics.vertAdvance / 64;
int face_ascender = g_font_face->ascender / 64;
int face_descender = g_font_face->descender / 64;
int face_height = g_font_face->height / 64;
memset(g_bitmap.ptr, 160, g_bitmap.len);
for (int y = 0; y < glyph_height; y++)
{
int src_row_start = y * glyph_pitch;
int dst_row_start = (y + (vert_advance - glyph_bearing_y)) * g_bitmap.width;
memcpy(g_bitmap.ptr + dst_row_start + glyph_bearing_x,
g_font_face->glyph->bitmap.buffer + src_row_start,
glyph_pitch);
}
::BitBlt(hdc, pen_x, 0, glyph_advance, face_height, g_memdc, 0, 0, SRCCOPY);
pen_x += glyph_advance;
}
}
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, g_title, MAX_LOADSTRING);
LoadString(hInstance, IDC_EXAMPLE1, g_window_class, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_EXAMPLE1));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_EXAMPLE1));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_EXAMPLE1);
wcex.lpszClassName = g_window_class;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
g_hinst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(g_window_class, g_title, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(g_hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
OnDrawWindow(hdc);
EndPaint(hWnd, &ps);
break;
case WM_CREATE:
return OnCreate(hWnd);
case WM_DESTROY:
OnDestroy();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"[email protected]"
] | [
[
[
1,
333
]
]
] |
c9afd64a71cead0b92f61176be503b0a8fe53c61 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-19/pcbnew/class_pad.cpp | ef3006eb081ed7a84f772d04aba9c58df6aabd88 | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 18,166 | cpp | /************************************************/
/* class_pad.cpp : fonctions de la classe D_PAD */
/************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "wxstruct.h"
#include "common.h"
#include "pcbnew.h"
#include "trigo.h"
#ifdef PCBNEW
#include "drag.h"
#endif
#ifdef CVPCB
#include "cvpcb.h"
#endif
#include "protos.h"
/*******************************/
/* classe D_PAD : constructeur */
/*******************************/
D_PAD::D_PAD(MODULE * parent): EDA_BaseStruct( parent, TYPEPAD)
{
memset(m_Padname, 0, sizeof(m_Padname));
m_Masque_Layer = CUIVRE_LAYER;
m_NetCode = 0; /* Numero de net pour comparaisons rapides */
m_Drill = 0; // Diametre de percage
m_Size.x = m_Size.y = 500; // Dimensions X et Y ( si orient 0 x = axe Y
// y = axe Y
if (m_Parent && (m_Parent->m_StructType == TYPEMODULE) )
{
m_Pos = ((MODULE*)m_Parent)->m_Pos;
}
m_PadShape = CIRCLE; // forme CERCLE, RECT OVALE TRAPEZE ou libre
m_Attribut = STANDARD; // NORMAL, SMD, CONN, Bit 7 = STACK
m_Orient = 0; // en 1/10 degres
m_logical_connexion = 0;
m_physical_connexion = 0; // variables utilisee lors du calcul du chevelu
ComputeRayon();
}
D_PAD::~D_PAD(void)
{
}
/****************************/
void D_PAD::ComputeRayon(void)
/****************************/
/* met a jour m_Rayon, rayon du cercle exinscrit
*/
{
switch (m_PadShape & 0x7F)
{
case CIRCLE :
m_Rayon = m_Size.x/2;
break;
case OVALE :
m_Rayon = MAX(m_Size.x, m_Size.y) / 2;
break;
case RECT :
case SPECIAL_PAD:
case TRAPEZE:
m_Rayon = (int)(sqrt((float)m_Size.y * m_Size.y
+ (float)m_Size.x * m_Size.x) / 2);
break;
}
}
/*********************************************/
const wxPoint D_PAD::ReturnShapePos(void) const
/*********************************************/
// retourne la position de la forme (pastilles excentrees)
{
if ( (m_Offset.x == 0) && (m_Offset.y == 0) ) return m_Pos;
wxPoint shape_pos;
int dX, dY;
dX = m_Offset.x; dY = m_Offset.y;
RotatePoint(&dX, &dY, m_Orient );
shape_pos.x = m_Pos.x + dX; shape_pos.y = m_Pos.y + dY;
return shape_pos;
}
/****************************************/
wxString D_PAD::ReturnStringPadName(void)
/****************************************/
/* Return pad name as string in a wxString
*/
{
wxString name;
ReturnStringPadName(name);
return name;
}
/********************************************/
void D_PAD::ReturnStringPadName(wxString & text)
/********************************************/
/* Return pad name as string in a buffer
*/
{
int ii;
text.Empty();
for ( ii = 0; ii < 4; ii++ )
{
if ( m_Padname[ii] == 0 ) break;
text.Append(m_Padname[ii]);
}
}
/********************************************/
void D_PAD::SetPadName(const wxString & name)
/********************************************/
// Change pad name
{
int ii, len;
len = name.Length();
if ( len > 4 ) len = 4;
for (ii = 0; ii < len; ii ++ ) m_Padname[ii] = name.GetChar(ii);
for (ii = len; ii < 4; ii ++ ) m_Padname[ii] = 0;
}
/********************************/
void D_PAD::Copy(D_PAD * source)
/********************************/
{
if (source == NULL) return;
m_Pos = source->m_Pos;
m_Masque_Layer = source->m_Masque_Layer;
memcpy(m_Padname,source->m_Padname, sizeof(m_Padname));/* nom de la pastille */
m_NetCode = source->m_NetCode; /* Numero de net pour comparaisons rapides */
m_Drill = source->m_Drill; // Diametre de percage
m_Offset = source->m_Offset; // Offset de la forme
m_Size = source->m_Size; // Dimension ( pour orient 0 )
m_DeltaSize = source->m_DeltaSize; // delta sur formes rectangle -> trapezes
m_Pos0 = source->m_Pos0; // Coord relatives a l'ancre du pad en
// orientation 0
m_Rayon = source->m_Rayon; // rayon du cercle exinscrit du pad
m_PadShape = source->m_PadShape; // forme CERCLE, RECT OVALE TRAPEZE ou libre
m_Attribut = source->m_Attribut; // NORMAL, SMD, CONN, Bit 7 = STACK
m_Orient = source->m_Orient; // en 1/10 degres
m_logical_connexion = 0; // variable utilisee lors du calcul du chevelu
m_physical_connexion = 0; // variable utilisee lors du calcul de la connexité
m_Netname = source->m_Netname;
}
/**************************/
void D_PAD::UnLink( void )
/**************************/
/* supprime du chainage la structure Struct
les structures arrieres et avant sont chainees directement
*/
{
/* Modification du chainage arriere */
if( Pback )
{
if( Pback->m_StructType != TYPEMODULE)
{
Pback->Pnext = Pnext;
}
else /* Le chainage arriere pointe sur la structure "Pere" */
{
((MODULE*)Pback)->m_Pads = (D_PAD *) Pnext;
}
}
/* Modification du chainage avant */
if( Pnext) Pnext->Pback = Pback;
Pnext = Pback = NULL;
}
/*******************************************************************************************/
void D_PAD::Draw(WinEDA_DrawPanel * panel, wxDC * DC, const wxPoint & offset, int draw_mode)
/*******************************************************************************************/
/* Tracé a l'écran d'un pad:
Entree :
ptr_pad = pointeur sur le pad du module
offset = offset de trace
draw_mode = mode de trace ( GR_OR, GR_XOR, GR_AND)
*/
{
int ii;
int color = 0;
int ux0,uy0,
dx,dx0,dy,dy0,
rotdx,
delta_cx, delta_cy,
xc, yc;
int angle, delta_angle, trou;
wxPoint coord[4];
int zoom;
int fillpad = 0;
PCB_SCREEN * screen;
WinEDA_BasePcbFrame * frame;
wxPoint shape_pos;
screen = panel ? (PCB_SCREEN *) panel->m_Parent->m_CurrentScreen : ActiveScreen;
frame = screen->GetParentPcbFrame();
/* Calcul de l'aspect du pad */
if( frame->m_DisplayPadFill == FILLED) fillpad = 1;
zoom = screen->GetZoom();
#ifdef PCBNEW
if( m_Flags & IS_MOVED) fillpad = 0;
#endif
if ( m_Masque_Layer & CMP_LAYER ) color = g_PadCMPColor ;
if ( m_Masque_Layer & CUIVRE_LAYER ) color |= g_PadCUColor ;
if( color == 0) /* Non cuivre externe */
{
color = DARKGRAY;
}
if ( draw_mode & GR_SURBRILL )
{
if(draw_mode & GR_AND) color &= ~HIGHT_LIGHT_FLAG;
else color |= HIGHT_LIGHT_FLAG;
}
if ( color & HIGHT_LIGHT_FLAG)
color = ColorRefs[color & MASKCOLOR].m_LightColor;
GRSetDrawMode(DC, draw_mode); /* mode de trace */
trou = m_Drill >> 1 ;
/* calcul du centre des pads en coordonnees Ecran : */
shape_pos = ReturnShapePos();
ux0 = shape_pos.x - offset.x;
uy0 = shape_pos.y - offset.y;
xc = ux0;
yc = uy0;
/* le trace depend de la rotation de l'empreinte */
dx = dx0 = m_Size.x >> 1 ;
dy = dy0 = m_Size.y >> 1 ; /* demi dim dx et dy */
angle = m_Orient;
switch (m_PadShape & 0x7F)
{
case CIRCLE :
if ( fillpad)
GRFilledCircle(&panel->m_ClipBox, DC, xc, yc, dx, color, color);
else GRCircle(&panel->m_ClipBox, DC, xc, yc, dx, color);
if(DisplayOpt.DisplayPadIsol)
{
GRCircle(&panel->m_ClipBox, DC, xc, yc, dx + g_DesignSettings.m_TrackClearence, color );
}
break;
case OVALE :
/* calcul de l'entraxe de l'ellipse */
if( dx > dy ) /* ellipse horizontale */
{
delta_cx = dx - dy; delta_cy = 0;
rotdx = m_Size.y;
delta_angle = angle+900;
}
else /* ellipse verticale */
{
delta_cx = 0; delta_cy = dy - dx;
rotdx = m_Size.x;
delta_angle = angle;
}
RotatePoint(&delta_cx, &delta_cy, angle);
if (fillpad)
{
GRFillCSegm(&panel->m_ClipBox, DC, ux0 + delta_cx, uy0 + delta_cy,
ux0 - delta_cx, uy0 - delta_cy,
rotdx, color);
}
else
{
GRCSegm(&panel->m_ClipBox, DC, ux0 + delta_cx, uy0 + delta_cy,
ux0 - delta_cx, uy0 - delta_cy,
rotdx, color);
}
/* Trace de la marge d'isolement */
if(DisplayOpt.DisplayPadIsol)
{
rotdx = rotdx + g_DesignSettings.m_TrackClearence + g_DesignSettings.m_TrackClearence;
GRCSegm(&panel->m_ClipBox, DC, ux0 + delta_cx, uy0 + delta_cy,
ux0 - delta_cx, uy0 - delta_cy,
rotdx, color);
}
break;
case RECT :
case SPECIAL_PAD:
case TRAPEZE:
{
int ddx, ddy ;
ddx = m_DeltaSize.x >> 1 ;
ddy = m_DeltaSize.y >> 1 ; /* demi dim dx et dy */
coord[0].x = - dx - ddy;
coord[0].y = + dy + ddx;
coord[1].x = - dx + ddy;
coord[1].y = - dy - ddx;
coord[2].x = + dx - ddy;
coord[2].y = - dy + ddx;
coord[3].x = + dx + ddy;
coord[3].y = + dy - ddx;
for (ii = 0; ii < 4; ii++)
{
RotatePoint(&coord[ii].x,&coord[ii].y, angle);
coord[ii].x = coord[ii].x + ux0;
coord[ii].y = coord[ii].y + uy0;
}
GRClosedPoly(&panel->m_ClipBox, DC, 4, (int*) coord, fillpad, color, color);
if(DisplayOpt.DisplayPadIsol)
{
dx += g_DesignSettings.m_TrackClearence; dy += g_DesignSettings.m_TrackClearence;
coord[0].x = -dx - ddy;
coord[0].y = dy + ddx;
coord[1].x = -dx + ddy;
coord[1].y = -dy - ddx;
coord[2].x = dx - ddy;
coord[2].y = -dy + ddx;
coord[3].x = dx + ddy;
coord[3].y = dy - ddx;
for (ii = 0; ii < 4; ii++)
{
RotatePoint(&coord[ii].x,&coord[ii].y, angle);
coord[ii].x = coord[ii].x + ux0;
coord[ii].y = coord[ii].y + uy0;
}
GRClosedPoly(&panel->m_ClipBox, DC, 4, (int*)coord, 0, color, color);
}
break;
default:
break;
}
}
/* trace du trou de percage */
int cx0 = m_Pos.x - offset.x;
int cy0 = m_Pos.y - offset.y;
if( fillpad && trou )
{
if( (trou/zoom) > 1 ) /* C.a.d si le diametre est suffisant */
{
color = g_IsPrinting ? WHITE : BLACK; // ou DARKGRAY;
if(draw_mode != GR_XOR) GRSetDrawMode(DC, GR_COPY);
else GRSetDrawMode(DC, GR_XOR);
GRFilledCircle(&panel->m_ClipBox, DC, cx0, cy0, trou, color, color);
}
}
GRSetDrawMode(DC, draw_mode);
/* Trace du symbole "No connect" ( / ou \ ou croix en X) si necessaire : */
if( (m_NetCode == 0) && DisplayOpt.DisplayPadNoConn )
{
dx0 = min(dx0,dy0);
int nc_color = BLUE;
if(m_Masque_Layer & CMP_LAYER) /* Trace forme \ */
GRLine(&panel->m_ClipBox, DC, cx0 - dx0, cy0 - dx0,
cx0 + dx0, cy0 + dx0, nc_color );
if(m_Masque_Layer & CUIVRE_LAYER) /* Trace forme / */
GRLine(&panel->m_ClipBox, DC, cx0 + dx0, cy0 - dx0,
cx0 - dx0, cy0 + dx0, nc_color );
}
/* Trace de la reference */
if( ! frame->m_DisplayPadNum) return;
dx = min(m_Size.x, m_Size.y); /* dx = taille du texte */
if( (dx / zoom) > 12 ) /* Si taille suffisante pour 2 lettres */
{
wxString buffer;
ReturnStringPadName(buffer);
dy = buffer.Len();
if ( dy < 2 ) dy = 2; /* alignement sur textes a 2 lettres */
dx = (dx * 9 ) / (dy * 13 ); /* le texte est ajuste pour
tenir entierement dans la pastille */
DrawGraphicText(panel, DC, wxPoint(ux0, uy0),
WHITE, buffer, angle, wxSize(dx, dx),
GR_TEXT_HJUSTIFY_CENTER, GR_TEXT_VJUSTIFY_CENTER);
}
}
/*************************************************/
int D_PAD::ReadDescr( FILE * File, int * LineNum)
/*************************************************/
/* Routine de lecture de descr de pads
la 1ere ligne de descr ($PAD) est supposee etre deja lue
syntaxe:
$PAD
Sh "N1" C 550 550 0 0 1800
Dr 310 0 0
At STD N 00C0FFFF
Ne 3 "netname"
Po 6000 -6000
$EndPAD
*/
{
char Line[1024], BufLine[1024], BufCar[256];
char * PtLine;
int nn, ll;
while( GetLine(File, Line, LineNum ) != NULL )
{
if( Line[0] == '$' ) return( 0 );
PtLine = Line + 3; /* Pointe 1er code utile de la ligne */
switch( Line[0] )
{
case 'S': /* Ligne de description de forme et dims*/
/* Lecture du nom pad */
nn = 0;
while( (*PtLine != '"') && *PtLine ) PtLine++;
if ( *PtLine ) PtLine++;
memset(m_Padname,0 ,sizeof(m_Padname) );
while( (*PtLine != '"') && *PtLine )
{
if(nn < (int) sizeof(m_Padname))
{
if( * PtLine > ' ' )
{
m_Padname[nn] = *PtLine; nn++;
}
}
PtLine++;
}
if ( *PtLine == '"' ) PtLine++;
nn = sscanf(PtLine," %s %d %d %d %d %d",
BufCar, &m_Size.x, &m_Size.y,
&m_DeltaSize.x, &m_DeltaSize.y,
&m_Orient);
ll = 0xFF & BufCar[0];
/* Mise a jour de la forme */
m_PadShape = CIRCLE;
switch(ll)
{
case 'C': m_PadShape = CIRCLE; break;
case 'R': m_PadShape = RECT; break;
case 'O': m_PadShape = OVALE; break;
case 'T': m_PadShape = TRAPEZE; break;
}
ComputeRayon();
break;
case 'D':
nn = sscanf(PtLine,"%d %d %d", &m_Drill,
&m_Offset.x, &m_Offset.y);
break;
case 'A':
nn = sscanf(PtLine,"%s %s %X", BufLine, BufCar,
&m_Masque_Layer);
/* Contenu de BufCar non encore utilise ( reserve pour evolutions
ulterieures */
/* Mise a jour de l'attribut */
m_Attribut = STANDARD;
if( strncmp(BufLine,"SMD",3) == 0 ) m_Attribut = SMD;
if( strncmp(BufLine,"CONN",4) == 0 ) m_Attribut = CONN;
if( strncmp(BufLine,"HOLE",4) == 0 ) m_Attribut = P_HOLE;
if( strncmp(BufLine,"MECA",4) == 0 ) m_Attribut = MECA;
break;
case 'N': /* Lecture du netname */
nn = sscanf(PtLine,"%d", &m_NetCode);
/* Lecture du netname */
ReadDelimitedText(BufLine, PtLine, sizeof(BufLine));
m_Netname = CONV_FROM_UTF8(StrPurge(BufLine));
break;
case 'P':
nn = sscanf(PtLine,"%d %d", &m_Pos0.x, &m_Pos0.y );
m_Pos = m_Pos0;
break;
default:
DisplayError(NULL, wxT("Err Pad: Id inconnu"));
return(1);
}
}
return(2); /* error : EOF */
}
/***********************************/
int D_PAD::WriteDescr( FILE * File )
/***********************************/
/* Sauvegarde de la description d'un PAD
*/
{
int cshape, NbLigne = 0;;
char * texttype;
if( GetState(DELETED) ) return(NbLigne);
/* Generation du fichier pad: */
fprintf( File,"$PAD\n"); NbLigne++;
switch(m_PadShape)
{
case CIRCLE: cshape = 'C'; break;
case RECT: cshape = 'R'; break;
case OVALE: cshape = 'O'; break;
case TRAPEZE: cshape = 'T'; break;
default: cshape = 'C';
DisplayError(NULL, wxT("Forme Pad inconnue"));
break;
}
fprintf(File,"Sh \"%.4s\" %c %d %d %d %d %d\n",
m_Padname, cshape, m_Size.x, m_Size.y,
m_DeltaSize.x, m_DeltaSize.y,m_Orient);
NbLigne++;
fprintf(File,"Dr %d %d %d\n", m_Drill, m_Offset.x, m_Offset.y );
NbLigne++;
switch(m_Attribut)
{
case STANDARD: texttype = "STD"; break;
case SMD: texttype = "SMD"; break;
case CONN: texttype = "CONN"; break;
case P_HOLE: texttype = "HOLE"; break;
case MECA: texttype = "MECA"; break;
default:
texttype = "STD";
DisplayError(NULL, wxT("attribut Pad inconnu"));
break;
}
fprintf(File,"At %s N %8.8X\n", texttype, m_Masque_Layer);
NbLigne++;
fprintf(File,"Ne %d \"%s\"\n", m_NetCode,CONV_TO_UTF8(m_Netname));
NbLigne++;
fprintf(File,"Po %d %d\n", m_Pos0.x, m_Pos0.y );
NbLigne++;
fprintf( File,"$EndPAD\n");
NbLigne++;
return(NbLigne);
}
/******************************************************/
void D_PAD::Display_Infos(WinEDA_BasePcbFrame * frame)
/******************************************************/
/* Affiche en bas d'ecran les caract de la pastille demandee */
{
int ii;
MODULE* Module;
wxString Line;
int pos = 1;
/* Pad messages */
wxString Msg_Pad_Shape[6] =
{ wxT("??? "), wxT("Circ"), wxT("Rect"), wxT("Oval"), wxT("trap"), wxT("spec") } ;
wxString Msg_Pad_Layer[8] =
{ wxT("??? "), wxT("cmp "), wxT("cu "), wxT("cmp+cu "), wxT("int "),
wxT("cmp+int "), wxT("cu+int "), wxT("all ") } ;
wxString Msg_Pad_Attribut[5] =
{ wxT("norm"), wxT("smd "), wxT("conn"), wxT("hole"), wxT("????")} ;
frame->MsgPanel->EraseMsgBox();
/* Recherche du module correspondant */
Module = (MODULE *) m_Parent;
if(Module)
{
wxString msg = Module->m_Reference->m_Text;
Affiche_1_Parametre(frame, pos,_("Module"), msg, DARKCYAN) ;
ReturnStringPadName(Line);
pos += 8;
Affiche_1_Parametre(frame, pos,_("RefP"),Line,BROWN) ;
}
pos += 4;
Affiche_1_Parametre(frame, pos,_("Net"),m_Netname, DARKCYAN);
/* pour mise au point (peut etre supprimé) : Affichage du numero de Net et sous net */
pos += 10;
#if 0
Line.Printf( wxT("%d.%d "),m_logical_connexion, m_physical_connexion);
Affiche_1_Parametre(frame, pos,"L.P",Line,WHITE);
#endif
ii = 0;
if(m_Masque_Layer & CUIVRE_LAYER) ii = 2;
if(m_Masque_Layer & CMP_LAYER) ii += 1;
if((m_Masque_Layer & ALL_CU_LAYERS) == ALL_CU_LAYERS) ii = 7;
pos += 3;
Affiche_1_Parametre(frame, pos,_("Layer"),Msg_Pad_Layer[ii], DARKGREEN) ;
pos += 6;
Affiche_1_Parametre(frame, pos,Msg_Pad_Shape[m_PadShape],wxEmptyString, DARKGREEN);
/* Affichage en couleur diff si pad stack ou non */
if (m_Attribut & PAD_STACK)
Affiche_1_Parametre(frame, -1,wxEmptyString,Msg_Pad_Attribut[m_Attribut&15],RED);
else Affiche_1_Parametre(frame, -1,wxEmptyString,Msg_Pad_Attribut[m_Attribut&15], DARKGREEN);
valeur_param(m_Size.x,Line) ;
pos += 6;
Affiche_1_Parametre(frame, pos,_("H Size"),Line,RED) ;
valeur_param(m_Size.y,Line) ;
pos += 7;
Affiche_1_Parametre(frame, pos,_("V Size"),Line,RED) ;
valeur_param((unsigned)m_Drill,Line) ;
pos += 7;
Affiche_1_Parametre(frame, pos,_("Drill"),Line,RED) ;
int module_orient = Module ? Module->m_Orient : 0;
if( module_orient )
Line.Printf( wxT("%3.1f(+%3.1f)"),
(float)(m_Orient - module_orient) /10, (float)module_orient /10);
else
Line.Printf( wxT("%3.1f"), (float) m_Orient /10);
pos += 8;
Affiche_1_Parametre(frame, pos,_("Orient"),Line,BLUE);
valeur_param(m_Pos.x,Line);
pos += 8;
Affiche_1_Parametre(frame, pos,_("X Pos"),Line,BLUE) ;
valeur_param(m_Pos.y,Line);
pos += 6;
Affiche_1_Parametre(frame, pos,_("Y pos"),Line,BLUE) ;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
668
]
]
] |
16ebe08b4ba33ede81651852f93490c4352e756e | b38ab5dcfb913569fc1e41e8deedc2487b2db491 | /libraries/SoftFX/header/Override.hpp | 5c98a36b685449872a187d0e206580669e48a581 | [] | no_license | santosh90n/Fury2 | dacec86ab3972952e4cf6442b38e66b7a67edade | 740a095c2daa32d33fdc24cc47145a1c13431889 | refs/heads/master | 2020-03-21T00:44:27.908074 | 2008-10-16T07:09:17 | 2008-10-16T07:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,950 | hpp | /*
SoftFX (Software graphics manipulation library)
Copyright (C) 2003 Kevin Gadd
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
*/
#define _SECURE_SCL 0
#define _SECURE_SCL_THROWS 0
#include <map>
#include <string>
#include <string.h>
#include <vector>
#include <list>
#include <algorithm>
#include "../header/Constant_Overrides.hpp"
#define SS_Start
#define SS_End
#ifndef Export
#define Export extern "C" __declspec(dllexport)
#endif
inline unsigned int va_float(float value) {
return *(reinterpret_cast<unsigned int*>(&value));
}
namespace Override {
typedef void* Override;
typedef std::vector<Override> OverrideList;
typedef std::map<std::string, OverrideIndex> SToITable;
extern std::string OverrideIToSTable[_count];
extern SToITable OverrideSToITable;
extern OverrideList Overrides[_count];
extern bool EnableOverrides;
extern int BypassOverrides;
struct OverrideParameters {
int count;
const char* key;
int index;
unsigned int p[16];
};
inline OverrideList* ResolveOverrides(const OverrideIndex key) {
#if (defined(OVERRIDES) || !defined(SOFTFX))
if (Overrides[key].size()) {
return Overrides + key;
}
return 0;
#else
return 0;
#endif
}
inline OverrideIndex OverrideKeyToIndex(const std::string& key) {
SToITable::const_iterator iter = OverrideSToITable.find(key);
if (iter != OverrideSToITable.end()) {
return iter->second;
} else {
return (OverrideIndex)-1;
}
}
inline OverrideIndex OverrideKeyToIndex(const char* key) {
return OverrideKeyToIndex(std::string(key));
}
inline const std::string& OverrideIndexToKey(OverrideIndex index) {
return (OverrideIToSTable[index]);
}
void InitOverrides();
void CleanupOverrides();
#if (defined(OVERRIDES) || !defined(SOFTFX))
int EnumOverrides(Override::OverrideIndex key, int parameter_count, ...);
#else
int EnumOverrides(Override::OverrideIndex key, int parameter_count, ...);
#endif
};
Export int AddOverride(const char* key, Override::Override value);
Export int AddOverrideAtBack(const char* key, Override::Override value);
Export int RemoveOverride(const char* key, Override::Override value);
Export int GetOverrideCount(const char* key);
Export int BypassOverrides(int Adjust);
| [
"kevin@1af785eb-1c5d-444a-bf89-8f912f329d98",
"janus@1af785eb-1c5d-444a-bf89-8f912f329d98"
] | [
[
[
1,
19
],
[
22,
36
],
[
41,
42
],
[
44,
59
],
[
63,
100
]
],
[
[
20,
21
],
[
37,
40
],
[
43,
43
],
[
60,
62
]
]
] |
b423d80c6fd17878a674280f69cef71dc0f25b37 | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /External/bullet/src/LinearMath/btScalar.h | 70994c19d615ec4a5f97caeae07ce989ee0e7f31 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 16,080 | h | /*
Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com
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.
*/
#ifndef SIMD___SCALAR_H
#define SIMD___SCALAR_H
#include <math.h>
#include <stdlib.h>//size_t for MSVC 6.0
#include <cstdlib>
#include <cfloat>
#include <float.h>
/* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
#define BT_BULLET_VERSION 275
inline int btGetVersion()
{
return BT_BULLET_VERSION;
}
#if defined(DEBUG) || defined (_DEBUG)
#define BT_DEBUG
#endif
#ifdef WIN32
#if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300)
#define SIMD_FORCE_INLINE inline
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#else
//#define BT_HAS_ALIGNED_ALLOCATOR
#pragma warning(disable : 4324) // disable padding warning
// #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning.
// #pragma warning(disable:4996) //Turn off warnings about deprecated C routines
// #pragma warning(disable:4786) // Disable the "debug name too long" warning
#define SIMD_FORCE_INLINE __forceinline
#define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a
#define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a
#ifdef _XBOX
#define BT_USE_VMX128
#include <ppcintrinsics.h>
#define BT_HAVE_NATIVE_FSEL
#define btFsel(a,b,c) __fsel((a),(b),(c))
#else
#if (defined (WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined (BT_USE_DOUBLE_PRECISION))
#define BT_USE_SSE
#include <emmintrin.h>
#endif
#endif//_XBOX
#endif //__MINGW32__
#include <assert.h>
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#if defined (__CELLOS_LV2__)
#define SIMD_FORCE_INLINE inline
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#ifdef USE_LIBSPE2
#define SIMD_FORCE_INLINE __inline
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) __builtin_expect((_c), 1)
#define btUnlikely(_c) __builtin_expect((_c), 0)
#else
//non-windows systems
#if (defined (__APPLE__) && defined (__i386__) && (!defined (BT_USE_DOUBLE_PRECISION)))
#define BT_USE_SSE
#include <emmintrin.h>
#define SIMD_FORCE_INLINE inline
///@todo: check out alignment methods for other platforms/compilers
#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined (_DEBUG)
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#define SIMD_FORCE_INLINE inline
///@todo: check out alignment methods for other platforms/compilers
///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined (_DEBUG)
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#endif //__APPLE__
#endif // LIBSPE2
#endif //__CELLOS_LV2__
#endif
///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
#if defined(BT_USE_DOUBLE_PRECISION)
typedef double btScalar;
//this number could be bigger in double precision
#define BT_LARGE_FLOAT 1e30
#else
typedef float btScalar;
//keep BT_LARGE_FLOAT*BT_LARGE_FLOAT < FLT_MAX
#define BT_LARGE_FLOAT 1e18f
#endif
#define BT_DECLARE_ALIGNED_ALLOCATOR() \
SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes,16); } \
SIMD_FORCE_INLINE void operator delete(void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete(void*, void*) { } \
SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes,16); } \
SIMD_FORCE_INLINE void operator delete[](void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete[](void*, void*) { } \
#if defined(BT_USE_DOUBLE_PRECISION) || defined(BT_FORCE_DOUBLE_FUNCTIONS)
SIMD_FORCE_INLINE btScalar btSqrt(btScalar x) { return sqrt(x); }
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabs(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cos(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sin(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tan(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { if (x<btScalar(-1)) x=btScalar(-1); if (x>btScalar(1)) x=btScalar(1); return acos(x); }
SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { if (x<btScalar(-1)) x=btScalar(-1); if (x>btScalar(1)) x=btScalar(1); return asin(x); }
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atan(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return exp(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return log(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return pow(x,y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmod(x,y); }
#else
SIMD_FORCE_INLINE btScalar btSqrt(btScalar y)
{
#ifdef USE_APPROXIMATION
double x, z, tempf;
unsigned long *tfptr = ((unsigned long *)&tempf) + 1;
tempf = y;
*tfptr = (0xbfcdd90a - *tfptr)>>1; /* estimate of 1/sqrt(y) */
x = tempf;
z = y*btScalar(0.5); /* hoist out the “/2” */
x = (btScalar(1.5)*x)-(x*x)*(x*z); /* iteration formula */
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
x = (btScalar(1.5)*x)-(x*x)*(x*z);
return x*y;
#else
return sqrtf(y);
#endif
}
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabsf(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x) {
btAssert(x <= btScalar(1.));
if (x<btScalar(-1))
x=btScalar(-1);
if (x>btScalar(1))
x=btScalar(1);
return acosf(x);
}
SIMD_FORCE_INLINE btScalar btAsin(btScalar x) {
if (x<btScalar(-1))
x=btScalar(-1);
if (x>btScalar(1))
x=btScalar(1);
return asinf(x);
}
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return expf(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return logf(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return powf(x,y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmodf(x,y); }
#endif
#define SIMD_2_PI btScalar(6.283185307179586232)
#define SIMD_PI (SIMD_2_PI * btScalar(0.5))
#define SIMD_HALF_PI (SIMD_2_PI * btScalar(0.25))
#define SIMD_RADS_PER_DEG (SIMD_2_PI / btScalar(360.0))
#define SIMD_DEGS_PER_RAD (btScalar(360.0) / SIMD_2_PI)
#define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
#define btRecipSqrt(x) ((btScalar)(btScalar(1.0)/btSqrt(btScalar(x)))) /* reciprocal square root */
#ifdef BT_USE_DOUBLE_PRECISION
#define SIMD_EPSILON DBL_EPSILON
#define SIMD_INFINITY DBL_MAX
#else
#define SIMD_EPSILON FLT_EPSILON
#define SIMD_INFINITY FLT_MAX
#endif
SIMD_FORCE_INLINE btScalar btAtan2Fast(btScalar y, btScalar x)
{
btScalar coeff_1 = SIMD_PI / 4.0f;
btScalar coeff_2 = 3.0f * coeff_1;
btScalar abs_y = btFabs(y);
btScalar angle;
if (x >= 0.0f) {
btScalar r = (x - abs_y) / (x + abs_y);
angle = coeff_1 - coeff_1 * r;
} else {
btScalar r = (x + abs_y) / (abs_y - x);
angle = coeff_2 - coeff_1 * r;
}
return (y < 0.0f) ? -angle : angle;
}
SIMD_FORCE_INLINE bool btFuzzyZero(btScalar x) { return btFabs(x) < SIMD_EPSILON; }
SIMD_FORCE_INLINE bool btEqual(btScalar a, btScalar eps) {
return (((a) <= eps) && !((a) < -eps));
}
SIMD_FORCE_INLINE bool btGreaterEqual (btScalar a, btScalar eps) {
return (!((a) <= eps));
}
SIMD_FORCE_INLINE int btIsNegative(btScalar x) {
return x < btScalar(0.0) ? 1 : 0;
}
SIMD_FORCE_INLINE btScalar btRadians(btScalar x) { return x * SIMD_RADS_PER_DEG; }
SIMD_FORCE_INLINE btScalar btDegrees(btScalar x) { return x * SIMD_DEGS_PER_RAD; }
#define BT_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name
#ifndef btFsel
SIMD_FORCE_INLINE btScalar btFsel(btScalar a, btScalar b, btScalar c)
{
return a >= 0 ? b : c;
}
#endif
#define btFsels(a,b,c) (btScalar)btFsel(a,b,c)
SIMD_FORCE_INLINE bool btMachineIsLittleEndian()
{
long int i = 1;
const char *p = (const char *) &i;
if (p[0] == 1) // Lowest address contains the least significant byte
return true;
else
return false;
}
///btSelect avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360
///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html
SIMD_FORCE_INLINE unsigned btSelect(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero)
{
// Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero
// Rely on positive value or'ed with its negative having sign bit on
// and zero value or'ed with its negative (which is still zero) having sign bit off
// Use arithmetic shift right, shifting the sign bit through all 32 bits
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE int btSelect(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero)
{
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return static_cast<int>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE float btSelect(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero)
{
#ifdef BT_HAVE_NATIVE_FSEL
return (float)btFsel((btScalar)condition - btScalar(1.0f), valueIfConditionNonZero, valueIfConditionZero);
#else
return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero;
#endif
}
template<typename T> SIMD_FORCE_INLINE void btSwap(T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
//PCK: endian swapping functions
SIMD_FORCE_INLINE unsigned btSwapEndian(unsigned val)
{
return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24));
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(unsigned short val)
{
return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8));
}
SIMD_FORCE_INLINE unsigned btSwapEndian(int val)
{
return btSwapEndian((unsigned)val);
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(short val)
{
return btSwapEndian((unsigned short) val);
}
///btSwapFloat uses using char pointers to swap the endianness
////btSwapFloat/btSwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values
///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754.
///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception.
///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you.
///so instead of returning a float/double, we return integer/long long integer
SIMD_FORCE_INLINE unsigned int btSwapEndianFloat(float d)
{
unsigned int a = 0;
unsigned char *dst = (unsigned char *)&a;
unsigned char *src = (unsigned char *)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return a;
}
// unswap using char pointers
SIMD_FORCE_INLINE float btUnswapEndianFloat(unsigned int a)
{
float d = 0.0f;
unsigned char *src = (unsigned char *)&a;
unsigned char *dst = (unsigned char *)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return d;
}
// swap using char pointers
SIMD_FORCE_INLINE void btSwapEndianDouble(double d, unsigned char* dst)
{
unsigned char *src = (unsigned char *)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
// unswap using char pointers
SIMD_FORCE_INLINE double btUnswapEndianDouble(const unsigned char *src)
{
double d = 0.0;
unsigned char *dst = (unsigned char *)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
return d;
}
// returns normalized value in range [-SIMD_PI, SIMD_PI]
SIMD_FORCE_INLINE btScalar btNormalizeAngle(btScalar angleInRadians)
{
angleInRadians = btFmod(angleInRadians, SIMD_2_PI);
if(angleInRadians < -SIMD_PI)
{
return angleInRadians + SIMD_2_PI;
}
else if(angleInRadians > SIMD_PI)
{
return angleInRadians - SIMD_2_PI;
}
else
{
return angleInRadians;
}
}
///rudimentary class to provide type info
struct btTypedObject
{
btTypedObject(int objectType)
:m_objectType(objectType)
{
}
int m_objectType;
inline int getObjectType() const
{
return m_objectType;
}
};
#endif //SIMD___SCALAR_H
| [
"janfietz@localhost"
] | [
[
[
1,
505
]
]
] |
913dc1e1590eac70a62372a13d3654908231e225 | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/scintilla/scintillawrappers/ScintillaDocView.cpp | d366c1e4c393b5700126643eec13b820fcaa68ca | [] | no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,014 | cpp | /*
Module : ScintillaDocView.CPP
Purpose: Defines the implementation for MFC CView and CDocument derived wrapper classes for the Scintilla
edit control (www.scintilla.org).
Created: PJN / 19-03-2004
History: PJN / 12-08-2004 1. Made all the remaining non virtual functions related to Find and Replace virtual.
2. TextNotFound function is now passed the parameters used for the search. Thanks
to Dmitry Naumov for this update.
3. Removed the OnTextNotFound function as all the work for it is achieved using the
TextNotFound function.
4. Creation of the find / replace dialog now takes place in a new virtual function
"CreateFindReplaceDialog". Again thanks to Dmitry Naumov for this update.
PJN / 04-03-2005 1. Fix in CScintillaView::PrintPage which now sorts out the issue of print preview
not working in the MFC doc / view wrappers for scintilla. Thanks to Frank Kiesel
for reporting this fix.
PJN / 10-07-2005 1. Addition of a virtual function namely OnAutoCSelection which handles the
SCN_AUTOCSELECTION notification message which was introduced in Scintilla v1.63.
Thanks to Dan Petitt for suggesting this update.
2. A new boolean variable called "m_bUseROFileAttributeDuringLoading" has been added
to CScintillaView. If this value is set then the code will check the read only file
attribute of the file being loaded and if it is set, then the document is marked as
read only by Scintilla. By doing this any attempts to modify the document will cause
the OnModifyAttemptRO virtual function to be called. This allows you to prompt to
make the file read write or to check out the file from a version control system.
Thanks to Dan Petitt for suggesting this update.
3. Demo app now demonstrates how to use the SCN_MODIFYATTEMPTRO notification.
4. Fixed a number of warnings when the code is compiled using Visual Studio .NET 2003.
5. SetSavePoint and SetReadOnly calls are now made in CScintillaDoc::OnSaveDocument
instead of CScintillaView::Serialize. This ensures that the control is only reset
upon a successful save.
PJN / 03-01-2006 1. Fixed a bug where the separator line in the header was not being drawn due to
issues in the code which calculates the coordinates.
2. Added two member variables which decide whether printer headers and footers should
be printed (CScintillaView::m_bPrintHeader and CScintillaView::m_bPrintFooter). You
could of course achieve the same result by deriving a class from CScintillaView and
implementing empty PrintHeader and PrinterFooter methods!!!. Thanks to Jason Elliott
for suggesting this update.
3. Optimized the construction of member variables in CScintillaView::CScintillaView
and in CScintillaFindReplaceDlg::CScintillaFindReplaceDlg
4. CScintillaView::OnReplaceAll sets the selection to 0,0 before doing text replacement.
This ensures that all text in a document is replaced. Also this function now does not
bother calling TextNotFound at the end of the function if replacements took place.
Thanks to Jason Elliott for this nice update.
5. A parameter which indicates whether text is being replaced or found is now sent to
CScintillaView::TextNotFound.
PJN / 06-01-2006 1. Removed some unnecessary code from CScintillaView::OnEndPrinting. Thanks to
Greg Smith for spotting this issue.
PJN / 08-01-2006 1. Find / Replace dialog and associated state is now maintained outside of CScintillaView.
This means that if you have multiple CScintillaView's in your app, that they share the
one find / replace dialog which is the standard type of UI you would normally expect for
this. Thanks to Greg Smith for reporting this issue.
2. Find / replace dialog is now closed when the last CScintillaView is destroyed. Thanks
to Greg Smith for reporting this issue.
PJN / 16-01-2006 1. Removed an unused "rSetup" variable in CScintillaView::PrintPage
2. Optimized code in CScintillaView::PrintPage and CScintillaView::OnFilePageSetup which
determines if metric or imperial measurements are being used. Now a boolean member variable
of CScintillaView called m_bUsingMetric which by default picks up the control panel
preference is provided. This allows client code to change this value to customize how
measurements are specified. Thanks to Greg Smith for reporting this issue.
3. Fixed a small typo in CScintillaView::PrintHeader and PrintFooter. Also explicitly uses
the TA_TOP flag in combination with TA_LEFT when setting alignment settings for header
and footer text. Again thanks to Greg Smith for reporting this.
4. Scintilla find / replace state is now stored in a standard global variable instead of
using the CProcessLocal template which it was using previously. This is no longer required
since it was used to provide Win32s support for MFC on older versions of MFC. Since Win32s
is no longer supported by MFC, there is no need to use this mechanism any more.
PJN / 02-02-2006 1. Minor update to CScintillaView to allow deletion of text when there is nothing selected.
Thanks to Alexander Kirillov for reporting this bug.
PJN / 14-03-2006 1. Updated the internal function CScintillaView::SameAsSelected to support regular
expressions. Thanks to Greg Smith for this update.
PJN / 22-05-2006 1. Fixed a flicker issue when the view is resized. Thanks to Michael Gunlock for reporting
this issue.
PJN / 29-06-2005 1. Code now uses new C++ style casts rather than old style C casts where necessary.
2. Code now supports persisting margin settings. Thanks to Krasimir Stoychev for this update
3. Updated the code to clean compile in VC 2005
PJN / 17-09-2006 1. Updated OnReplaceSel and OnReplaceAll implementations to use TargetFromSelection and
ReplaceTargetRE/ReplaceTarget. Thanks to Matt Spear for reporting this issue.
PJN / 11-06-2007 1. Addition of a SCINTILLADOCVIEW_EXT_CLASS preprocessor macro to allow the classes to be
more easily used in an extension DLL.
PJN / 19-03-2008 1. Fixed a copy and paste bug in CScintillaView::PrintPage where the incorrect margin value
was being used in the calculation of "rfPrint.rc.left". Thanks to Steve Arnold for reporting
this bug.
Copyright (c) 2004 - 2008 by PJ Naughter (Web: www.naughter.com, Email: [email protected])
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
///////////////////////////////// Includes //////////////////////////////////
#include "stdafx.h"
#include "ScintillaDocView.h"
#ifndef __AFXDISP_H__
#pragma message("To avoid this message, please put afxdisp.h in your pre compiled header (normally stdafx.h)")
#include <afxdisp.h>
#endif
#include "resource.h"
//////////////////////////////// Statics / Macros /////////////////////////////
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
////////////////////////////////// Implementation /////////////////////////////
class _SCINTILLA_EDIT_STATE
{
public:
//Constructors / Destructors
_SCINTILLA_EDIT_STATE();
//Member variables
CScintillaFindReplaceDlg* pFindReplaceDlg; //find or replace dialog
BOOL bFindOnly; //Is pFindReplace the find or replace?
CString strFind; //last find string
CString strReplace; //last replace string
BOOL bCase; //TRUE==case sensitive, FALSE==not
int bNext; //TRUE==search down, FALSE== search up
BOOL bWord; //TRUE==match whole word, FALSE==not
BOOL bRegularExpression; //TRUE==regular expression search, FALSE==not
};
_SCINTILLA_EDIT_STATE::_SCINTILLA_EDIT_STATE() : bRegularExpression(FALSE),
pFindReplaceDlg(NULL),
bWord(FALSE),
bFindOnly(TRUE),
bCase(FALSE),
bNext(TRUE)
{
}
_SCINTILLA_EDIT_STATE _scintillaEditState;
BEGIN_MESSAGE_MAP(CScintillaFindReplaceDlg, CFindReplaceDialog)
ON_BN_CLICKED(IDC_REGULAR_EXPRESSION, OnRegularExpression)
END_MESSAGE_MAP()
CScintillaFindReplaceDlg::CScintillaFindReplaceDlg(): m_bRegularExpression(FALSE)
{
}
BOOL CScintillaFindReplaceDlg::Create(BOOL bFindDialogOnly, LPCTSTR lpszFindWhat, LPCTSTR lpszReplaceWith, DWORD dwFlags, CWnd* pParentWnd)
{
//Tell Windows to use our dialog instead of the standard one
m_fr.hInstance = AfxGetResourceHandle();
m_fr.Flags |= FR_ENABLETEMPLATE;
if (bFindDialogOnly)
m_fr.lpTemplateName = MAKEINTRESOURCE(IDD_SCINTILLA_FINDDLGORD);
else
m_fr.lpTemplateName = MAKEINTRESOURCE(IDD_SCINTILLA_REPLACEDLGORD);
//Let the base class do its thing
return CFindReplaceDialog::Create(bFindDialogOnly, lpszFindWhat, lpszReplaceWith, dwFlags, pParentWnd);
}
BOOL CScintillaFindReplaceDlg::OnInitDialog()
{
//let the base class do its thing
BOOL bReturn = CFindReplaceDialog::OnInitDialog();
//Should we check the regular expression check box
CButton* pCtrl = static_cast<CButton*>(GetDlgItem(IDC_REGULAR_EXPRESSION));
AFXASSUME(pCtrl);
pCtrl->SetCheck(m_bRegularExpression);
return bReturn;
}
void CScintillaFindReplaceDlg::OnRegularExpression()
{
//Save the state of the Regular expression checkbox into a member variable
CButton* pCtrl = static_cast<CButton*>(GetDlgItem(IDC_REGULAR_EXPRESSION));
AFXASSUME(pCtrl);
m_bRegularExpression = (pCtrl->GetCheck() == 1);
}
IMPLEMENT_DYNCREATE(CScintillaView, CView)
const UINT _ScintillaMsgFindReplace = ::RegisterWindowMessage(FINDMSGSTRING);
BEGIN_MESSAGE_MAP(CScintillaView, CView)
ON_WM_PAINT()
ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateNeedSel)
ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateNeedPaste)
ON_UPDATE_COMMAND_UI(ID_EDIT_FIND, OnUpdateNeedText)
ON_UPDATE_COMMAND_UI(ID_EDIT_REPEAT, OnUpdateNeedFind)
ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo)
ON_COMMAND(ID_EDIT_CUT, OnEditCut)
ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
ON_COMMAND(ID_EDIT_CLEAR, OnEditClear)
ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
ON_COMMAND(ID_EDIT_REDO, OnEditRedo)
ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll)
ON_COMMAND(ID_EDIT_FIND, OnEditFind)
ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace)
ON_COMMAND(ID_EDIT_REPEAT, OnEditRepeat)
ON_WM_SETFOCUS()
ON_WM_SIZE()
ON_WM_ERASEBKGND()
ON_WM_CREATE()
ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateNeedSel)
ON_UPDATE_COMMAND_UI(ID_EDIT_CLEAR, OnUpdateNeedTextAndFollowingText)
ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateNeedText)
ON_UPDATE_COMMAND_UI(ID_EDIT_REPLACE, OnUpdateNeedText)
ON_COMMAND(ID_FILE_PAGE_SETUP, OnFilePageSetup)
ON_WM_DESTROY()
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
ON_REGISTERED_MESSAGE(_ScintillaMsgFindReplace, OnFindReplaceCmd)
END_MESSAGE_MAP()
CScintillaView::CScintillaView() : m_rMargin(0, 0, 0, 0),
m_bFirstSearch(TRUE),
m_bUseROFileAttributeDuringLoading(TRUE),
m_bPrintHeader(TRUE),
m_bPrintFooter(TRUE),
m_bPersistMarginSettings(TRUE),
m_bUsingMetric(UserWantsMetric())
{
}
CScintillaCtrl& CScintillaView::GetCtrl()
{
CScintillaCtrl& ctrl = m_Edit;
return ctrl;
}
void CScintillaView::LoadMarginSettings(const CString& sSection)
{
//Get the margin values
CWinApp* pApp = AfxGetApp();
AFXASSUME(pApp);
m_rMargin.left = pApp->GetProfileInt(sSection, _T("LeftMargin"), m_rMargin.left);
m_rMargin.right = pApp->GetProfileInt(sSection, _T("RightMargin"), m_rMargin.right);
m_rMargin.top = pApp->GetProfileInt(sSection, _T("TopMargin"), m_rMargin.top);
m_rMargin.bottom = pApp->GetProfileInt(sSection, _T("BottomMargin"), m_rMargin.bottom);
}
void CScintillaView::SaveMarginSettings(const CString& sSection)
{
//Write out the margin values
CWinApp* pApp = AfxGetApp();
AFXASSUME(pApp);
pApp->WriteProfileInt(sSection, _T("LeftMargin"), m_rMargin.left);
pApp->WriteProfileInt(sSection, _T("RightMargin"), m_rMargin.right);
pApp->WriteProfileInt(sSection, _T("TopMargin"), m_rMargin.top);
pApp->WriteProfileInt(sSection, _T("BottomMargin"), m_rMargin.bottom);
}
void CScintillaView::OnDestroy()
{
//Close Find/Replace dialog if this is the last CScintillaView
if (_scintillaEditState.pFindReplaceDlg)
{
CWinApp* pApp = AfxGetApp();
//Count up the number of CScintillaView's we have (excluding this one)
int nScintillaViews = 0;
//no doc manager - no templates
if (pApp->m_pDocManager)
{
//walk all templates
CDocTemplate* pTemplate;
POSITION pos = pApp->m_pDocManager->GetFirstDocTemplatePosition();
while (pos && (nScintillaViews == 0))
{
pTemplate = pApp->m_pDocManager->GetNextDocTemplate(pos);
AFXASSUME(pTemplate);
//walk all documents in the template
POSITION pos2 = pTemplate->GetFirstDocPosition();
while (pos2 && (nScintillaViews == 0))
{
CDocument* pDoc = pTemplate->GetNextDoc(pos2);
ASSERT(pDoc);
//walk all views in the document
POSITION pos3 = pDoc->GetFirstViewPosition();
while (pos3 && (nScintillaViews == 0))
{
CView* pView = pDoc->GetNextView(pos3);
ASSERT(pView);
//if we find another CScintillaView, skip code that closes find dialog
if (pView->IsKindOf(RUNTIME_CLASS(CScintillaView)) && (pView != this) && ::IsWindow(pView->GetSafeHwnd()))
++nScintillaViews;
}
}
}
}
//Close down the find/replace dialog if we are the last CScintillaView
if (nScintillaViews == 0)
{
if (::IsWindow(_scintillaEditState.pFindReplaceDlg->m_hWnd))
_scintillaEditState.pFindReplaceDlg->SendMessage(WM_CLOSE);
_scintillaEditState.pFindReplaceDlg = NULL;
}
}
//Let the base class do its thing
CView::OnDestroy();
}
void CScintillaView::DeleteContents()
{
ASSERT_VALID(this);
ASSERT(m_hWnd != NULL);
CScintillaCtrl& rCtrl = GetCtrl();
rCtrl.ClearAll();
rCtrl.EmptyUndoBuffer();
}
void CScintillaView::OnDraw(CDC*)
{
ASSERT(FALSE);
}
void CScintillaView::OnPaint()
{
//this is done to avoid CView::OnPaint
Default();
}
BOOL CScintillaView::OnPreparePrinting(CPrintInfo* pInfo)
{
//Determine if we should allow selection printing
CScintillaCtrl& rCtrl = GetCtrl();
long nStartChar = rCtrl.GetSelectionStart();
long nEndChar = rCtrl.GetSelectionEnd();
if (nStartChar != nEndChar)
{
// Enable the Selection button
pInfo->m_pPD->m_pd.Flags &= ~PD_NOSELECTION;
// Check the Selection button
pInfo->m_pPD->m_pd.Flags |= PD_SELECTION;
}
//Let the base class do its thing
return DoPreparePrinting(pInfo);
}
void CScintillaView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* pInfo)
{
//Validate our parameters
ASSERT_VALID(this);
CScintillaCtrl& rCtrl = GetCtrl();
//initialize page start vector
ASSERT(m_aPageStart.GetSize() == 0);
if (pInfo->m_pPD->PrintSelection())
m_aPageStart.Add(rCtrl.GetSelectionStart());
else
m_aPageStart.Add(0);
ASSERT(m_aPageStart.GetSize() > 0);
ASSERT_VALID(this);
}
BOOL CScintillaView::PaginateTo(CDC* pDC, CPrintInfo* pInfo)
{
//Validate our parameters
ASSERT_VALID(this);
ASSERT_VALID(pDC);
CRect rectSave = pInfo->m_rectDraw;
UINT nPageSave = pInfo->m_nCurPage;
ASSERT(nPageSave > 1);
ASSERT(nPageSave >= static_cast<UINT>(m_aPageStart.GetSize()));
VERIFY(pDC->SaveDC() != 0);
pDC->IntersectClipRect(0, 0, 0, 0);
pInfo->m_nCurPage = m_aPageStart.GetSize();
while (pInfo->m_nCurPage < nPageSave)
{
ASSERT(pInfo->m_nCurPage == static_cast<UINT>(m_aPageStart.GetSize()));
OnPrepareDC(pDC, pInfo);
ASSERT(pInfo->m_bContinuePrinting);
pInfo->m_rectDraw.SetRect(0, 0, pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES));
OnPrint(pDC, pInfo);
if (pInfo->m_nCurPage == static_cast<UINT>(m_aPageStart.GetSize()))
break;
++pInfo->m_nCurPage;
}
BOOL bResult = pInfo->m_nCurPage == nPageSave;
pDC->RestoreDC(-1);
pInfo->m_nCurPage = nPageSave;
pInfo->m_rectDraw = rectSave;
ASSERT_VALID(this);
return bResult;
}
void CScintillaView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
{
//Validate our parameters
ASSERT_VALID(this);
ASSERT_VALID(pDC);
AFXASSUME(pInfo != NULL);
if (pInfo->m_nCurPage <= pInfo->GetMaxPage())
{
if ((pInfo->m_nCurPage > static_cast<UINT>(m_aPageStart.GetSize())) && !PaginateTo(pDC, pInfo))
{
//can't paginate to that page, thus cannot print it.
pInfo->m_bContinuePrinting = FALSE;
}
ASSERT_VALID(this);
}
else
{
//Reached the max page to print
pInfo->m_bContinuePrinting = FALSE;
}
}
void CScintillaView::PrintHeader(CDC* pDC, CPrintInfo* /*pInfo*/, RangeToFormat& frPrint)
{
//By Default we print "Document Name - Printed on Date" as well as a line separator below the text
//Derived classes are of course free to implement their own version of PrintHeader
CString sHeader;
AfxFormatString2(sHeader, IDS_SCINTILLA_DEFAULT_PRINT_HEADER, GetDocument()->GetTitle(), COleDateTime::GetCurrentTime().Format());
//Setup the DC
pDC->SetTextColor(RGB(0, 0, 0));
UINT nAlign = pDC->SetTextAlign(TA_LEFT | TA_TOP);
//Draw the header
CSize sizeText = pDC->GetTextExtent(sHeader);
int nHeaderDepth = 2*sizeText.cy;
CRect rLine(frPrint.rcPage.left, frPrint.rcPage.top, frPrint.rcPage.right, frPrint.rcPage.top + nHeaderDepth);
pDC->ExtTextOut(frPrint.rcPage.left, frPrint.rcPage.top + nHeaderDepth/3, 0, &rLine, sHeader, NULL);
//Draw a line underneath the text
pDC->MoveTo(frPrint.rcPage.left, frPrint.rcPage.top + nHeaderDepth - 5);
pDC->LineTo(frPrint.rcPage.right, frPrint.rcPage.top + nHeaderDepth - 5);
//Restore the DC
pDC->SetTextAlign(nAlign);
//Adjust the place where scintilla will draw the text
if (frPrint.rc.top < (frPrint.rcPage.top + nHeaderDepth))
frPrint.rc.top = frPrint.rcPage.top + nHeaderDepth;
}
void CScintillaView::PrintFooter(CDC* pDC, CPrintInfo* pInfo, RangeToFormat& frPrint)
{
//By Default we print "Page X" as well as a line separator above the text
//Derived classes are of course free to implement their own version of PrintFooter
CString sPage;
sPage.Format(_T("%d"), pInfo->m_nCurPage);
CString sFooter;
AfxFormatString1(sFooter, IDS_SCINTILLA_DEFAULT_PRINT_FOOTER, sPage);
//Setup the DC
pDC->SetTextColor(RGB(0, 0, 0));
UINT nAlign = pDC->SetTextAlign(TA_LEFT | TA_TOP);
//Draw the header
CSize sizeText = pDC->GetTextExtent(sFooter);
int nFooterDepth = 2*sizeText.cy;
CRect rLine(frPrint.rcPage.left, frPrint.rcPage.bottom - nFooterDepth, frPrint.rcPage.right, frPrint.rcPage.bottom);
pDC->ExtTextOut(frPrint.rcPage.left, frPrint.rcPage.bottom - nFooterDepth*2/3, 0, &rLine, sFooter, NULL);
//Draw a line above the text
pDC->MoveTo(frPrint.rcPage.left, frPrint.rcPage.bottom - nFooterDepth + 5);
pDC->LineTo(frPrint.rcPage.right, frPrint.rcPage.bottom - nFooterDepth + 5);
//Restore the DC
pDC->SetTextAlign(nAlign);
//Adjust the place where scintilla will draw the text
if (frPrint.rc.bottom > (frPrint.rcPage.bottom - nFooterDepth))
frPrint.rc.bottom = frPrint.rcPage.bottom - nFooterDepth;
}
BOOL CScintillaView::UserWantsMetric()
{
TCHAR localeInfo[3];
localeInfo[0] = _T('\0');
GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);
return (localeInfo[0] == _T('0')) ;
}
long CScintillaView::PrintPage(CDC* pDC, CPrintInfo* pInfo, long nIndexStart, long nIndexStop)
{
//Validate our parameters
ASSERT_VALID(this);
ASSERT_VALID(pDC);
RangeToFormat rfPrint;
rfPrint.hdc = pDC->m_hDC;
rfPrint.hdcTarget = pDC->m_hAttribDC;
//Take into account the specified margins
CRect rMargins;
if ((m_rMargin.left) != 0 || (m_rMargin.right) != 0 || (m_rMargin.top) != 0 || (m_rMargin.bottom != 0))
{
//Get printer resolution
CPoint pDpi;
pDpi.x = pDC->GetDeviceCaps(LOGPIXELSX); //DPI in X direction
pDpi.y = pDC->GetDeviceCaps(LOGPIXELSY); //DPI in Y direction
//Convert the hundredths of millimeters or thousandths of inches margin values
//from the Page Setup dialog to device units.
int iScale = m_bUsingMetric ? 2540 : 1000; //scale factor for margin scaling;
rMargins.left = MulDiv(m_rMargin.left, pDpi.x, iScale);
rMargins.top = MulDiv(m_rMargin.top, pDpi.y, iScale);
rMargins.right = MulDiv(m_rMargin.right, pDpi.x, iScale);
rMargins.bottom = MulDiv(m_rMargin.bottom, pDpi.y, iScale);
}
else
rMargins = m_rMargin;
//We take the page size from the pInfo member variable (decrement the right and
//bottom values by 1 to suit Scintilla)
rfPrint.rcPage.left = pInfo->m_rectDraw.left;
rfPrint.rcPage.top = pInfo->m_rectDraw.top;
rfPrint.rcPage.right = pInfo->m_rectDraw.right - 1;
rfPrint.rcPage.bottom = pInfo->m_rectDraw.bottom - 1;
//Fill in the area to print
rfPrint.rc.left = rfPrint.rcPage.left + rMargins.left;
rfPrint.rc.top = rfPrint.rcPage.top + rMargins.top;
rfPrint.rc.right = rfPrint.rcPage.right - rMargins.right;
rfPrint.rc.bottom = rfPrint.rcPage.bottom - rMargins.bottom;
//Fill in the text to print
rfPrint.chrg.cpMin = nIndexStart;
rfPrint.chrg.cpMax = nIndexStop;
//Print the header (if requested to)
if (m_bPrintHeader)
PrintHeader(pDC, pInfo, rfPrint);
//Print the footer (if requested to)
if (m_bPrintFooter)
PrintFooter(pDC, pInfo, rfPrint);
//Finally ask the control to print the text
return GetCtrl().FormatRange(TRUE, &rfPrint);
}
void CScintillaView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
//Validate our parameters
ASSERT_VALID(this);
ASSERT_VALID(pDC);
AFXASSUME(pInfo != NULL);
ASSERT(pInfo->m_bContinuePrinting);
UINT nPage = pInfo->m_nCurPage;
ASSERT(nPage <= (UINT) m_aPageStart.GetSize());
int nIndex = m_aPageStart[nPage-1];
//Determine where we should end the printing
int nEndPrint = 0;
if (pInfo->m_pPD->PrintSelection())
nEndPrint = GetCtrl().GetSelectionEnd();
else
nEndPrint = GetCtrl().GetTextLength();
//print as much as possible in the current page.
nIndex = PrintPage(pDC, pInfo, nIndex, nEndPrint);
if (nIndex >= nEndPrint)
{
TRACE0("End of Document\n");
pInfo->SetMaxPage(nPage);
}
//update pagination information for page just printed
if (nPage == (UINT) m_aPageStart.GetSize())
{
if (nIndex < nEndPrint)
m_aPageStart.Add(nIndex);
}
else
{
ASSERT(nPage+1 <= static_cast<UINT>(m_aPageStart.GetSize()));
ASSERT(nIndex == m_aPageStart[nPage+1-1]);
}
}
void CScintillaView::OnEndPrinting(CDC*, CPrintInfo*)
{
//Validate our parameters
ASSERT_VALID(this);
m_aPageStart.RemoveAll();
}
void CScintillaView::OnUpdateNeedPaste(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
pCmdUI->Enable(GetCtrl().CanPaste());
}
void CScintillaView::OnUpdateNeedText(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
pCmdUI->Enable(GetCtrl().GetTextLength() != 0);
}
void CScintillaView::OnUpdateNeedTextAndFollowingText(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
CScintillaCtrl& rCtrl = GetCtrl();
int nLength = rCtrl.GetTextLength();
long nStartChar = rCtrl.GetSelectionStart();
pCmdUI->Enable(nLength && (nStartChar != nLength));
}
void CScintillaView::OnUpdateNeedFind(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
pCmdUI->Enable(GetCtrl().GetLength() != 0 && !_scintillaEditState.strFind.IsEmpty());
}
void CScintillaView::OnUpdateEditUndo(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
pCmdUI->Enable(GetCtrl().CanUndo());
}
void CScintillaView::OnUpdateEditRedo(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
pCmdUI->Enable(GetCtrl().CanRedo());
}
void CScintillaView::OnUpdateNeedSel(CCmdUI* pCmdUI)
{
//Validate our parameters
ASSERT_VALID(this);
CScintillaCtrl& rCtrl = GetCtrl();
long nStartChar = rCtrl.GetSelectionStart();
long nEndChar = rCtrl.GetSelectionEnd();
pCmdUI->Enable(nStartChar != nEndChar);
}
void CScintillaView::OnEditCut()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Cut();
}
void CScintillaView::OnEditCopy()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Copy();
}
void CScintillaView::OnEditPaste()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Paste();
}
void CScintillaView::OnEditClear()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Clear();
}
void CScintillaView::OnEditUndo()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Undo();
}
void CScintillaView::OnEditRedo()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().Redo();
}
void CScintillaView::OnEditSelectAll()
{
//Validate our parameters
ASSERT_VALID(this);
GetCtrl().SelectAll();
}
void CScintillaView::OnEditFind()
{
//Validate our parameters
ASSERT_VALID(this);
OnEditFindReplace(TRUE);
}
void CScintillaView::OnEditReplace()
{
//Validate our parameters
ASSERT_VALID(this);
OnEditFindReplace(FALSE);
}
void CScintillaView::OnEditRepeat()
{
//Validate our parameters
ASSERT_VALID(this);
if (!FindText(_scintillaEditState.strFind, _scintillaEditState.bNext, _scintillaEditState.bCase, _scintillaEditState.bWord, _scintillaEditState.bRegularExpression))
TextNotFound(_scintillaEditState.strFind, _scintillaEditState.bNext, _scintillaEditState.bCase, _scintillaEditState.bWord, _scintillaEditState.bRegularExpression, FALSE);
}
void CScintillaView::AdjustFindDialogPosition()
{
//Validate our parameters
AFXASSUME(_scintillaEditState.pFindReplaceDlg);
CScintillaCtrl& rCtrl = GetCtrl();
int nStart = rCtrl.GetSelectionStart();
CPoint point;
point.x = rCtrl.PointXFromPosition(nStart);
point.y = rCtrl.PointYFromPosition(nStart);
ClientToScreen(&point);
CRect rectDlg;
_scintillaEditState.pFindReplaceDlg->GetWindowRect(&rectDlg);
if (rectDlg.PtInRect(point))
{
if (point.y > rectDlg.Height())
rectDlg.OffsetRect(0, point.y - rectDlg.bottom - 20);
else
{
int nVertExt = GetSystemMetrics(SM_CYSCREEN);
if (point.y + rectDlg.Height() < nVertExt)
rectDlg.OffsetRect(0, 40 + point.y - rectDlg.top);
}
_scintillaEditState.pFindReplaceDlg->MoveWindow(&rectDlg);
}
}
CScintillaFindReplaceDlg* CScintillaView::CreateFindReplaceDialog()
{
return new CScintillaFindReplaceDlg;
}
void CScintillaView::OnEditFindReplace(BOOL bFindOnly)
{
//Validate our parameters
ASSERT_VALID(this);
m_bFirstSearch = TRUE;
if (_scintillaEditState.pFindReplaceDlg != NULL)
{
if (_scintillaEditState.bFindOnly == bFindOnly)
{
_scintillaEditState.pFindReplaceDlg->SetActiveWindow();
_scintillaEditState.pFindReplaceDlg->ShowWindow(SW_SHOW);
return;
}
else
{
ASSERT(_scintillaEditState.bFindOnly != bFindOnly);
_scintillaEditState.pFindReplaceDlg->SendMessage(WM_CLOSE);
ASSERT(_scintillaEditState.pFindReplaceDlg == NULL);
ASSERT_VALID(this);
}
}
CScintillaCtrl& rCtrl = GetCtrl();
CString strFind(rCtrl.GetSelText());
//if selection is empty or spans multiple lines use old find text
if (strFind.IsEmpty() || (strFind.FindOneOf(_T("\n\r")) != -1))
strFind = _scintillaEditState.strFind;
CString strReplace(_scintillaEditState.strReplace);
_scintillaEditState.pFindReplaceDlg = CreateFindReplaceDialog();
AFXASSUME(_scintillaEditState.pFindReplaceDlg != NULL);
DWORD dwFlags = NULL;
if (_scintillaEditState.bNext)
dwFlags |= FR_DOWN;
if (_scintillaEditState.bCase)
dwFlags |= FR_MATCHCASE;
if (_scintillaEditState.bWord)
dwFlags |= FR_WHOLEWORD;
if (_scintillaEditState.bRegularExpression)
_scintillaEditState.pFindReplaceDlg->SetRegularExpression(TRUE);
if (!_scintillaEditState.pFindReplaceDlg->Create(bFindOnly, strFind, strReplace, dwFlags, this))
{
_scintillaEditState.pFindReplaceDlg = NULL;
ASSERT_VALID(this);
return;
}
ASSERT(_scintillaEditState.pFindReplaceDlg != NULL);
_scintillaEditState.bFindOnly = bFindOnly;
_scintillaEditState.pFindReplaceDlg->SetActiveWindow();
_scintillaEditState.pFindReplaceDlg->ShowWindow(SW_SHOW);
ASSERT_VALID(this);
}
void CScintillaView::OnFindNext(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord, BOOL bRegularExpression)
{
//Validate our parameters
ASSERT_VALID(this);
_scintillaEditState.strFind = lpszFind;
_scintillaEditState.bCase = bCase;
_scintillaEditState.bWord = bWord;
_scintillaEditState.bNext = bNext;
_scintillaEditState.bRegularExpression = bRegularExpression;
if (!FindText(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression))
TextNotFound(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression, FALSE);
else
AdjustFindDialogPosition();
ASSERT_VALID(this);
}
void CScintillaView::OnReplaceSel(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord, BOOL bRegularExpression, LPCTSTR lpszReplace)
{
//Validate our parameters
ASSERT_VALID(this);
_scintillaEditState.strFind = lpszFind;
_scintillaEditState.strReplace = lpszReplace;
_scintillaEditState.bCase = bCase;
_scintillaEditState.bWord = bWord;
_scintillaEditState.bNext = bNext;
_scintillaEditState.bRegularExpression = bRegularExpression;
CScintillaCtrl& rCtrl = GetCtrl();
if (!SameAsSelected(_scintillaEditState.strFind, bCase, bWord, bRegularExpression))
{
if (!FindText(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression))
TextNotFound(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression, TRUE);
else
AdjustFindDialogPosition();
return;
}
if (bRegularExpression)
{
rCtrl.TargetFromSelection();
rCtrl.ReplaceTargetRE(_scintillaEditState.strReplace.GetLength(), _scintillaEditState.strReplace);
}
else
GetCtrl().ReplaceSel(_scintillaEditState.strReplace);
if (!FindText(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression))
TextNotFound(_scintillaEditState.strFind, bNext, bCase, bWord, bRegularExpression, TRUE);
else
AdjustFindDialogPosition();
ASSERT_VALID(this);
}
void CScintillaView::OnReplaceAll(LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bCase, BOOL bWord, BOOL bRegularExpression)
{
//Validate our parameters
ASSERT_VALID(this);
_scintillaEditState.strFind = lpszFind;
_scintillaEditState.strReplace = lpszReplace;
_scintillaEditState.bCase = bCase;
_scintillaEditState.bWord = bWord;
_scintillaEditState.bNext = TRUE;
_scintillaEditState.bRegularExpression = bRegularExpression;
CWaitCursor wait;
//Set the selection to the begining of the document to ensure all text is replaced in the document
CScintillaCtrl& rCtrl = GetCtrl();
rCtrl.SetSel(0, 0);
//Do the replacments
rCtrl.HideSelection(TRUE, FALSE);
BOOL bFoundSomething = FALSE;
while (FindTextSimple(_scintillaEditState.strFind, _scintillaEditState.bNext, bCase, bWord, bRegularExpression))
{
bFoundSomething = TRUE;
if (bRegularExpression)
{
rCtrl.TargetFromSelection();
rCtrl.ReplaceTargetRE(_scintillaEditState.strReplace.GetLength(), _scintillaEditState.strReplace);
}
else
rCtrl.ReplaceSel(_scintillaEditState.strReplace);
}
//Restore the old selection
rCtrl.HideSelection(FALSE, FALSE);
//Inform the user if we could not find anything
if (!bFoundSomething)
TextNotFound(_scintillaEditState.strFind, _scintillaEditState.bNext, bCase, bWord, bRegularExpression, TRUE);
ASSERT_VALID(this);
}
LRESULT CScintillaView::OnFindReplaceCmd(WPARAM /*wParam*/, LPARAM lParam)
{
//Validate our parameters
ASSERT_VALID(this);
CScintillaFindReplaceDlg* pDialog = static_cast<CScintillaFindReplaceDlg*>(CFindReplaceDialog::GetNotifier(lParam));
AFXASSUME(pDialog != NULL);
ASSERT(pDialog == _scintillaEditState.pFindReplaceDlg);
if (pDialog->IsTerminating())
_scintillaEditState.pFindReplaceDlg = NULL;
else if (pDialog->FindNext())
OnFindNext(pDialog->GetFindString(), pDialog->SearchDown(), pDialog->MatchCase(), pDialog->MatchWholeWord(), pDialog->GetRegularExpression());
else if (pDialog->ReplaceCurrent())
{
ASSERT(!_scintillaEditState.bFindOnly);
OnReplaceSel(pDialog->GetFindString(), pDialog->SearchDown(), pDialog->MatchCase(), pDialog->MatchWholeWord(), pDialog->GetRegularExpression(), pDialog->GetReplaceString());
}
else if (pDialog->ReplaceAll())
{
ASSERT(!_scintillaEditState.bFindOnly);
OnReplaceAll(pDialog->GetFindString(), pDialog->GetReplaceString(), pDialog->MatchCase(), pDialog->MatchWholeWord(), pDialog->GetRegularExpression());
}
ASSERT_VALID(this);
return 0;
}
BOOL CScintillaView::SameAsSelected(LPCTSTR lpszCompare, BOOL bCase, BOOL bWord, BOOL bRegularExpression)
{
CScintillaCtrl& rCtrl = GetCtrl();
//check length first
int nStartChar = rCtrl.GetSelectionStart(); //get the selection size
int nEndChar = rCtrl.GetSelectionEnd();
size_t nLen = lstrlen(lpszCompare); //get the #chars to search for
if (!bRegularExpression && (nLen != (size_t)(nEndChar - nStartChar))) //if not a regular expression...
return FALSE; //...sizes must match,
//Now use the advanced search functionality of scintilla to determine the result
int iFlags = bCase ? SCFIND_MATCHCASE : 0;
iFlags |= bWord ? SCFIND_WHOLEWORD : 0;
iFlags |= bRegularExpression ? SCFIND_REGEXP : 0;
rCtrl.SetSearchFlags(iFlags);
rCtrl.TargetFromSelection(); //set target
if (rCtrl.SearchInTarget(static_cast<int>(nLen), lpszCompare) < 0) //see what we got
return FALSE; //no match
//If we got a match, the target is set to the found text
return (rCtrl.GetTargetStart() == nStartChar) && (rCtrl.GetTargetEnd() == nEndChar);
}
BOOL CScintillaView::FindText(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord, BOOL bRegularExpression)
{
//Validate our parameters
ASSERT_VALID(this);
CWaitCursor wait;
return FindTextSimple(lpszFind, bNext, bCase, bWord, bRegularExpression);
}
BOOL CScintillaView::FindTextSimple(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord, BOOL bRegularExpression)
{
//Validate our parameters
ASSERT(lpszFind != NULL);
CScintillaCtrl& rCtrl = GetCtrl();
TextToFind ft;
ft.chrg.cpMin = rCtrl.GetSelectionStart();
ft.chrg.cpMax = rCtrl.GetSelectionEnd();
if (m_bFirstSearch)
m_bFirstSearch = FALSE;
#ifdef _UNICODE
CScintillaCtrl::W2UTF8(lpszFind, -1, ft.lpstrText);
#else
ft.lpstrText = T2A(const_cast<LPTSTR>(lpszFind));
#endif
if (ft.chrg.cpMin != ft.chrg.cpMax) // i.e. there is a selection
{
#ifndef _UNICODE
// If byte at beginning of selection is a DBCS lead byte,
// increment by one extra byte.
TEXTRANGE textRange;
TCHAR ch[2];
textRange.chrg.cpMin = ft.chrg.cpMin;
textRange.chrg.cpMax = ft.chrg.cpMin + 1;
textRange.lpstrText = ch;
rCtrl.SendMessage(EM_GETTEXTRANGE, 0, (LPARAM)&textRange);
if (_istlead(ch[0]))
{
ASSERT(ft.chrg.cpMax - ft.chrg.cpMin >= 2);
if (bNext)
ft.chrg.cpMin++;
else
ft.chrg.cpMax = ft.chrg.cpMin - 1;
}
#endif
if (bNext)
ft.chrg.cpMin++;
else
ft.chrg.cpMax = ft.chrg.cpMin - 1;
}
int nLength = rCtrl.GetLength();
if (bNext)
ft.chrg.cpMax = nLength;
else
ft.chrg.cpMin = 0;
DWORD dwFlags = bCase ? SCFIND_MATCHCASE : 0;
dwFlags |= bWord ? SCFIND_WHOLEWORD : 0;
dwFlags |= bRegularExpression ? SCFIND_REGEXP : 0;
if (!bNext)
{
//Swap the start and end positions which Scintilla uses to flag backward searches
int ncpMinTemp = ft.chrg.cpMin;
ft.chrg.cpMin = ft.chrg.cpMax;
ft.chrg.cpMax = ncpMinTemp;
}
//if we find the text return TRUE
BOOL bFound = (FindAndSelect(dwFlags, ft) != -1);
#ifdef _UNICODE
//Tidy up the heap memory before we return
delete [] ft.lpstrText;
#endif
return bFound;
}
long CScintillaView::FindAndSelect(DWORD dwFlags, TextToFind& ft)
{
CScintillaCtrl& rCtrl = GetCtrl();
long index = rCtrl.FindText(dwFlags, &ft);
if (index != -1) // i.e. we found something
rCtrl.SetSel(ft.chrgText.cpMin, ft.chrgText.cpMax);
return index;
}
void CScintillaView::TextNotFound(LPCTSTR /*lpszFind*/, BOOL /*bNext*/, BOOL /*bCase*/, BOOL /*bWord*/, BOOL /*bRegularExpression*/, BOOL /*bReplaced*/)
{
//Validate our parameters
ASSERT_VALID(this);
m_bFirstSearch = TRUE;
MessageBeep(MB_ICONHAND);
}
void CScintillaView::OnSetFocus(CWnd* /*pOldWnd*/)
{
//Give the focus to the child control
m_Edit.SetFocus();
}
void CScintillaView::OnSize(UINT nType, int cx, int cy)
{
//Let the base class do its thing
CView::OnSize(nType, cx, cy);
//Resize the edit control to be the size of the client area
CRect r;
GetClientRect(&r);
m_Edit.MoveWindow(&r);
}
BOOL CScintillaView::OnEraseBkgnd(CDC* /*pDC*/)
{
//We do nothing here, because the scintilla control takes up the entire
//client area of our view;
return TRUE;
}
void CScintillaView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
{
//need to set owner of Find/Replace dialog
if (_scintillaEditState.pFindReplaceDlg && pActivateView == this)
_scintillaEditState.pFindReplaceDlg->m_fr.hwndOwner = m_hWnd;
//let the base class do its thing
CView::OnActivateView(bActivate, pActivateView, pDeactiveView);
}
int CScintillaView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
//let the base class do its thing
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
//Create the scintilla edit control
CRect r;
if (!m_Edit.Create(WS_CHILD|WS_VISIBLE|WS_TABSTOP, r, this, 0))
return -1;
return 0;
}
#ifdef _DEBUG
void CScintillaView::AssertValid() const
{
//Let the base class do its thing
CView::AssertValid();
//Validate our parameters
ASSERT_VALID(&m_aPageStart);
if (_scintillaEditState.pFindReplaceDlg != NULL)
ASSERT_VALID(_scintillaEditState.pFindReplaceDlg);
}
void CScintillaView::Dump(CDumpContext& dc) const
{
//Let the base class do its thing
CView::Dump(dc);
dc << _T("\nm_aPageStart ") << &m_aPageStart;
dc << _T("\nbUseROFileAttributeDuringLoading = ") << m_bUseROFileAttributeDuringLoading;
dc << _T("\n Static Member Data:");
if (_scintillaEditState.pFindReplaceDlg != NULL)
{
dc << _T("\npFindReplaceDlg = ") << static_cast<void*>(_scintillaEditState.pFindReplaceDlg);
dc << _T("\nbFindOnly = ") << _scintillaEditState.bFindOnly;
}
dc << _T("\nstrFind = ") << _scintillaEditState.strFind;
dc << _T("\nstrReplace = ") << _scintillaEditState.strReplace;
dc << _T("\nbCase = ") << _scintillaEditState.bCase;
dc << _T("\nbWord = ") << _scintillaEditState.bWord;
dc << _T("\nbNext = ") << _scintillaEditState.bNext;
dc << _T("\nbRegularExpression = ") << _scintillaEditState.bRegularExpression;
}
#endif //_DEBUG
void CScintillaView::Serialize(CArchive& ar)
{
//Validate our parameters
ASSERT_VALID(this);
CScintillaCtrl& rCtrl = GetCtrl();
if (ar.IsLoading())
{
//Tell the control not to maintain any undo info while we stream the data
rCtrl.Cancel();
rCtrl.SetUndoCollection(FALSE);
//Read the data in from the file in blocks
CFile* pFile = ar.GetFile();
char Buffer[4096];
int nBytesRead = 0;
do
{
nBytesRead = pFile->Read(Buffer, 4096);
if (nBytesRead)
rCtrl.AddText(nBytesRead, Buffer);
}
while (nBytesRead);
//Set the read only state if required
if (m_bUseROFileAttributeDuringLoading && ((GetFileAttributes(pFile->GetFilePath()) & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY))
rCtrl.SetReadOnly(TRUE);
else
rCtrl.SetReadOnly(FALSE);
//Reinitialize the control settings
rCtrl.SetUndoCollection(TRUE);
rCtrl.EmptyUndoBuffer();
rCtrl.SetSavePoint();
rCtrl.GotoPos(0);
}
else
{
//Get the length of the document
int nDocLength = rCtrl.GetLength();
//Write the data in blocks to disk
CFile* pFile = ar.GetFile();
for (int i=0; i<nDocLength; i += 4095) //4095 because data will be returned NULL terminated
{
int nGrabSize = nDocLength - i;
if (nGrabSize > 4095)
nGrabSize = 4095;
//Get the data from the control
TextRange tr;
tr.chrg.cpMin = i;
tr.chrg.cpMax = i + nGrabSize;
char Buffer[4096];
tr.lpstrText = Buffer;
rCtrl.GetTextRange(&tr);
//Write it to disk
pFile->Write(Buffer, nGrabSize);
}
}
}
void CScintillaView::OnFilePageSetup()
{
//Display a standard page setup dialog
CPageSetupDialog dlg;
//Allow the margin settings to be tweaked
dlg.m_psd.Flags |= PSD_MARGINS;
//Are we using the metric or imperial system
if (m_bUsingMetric)
dlg.m_psd.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
else
dlg.m_psd.Flags |= PSD_INTHOUSANDTHSOFINCHES;
if (m_bPersistMarginSettings)
LoadMarginSettings();
//Set the current margin settings to the current value from m_rectMargin
dlg.m_psd.rtMargin = m_rMargin;
//get the current device from the app
PRINTDLG pd;
pd.hDevNames = NULL;
pd.hDevMode = NULL;
CWinApp* pApp = AfxGetApp();
pApp->GetPrinterDeviceDefaults(&pd);
dlg.m_psd.hDevNames = pd.hDevNames;
dlg.m_psd.hDevMode = pd.hDevMode;
if (dlg.DoModal() == IDOK)
{
//Save the new margin value in to the member variable
m_rMargin = dlg.m_psd.rtMargin;
if (m_bPersistMarginSettings)
SaveMarginSettings();
//Update the printer settings
pApp->SelectPrinter(dlg.m_psd.hDevNames, dlg.m_psd.hDevMode);
}
}
void CScintillaView::OnStyleNeeded(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnCharAdded(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnSavePointReached(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnSavePointLeft(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnModifyAttemptRO(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnDoubleClick(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnUpdateUI(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnModified(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnMacroRecord(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnMarginClick(SCNotification* pSCNotification)
{
//By default get the line where the click occured and toggle its fold state
CScintillaCtrl& rCtrl = GetCtrl();
int nLine = rCtrl.LineFromPosition(pSCNotification->position);
rCtrl.ToggleFold(nLine);
}
void CScintillaView::OnNeedShown(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnPainted(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnUserListSelection(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnDwellStart(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnDwellEnd(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnZoom(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnHotSpotClick(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnHotSpotDoubleClick(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnCallTipClick(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnAutoCSelection(SCNotification* /*pSCNotification*/)
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnChange()
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnSetFocus()
{
//By default do nothing, derived classes may want to do something
}
void CScintillaView::OnKillFocus()
{
//By default do nothing, derived classes may want to do something
}
BOOL CScintillaView::OnCommand(WPARAM wParam, LPARAM lParam)
{
HWND hWndControl = reinterpret_cast<HWND>(lParam);
if (hWndControl == GetCtrl().GetSafeHwnd())
{
WORD wNotification = HIWORD(wParam);
switch (wNotification)
{
case SCEN_CHANGE:
{
OnChange();
break;
}
case SCEN_SETFOCUS:
{
OnSetFocus();
break;
}
case SCEN_KILLFOCUS:
{
OnKillFocus();
break;
}
default:
{
break;
}
}
return TRUE;
}
//let the base class do its thing
return CView::OnCommand(wParam, lParam);
}
BOOL CScintillaView::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
NMHDR* pNMHdr = reinterpret_cast<NMHDR*>(lParam);
AFXASSUME(pNMHdr);
//Is it a notification from the embedded control
CScintillaCtrl& rCtrl = GetCtrl();
if (pNMHdr->hwndFrom == rCtrl.GetSafeHwnd())
{
SCNotification* pSCNotification = reinterpret_cast<SCNotification*>(lParam);
switch (pNMHdr->code)
{
case SCN_STYLENEEDED:
{
OnStyleNeeded(pSCNotification);
break;
}
case SCN_CHARADDED:
{
OnCharAdded(pSCNotification);
break;
}
case SCN_SAVEPOINTREACHED:
{
OnSavePointReached(pSCNotification);
break;
}
case SCN_SAVEPOINTLEFT:
{
OnSavePointLeft(pSCNotification);
break;
}
case SCN_MODIFYATTEMPTRO:
{
OnModifyAttemptRO(pSCNotification);
break;
}
case SCN_DOUBLECLICK:
{
OnDoubleClick(pSCNotification);
break;
}
case SCN_UPDATEUI:
{
OnUpdateUI(pSCNotification);
break;
}
case SCN_MODIFIED:
{
OnModified(pSCNotification);
break;
}
case SCN_MACRORECORD:
{
OnMacroRecord(pSCNotification);
break;
}
case SCN_MARGINCLICK:
{
OnMarginClick(pSCNotification);
break;
}
case SCN_NEEDSHOWN:
{
OnNeedShown(pSCNotification);
break;
}
case SCN_PAINTED:
{
OnPainted(pSCNotification);
break;
}
case SCN_USERLISTSELECTION:
{
OnUserListSelection(pSCNotification);
break;
}
case SCN_DWELLSTART:
{
OnDwellStart(pSCNotification);
break;
}
case SCN_DWELLEND:
{
OnDwellEnd(pSCNotification);
break;
}
case SCN_ZOOM:
{
OnZoom(pSCNotification);
break;
}
case SCN_HOTSPOTCLICK:
{
OnHotSpotClick(pSCNotification);
break;
}
case SCN_HOTSPOTDOUBLECLICK:
{
OnHotSpotDoubleClick(pSCNotification);
break;
}
case SCN_CALLTIPCLICK:
{
OnCallTipClick(pSCNotification);
break;
}
case SCN_AUTOCSELECTION:
{
OnAutoCSelection(pSCNotification);
break;
}
default:
{
break;
}
}
return TRUE; // we processed the message
}
else
{
//let the base class do its thing
return CView::OnNotify(wParam, lParam, pResult);
}
}
IMPLEMENT_DYNAMIC(CScintillaDoc, CDocument)
CScintillaDoc::CScintillaDoc()
{
ASSERT_VALID(this);
}
CScintillaView* CScintillaDoc::GetView() const
{
//find the first view - if there are no views
//we must return NULL
POSITION pos = GetFirstViewPosition();
if (pos == NULL)
return NULL;
//find the first view that is a CScintillaView
CView* pView;
while (pos != NULL)
{
pView = GetNextView(pos);
if (pView->IsKindOf(RUNTIME_CLASS(CScintillaView)))
return static_cast<CScintillaView*>(pView);
}
//can't find one--return NULL
return NULL;
}
void CScintillaDoc::SetModifiedFlag(BOOL bModified)
{
CScintillaView* pView = GetView();
AFXASSUME(pView);
if (bModified == FALSE)
pView->GetCtrl().SetSavePoint();
m_bModified = bModified;
}
BOOL CScintillaDoc::IsModified()
{
CScintillaView* pView = GetView();
AFXASSUME(pView);
return m_bModified || pView->GetCtrl().GetModify();
}
void CScintillaDoc::DeleteContents()
{
//let the base class do its thing
CDocument::DeleteContents();
//Ask our accompanying view to delete its contents
CWaitCursor wait;
CScintillaView* pView = GetView();
if (pView)
pView->DeleteContents();
}
void CScintillaDoc::Serialize(CArchive& ar)
{
CScintillaView* pView = GetView();
AFXASSUME(pView);
pView->Serialize(ar);
}
BOOL CScintillaDoc::OnSaveDocument(LPCTSTR lpszPathName)
{
//Let the base class do its thing
BOOL bSuccess = CDocument::OnSaveDocument(lpszPathName);
if (bSuccess)
{
CScintillaView* pView = GetView();
AFXASSUME(pView);
CScintillaCtrl& rCtrl = pView->GetCtrl();
//Tell the control that the document has now been saved
rCtrl.SetSavePoint();
rCtrl.SetReadOnly(FALSE);
}
return bSuccess;
}
#ifdef _DEBUG
void CScintillaDoc::AssertValid() const
{
//Let the base class do its thing
CDocument::AssertValid();
}
void CScintillaDoc::Dump(CDumpContext& dc) const
{
//let the base class do its thing
CDocument::Dump(dc);
}
#endif //_DEBUG
| [
"[email protected]"
] | [
[
[
1,
1669
]
]
] |
22df3c59f452fb47606fc3327b842a205bff9a0d | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/assign/test/multi_index_container.cpp | f0ec974d9a7476f60129ddba74c1265a406b5502 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,905 | cpp | // Boost.Assign library
//
// Copyright Thorsten Ottosen 2003-2004. 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)
//
// For more information, see http://www.boost.org/libs/assign/
//
#include <boost/detail/workaround.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
# pragma warn -8091 // supress warning in Boost.Test
# pragma warn -8057 // unused argument argc/argv in Boost.Test
#endif
#include <boost/assign/list_of.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <cstddef>
#include <ostream>
#include <string>
using namespace boost;
using namespace boost::multi_index;
namespace ba = boost::assign;
//
// Define a classical multi_index_container for employees
//
struct employee
{
int id;
std::string name;
int age;
employee(int id_,std::string name_,int age_):id(id_),name(name_),age(age_){}
bool operator==(const employee& x)const
{
return id==x.id&&name==x.name&&age==x.age;
}
bool operator<(const employee& x)const
{
return id<x.id;
}
bool operator!=(const employee& x)const{return !(*this==x);}
bool operator> (const employee& x)const{return x<*this;}
bool operator>=(const employee& x)const{return !(*this<x);}
bool operator<=(const employee& x)const{return !(x<*this);}
struct comp_id
{
bool operator()(int x,const employee& e2)const{return x<e2.id;}
bool operator()(const employee& e1,int x)const{return e1.id<x;}
};
friend std::ostream& operator<<(std::ostream& os,const employee& e)
{
os<<e.id<<" "<<e.name<<" "<<e.age<<std::endl;
return os;
}
};
struct name{};
struct by_name{};
struct age{};
struct as_inserted{};
typedef
multi_index_container<
employee,
indexed_by<
ordered_unique<
identity<employee> >,
ordered_non_unique<
tag<name,by_name>,
BOOST_MULTI_INDEX_MEMBER(employee,std::string,name)>,
ordered_non_unique<
tag<age>,
BOOST_MULTI_INDEX_MEMBER(employee,int,age)>,
sequenced<
tag<as_inserted> > > >
employee_set;
#if defined(BOOST_NO_MEMBER_TEMPLATES)
typedef nth_index<
employee_set,1>::type employee_set_by_name;
#else
typedef employee_set::nth_index<1>::type employee_set_by_name;
#endif
typedef boost::multi_index::index<
employee_set,age>::type employee_set_by_age;
typedef boost::multi_index::index<
employee_set,as_inserted>::type employee_set_as_inserted;
//
// Define a multi_index_container with a list-like index and an ordered index
//
typedef multi_index_container<
std::string,
indexed_by<
sequenced<>, // list-like index
ordered_non_unique<identity<std::string> > // words by alphabetical order
>
> text_container;
void test_multi_index_container()
{
employee_set eset = ba::list_of< employee >(1,"Franz",30)(2,"Hanz",40)(3,"Ilse",50);
BOOST_CHECK( eset.size() == 3u );
//
// This container is associative, hence we can use 'insert()'
//
ba::insert( eset )(4,"Kurt",55)(5,"Bjarne",77)(7,"Thorsten",24);
BOOST_CHECK( eset.size() == 6u );
employee_set_by_name& name_index = boost::multi_index::get<name>(eset);
employee_set_by_name::iterator i = name_index.find("Ilse");
BOOST_CHECK( i->id == 3 );
BOOST_CHECK( i->age == 50 );
text_container text = ba::list_of< std::string >("Have")("you")("ever")("wondered")("how")("much")("Boost")("rocks?!");
BOOST_CHECK_EQUAL( text.size(), 8u );
BOOST_CHECK_EQUAL( *text.begin(), "Have" );
//
// This container is a sequence, hence we can use 'push_back()' and 'push_font()'
//
ba::push_back( text )("Well")(",")("A")("LOT")(",")("obviously!");
BOOST_CHECK_EQUAL( text.size(), 14u );
BOOST_CHECK_EQUAL( *--text.end(), "obviously!" );
ba::push_front( text ) = "question:", "simple", "A";
BOOST_CHECK_EQUAL( text.size(), 17u );
BOOST_CHECK_EQUAL( text.front(), "A" );
}
#include <boost/test/included/unit_test_framework.hpp>
using boost::unit_test_framework::test_suite;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "List Test Suite" );
test->add( BOOST_TEST_CASE( &test_multi_index_container ) );
return test;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
170
]
]
] |
bb20e2f52da4266cd61ae5a084d8cebc7988a30b | 0d717689533512937c427d3695e7f47839f23a9b | /scbwai/BWSAL_0.9.11/BWSAL_0.9.11/Addons/BuildOrderManager.cpp | c8c6d11b1f69bfd9dc32d7c8a0045c92a406f5c7 | [
"MIT"
] | permissive | unqueued/bwmas | 1b6d506ab390339b82992563230622dbedd1a76f | 22ad91482aed041684bc2389661260e0d8d8dda5 | refs/heads/master | 2020-12-24T13:28:48.836488 | 2011-05-17T21:40:27 | 2011-05-17T21:40:27 | 35,456,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,691 | cpp | #include <BuildOrderManager.h>
#include <BuildManager.h>
#include <TechManager.h>
#include <UpgradeManager.h>
#include <WorkerManager.h>
#include <SupplyManager.h>
#include <algorithm>
#include <stdarg.h>
#include <UnitGroupManager.h>
using namespace std;
using namespace BWAPI;
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > >* globalUnitSet;
int y;
int currentPriority;
map<const BWAPI::Unit*,int> nextFreeTimeData;
map<BWAPI::UnitType, set<BWAPI::UnitType> > makes;
map<BWAPI::UnitType, set<BWAPI::TechType> > researches;
map<BWAPI::UnitType, set<BWAPI::UpgradeType> > upgrades;
BuildOrderManager* buildOrderManager;
BuildOrderManager::BuildOrderManager(BuildManager* buildManager, TechManager* techManager, UpgradeManager* upgradeManager, WorkerManager* workerManager, SupplyManager* supplyManager)
{
buildOrderManager = this;
this->buildManager = buildManager;
this->techManager = techManager;
this->upgradeManager = upgradeManager;
this->workerManager = workerManager;
this->supplyManager = supplyManager;
this->usedMinerals = 0;
this->usedGas = 0;
this->dependencyResolver = false;
this->debugMode = false;
UnitItem::getBuildManager() = buildManager;
for(set<BWAPI::UnitType>::iterator i=UnitTypes::allUnitTypes().begin();i!=UnitTypes::allUnitTypes().end();i++)
{
makes[(*i).whatBuilds().first].insert(*i);
}
for(set<BWAPI::TechType>::iterator i=TechTypes::allTechTypes().begin();i!=TechTypes::allTechTypes().end();i++)
{
researches[i->whatResearches()].insert(*i);
}
for(set<BWAPI::UpgradeType>::iterator i=UpgradeTypes::allUpgradeTypes().begin();i!=UpgradeTypes::allUpgradeTypes().end();i++)
{
upgrades[i->whatUpgrades()].insert(*i);
}
}
//returns the next frame that the given unit type will be ready to produce units or research tech or upgrades
int BuildOrderManager::nextFreeTime(const MetaUnit* unit)
{
int ctime=Broodwar->getFrameCount();
if (!unit->isCompleted() && unit->unit!=NULL)
{
if (unit->getType().getRace()==Races::Protoss && unit->getType().isBuilding() && unit->getRemainingBuildTime()>0 && nextFreeTimeData[unit->unit]<ctime+24*3)
nextFreeTimeData[unit->unit]=ctime+24*3;
if (!unit->isBeingConstructed() && !unit->getType().isAddon())
return -1;
}
int natime=ctime;
natime=max(ctime,ctime+unit->getRemainingBuildTime());
if (unit->getType().getRace()==Races::Protoss && unit->getType().isBuilding() && unit->getRemainingBuildTime()>0)
natime=max(ctime,ctime+unit->getRemainingBuildTime()+24*3);
natime=max(natime,ctime+unit->getRemainingTrainTime());
natime=max(natime,ctime+unit->getRemainingResearchTime());
natime=max(natime,ctime+unit->getRemainingUpgradeTime());
if (unit->unit!=NULL)
natime=max(natime,nextFreeTimeData[unit->unit]);
if (this->buildManager->getBuildType((Unit*)(unit->unit))!=UnitTypes::None && !unit->hasBuildUnit() && !unit->isTraining() && !unit->isMorphing())
natime=max(natime,ctime+this->buildManager->getBuildType((Unit*)(unit->unit)).buildTime());
return natime;
}
//returns the next available time that at least one unit of the given type (buildings only right now) will be completed
int BuildOrderManager::nextFreeTime(UnitType t)
{
//if one unit of the given type is already completed, return the given frame count
if (Broodwar->self()->completedUnitCount(t)>0)
return Broodwar->getFrameCount();
//if no units of the given type are being constructed, return -1
if (t!=UnitTypes::Zerg_Larva)
if (Broodwar->self()->incompleteUnitCount(t)==0)
return -1;
int time;
bool setflag=false;
for(set<MetaUnit*>::iterator i=this->MetaUnitPointers.begin();i!=this->MetaUnitPointers.end();i++)
{
if ((*i)->getType()!=t) continue;
int ntime=nextFreeTime(*i);
if (ntime>-1)
{
//set time to the earliest available time
if (!setflag || ntime<time)
{
time=ntime;
setflag=true;
}
}
}
if (t.supplyRequired()>0)
{
if (Broodwar->self()->supplyUsed()+t.supplyRequired()>Broodwar->self()->supplyTotal())
{
time=this->supplyManager->getSupplyTime(Broodwar->self()->supplyUsed()+t.supplyRequired());
}
}
if (setflag)
return time;
//we can get here if construction has been halted by an SCV
return -1;
}
//returns the next available time that the given unit will be able to train the given unit type
//takes into account required units
//todo: take into account required tech and supply
int BuildOrderManager::nextFreeTime(const MetaUnit* unit, UnitType t)
{
int time=nextFreeTime(unit);
for(map<UnitType,int>::const_iterator i=t.requiredUnits().begin();i!=t.requiredUnits().end();i++)
{
int ntime=nextFreeTime(i->first);
if (ntime==-1)
return -1;
if (ntime>time)
time=ntime;
if (i->first.isAddon() && i->first.whatBuilds().first==unit->getType() && !unit->hasAddon())
return -1;
}
return time;
}
int BuildOrderManager::nextFreeTime(const MetaUnit* unit, TechType t)
{
int time=nextFreeTime(unit);
//if something else is already researching it, this unit will never be able to research it
if (Broodwar->self()->isResearching(t))
return -1;
return time;
}
int BuildOrderManager::nextFreeTime(const MetaUnit* unit, UpgradeType t)
{
int time=nextFreeTime(unit);
if (!Broodwar->self()->isUpgrading(t))
return time;
for(std::set<MetaUnit*>::iterator i=this->MetaUnitPointers.begin();i!=this->MetaUnitPointers.end();i++)
{
if ((*i)->getType()!=t.whatUpgrades()) continue;
if ((*i)->isUpgrading() && (*i)->getUpgrade()==t)
{
time=max(time,nextFreeTime(*i));
}
}
return time;
}
bool BuildOrderManager::isResourceLimited()
{
return this->isMineralLimited && this->isGasLimited;
}
//returns the set of unit types the given unit will be able to make at the given time
set<BWAPI::UnitType> BuildOrderManager::unitsCanMake(MetaUnit* builder, int time)
{
set<BWAPI::UnitType> result;
for(set<BWAPI::UnitType>::iterator i=makes[builder->getType()].begin();i!=makes[builder->getType()].end();i++)
{
int t=nextFreeTime(builder,*i);
if (t>-1 && t<=time)
result.insert(*i);
}
return result;
}
set<BWAPI::TechType> BuildOrderManager::techsCanResearch(MetaUnit* techUnit, int time)
{
set<BWAPI::TechType> result;
for(set<BWAPI::TechType>::iterator i=researches[techUnit->getType()].begin();i!=researches[techUnit->getType()].end();i++)
{
int t=nextFreeTime(techUnit,*i);
if (t>-1 && t<=time)
result.insert(*i);
}
return result;
}
set<BWAPI::UpgradeType> BuildOrderManager::upgradesCanResearch(MetaUnit* techUnit, int time)
{
set<BWAPI::UpgradeType> result;
for(set<BWAPI::UpgradeType>::iterator i=upgrades[techUnit->getType()].begin();i!=upgrades[techUnit->getType()].end();i++)
{
int t=nextFreeTime(techUnit,*i);
if (t>-1 && t<=time)
result.insert(*i);
}
return result;
}
//prefer unit types that have larger remaining unit counts
//if we need a tie-breaker, we prefer cheaper units
bool unitTypeOrderCompare(const pair<BWAPI::UnitType, int >& a, const pair<BWAPI::UnitType, int >& b)
{
int rA=a.second;
int rB=b.second;
int pA=a.first.mineralPrice()+a.first.gasPrice();
int pB=b.first.mineralPrice()+b.first.gasPrice();
return rA>rB || (rA == rB && pA<pB);
}
UnitType getUnitType(set<UnitType>& validUnitTypes,vector<pair<BWAPI::UnitType, int > >& unitCounts)
{
UnitType answer=UnitTypes::None;
//sort unit counts in descending order of size
sort(unitCounts.begin(),unitCounts.end(),unitTypeOrderCompare);
for(vector<pair<BWAPI::UnitType, int > >::iterator i=unitCounts.begin();i!=unitCounts.end();i++)
{
//use the first valid unit type we find
if (validUnitTypes.find(i->first)!=validUnitTypes.end())
{
answer=i->first;
i->second--;
if (i->second<=0)
{
unitCounts.erase(i);
}
break;
}
}
return answer;
}
pair<TechType,UpgradeType> getTechOrUpgradeType(set<TechType>& validTechTypes, set<UpgradeType>& validUpgradeTypes, list<TechItem> &remainingTech)
{
pair<TechType,UpgradeType> answer(TechTypes::None,UpgradeTypes::None);
for(list<TechItem>::iterator i=remainingTech.begin();i!=remainingTech.end();i++)
{
//use the first valid unit type we find
TechType t=(*i).techType;
UpgradeType u=(*i).upgradeType;
if (t!=TechTypes::None)
{
if (validTechTypes.find(t)!=validTechTypes.end())
{
answer.first=t;
remainingTech.erase(i);
break;
}
}
else if (u!=UpgradeTypes::None)
{
if (validUpgradeTypes.find(u)!=validUpgradeTypes.end())
{
answer.second=u;
remainingTech.erase(i);
break;
}
}
}
return answer;
}
bool factoryCompare(const BuildOrderManager::MetaUnit* a, const BuildOrderManager::MetaUnit* b)
{
return buildOrderManager->nextFreeTime(a)>buildOrderManager->nextFreeTime(b);
}
bool BuildOrderManager::updateUnits()
{
set<MetaUnit*> allUnits = this->MetaUnitPointers;
//sanity check the data (not sure if we need to, but just in case)
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > >::iterator i2;
for(map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > >::iterator i=globalUnitSet->begin();i!=globalUnitSet->end();i=i2)
{
i2=i;
i2++;
map<BWAPI::UnitType, UnitItem* >::iterator j2;
for(map<BWAPI::UnitType, UnitItem* >::iterator j=i->second.begin();j!=i->second.end();j=j2)
{
j2=j;
j2++;
if (j->second==NULL || j->second->getRemainingCount()==0)
{
i->second.erase(j);
}
}
if (i->second.empty())
globalUnitSet->erase(i);
}
if (globalUnitSet->empty())
{
//false = not resource limited
return false;
}
//get the set of factory Units
list<MetaUnit*> factories;
for(set<MetaUnit*>::iterator i=allUnits.begin();i!=allUnits.end();i++)
{
MetaUnit* u=*i;
UnitType type=u->getType();
//only add the factory if it hasn't been reserved and if its a builder type that we need
if (globalUnitSet->find(type)!=globalUnitSet->end() && this->reservedUnits.find(u)==this->reservedUnits.end())
factories.push_back(u);
}
factories.sort(factoryCompare);
//find the sequence of interesting points in time in the future
set<int> times;
//iterate through each type of builder
for(map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > >::iterator i=globalUnitSet->begin();i!=globalUnitSet->end();i++)
{
UnitType unitType=i->first;//builder type
//iterate through all our factory Units
for(list<MetaUnit*>::iterator f=factories.begin();f!=factories.end();f++)
{
MetaUnit* u=*f;
UnitType type=u->getType();
if (type==i->first)//only look at units of this builder type
{
//iterate over all the types of units we want to make with this builder type
for(map<BWAPI::UnitType, UnitItem* >::iterator j=i->second.begin();j!=i->second.end();j++)
{
//add the time to the sequence if it is in the future (and not -1)
int time=nextFreeTime(*f,j->first);
if (time>-1)
times.insert(time);
}
}
}
}
//get the remaining unit counts for each type of unit we want to make
vector<pair<BWAPI::UnitType, int > > remainingUnitCounts;
for(map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > >::iterator i=globalUnitSet->begin();i!=globalUnitSet->end();i++)
{
for(map<BWAPI::UnitType, UnitItem* >::iterator j=i->second.begin();j!=i->second.end();j++)
{
remainingUnitCounts.push_back(make_pair(j->first,j->second->getRemainingCount(currentlyPlannedCount[j->first])));
}
}
//reserve units and resources for later
//iterate through time (this gives earlier events higher priority)
times.insert(Broodwar->getFrameCount());
for(set<int>::iterator t=times.begin();t!=times.end();t++)
{
int ctime=*t;
//remove all factories that have been reserved
list<MetaUnit*>::iterator f2;
for(list<MetaUnit*>::iterator f=factories.begin();f!=factories.end();f=f2)
{
f2=f;
f2++;
if (this->reservedUnits.find(*f)!=this->reservedUnits.end())
factories.erase(f);
}
//iterate through all factories that haven't been reserved yet
for(list<MetaUnit*>::iterator f=factories.begin();f!=factories.end();f++)
{
MetaUnit* factory=*f;
//get a unit type, taking into account the remaining unit counts and the set of units this factory can make at time ctime
UnitType t=getUnitType(unitsCanMake(*f,ctime),remainingUnitCounts);
if (t==UnitTypes::None)
continue;
int btime=ctime;
if (factory->getType().isWorker())
btime=ctime+24*4;
currentlyPlannedCount[t]++;
this->reserveResources(factory,t);
this->reservedUnits.insert(factory);
this->savedPlan.push_back(Type(t,factory,currentPriority,ctime));
if (this->isResourceLimited())
return true;
}
}
//false = not resource limited
return false;
}
void BuildOrderManager::update()
{
int time=Broodwar->getFrameCount();
if (time>=this->nextUpdateFrame)
{
updatePlan();
this->nextUpdateFrame=time+24*3;
}
y=0;
this->reservedResources.clear();
this->reservedUnits.clear();
this->isGasLimited=false;
this->isMineralLimited=false;
debug("time=%d",time);
list<Type>::iterator i2;
for(list<Type>::iterator i=this->savedPlan.begin();i!=this->savedPlan.end();i=i2)
{
i2=i;
i2++;
UnitType unit=(*i).unitType;
TechType tech=(*i).techType;
UpgradeType upgrade=(*i).upgradeType;
MetaUnit* factory=(*i).unit;
int priority=(*i).priority;
int ctime=(*i).time;
if (ctime<Broodwar->getFrameCount())
ctime=Broodwar->getFrameCount();
int btime=ctime;
if (factory->getType().isWorker())
btime=ctime+24*4;
if (unit!=UnitTypes::None)
{
if ((*i).time>=time)
debug("%s at %d",unit.getName().c_str(),(*i).time);
else
debug("%s as soon as possible",unit.getName().c_str());
if (ctime<=time && hasResources(unit,btime))
{
TilePosition tp=this->items[priority].units[factory->getType()][unit].decrementAdditional();
if (!factory->hasAddon())
this->buildManager->build(unit,tp,true);
else
this->buildManager->build(unit,tp);
nextFreeTimeData[factory->unit]=time+24*6;
if (this->debugMode) Broodwar->printf("Build %s",unit.getName().c_str());
this->spendResources(unit);
savedPlan.erase(i);
}
else
this->reserveResources(factory,unit);
}
else if (tech!=TechTypes::None)
{
if ((*i).time>=time)
debug("%s at %d",tech.getName().c_str(),(*i).time);
else
debug("%s as soon as possible",tech.getName().c_str());
if (ctime<=time && hasResources(tech,btime))
{
if (this->debugMode) Broodwar->printf("Research %s",tech.getName().c_str());
this->techManager->research(tech);
nextFreeTimeData[factory->unit]=time+24*6;
this->spendResources(tech);
savedPlan.erase(i);
}
else
this->reserveResources(factory,tech);
}
else if (upgrade!=UpgradeTypes::None)
{
if ((*i).time>=time)
debug("%s at %d",upgrade.getName().c_str(),(*i).time);
else
debug("%s as soon as possible",upgrade.getName().c_str());
if (ctime<=time && hasResources(upgrade,btime))
{
if (this->debugMode) Broodwar->printf("Upgrade %s",upgrade.getName().c_str());
this->upgradeManager->upgrade(upgrade);
nextFreeTimeData[factory->unit]=time+24*6;
this->spendResources(upgrade);
savedPlan.erase(i);
}
else
this->reserveResources(factory,upgrade);
}
}
}
void BuildOrderManager::updatePlan()
{
this->savedPlan.clear();
this->MetaUnits.clear();
this->MetaUnitPointers.clear();
for(set<Unit*>::const_iterator i=BWAPI::Broodwar->self()->getUnits().begin();i!=BWAPI::Broodwar->self()->getUnits().end();i++)
{
MetaUnits.push_back(MetaUnit(*i));
if ((*i)->getType()==UnitTypes::Zerg_Hatchery || (*i)->getType()==UnitTypes::Zerg_Lair || (*i)->getType()==UnitTypes::Zerg_Hive)
{
int larva=(*i)->getLarva().size();
if ((*i)->getRemainingTrainTime()>0)
MetaUnits.push_back(MetaUnit(Broodwar->getFrameCount()+(*i)->getRemainingTrainTime()));
for(int j=1;j<4;j++)
MetaUnits.push_back(MetaUnit(Broodwar->getFrameCount()+(*i)->getRemainingTrainTime()+334*j));
}
}
for(list<MetaUnit>::iterator i=MetaUnits.begin();i!=MetaUnits.end();i++)
{
this->MetaUnitPointers.insert(&(*i));
}
for(set<UnitType>::iterator i=UnitTypes::allUnitTypes().begin();i!=UnitTypes::allUnitTypes().end();i++)
{
currentlyPlannedCount[*i]=this->buildManager->getPlannedCount(*i);
}
map< int, PriorityLevel >::iterator l2;
for(map< int, PriorityLevel >::iterator l=items.begin();l!=items.end();l=l2)
{
l2=l;
l2++;
if (l->second.techs.empty() && l->second.units.empty())
items.erase(l);
}
if (items.empty()) return;
map< int, PriorityLevel >::iterator l=items.end();
l--;
this->reservedResources.clear();
this->reservedUnits.clear();
this->isGasLimited=false;
this->isMineralLimited=false;
y=5;
//Iterate through priority levels in decreasing order
//---------------------------------------------------------------------------------------------------------
for(;l!=items.end();l--)
{
currentPriority=l->first;
//First consider all techs and upgrades for this priority level
set<UnitType> techUnitTypes;
for(list<TechItem>::iterator i=l->second.techs.begin();i!=l->second.techs.end();i++)
{
if (i->techType!=TechTypes::None)
techUnitTypes.insert(i->techType.whatResearches());
if (i->upgradeType!=UpgradeTypes::None)
techUnitTypes.insert(i->upgradeType.whatUpgrades());
}
set<MetaUnit*> allUnits=this->MetaUnitPointers;
//get the set of tech Units
set<MetaUnit*> techUnits;
for(set<MetaUnit*>::iterator i=allUnits.begin();i!=allUnits.end();i++)
{
MetaUnit* u=*i;
UnitType type=u->getType();
//only add the factory if it hasn't been reserved and if its a builder type that we need
if (techUnitTypes.find(type)!=techUnitTypes.end() && this->reservedUnits.find(u)==this->reservedUnits.end())
techUnits.insert(u);
}
//find the sequence of interesting points in time in the future
set<int> times;
for(set<MetaUnit*>::iterator i=techUnits.begin();i!=techUnits.end();i++)
{
//add the time to the sequence if it is in the future (and not -1)
int time=nextFreeTime(*i);
if (time>-1)
times.insert(time);
}
//get the remaining tech
list<TechItem > remainingTech=l->second.techs;
if (this->dependencyResolver)
{
//check dependencies
for(list<TechItem>::iterator i=remainingTech.begin();i!=remainingTech.end();i++)
{
TechType t=i->techType;
UpgradeType u=i->upgradeType;
if (t!=TechTypes::None)
{
if (this->getPlannedCount(t.whatResearches())==0)
{
this->build(1,t.whatResearches(),l->first);
}
//also check to see if we have enough gas, or a refinery planned
if (t.gasPrice()>BWAPI::Broodwar->self()->cumulativeGas()-this->usedGas)
{
UnitType refinery=Broodwar->self()->getRace().getRefinery();
if (this->getPlannedCount(refinery)==0)
this->build(1,refinery,l->first);
}
}
else if (u!=UpgradeTypes::None)
{
if (this->getPlannedCount(u.whatUpgrades())==0)
this->build(1,u.whatUpgrades(),l->first);
//also check to see if we have enough gas, or a refinery planned
if (u.gasPriceBase()+u.gasPriceFactor()*(BWAPI::Broodwar->self()->getUpgradeLevel(u)-1)>BWAPI::Broodwar->self()->cumulativeGas()-this->usedGas)
{
UnitType refinery=Broodwar->self()->getRace().getRefinery();
if (this->getPlannedCount(refinery)==0)
this->build(1,refinery,l->first);
}
if (i->level>1)
{
if (u.getRace()==Races::Terran)
{
if (this->getPlannedCount(UnitTypes::Terran_Science_Facility)==0)
this->build(1,UnitTypes::Terran_Science_Facility,l->first);
}
else if (u.getRace()==Races::Protoss)
{
if (this->getPlannedCount(UnitTypes::Protoss_Templar_Archives)==0)
this->build(1,UnitTypes::Protoss_Templar_Archives,l->first);
}
else if (u.getRace()==Races::Zerg)
{
if (this->getPlannedCount(UnitTypes::Zerg_Lair)==0)
this->build(1,UnitTypes::Zerg_Lair,l->first);
}
}
}
}
}
//reserve units and resources for later
//iterate through time (this gives earlier events higher priority)
for(set<int>::iterator t=times.begin();t!=times.end();t++)
{
int ctime=*t;
//remove all tech units that have been reserved
set<MetaUnit*>::iterator i2;
for(set<MetaUnit*>::iterator i=techUnits.begin();i!=techUnits.end();i=i2)
{
i2=i;
i2++;
if (this->reservedUnits.find(*i)!=this->reservedUnits.end())
techUnits.erase(i);
}
//iterate through all tech units that haven't been reserved yet
for(set<MetaUnit*>::iterator i=techUnits.begin();i!=techUnits.end();i++)
{
MetaUnit* techUnit=*i;
//get a unit type, taking into account the remaining unit counts and the set of units this factory can make right now
pair< TechType,UpgradeType > p=getTechOrUpgradeType(techsCanResearch(*i,ctime),upgradesCanResearch(*i,ctime),remainingTech);
TechType t=p.first;
UpgradeType u=p.second;
if (t==TechTypes::None && u==UpgradeTypes::None)
continue;
this->reservedUnits.insert(techUnit);
if (t!=TechTypes::None)
{
this->reserveResources(techUnit,t);
this->savedPlan.push_back(Type(t,techUnit,currentPriority,ctime));
}
else if (u!=UpgradeTypes::None)
{
this->reserveResources(techUnit,u);
this->savedPlan.push_back(Type(u,techUnit,currentPriority,ctime));
}
if (this->isResourceLimited())
return;
}
}
//-------------------------------------------------------------------------------------------------------
//Next consider all buildings and units for this priority level
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > > buildings;
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > > unitsA;//units that require addons
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem* > > units;
for(map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >::iterator i=l->second.units.begin();i!=l->second.units.end();i++)
{
for(map<BWAPI::UnitType, UnitItem >::iterator j=i->second.begin();j!=i->second.end();j++)
{
if (j->first.isBuilding())
buildings[i->first][j->first]=&(j->second);
else
{
//see if the unit type requires an addon
if (j->first==UnitTypes::Terran_Siege_Tank_Tank_Mode ||
j->first==UnitTypes::Terran_Siege_Tank_Siege_Mode ||
j->first==UnitTypes::Terran_Dropship ||
j->first==UnitTypes::Terran_Battlecruiser ||
j->first==UnitTypes::Terran_Science_Vessel ||
j->first==UnitTypes::Terran_Valkyrie)
unitsA[i->first][j->first]=&(j->second);
else
units[i->first][j->first]=&(j->second);
}
if (this->dependencyResolver)
{
//check dependencies (required units)
for(map<BWAPI::UnitType, int>::const_iterator k=j->first.requiredUnits().begin();k!=j->first.requiredUnits().end();k++)
{
if (k->first == UnitTypes::Zerg_Larva) continue;
if (this->getPlannedCount(k->first)==0)
{
this->build(1,k->first,l->first);
}
}
//also check to see if we have enough gas, or a refinery planned
if (j->first.gasPrice()>BWAPI::Broodwar->self()->cumulativeGas()-this->usedGas)
{
if (j->first!=UnitTypes::Zerg_Larva && j->first!=UnitTypes::Zerg_Egg && j->first!=UnitTypes::Zerg_Lurker_Egg && j->first!=UnitTypes::Zerg_Cocoon)
{
UnitType refinery=Broodwar->self()->getRace().getRefinery();
if (this->getPlannedCount(refinery)==0)
this->build(1,refinery,l->first);
}
}
}
}
}
globalUnitSet=&buildings;
if (updateUnits()) return;
globalUnitSet=&unitsA;
if (updateUnits()) return;
globalUnitSet=&units;
if (updateUnits()) return;
this->removeCompletedItems(&(l->second));
}
debug("unit-limited");
}
string BuildOrderManager::getName() const
{
return "Build Order Manager";
}
void BuildOrderManager::build(int count, BWAPI::UnitType t, int priority, BWAPI::TilePosition seedPosition)
{
if (t == BWAPI::UnitTypes::None || t == BWAPI::UnitTypes::Unknown) return;
if (seedPosition == BWAPI::TilePositions::None || seedPosition == BWAPI::TilePositions::Unknown)
seedPosition=BWAPI::Broodwar->self()->getStartLocation();
if (t==UnitTypes::Protoss_Pylon && this->getPlannedCount(t)==0)
{
if (!this->buildManager->getBuildingPlacer()->canBuildHereWithSpace(seedPosition, t, 3))
seedPosition = this->buildManager->getBuildingPlacer()->getBuildLocationNear(seedPosition, t, 3);
}
if (items[priority].units[t.whatBuilds().first].find(t)==items[priority].units[t.whatBuilds().first].end())
items[priority].units[t.whatBuilds().first].insert(make_pair(t,UnitItem(t)));
items[priority].units[t.whatBuilds().first][t].setNonAdditional(count,seedPosition);
nextUpdateFrame=0;
}
void BuildOrderManager::buildAdditional(int count, BWAPI::UnitType t, int priority, BWAPI::TilePosition seedPosition)
{
if (t == BWAPI::UnitTypes::None || t == BWAPI::UnitTypes::Unknown) return;
if (seedPosition == BWAPI::TilePositions::None || seedPosition == BWAPI::TilePositions::Unknown)
seedPosition=BWAPI::Broodwar->self()->getStartLocation();
if (items[priority].units[t.whatBuilds().first].find(t)==items[priority].units[t.whatBuilds().first].end())
items[priority].units[t.whatBuilds().first].insert(make_pair(t,UnitItem(t)));
items[priority].units[t.whatBuilds().first][t].addAdditional(count,seedPosition);
nextUpdateFrame=0;
}
void BuildOrderManager::research(BWAPI::TechType t, int priority)
{
if (t==BWAPI::TechTypes::None || t==BWAPI::TechTypes::Unknown) return;
items[priority].techs.push_back(TechItem(t));
nextUpdateFrame=0;
}
void BuildOrderManager::upgrade(int level, BWAPI::UpgradeType t, int priority)
{
if (t==BWAPI::UpgradeTypes::None || t==BWAPI::UpgradeTypes::Unknown) return;
items[priority].techs.push_back(TechItem(t,level));
nextUpdateFrame=0;
}
bool BuildOrderManager::hasResources(std::pair<int, BuildOrderManager::Resources> res)
{
bool mineralLimited=false;
bool gasLimited=false;
this->reserveResources(res);
double m=BWAPI::Broodwar->self()->cumulativeMinerals()-this->usedMinerals;
double g=BWAPI::Broodwar->self()->cumulativeGas()-this->usedGas;
for(map<int, Resources>::iterator i=this->reservedResources.begin();i!=this->reservedResources.end();i++)
{
double t=i->first-Broodwar->getFrameCount();
m-=i->second.minerals;
g-=i->second.gas;
if (m+t*this->workerManager->getMineralRate()<0)
mineralLimited=true;
if (g+t*this->workerManager->getGasRate()<0)
gasLimited=true;
}
this->unreserveResources(res);
this->isMineralLimited = this->isMineralLimited || mineralLimited;
this->isGasLimited = this->isGasLimited || gasLimited;
return (!mineralLimited || res.second.minerals==0) && (!gasLimited || res.second.gas==0);
}
bool BuildOrderManager::hasResources(BWAPI::UnitType t)
{
bool ret=hasResources(t,Broodwar->getFrameCount());
return ret;
}
bool BuildOrderManager::hasResources(BWAPI::TechType t)
{
return hasResources(t,Broodwar->getFrameCount());
}
bool BuildOrderManager::hasResources(BWAPI::UpgradeType t)
{
return hasResources(t,Broodwar->getFrameCount());
}
bool BuildOrderManager::hasResources(BWAPI::UnitType t, int time)
{
pair<int, Resources> res;
res.first=time;
res.second.minerals=t.mineralPrice();
res.second.gas=t.gasPrice();
bool ret=hasResources(res);
return ret;
}
bool BuildOrderManager::hasResources(BWAPI::TechType t, int time)
{
pair<int, Resources> res;
res.first=time;
res.second.minerals=t.mineralPrice();
res.second.gas=t.gasPrice();
return hasResources(res);
}
bool BuildOrderManager::hasResources(BWAPI::UpgradeType t, int time)
{
pair<int, Resources> res;
res.first=time;
res.second.minerals=t.mineralPriceBase()+t.mineralPriceFactor()*this->upgradeManager->getPlannedLevel(t);
res.second.gas=t.gasPriceBase()+t.gasPriceFactor()*this->upgradeManager->getPlannedLevel(t);
return hasResources(res);
}
void BuildOrderManager::spendResources(BWAPI::UnitType t)
{
this->usedMinerals+=t.mineralPrice();
this->usedGas+=t.gasPrice();
}
void BuildOrderManager::spendResources(BWAPI::TechType t)
{
this->usedMinerals+=t.mineralPrice();
this->usedGas+=t.gasPrice();
}
void BuildOrderManager::spendResources(BWAPI::UpgradeType t)
{
this->usedMinerals+=t.mineralPriceBase()+t.mineralPriceFactor()*this->upgradeManager->getPlannedLevel(t);
this->usedGas+=t.gasPriceBase()+t.gasPriceFactor()*this->upgradeManager->getPlannedLevel(t);
}
//returns the BuildOrderManager's planned count of units for this type
int BuildOrderManager::getPlannedCount(BWAPI::UnitType t)
{
//builder unit type
UnitType builder=t.whatBuilds().first;
int c=this->buildManager->getPlannedCount(t);
//sum all the remaining units for every priority level
for(map<int, PriorityLevel>::iterator p=items.begin();p!=items.end();p++)
{
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >* units=&(p->second.units);
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >::iterator i=units->find(builder);
if (i!=units->end())
{
map<BWAPI::UnitType, UnitItem >* units2=&(i->second);
map<BWAPI::UnitType, UnitItem >::iterator j=units2->find(t);
if (j!=units2->end())
{
c+=j->second.getRemainingCount(c);
}
}
}
if (t==UnitTypes::Zerg_Hatchery)
c+=this->getPlannedCount(UnitTypes::Zerg_Lair);
if (t==UnitTypes::Zerg_Lair)
c+=this->getPlannedCount(UnitTypes::Zerg_Hive);
return c;
}
//returns the BuildOrderManager's planned count of units for this type
int BuildOrderManager::getPlannedCount(BWAPI::UnitType t, int minPriority)
{
//builder unit type
UnitType builder=t.whatBuilds().first;
int c=this->buildManager->getPlannedCount(t);
//sum all the remaining units for every priority level
for(map<int, PriorityLevel>::iterator p=items.begin();p!=items.end();p++)
{
if (p->first<minPriority) continue; //don't consider planned units below min priority
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >* units=&(p->second.units);
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >::iterator i=units->find(builder);
if (i!=units->end())
{
map<BWAPI::UnitType, UnitItem >* units2=&(i->second);
map<BWAPI::UnitType, UnitItem >::iterator j=units2->find(t);
if (j!=units2->end())
{
c+=j->second.getRemainingCount(c);
}
}
}
if (t==UnitTypes::Zerg_Hatchery)
c+=this->getPlannedCount(UnitTypes::Zerg_Lair);
if (t==UnitTypes::Zerg_Lair)
c+=this->getPlannedCount(UnitTypes::Zerg_Hive);
return c;
}
//reserves resources for this unit type
pair<int, BuildOrderManager::Resources> BuildOrderManager::reserveResources(MetaUnit* builder, UnitType unitType)
{
int t=Broodwar->getFrameCount();
if (builder)
t=nextFreeTime(builder,unitType);
pair<int, Resources> ret;
ret.first=t;
ret.second.minerals=unitType.mineralPrice();
ret.second.gas=unitType.gasPrice();
reserveResources(ret);
return ret;
}
//reserves resources for this tech type
pair<int, BuildOrderManager::Resources> BuildOrderManager::reserveResources(MetaUnit* techUnit, TechType techType)
{
int t=Broodwar->getFrameCount();
if (techUnit)
t=nextFreeTime(techUnit);
pair<int, Resources> ret;
ret.first=t;
ret.second.minerals=techType.mineralPrice();
ret.second.gas=techType.gasPrice();
reserveResources(ret);
return ret;
}
//reserves resources for this upgrade type
pair<int, BuildOrderManager::Resources> BuildOrderManager::reserveResources(MetaUnit* techUnit, UpgradeType upgradeType)
{
int t=Broodwar->getFrameCount();
if (techUnit)
t=nextFreeTime(techUnit);
pair<int, Resources> ret;
ret.first=t;
ret.second.minerals=upgradeType.mineralPriceBase()+upgradeType.mineralPriceFactor()*this->upgradeManager->getPlannedLevel(upgradeType);
ret.second.gas=upgradeType.gasPriceBase()+upgradeType.gasPriceFactor()*this->upgradeManager->getPlannedLevel(upgradeType);
reserveResources(ret);
return ret;
}
void BuildOrderManager::reserveResources(pair<int, BuildOrderManager::Resources> res)
{
this->reservedResources[res.first].minerals+=res.second.minerals;
this->reservedResources[res.first].gas+=res.second.gas;
}
//unreserves the given resources
void BuildOrderManager::unreserveResources(pair<int, BuildOrderManager::Resources> res)
{
this->reservedResources[res.first].minerals-=res.second.minerals;
this->reservedResources[res.first].gas-=res.second.gas;
if (this->reservedResources[res.first].minerals==0 && this->reservedResources[res.first].gas == 0)
this->reservedResources.erase(res.first);
}
void BuildOrderManager::enableDependencyResolver()
{
this->dependencyResolver=true;
}
void BuildOrderManager::setDebugMode(bool debugMode)
{
this->debugMode=debugMode;
this->buildManager->setDebugMode(debugMode);
}
void BuildOrderManager::removeCompletedItems(PriorityLevel* p)
{
list<TechItem>::iterator i2;
for(list<TechItem>::iterator i=p->techs.begin();i!=p->techs.end();i=i2)
{
i2=i;
i2++;
if (i->techType!=TechTypes::None)
{
if (this->techManager->planned(i->techType))
{
p->techs.erase(i);
}
}
else if (i->upgradeType!=UpgradeTypes::None)
{
if (this->upgradeManager->getPlannedLevel(i->upgradeType)==i->level)
{
p->techs.erase(i);
}
}
}
map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >::iterator i3;
for(map<BWAPI::UnitType, map<BWAPI::UnitType, UnitItem > >::iterator i=p->units.begin();i!=p->units.end();i=i3)
{
i3=i;
i3++;
map<BWAPI::UnitType, UnitItem >::iterator j2;
for(map<BWAPI::UnitType, UnitItem >::iterator j=i->second.begin();j!=i->second.end();j=j2)
{
j2=j;
j2++;
if (j->second.getRemainingCount()==0)
i->second.erase(j);
}
if (i->second.empty())
p->units.erase(i);
}
}
void BuildOrderManager::debug(const char* text, ...)
{
const int BUFFER_SIZE = 1024;
char buffer[BUFFER_SIZE];
va_list ap;
va_start(ap, text);
vsnprintf_s(buffer, BUFFER_SIZE, BUFFER_SIZE, text, ap);
va_end(ap);
if (this->debugMode)
{
Broodwar->drawTextScreen(5,y,"%s",buffer);
y+=15;
}
}
| [
"[email protected]"
] | [
[
[
1,
1016
]
]
] |
47c992305d0335f48b00a86a048e0722ade7722c | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/imglib/memmap/source/memmap.cpp | 4364e564376dc1bc0e33df35be0b42466c4d7cde | [] | no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,219 | cpp | /*
* Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "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:
*
*/
#include "memmap.h"
/**
Constructor: Memmap class
Initilize the parameters to data members.
@internalComponent
@released
@param aFillFlg - Flag to enable the initialisation of memory map
@param aOutputFile - Name of the output file
*/
Memmap::Memmap( int aFillFlg, const string& aOutputFile )
: iOutFileName(aOutputFile), iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg) {
iUtils = new MemmapUtils();
}
/**
Constructor: Memmap class
Initilize the parameters to data members.
@internalComponent
@released
@param aFillFlg - Flag to enable the initialisation of memory map
*/
Memmap::Memmap( int aFillFlg )
: iData(0), iMaxMapSize(0), iStartOffset(0), iFillFlg(aFillFlg) {
iUtils = new MemmapUtils();
}
/**
Destructor: Memmap class
Deallocates the memory for data members
@internalComponent
@released
*/
Memmap::~Memmap( ) {
if(iData) {
CloseMemoryMap();
}
if(iUtils) {
delete iUtils;
}
}
/**
SetOutputFile: To set the output image file
@internalComponent
@released
@param aOutputFile - Name of the output image file
*/
void Memmap::SetOutputFile(const string& aOutputFile ) {
iOutFileName = aOutputFile;
}
/**
SetMaxMapSize: To set the maximum size of the memory map
@internalComponent
@released
@param aMaxSize - Size of the memory map
*/
void Memmap::SetMaxMapSize( unsigned long aMaxSize )
{
iMaxMapSize = aMaxSize;
};
/**
GetMapSize: To get the size of the memory map
@internalComponent
@released
*/
unsigned long Memmap::GetMapSize( )
{
return iMaxMapSize;
}
/**
operator[]: To access the memory map contents
@internalComponent
@released
@param aIndex - Offset of the memory map location
*/
char& Memmap::operator[]( unsigned long aIndex )
{
return iData[aIndex];
}
/**
CreateMemoryMap:
Opens the memory map file
Initialises the map size member
Create the memory map pointer
Fill the memory map with the specified value
@internalComponent
@released
@param aStartOffset - Start offset of the memory map location
@param aFillVal - Value to be filled in the memory map
*/
int Memmap::CreateMemoryMap( unsigned long aStartOffset, unsigned char aFillVal ) {
if((!iMaxMapSize) || (aStartOffset > iMaxMapSize)) {
return KStatFalse;
}
else if(iUtils->IsMapFileOpen() && iData) {
iStartOffset = aStartOffset;
return KStatTrue;
}
if(iUtils->IsMapFileOpen() == KStatFalse) {
if(iUtils->OpenMapFile() == KStatFalse) {
return KStatFalse;
}
}
if(iUtils->CreateFileMapObject(iMaxMapSize) == KStatFalse) {
return KStatFalse;
}
iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
if( !iData ) {
return KStatFalse;
}
iStartOffset = aStartOffset;
if(iFillFlg) {
return FillMemMap( aFillVal );
}
return KStatTrue;
}
/**
CloseMemoryMap: Close the memory map and the associated objects
@internalComponent
@released
@param aCloseFile - Flag to close the memory map file
*/
void Memmap::CloseMemoryMap( int aCloseFile ) {
// Close map view pointer
if(!iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize)) {
Print(ELog, "Failed to unmap the memory map object");
}
iData = 0;
iUtils->CloseFileMapObject();
// Close map file
if(aCloseFile) {
iUtils->CloseMapFile();
}
}
/**
GetMemoryMapPointer: Get the stating address of the memory map
@internalComponent
@released
*/
char *Memmap::GetMemoryMapPointer( ) {
if(iData)
return (iData + iStartOffset);
return KStatFalse;
}
/**
WriteToOutputFile: Writes the memory map contents to the output file
@internalComponent
@released
*/
void Memmap::WriteToOutputFile( ) {
if(!iData) {
Print(EAlways, "Memory map has not been created");
}
if(iOutFileName.empty()) {
Print(EAlways, "Output file has not been set");
return;
}
ofstream ofs(iOutFileName.c_str(), ios_base::out + ios_base::binary );
if(!ofs.is_open()) {
Print(EAlways, "Cannot open output file %s", (char*)iOutFileName.data());
return;
}
ofs.write((const char*)(iData + iStartOffset), (iMaxMapSize - iStartOffset));
ofs.close();
return;
}
/**
FillMemMap: Fills the memory map with the specified value
@internalComponent
@released
@param aFillVal - Value to be filled
*/
int Memmap::FillMemMap( unsigned char aFillVal ) {
if(iData) {
// Fill the value
memset(iData, aFillVal, iMaxMapSize);
// Unmap the file
if(iUtils->CloseMemMapPointer((void*)iData, iMaxMapSize) == KStatFalse) {
return KStatFalse;
}
// Map it again
iData = (char*)(iUtils->OpenMemMapPointer(0,iMaxMapSize));
if(!iData) {
return KStatFalse;
}
}
return KStatTrue;
}
| [
"none@none"
] | [
[
[
1,
257
]
]
] |
fa2133ff66e6b6935674cbdd707678e1dec1d868 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/MtlUpdateCmdUI.h | 9ee9d505a33324af26c0e74ae30ac5f71b1ed744 | [] | no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 19,393 | h | /**
* @file MtlUpdateCmdUI.h
* @brief CmdUI の更新関係.
*/
////////////////////////////////////////////////////////////////////////////
// MTL Version 0.10
// Copyright (C) 2001 MB<[email protected]>
// All rights unreserved.
//
// This file is a part of Mb Template Library.
// The code and information is *NOT* provided "as-is" without
// warranty of any kind, either expressed or implied.
//
// MtlUpdateCmdUI.h: Last updated: March 17, 2001
/////////////////////////////////////////////////////////////////////////////
#ifndef __MTLUPDATECMDUI_H__
#define __MTLUPDATECMDUI_H__
#pragma once
#include "MtlWin.h"
namespace MTL {
// better not use
#define CN_UPDATE_COMMAND_UI ( (UINT) (-1) ) // void (CCmdUI*)
#define BEGIN_UPDATE_COMMAND_UI_MAP(theClass) \
public: \
BOOL m_bCmdUIHandled; \
/* "handled" management for cracked handlers */ \
BOOL IsCmdUIHandled() const \
{ \
return m_bCmdUIHandled; \
} \
void SetCmdUIHandled(BOOL bHandled) \
{ \
m_bCmdUIHandled = bHandled; \
} \
BOOL ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI) \
{ \
BOOL bOldCmdUIHandled = m_bCmdUIHandled; \
BOOL bRet = _ProcessCmdUIMap(nID, pCmdUI); \
m_bCmdUIHandled = bOldCmdUIHandled; \
return bRet; \
} \
BOOL _ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI) \
{
#if 1 //+++ ヘッダ&ルーチン分離用
#define BEGIN_UPDATE_COMMAND_UI_MAP_decl(theClass) \
public: \
BOOL m_bCmdUIHandled; \
/* "handled" management for cracked handlers */ \
BOOL IsCmdUIHandled() const; \
void SetCmdUIHandled(BOOL bHandled); \
BOOL ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI); \
BOOL _ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI);
#define BEGIN_UPDATE_COMMAND_UI_MAP_impl(theClass) \
BOOL IsCmdUIHandled() const \
{ \
return m_bCmdUIHandled; \
} \
void SetCmdUIHandled(BOOL bHandled) \
{ \
m_bCmdUIHandled = bHandled; \
} \
BOOL ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI) \
{ \
BOOL bOldCmdUIHandled = m_bCmdUIHandled; \
BOOL bRet = _ProcessCmdUIMap(nID, pCmdUI); \
m_bCmdUIHandled = bOldCmdUIHandled; \
return bRet; \
} \
BOOL _ProcessCmdUIMap(UINT nID, CCmdUI * pCmdUI) \
{
#endif
#define UPDATE_COMMAND_UI(id, func) \
if (nID == id) { \
SetCmdUIHandled(TRUE); \
func(pCmdUI); \
if ( IsCmdUIHandled() ) \
return TRUE; \
}
// set text
#define UPDATE_COMMAND_UI_SETTEXT(id, text) \
if (nID == id) { \
pCmdUI->SetText(text); \
return TRUE; \
}
// set check
#define UPDATE_COMMAND_UI_SETCHECK_IF(id, condition) \
if (nID == id) { \
pCmdUI->SetCheck(condition != 0/*? 1 : 0*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETCHECK_IF_PASS(id, condition) \
if (nID == id) { \
pCmdUI->SetCheck(condition != 0/*? 1 : 0*/); \
}
#define UPDATE_COMMAND_UI_ENABLE_SETCHECK_IF(id, condition) \
if (nID == id) { \
pCmdUI->Enable(); \
pCmdUI->SetCheck(condition != 0/*? 1 : 0*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETCHECK_FLAG(id, flag, flags) \
if (nID == id) { \
pCmdUI->SetCheck((flags & flag) != 0/*? 1 : 0*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETCHECK_FLAG_PASS(id, flag, flags) \
if (nID == id) { \
pCmdUI->SetCheck((flags & flag) != 0/*? 1 : 0*/); \
}
#define UPDATE_COMMAND_UI_SETCHECK_FLAG_REV(id, flag, flags) \
if (nID == id) { \
pCmdUI->SetCheck((flags & flag) ? 0 : 1); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_ENABLE_SETCHECK_FLAG(id, flag, flags) \
if (nID == id) { \
pCmdUI->Enable(); \
pCmdUI->SetCheck((flags & flag) != 0/*? 1 : 0*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_ENABLE_SETCHECK_FLAG_REV(id, flag, flags) \
if (nID == id) { \
pCmdUI->Enable(); \
pCmdUI->SetCheck((flags & flag) == 0 /*? 0 : 1*/); \
return TRUE; \
}
// enable
#define UPDATE_COMMAND_UI_ENABLE_IF(id, condition) \
if (nID == id) { \
pCmdUI->Enable((condition) != 0 /*? true : false*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_ENABLE_IF_PASS(id, condition) \
if (nID == id) { \
pCmdUI->Enable(condition != 0/*? true : false*/); \
}
#define UPDATE_COMMAND_UI_ENABLE_FLAG(id, flag, flags) \
if (nID == id) { \
pCmdUI->Enable((flags & flag) != 0 /*? true : false*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_ENABLE_FLAG_REV(id, flag, flags) \
if (nID == id) { \
pCmdUI->Enable((flags & flag) ? 0 : 1); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_POPUP_ENABLE_IF(id, condition) \
if (nID == id) { \
if (pCmdUI->m_menuSub.m_hMenu) { \
pCmdUI->m_menu.EnableMenuItem( pCmdUI->m_nIndex, MF_BYPOSITION | \
( condition ? MF_ENABLED : (MF_DISABLED | MF_GRAYED) ) ); \
} \
return TRUE; \
}
#define UPDATE_COMMAND_UI_ENABLE_IF_WITH_POPUP(id, condition, popup_condition) \
if (nID == id) { \
if (pCmdUI->m_menuSub.m_hMenu) { \
pCmdUI->m_menu.EnableMenuItem( pCmdUI->m_nIndex, MF_BYPOSITION | \
( popup_condition ? MF_ENABLED : (MF_DISABLED | MF_GRAYED) ) ); \
} else { \
pCmdUI->Enable(condition != 0 /*? true : false*/); \
} \
return TRUE; \
}
// set default
#define UPDATE_COMMAND_UI_SETDEFAULT(id) \
if (nID == id) { \
pCmdUI->SetDefault(); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETDEFAULT_PASS(id) \
if (nID == id) { \
pCmdUI->SetDefault(); \
}
#define UPDATE_COMMAND_UI_SETDEFAULT_IF(id, condition) \
if (nID == id) { \
pCmdUI->SetDefault(condition); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETDEFAULT_IF_PASS(id, condition) \
if (nID == id) { \
pCmdUI->SetDefault(condition); \
}
#define UPDATE_COMMAND_UI_SETDEFAULT_FLAG(id, flag, flags) \
if (nID == id) { \
pCmdUI->SetDefault((flags & flag) != 0/*? true : false*/); \
return TRUE; \
}
#define UPDATE_COMMAND_UI_SETDEFAULT_FLAG_PASS(id, flag, flags) \
if (nID == id) { \
pCmdUI->SetDefault((flags & flag) != 0/*? true : false*/); \
}
#define END_UPDATE_COMMAND_UI_MAP() \
return FALSE; \
}
/// simple helper class
class CCmdUI {
public:
// Attributes
UINT m_nID;
UINT m_nIndex; // menu item or other index
// if a menu item
CMenuHandle m_menu; // NULL if not a menu
CMenuHandle m_menuSub; // sub containing menu item
// if a popup sub menu - ID is for first in popup
// if from some other window
CWindow m_wndOther; // NULL if a menu or not a CWnd
// bool m_bEnableChanged;
// bool m_bContinueRouting;
UINT m_nIndexMax; // last + 1 for iterating m_nIndex
public:
// Operations to do in ON_UPDATE_COMMAND_UI
virtual void Enable(bool bOn = true)
{
if (m_menu.m_hMenu != NULL) {
if (m_menuSub.m_hMenu != NULL)
return; // don't change popup menus indirectly
ATLASSERT(m_nIndex < m_nIndexMax);
m_menu.EnableMenuItem( m_nIndex, MF_BYPOSITION | ( bOn ? MF_ENABLED : (MF_DISABLED | MF_GRAYED) ) );
} else {
// enable/disable a control (i.e. child window)
ATLASSERT(m_wndOther.m_hWnd != NULL);
// if control has the focus, move the focus before disabling
// if (!bOn && (::GetFocus() == m_wndOther.m_hWnd)) {
// m_pOther->GetParent()->GetNextDlgTabItem(m_pOther)->SetFocus();
// }
m_wndOther.EnableWindow(bOn);
}
// m_bEnableChanged = true;
}
virtual void SetCheck(int nCheck = 1) // 0, 1 or 2 (indeterminate)
{
if (m_menu.m_hMenu != NULL) {
if (m_menuSub.m_hMenu != NULL)
return; // don't change popup menus indirectly
// place checkmark next to menu item
ATLASSERT(m_nIndex < m_nIndexMax);
m_menu.CheckMenuItem( m_nIndex, MF_BYPOSITION | (nCheck ? MF_CHECKED : MF_UNCHECKED) );
}
}
virtual void SetRadio(bool bOn = true)
{
// not supported
SetCheck(bOn /*? 1 : 0*/);
}
virtual void SetText(LPCTSTR lpszText)
{
if (lpszText == NULL)
lpszText = _T("");
// ATLASSERT(lpszText != NULL);
if (m_menu.m_hMenu != NULL) {
if (m_menuSub.m_hMenu != NULL)
return; // don't change popup menus indirectly
// get current menu state so it doesn't change
UINT nState = m_menu.GetMenuState(m_nIndex, MF_BYPOSITION);
nState &= ~(MF_BITMAP | MF_OWNERDRAW | MF_SEPARATOR);
// set menu text
ATLASSERT(m_nIndex < m_nIndexMax);
m_menu.ModifyMenu(m_nIndex, MF_BYPOSITION | MF_STRING | nState, m_nID, lpszText);
} else {
ATLASSERT(m_wndOther.m_hWnd != NULL);
MtlSetWindowText(m_wndOther.m_hWnd, lpszText);
}
}
virtual void SetDefault(bool bOn = true)
{
if (m_menu.m_hMenu != NULL) {
if (m_menuSub.m_hMenu != NULL)
return; // don't change popup menus indirectly
// place checkmark next to menu item
ATLASSERT(m_nIndex < m_nIndexMax);
if (bOn)
m_menu.SetMenuDefaultItem(m_nIndex, TRUE);
}
}
private:
// Advanced operation
void ContinueRouting() { /*m_bContinueRouting = true;*/ }
public:
// Implementation
CCmdUI()
{
// zero out everything
m_nID = m_nIndex = m_nIndexMax = 0;
}
};
// class private to this file !
class CToolCmdUI : public CCmdUI {
public: // re-implementations only
private:
virtual void Enable(bool bOn = true)
{
// ATLTRACE2(atlTraceGeneral, 4, _T("CToolCmdUI::Enable (%d:%d)\n"), m_wndOther.m_hWnd, m_nIndex);
// m_bEnableChanged = true;
CToolBarCtrl toolbar = m_wndOther.m_hWnd;
ATLASSERT(m_nIndex < m_nIndexMax);
UINT nOldState = toolbar.GetState(m_nID);
UINT nNewState = nOldState;
ATLASSERT(nNewState != -1);
if (!bOn) {
nNewState &= ~TBSTATE_ENABLED;
// WINBUG: If a button is currently pressed and then is disabled
// COMCTL32.DLL does not unpress the button, even after the mouse
// button goes up! We work around this bug by forcing TBBS_PRESSED
// off when a button is disabled.
nNewState &= ~TBSTATE_CHECKED;
} else {
nNewState |= TBSTATE_ENABLED;
}
if (nNewState != nOldState) {
MTLVERIFY( toolbar.SetState(m_nID, nNewState) );
}
}
virtual void SetCheck(int nCheck = 1)
{
ATLASSERT(nCheck >= 0 && nCheck <= 2); // 0=>off, 1=>on, 2=>indeterminate
CToolBarCtrl toolbar = m_wndOther.m_hWnd;
ATLASSERT(m_nIndex < m_nIndexMax);
CVersional<TBBUTTONINFO> tbb;
tbb.dwMask = TBIF_STATE | TBIF_STYLE;
MTLVERIFY( toolbar.GetButtonInfo(m_nID, &tbb) != -1 );
BYTE fsNewState = tbb.fsState & ~(TBSTATE_CHECKED | TBSTATE_INDETERMINATE);
if (nCheck == 1)
fsNewState |= TBSTATE_CHECKED;
else if (nCheck == 2)
fsNewState |= TBSTATE_INDETERMINATE;
BYTE fsNewStyle = tbb.fsStyle | TBSTYLE_CHECK; // add a check style
bool bUpdate = false;
if (tbb.fsState != fsNewState) {
bUpdate = true;
tbb.fsState = fsNewState;
}
if (tbb.fsStyle != fsNewStyle) {
bUpdate = true;
tbb.fsStyle = fsNewStyle;
} else {
tbb.dwMask = TBIF_STATE; // update only state
}
if (bUpdate) {
MTLVERIFY( toolbar.SetButtonInfo(m_nID, &tbb /* | TBBS_CHECKBOX*/) );
}
}
virtual void SetText(LPCTSTR lpszText)
{
// ignored it.
}
virtual void SetDefault(bool bOn = true)
{
// ignored it.
}
};
class CUpdateCmdUIBase {
public:
static bool s_bAutoMenuEnable; // not supported yet
DECLARE_REGISTERED_MESSAGE(Mtl_Update_CmdUI_Message)
static BOOL ProcessCmdUIToWindow(HWND hWnd, UINT nID, CCmdUI *pCmdUI)
{
return ::SendMessage(hWnd, GET_REGISTERED_MESSAGE(Mtl_Update_CmdUI_Message), (WPARAM) nID, (LPARAM) pCmdUI) != 0;
}
};
__declspec(selectany) bool CUpdateCmdUIBase::s_bAutoMenuEnable = true;
template <class T>
class CUpdateCmdUIHandler : public CUpdateCmdUIBase {
public:
BEGIN_MSG_MAP(CUpdateCmdUIHandler)
MESSAGE_HANDLER(GET_REGISTERED_MESSAGE(Mtl_Update_CmdUI_Message), OnUpdateCommandUI)
END_MSG_MAP()
private:
LRESULT OnUpdateCommandUI(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled)
{
ATLASSERT( uMsg == GET_REGISTERED_MESSAGE(Mtl_Update_CmdUI_Message) );
UINT nID = (UINT) wParam;
CCmdUI *pCmdUI = (CCmdUI *) lParam;
T * pT = static_cast<T *>(this);
return pT->ProcessCmdUIMap(nID, pCmdUI);
}
};
template <class T>
class CUpdateCmdUI : public CUpdateCmdUIBase {
public:
// Data members
CSimpleArray<HWND> m_arrToolBar;
// Constructor
CUpdateCmdUI()
{
}
// Methods
void CmdUIAddToolBar(HWND hWndToolBar)
{
m_arrToolBar.Add(hWndToolBar);
}
// Message map and handlers
BEGIN_MSG_MAP(CUpdateCmdUI)
MESSAGE_HANDLER(WM_COMMAND, OnCommand)
MSG_WM_INITMENUPOPUP(OnInitMenuPopup)
MESSAGE_HANDLER(GET_REGISTERED_MESSAGE(Mtl_Update_CmdUI_Message), OnUpdateCommandUI)
END_MSG_MAP()
private:
LRESULT OnCommand(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL &bHandled)
{ // a service to avoid a tool bar button's flicker
bHandled = FALSE;
HWND hWndCtl = (HWND) lParam;
if (hWndCtl != NULL && m_arrToolBar.Find(hWndCtl) != -1) {
::UpdateWindow(hWndCtl);
}
return 0;
}
void OnInitMenuPopup(HMENU hmenuPopup, UINT uPos, BOOL fSystemMenu)
{
SetMsgHandled(FALSE);
CmdUIUpdateMenuBar(hmenuPopup);
}
LRESULT OnUpdateCommandUI(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL & /*bHandled*/)
{
UINT nID = (UINT) wParam;
CCmdUI* pCmdUI = (CCmdUI *) lParam;
T * pT = static_cast<T *>(this);
return pT->ProcessCmdUIMap(nID, pCmdUI);
}
BOOL _DoUpdate(CCmdUI *pCmdUI, bool bDisableIfNoHndler)
{
if ( /*pCmdUI->m_nID == 0 || */ LOWORD(pCmdUI->m_nID) == 0xFFFF)
return TRUE;
// ignore invalid IDs
// pCmdUI->m_bEnableChanged = false;
T * pT = static_cast<T *>(this);
BOOL bResult = pT->ProcessCmdUIMap(pCmdUI->m_nID, pCmdUI);
//if (!bResult)
// ATLASSERT(!pCmdUI->m_bEnableChanged); // not routed
//if (bDisableIfNoHndler && !pCmdUI->m_bEnableChanged && !bResult)
//{
// Enable or Disable based on whether there is a handler there
//}
return bResult;
}
void CmdUIUpdateMenuBar(CMenuHandle menuPopup)
{
CCmdUI state;
state.m_menu = menuPopup.m_hMenu;
ATLASSERT(state.m_wndOther.m_hWnd == NULL);
state.m_nIndexMax = menuPopup.GetMenuItemCount();
for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax; state.m_nIndex++) {
state.m_nID = menuPopup.GetMenuItemID(state.m_nIndex);
if (state.m_nID == 0)
continue;
// menu separator or invalid cmd - ignore it
ATLASSERT(state.m_wndOther.m_hWnd == NULL);
ATLASSERT(state.m_menu.m_hMenu != NULL);
if (state.m_nID == (UINT) -1) {
// possibly a popup menu, route to first item of that popup
state.m_menuSub = menuPopup.GetSubMenu(state.m_nIndex);
if (state.m_menuSub.m_hMenu == NULL
|| ( state.m_nID = state.m_menuSub.GetMenuItemID(0) ) == 0
|| state.m_nID == (UINT) -1)
{
continue; // first item of popup can't be routed to
}
_DoUpdate(&state, false); // popups are never auto disabled
} else {
// normal menu item
// Auto enable/disable if frame window has 's_bAutoMenuEnable'
// set and command is _not_ a system command.
//state.m_menuSub = NULL;
state.m_menuSub.Detach();
_DoUpdate(&state, s_bAutoMenuEnable && state.m_nID < 0xF000);
}
// adjust for menu deletions and additions
UINT nCount = menuPopup.GetMenuItemCount();
if (nCount < state.m_nIndexMax) {
state.m_nIndex -= (state.m_nIndexMax - nCount);
while (state.m_nIndex < nCount
&& menuPopup.GetMenuItemID(state.m_nIndex) == state.m_nID)
{
state.m_nIndex++;
}
}
state.m_nIndexMax = nCount;
} // for
}
public:
void CmdUIUpdateToolBars()
{
for (int i = 0; i < m_arrToolBar.GetSize(); ++i) {
_CmdUIUpdateToolBar(m_arrToolBar[i]);
}
}
private:
void _CmdUIUpdateToolBar(HWND hWndToolBar)
{
// ATLTRACE2(atlTraceGeneral, 4, _T("CUpdateCmdUI::_CmdUIUpdateToolBar\n"));
if ( !::IsWindowVisible(hWndToolBar) )
return;
CToolBarCtrl toolbar(hWndToolBar);
CToolCmdUI state;
state.m_wndOther = hWndToolBar;
state.m_nIndexMax = toolbar.GetButtonCount();
for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax; state.m_nIndex++) {
// get buttons state
TBBUTTON button;
MTLVERIFY( toolbar.GetButton(state.m_nIndex, &button) );
state.m_nID = button.idCommand;
// ignore separators
if ( !(button.fsStyle & TBSTYLE_SEP) ) {
// allow reflections
// if (CWnd::OnCmdMsg(0,
// MAKELONG((int)CN_UPDATE_COMMAND_UI, WM_COMMAND+WM_REFLECT_BASE),
// &state, NULL))
// continue;
// allow the toolbar itself to have update handlers
// if (CWnd::OnCmdMsg(state.m_nID, CN_UPDATE_COMMAND_UI, &state, NULL))
// continue;
// allow the owner to process the update
_DoUpdate(&state, false);
}
}
// update the dialog controls added to the toolbar
//UpdateDialogControls(pTarget, bDisableIfNoHndler);
}
public:
void CmdUIUpdateChildWindow(HWND hWndContainer, int nID)
{
HWND hWndChild = ::GetDlgItem(hWndContainer, nID);
ATLASSERT( ::IsWindow(hWndChild) );
CCmdUI state;
state.m_wndOther = hWndChild;
state.m_nID = nID;
state.m_nIndexMax = 1;
_DoUpdate(&state, false);
}
void CmdUIUpdateStatusBar(HWND hWndStatusBar, int nPaneID)
{
CCmdUI state;
state.m_wndOther = hWndStatusBar;
state.m_nIndexMax = 1;
state.m_nID = nPaneID;
_DoUpdate(&state, false);
}
};
// Update Command UI Chaining Macros
#define CHAIN_UPDATE_COMMAND_UI_MEMBER(theChainMember) \
if ( theChainMember.ProcessCmdUIMap(nID, pCmdUI) ) \
return TRUE;
#define CHAIN_CLIENT_UPDATE_COMMAND_UI() \
if ( ProcessCmdUIToWindow(m_hWndClient, nID, pCmdUI) ) \
return TRUE;
#define CHAIN_MDI_CHILD_UPDATE_COMMAND_UI() \
{ \
HWND hWndActive = MDIGetActive(); \
if ( hWndActive && ProcessCmdUIToWindow(hWndActive, nID, pCmdUI) ) \
return TRUE; \
}
////////////////////////////////////////////////////////////////////////////
} //namespace MTL
#endif // __MTLUPDATECMDUI_H__
| [
"[email protected]"
] | [
[
[
1,
744
]
]
] |
1275d9166ee4db5dab5c1aebc0f2179d77998540 | 9907be749dc7553f97c9e51c5f35e69f55bd02c0 | /WordplaySingle/Wordplay/wordplay_code/Tile.cpp | fc02287347d078a86cb57e51db5b5e46b66dc877 | [] | no_license | jdeering/csci476winthrop | bc8907b9cc0406826de76aca05e6758810377813 | 2bc485781f819c8fd82393ac86de33404e7ad6d3 | refs/heads/master | 2021-01-10T19:53:14.853438 | 2009-04-24T14:26:36 | 2009-04-24T14:26:36 | 32,223,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,976 | cpp | /*
Lauren Cairco
26 February 2009
CSCI 476 Project
Tile.cpp
This file is implementation of Tile.h, the Tile class for use in the Wordplay game module.
Functions are described in the .h file. Cppdocs comments are also found in this file.
*/
#include "Tile.h"
#include <iostream>
//////////////////////////////
// constructors & utilities //
//////////////////////////////
//default constructor
/*********************************************
Default constructor for a Tile object. Uses <code>generateLetter</code> to decide which letter the tile should represent,
sets the <code>letter</code> attribute to that letter, creates a <code>GFSprite</code> for the letter, and assigns it to
the <code>relatedSprite</code> attribute. Also, sets the <code>selected</code> flag to show that the tile is not yet selected.
*********************************************/
Tile::Tile()
{
//generate a tile based on letter distribution
letter = generateLetter();
//get the correct sprite based on the letter we just generated
std::string assetName = "";
assetName = "letter_";
assetName = assetName + letter;
relatedSprite = &GameFramework::createSprite(assetName,0,0,50,50);
//the letter is not yet selected
selected = 0;
}
//returns a letter that's been generated based on the probability of distribution
//of letters in the English language
/*********************************************
Returns a randomly selected letter based on the probability of letter occurence found at http://www.csm.astate.edu/~rossa/datasec/frequency.html.
@return a letter
*********************************************/
char Tile::generateLetter(){
//generate random number between 0 and 100 (double precision)
int leftDecimal = (rand() % 100);
double rightDecimal = (rand() % 1000) / 1000.00;
double n = leftDecimal + rightDecimal;
//depending on where it is in the distribution, return a letter
//distribution based on http://www.csm.astate.edu/~rossa/datasec/frequency.html
if (n < 8.167) return 'a';
else if (n < 9.659) return 'b';
else if (n < 12.441) return 'c';
else if (n < 16.694) return 'd';
else if (n < 29.396) return 'e';
else if (n < 31.624) return 'f';
else if (n < 33.639) return 'g';
else if (n < 39.733) return 'h';
else if (n < 46.729) return 'i';
else if (n < 46.882) return 'j';
else if (n < 47.654) return 'k';
else if (n < 51.679) return 'l';
else if (n < 54.085) return 'm';
else if (n < 60.834) return 'n';
else if (n < 68.341) return 'o';
else if (n < 70.27) return 'p';
else if (n < 70.365) return 'q';
else if (n < 76.352) return 'r';
else if (n < 82.679) return 's';
else if (n < 91.735) return 't';
else if (n < 94.493) return 'u';
else if (n < 95.471) return 'v';
else if (n < 97.831) return 'w';
else if (n < 97.981) return 'x';
else if (n < 99.955) return 'y';
else return 'z';
}
//////////////////////////////////
// attribute returning //
//////////////////////////////////
//returns the letter the tile represents
/*********************************************
Returns the <code>letter</code> attribute of the object.
@return value of <code>letter</code> attribute
*********************************************/
char Tile::getLetter()
{
return letter;
}
//returns whether the tile is selected or not
/*********************************************
Returns the <code>selected</code> attribute of the object. 0 is not selected, 1 is selected
as part of an invalid word, and 2 is selected as part of a valid word. This also corresponds
to the frame number of the <code>GFSprite</code> that should be displayed for this object.
@return value of <code>selected</code> attribute
*********************************************/
int Tile::isSelected()
{
return selected;
}
//returns pointer to the related sprite
/*********************************************
Returns a pointer to the <code>relatedSprite</code> attribute of the object.
@return a pointer to the <code>relatedSprite</code> attribute of the object
*********************************************/
GFSprite * Tile::returnSprite(){
return relatedSprite;
}
//////////////////////////////////
// display functions //
//////////////////////////////////
//places the tile at the given xy coordinates
//used to show the tile initially
/*********************************************
Positions the <code>relatedSprite</code> of the object at (<code>x</code>, <code>y</code>) using the
<code>GFSprite::setSpritePosition</code> function, and sets it visible using the <code>GFSprite::setVisible</code>
function.
@param x desired x position for sprite
@param y desired y position for sprite
*********************************************/
void Tile::showTile(int x, int y)
{
relatedSprite->setSpritePosition(x,y);
relatedSprite->setVisible(true);
//show the letter as unselected
unhighlight();
}
//this is used to slide a tile down
/*********************************************
Makes the sprite associated with the object slide down 50 pixels * <code>spacesToDrop</code>. This is used
in gameplay when replacing letter tiles with the tiles above them. Uses the <code>GFSprite::MoveTo</code> function.
@param spacesToDrop number of tiles the sprite should move down
*********************************************/
void Tile::dropDown(int spacesToDrop)
{
relatedSprite->moveTo(relatedSprite->_x, relatedSprite->_y + (50 * spacesToDrop), 20);
}
/*********************************************
Makes the sprite associated with the object slide down from the top of the screen at (<code>x</code> * 50 + 25, 0) to (<code>x</code> * 50 + 25, <code>y</code> * 50 + 25).
The coefficients and additons are used because of the position of the gameboard in the game play-- <code>x</code> and <code>y</code> are referring to the indices of the
row and column we want this sprite to show up at on the gameboard.
Uses the <code>showTile</code> function to get it in the appropriate starting place, and <code>GFSprite::moveTo</code> to get it to the right place.
@param x x index of where tile should end up on the gameboard
@param y y index of where the tile should end up on the gameboard
*********************************************/
//this is used to slide a tile from the top of the screen
//to the specified spot x-column and y-row
void Tile::slideFromTop(int x, int y)
{
showTile(x * 50 + 25, 0);
//slide to position we want
relatedSprite->moveTo(x * 50 + 25, y * 50 + 25, 20);
}
//show the tile as highlighted and as part of a valid word
/*********************************************
Changes the frame of <code>relatedSprite</code> to frame 2 using <code>GFSprite::setSpriteFrame</code>, and the <code>selected</code>
attribute to 2, to denote that the <code>Tile</code> has been selected as part of a valid word
*********************************************/
void Tile::highlightValid()
{
selected = 2;
relatedSprite->setSpriteFrame(2);
}
//show the tile as highlighted and not a part of a valid word
/*********************************************
Changes the frame of <code>relatedSprite</code> to frame 1 using <code>GFSprite::setSpriteFrame</code>, and the <code>selected</code>
attribute to 1, to denote that the <code>Tile</code> has been selected as part of an invalid word
*********************************************/
void Tile::highlightInvalid()
{
selected = 1;
relatedSprite->setSpriteFrame(1);
}
//show the tile as unselected
/*********************************************
Changes the frame of <code>relatedSprite</code> to frame 0 using <code>GFSprite::setSpriteFrame</code>, and the <code>selected</code>
attribute to 0, to denote that the <code>Tile</code> is not selected
*********************************************/
void Tile::unhighlight()
{
selected = 0;
relatedSprite->setSpriteFrame(0);
} | [
"deeringj2@2656ef14-ecf4-11dd-8fb1-9960f2a117f8",
"lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8"
] | [
[
[
1,
8
],
[
10,
20
],
[
26,
42
],
[
48,
88
],
[
94,
99
],
[
107,
112
],
[
118,
127
],
[
136,
140
],
[
142,
143
],
[
151,
155
],
[
165,
170
],
[
172,
175
],
[
180,
182
],
[
184,
186
],
[
191,
193
],
[
195,
197
],
[
202,
203
],
[
205,
206
]
],
[
[
9,
9
],
[
21,
25
],
[
43,
47
],
[
89,
93
],
[
100,
106
],
[
113,
117
],
[
128,
135
],
[
141,
141
],
[
144,
150
],
[
156,
164
],
[
171,
171
],
[
176,
179
],
[
183,
183
],
[
187,
190
],
[
194,
194
],
[
198,
201
],
[
204,
204
]
]
] |
37a711b74ed0d6d056e0a52dcf7562fb778628cc | 5506729a4934330023f745c3c5497619bddbae1d | /vst2.x/tuio/dev_asio.cpp | 4288537b50943ae9ef471c37b41b27ebfdc09d82 | [] | no_license | berak/vst2.0 | 9e6d1d7246567f367d8ba36cf6f76422f010739e | 9d8f51ad3233b9375f7768be528525c15a2ba7a1 | refs/heads/master | 2020-03-27T05:42:19.762167 | 2011-02-18T13:35:09 | 2011-02-18T13:35:09 | 1,918,997 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 20,569 | cpp | #include <stdio.h>
#include <string.h>
#include "asiosys.h"
#include "asio.h"
#include "asiodrivers.h"
#include "dev_asio.h"
#include "sound.h"
// name of the ASIO device to be used
#if WINDOWS
#define ASIO_DRIVER_NAME "ASIO DirectX Full Duplex Driver"
// #define ASIO_DRIVER_NAME "ASIO Multimedia Driver"
// #define ASIO_DRIVER_NAME "ASIO Sample"
#elif MAC
// #define ASIO_DRIVER_NAME "Apple Sound Manager"
#define ASIO_DRIVER_NAME "ASIO Sample"
#endif
#define TEST_RUN_TIME 20.0 // run for 20 seconds
enum {
// number of input and outputs supported by the host application
// you can change these to higher or lower values
kMaxInputChannels = 32,
kMaxOutputChannels = 32
};
// internal data storage
typedef struct DriverInfo
{
// ASIOInit()
ASIODriverInfo driverInfo;
// ASIOGetChannels()
long inputChannels;
long outputChannels;
// ASIOGetBufferSize()
long minSize;
long maxSize;
long preferredSize;
long granularity;
// ASIOGetSampleRate()
ASIOSampleRate sampleRate;
// ASIOOutputReady()
bool postOutput;
// ASIOGetLatencies ()
long inputLatency;
long outputLatency;
// ASIOCreateBuffers ()
long inputBuffers; // becomes number of actual created input buffers
long outputBuffers; // becomes number of actual created output buffers
ASIOBufferInfo bufferInfos[kMaxInputChannels + kMaxOutputChannels]; // buffer info's
// ASIOGetChannelInfo()
ASIOChannelInfo channelInfos[kMaxInputChannels + kMaxOutputChannels]; // channel info's
// The above two arrays share the same indexing, as the data in them are linked together
// Information from ASIOGetSamplePosition()
// data is converted to double floats for easier use, however 64 bit integer can be used, too
double nanoSeconds;
double samples;
double tcSamples; // time code samples
// bufferSwitchTimeInfo()
ASIOTime tInfo; // time info state
unsigned long sysRefTime; // system reference time, when bufferSwitch() was called
// Signal the end of processing in this example
bool stopped;
} DriverInfo;
DriverInfo asioDriverInfo = {0};
ASIOCallbacks asioCallbacks;
DAsio::Callback doAudioAsio = 0;
//----------------------------------------------------------------------------------
// some external references
extern AsioDrivers* asioDrivers;
bool loadAsioDriver(char *name);
// internal prototypes (required for the Metrowerks CodeWarrior compiler)
//int startupAsio(int argc, char* argv[]);
long init_asio_static_data (DriverInfo *asioDriverInfo);
ASIOError create_asio_buffers (DriverInfo *asioDriverInfo);
unsigned long get_sys_reference_time();
// callback prototypes
void bufferSwitch(long index, ASIOBool processNow);
ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow);
void sampleRateChanged(ASIOSampleRate sRate);
long asioMessages(long selector, long value, void* message, double* opt);
//----------------------------------------------------------------------------------
long init_asio_static_data (DriverInfo *asioDriverInfo)
{ // collect the informational data of the driver
// get the number of available channels
if(ASIOGetChannels(&asioDriverInfo->inputChannels, &asioDriverInfo->outputChannels) == ASE_OK)
{
printf ("ASIOGetChannels (inputs: %d, outputs: %d);\n", asioDriverInfo->inputChannels, asioDriverInfo->outputChannels);
// get the usable buffer sizes
if(ASIOGetBufferSize(&asioDriverInfo->minSize, &asioDriverInfo->maxSize, &asioDriverInfo->preferredSize, &asioDriverInfo->granularity) == ASE_OK)
{
printf ("ASIOGetBufferSize (min: %d, max: %d, preferred: %d, granularity: %d);\n",
asioDriverInfo->minSize, asioDriverInfo->maxSize,
asioDriverInfo->preferredSize, asioDriverInfo->granularity);
// get the currently selected sample rate
if(ASIOGetSampleRate(&asioDriverInfo->sampleRate) == ASE_OK)
{
printf ("ASIOGetSampleRate (sampleRate: %f);\n", asioDriverInfo->sampleRate);
if (asioDriverInfo->sampleRate <= 0.0 || asioDriverInfo->sampleRate > 96000.0)
{
// Driver does not store it's internal sample rate, so set it to a know one.
// Usually you should check beforehand, that the selected sample rate is valid
// with ASIOCanSampleRate().
if(ASIOSetSampleRate(SampleRate) == ASE_OK)
{
if(ASIOGetSampleRate(&asioDriverInfo->sampleRate) == ASE_OK)
printf ("ASIOGetSampleRate (sampleRate: %f);\n", asioDriverInfo->sampleRate);
else
return -6;
}
else
return -5;
}
// check wether the driver requires the ASIOOutputReady() optimization
// (can be used by the driver to reduce output latency by one block)
if(ASIOOutputReady() == ASE_OK)
asioDriverInfo->postOutput = true;
else
asioDriverInfo->postOutput = false;
printf ("ASIOOutputReady(); - %s\n", asioDriverInfo->postOutput ? "Supported" : "Not supported");
return 0;
}
return -3;
}
return -2;
}
return -1;
}
//----------------------------------------------------------------------------------
// conversion from 64 bit ASIOSample/ASIOTimeStamp to double float
#if NATIVE_INT64
#define ASIO64toDouble(a) (a)
#else
const double twoRaisedTo32 = 4294967296.;
#define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32)
#endif
ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow)
{ // the actual processing callback.
// Beware that this is normally in a seperate thread, hence be sure that you take care
// about thread synchronization. This is omitted here for simplicity.
static long processedSamples = 0;
// store the timeInfo for later use
asioDriverInfo.tInfo = *timeInfo;
// get the time stamp of the buffer, not necessary if no
// synchronization to other media is required
if (timeInfo->timeInfo.flags & kSystemTimeValid)
asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime);
else
asioDriverInfo.nanoSeconds = 0;
if (timeInfo->timeInfo.flags & kSamplePositionValid)
asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
else
asioDriverInfo.samples = 0;
if (timeInfo->timeCode.flags & kTcValid)
asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
else
asioDriverInfo.tcSamples = 0;
// get the system reference time
asioDriverInfo.sysRefTime = get_sys_reference_time();
#if WINDOWS && _DEBUG
// a few debug messages for the Windows device driver developer
// tells you the time when driver got its interrupt and the delay until the app receives
// the event notification.
static double last_samples = 0;
char tmp[128];
sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples));
OutputDebugString (tmp);
last_samples = asioDriverInfo.samples;
#endif
// buffer size in samples
long buffSize = asioDriverInfo.preferredSize;
if ( ! doAudioAsio )
return 0;
// perform the processing
short ** b = doAudioAsio(buffSize);
for (int i = 0; i < asioDriverInfo.inputBuffers + asioDriverInfo.outputBuffers; i++)
{
if (asioDriverInfo.bufferInfos[i].isInput == false)
{
// OK do processing for the outputs only
switch (asioDriverInfo.channelInfos[i].type)
{
case ASIOSTInt16LSB:
{
int chan = asioDriverInfo.bufferInfos[i].channelNum;
//memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 2);
memcpy(asioDriverInfo.bufferInfos[i].buffers[index], b[chan], buffSize * 2 );
break;
}
//case ASIOSTInt24LSB: // used for 20 bits as well
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 3);
// break;
//case ASIOSTInt32LSB:
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
//case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
//case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 8);
// break;
// // these are used for 32 bit data buffer, with different alignment of the data inside
// // 32 bit PCI bus systems can more easily used with these
//case ASIOSTInt32LSB16: // 32 bit data with 18 bit alignment
//case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment
//case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment
//case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
//case ASIOSTInt16MSB:
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 2);
// break;
//case ASIOSTInt24MSB: // used for 20 bits as well
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 3);
// break;
//case ASIOSTInt32MSB:
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
//case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
//case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 8);
// break;
// // these are used for 32 bit data buffer, with different alignment of the data inside
// // 32 bit PCI bus systems can more easily used with these
//case ASIOSTInt32MSB16: // 32 bit data with 18 bit alignment
//case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment
//case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment
//case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment
// memset (asioDriverInfo.bufferInfos[i].buffers[index], 0, buffSize * 4);
// break;
default:
printf(" : unknown data format %d !\n", asioDriverInfo.channelInfos[i].type );
break;
}
}
}
// finally if the driver supports the ASIOOutputReady() optimization, do it here, all data are in place
if (asioDriverInfo.postOutput)
ASIOOutputReady();
if (processedSamples >= asioDriverInfo.sampleRate * TEST_RUN_TIME) // roughly measured
asioDriverInfo.stopped = true;
else
processedSamples += buffSize;
return 0L;
}
//----------------------------------------------------------------------------------
void bufferSwitch(long index, ASIOBool processNow)
{ // the actual processing callback.
// Beware that this is normally in a seperate thread, hence be sure that you take care
// about thread synchronization. This is omitted here for simplicity.
// as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs to be created
// though it will only set the timeInfo.samplePosition and timeInfo.systemTime fields and the according flags
ASIOTime timeInfo;
memset (&timeInfo, 0, sizeof (timeInfo));
// get the time stamp of the buffer, not necessary if no
// synchronization to other media is required
if(ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK)
timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid;
bufferSwitchTimeInfo (&timeInfo, index, processNow);
//printf( __FUNCTION__ "(%lu)(%lu)\n", index,asioDriverInfo.granularity );
}
//----------------------------------------------------------------------------------
void sampleRateChanged(ASIOSampleRate sRate)
{
printf( __FUNCTION__ " (%f)\n", sRate );
// do whatever you need to do if the sample rate changed
// usually this only happens during external sync.
// Audio processing is not stopped by the driver, actual sample rate
// might not have even changed, maybe only the sample rate status of an
// AES/EBU or S/PDIF digital input at the audio device.
// You might have to update time/sample related conversion routines, etc.
}
//----------------------------------------------------------------------------------
long asioMessages(long selector, long value, void* message, double* opt)
{
// currently the parameters "value", "message" and "opt" are not used.
long ret = 0;
switch(selector)
{
case kAsioSelectorSupported:
if(value == kAsioResetRequest
|| value == kAsioEngineVersion
|| value == kAsioResyncRequest
|| value == kAsioLatenciesChanged
// the following three were added for ASIO 2.0, you don't necessarily have to support them
|| value == kAsioSupportsTimeInfo
|| value == kAsioSupportsTimeCode
|| value == kAsioSupportsInputMonitor)
ret = 1L;
break;
case kAsioResetRequest:
// defer the task and perform the reset of the driver during the next "safe" situation
// You cannot reset the driver right now, as this code is called from the driver.
// Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction
// Afterwards you initialize the driver again.
asioDriverInfo.stopped; // In this sample the processing will just stop
ret = 1L;
break;
case kAsioResyncRequest:
// This informs the application, that the driver encountered some non fatal data loss.
// It is used for synchronization purposes of different media.
// Added mainly to work around the Win16Mutex problems in Windows 95/98 with the
// Windows Multimedia system, which could loose data because the Mutex was hold too long
// by another thread.
// However a driver can issue it in other situations, too.
ret = 1L;
break;
case kAsioLatenciesChanged:
// This will inform the host application that the drivers were latencies changed.
// Beware, it this does not mean that the buffer sizes have changed!
// You might need to update internal delay data.
ret = 1L;
break;
case kAsioEngineVersion:
// return the supported ASIO version of the host application
// If a host applications does not implement this selector, ASIO 1.0 is assumed
// by the driver
ret = 2L;
break;
case kAsioSupportsTimeInfo:
// informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback
// is supported.
// For compatibility with ASIO 1.0 drivers the host application should always support
// the "old" bufferSwitch method, too.
ret = 1;
break;
case kAsioSupportsTimeCode:
// informs the driver wether application is interested in time code info.
// If an application does not need to know about time code, the driver has less work
// to do.
ret = 0;
break;
}
return ret;
}
//----------------------------------------------------------------------------------
ASIOError create_asio_buffers (DriverInfo *asioDriverInfo)
{ // create buffers for all inputs and outputs of the card with the
// preferredSize from ASIOGetBufferSize() as buffer size
long i;
ASIOError result;
// fill the bufferInfos from the start without a gap
ASIOBufferInfo *info = asioDriverInfo->bufferInfos;
// prepare inputs (Though this is not necessaily required, no opened inputs will work, too
if (asioDriverInfo->inputChannels > kMaxInputChannels)
asioDriverInfo->inputBuffers = kMaxInputChannels;
else
asioDriverInfo->inputBuffers = asioDriverInfo->inputChannels;
for(i = 0; i < asioDriverInfo->inputBuffers; i++, info++)
{
info->isInput = ASIOTrue;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = 0;
}
// prepare outputs
if (asioDriverInfo->outputChannels > kMaxOutputChannels)
asioDriverInfo->outputBuffers = kMaxOutputChannels;
else
asioDriverInfo->outputBuffers = asioDriverInfo->outputChannels;
for(i = 0; i < asioDriverInfo->outputBuffers; i++, info++)
{
info->isInput = ASIOFalse;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = 0;
}
// create and activate buffers
result = ASIOCreateBuffers(asioDriverInfo->bufferInfos,
asioDriverInfo->inputBuffers + asioDriverInfo->outputBuffers,
asioDriverInfo->preferredSize, &asioCallbacks);
if (result == ASE_OK)
{
// now get all the buffer details, sample word length, name, word clock group and activation
for (i = 0; i < asioDriverInfo->inputBuffers + asioDriverInfo->outputBuffers; i++)
{
asioDriverInfo->channelInfos[i].channel = asioDriverInfo->bufferInfos[i].channelNum;
asioDriverInfo->channelInfos[i].isInput = asioDriverInfo->bufferInfos[i].isInput;
result = ASIOGetChannelInfo(&asioDriverInfo->channelInfos[i]);
if (result != ASE_OK)
break;
}
if (result == ASE_OK)
{
// get the input and output latencies
// Latencies often are only valid after ASIOCreateBuffers()
// (input latency is the age of the first sample in the currently returned audio block)
// (output latency is the time the first sample in the currently returned audio block requires to get to the output)
result = ASIOGetLatencies(&asioDriverInfo->inputLatency, &asioDriverInfo->outputLatency);
if (result == ASE_OK)
printf ("ASIOGetLatencies (input: %d, output: %d);\n", asioDriverInfo->inputLatency, asioDriverInfo->outputLatency);
}
}
return result;
}
unsigned long get_sys_reference_time()
{ // get the system reference time
#if WINDOWS
return timeGetTime();
#elif MAC
static const double twoRaisedTo32 = 4294967296.;
UnsignedWide ys;
Microseconds(&ys);
double r = ((double)ys.hi * twoRaisedTo32 + (double)ys.lo);
return (unsigned long)(r / 1000.);
#endif
}
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
DAsio::DAsio()
{
}
bool DAsio::loadDriver( const char * name, DAsio::Callback cb )
{
doAudioAsio = cb;
// load the driver, this will setup all the necessary internal data structures
if ( ! loadAsioDriver ((char*)name) )
{
printf( __FUNCTION__ " : DRIVER '%s' NOT LOADED !\n", name );
return 0;
}
// initialize the driver
if ( ASIOInit (&asioDriverInfo.driverInfo) != ASE_OK)
{
printf( __FUNCTION__ " : ASIOInit '%s' failed !\n", name );
return 0;
}
printf ("asioVersion: %d\n"
"driverVersion: %d\n"
"Name: %s\n"
"ErrorMessage: %s\n",
asioDriverInfo.driverInfo.asioVersion, asioDriverInfo.driverInfo.driverVersion,
asioDriverInfo.driverInfo.name, asioDriverInfo.driverInfo.errorMessage);
if ( init_asio_static_data (&asioDriverInfo) != ASE_OK )
{
printf( __FUNCTION__ " : init '%s' failed !\n", name );
return 0;
}
// ASIOControlPanel(); //you might want to check wether the ASIOControlPanel() can open
// set up the asioCallback structure and create the ASIO data buffer
asioCallbacks.bufferSwitch = &bufferSwitch;
asioCallbacks.sampleRateDidChange = &sampleRateChanged;
asioCallbacks.asioMessage = &asioMessages;
asioCallbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfo;
if ( create_asio_buffers (&asioDriverInfo) != ASE_OK )
{
printf( __FUNCTION__ " : create_asio_buffers '%s' failed !\n", name );
return 0;
}
return 1;
}
bool DAsio::startDriver()
{
if ( ASIOStart() != ASE_OK )
{
printf( __FUNCTION__ " : ASIOStart '%s' failed !\n", asioDriverInfo.driverInfo.name );
return false;
}
fprintf (stdout, "\n%s started succefully.\n\n", asioDriverInfo.driverInfo.name );
return true;
}
bool DAsio::stopDriver()
{
return ( ASIOStop() == ASE_OK );
}
bool DAsio::unloadDriver()
{
if ( ! asioDriverInfo.driverInfo.asioVersion )
return false;
if ( ASIOStop() != ASE_OK ) return false;
if ( ASIODisposeBuffers() != ASE_OK ) return false;
ASIOExit();
if ( asioDrivers->asioGetNumDev() )
{
asioDrivers->removeCurrentDriver();
}
asioDriverInfo.driverInfo.asioVersion = 0;
return true;
}
DAsio::~DAsio()
{
unloadDriver();
}
| [
"[email protected]"
] | [
[
[
1,
569
]
]
] |
0047e3ecab730640d0e7b36165b9aec56cdb696f | 27bde5e083cf5a32f75de64421ba541b3a23dd29 | /external/GameX/source/gamex-image-bmp.cpp | 69c342d02eba4f05f6d2975e587d47dde42b74d0 | [] | no_license | jbsheblak/fatal-inflation | 229fc6111039aff4fd00bb1609964cf37e4303af | 5d6c0a99e8c4791336cf529ed8ce63911a297a23 | refs/heads/master | 2021-03-12T19:22:31.878561 | 2006-10-20T21:48:17 | 2006-10-20T21:48:17 | 32,184,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,970 | cpp | //
// GameX - BMP/JPG/GIF-Handling Code
//
// This software is released under the GameX GNU GPL
// Open Source License. See the GameX documentation included
// with this source code for terms of modification,
// distribution and re-release.
//
//**************************************
//
// BMP Format - File Format support for ImageExtender class
//
// NOTE: CURRENT CAPABILITIES:
// - Load supports:
// 8 bit indexed color (no alpha)
// 16 bit X1-R5-G5-B5 (without alpha)
// 24 bit R8-G8-B8 (without alpha)
// 32 bit A8-R8-G8-B8 (with alpha)
// - Save supports:
// 16 bit X1-R5-G5-B5 (without alpha)
// 32 bit A8-R8-G8-B8 (with alpha)
//
// Other Formats: Can load JPG and GIF files (without alpha)
//
//**************************************
#include "gamex-image-bmp.hpp"
#include <olectl.h> // required for JPG/GIF reading
// (also need to link with ole32.lib and oleaut32.lib)
#pragma comment(lib,"ole32.lib") // auto-link ole32.lib
#pragma comment(lib,"oleaut32.lib ") // auto-link oleaut32.lib
char last_filename [MAX_PATH];
// Function: LoadBMP
//
// filename Name of BMP file to load
// img ImageX object to fill with image data from bitmap
bool ImageExt::LoadBMP (char *filename, ImageX *img)
{
if(strcmp(last_filename, filename)==0) // sometimes Windows inserts GUI element graphics where the BMP should be
Sleep(120); // when loading the same file twice in a row without waiting a bit in-between
m_pImg = img;
strcpy (m_filename, filename);
strcpy (last_filename, filename);
// actually load the bitmap from file:
HBITMAP hbmp = (HBITMAP) LoadImage(NULL,filename,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION);
if(hbmp == NULL) {
return false;
} else {
bool retVal = InterpretBits(hbmp); // interpret the bitmap data and return whether we succeeded:
DeleteObject(hbmp);
return retVal;
}
}
// can load JPEG and GIF files (can also load BMP, WMF, and TIF, if they are in 24 bit format)
bool ImageExt::LoadJPGorGIF (char *filename, ImageX *img)
{
m_pImg = img;
strcpy (m_filename, filename);
IPicture * picture;
IStream * stream;
HGLOBAL hGlobal;
FILE * file;
file = fopen(filename,"rb"); // open file in read only mode
if(file == NULL)
return false;
fseek(file,0,SEEK_END);
int file_size = ftell(file);
fseek(file,0,SEEK_SET);
hGlobal = GlobalAlloc(GPTR, file_size); // allocates 112 k
if(hGlobal == NULL) {
fclose(file);
return false;
}
fread((void*)hGlobal, 1, file_size, file);
fclose(file);
CreateStreamOnHGlobal(hGlobal,false,&stream);
if(stream == NULL) {
GlobalFree(hGlobal);
return false;
}
// Decompress and load the JPG or GIF
OleLoadPicture(stream,0,false,IID_IPicture,(void**)&picture); // 42,804 -> 43,844
if(picture == NULL) { // allocates 1052 k
stream->Release();
GlobalFree(hGlobal);
return false;
}
stream->Release();
GlobalFree(hGlobal); // deallocates 52 k
HBITMAP hB = 0;
picture->get_Handle((unsigned int*)&hB);
if(hB == 0) return false;
HBITMAP hbmp = (HBITMAP)CopyImage(hB,IMAGE_BITMAP,0,0,LR_COPYRETURNORG);
if(hbmp == 0) return false;
picture->Release(); // deallocates 1024 k
bool retVal = InterpretBits(hbmp);
if(hB) DeleteObject(hB);
if(hbmp) DeleteObject(hbmp);
return retVal;
}
bool ImageExt::InterpretBits(HBITMAP hbmp)
{
HBITMAP hbmp2;
bool noMerge = false;
bool ok = false;
if(hbmp) {
BITMAP bitmap;
LPVOID bits;
GetObject(hbmp,sizeof(bitmap),&bitmap);
if(bitmap.bmBits != NULL) {
// if the bits are conveniently where one would expect them to be (BMP)
bits = bitmap.bmBits;
} else {
// if we have to do a little more work to locate the bits (JPG, GIF)
int success = false;
HDC hdc = CreateCompatibleDC(NULL); // DC for Source Bitmap
if(hdc) {
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdc,hbmp);
// here hdc contains the bitmap
HDC hdc2 = CreateCompatibleDC(NULL); // DC for working
if (hdc2) {
// get bitmap size
BITMAP bm;
GetObject(hbmp, sizeof(bm), &bm);
BITMAPINFO bitmapinfo;
ZeroMemory(&bitmapinfo, sizeof(BITMAPINFO));
bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapinfo.bmiHeader.biWidth = bm.bmWidth;
bitmapinfo.bmiHeader.biHeight = bm.bmHeight;
bitmapinfo.bmiHeader.biPlanes = bm.bmPlanes;
bitmapinfo.bmiHeader.biBitCount = 32;
noMerge = true; // prevent from assuming 32-bit means alpha information
UINT * pixels;
hbmp2 = CreateDIBSection(hdc2, (BITMAPINFO *)&bitmapinfo,
DIB_RGB_COLORS, (void **)&pixels,
NULL, 0);
if(hbmp2) {
HBITMAP hOldBitmap2 = (HBITMAP)SelectObject(hdc2, hbmp2);
BitBlt(hdc2,0,0,
bm.bmWidth,bm.bmHeight,
hdc,0,0,SRCCOPY); // 42,768 -> 44,816
SelectObject(hdc2, hOldBitmap2);
success = true;
bits = pixels;
bitmap.bmBitsPixel = bitmapinfo.bmiHeader.biBitCount;
m_pImg->m_xres = bm.bmWidth;
m_pImg->m_yres = bm.bmHeight;
bitmap.bmWidthBytes = m_pImg->m_xres*bitmap.bmBitsPixel/8;
}
}
SelectObject(hdc,hOldBitmap);
if(hdc2) DeleteDC(hdc2);
}
if(hdc) DeleteDC(hdc);
if(!success) {
/// if(bits) DeleteObject((HGDIOBJ) bits);
return false;
}
}
/* if(bitmap.bmWidth > 2048 || bitmap.bmHeight > 2048) {
char errstr [256];
sprintf(errstr,"The %dx%d image in file %s is too large for GameX to use.\nNeither width nor height may exceed 2048 pixels.",bitmap.bmWidth,bitmap.bmHeight,m_filename);
MessageBox (NULL, errstr, "GameX Error", MB_OK|MB_ICONSTOP);
if(bitmap.bmWidth > 2048) bitmap.bmWidth = 2048;
if(bitmap.bmHeight > 2048) bitmap.bmHeight = 2048;
}
*/
int pitch = bitmap.bmWidthBytes;
switch(bitmap.bmBitsPixel)
{
case 8: {
HDC hdc = CreateCompatibleDC(NULL);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdc, hbmp);
RGBQUAD palette[256];
GetDIBColorTable(hdc, 0, 256, palette);
m_pImg->Size(bitmap.bmWidth, bitmap.bmHeight, IMG_TRUECOLOR);
XBYTE * pData = (XBYTE *) m_pImg->m_data;
XBYTE * bmpData = (XBYTE *) bits;
for(int y = 0 ; y < m_pImg->m_yres ; y++)
for(int x = 0 ; x < m_pImg->m_xres ; x++) {
int n = (x+y*m_pImg->m_xres)*3; // pixel address -- destination
int yi = m_pImg->m_yres-y-1; // inverted y, because bmp's are stored upside-down
int ni = x+yi*pitch; // inverted pixel address -- source
pData[n+2] = palette[bmpData[ni]].rgbBlue; // blue
pData[n+1] = palette[bmpData[ni]].rgbGreen; // green
pData[n] = palette[bmpData[ni]].rgbRed; // red
}
SelectObject(hdc, hOldBitmap);
if(hdc) DeleteDC(hdc);
break;
}
case 16: {
int bmp_mask_red = 0x7C00, bmp_mask_green = 0x03E0, bmp_mask_blue = 0x001F;
int bmp_shift_red, bmp_shift_green;
bmp_shift_red = GameX.GetShift(bmp_mask_red);
bmp_shift_green = GameX.GetShift(bmp_mask_green);
m_pImg->Size(bitmap.bmWidth, bitmap.bmHeight, IMG_HIGHCOLOR);
XBYTE2 * pData = (XBYTE2 *) m_pImg->m_data;
XBYTE2 * bmpData = (XBYTE2 *) bits;
for(int y = 0 ; y < m_pImg->m_yres ; y++)
for(int x = 0 ; x < m_pImg->m_xres ; x++) {
int n = x+y*m_pImg->m_xres; // pixel address -- destination
int yi = m_pImg->m_yres-y-1; // inverted y, because bmp's are stored upside-down
int ni = x+yi*pitch/2; // inverted pixel address -- source
int clr = bmpData[ni] ;
int blue = clr & bmp_mask_blue; // decode blue
int green = (clr & bmp_mask_green) >> (bmp_shift_green-1); // decode green
int red = (clr & bmp_mask_red) >> bmp_shift_red; // decode red
pData[n] = ((red << 11) + (green << 5) + blue); // re-encode
}
} break;
case 24: {
m_pImg->Size(bitmap.bmWidth, bitmap.bmHeight, IMG_TRUECOLOR);
XBYTE * pData = (XBYTE *) m_pImg->m_data;
XBYTE * bmpData = (XBYTE *) bits;
for(int y = 0 ; y < m_pImg->m_yres ; y++)
for(int x = 0 ; x < 3*m_pImg->m_xres ; x+=3) {
int n = x+y*m_pImg->m_xres*3; // pixel address -- destination
int yi = m_pImg->m_yres-y-1; // inverted y, because bmp's are stored upside-down
int ni = x+yi*pitch; // inverted pixel address -- source
pData[n+2] = bmpData[ni]; // blue // (not only is it upside-down, but RGB is backwards)
pData[n+1] = bmpData[ni+1]; // green
pData[n] = bmpData[ni+2]; // red
}
} break;
case 32: {
if(noMerge) m_pImg->Size(bitmap.bmWidth, bitmap.bmHeight, IMG_TRUECOLORX);
else m_pImg->Size(bitmap.bmWidth, bitmap.bmHeight, IMG_TRUECOLORX|IMG_MERGEALPHA);
XBYTE * pData = (XBYTE *) m_pImg->m_data;
XBYTE * bmpData = (XBYTE *) bits;
for(int y = 0 ; y < m_pImg->m_yres ; y++)
for(int x = 0 ; x < 4*m_pImg->m_xres ; x+=4) {
int n = x+y*m_pImg->m_xres*4; // pixel address -- destination
int yi = m_pImg->m_yres-y-1; // inverted y, because bmp's are stored upside-down
int ni = x+yi*pitch; // inverted pixel address -- source
pData[n+3] = bmpData[ni+3]; // alpha
pData[n+2] = bmpData[ni+2]; // red
pData[n+1] = bmpData[ni+1]; // green
pData[n] = bmpData[ni]; // blue
}
} break;
}
DeleteObject(hbmp2);
ok = true;
}
return ok;
}
bool ImageExt::SaveBmp(char *filename, HBITMAP hBitmap)
{
bool ok = true;
BITMAPINFO bmpInfo;
ZeroMemory (&bmpInfo,sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
HDC hdc = GetDC(NULL);
GetDIBits (hdc, hBitmap, 0, 0, NULL, &bmpInfo, DIB_RGB_COLORS);
if(bmpInfo.bmiHeader.biSizeImage <= 0)
bmpInfo.bmiHeader.biSizeImage = bmpInfo.bmiHeader.biWidth * abs(bmpInfo.bmiHeader.biHeight) * (bmpInfo.bmiHeader.biBitCount+7) / 8;
LPVOID pixelBuffer = malloc(bmpInfo.bmiHeader.biSizeImage);
if(pixelBuffer != NULL) {
bmpInfo.bmiHeader.biCompression=BI_RGB;
GetDIBits(hdc,hBitmap,0,bmpInfo.bmiHeader.biHeight,pixelBuffer, &bmpInfo, DIB_RGB_COLORS);
FILE* file = fopen(filename,"wb");
if(file != NULL) {
BITMAPFILEHEADER bmpFileHeader;
bmpFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmpFileHeader.bfReserved1 = 0;
bmpFileHeader.bfReserved2 = 0;
bmpFileHeader.bfSize = bmpFileHeader.bfOffBits + bmpInfo.bmiHeader.biSizeImage;
bmpFileHeader.bfType = 'MB';
fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,file);
fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,file);
fwrite(pixelBuffer,bmpInfo.bmiHeader.biSizeImage,1,file);
} else {
debug.Output("ImageExt::SaveBmp: Unable to Create Bitmap File");
ok = false;
}
if(file) fclose(file);
} else {
debug.Output("ImageExt::SaveBmp: Unable to Allocate Bitmap Memory");
ok = false;
}
if(hdc) ReleaseDC(NULL,hdc);
if(pixelBuffer) free(pixelBuffer);
return ok;
}
| [
"jbsheblak@5660b91f-811d-0410-8070-91869aa11e15"
] | [
[
[
1,
326
]
]
] |
25500b01c651827a85549b6b2f7ac9bdd9aff15e | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/GridCtrl/GridCellBase.cpp | bcb91b7f8899e5ddf9f8f596471a65cf80baa154 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,801 | cpp | // GridCellBase.cpp : implementation file
//
// MFC Grid Control - Main grid cell base class
//
// Provides the implementation for the base cell type of the
// grid control. No data is stored (except for state) but default
// implementations of drawing, printingetc provided. MUST be derived
// from to be used.
//
// Written by Chris Maunder <[email protected]>
// Copyright (c) 1998-2000. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20
//
// History:
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// C Maunder - 19 May 2000 - Fixed sort arrow drawing (Ivan Ilinov)
// C Maunder - 29 Aug 2000 - operator= checks for NULL font before setting (Martin Richter)
//
// NOTES: Each grid cell should take care of it's own drawing, though the Draw()
// method takes an "erase background" paramter that is called if the grid
// decides to draw the entire grid background in on hit. Certain ambient
// properties such as the default font to use, and hints on how to draw
// fixed cells should be fetched from the parent grid. The grid trusts the
// cells will behave in a certain way, and the cells trust the grid will
// supply accurate information.
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCtrl.h"
#include "GridCellBase.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCellBase, CObject)
/////////////////////////////////////////////////////////////////////////////
// GridCellBase
CGridCellBase::CGridCellBase()
{
Reset();
}
CGridCellBase::~CGridCellBase()
{
}
/////////////////////////////////////////////////////////////////////////////
// GridCellBase Operations
void CGridCellBase::Reset()
{
m_nState = 0;
}
void CGridCellBase::operator=(const CGridCellBase& cell)
{
SetGrid(cell.GetGrid()); // do first in case of dependencies
SetText(cell.GetText());
SetImage(cell.GetImage());
SetData(cell.GetData());
SetState(cell.GetState());
SetFormat(cell.GetFormat());
SetTextClr(cell.GetTextClr());
SetBackClr(cell.GetBackClr());
SetFont(cell.IsDefaultFont()? NULL : cell.GetFont());
SetMargin(cell.GetMargin());
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
// Returns a pointer to a cell that holds default values for this particular type of cell
CGridCellBase* CGridCellBase::GetDefaultCell() const
{
if (GetGrid())
return GetGrid()->GetDefaultCell(IsFixedRow(), IsFixedCol());
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
// EFW - Various changes to make it draw cells better when using alternate
// color schemes. Also removed printing references as that's now done
// by PrintCell() and fixed the sort marker so that it doesn't draw out
// of bounds.
BOOL CGridCellBase::Draw(CDC* pDC, int nRow, int nCol, CRect rect, BOOL bEraseBkgnd /*=TRUE*/)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0 || rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
//TRACE3("Drawing %scell %d, %d\n", IsFixed()? _T("Fixed ") : _T(""), nRow, nCol);
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Set up text and background colours
COLORREF TextClr, TextBkClr;
TextClr = (GetTextClr() == CLR_DEFAULT)? pDefaultCell->GetTextClr() : GetTextClr();
if (GetBackClr() == CLR_DEFAULT)
TextBkClr = pDefaultCell->GetBackClr();
else
{
bEraseBkgnd = TRUE;
TextBkClr = GetBackClr();
}
// Draw cell background and highlighting (if necessary)
if ( IsFocused() || IsDropHighlighted() )
{
// Always draw even in list mode so that we can tell where the
// cursor is at. Use the highlight colors though.
if(GetState() & GVIS_SELECTED)
{
TextBkClr = ::GetSysColor(COLOR_HIGHLIGHT);
TextClr = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
bEraseBkgnd = TRUE;
}
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
if (bEraseBkgnd)
{
TRY
{
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
// Don't adjust frame rect if no grid lines so that the
// whole cell is enclosed.
if(pGrid->GetGridLines() != GVL_NONE)
{
rect.right--;
rect.bottom--;
}
if (pGrid->GetFrameFocusCell())
{
// Use same color as text to outline the cell so that it shows
// up if the background is black.
TRY
{
CBrush brush(TextClr);
pDC->FrameRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
pDC->SetTextColor(TextClr);
// Adjust rect after frame draw if no grid lines
if(pGrid->GetGridLines() == GVL_NONE)
{
rect.right--;
rect.bottom--;
}
rect.DeflateRect(1,1);
}
else if ((GetState() & GVIS_SELECTED))
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
pDC->FillSolidRect(rect, ::GetSysColor(COLOR_HIGHLIGHT));
rect.right--; rect.bottom--;
pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
if (bEraseBkgnd)
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
pDC->SetTextColor(TextClr);
}
// Draw lines only when wanted
if (IsFixed() && pGrid->GetGridLines() != GVL_NONE)
{
CCellID FocusCell = pGrid->GetFocusCell();
// As above, always show current location even in list mode so
// that we know where the cursor is at.
BOOL bHiliteFixed = pGrid->GetTrackFocusCell() && pGrid->IsValid(FocusCell) &&
(FocusCell.row == nRow || FocusCell.col == nCol);
// If this fixed cell is on the same row/col as the focus cell,
// highlight it.
if (bHiliteFixed)
{
rect.right++; rect.bottom++;
pDC->DrawEdge(rect, BDR_SUNKENINNER /*EDGE_RAISED*/, BF_RECT);
rect.DeflateRect(1,1);
}
else
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(pOldPen);
rect.DeflateRect(1,1);
}
}
// Draw Text and image
CFont* pFont = GetFontObject();
ASSERT(pFont);
if (pFont)
pDC->SelectObject(pFont);
rect.DeflateRect(GetMargin(), 0);
if (pGrid->GetImageList() && GetImage() >= 0)
{
IMAGEINFO Info;
if (pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
// would like to use a clipping region but seems to have issue
// working with CMemDC directly. Instead, don't display image
// if any part of it cut-off
//
// CRgn rgn;
// rgn.CreateRectRgnIndirect(rect);
// pDC->SelectClipRgn(&rgn);
// rgn.DeleteObject();
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
int nImageHeight = Info.rcImage.bottom-Info.rcImage.top+1;
if( nImageWidth + rect.left <= rect.right + (int)(2*GetMargin())
&& nImageHeight + rect.top <= rect.bottom + (int)(2*GetMargin()) )
{
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
}
rect.left += nImageWidth+GetMargin();
}
}
// Draw sort arrow
if (pGrid->GetSortColumn() == nCol && nRow == 0)
{
CSize size = pDC->GetTextExtent(_T("M"));
int nOffset = 2;
// Base the size of the triangle on the smaller of the column
// height or text height with a slight offset top and bottom.
// Otherwise, it can get drawn outside the bounds of the cell.
size.cy -= (nOffset * 2);
if (size.cy >= rect.Height())
size.cy = rect.Height() - (nOffset * 2);
size.cx = size.cy; // Make the dimensions square
// Kludge for vertical text
BOOL bVertical = (GetFont()->lfEscapement == 900);
// Only draw if it'll fit!
if (size.cx + rect.left < rect.right + (int)(2*GetMargin()))
{
int nTriangleBase = rect.bottom - nOffset - size.cy; // Triangle bottom right
//int nTriangleBase = (rect.top + rect.bottom - size.cy)/2; // Triangle middle right
//int nTriangleBase = rect.top + nOffset; // Triangle top right
//int nTriangleLeft = rect.right - size.cx; // Triangle RHS
//int nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
//int nTriangleLeft = rect.left; // Triangle LHS
int nTriangleLeft;
if (bVertical)
nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
else
nTriangleLeft = rect.right - size.cx; // Triangle RHS
CPen penShadow(PS_SOLID, 0, ::GetSysColor(COLOR_3DSHADOW));
CPen penLight(PS_SOLID, 0, ::GetSysColor(COLOR_3DHILIGHT));
if (pGrid->GetSortAscending())
{
// Draw triangle pointing upwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->SelectObject(pOldPen);
}
else
{
// Draw triangle pointing downwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + size.cy + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase );
pDC->LineTo( nTriangleLeft, nTriangleBase );
pDC->SelectObject(pOldPen);
}
if (!bVertical)
rect.right -= size.cy;
}
}
// We want to see '&' characters so use DT_NOPREFIX
DrawText(pDC->m_hDC, GetText(), -1, rect, GetFormat() | DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Mouse and Cursor events
// Not yet implemented
void CGridCellBase::OnMouseEnter()
{
TRACE0("Mouse entered cell\n");
}
void CGridCellBase::OnMouseOver()
{
//TRACE0("Mouse over cell\n");
}
// Not Yet Implemented
void CGridCellBase::OnMouseLeave()
{
TRACE0("Mouse left cell\n");
}
void CGridCellBase::OnClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn up in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnClickDown( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn down in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnRClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse right-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnDblClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse double-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
// Return TRUE if you set the cursor
BOOL CGridCellBase::OnSetCursor()
{
#ifndef _WIN32_WCE_NO_CURSOR
SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
#endif
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Sizing
BOOL CGridCellBase::GetTextRect( LPRECT pRect) // i/o: i=dims of cell rect; o=dims of text rect
{
if (GetImage() >= 0)
{
IMAGEINFO Info;
CGridCtrl* pGrid = GetGrid();
CImageList* pImageList = pGrid->GetImageList();
if (pImageList->GetImageInfo( GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
pRect->left += nImageWidth + GetMargin();
}
}
return TRUE;
}
// By default this uses the selected font (which is a bigger font)
CSize CGridCellBase::GetTextExtent(LPCTSTR szText, CDC* pDC /*= NULL*/)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
BOOL bReleaseDC = FALSE;
if (pDC == NULL)
{
pDC = pGrid->GetDC();
if (!pDC)
{
CGridDefaultCell* pDefCell = (CGridDefaultCell*) GetDefaultCell();
ASSERT(pDefCell);
return CSize(pDefCell->GetWidth(), pDefCell->GetHeight());
}
bReleaseDC = TRUE;
}
CFont *pOldFont = NULL,
*pFont = GetFontObject();
if (pFont)
pOldFont = pDC->SelectObject(pFont);
CSize size;
int nFormat = GetFormat();
// If the cell is a multiline cell, then use the width of the cell
// to get the height
if ((nFormat & DT_WORDBREAK) && !(nFormat & DT_SINGLELINE))
{
CString str = szText;
int nMaxWidth = 0;
while (TRUE)
{
int nPos = str.Find(_T('\n'));
CString TempStr = (nPos < 0)? str : str.Left(nPos);
int nTempWidth = pDC->GetTextExtent(TempStr).cx;
if (nTempWidth > nMaxWidth)
nMaxWidth = nTempWidth;
if (nPos < 0)
break;
str = str.Mid(nPos + 1); // Bug fix by Thomas Steinborn
}
CRect rect;
rect.SetRect(0,0, nMaxWidth, 0);
pDC->DrawText(szText, -1, rect, nFormat | DT_CALCRECT);
size = rect.Size();
}
else
size = pDC->GetTextExtent(szText, _tcslen(szText));
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
size.cx += (tm.tmOverhang);
if (pOldFont)
pDC->SelectObject(pOldFont);
size += CSize(4*GetMargin(), 2*GetMargin());
// Kludge for vertical text
LOGFONT *pLF = GetFont();
if (pLF->lfEscapement == 900 || pLF->lfEscapement == -900)
{
int nTemp = size.cx;
size.cx = size.cy;
size.cy = nTemp;
size += CSize(0, 4*GetMargin());
}
if (bReleaseDC)
pGrid->ReleaseDC(pDC);
return size;
}
CSize CGridCellBase::GetCellExtent(CDC* pDC)
{
CSize size = GetTextExtent(GetText(), pDC);
CSize ImageSize(0,0);
int nImage = GetImage();
if (nImage >= 0)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
if (pGrid->GetImageList())
{
IMAGEINFO Info;
if (pGrid->GetImageList()->GetImageInfo(nImage, &Info))
ImageSize = CSize(Info.rcImage.right-Info.rcImage.left+1,
Info.rcImage.bottom-Info.rcImage.top+1);
}
}
return CSize(size.cx + ImageSize.cx, max(size.cy, ImageSize.cy));
}
// EFW - Added to print cells so that grids that use different colors are
// printed correctly.
BOOL CGridCellBase::PrintCell(CDC* pDC, int /*nRow*/, int /*nCol*/, CRect rect)
{
#if defined(_WIN32_WCE_NO_PRINTING) || defined(GRIDCONTROL_NO_PRINTING)
return FALSE;
#else
COLORREF crFG, crBG;
GV_ITEM Item;
CGridCtrl* pGrid = GetGrid();
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0
|| rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
if(pGrid->GetShadedPrintOut())
{
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Use custom color if it doesn't match the default color and the
// default grid background color. If not, leave it alone.
if(IsFixed())
crBG = (GetBackClr() != CLR_DEFAULT) ? GetBackClr() : pDefaultCell->GetBackClr();
else
crBG = (GetBackClr() != CLR_DEFAULT && GetBackClr() != pDefaultCell->GetBackClr()) ?
GetBackClr() : CLR_DEFAULT;
// Use custom color if the background is different or if it doesn't
// match the default color and the default grid text color. If not,
// use black to guarantee the text is visible.
if(IsFixed())
crFG = (GetBackClr() != CLR_DEFAULT) ? GetTextClr() : pDefaultCell->GetTextClr();
else
crFG = (GetBackClr() != CLR_DEFAULT ||
(GetTextClr() != CLR_DEFAULT && GetTextClr() != pDefaultCell->GetTextClr())) ?
GetTextClr() : RGB(0, 0, 0);
// If not printing on a color printer, adjust the foreground color
// to a gray scale if the background color isn't used so that all
// colors will be visible. If not, some colors turn to solid black
// or white when printed and may not show up. This may be caused by
// coarse dithering by the printer driver too (see image note below).
if(pDC->GetDeviceCaps(NUMCOLORS) == 2 && crBG == CLR_DEFAULT)
crFG = RGB(GetRValue(crFG) * 0.30, GetGValue(crFG) * 0.59,
GetBValue(crFG) * 0.11);
// Only erase the background if the color is not the default
// grid background color.
if(crBG != CLR_DEFAULT)
{
CBrush brush(crBG);
rect.right++; rect.bottom++;
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
}
else
{
crBG = CLR_DEFAULT;
crFG = RGB(0, 0, 0);
}
pDC->SetTextColor(crFG);
CFont *pFont = GetFontObject();
if (pFont)
pDC->SelectObject(pFont);
/*
// ***************************************************
// Disabled - if you need this functionality then you'll need to rewrite.
// Create the appropriate font and select into DC.
CFont Font;
// Bold the fixed cells if not shading the print out. Use italic
// font it it is enabled.
const LOGFONT* plfFont = GetFont();
if(IsFixed() && !pGrid->GetShadedPrintOut())
{
Font.CreateFont(plfFont->lfHeight, 0, 0, 0, FW_BOLD, plfFont->lfItalic, 0, 0,
ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
#ifndef _WIN32_WCE
PROOF_QUALITY,
#else
DEFAULT_QUALITY,
#endif
VARIABLE_PITCH | FF_SWISS, plfFont->lfFaceName);
}
else
Font.CreateFontIndirect(plfFont);
pDC->SelectObject(&Font);
// ***************************************************
*/
// Draw lines only when wanted on fixed cells. Normal cell grid lines
// are handled in OnPrint.
if(pGrid->GetGridLines() != GVL_NONE && IsFixed())
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
rect.DeflateRect(1,1);
pDC->SelectObject(pOldPen);
}
rect.DeflateRect(GetMargin(), 0);
if(pGrid->GetImageList() && GetImage() >= 0)
{
// NOTE: If your printed images look like fuzzy garbage, check the
// settings on your printer driver. If it's using coarse
// dithering and/or vector graphics, they may print wrong.
// Changing to fine dithering and raster graphics makes them
// print properly. My HP 4L had that problem.
IMAGEINFO Info;
if(pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left;
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
rect.left += nImageWidth+GetMargin();
}
}
// Draw without clipping so as not to lose text when printed for real
DrawText(pDC->m_hDC, GetText(), -1, rect,
GetFormat() | DT_NOCLIP | DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
#endif
}
/*****************************************************************************
Callable by derived classes, only
*****************************************************************************/
LRESULT CGridCellBase::SendMessageToParent(int nRow, int nCol, int nMessage)
{
CGridCtrl* pGrid = GetGrid();
if( pGrid)
return pGrid->SendMessageToParent(nRow, nCol, nMessage);
else
return 0;
} | [
"[email protected]"
] | [
[
[
1,
723
]
]
] |
2a1a215a45a8a0a3e3d4dee52681bbc6261ed47d | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/UILayer/SearchResultsWnd.cpp | 2c3af73a4292a84df6992281119fb5e6eb00ead4 | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 67,062 | cpp | /*
* $Id: SearchResultsWnd.cpp 18513 2010-03-24 09:41:45Z huby $
*
* 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.
*/
#include "stdafx.h"
#include "emule.h"
#include "SearchDlg.h"
#include "SearchResultsWnd.h"
#include "SearchParamsWnd.h"
#include "SearchParams.h"
#include "Packets.h"
#include "OtherFunctions.h"
#include "SearchFile.h"
#include "SearchList.h"
#include "Sockets.h"
#include "ServerList.h"
#include "Server.h"
#include "SafeFile.h"
#include "DownloadQueue.h"
#include "Statistics.h"
#include "emuledlg.h"
#include "opcodes.h"
#include "ED2KLink.h"
#include "Kademlia/Kademlia/Kademlia.h"
#include "kademlia/kademlia/SearchManager.h"
#include "kademlia/kademlia/search.h"
#include "SearchExpr.h"
#define USE_FLEX
#include "Parser.hpp"
#include "Scanner.h"
#include "HelpIDs.h"
#include "Exceptions.h"
#include "StringConversion.h"
#include "UserMsgs.h"
#include "webbrowserWnd.h" //Added by thilon on 2006.08 for VeryCD Search
#include "Log.h"
#include "MenuCmds.h"
#include "DropDownButton.h"
#include "CmdFuncs.h"
#include ".\searchresultswnd.h"
#include "SearchParams.h"
#include "StatForServer.h"
#include "WorkLayer/FileSearch.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern int yyparse();
extern int yyerror(const char* errstr);
extern int yyerror(LPCTSTR errstr);
extern LPCTSTR _aszInvKadKeywordChars;
enum ESearchTimerID
{
TimerServerTimeout = 1,
TimerGlobalSearch
};
enum ESearchResultImage
{
sriServerActive,
sriGlobalActive,
sriKadActice,
sriClient,
sriServer,
sriGlobal,
sriKad
};
#define SEARCH_LIST_MENU_BUTTON_XOFF 8
#define SEARCH_LIST_MENU_BUTTON_WIDTH 170
#define SEARCH_LIST_MENU_BUTTON_HEIGHT 22 // don't set the height do something different than 22 unless you know exactly what you are doing!
// CSearchResultsWnd dialog
IMPLEMENT_DYNCREATE(CSearchResultsWnd, CResizableFormView)
BEGIN_MESSAGE_MAP(CSearchResultsWnd, CResizableFormView)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_SDOWNLOAD, OnBnClickedDownloadSelected)
ON_BN_CLICKED(IDC_CLEARALL, OnBnClickedClearAll)
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnSelChangeTab)
ON_MESSAGE(UM_CLOSETAB, OnCloseTab)
ON_MESSAGE(UM_DBLCLICKTAB, OnDblClickTab)
ON_WM_DESTROY()
ON_WM_SYSCOLORCHANGE()
ON_WM_SIZE()
ON_WM_CLOSE()
ON_WM_CREATE()
ON_WM_HELPINFO()
ON_MESSAGE(WM_IDLEUPDATECMDUI, OnIdleUpdateCmdUI)
//ON_BN_CLICKED(IDC_OPEN_PARAMS_WND, OnBnClickedOpenParamsWnd)
ON_WM_SYSCOMMAND()
ON_MESSAGE(UM_DELAYED_EVALUATE, OnChangeFilter)
ON_NOTIFY(TBN_DROPDOWN, IDC_SEARCHLST_ICO, OnSearchListMenuBtnDropDown)
ON_BN_CLICKED(IDC_BUTTON_SEARCH, OnBnClickedButtonSearch)
END_MESSAGE_MAP()
CSearchResultsWnd::CSearchResultsWnd(CWnd* /*pParent*/)
: CResizableFormView(CSearchResultsWnd::IDD)
{
m_nEd2kSearchID = 0x80000000;
global_search_timer = 0;
searchpacket = NULL;
m_b64BitSearchPacket = false;
canceld = false;
servercount = 0;
globsearch = false;
icon_search = NULL;
m_uTimerLocalServer = 0;
m_iSentMoreReq = 0;
searchselect.m_bCloseable = true;
m_btnSearchListMenu = new CDropDownButton;
m_nFilterColumn = 0;
m_iCurSearchIndexInRes = 0;
}
CSearchResultsWnd::~CSearchResultsWnd()
{
delete m_btnSearchListMenu;
if (globsearch)
delete searchpacket;
if (icon_search)
VERIFY( DestroyIcon(icon_search) );
if (m_uTimerLocalServer)
VERIFY( KillTimer(m_uTimerLocalServer) );
POSITION pos = m_FileSearchMap.GetStartPosition();
while (pos != NULL)
{
uint32 key;
CFileSearch * pFileSearch;
m_FileSearchMap.GetNextAssoc(pos, key, pFileSearch);
if(pFileSearch != NULL)
delete pFileSearch;
}
m_FileSearchMap.RemoveAll();
}
void CSearchResultsWnd::OnInitialUpdate()
{
CResizableFormView::OnInitialUpdate();
InitWindowStyles(this);
//CGlobalVariable::searchlist->SetOutputWnd(&searchlistctrl);
searchlistctrl.Init(CGlobalVariable::searchlist);
searchlistctrl.SetName(_T("SearchListCtrl"));
CRect rc;
rc.top = 2;
rc.left = SEARCH_LIST_MENU_BUTTON_XOFF;
rc.right = rc.left + SEARCH_LIST_MENU_BUTTON_WIDTH;
rc.bottom = rc.top + SEARCH_LIST_MENU_BUTTON_HEIGHT;
m_btnSearchListMenu->Init(true, true);
m_btnSearchListMenu->MoveWindow(&rc);
m_btnSearchListMenu->AddBtnStyle(IDC_SEARCHLST_ICO, TBSTYLE_AUTOSIZE);
m_btnSearchListMenu->ModifyStyle(TBSTYLE_TOOLTIPS, 0);
m_btnSearchListMenu->SetExtendedStyle(m_btnSearchListMenu->GetExtendedStyle() & ~TBSTYLE_EX_MIXEDBUTTONS);
m_btnSearchListMenu->RecalcLayout(true);
m_ctlFilter.OnInit(searchlistctrl.GetHeaderCtrl());
SetAllIcons();
Localize();
searchprogress.SetStep(1);
global_search_timer = 0;
globsearch = false;
AddAnchor(*m_btnSearchListMenu, TOP_LEFT);
AddAnchor(IDC_FILTER, TOP_RIGHT);
AddAnchor(IDC_SDOWNLOAD, BOTTOM_LEFT);
AddAnchor(IDC_SEARCHLIST, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(IDC_PROGRESS1, BOTTOM_LEFT, BOTTOM_RIGHT);
AddAnchor(IDC_CLEARALL, BOTTOM_RIGHT);
//AddAnchor(IDC_OPEN_PARAMS_WND, TOP_RIGHT);
AddAnchor(searchselect.m_hWnd, TOP_LEFT, TOP_RIGHT);
AddAnchor(IDC_STATIC_DLTOof, BOTTOM_LEFT);
AddAnchor(IDC_CATTAB2, BOTTOM_LEFT, BOTTOM_RIGHT);
AddAnchor(IDC_EDIT_SEARCH, TOP_LEFT);
AddAnchor(IDC_BUTTON_SEARCH, TOP_LEFT);
m_BtnSearch.SetWindowText(GetResString(IDS_SW_SEARCHBOX));
ShowSearchSelector(false);
if (theApp.m_fontSymbol.m_hObject)
{
GetDlgItem(IDC_STATIC_DLTOof)->SetFont(&theApp.m_fontSymbol);
GetDlgItem(IDC_STATIC_DLTOof)->SetWindowText(GetExStyle() & WS_EX_LAYOUTRTL ? _T("3") : _T("4")); // show a right-arrow
}
m_ctlMethod.ResetContent();
//VERIFY( m_ctlMethod.AddItem(_T("Automatic"), 0) == SearchAreaVCAutomatic);
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_CAPTION), 0) == SearchAreaEasyMuleFile);
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_GLOBALSEARCH), 1) == SearchAreaEd2kGlobal );
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_KADEMLIA) + _T(" ") + GetResString(IDS_NETWORK), 2) == SearchAreaKademlia );
UpdateHorzExtent(m_ctlMethod, 16); // adjust dropped width to ensure all strings are fully visible
m_ctlMethod.SetCurSel(SearchAreaEasyMuleFile);
}
void CSearchResultsWnd::DoDataExchange(CDataExchange* pDX)
{
CResizableFormView::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SEARCHLIST, searchlistctrl);
DDX_Control(pDX, IDC_PROGRESS1, searchprogress);
DDX_Control(pDX, IDC_TAB1, searchselect);
DDX_Control(pDX, IDC_CATTAB2, m_cattabs);
DDX_Control(pDX, IDC_FILTER, m_ctlFilter);
/*DDX_Control(pDX, IDC_OPEN_PARAMS_WND, m_ctlOpenParamsWnd);*/
DDX_Control(pDX, IDC_SEARCHLST_ICO, *m_btnSearchListMenu);
DDX_Control(pDX, IDC_EDIT_SEARCH, m_SearchCtrl);
DDX_Control(pDX, IDC_BUTTON_SEARCH, m_BtnSearch);
DDX_Control(pDX, IDC_COMBO_AREA, m_ctlMethod);
}
//MODIFIED by VC-fengwen on 2007/09/11 <begin> : 返回值标识pParams是否被删除了。
//void CSearchResultsWnd::StartSearch(SSearchParams* pParams)
bool CSearchResultsWnd::StartSearch(SSearchParams* pParams)
//MODIFIED by VC-fengwen on 2007/09/11 <end> : 返回值标识pParams是否被删除了。
{
switch (pParams->eType)
{
case SearchTypeEasyMuleFile:
return StartNeweasyMuleFileSearch(pParams);
break;
/*
case SearchTypeVCAutomatic:
return StartVCAutomaticSearch(pParams);
break;
*/
case SearchTypeEd2kServer:
case SearchTypeEd2kGlobal:
case SearchTypeKademlia:
return StartNewSearch(pParams);
break;
case SearchTypeFileDonkey:
ShellOpenFile(CreateWebQuery(pParams));
delete pParams;
return false;
break;
/*
case SearchTypeVeryCD: // Added by thilon on 2006.09.05 for VeryCD search
if(thePrefs.m_bShowBroswer && IsWindow(theApp.emuledlg->webbrowser->m_hWnd))
{
theApp.emuledlg->webbrowser->Navigate(CreateWebQuery(pParams));
theApp.emuledlg->SetActiveDialog(theApp.emuledlg->webbrowser);
}
else
{
ShellOpenFile(CreateWebQuery(pParams));
}
delete pParams;
return false;
break;
*/
default:
ASSERT(0);
delete pParams;
return false;
}
}
void CSearchResultsWnd::OnTimer(UINT nIDEvent)
{
CResizableFormView::OnTimer(nIDEvent);
if (m_uTimerLocalServer != 0 && nIDEvent == m_uTimerLocalServer)
{
if (thePrefs.GetDebugServerSearchesLevel() > 0)
Debug(_T("Timeout waiting on search results of local server\n"));
// the local server did not answer within the timeout
VERIFY( KillTimer(m_uTimerLocalServer) );
m_uTimerLocalServer = 0;
// start the global search
if (globsearch)
{
if (global_search_timer == 0)
VERIFY( (global_search_timer = SetTimer(TimerGlobalSearch, 750, 0)) != NULL );
}
else
CancelEd2kSearch();
}
else if (nIDEvent == global_search_timer)
{
if (CGlobalVariable::serverconnect->IsConnected())
{
CServer* pConnectedServer = CGlobalVariable::serverconnect->GetCurrentServer();
if (pConnectedServer)
pConnectedServer = CGlobalVariable::serverlist->GetServerByAddress(pConnectedServer->GetAddress(), pConnectedServer->GetPort());
CServer* toask = NULL;
while (servercount < CGlobalVariable::serverlist->GetServerCount()-1)
{
servercount++;
searchprogress.StepIt();
toask = CGlobalVariable::serverlist->GetNextSearchServer();
if (toask == NULL)
break;
if (toask == pConnectedServer) {
toask = NULL;
continue;
}
if (toask->GetFailedCount() >= thePrefs.GetDeadServerRetries()) {
toask = NULL;
continue;
}
break;
}
if (toask)
{
if (toask->SupportsLargeFilesUDP() && (toask->GetUDPFlags() & SRV_UDPFLG_EXT_GETFILES))
{
CSafeMemFile data(50);
uint32 nTagCount = 1;
data.WriteUInt32(nTagCount);
CTag tagFlags(CT_SERVER_UDPSEARCH_FLAGS, SRVCAP_UDP_NEWTAGS_LARGEFILES);
tagFlags.WriteNewEd2kTag(&data);
Packet* pExtSearchPacket = new Packet(OP_GLOBSEARCHREQ3, searchpacket->size + (uint32)data.GetLength());
data.SeekToBegin();
data.Read(pExtSearchPacket->pBuffer, (uint32)data.GetLength());
memcpy(pExtSearchPacket->pBuffer+(uint32)data.GetLength(), searchpacket->pBuffer, searchpacket->size);
theStats.AddUpDataOverheadServer(pExtSearchPacket->size);
CGlobalVariable::serverconnect->SendUDPPacket(pExtSearchPacket, toask, true);
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Sending %s to server %-21s (%3u of %3u)\n"), _T("OP__GlobSearchReq3"), ipstr(toask->GetAddress(), toask->GetPort()), servercount, CGlobalVariable::serverlist->GetServerCount());
}
else if (toask->GetUDPFlags() & SRV_UDPFLG_EXT_GETFILES)
{
if (!m_b64BitSearchPacket || toask->SupportsLargeFilesUDP()){
searchpacket->opcode = OP_GLOBSEARCHREQ2;
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Sending %s to server %-21s (%3u of %3u)\n"), _T("OP__GlobSearchReq2"), ipstr(toask->GetAddress(), toask->GetPort()), servercount, CGlobalVariable::serverlist->GetServerCount());
theStats.AddUpDataOverheadServer(searchpacket->size);
CGlobalVariable::serverconnect->SendUDPPacket(searchpacket, toask, false);
}
else{
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Skipped UDP search on server %-21s (%3u of %3u): No large file support\n"), ipstr(toask->GetAddress(), toask->GetPort()), servercount, CGlobalVariable::serverlist->GetServerCount());
}
}
else
{
if (!m_b64BitSearchPacket || toask->SupportsLargeFilesUDP()){
searchpacket->opcode = OP_GLOBSEARCHREQ;
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Sending %s to server %-21s (%3u of %3u)\n"), _T("OP__GlobSearchReq1"), ipstr(toask->GetAddress(), toask->GetPort()), servercount, CGlobalVariable::serverlist->GetServerCount());
theStats.AddUpDataOverheadServer(searchpacket->size);
CGlobalVariable::serverconnect->SendUDPPacket(searchpacket, toask, false);
}
else{
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Skipped UDP search on server %-21s (%3u of %3u): No large file support\n"), ipstr(toask->GetAddress(), toask->GetPort()), servercount, CGlobalVariable::serverlist->GetServerCount());
}
}
}
else
CancelEd2kSearch();
}
else
CancelEd2kSearch();
}
else
ASSERT( 0 );
}
void CSearchResultsWnd::SetSearchResultsIcon(UINT uSearchID, int iImage)
{
int iTabItems = searchselect.GetItemCount();
for (int i = 0; i < iTabItems; i++)
{
TCITEM tci;
tci.mask = TCIF_PARAM;
if (searchselect.GetItem(i, &tci) && tci.lParam != NULL && ((const SSearchParams*)tci.lParam)->dwSearchID == uSearchID)
{
tci.mask = TCIF_IMAGE;
tci.iImage = iImage;
searchselect.SetItem(i, &tci);
break;
}
}
}
void CSearchResultsWnd::SetActiveSearchResultsIcon(UINT uSearchID)
{
SSearchParams* pParams = GetSearchResultsParams(uSearchID);
if (pParams)
{
int iImage;
if (pParams->eType == SearchTypeKademlia)
iImage = sriKadActice;
else if (pParams->eType == SearchTypeEd2kGlobal)
iImage = sriGlobalActive;
else
iImage = sriServerActive;
SetSearchResultsIcon(uSearchID, iImage);
}
}
void CSearchResultsWnd::SetInactiveSearchResultsIcon(UINT uSearchID)
{
SSearchParams* pParams = GetSearchResultsParams(uSearchID);
if (pParams)
{
int iImage;
if (pParams->eType == SearchTypeKademlia)
iImage = sriKad;
else if (pParams->eType == SearchTypeEd2kGlobal)
iImage = sriGlobal;
else
iImage = sriServer;
SetSearchResultsIcon(uSearchID, iImage);
}
}
SSearchParams* CSearchResultsWnd::GetSearchResultsParams(UINT uSearchID) const
{
int iTabItems = searchselect.GetItemCount();
for (int i = 0; i < iTabItems; i++)
{
TCITEM tci;
tci.mask = TCIF_PARAM;
if (searchselect.GetItem(i, &tci) && tci.lParam != NULL && ((const SSearchParams*)tci.lParam)->dwSearchID == uSearchID)
return (SSearchParams*)tci.lParam;
}
return NULL;
}
void CSearchResultsWnd::CancelSearch(UINT uSearchID)
{
if (uSearchID == 0)
{
int iCurSel = searchselect.GetCurSel();
if (iCurSel == -1)
return;
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem(iCurSel, &item) && item.lParam != NULL)
uSearchID = ((const SSearchParams*)item.lParam)->dwSearchID;
if (uSearchID == 0)
return;
}
SSearchParams* pParams = GetSearchResultsParams(uSearchID);
if (pParams == NULL)
return;
if (pParams->eType == SearchTypeEd2kServer || pParams->eType == SearchTypeEd2kGlobal)
CancelEd2kSearch();
else if (pParams->eType == SearchTypeKademlia)
{
Kademlia::CSearchManager::StopSearch(pParams->dwSearchID, false);
CancelKadSearch(pParams->dwSearchID);
}
}
void CSearchResultsWnd::CancelEd2kSearch()
{
SetInactiveSearchResultsIcon(m_nEd2kSearchID);
canceld = true;
// delete any global search timer
if (globsearch){
delete searchpacket;
searchpacket = NULL;
m_b64BitSearchPacket = false;
}
globsearch = false;
if (global_search_timer){
VERIFY( KillTimer(global_search_timer) );
global_search_timer = 0;
searchprogress.SetPos(0);
}
// delete local server timeout timer
if (m_uTimerLocalServer){
VERIFY( KillTimer(m_uTimerLocalServer) );
m_uTimerLocalServer = 0;
}
SearchCanceled(m_nEd2kSearchID);
}
void CSearchResultsWnd::CancelKadSearch(UINT uSearchID)
{
SearchCanceled(uSearchID);
}
void CSearchResultsWnd::SearchStarted()
{
//CWnd* pWndFocus = GetFocus();
//m_pwndParams->m_ctlStart.EnableWindow(FALSE);
//if (pWndFocus && pWndFocus->m_hWnd == m_pwndParams->m_ctlStart.m_hWnd)
// m_pwndParams->m_ctlName.SetFocus();
//m_pwndParams->m_ctlCancel.EnableWindow(TRUE);
}
void CSearchResultsWnd::SearchCanceled(UINT uSearchID)
{
SetInactiveSearchResultsIcon(uSearchID);
int iCurSel = searchselect.GetCurSel();
if (iCurSel != -1)
{
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem(iCurSel, &item) && item.lParam != NULL && uSearchID == ((const SSearchParams*)item.lParam)->dwSearchID)
{
//CWnd* pWndFocus = GetFocus();
//m_pwndParams->m_ctlCancel.EnableWindow(FALSE);
//if (pWndFocus && pWndFocus->m_hWnd == m_pwndParams->m_ctlCancel.m_hWnd)
// m_pwndParams->m_ctlName.SetFocus();
//m_pwndParams->m_ctlStart.EnableWindow(TRUE);
}
}
}
void CSearchResultsWnd::LocalEd2kSearchEnd(UINT count, bool /*bMoreResultsAvailable*/)
{
// local server has answered, kill the timeout timer
if (m_uTimerLocalServer) {
VERIFY( KillTimer(m_uTimerLocalServer) );
m_uTimerLocalServer = 0;
}
if (!canceld && count > MAX_RESULTS)
CancelEd2kSearch();
if (!canceld) {
if (!globsearch)
SearchCanceled(m_nEd2kSearchID);
else
VERIFY( (global_search_timer = SetTimer(TimerGlobalSearch, 750, 0)) != NULL );
}
//m_pwndParams->m_ctlMore.EnableWindow(bMoreResultsAvailable && m_iSentMoreReq < MAX_MORE_SEARCH_REQ);
}
void CSearchResultsWnd::AddGlobalEd2kSearchResults(UINT count)
{
if (!canceld && count > MAX_RESULTS)
CancelEd2kSearch();
}
void CSearchResultsWnd::OnBnClickedDownloadSelected()
{
//start download(s)
DownloadSelected();
}
void CSearchResultsWnd::OnDblClkSearchList(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
OnBnClickedDownloadSelected();
*pResult = 0;
}
CString CSearchResultsWnd::CreateWebQuery(SSearchParams* pParams)
{
CString query;
switch (pParams->eType)
{
case SearchTypeFileDonkey:
query = _T("http://www.filedonkey.com/search.html?");
query += _T("pattern=") + EncodeURLQueryParam(pParams->strExpression);
if (pParams->strFileType == ED2KFTSTR_AUDIO)
query += _T("&media=Audio");
else if (pParams->strFileType == ED2KFTSTR_VIDEO)
query += _T("&media=Video");
else if (pParams->strFileType == ED2KFTSTR_PROGRAM)
query += _T("&media=Pro");
query += _T("&requestby=emule");
if (pParams->ullMinSize > 0)
query.AppendFormat(_T("&min_size=%I64u"),pParams->ullMinSize);
if (pParams->ullMaxSize > 0)
query.AppendFormat(_T("&max_size=%I64u"),pParams->ullMaxSize);
break;
case SearchTypeVeryCD: // Added by thilon on 2006.09.05 for VeryCD search
query = "http://www.verycd.com/search/folders/";
query += EncodeUrlUtf8(pParams->strExpression);
query += "/";
break;
default:
return _T("");
}
return query;
}
void CSearchResultsWnd::DownloadSelected()
{
DownloadSelected(thePrefs.AddNewFilesPaused());
}
void CSearchResultsWnd::DownloadSelected(bool bPaused)
{
CWaitCursor curWait;
POSITION pos = searchlistctrl.GetFirstSelectedItemPosition();
while (pos != NULL)
{
int iIndex = searchlistctrl.GetNextSelectedItem(pos);
if (iIndex >= 0)
{
// get selected listview item (may be a child item from an expanded search result)
const CSearchFile* sel_file = (CSearchFile*)searchlistctrl.GetItemData(iIndex);
// get parent
const CSearchFile* parent;
if (sel_file->GetListParent() != NULL)
parent = sel_file->GetListParent();
else
parent = sel_file;
if (parent->IsComplete() == 0 && parent->GetSourceCount() >= 50)
{
CString strMsg;
strMsg.Format(GetResString(IDS_ASKDLINCOMPLETE), sel_file->GetFileName());
int iAnswer = AfxMessageBox(strMsg, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2);
if (iAnswer != IDYES)
continue;
}
// create new DL-queue entry with all properties of parent (e.g. already received sources!)
// but with the filename of the selected listview item.
CSearchFile tempFile(parent);
tempFile.SetFileName(sel_file->GetFileName());
tempFile.SetStrTagValue(FT_FILENAME, sel_file->GetFileName());
//MODIFIED by fengwen on 2007/02/09 <begin> :
//CGlobalVariable::downloadqueue->AddSearchToDownload(&tempFile, bPaused, m_cattabs.GetCurSel());
CmdFuncs::AddSearchToDownload(&tempFile, bPaused, m_cattabs.GetCurSel());
//MODIFIED by fengwen on 2007/02/09 <end> :
// update parent and all childs
searchlistctrl.UpdateSources(parent);
}
}
}
void CSearchResultsWnd::OnSysColorChange()
{
CResizableFormView::OnSysColorChange();
SetAllIcons();
searchlistctrl.CreateMenues();
}
void CSearchResultsWnd::SetAllIcons()
{
m_btnSearchListMenu->SetIcon(_T("SearchResults"));
if (icon_search)
VERIFY( DestroyIcon(icon_search) );
icon_search = theApp.LoadIcon(_T("SearchResults"), 16, 16);
((CStatic*)GetDlgItem(IDC_SEARCHLST_ICO))->SetIcon(icon_search);
CImageList iml;
iml.Create(16,16,theApp.m_iDfltImageListColorFlags|ILC_MASK,0,1);
iml.SetBkColor(CLR_NONE);
iml.Add(CTempIconLoader(_T("SearchMethod_ServerActive"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_GlobalActive"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_KademliaActive"), 16, 16));
iml.Add(CTempIconLoader(_T("StatsClients"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_SERVER"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_GLOBAL"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_KADEMLIA"), 16, 16));
searchselect.SetImageList(&iml);
m_imlSearchResults.DeleteImageList();
m_imlSearchResults.Attach(iml.Detach());
searchselect.SetPadding(CSize(10, 3));
iml.Create(16,16,theApp.m_iDfltImageListColorFlags|ILC_MASK,0,1);
iml.SetBkColor(CLR_NONE);
iml.Add(CTempIconLoader(IDI_ICON_EMULE,16 ,16));
iml.Add(CTempIconLoader(_T("SearchMethod_GLOBAL"), 16, 16));
iml.Add(CTempIconLoader(_T("SearchMethod_KADEMLIA"), 16, 16));
m_ctlMethod.SetImageList(&iml);
m_imlSearchMethods.DeleteImageList();
m_imlSearchMethods.Attach(iml.Detach());
}
void CSearchResultsWnd::Localize()
{
searchlistctrl.Localize();
UpdateCatTabs();
GetDlgItem(IDC_CLEARALL)->SetWindowText(GetResString(IDS_REMOVEALLSEARCH));
m_btnSearchListMenu->SetWindowText(GetResString(IDS_SW_RESULT));
GetDlgItem(IDC_SDOWNLOAD)->SetWindowText(GetResString(IDS_SW_DOWNLOAD));
GetDlgItem(IDC_BUTTON_SEARCH)->SetWindowText(GetResString(IDS_SW_SEARCHBOX));
//{begin} VC-dgkang 2008年7月17日
int Sel = m_ctlMethod.GetCurSel();
m_ctlMethod.ResetContent();
//VERIFY( m_ctlMethod.AddItem(_T("Automatic"), 0) == SearchAreaVCAutomatic);
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_CAPTION), 0) == SearchAreaEasyMuleFile );
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_GLOBALSEARCH), 1) == SearchAreaEd2kGlobal );
VERIFY( m_ctlMethod.AddItem(GetResString(IDS_KADEMLIA) + _T(" ") + GetResString(IDS_NETWORK), 2) == SearchAreaKademlia );
UpdateHorzExtent(m_ctlMethod, 16); // adjust dropped width to ensure all strings are fully visible
m_ctlMethod.SetCurSel(Sel);
//{end}
/*m_ctlOpenParamsWnd.SetWindowText(GetResString(IDS_SEARCHPARAMS)+_T("..."));*/
}
void CSearchResultsWnd::OnBnClickedClearAll()
{
DeleteAllSearches();
}
CString DbgGetFileMetaTagName(UINT uMetaTagID)
{
switch (uMetaTagID)
{
case FT_FILENAME: return _T("@Name");
case FT_FILESIZE: return _T("@Size");
case FT_FILESIZE_HI: return _T("@SizeHI");
case FT_FILETYPE: return _T("@Type");
case FT_FILEFORMAT: return _T("@Format");
case FT_LASTSEENCOMPLETE: return _T("@LastSeenComplete");
case FT_SOURCES: return _T("@Sources");
case FT_COMPLETE_SOURCES: return _T("@Complete");
case FT_MEDIA_ARTIST: return _T("@Artist");
case FT_MEDIA_ALBUM: return _T("@Album");
case FT_MEDIA_TITLE: return _T("@Title");
case FT_MEDIA_LENGTH: return _T("@Length");
case FT_MEDIA_BITRATE: return _T("@Bitrate");
case FT_MEDIA_CODEC: return _T("@Codec");
case FT_FILECOMMENT: return _T("@Comment");
case FT_FILERATING: return _T("@Rating");
case FT_FILEHASH: return _T("@Filehash");
}
CString buffer;
buffer.Format(_T("Tag0x%02X"), uMetaTagID);
return buffer;
}
CString DbgGetFileMetaTagName(LPCSTR pszMetaTagID)
{
if (strlen(pszMetaTagID) == 1)
return DbgGetFileMetaTagName(((BYTE*)pszMetaTagID)[0]);
CString strName;
strName.Format(_T("\"%hs\""), pszMetaTagID);
return strName;
}
CString DbgGetSearchOperatorName(UINT uOperator)
{
static const LPCTSTR _aszEd2kOps[] =
{
_T("="),
_T(">"),
_T("<"),
_T(">="),
_T("<="),
_T("<>"),
};
if (uOperator >= ARRSIZE(_aszEd2kOps)){
ASSERT(0);
return _T("*UnkOp*");
}
return _aszEd2kOps[uOperator];
}
static CStringA _strCurKadKeywordA;
static CSearchExpr _SearchExpr;
CStringArray _astrParserErrors;
static TCHAR _chLastChar = 0;
static CString _strSearchTree;
bool DumpSearchTree(int& iExpr, const CSearchExpr& rSearchExpr, int iLevel, bool bFlat)
{
if (iExpr >= rSearchExpr.m_aExpr.GetCount())
return false;
if (!bFlat)
_strSearchTree += _T('\n') + CString(_T(' '), iLevel);
const CSearchAttr& rSearchAttr = rSearchExpr.m_aExpr[iExpr++];
CStringA strTok = rSearchAttr.m_str;
if (strTok == SEARCHOPTOK_AND || strTok == SEARCHOPTOK_OR || strTok == SEARCHOPTOK_NOT)
{
if (bFlat) {
if (_chLastChar != _T('(') && _chLastChar != _T('\0'))
_strSearchTree.AppendFormat(_T(" "));
}
_strSearchTree.AppendFormat(_T("(%hs "), strTok.Mid(1));
_chLastChar = _T('(');
DumpSearchTree(iExpr, rSearchExpr, iLevel + 4, bFlat);
DumpSearchTree(iExpr, rSearchExpr, iLevel + 4, bFlat);
_strSearchTree.AppendFormat(_T(")"));
_chLastChar = _T(')');
}
else
{
if (bFlat) {
if (_chLastChar != _T('(') && _chLastChar != _T('\0'))
_strSearchTree.AppendFormat(_T(" "));
}
_strSearchTree += rSearchAttr.DbgGetAttr();
_chLastChar = _T('\1');
}
return true;
}
bool DumpSearchTree(const CSearchExpr& rSearchExpr, bool bFlat)
{
_chLastChar = _T('\0');
int iExpr = 0;
int iLevel = 0;
return DumpSearchTree(iExpr, rSearchExpr, iLevel, bFlat);
}
void ParsedSearchExpression(const CSearchExpr* pexpr)
{
int iOpAnd = 0;
int iOpOr = 0;
int iOpNot = 0;
int iNonDefTags = 0;
//CStringA strDbg;
for (int i = 0; i < pexpr->m_aExpr.GetCount(); i++)
{
const CSearchAttr& rSearchAttr = pexpr->m_aExpr[i];
const CStringA& rstr = rSearchAttr.m_str;
if (rstr == SEARCHOPTOK_AND)
{
iOpAnd++;
//strDbg.AppendFormat("%s ", rstr.Mid(1));
}
else if (rstr == SEARCHOPTOK_OR)
{
iOpOr++;
//strDbg.AppendFormat("%s ", rstr.Mid(1));
}
else if (rstr == SEARCHOPTOK_NOT)
{
iOpNot++;
//strDbg.AppendFormat("%s ", rstr.Mid(1));
}
else
{
if (rSearchAttr.m_iTag != FT_FILENAME)
iNonDefTags++;
//strDbg += rSearchAttr.DbgGetAttr() + " ";
}
}
//if (thePrefs.GetDebugServerSearchesLevel() > 0)
// Debug(_T("Search Expr: %hs\n"), strDbg);
// this limit (+ the additional operators which will be added later) has to match the limit in 'CreateSearchExpressionTree'
// +1 Type (Audio, Video)
// +1 MinSize
// +1 MaxSize
// +1 Avail
// +1 Extension
// +1 Complete sources
// +1 Codec
// +1 Bitrate
// +1 Length
// +1 Title
// +1 Album
// +1 Artist
// ---------------
// 12
if (iOpAnd + iOpOr + iOpNot > 10)
yyerror(GetResString(IDS_SEARCH_TOOCOMPLEX));
_SearchExpr.m_aExpr.RemoveAll();
// optimize search expression, if no OR nor NOT specified
if (iOpAnd > 0 && iOpOr == 0 && iOpNot == 0 && iNonDefTags == 0)
{
CStringA strAndTerms;
for (int i = 0; i < pexpr->m_aExpr.GetCount(); i++)
{
if (pexpr->m_aExpr[i].m_str != SEARCHOPTOK_AND)
{
ASSERT( pexpr->m_aExpr[i].m_iTag == FT_FILENAME );
// Minor optimization: Because we added the Kad keyword to the boolean search expression,
// we remove it here (and only here) again because we know that the entire search expression
// does only contain (implicit) ANDed strings.
if (pexpr->m_aExpr[i].m_str != _strCurKadKeywordA)
{
if (!strAndTerms.IsEmpty())
strAndTerms += ' ';
strAndTerms += pexpr->m_aExpr[i].m_str;
}
}
}
ASSERT( _SearchExpr.m_aExpr.GetCount() == 0);
_SearchExpr.m_aExpr.Add(CSearchAttr(strAndTerms));
}
else
{
if (pexpr->m_aExpr.GetCount() != 1
|| !(pexpr->m_aExpr[0].m_iTag == FT_FILENAME && pexpr->m_aExpr[0].m_str == _strCurKadKeywordA))
_SearchExpr.m_aExpr.Append(pexpr->m_aExpr);
}
}
class CSearchExprTarget
{
public:
CSearchExprTarget(CSafeMemFile* pData, EUtf8Str eStrEncode, bool bSupports64Bit, bool* pbPacketUsing64Bit)
{
m_data = pData;
m_eStrEncode = eStrEncode;
m_bSupports64Bit = bSupports64Bit;
m_pbPacketUsing64Bit = pbPacketUsing64Bit;
if (m_pbPacketUsing64Bit)
*m_pbPacketUsing64Bit = false;
}
const CString& GetDebugString() const
{
return m_strDbg;
}
void WriteBooleanAND()
{
m_data->WriteUInt8(0); // boolean operator parameter type
m_data->WriteUInt8(0x00); // "AND"
m_strDbg.AppendFormat(_T("AND "));
}
void WriteBooleanOR()
{
m_data->WriteUInt8(0); // boolean operator parameter type
m_data->WriteUInt8(0x01); // "OR"
m_strDbg.AppendFormat(_T("OR "));
}
void WriteBooleanNOT()
{
m_data->WriteUInt8(0); // boolean operator parameter type
m_data->WriteUInt8(0x02); // "NOT"
m_strDbg.AppendFormat(_T("NOT "));
}
void WriteMetaDataSearchParam(const CString& rstrValue)
{
m_data->WriteUInt8(1); // string parameter type
m_data->WriteString(rstrValue, m_eStrEncode); // string value
m_strDbg.AppendFormat(_T("\"%s\" "), rstrValue);
}
void WriteMetaDataSearchParam(UINT uMetaTagID, const CString& rstrValue)
{
m_data->WriteUInt8(2); // string parameter type
m_data->WriteString(rstrValue, m_eStrEncode); // string value
m_data->WriteUInt16(sizeof uint8); // meta tag ID length
m_data->WriteUInt8((uint8)uMetaTagID); // meta tag ID name
m_strDbg.AppendFormat(_T("%s=\"%s\" "), DbgGetFileMetaTagName(uMetaTagID), rstrValue);
}
void WriteMetaDataSearchParamA(UINT uMetaTagID, const CStringA& rstrValueA)
{
m_data->WriteUInt8(2); // string parameter type
m_data->WriteString(rstrValueA); // string value
m_data->WriteUInt16(sizeof uint8); // meta tag ID length
m_data->WriteUInt8((uint8)uMetaTagID); // meta tag ID name
m_strDbg.AppendFormat(_T("%s=\"%hs\" "), DbgGetFileMetaTagName(uMetaTagID), rstrValueA);
}
void WriteMetaDataSearchParam(LPCSTR pszMetaTagID, const CString& rstrValue)
{
m_data->WriteUInt8(2); // string parameter type
m_data->WriteString(rstrValue, m_eStrEncode); // string value
m_data->WriteString(pszMetaTagID); // meta tag ID
m_strDbg.AppendFormat(_T("%s=\"%s\" "), DbgGetFileMetaTagName(pszMetaTagID), rstrValue);
}
void WriteMetaDataSearchParam(UINT uMetaTagID, UINT uOperator, uint64 ullValue)
{
bool b64BitValue = ullValue > 0xFFFFFFFFui64;
if (b64BitValue && m_bSupports64Bit) {
if (m_pbPacketUsing64Bit)
*m_pbPacketUsing64Bit = true;
m_data->WriteUInt8(8); // numeric parameter type (int64)
m_data->WriteUInt64(ullValue); // numeric value
}
else {
if (b64BitValue)
ullValue = 0xFFFFFFFFU;
m_data->WriteUInt8(3); // numeric parameter type (int32)
m_data->WriteUInt32((uint32)ullValue); // numeric value
}
m_data->WriteUInt8((uint8)uOperator); // comparison operator
m_data->WriteUInt16(sizeof uint8); // meta tag ID length
m_data->WriteUInt8((uint8)uMetaTagID); // meta tag ID name
m_strDbg.AppendFormat(_T("%s%s%I64u "), DbgGetFileMetaTagName(uMetaTagID), DbgGetSearchOperatorName(uOperator), ullValue);
}
void WriteMetaDataSearchParam(LPCSTR pszMetaTagID, UINT uOperator, uint64 ullValue)
{
bool b64BitValue = ullValue > 0xFFFFFFFFui64;
if (b64BitValue && m_bSupports64Bit) {
if (m_pbPacketUsing64Bit)
*m_pbPacketUsing64Bit = true;
m_data->WriteUInt8(8); // numeric parameter type (int64)
m_data->WriteUInt64(ullValue); // numeric value
}
else {
if (b64BitValue)
ullValue = 0xFFFFFFFFU;
m_data->WriteUInt8(3); // numeric parameter type (int32)
m_data->WriteUInt32((uint32)ullValue); // numeric value
}
m_data->WriteUInt8((uint8)uOperator); // comparison operator
m_data->WriteString(pszMetaTagID); // meta tag ID
m_strDbg.AppendFormat(_T("%s%s%I64u "), DbgGetFileMetaTagName(pszMetaTagID), DbgGetSearchOperatorName(uOperator), ullValue);
}
protected:
CSafeMemFile* m_data;
CString m_strDbg;
EUtf8Str m_eStrEncode;
bool m_bSupports64Bit;
bool* m_pbPacketUsing64Bit;
};
static CSearchExpr _SearchExpr2;
static void AddAndAttr(UINT uTag, const CString& rstr)
{
_SearchExpr2.m_aExpr.InsertAt(0, CSearchAttr(uTag, StrToUtf8(rstr)));
if (_SearchExpr2.m_aExpr.GetCount() > 1)
_SearchExpr2.m_aExpr.InsertAt(0, CSearchAttr(SEARCHOPTOK_AND));
}
static void AddAndAttr(UINT uTag, UINT uOpr, uint64 ullVal)
{
_SearchExpr2.m_aExpr.InsertAt(0, CSearchAttr(uTag, uOpr, ullVal));
if (_SearchExpr2.m_aExpr.GetCount() > 1)
_SearchExpr2.m_aExpr.InsertAt(0, CSearchAttr(SEARCHOPTOK_AND));
}
bool GetSearchPacket(CSafeMemFile* pData, SSearchParams* pParams, bool bTargetSupports64Bit, bool* pbPacketUsing64Bit)
{
CStringA strFileType;
if (pParams->strFileType == ED2KFTSTR_ARCHIVE){
// eDonkeyHybrid 0.48 uses type "Pro" for archives files
// www.filedonkey.com uses type "Pro" for archives files
strFileType = ED2KFTSTR_PROGRAM;
}
else if (pParams->strFileType == ED2KFTSTR_CDIMAGE){
// eDonkeyHybrid 0.48 uses *no* type for iso/nrg/cue/img files
// www.filedonkey.com uses type "Pro" for CD-image files
strFileType = ED2KFTSTR_PROGRAM;
}
else{
//TODO: Support "Doc" types
strFileType = pParams->strFileType;
}
_strCurKadKeywordA.Empty();
ASSERT( !pParams->strExpression.IsEmpty() );
if (pParams->eType == SearchTypeKademlia)
{
ASSERT( !pParams->strKeyword.IsEmpty() );
_strCurKadKeywordA = StrToUtf8(pParams->strKeyword);
}
if (pParams->strBooleanExpr.IsEmpty())
pParams->strBooleanExpr = pParams->strExpression;
if (pParams->strBooleanExpr.IsEmpty())
return false;
//TRACE(_T("Raw search expr:\n"));
//TRACE(_T("%s"), pParams->strBooleanExpr);
//TRACE(_T(" %s\n"), DbgGetHexDump((uchar*)(LPCTSTR)pParams->strBooleanExpr, pParams->strBooleanExpr.GetLength()*sizeof(TCHAR)));
_astrParserErrors.RemoveAll();
_SearchExpr.m_aExpr.RemoveAll();
if (!pParams->strBooleanExpr.IsEmpty())
{
// check this here again, we could have been called from Webinterface or MM
if (!pParams->bUnicode)
{
CStringA strACP(pParams->strBooleanExpr);
if (!IsValidEd2kStringA(strACP)){
CString strError(GetResString(IDS_SEARCH_EXPRERROR) + _T("\n\n") + GetResString(IDS_SEARCH_INVALIDCHAR));
throw new CMsgBoxException(strError, MB_ICONWARNING | MB_HELP, eMule_FAQ_Search - HID_BASE_PROMPT);
}
}
LexInit(pParams->strBooleanExpr, true);
int iParseResult = yyparse();
LexFree();
if (_astrParserErrors.GetSize() > 0)
{
_SearchExpr.m_aExpr.RemoveAll();
CString strError(GetResString(IDS_SEARCH_EXPRERROR) + _T("\n\n") + _astrParserErrors[_astrParserErrors.GetSize() - 1]);
throw new CMsgBoxException(strError, MB_ICONWARNING | MB_HELP, eMule_FAQ_Search - HID_BASE_PROMPT);
}
else if (iParseResult != 0)
{
_SearchExpr.m_aExpr.RemoveAll();
CString strError(GetResString(IDS_SEARCH_EXPRERROR) + _T("\n\n") + GetResString(IDS_SEARCH_GENERALERROR));
throw new CMsgBoxException(strError, MB_ICONWARNING | MB_HELP, eMule_FAQ_Search - HID_BASE_PROMPT);
}
}
//TRACE(_T("Parsed search expr:\n"));
//for (int i = 0; i < _SearchExpr.m_aExpr.GetCount(); i++){
// TRACE(_T("%hs"), _SearchExpr.m_aExpr[i]);
// TRACE(_T(" %s\n"), DbgGetHexDump((uchar*)(LPCSTR)_SearchExpr.m_aExpr[i], _SearchExpr.m_aExpr[i].GetLength()*sizeof(CHAR)));
//}
// create ed2k search expression
CSearchExprTarget target(pData, pParams->bUnicode ? utf8strRaw : utf8strNone, bTargetSupports64Bit, pbPacketUsing64Bit);
_SearchExpr2.m_aExpr.RemoveAll();
if (!pParams->strExtension.IsEmpty())
AddAndAttr(FT_FILEFORMAT, pParams->strExtension);
if (pParams->uAvailability > 0)
AddAndAttr(FT_SOURCES, ED2K_SEARCH_OP_GREATER_EQUAL, pParams->uAvailability);
if (pParams->ullMaxSize > 0)
AddAndAttr(FT_FILESIZE, ED2K_SEARCH_OP_LESS_EQUAL, pParams->ullMaxSize);
if (pParams->ullMinSize > 0)
AddAndAttr(FT_FILESIZE, ED2K_SEARCH_OP_GREATER_EQUAL, pParams->ullMinSize);
if (!strFileType.IsEmpty())
AddAndAttr(FT_FILETYPE, CString(strFileType));
if (pParams->uComplete > 0)
AddAndAttr(FT_COMPLETE_SOURCES, ED2K_SEARCH_OP_GREATER_EQUAL, pParams->uComplete);
if (pParams->ulMinBitrate > 0)
AddAndAttr(FT_MEDIA_BITRATE, ED2K_SEARCH_OP_GREATER_EQUAL, pParams->ulMinBitrate);
if (pParams->ulMinLength > 0)
AddAndAttr(FT_MEDIA_LENGTH, ED2K_SEARCH_OP_GREATER_EQUAL, pParams->ulMinLength);
if (!pParams->strCodec.IsEmpty())
AddAndAttr(FT_MEDIA_CODEC, pParams->strCodec);
if (!pParams->strTitle.IsEmpty())
AddAndAttr(FT_MEDIA_TITLE, pParams->strTitle);
if (!pParams->strAlbum.IsEmpty())
AddAndAttr(FT_MEDIA_ALBUM, pParams->strAlbum);
if (!pParams->strArtist.IsEmpty())
AddAndAttr(FT_MEDIA_ARTIST, pParams->strArtist);
if (_SearchExpr2.m_aExpr.GetCount() > 0)
{
if (_SearchExpr.m_aExpr.GetCount() > 0)
_SearchExpr.m_aExpr.InsertAt(0, CSearchAttr(SEARCHOPTOK_AND));
_SearchExpr.Add(&_SearchExpr2);
}
if (thePrefs.GetVerbose())
{
_strSearchTree.Empty();
DumpSearchTree(_SearchExpr, true);
DebugLog(_T("Search Expr: %s"), _strSearchTree);
}
for (int j = 0; j < _SearchExpr.m_aExpr.GetCount(); j++)
{
const CSearchAttr& rSearchAttr = _SearchExpr.m_aExpr[j];
const CStringA& rstrA = rSearchAttr.m_str;
if (rstrA == SEARCHOPTOK_AND)
{
target.WriteBooleanAND();
}
else if (rstrA == SEARCHOPTOK_OR)
{
target.WriteBooleanOR();
}
else if (rstrA == SEARCHOPTOK_NOT)
{
target.WriteBooleanNOT();
}
else if (rSearchAttr.m_iTag == FT_FILESIZE ||
rSearchAttr.m_iTag == FT_SOURCES ||
rSearchAttr.m_iTag == FT_COMPLETE_SOURCES ||
rSearchAttr.m_iTag == FT_FILERATING ||
rSearchAttr.m_iTag == FT_MEDIA_BITRATE ||
rSearchAttr.m_iTag == FT_MEDIA_LENGTH)
{
// 11-Sep-2005 []: Kad comparison operators where changed to match the ED2K operators. For backward
// compatibility with old Kad nodes, we map ">=val" and "<=val" to ">val-1" and "<val+1". This way,
// the older Kad nodes will perform a ">=val" and "<=val".
//
// TODO: This should be removed in couple of months!
if (rSearchAttr.m_uIntegerOperator == ED2K_SEARCH_OP_GREATER_EQUAL)
target.WriteMetaDataSearchParam(rSearchAttr.m_iTag, ED2K_SEARCH_OP_GREATER, rSearchAttr.m_nNum - 1);
else if (rSearchAttr.m_uIntegerOperator == ED2K_SEARCH_OP_LESS_EQUAL)
target.WriteMetaDataSearchParam(rSearchAttr.m_iTag, ED2K_SEARCH_OP_LESS, rSearchAttr.m_nNum + 1);
else
target.WriteMetaDataSearchParam(rSearchAttr.m_iTag, rSearchAttr.m_uIntegerOperator, rSearchAttr.m_nNum);
}
else if (rSearchAttr.m_iTag == FT_FILETYPE ||
rSearchAttr.m_iTag == FT_FILEFORMAT ||
rSearchAttr.m_iTag == FT_MEDIA_CODEC ||
rSearchAttr.m_iTag == FT_MEDIA_TITLE ||
rSearchAttr.m_iTag == FT_MEDIA_ALBUM ||
rSearchAttr.m_iTag == FT_MEDIA_ARTIST)
{
ASSERT( rSearchAttr.m_uIntegerOperator == ED2K_SEARCH_OP_EQUAL );
target.WriteMetaDataSearchParam(rSearchAttr.m_iTag, OptUtf8ToStr(rSearchAttr.m_str));
}
else
{
ASSERT( rSearchAttr.m_iTag == FT_FILENAME );
ASSERT( rSearchAttr.m_uIntegerOperator == ED2K_SEARCH_OP_EQUAL );
target.WriteMetaDataSearchParam(OptUtf8ToStr(rstrA));
}
}
if (thePrefs.GetDebugServerSearchesLevel() > 0)
Debug(_T("Search Data: %s\n"), target.GetDebugString());
_SearchExpr.m_aExpr.RemoveAll();
_SearchExpr2.m_aExpr.RemoveAll();
return true;
}
bool CSearchResultsWnd::StartNeweasyMuleFileSearch(SSearchParams* pParams)
{
CFileSearch * pFileSearch = new CFileSearch;
pFileSearch->m_pSearchListCtrl = &searchlistctrl;
pFileSearch->Start( pParams->strExpression );
m_nEd2kSearchID++;
pParams->dwSearchID = m_nEd2kSearchID;
pFileSearch->m_dwSearchID = m_nEd2kSearchID;
m_FileSearchMap.SetAt(pParams->dwSearchID,pFileSearch);
CStringA strResultType = pParams->strFileType;
if (strResultType == ED2KFTSTR_PROGRAM)
strResultType.Empty();
CGlobalVariable::searchlist->NewSearch(&searchlistctrl, strResultType, m_nEd2kSearchID, pParams->eType, pParams->strExpression);
if( thePrefs.IsHybridSearchEnabled() )
{
///混合ed2k search
DoNewEd2kSearch(pParams,pParams->dwSearchID);
///混合kad search
DoNewKadSearch(pParams,pParams->dwSearchID);
}
return true;
}
/*
bool CSearchResultsWnd::StartVCAutomaticSearch(SSearchParams* pParams)
{
CFileSearch * pFileSearch = new CFileSearch;
pFileSearch->m_pSearchListCtrl = &searchlistctrl;
pFileSearch->Start( pParams->strExpression );
m_nEd2kSearchID++;
pParams->dwSearchID = m_nEd2kSearchID;
pFileSearch->m_dwSearchID = m_nEd2kSearchID;
m_FileSearchMap.SetAt(pParams->dwSearchID,pFileSearch);
///混合ed2k search
DoNewEd2kSearch(pParams,pParams->dwSearchID);
///混合kad search
DoNewKadSearch(pParams,pParams->dwSearchID);
return true;
}
*/
bool CSearchResultsWnd::StartNewSearch(SSearchParams* pParams)
{
ESearchType eSearchType = pParams->eType;
if (eSearchType == SearchTypeEd2kServer || eSearchType == SearchTypeEd2kGlobal)
{
if (!CGlobalVariable::serverconnect->IsConnected())
{
MessageBox(GetResString(IDS_ERR_NOTCONNECTED),GetResString(IDS_CAPTION),MB_ICONWARNING);
delete pParams;
//if (!CGlobalVariable::serverconnect->IsConnecting() && !CGlobalVariable::serverconnect->IsConnected())
// CGlobalVariable::serverconnect->ConnectToAnyServer();
return false;
}
try
{
if (!DoNewEd2kSearch(pParams))
{
delete pParams;
return false;
}
}
catch (CMsgBoxException* ex)
{
AfxMessageBox(ex->m_strMsg, ex->m_uType, ex->m_uHelpID);
ex->Delete();
delete pParams;
return false;
}
SearchStarted();
return true;
}
if (eSearchType == SearchTypeKademlia)
{
// Kademlia 返回错误,但不Delete pParams.在删除标签页一起删除。
if (!Kademlia::CKademlia::IsRunning() || !Kademlia::CKademlia::IsConnected()) {
MessageBox(GetResString(IDS_ERR_NOTCONNECTEDKAD),GetResString(IDS_CAPTION),MB_ICONWARNING);
//VC-dgkang 2008年7月17日
//delete pParams;
//if (!Kademlia::CKademlia::IsRunning())
// Kademlia::CKademlia::Start();
return false;
}
try
{
if (!DoNewKadSearch(pParams)) {
//VC-dgkang 2008年7月17日
//delete pParams;
return false;
}
}
catch (CMsgBoxException* ex)
{
AfxMessageBox(ex->m_strMsg, ex->m_uType, ex->m_uHelpID);
ex->Delete();
//VC-dgkang 2008年7月17日
//delete pParams;
return false;
}
SearchStarted();
return true;
}
ASSERT(0);
delete pParams;
return false;
}
bool CSearchResultsWnd::DoNewEd2kSearch(SSearchParams* pParams,UINT uSearchID/*=0*/)
{
if (!CGlobalVariable::serverconnect->IsConnected())
return false;
bool bServerSupports64Bit = CGlobalVariable::serverconnect->GetCurrentServer() != NULL
&& (CGlobalVariable::serverconnect->GetCurrentServer()->GetTCPFlags() & SRV_TCPFLG_LARGEFILES);
bool bPacketUsing64Bit = false;
CSafeMemFile data(100);
if (!GetSearchPacket(&data, pParams, bServerSupports64Bit, &bPacketUsing64Bit) || data.GetLength() == 0)
return false;
CancelEd2kSearch();
CStringA strResultType = pParams->strFileType;
if (strResultType == ED2KFTSTR_PROGRAM)
strResultType.Empty();
if(0==uSearchID)
{
m_nEd2kSearchID++;
pParams->dwSearchID = m_nEd2kSearchID;
CGlobalVariable::searchlist->NewSearch(&searchlistctrl, strResultType, m_nEd2kSearchID, pParams->eType, pParams->strExpression);
}
else
{
//和VC电驴文件搜索类型一起混合搜索,共用一个SearchID
//pParams->dwSearchID = uSearchID;
//CGlobalVariable::searchlist->NewSearch(&searchlistctrl, strResultType, uSearchID, pParams->eType, pParams->strExpression);
}
canceld = false;
if (m_uTimerLocalServer)
{
VERIFY( KillTimer(m_uTimerLocalServer) );
m_uTimerLocalServer = 0;
}
// once we've sent a new search request, any previously received 'More' gets invalid.
//CWnd* pWndFocus = GetFocus();
//m_pwndParams->m_ctlMore.EnableWindow(FALSE);
//if (pWndFocus && pWndFocus->m_hWnd == m_pwndParams->m_ctlMore.m_hWnd)
// m_pwndParams->m_ctlCancel.SetFocus();
m_iSentMoreReq = 0;
Packet* packet = new Packet(&data);
packet->opcode = OP_SEARCHREQUEST;
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T(">>> Sending OP__SearchRequest\n"));
theStats.AddUpDataOverheadServer(packet->size);
CGlobalVariable::serverconnect->SendPacket(packet,false);
if (pParams->eType == SearchTypeEd2kGlobal && CGlobalVariable::serverconnect->IsUDPSocketAvailable())
{
// set timeout timer for local server
m_uTimerLocalServer = SetTimer(TimerServerTimeout, 50000, NULL);
if (thePrefs.GetUseServerPriorities())
CGlobalVariable::serverlist->ResetSearchServerPos();
if (globsearch)
{
delete searchpacket;
searchpacket = NULL;
m_b64BitSearchPacket = false;
}
searchpacket = packet;
searchpacket->opcode = OP_GLOBSEARCHREQ; // will be changed later when actually sending the packet!!
m_b64BitSearchPacket = bPacketUsing64Bit;
servercount = 0;
searchprogress.SetRange32(0, CGlobalVariable::serverlist->GetServerCount() - 1);
globsearch = true;
}
else
{
globsearch = false;
delete packet;
}
//CreateNewTab(pParams);
searchlistctrl.ShowResults(pParams->dwSearchID);
return true;
}
bool CSearchResultsWnd::SearchMore()
{
if (!CGlobalVariable::serverconnect->IsConnected())
return false;
SetActiveSearchResultsIcon(m_nEd2kSearchID);
canceld = false;
Packet* packet = new Packet();
packet->opcode = OP_QUERY_MORE_RESULT;
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T(">>> Sending OP__QueryMoreResults\n"));
theStats.AddUpDataOverheadServer(packet->size);
CGlobalVariable::serverconnect->SendPacket(packet);
m_iSentMoreReq++;
return true;
}
bool CSearchResultsWnd::DoNewKadSearch(SSearchParams* pParams,UINT uSearchID/*=0*/)
{
if (!Kademlia::CKademlia::IsConnected())
return false;
int iPos = 0;
pParams->strKeyword = pParams->strExpression.Tokenize(_T(" "), iPos);
pParams->strKeyword.Trim();
if (pParams->strKeyword.IsEmpty() || pParams->strKeyword.FindOneOf(_aszInvKadKeywordChars) != -1){
CString strError;
strError.Format(GetResString(IDS_KAD_SEARCH_KEYWORD_INVALID), _aszInvKadKeywordChars);
throw new CMsgBoxException(strError, MB_ICONWARNING | MB_HELP, eMule_FAQ_Search - HID_BASE_PROMPT);
}
CSafeMemFile data(100);
if (!GetSearchPacket(&data, pParams, true, NULL)/* || (!pParams->strBooleanExpr.IsEmpty() && data.GetLength() == 0)*/)
return false;
LPBYTE pSearchTermsData = NULL;
UINT uSearchTermsSize = (UINT)data.GetLength();
if (uSearchTermsSize){
pSearchTermsData = new BYTE[uSearchTermsSize];
data.SeekToBegin();
data.Read(pSearchTermsData, uSearchTermsSize);
}
Kademlia::CSearch* pSearch = NULL;
try
{
pSearch = Kademlia::CSearchManager::PrepareFindKeywords(pParams->bUnicode, pParams->strKeyword, uSearchTermsSize, pSearchTermsData,uSearchID);
delete[] pSearchTermsData;
if (!pSearch){
ASSERT(0);
return false;
}
}
catch (CString strException)
{
delete[] pSearchTermsData;
throw new CMsgBoxException(strException, MB_ICONWARNING | MB_HELP, eMule_FAQ_Search - HID_BASE_PROMPT);
}
if(uSearchID==0)
{
pParams->dwSearchID = pSearch->GetSearchID();
CStringA strResultType = pParams->strFileType;
if (strResultType == ED2KFTSTR_PROGRAM)
strResultType.Empty();
CGlobalVariable::searchlist->NewSearch(&searchlistctrl, strResultType, pParams->dwSearchID, pParams->eType, pParams->strExpression);
}
//CreateNewTab(pParams);
searchlistctrl.ShowResults(pParams->dwSearchID);
return true;
}
bool CSearchResultsWnd::CreateNewTab(SSearchParams* pParams)
{
int iTabItems = searchselect.GetItemCount();
for (int i = 0; i < iTabItems; i++)
{
TCITEM tci;
tci.mask = TCIF_PARAM;
if (searchselect.GetItem(i, &tci) && tci.lParam != NULL && ((const SSearchParams*)tci.lParam)->dwSearchID == pParams->dwSearchID)
return false;
}
// add new tab
TCITEM newitem;
if (pParams->strExpression.IsEmpty())
pParams->strExpression = _T("-");
newitem.mask = TCIF_PARAM | TCIF_TEXT | TCIF_IMAGE;
newitem.lParam = (LPARAM)pParams;
pParams->strSearchTitle = (pParams->strSpecialTitle.IsEmpty() ? pParams->strExpression : pParams->strSpecialTitle);
newitem.pszText = const_cast<LPTSTR>((LPCTSTR)pParams->strSearchTitle);
newitem.cchTextMax = 0;
if (pParams->bClientSharedFiles)
newitem.iImage = sriClient;
else if (pParams->eType == SearchTypeKademlia)
newitem.iImage = sriKadActice;
else if (pParams->eType == SearchTypeEd2kGlobal)
newitem.iImage = sriGlobalActive;
else
{
ASSERT( pParams->eType == SearchTypeEd2kServer );
newitem.iImage = sriServerActive;
}
int itemnr = searchselect.InsertItem(INT_MAX, &newitem);
if (!searchselect.IsWindowVisible())
ShowSearchSelector(true);
searchselect.SetCurSel(itemnr);
//searchlistctrl.ShowResults(pParams->dwSearchID);
return true;
}
bool CSearchResultsWnd::CanDeleteSearch(uint32 /*nSearchID*/) const
{
return (searchselect.GetItemCount() > 0);
}
void CSearchResultsWnd::DeleteSearch(uint32 nSearchID)
{
Kademlia::CSearchManager::StopSearch(nSearchID, false);
TCITEM item;
item.mask = TCIF_PARAM;
item.lParam = -1;
int i;
for (i = 0; i < searchselect.GetItemCount(); i++) {
if (searchselect.GetItem(i, &item) && item.lParam != -1 && item.lParam != NULL && ((const SSearchParams*)item.lParam)->dwSearchID == nSearchID)
break;
}
if (item.lParam == -1 || item.lParam == NULL || ((const SSearchParams*)item.lParam)->dwSearchID != nSearchID)
return;
// delete search results
if (!canceld && nSearchID == m_nEd2kSearchID)
CancelEd2kSearch();
//if (nSearchID == m_nEd2kSearchID)
//m_pwndParams->m_ctlMore.EnableWindow(FALSE);
CGlobalVariable::searchlist->RemoveResults(nSearchID);
// clean up stored states (scrollingpos etc) for this search
searchlistctrl.ClearResultViewState(nSearchID);
// delete search tab
int iCurSel = searchselect.GetCurSel();
searchselect.DeleteItem(i);
delete (SSearchParams*)item.lParam;
int iTabItems = searchselect.GetItemCount();
if (iTabItems > 0){
// select next search tab
if (iCurSel == CB_ERR)
iCurSel = 0;
else if (iCurSel >= iTabItems)
iCurSel = iTabItems - 1;
(void)searchselect.SetCurSel(iCurSel); // returns CB_ERR if error or no prev. selection(!)
iCurSel = searchselect.GetCurSel(); // get the real current selection
if (iCurSel == CB_ERR) // if still error
iCurSel = searchselect.SetCurSel(0);
if (iCurSel != CB_ERR){
item.mask = TCIF_PARAM;
item.lParam = NULL;
if (searchselect.GetItem(iCurSel, &item) && item.lParam != NULL){
searchselect.HighlightItem(iCurSel, FALSE);
ShowResults((const SSearchParams*)item.lParam);
}
}
}
else{
searchlistctrl.DeleteAllItems();
ShowSearchSelector(false);
searchlistctrl.NoTabs();
}
}
bool CSearchResultsWnd::CanDeleteAllSearches() const
{
return (searchselect.GetItemCount() > 0);
}
void CSearchResultsWnd::DeleteAllSearches()
{
CancelEd2kSearch();
for (int i = 0; i < searchselect.GetItemCount(); i++){
TCITEM item;
item.mask = TCIF_PARAM;
item.lParam = -1;
if (searchselect.GetItem(i, &item) && item.lParam != -1 && item.lParam != NULL){
Kademlia::CSearchManager::StopSearch(((const SSearchParams*)item.lParam)->dwSearchID, false);
delete (SSearchParams*)item.lParam;
}
}
CGlobalVariable::searchlist->Clear();
searchlistctrl.DeleteAllItems();
ShowSearchSelector(false);
searchselect.DeleteAllItems();
//CWnd* pWndFocus = GetFocus();
//m_pwndParams->m_ctlMore.EnableWindow(FALSE);
//m_pwndParams->m_ctlCancel.EnableWindow(FALSE);
//m_pwndParams->m_ctlStart.EnableWindow(TRUE);
//if (pWndFocus && (pWndFocus->m_hWnd == m_pwndParams->m_ctlMore.m_hWnd || pWndFocus->m_hWnd == m_pwndParams->m_ctlCancel.m_hWnd))
// m_pwndParams->m_ctlStart.SetFocus();
}
void CSearchResultsWnd::ShoweasyMuleFileSearch( DWORD dwSearchID )
{
CFileSearch* pFileSearch = NULL;
m_FileSearchMap.Lookup(dwSearchID,pFileSearch);
if( pFileSearch )
{
searchlistctrl.ShowResults(dwSearchID,pFileSearch);
m_iCurSearchIndexInRes = dwSearchID;
}
}
void CSearchResultsWnd::ShowResults(const SSearchParams* pParams)
{
// restoring the params works and is nice during development/testing but pretty annoying in practice.
// TODO: maybe it should be done explicitly via a context menu function or such.
//if (GetAsyncKeyState(VK_CONTROL) < 0)
//m_pwndParams->SetParameters(pParams);
//if (pParams->eType == SearchTypeEd2kServer)
//{
// m_pwndParams->m_ctlCancel.EnableWindow(pParams->dwSearchID == m_nEd2kSearchID && IsLocalEd2kSearchRunning());
//}
//else if (pParams->eType == SearchTypeEd2kGlobal)
//{
// m_pwndParams->m_ctlCancel.EnableWindow(pParams->dwSearchID == m_nEd2kSearchID && (IsLocalEd2kSearchRunning() || IsGlobalEd2kSearchRunning()));
//}
//else if (pParams->eType == SearchTypeKademlia)
//{
// m_pwndParams->m_ctlCancel.EnableWindow(Kademlia::CSearchManager::IsSearching(pParams->dwSearchID));
//}
searchlistctrl.ShowResults(pParams->dwSearchID);
}
void CSearchResultsWnd::OnSelChangeTab(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
CWaitCursor curWait; // this may take a while
int cur_sel = searchselect.GetCurSel();
if (cur_sel == -1)
return;
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem(cur_sel, &item) && item.lParam != NULL)
{
searchselect.HighlightItem(cur_sel, FALSE);
ShowResults((const SSearchParams*)item.lParam);
}
*pResult = 0;
}
LRESULT CSearchResultsWnd::OnCloseTab(WPARAM wParam, LPARAM /*lParam*/)
{
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem((int)wParam, &item) && item.lParam != NULL)
{
int nSearchID = ((const SSearchParams*)item.lParam)->dwSearchID;
if (!canceld && (UINT)nSearchID == m_nEd2kSearchID)
CancelEd2kSearch();
DeleteSearch(nSearchID);
}
return TRUE;
}
LRESULT CSearchResultsWnd::OnDblClickTab(WPARAM wParam, LPARAM /*lParam*/)
{
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem((int)wParam, &item) && item.lParam != NULL)
{
//m_pwndParams->SetParameters((const SSearchParams*)item.lParam);
}
return TRUE;
}
void CSearchResultsWnd::UpdateCatTabs()
{
int oldsel=m_cattabs.GetCurSel();
m_cattabs.DeleteAllItems();
for (int ix=0;ix<thePrefs.GetCatCount();ix++) {
CString label=(ix==0)?GetResString(IDS_ALL):thePrefs.GetCategory(ix)->strTitle;
label.Replace(_T("&"),_T("&&"));
m_cattabs.InsertItem(ix,label);
}
if (oldsel>=m_cattabs.GetItemCount() || oldsel==-1)
oldsel=0;
m_cattabs.SetCurSel(oldsel);
int flag;
flag=(m_cattabs.GetItemCount()>1) ? SW_SHOW:SW_HIDE;
GetDlgItem(IDC_CATTAB2)->ShowWindow(flag);
GetDlgItem(IDC_STATIC_DLTOof)->ShowWindow(flag);
}
void CSearchResultsWnd::ShowSearchSelector(bool visible)
{
WINDOWPLACEMENT wpSearchWinPos;
WINDOWPLACEMENT wpSelectWinPos;
searchselect.GetWindowPlacement(&wpSelectWinPos);
searchlistctrl.GetWindowPlacement(&wpSearchWinPos);
if (visible)
wpSearchWinPos.rcNormalPosition.top = wpSelectWinPos.rcNormalPosition.bottom;
else
wpSearchWinPos.rcNormalPosition.top = wpSelectWinPos.rcNormalPosition.top;
searchselect.ShowWindow(visible ? SW_SHOW : SW_HIDE);
RemoveAnchor(searchlistctrl);
searchlistctrl.SetWindowPlacement(&wpSearchWinPos);
AddAnchor(searchlistctrl, TOP_LEFT, BOTTOM_RIGHT);
GetDlgItem(IDC_CLEARALL)->ShowWindow(visible ? SW_SHOW : SW_HIDE);
m_ctlFilter.ShowWindow(visible ? SW_SHOW : SW_HIDE);
}
void CSearchResultsWnd::OnDestroy()
{
int iTabItems = searchselect.GetItemCount();
__try{
for (int i = 0; i < iTabItems; i++){
TCITEM tci;
tci.mask = TCIF_PARAM;
if (searchselect.GetItem(i, &tci) && tci.lParam != NULL){
delete (SSearchParams*)tci.lParam;
}
}
}
__except(true)
{
}
m_imlSearchMethods.DeleteImageList();
CResizableFormView::OnDestroy();
}
void CSearchResultsWnd::OnSize(UINT nType, int cx, int cy)
{
CResizableFormView::OnSize(nType, cx, cy);
}
void CSearchResultsWnd::OnClose()
{
// Do not pass the WM_CLOSE to the base class. Since we have a rich edit control *and* an attached auto complete
// control, the WM_CLOSE will get generated by the rich edit control when user presses ESC while the auto complete
// is open.
//__super::OnClose();
}
BOOL CSearchResultsWnd::OnHelpInfo(HELPINFO* /*pHelpInfo*/)
{
theApp.ShowHelp(eMule_FAQ_Search);
return TRUE;
}
LRESULT CSearchResultsWnd::OnIdleUpdateCmdUI(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
//BOOL bSearchParamsWndVisible = theApp.emuledlg->searchwnd->IsSearchParamsWndVisible();
//if (!bSearchParamsWndVisible) {
// m_ctlOpenParamsWnd.ShowWindow(SW_SHOW);
//}
//else {
// m_ctlOpenParamsWnd.ShowWindow(SW_HIDE);
//}
return 0;
}
void CSearchResultsWnd::OnBnClickedOpenParamsWnd()
{
theApp.emuledlg->searchwnd->OpenParametersWnd();
}
void CSearchResultsWnd::OnSysCommand(UINT nID, LPARAM lParam)
{
if (nID == SC_KEYMENU)
{
if (lParam == EMULE_HOTMENU_ACCEL)
theApp.emuledlg->SendMessage(WM_COMMAND, IDC_HOTMENU);
else
theApp.emuledlg->SendMessage(WM_SYSCOMMAND, nID, lParam);
return;
}
__super::OnSysCommand(nID, lParam);
}
bool CSearchResultsWnd::CanSearchRelatedFiles() const
{
return CGlobalVariable::serverconnect->IsConnected()
&& CGlobalVariable::serverconnect->GetCurrentServer() != NULL
&& CGlobalVariable::serverconnect->GetCurrentServer()->GetRelatedSearchSupport();
}
void CSearchResultsWnd::SearchRelatedFiles(const CAbstractFile* file)
{
SSearchParams* pParams = new SSearchParams;
pParams->strExpression = _T("related::") + md4str(file->GetFileHash());
pParams->strSpecialTitle = GetResString(IDS_RELATED) + _T(": ") + file->GetFileName();
if (pParams->strSpecialTitle.GetLength() > 50)
pParams->strSpecialTitle = pParams->strSpecialTitle.Left(50) + _T("...");
StartSearch(pParams);
}
///////////////////////////////////////////////////////////////////////////////
// CSearchResultsSelector
BEGIN_MESSAGE_MAP(CSearchResultsSelector, CClosableTabCtrl)
ON_WM_CONTEXTMENU()
END_MESSAGE_MAP()
BOOL CSearchResultsSelector::OnCommand(WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case MP_RESTORESEARCHPARAMS:{
int iTab = GetTabUnderContextMenu();
if (iTab != -1) {
GetParent()->SendMessage(UM_DBLCLICKTAB, (WPARAM)iTab);
return TRUE;
}
break;
}
}
return CClosableTabCtrl::OnCommand(wParam, lParam);
}
void CSearchResultsSelector::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
{
CTitleMenu menu;
menu.CreatePopupMenu();
menu.AddMenuTitle(GetResString(IDS_SW_RESULT));
menu.AppendMenu(MF_STRING, MP_RESTORESEARCHPARAMS, GetResString(IDS_RESTORESEARCHPARAMS));
menu.AppendMenu(MF_STRING, MP_REMOVE, GetResString(IDS_FD_CLOSE));
menu.SetDefaultItem(MP_RESTORESEARCHPARAMS);
m_ptCtxMenu = point;
ScreenToClient(&m_ptCtxMenu);
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
}
LRESULT CSearchResultsWnd::OnChangeFilter(WPARAM wParam, LPARAM lParam)
{
CWaitCursor curWait; // this may take a while
m_nFilterColumn = (uint32)wParam;
CStringArray astrFilter;
CString strFullFilterExpr = (LPCTSTR)lParam;
int iPos = 0;
CString strFilter(strFullFilterExpr.Tokenize(_T(" "), iPos));
while (!strFilter.IsEmpty()) {
if (strFilter != _T("-"))
astrFilter.Add(strFilter);
strFilter = strFullFilterExpr.Tokenize(_T(" "), iPos);
}
bool bFilterDiff = (astrFilter.GetSize() != m_astrFilter.GetSize());
if (!bFilterDiff) {
for (int i = 0; i < astrFilter.GetSize(); i++) {
if (astrFilter[i] != m_astrFilter[i]) {
bFilterDiff = true;
break;
}
}
}
if (!bFilterDiff)
return 0;
m_astrFilter.RemoveAll();
m_astrFilter.Append(astrFilter);
int iCurSel = searchselect.GetCurSel();
if (iCurSel == -1)
return 0;
TCITEM item;
item.mask = TCIF_PARAM;
if (searchselect.GetItem(iCurSel, &item) && item.lParam != NULL)
ShowResults((const SSearchParams*)item.lParam);
return 0;
}
void CSearchResultsWnd::OnSearchListMenuBtnDropDown(NMHDR* /*pNMHDR*/, LRESULT* /*pResult*/)
{
CTitleMenu menu;
menu.CreatePopupMenu();
menu.AppendMenu(MF_STRING | (searchselect.GetItemCount() > 0 ? MF_ENABLED : MF_GRAYED), MP_REMOVEALL, GetResString(IDS_REMOVEALLSEARCH));
menu.AppendMenu(MF_SEPARATOR);
CMenu menuFileSizeFormat;
menuFileSizeFormat.CreateMenu();
menuFileSizeFormat.AppendMenu(MF_STRING, MP_SHOW_FILESIZE_DFLT, GetResString(IDS_DEFAULT));
menuFileSizeFormat.AppendMenu(MF_STRING, MP_SHOW_FILESIZE_KBYTE, GetResString(IDS_KBYTES));
menuFileSizeFormat.AppendMenu(MF_STRING, MP_SHOW_FILESIZE_MBYTE, GetResString(IDS_MBYTES));
menuFileSizeFormat.CheckMenuRadioItem(MP_SHOW_FILESIZE_DFLT, MP_SHOW_FILESIZE_MBYTE, MP_SHOW_FILESIZE_DFLT + searchlistctrl.GetFileSizeFormat(), 0);
menu.AppendMenu(MF_POPUP, (UINT_PTR)menuFileSizeFormat.m_hMenu, GetResString(IDS_DL_SIZE));
CRect rc;
m_btnSearchListMenu->GetWindowRect(&rc);
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, rc.left, rc.bottom, this);
}
BOOL CSearchResultsWnd::OnCommand(WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case MP_REMOVEALL:
DeleteAllSearches();
return TRUE;
case MP_SHOW_FILESIZE_DFLT:
searchlistctrl.SetFileSizeFormat(fsizeDefault);
return TRUE;
case MP_SHOW_FILESIZE_KBYTE:
searchlistctrl.SetFileSizeFormat(fsizeKByte);
return TRUE;
case MP_SHOW_FILESIZE_MBYTE:
searchlistctrl.SetFileSizeFormat(fsizeMByte);
return TRUE;
}
return CResizableFormView::OnCommand(wParam, lParam);
}
void CSearchResultsWnd::OnBnClickedButtonSearch()
{
CString str;
m_SearchCtrl.GetWindowText(str);
if(str.IsEmpty())
{
return;
}
else
{
//VC-dgkang 2008年7月9日
if (searchlistctrl.GetItemCount() != 0)
{
ESearchType SearchType = SearchAreaToType((ESearchArea)m_ctlMethod.GetCurSel());
CmdFuncs::CreateNewTabForSearchED2K(str,&SearchType);
}
else
{
CmdFuncs::SetResActiveSearchTabText(GetResString(IDS_TABTITLE_SEARCH_RESULT) + str);
SSearchParams * pSearchParams = GetParameters(str);
if (StartSearch(pSearchParams))
CmdFuncs::UpdateResSearchParam(m_iCurSearchIndexInRes, pSearchParams);
//VC-dgkang 2008年7月9日
/*
if(theApp.emuledlg && theApp.emuledlg->m_mainTabWnd.GetActiveTab() == theApp.emuledlg->m_mainTabWnd.m_aposTabs[CMainTabWnd::TI_RESOURCE])
theApp.emuledlg->m_mainTabWnd.m_dlgResource.UpdateEMsClosableStatus();
else */
if(theApp.emuledlg && theApp.emuledlg->m_mainTabWnd.GetActiveTab() == theApp.emuledlg->m_mainTabWnd.m_aposTabs[CMainTabWnd::TI_SEARCH])
theApp.emuledlg->m_mainTabWnd.m_dlgSearch.UpdateEMsClosableStatus();
}
}
}
SSearchParams* CSearchResultsWnd::GetParameters(CString expression)
{
CString strExpression = expression;
CString strExtension;
UINT uAvailability = 0;
UINT uComplete = 0;
CString strCodec;
ULONG ulMinBitrate = 0;
ULONG ulMinLength = 0;
SSearchParams* pParams = new SSearchParams;
pParams->strExpression = strExpression;
pParams->eType = SearchTypeEasyMuleFile; //SearchTypeEd2kGlobal;
pParams->strFileType = _T("");
pParams->strMinSize = _T("");
pParams->ullMinSize = 0;
pParams->strMaxSize = _T("");
pParams->ullMaxSize = 0;
pParams->uAvailability = uAvailability;
pParams->strExtension = strExtension;
pParams->uComplete = uComplete;
pParams->strCodec = strCodec;
pParams->ulMinBitrate = ulMinBitrate;
pParams->ulMinLength = ulMinLength;
pParams->eType = SearchAreaToType((ESearchArea)m_ctlMethod.GetCurSel());
return pParams;
}
void CSearchResultsWnd::UpdateParamDisplay(SSearchParams* pParams)
{
m_ctlMethod.SetCurSel(SearchTypeToArea(pParams->eType));
m_SearchCtrl.SetWindowText(pParams->strExpression);
}
ESearchType CSearchResultsWnd::SearchAreaToType(ESearchArea eArea)
{
switch(eArea)
{
case SearchAreaEasyMuleFile:
return SearchTypeEasyMuleFile;
break;
/*
case SearchAreaVCAutomatic:
return SearchTypeVCAutomatic;
break;
*/
case SearchAreaEd2kGlobal:
return SearchTypeEd2kGlobal;
break;
case SearchAreaKademlia:
return SearchTypeKademlia;
break;
default:
break;
}
return SearchTypeEasyMuleFile;
}
CSearchResultsWnd::ESearchArea CSearchResultsWnd::SearchTypeToArea(ESearchType eType)
{
switch(eType)
{
case SearchTypeEasyMuleFile:
return SearchAreaEasyMuleFile;
break;
/*
case SearchTypeVCAutomatic:
return SearchAreaVCAutomatic;
break;
*/
case SearchTypeEd2kGlobal:
return SearchAreaEd2kGlobal;
break;
case SearchTypeKademlia:
return SearchAreaKademlia;
break;
default:
break;
}
return SearchAreaEd2kGlobal;
}
BOOL CSearchResultsWnd::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam == VK_RETURN)
{
OnBnClickedButtonSearch();
}
}
return CResizableFormView::PreTranslateMessage(pMsg);
}
void CSearchResultsWnd::SetPos(int pos)
{
searchprogress.SetPos(pos);
CancelEd2kSearch();
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
2127
]
]
] |
a26f35e8ae0444ac587526699c320b28154f5810 | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/SmartWires/SmartWndSizer/SmartWndSizer.cpp | dacff5b3e9718715bab8711bdc4af9ac58b9c7ac | [] | 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 | 42,594 | cpp | // SmartWndSizer.cpp: implementation of the CSmartWndSizer class.
//
//////////////////////////////////////////////////////////////////////
#include "SmartWndSizer.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define ADDDEBUGCHAR(c)
//#define ADDDEBUGCHAR(c) {CString s;m_pMain->GetWindowText(s);s=CString(c)+s;m_pMain->SetWindowText(s);}
typedef struct tagMENUBARINFO
{
DWORD cbSize;
RECT rcBar; // rect of bar, popup, item
HMENU hMenu; // real menu handle of bar, popup
HWND hwndMenu; // hwnd of item submenu if one
BOOL fBarFocused:1; // bar, popup has the focus
BOOL fFocused:1; // item has the focus
} MENUBARINFO, *PMENUBARINFO, *LPMENUBARINFO;
typedef BOOL (WINAPI *_GetMenuBarInfo)(HWND hwnd,LONG idObject,LONG idItem,MENUBARINFO* pmbi);
CSmartCritSection& GetSizerLock()
{
static CSmartCritSection cs;
return cs;
}
CSmartCritSection* CSmartWndSizer::rectLock=&GetSizerLock();
CArray<SizerWnd,SizerWnd&>* CSmartWndSizer::m_AllWndSizerRectangles=NULL;
int CSmartWndSizer::iGlobalCounter=0;
CRect CSmartWndSizer::DesktopDialogRect(0,0,0,0);
BOOL CSmartWndSizer::bSlowMachine=-1;
CSmartWndSizer::CSmartWndSizer()
{
m_iSaWi=0;
iMenuH=-1;
bMaximized=0;
bSkipResize=0;
if(iGlobalCounter==0){
//rectLock=new CSmartCritSection();
m_AllWndSizerRectangles=new CArray<SizerWnd,SizerWnd&>;
}
iGlobalCounter++;
if(bSlowMachine==-1){
bSlowMachine=GetSystemMetrics(SM_SLOWMACHINE);
}
iInit=0;m_hKeyRoot=HKEY_CURRENT_USER;m_dwOptions=STICKABLE;
if(DesktopDialogRect.IsRectEmpty()){
//::SystemParametersInfo(SPI_GETWORKAREA,0,&DesktopDialogRect,0);
DesktopDialogRect=GetAllMonitorsRECT();
}
bInResizingLock=0;
dwSizerLevel=0;
bMessageRecursingPreventer=0;
bResizingElementsArePresent=-1;
pResizeAffectedWnd=NULL;
iInPresetPosition=0;
hResizeCur=NULL;
iAffectType=-1;
};
CSmartWndSizer::~CSmartWndSizer()
{
SaveSizeAndPosToRegistry();
iInit=0;
int i=0;
{
CSmartLocker lock(rectLock);
int iMax=m_AllWndSizerRectangles->GetSize();
for(i=0; i<iMax;i++){
SizerWnd& aRect=(*m_AllWndSizerRectangles)[i];
DWORD dwWnd1=DWORD(aRect.pWnd);
DWORD dwWnd2=DWORD(m_pMain);
if(dwWnd1==dwWnd2){
m_AllWndSizerRectangles->RemoveAt(i);
break;
}
}
}
for(i=0;i<m_AlignRules.GetSize();i++){
delete m_AlignRules[i];
}
m_AlignRules.RemoveAll();
int iKey;
CSmartWndSizer_Element* pElem;
POSITION p=m_WndElements.GetStartPosition();
while(p!=NULL){
m_WndElements.GetNextAssoc(p, iKey, pElem);
delete pElem;
}
m_WndElements.RemoveAll();
m_Labels.RemoveAll();
iGlobalCounter--;
if(iGlobalCounter==0){
//delete rectLock;rectLock=0;
delete m_AllWndSizerRectangles;
m_AllWndSizerRectangles=0;
}
if(hInternalWnd.m_hWnd){
hInternalWnd.Detach();
}
}
void CSmartWndSizer::InitSizer(HWND pMainWnd, int iStickness, HKEY hKeyRoot,const char* szKey)
{
hInternalWnd.Attach(pMainWnd);
InitSizer(&hInternalWnd, iStickness, hKeyRoot,szKey);
}
void CSmartWndSizer::InitSizer(CWnd* pMainWnd, int iStickness, HKEY hKeyRoot,const char* szKey)
{
CSmartLocker lock(rectLock);
if(!IsWindow(pMainWnd->GetSafeHwnd())){
return;
}
m_rMain.SetRect(0,0,0,0);
m_rMainMin.SetRect(0,0,0,0);
m_rMainMax.SetRect(0,0,0,0);
m_pMain=pMainWnd;
m_hKeyRoot=hKeyRoot;
m_szRegKey=szKey;
m_iStickness=iStickness;
SizerWnd pObj;
pObj.pWnd=m_pMain;
m_AllWndSizerRectangles->Add(pObj);
iInit=2;
}
CSmartWndSizer& CSmartWndSizer::operator=(CSmartWndSizer& pCopy)
{
m_pMain=pCopy.m_pMain;
m_szRegKey=pCopy.m_szRegKey;
m_iStickness=pCopy.m_iStickness;
iInit=pCopy.iInit;
m_rMainMin.CopyRect(pCopy.m_rMainMin);
m_rMainMax.CopyRect(pCopy.m_rMainMax);
m_dwOptions=pCopy.m_dwOptions;
// Копируем элементы...
int iKey;
CSmartWndSizer_Element* pElem;
POSITION p=m_WndElements.GetStartPosition();
while(p!=NULL){
m_WndElements.GetNextAssoc(p, iKey, pElem);
delete pElem;
}
m_WndElements.RemoveAll();
p=pCopy.m_WndElements.GetStartPosition();
while(p!=NULL){
pCopy.m_WndElements.GetNextAssoc(p, iKey, pElem);
m_WndElements[iKey]=pElem->Copy();
}
// Копируем правила...
for(int i=0;i<m_AlignRules.GetSize();i++){
delete m_AlignRules[i];
}
m_AlignRules.RemoveAll();
m_AlignRules.Copy(pCopy.m_AlignRules);
// копируем метки...
m_Labels.RemoveAll();
DWORD dwKey, dwLabelID;
p=pCopy.m_Labels.GetStartPosition();
while(p!=NULL){
pCopy.m_Labels.GetNextAssoc(p, dwKey, dwLabelID);
m_Labels[dwKey]=dwLabelID;
}
return *this;
}
int CSmartWndSizer::AddDialogElement(int ID, DWORD dwFixed, int iFixedFrom)
{
if(ID==0 || !iInit){
return FALSE;
}
CSmartWndSizer_Element* bPrevElem=NULL;
if(m_WndElements.Lookup(ID,bPrevElem) && bPrevElem!=NULL){
delete bPrevElem;
}
m_WndElements.SetAt(ID,new CSmartWndSizer_Element(ID,dwFixed,iFixedFrom));
if(dwFixed & transparent){
CWnd* pWnd=m_pMain->GetDlgItem(ID);
SetWindowLong(pWnd->GetSafeHwnd(),GWL_EXSTYLE,GetWindowLong(pWnd->GetSafeHwnd(),GWL_EXSTYLE)|WS_EX_TRANSPARENT);//WS_EX_COMPOSITED-0x02000000L
pWnd->Invalidate();
}
return TRUE;
}
void CSmartWndSizer::SetStickness(int iStickness)
{
m_iStickness=iStickness;
}
int CSmartWndSizer::GetWindowMenuHeightSW(BOOL bForceReCalc)
{
if(m_pMain->GetMenu() && (iMenuH==-1 || bForceReCalc)){
MENUBARINFO pmbi;
memset(&pmbi,0,sizeof(pmbi));
pmbi.cbSize=sizeof(pmbi);
static HINSTANCE hUser32=HINSTANCE(-1);
if(hUser32==HINSTANCE(-1)){
hUser32=GetModuleHandle("user32.dll");
}
if(hUser32){
static _GetMenuBarInfo fp=_GetMenuBarInfo(-1);
if(fp==_GetMenuBarInfo(-1)){
fp=(_GetMenuBarInfo)::GetProcAddress(hUser32,"GetMenuBarInfo");
}
if(fp){
(*fp)(m_pMain->m_hWnd,0xFFFFFFFD,0,&pmbi);//OBJID_MENU
iMenuH=(pmbi.rcBar.bottom-pmbi.rcBar.top);
}
}
}
return iMenuH;
}
void CSmartWndSizer::UpdateClientOffsets()
{
iMenuH=-1;
CRect rtClient;
m_pMain->GetClientRect(&rtClient);
m_pMain->ClientToScreen(&rtClient);
lClientOffsetL=rtClient.left-m_rMain.left;
lClientOffsetR=m_rMain.right-rtClient.right;//-GetSystemMetrics(SM_CXDLGFRAME);SM_CYSIZEFRAME
lClientOffsetT=rtClient.top-m_rMain.top;
lClientOffsetB=m_rMain.bottom-rtClient.bottom;//-GetSystemMetrics(SM_CYDLGFRAME);
// Если подчиненное окно находится за пределами главного - игнорируем его offset!
if(lClientOffsetR<0){
lClientOffsetR=0;
lClientOffsetL=0;
}
if(lClientOffsetB<0){
lClientOffsetB=0;
lClientOffsetT=0;
}
}
BOOL CSmartWndSizer::SmartPRESetWindowPosition()
{
iInPresetPosition++;
// Считываем минимальный размер...
BOOL bLoadRes=LoadSizeAndPosFromRegistry();
if((m_dwOptions & FIXEDSIZE) && (m_rMainMin.Width()>0 || m_rMainMin.Height()>0)){
if(m_rMainMin.Width()>0){
m_rMain.right=m_rMain.left+m_rMainMin.Width();
}
if(m_rMainMin.Height()>0){
m_rMain.bottom=m_rMain.top+m_rMainMin.Height();
}
}
if(!m_rMainMax.IsRectEmpty()){
if(m_rMain.Width()>m_rMainMax.Width()){
m_rMain.right=m_rMain.left+m_rMainMax.Width();
}
if(m_rMain.Height()>m_rMainMax.Height()){
m_rMain.bottom=m_rMain.top+m_rMainMax.Height();
}
}
if(m_pMain==NULL || !::IsWindow(m_pMain->m_hWnd)){
return FALSE;
}
/*
if(m_dwOptions & DOUBLEBUFFER){
SetWindowLong(m_pMain->m_hWnd,GWL_EXSTYLE,GetWindowLong(m_pMain->m_hWnd,GWL_EXSTYLE)|0x02000000L);//WS_EX_COMPOSITED-0x02000000L
}
*/
iInit=1;
RECT rect;
m_pMain->GetWindowRect(&rect);
if(m_rMain.IsRectEmpty()){
m_rMain.CopyRect(&rect);
};
if(m_dwOptions & CENTERUNDERMOUSE){
CPoint p;
::GetCursorPos(&p);
long w=m_rMain.Width();
m_rMain.left=p.x-w/2;
m_rMain.right=p.x+w/2;
long h=m_rMain.Height();
m_rMain.top=p.y-h/2;
m_rMain.bottom=p.y+h/2;
TestOnScreenOut(m_rMain,m_iStickness,1,1);
}
TestStickness(m_rMain, FALSE);
m_pMain->MoveWindow(m_rMain);
if(bMaximized){
m_pMain->SendMessage(WM_SYSCOMMAND,SC_MAXIMIZE,0);
}
// Запоминаем соотношение между клиентской и всем окном
UpdateClientOffsets();
ADDDEBUGCHAR("1");
ApplyLayout();
//------------------------------------------
iInPresetPosition--;
return TRUE;
}
int CSmartWndSizer::ApplyShowRules(BOOL bFullCheck)
{// Скрываем/показываем окна
if(iInPresetPosition){
return 0;
}
int iID=0;
CSmartWndSizer_Element* pControlWnd;
POSITION p=m_WndElements.GetStartPosition();
while(p){
m_WndElements.GetNextAssoc(p,iID,pControlWnd);
if(pControlWnd && (pControlWnd->m_dwFixed & alwaysInvisible)!=0){
CWnd* pControl=m_pMain->GetDlgItem(pControlWnd->m_ID);
pControl->ShowWindow(SW_HIDE);
}
if(pControlWnd && (pControlWnd->m_dwFixed & hidable)!=0){
CWnd* pControl=m_pMain->GetDlgItem(pControlWnd->m_ID);
if(pControl && (bFullCheck?(::IsWindow(pControl->GetSafeHwnd())):TRUE)){
BOOL bIntersected=IsWindowIntersected(iID,bFullCheck,TRUE);
BOOL bVisible=bFullCheck?(::IsWindowVisible(pControl->GetSafeHwnd())):TRUE;
BOOL bStateSet=-1;
if(bIntersected && bVisible){
bStateSet=SW_HIDE;
}
if(!bIntersected && !bVisible && pControlWnd->m_bCanBeVisible){
bStateSet=SW_SHOW;
}
if(bStateSet!=-1){
pControl->ShowWindow(bStateSet);
}
}
}
}
return 1;
}
int CSmartWndSizer::ApplyLayout(BOOL bClearCash, BOOL bCheckIfOnlyRules)
{
if(iInit==0 || !::IsWindow(m_pMain->m_hWnd)){
return FALSE;
};
if((m_dwOptions & SIZEABLE)==0 && (m_dwOptions & FIXEDXSIZE)==0 && (m_dwOptions & FIXEDYSIZE)==0 && (m_dwOptions & FIXEDSIZE)==0){
return FALSE;
}
if(bClearCash){
// Очищаем кеш местоположений
int iKey;
CSmartWndSizer_Element* pElem;
POSITION p=m_WndElements.GetStartPosition();
while(p!=NULL){
m_WndElements.GetNextAssoc(p, iKey, pElem);
pElem->m_Rect.top=-1;
}
}
BOOL bIfOnlyRuleTriggered=0;
int i=0;
for(i=0;i<m_AlignRules.GetSize();i++){
////////////////
// Подготовка...
CSmartWndSizer_AlignRule* pCurRule=m_AlignRules[i];
////////////////
// Переходы если есть...
if(pCurRule->m_GotoLabel!=-1){
DWORD dwNewIndex;
if(m_Labels.Lookup(pCurRule->m_GotoLabel,dwNewIndex)){
i=dwNewIndex-1;
continue;
}
}
if(pCurRule->m_Level!=0 && (pCurRule->m_Level & dwSizerLevel)==0){
// не тот уровень...
continue;
}
////////////////
CRect rTo;
CRect rFrom;
CSmartWndSizer_Element* pWnd;
//////////////////
// Откуда брать...
if(pCurRule->m_TakeFrom==0){
m_pMain->GetClientRect(&rFrom);
//rFrom.bottom-=lClientOffsetB;
//rFrom.right-=lClientOffsetR;
/*
rFrom.CopyRect(m_rMain);
rFrom.OffsetRect(-m_rMain.left,-m_rMain.top);
rFrom.bottom-=lClientOffsetT+lClientOffsetB;
rFrom.right-=lClientOffsetL+lClientOffsetR;
*/
}else{
if(!m_WndElements.Lookup(pCurRule->m_TakeFrom,pWnd)){
continue;
}
if(pWnd->m_Rect.top==-1){
m_pMain->GetDlgItem(pWnd->m_ID)->GetWindowRect(rFrom);
CRect rScreenBase;
m_pMain->GetWindowRect(rScreenBase);
rFrom.OffsetRect(-rScreenBase.left,-rScreenBase.top);
pWnd->m_Rect=rFrom;
}else{
rFrom=pWnd->m_Rect;
}
}
/////////////////
// Куда ложить...
if(pCurRule->m_TargetElement==0){
// Нельзя применять align к главному окну
continue;
}
CSmartWndSizer_Element* pToWnd=NULL;
if(!m_WndElements.Lookup(pCurRule->m_TargetElement,pToWnd)){
continue;
}
CWnd* p_IDWnd=m_pMain->GetDlgItem(pToWnd->m_ID);
if(!p_IDWnd || !::IsWindow(p_IDWnd->GetSafeHwnd())){
continue;
}
if(pToWnd->m_Rect.top==-1){
p_IDWnd->GetWindowRect(rTo);
m_pMain->ScreenToClient(rTo);
pToWnd->m_Rect=rTo;
}else{
rTo=pToWnd->m_Rect;
}
/////////////////////////////////
// Фиксировать параметры с чем...
DWORD dwFixes=pToWnd->m_dwFixed;
CRect rFixedFrom;
if(pToWnd->m_iFixedFrom==0){
// оригинальные значения...
rFixedFrom=rTo;
}else{
// неоригинальные значения...
if((pToWnd->m_dwFixed) & fixedDimensions){
// Жестко заданное значение...
rFixedFrom=rTo;
rFixedFrom.right=rFixedFrom.left+pToWnd->m_iFixedFrom;
rFixedFrom.bottom=rFixedFrom.top+pToWnd->m_iFixedFrom;
}else{
// С другого элемента...
CSmartWndSizer_Element* pFixedFrom=NULL;
if(!m_WndElements.Lookup(pToWnd->m_iFixedFrom,pFixedFrom)){
continue;
}
if(pFixedFrom->m_Rect.top==-1){
(m_pMain->GetDlgItem(pFixedFrom->m_ID))->GetWindowRect(rFixedFrom);
m_pMain->ScreenToClient(rFixedFrom);
pFixedFrom->m_Rect=rFixedFrom;
}else{
rFixedFrom=pFixedFrom->m_Rect;
}
}
}
///////////////////////
// Вытаскиваем значения
BOOL bIfOnlyBigger=(pCurRule->m_TakeWhat & ifBigger);
BOOL bIfOnlyLess=(pCurRule->m_TakeWhat & ifLess);
if(!bCheckIfOnlyRules && (bIfOnlyLess|bIfOnlyBigger)){
continue;
}
long lValue=0;
if((pCurRule->m_TakeWhat & visibility)!=0 && p_IDWnd){
if(pCurRule->m_Spacing){
if(!p_IDWnd->IsWindowVisible()){
pToWnd->m_bCanBeVisible=TRUE;
//CString sT;p_IDWnd->GetWindowText(sT);
p_IDWnd->ShowWindow(SW_SHOW);
}
}else{
if(p_IDWnd->IsWindowVisible()){
pToWnd->m_bCanBeVisible=FALSE;
p_IDWnd->ShowWindow(SW_HIDE);
}
}
continue;
}else if(pCurRule->m_TakeWhat & leftPos){
lValue=rFrom.left;
}else if(pCurRule->m_TakeWhat & rightPos){
lValue=rFrom.right;
}else if(pCurRule->m_TakeWhat & topPos){
lValue=rFrom.top;
}else if(pCurRule->m_TakeWhat & bottomPos){
lValue=rFrom.bottom;
}else if(pCurRule->m_TakeWhat & widthSize){
lValue=rFrom.Width();
}else if(pCurRule->m_TakeWhat & heightSize){
lValue=rFrom.Height();
}else if(pCurRule->m_TakeWhat & topCenter){
lValue=rFrom.left+(rFrom.Width()/2);
}else if(pCurRule->m_TakeWhat & sideCenter){
lValue=rFrom.top+(rFrom.Height()/2);
}else{
// Странно ... сюда попадать не должно!
}
lValue=lValue+pCurRule->m_Spacing;
//////////////
// Выравниваем
if(pCurRule->m_ApplyToWhat & leftPos){
if(bIfOnlyBigger){
if(rTo.left<lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
if(bIfOnlyLess){
if(rTo.left>lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
rTo.left=lValue;
if(!bIfOnlyRuleTriggered && (dwFixes & widthSize)){
rTo.right=rTo.left+rFixedFrom.Width();
}
}
if(pCurRule->m_ApplyToWhat & rightPos){
if(bIfOnlyBigger){
if(rTo.right<lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
if(bIfOnlyLess){
if(rTo.right>lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
rTo.right=lValue;
if(!bIfOnlyRuleTriggered && (dwFixes & widthSize)){
rTo.left=rTo.right-rFixedFrom.Width();
}
}
if(pCurRule->m_ApplyToWhat & topPos){
if(bIfOnlyBigger){
if(rTo.top<lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
if(bIfOnlyLess){
if(rTo.top>lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
rTo.top=lValue;
if(!bIfOnlyRuleTriggered && (dwFixes & heightSize)){
rTo.bottom=rTo.top+rFixedFrom.Height();
}
}
if(pCurRule->m_ApplyToWhat & bottomPos){
if(bIfOnlyBigger){
if(rTo.bottom<lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
if(bIfOnlyLess){
if(rTo.bottom>lValue){
continue;
}
bIfOnlyRuleTriggered=1;
}
rTo.bottom=lValue;
if(!bIfOnlyRuleTriggered && (dwFixes & heightSize)){
rTo.top=rTo.bottom-rFixedFrom.Height();
}
}
if(pCurRule->m_ApplyToWhat & widthSize){
if(dwFixes & rightPos){
rTo.left=rTo.right-lValue;
}else{
rTo.right=rTo.left+lValue;
}
}
if(pCurRule->m_ApplyToWhat & heightSize){
if(dwFixes & bottomPos){
rTo.top=rTo.bottom-lValue;
}else{
rTo.bottom=rTo.top+lValue;
}
}
if(pCurRule->m_ApplyToWhat & topCenter){
rTo.left=lValue-(rTo.Width()/2);
rTo.right=rTo.left+rFixedFrom.Width();
}
if(pCurRule->m_ApplyToWhat & sideCenter){
rTo.top=lValue-(rTo.Height()/2);
rTo.bottom=rTo.top+rFixedFrom.Height();
}
pToWnd->m_Rect=rTo;
p_IDWnd->MoveWindow(rTo,FALSE);
#ifdef _DEBUG
{
CRect rtNew(rTo),rtNewMain(m_rMain);
m_pMain->ClientToScreen(rtNew);
}
#endif
}
int iRes=0;
if(bIfOnlyRuleTriggered){
ADDDEBUGCHAR("2");
iRes=ApplyLayout(FALSE,FALSE);
}else{
ApplyShowRules(TRUE);
iRes=ApplyStickness(FALSE,!bClearCash);
RedrawWindowFlickerFree(m_pMain);
}
return iRes;
}
int CSmartWndSizer::RedrawWindowFlickerFree(CWnd* pWnd)
{
if(m_dwOptions & SETCLIPSIBL){
int iID=0;
pWnd->RedrawWindow();
CSmartWndSizer_Element* pControlWnd;
POSITION p=m_WndElements.GetStartPosition();
while(p){
m_WndElements.GetNextAssoc(p,iID,pControlWnd);
if(pControlWnd){
CWnd* pControl=m_pMain->GetDlgItem(pControlWnd->m_ID);
if(pControl && ::IsWindowVisible(pControl->GetSafeHwnd())){
pControl->RedrawWindow(NULL,NULL,RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE | RDW_FRAME);//| RDW_ALLCHILDREN | RDW_ERASENOW
}
}
}
return TRUE;
}
if(bSlowMachine || (m_dwOptions & NODOUBLEBUFFER)!=0){// || (GetWindowLong(pWnd->GetSafeHwnd(), GWL_EXSTYLE) & (0x00080000L)!=0)){
pWnd->RedrawWindow();
return TRUE;
}
if(!pWnd || !IsWindow(pWnd->GetSafeHwnd())){
return FALSE;
}
if(pWnd->IsWindowVisible()){
CDC* pDC=pWnd->GetWindowDC();
if(!pDC){
return FALSE;
}
CRect rt,rtWin;
pWnd->GetClientRect(&rt);
pWnd->GetWindowRect(&rtWin);
CDC dcMem;
CBitmap bmp;
bmp.CreateCompatibleBitmap(pDC,rtWin.Width(),rtWin.Height());
dcMem.CreateCompatibleDC(pDC);
CBitmap* bmpOld=dcMem.SelectObject(&bmp);
pWnd->SendMessage(WM_PRINT,WPARAM(dcMem.GetSafeHdc()),LPARAM(PRF_CHECKVISIBLE|PRF_OWNED|PRF_CHILDREN|PRF_CLIENT|PRF_ERASEBKGND|PRF_NONCLIENT));
pDC->BitBlt(rt.left,rt.top,rtWin.Width(),rtWin.Height(),&dcMem,0,0,SRCCOPY);
dcMem.SelectObject(bmpOld);
pWnd->ReleaseDC(pDC);
pWnd->ValidateRect(&rt);
}
return TRUE;
}
int CSmartWndSizer::IsWindowIntersected(int iIDWith, BOOL bFullCheck, BOOL bWithMainWindow)
{
CSmartWndSizer_Element* pLookWith=NULL;
if(!m_WndElements.Lookup(iIDWith, pLookWith)){
return 0;
}
CRect rtWith=pLookWith->m_Rect;
rtWith.InflateRect(m_iSaWi,m_iSaWi);
if(bWithMainWindow){
if(rtWith.left<0 || rtWith.top<0){
return 1;
}
CRect rt2;
m_pMain->GetClientRect(&rt2);
int iW=rt2.Width(),iH=rt2.Height();
if(rtWith.right>iW || rtWith.bottom>iH){
return 1;
}
}
CSmartWndSizer_Element* pControlWnd=NULL;
int iID=0;
POSITION p=m_WndElements.GetStartPosition();
while(p){
m_WndElements.GetNextAssoc(p,iID,pControlWnd);
if(pControlWnd && iID!=iIDWith){
if(pControlWnd && pControlWnd->m_Rect.left>0){
CWnd* pWndWith=m_pMain->GetDlgItem(iID);
if(pWndWith){
BOOL bWithOK=1;
if(bFullCheck && (pControlWnd->m_dwFixed & alwaysVisible)==0){
BOOL bIsWnd=::IsWindow(pWndWith->GetSafeHwnd());
BOOL bVisible=::IsWindowVisible(pWndWith->GetSafeHwnd());
bWithOK=(bIsWnd && bVisible);
}
if(bWithOK){
CRect inter(0,0,0,0);
inter.IntersectRect(rtWith,pControlWnd->m_Rect);
if(!inter.IsRectEmpty()){
return 1;
}
}
}
}
}
}
return 0;
}
int CSmartWndSizer::TestOnScreenOut(CRect& CurDialogRect, int Stickness, BOOL bForceInScreen, BOOL bBestMonitorForMM)
{
BOOL bOnMulty=FALSE;
CRect CurDialogRectCp(CurDialogRect);
DesktopDialogRect=GetScreenRect(&CurDialogRectCp,&bOnMulty,bBestMonitorForMM);
int iRightEdge=DesktopDialogRect.right-CurDialogRect.Width();
int iBottomEdge=DesktopDialogRect.bottom-CurDialogRect.Height();
if(bForceInScreen || (!bOnMulty && IsScreenBordersAreFAT()==1)){
if(CurDialogRect.left>iRightEdge-Stickness){
CurDialogRect.left=iRightEdge;
}
if(CurDialogRect.left<DesktopDialogRect.left+Stickness){
CurDialogRect.left=DesktopDialogRect.left;
}
if(CurDialogRect.top>iBottomEdge-Stickness){
CurDialogRect.top=iBottomEdge;
}
if(CurDialogRect.top<DesktopDialogRect.top+Stickness){
CurDialogRect.top=DesktopDialogRect.top;
}
}else{
if(abs(CurDialogRect.left-iRightEdge)<Stickness){
CurDialogRect.left=iRightEdge;
}
if(abs(CurDialogRect.left-DesktopDialogRect.left)<Stickness){
CurDialogRect.left=DesktopDialogRect.left;
}
if(abs(CurDialogRect.top-iBottomEdge)<Stickness){
CurDialogRect.top=iBottomEdge;
}
if(abs(CurDialogRect.top-DesktopDialogRect.top)<Stickness){
CurDialogRect.top=DesktopDialogRect.top;
}
}
CurDialogRect.right=CurDialogRect.left+CurDialogRectCp.Width();
CurDialogRect.bottom=CurDialogRect.top+CurDialogRectCp.Height();
return (CurDialogRect.left!=CurDialogRectCp.left || CurDialogRect.top!=CurDialogRectCp.top || CurDialogRect.right!=CurDialogRectCp.right || CurDialogRect.bottom!=CurDialogRectCp.bottom);
}
int CSmartWndSizer::IsRectStickedTogether(CRect rect1, CRect rect2, int iStickness)
{
if (iStickness==0){
iStickness=m_iStickness;
}
// Пересекать будем с расширенным прямоугольником
// чтобы окно притягивалось и снаружи тоже
CRect IntersectWith(rect2);
IntersectWith.InflateRect(iStickness,iStickness,iStickness,iStickness);
CRect Intersect;
if(Intersect.IntersectRect(rect1,IntersectWith)!=0){
return 1;
}
return 0;
}
int CSmartWndSizer::TestStickness(CRect& CurDialogRect, BOOL bTestVisibleOnly)
{
if(iInit==0 || !::IsWindow(m_pMain->m_hWnd) || ((m_dwOptions & STICKABLE)==0)){
return 0;
};
if(bTestVisibleOnly && !::IsWindowVisible(m_pMain->m_hWnd)){
return 0;
};
if(CurDialogRect.IsRectEmpty()){
return 0;
}
BOOL bWindowStickToMinSize=0;
CRect rMinimumRect(m_rMainMin);
if(CurDialogRect.Height()<rMinimumRect.Height()){
CurDialogRect.bottom=CurDialogRect.top+rMinimumRect.Height();
bWindowStickToMinSize=TRUE;
}
if(CurDialogRect.Width()<rMinimumRect.Width()){
CurDialogRect.right=CurDialogRect.left+rMinimumRect.Width();
bWindowStickToMinSize=TRUE;
}
CRect rMaximumRect(m_rMainMax);
if(!rMaximumRect.IsRectEmpty()){
if(CurDialogRect.Height()>rMaximumRect.Height()){
CurDialogRect.bottom=CurDialogRect.top+rMaximumRect.Height();
bWindowStickToMinSize=TRUE;
}
if(CurDialogRect.Width()>rMaximumRect.Width()){
CurDialogRect.right=CurDialogRect.left+rMaximumRect.Width();
bWindowStickToMinSize=TRUE;
}
}
if((m_dwOptions & FIXEDYSIZE) && CurDialogRect.Height()!=m_rMainMin.Height()){
CurDialogRect.bottom=CurDialogRect.top+m_rMainMin.Height();
bWindowStickToMinSize=TRUE;
}
if((m_dwOptions & FIXEDXSIZE) && CurDialogRect.Width()!=m_rMainMin.Width()){
CurDialogRect.right=CurDialogRect.left+m_rMainMin.Width();
bWindowStickToMinSize=TRUE;
}
BOOL bWindowMovedInScreen=bMaximized?0:TestOnScreenOut(CurDialogRect,m_iStickness);
if(m_iStickness<0){
return bWindowMovedInScreen;
}
// Прилипание к другим окнам...
BOOL bTwiced=FALSE;
int iWidth=CurDialogRect.Width();
int iHeight=CurDialogRect.Height();
CRect CurDialogRectCp(CurDialogRect);
{
CSmartLocker lock(rectLock);
for(int i=0;i<m_AllWndSizerRectangles->GetSize();i++){
CWnd* pCompWith=(*m_AllWndSizerRectangles)[i].pWnd;
if(pCompWith==NULL || pCompWith==m_pMain || !IsWindow(pCompWith->m_hWnd) || !(pCompWith->IsWindowVisible())){
continue;
}
CRect rCompWith;
pCompWith->GetWindowRect(rCompWith);
if(rCompWith.IsRectEmpty()){
continue;
}
if(IsRectStickedTogether(CurDialogRect,rCompWith)==0){
continue;
}
bTwiced=FALSE;
// Внутри ....
if(abs(CurDialogRect.left-rCompWith.left)<m_iStickness){
CurDialogRect.left=rCompWith.left;
CurDialogRect.right=CurDialogRect.left+iWidth;
bTwiced=TRUE;
}
if(abs(CurDialogRect.right-rCompWith.right)<m_iStickness){
CurDialogRect.right=rCompWith.right;
if(!bTwiced){
CurDialogRect.left=CurDialogRect.right-iWidth;
}
}
bTwiced=FALSE;
if(abs(CurDialogRect.top-rCompWith.top)<m_iStickness){
CurDialogRect.top=rCompWith.top;
CurDialogRect.bottom=CurDialogRect.top+iHeight;
bTwiced=TRUE;
}
if(abs(CurDialogRect.bottom-rCompWith.bottom)<m_iStickness){
CurDialogRect.bottom=rCompWith.bottom;
if(!bTwiced){
CurDialogRect.top=CurDialogRect.bottom-iHeight;
}
}
// Снаружи...
bTwiced=FALSE;
if(abs(CurDialogRect.left-rCompWith.right)<m_iStickness){
CurDialogRect.left=rCompWith.right;
CurDialogRect.right=CurDialogRect.left+iWidth;
bTwiced=TRUE;
}
if(abs(CurDialogRect.right-rCompWith.left)<m_iStickness){
CurDialogRect.right=rCompWith.left;
if(!bTwiced){
CurDialogRect.left=CurDialogRect.right-iWidth;
}
}
bTwiced=FALSE;
if(abs(CurDialogRect.top-rCompWith.bottom)<m_iStickness){
CurDialogRect.top=rCompWith.bottom;
CurDialogRect.bottom=CurDialogRect.top+iHeight;
bTwiced=TRUE;
}
if(abs(CurDialogRect.bottom-rCompWith.top)<m_iStickness){
CurDialogRect.bottom=rCompWith.top;
if(!bTwiced){
CurDialogRect.top=CurDialogRect.bottom-iHeight;
}
}
}
}
BOOL bWindowMoved=(CurDialogRect.left!=CurDialogRectCp.left || CurDialogRect.top!=CurDialogRectCp.top || CurDialogRect.right!=CurDialogRectCp.right || CurDialogRect.bottom!=CurDialogRectCp.bottom);
return (bWindowMovedInScreen?windowStickToScreen:0)|(bWindowMoved?windowStickToWnd:0)|(bWindowStickToMinSize?windowStickToMinSize:0);
}
int CSmartWndSizer::ApplyStickness(BOOL bRedraw, BOOL bUseCashedRect)
{
if(iInit==0 || !::IsWindow(m_pMain->m_hWnd) || !::IsWindowVisible(m_pMain->m_hWnd) || ((m_dwOptions & STICKABLE)==0)){
return FALSE;
};
// Прилипание к краям экрана...
CRect CurDialogRect;
if(bUseCashedRect){
CurDialogRect=m_rMain;
}else{
m_pMain->GetWindowRect(CurDialogRect);
}
BOOL bMoved=TestStickness(CurDialogRect);
if(bMoved!=0 &&
(CurDialogRect.left!=m_rMain.left || CurDialogRect.top!=m_rMain.top ||
CurDialogRect.right!=m_rMain.right || CurDialogRect.bottom!=m_rMain.bottom)){
m_pMain->MoveWindow(CurDialogRect,TRUE);
// Берем положение основного окна для сохранения...
m_rMain.CopyRect(CurDialogRect);
}
return bMoved;
}
int CSmartWndSizer::SaveSizeAndPosToRegistry()
{
CString sKeyName=m_szRegKey;
if(m_pMain==NULL || sKeyName==""){
return 0;
}
int iPos=sKeyName.ReverseFind('\\');
if(iPos==-1){
return 0;
}
if(m_pMain && IsWindow(m_pMain->GetSafeHwnd())){
bMaximized=IsZoomed(m_pMain->GetSafeHwnd());
}
CString sValueName=sKeyName.Mid(iPos+1);
if(m_pMain && ::IsWindow(m_pMain->GetSafeHwnd())){
if(bMaximized!=0){
WINDOWPLACEMENT wndpl;
m_pMain->GetWindowPlacement(&wndpl);
m_rMain.CopyRect(&wndpl.rcNormalPosition);
}else{
m_pMain->GetWindowRect(&m_rMain);
}
}
CRect rtAll(GetAllMonitorsRECT());
if(m_rMain.left<rtAll.left || m_rMain.top<rtAll.top
|| m_rMain.right>rtAll.right || m_rMain.bottom>rtAll.bottom){
// Не сохраняем плохих данных
return 0;
}
sKeyName=sKeyName.Left(iPos);
char szValue[256];
sprintf(szValue,"x={%i};y={%i};x1={%i};y1={%i}",m_rMain.left,m_rMain.top,m_rMain.right,m_rMain.bottom);
if(bMaximized){
strcat(szValue,"{MAX}");
}
CRegKey key;
key.Create(m_hKeyRoot, sKeyName);
DWORD dwType=REG_SZ,dwSize=0;
if(RegSetValueEx(key.m_hKey,sValueName,0,REG_SZ,(BYTE*)szValue,lstrlen(szValue)+1)!= ERROR_SUCCESS){
return 0;
}
return 1;
}
/*
#define SM_XVIRTUALSCREEN 76
#define SM_YVIRTUALSCREEN 77
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
*/
CRect GetAllMonitorsRECT()
{
CRect rDesktopRECT(GetSystemMetrics(76),GetSystemMetrics(77),GetSystemMetrics(78),GetSystemMetrics(79));
if(rDesktopRECT.IsRectEmpty() || GetSystemMetrics(80)<=1){
::SystemParametersInfo(SPI_GETWORKAREA,0,&rDesktopRECT,0);
}
return rDesktopRECT;
}
int CSmartWndSizer::LoadSizeAndPosFromRegistry()
{
if(m_pMain==NULL){
return 0;
}
CString sKeyName=m_szRegKey;
int iPos=sKeyName.ReverseFind('\\');
if(iPos==-1){
return 0;
}
CString sValueName=sKeyName.Mid(iPos+1);
sKeyName=sKeyName.Left(iPos);
char szValue[256]={0};
CRegKey key;
key.Create(m_hKeyRoot, sKeyName);
DWORD dwCount=sizeof(szValue);
DWORD dwType=0;
if(RegQueryValueEx(key.m_hKey,sValueName,NULL, &dwType,(LPBYTE)szValue, &dwCount)!= ERROR_SUCCESS){
return 0;
}
CRect m_rMainTmp;
char* szPos=strstr(szValue,"{");
if(!szPos) return 0; else szPos++;
m_rMainTmp.left=atol(szPos);
szPos=strstr(szPos,"{");
if(!szPos) return 0; else szPos++;
m_rMainTmp.top=atol(szPos);
szPos=strstr(szPos,"{");
if(!szPos) return 0; else szPos++;
m_rMainTmp.right=atol(szPos);
szPos=strstr(szPos,"{");
if(!szPos) return 0; else szPos++;
m_rMainTmp.bottom=atol(szPos);
m_rMain.CopyRect(m_rMainTmp);
// Должно попадать в основной десктоп
CRect rtAll(GetAllMonitorsRECT());
if(m_rMain.left<rtAll.left){
m_rMain.OffsetRect(rtAll.left-m_rMain.left,0);
}
if(m_rMain.top<rtAll.top){
m_rMain.OffsetRect(0,rtAll.top-m_rMain.top);
}
if(strstr(szValue,"{MAX}")){
bMaximized=1;
}
return 1;
}
class SimpleTracker
{
public:
long* bValue;
SimpleTracker(long& b){
bValue=&b;
InterlockedIncrement(bValue);
};
~SimpleTracker(){
InterlockedDecrement(bValue);
};
};
#define CSimpleLock SimpleTracker
BOOL CSmartWndSizer::ApllyAndRefresh(BOOL bNotUsingSys)
{
static BOOL bNoRepaint=-1;
if(bNoRepaint==-1){
::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS,0,&bNoRepaint,0);
}
if(bNotUsingSys || bNoRepaint){
ApplyLayout();
}
return TRUE;
}
#define RESIZE_SPOT 5
BOOL CSmartWndSizer::HandleWndMesages(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& DispatchResultFromSizer)
{
if(bMessageRecursingPreventer>0){
// Чтобы не входить в штопор от сообщений,
// которые порождаются при обработке др. сообщений
return FALSE;
}
SimpleTracker track(bMessageRecursingPreventer);
//------------------------
DispatchResultFromSizer=0;
if((message==WM_SHOWWINDOW && wParam==TRUE) || message==WM_ACTIVATE || message==WM_NCCREATE || (message==WM_WINDOWPOSCHANGED && iInit==2)){
if(iInit==2){
// сюда должно попадать только один раз
SmartPRESetWindowPosition();
ApplyShowRules(FALSE);
}
}
if((message==WM_DESTROY || message==WM_CLOSE) && iInit==1){// Если не был инициализирован, то и сохранять нечего!
SaveSizeAndPosToRegistry();
}
if(message==WM_SYSCOMMAND && wParam==SC_MAXIMIZE){
bMaximized=1;
}
if(message==WM_SYSCOMMAND && wParam==SC_RESTORE){
bMaximized=0;
}
if((message==WM_WINDOWPOSCHANGING || message==WM_SIZE || message==WM_SIZING) && iInit==1){
if(int(GetProp(m_pMain->GetSafeHwnd(),"ALLOW_OFFSCR"))!=1){
CRect rect(m_rMain);
WINDOWPOS* pos=(WINDOWPOS*)lParam;
if(((message==WM_WINDOWPOSCHANGING || message==WM_WINDOWPOSCHANGED)&& (m_dwOptions & FIXEDPOS)) || ((message==WM_SIZING || message==WM_SIZE)&& (m_dwOptions & FIXEDSIZE))){
if(IsWindow(m_pMain->GetSafeHwnd()) && IsWindowVisible(m_pMain->GetSafeHwnd())){
pos->x=rect.left;
pos->y=rect.top;
pos->cx=rect.Width();
pos->cy=rect.Height();
ADDDEBUGCHAR("a");
ApllyAndRefresh((message==WM_WINDOWPOSCHANGED || message==WM_SIZE));
return TRUE;
}
}
BOOL bFollow=::GetKeyState(VK_CONTROL)<0 && ::GetKeyState(VK_MENU)<0;
if(!bFollow){
bFollowModeEnabled=FALSE;
}
if(message==WM_WINDOWPOSCHANGING){
rect.SetRect(pos->x,pos->y,pos->x+pos->cx,pos->y+pos->cy);
CPoint pOffset(rect.left-m_rMain.left,rect.top-m_rMain.top);
if(bFollow && !rect.IsRectEmpty() && !(pOffset.x==0 && pOffset.y==0) && !((pos->flags & SWP_NOMOVE) || (pos->flags & SWP_NOSIZE) || (pos->flags & SWP_NOSENDCHANGING))){
FollowWndRect(m_rMain,pOffset);
}
}
if(message==WM_SIZING && lParam && !bSkipResize){
CRect rMessageRect=*((RECT*)lParam);
if(rMessageRect.left!=m_rMain.left || rMessageRect.right!=m_rMain.right ||
rMessageRect.top!=m_rMain.top || rMessageRect.bottom!=m_rMain.bottom){
if((TestStickness(rMessageRect)&windowStickToMinSize)==0){
m_rMain.CopyRect(rMessageRect);
ADDDEBUGCHAR("b");
ApllyAndRefresh(message==WM_SIZE);
}
rect.CopyRect(m_rMain);
}
}else if(message==WM_SIZE && lParam && !bSkipResize){
WORD lWClientArea=LOWORD(lParam);
WORD lHClientArea=HIWORD(lParam);
DWORD dwMainClientBordersW=lClientOffsetR+lClientOffsetL;
DWORD dwMainClientBordersH=lClientOffsetB+lClientOffsetT+GetWindowMenuHeightSW(TRUE);
if(lWClientArea!=(m_rMain.Width()-dwMainClientBordersW) || lHClientArea!=(m_rMain.Height()-dwMainClientBordersH)){
m_pMain->GetWindowRect(&m_rMain);
rect.CopyRect(m_rMain);
ADDDEBUGCHAR("d");
ApllyAndRefresh(message==WM_SIZE);
}
}else if(message==WM_WINDOWPOSCHANGING && pos->cy!=0 && pos->cx!=0){
if(!bFollowModeEnabled){// Если идет drag с follow, ничего не проверяем
if(::GetKeyState(VK_SHIFT)>=0){// Если прилипание отключено, не проверяем
CRect rectNew(rect);//pos->x,pos->y,pos->x+pos->cx,pos->y+pos->cy);
if(TestStickness(rectNew)!=0){
if(pos->x!=rectNew.left || pos->y!=rectNew.top || pos->cx!=rectNew.Width() || pos->cy!=rectNew.Height()){
pos->x=rectNew.left;
pos->y=rectNew.top;
pos->cx=rectNew.Width();
pos->cy=rectNew.Height();
ADDDEBUGCHAR("?");
}
}
}
}
if(!rect.IsRectEmpty() && rect!=m_rMain){
m_rMain.CopyRect(rect);
}
}
return TRUE;
}
}
static CPoint pRevPT(-1,-1);
if(message==WM_LBUTTONUP){
bFollowModeEnabled=FALSE;
if(bInResizingLock){
if(hResizeCur){
SetCursor(hResizeCur);
}
pRevPT.x=-1;
pRevPT.y=-1;
bInResizingLock=0;
ReleaseCapture();
return TRUE;
}
}
if(message==WM_LBUTTONDOWN){
if(pResizeAffectedWnd!=NULL){
pRevPT.x=LOWORD(lParam);
pRevPT.y=HIWORD(lParam);
m_pMain->SetCapture();
if(iAffectType<2){
SetCursor(::LoadCursor(NULL,MAKEINTRESOURCE(IDC_SIZEWE)));
}else{
SetCursor(::LoadCursor(NULL,MAKEINTRESOURCE(IDC_SIZENS)));
}
bInResizingLock=TRUE;
return TRUE;
}
}
if(message==WM_MOUSEMOVE && bResizingElementsArePresent!=0){
CPoint pt(LOWORD(lParam),HIWORD(lParam));
if(bInResizingLock && pResizeAffectedWnd){
if(pRevPT.x>=0 && pRevPT.y>=0 && pt.x>=0 && pt.x<=m_rMain.Width() && pt.y>=0 && pt.y<=m_rMain.Height()){
//&& (abs(pt.x-pResizeAffectedWnd->m_Rect.left)<RESIZE_SPOT || abs(pt.x-pResizeAffectedWnd->m_Rect.right)<RESIZE_SPOT || abs(pt.y-pResizeAffectedWnd->m_Rect.top)<RESIZE_SPOT || abs(pt.y-pResizeAffectedWnd->m_Rect.bottom)<RESIZE_SPOT)
BOOL bChanged=FALSE;
if(iAffectType==0){
long lNew=pResizeAffectedWnd->m_Rect.left+pt.x-pRevPT.x;
pResizeAffectedWnd->m_Rect.left=lNew;
bChanged=TRUE;
}else if(iAffectType==1){
long lNew=pResizeAffectedWnd->m_Rect.right+pt.x-pRevPT.x;
pResizeAffectedWnd->m_Rect.right=lNew;
bChanged=TRUE;
}else if(iAffectType==2){
long lNew=pResizeAffectedWnd->m_Rect.top+pt.y-pRevPT.y;
pResizeAffectedWnd->m_Rect.top=lNew;
bChanged=TRUE;
}else if(iAffectType==3){
long lNew=pResizeAffectedWnd->m_Rect.bottom+pt.y-pRevPT.y;
pResizeAffectedWnd->m_Rect.bottom=lNew;
bChanged=TRUE;
}
if(bChanged){
pRevPT=pt;
m_pMain->GetDlgItem(pResizeAffectedWnd->m_ID)->MoveWindow(pResizeAffectedWnd->m_Rect);
m_pMain->GetWindowRect(&m_rMain);
ADDDEBUGCHAR("e");
ApllyAndRefresh(1);
}
return TRUE;
}
}else{
pResizeAffectedWnd=NULL;
BOOL bNeedSetCursor=FALSE;
int iID=0;
iAffectType=-1;
CSmartWndSizer_Element* pControlWnd=NULL;
// Бегаем и ищем контрол, который можно сресайзить
POSITION p=m_WndElements.GetStartPosition();
while(p){
m_WndElements.GetNextAssoc(p,iID,pControlWnd);
if(pControlWnd->m_dwFixed & leftResize){
bResizingElementsArePresent=1;
if(pt.y>pControlWnd->m_Rect.top && pt.y<pControlWnd->m_Rect.bottom){
if(abs(pt.x-pControlWnd->m_Rect.left)<RESIZE_SPOT){
pResizeAffectedWnd=pControlWnd;
iAffectType=0;
break;
}
}
}
if(pControlWnd->m_dwFixed & rightResize){
bResizingElementsArePresent=1;
if(pt.y>pControlWnd->m_Rect.top && pt.y<pControlWnd->m_Rect.bottom){
if(abs(pt.x-pControlWnd->m_Rect.right)<RESIZE_SPOT){
pResizeAffectedWnd=pControlWnd;
iAffectType=1;
break;
}
}
}
if(pControlWnd->m_dwFixed & topResize){
bResizingElementsArePresent=1;
if(pt.x>pControlWnd->m_Rect.left && pt.x<pControlWnd->m_Rect.right){
if(abs(pt.y-pControlWnd->m_Rect.top)<RESIZE_SPOT){
pResizeAffectedWnd=pControlWnd;
iAffectType=2;
break;
}
}
}
if(pControlWnd->m_dwFixed & bottomResize){
bResizingElementsArePresent=1;
if(pt.x>pControlWnd->m_Rect.left && pt.x<pControlWnd->m_Rect.right){
if(abs(pt.y-pControlWnd->m_Rect.bottom)<RESIZE_SPOT){
pResizeAffectedWnd=pControlWnd;
iAffectType=3;
break;
}
}
}
}
if(bResizingElementsArePresent<0){
bResizingElementsArePresent=0;
}
if(pResizeAffectedWnd){
if(iAffectType<2){
hResizeCur=SetCursor(::LoadCursor(NULL,MAKEINTRESOURCE(IDC_SIZEWE)));
}else{
hResizeCur=SetCursor(::LoadCursor(NULL,MAKEINTRESOURCE(IDC_SIZENS)));
}
}else if(hResizeCur){
SetCursor(hResizeCur);
}
}
}
return FALSE;
};
BOOL CSmartWndSizer::bFollowModeEnabled=FALSE;
void CSmartWndSizer::FollowWndRect(CRect rMaster, CPoint pOffset)
{
int i=0;
CSmartLocker lock(rectLock);
for(i=0;i<m_AllWndSizerRectangles->GetSize();i++){
(*m_AllWndSizerRectangles)[i].bStickedForFollow=FALSE;
}
bFollowModeEnabled=TRUE;
for(i=0;i<m_AllWndSizerRectangles->GetSize();i++){
CWnd* pCompWith=(*m_AllWndSizerRectangles)[i].pWnd;
if(pCompWith==NULL || !IsWindow(pCompWith->m_hWnd) || !(pCompWith->IsWindowVisible())){
continue;
}
CRect rCompWith;
pCompWith->GetWindowRect(rCompWith);
if(rMaster.EqualRect(rCompWith)){
continue;
}
if(!(*m_AllWndSizerRectangles)[i].bStickedForFollow && IsRectStickedTogether(rMaster, rCompWith, 1)){
rCompWith.OffsetRect(pOffset);
pCompWith->MoveWindow(rCompWith,TRUE);
(*m_AllWndSizerRectangles)[i].bStickedForFollow=TRUE;
}
}
return;
}
BOOL CSmartWndSizer::TestRectInWindows(CRect rt, BOOL bExcludeSelf, BOOL bExcludeInvises, const char* szTestOnProp)
{
if(TestPointInWindows(rt.TopLeft())==2 || TestPointInWindows(rt.BottomRight())==2){
return 2;
}
CSmartLocker lock(rectLock);
for(int i=0;i<m_AllWndSizerRectangles->GetSize();i++){
CWnd* pCompWith=(*m_AllWndSizerRectangles)[i].pWnd;
if(pCompWith==NULL || !IsWindow(pCompWith->m_hWnd)){
continue;
}
if(bExcludeInvises && !(pCompWith->IsWindowVisible())){
continue;
}
if(bExcludeInvises==0 && szTestOnProp){
HANDLE h=GetProp(pCompWith->m_hWnd,szTestOnProp);
if(h==0){
continue;
}
}
CRect rCompWith;
pCompWith->GetWindowRect(rCompWith);
if(bExcludeSelf && rCompWith.EqualRect(&rt)){
continue;
}
CRect Intersect(rt);
Intersect.IntersectRect(rCompWith,rt);
if(!Intersect.IsRectEmpty()){
return 1;
}
}
return 0;
}
BOOL CSmartWndSizer::TestPointInWindows(CPoint pt)
{
//::SystemParametersInfo(SPI_GETWORKAREA,0,&DesktopDialogRect,0);
DesktopDialogRect=GetAllMonitorsRECT();
if(!DesktopDialogRect.PtInRect(pt)){
return 2;
}
CSmartLocker lock(rectLock);
for(int i=0;i<m_AllWndSizerRectangles->GetSize();i++){
CWnd* pCompWith=(*m_AllWndSizerRectangles)[i].pWnd;
if(pCompWith==NULL || !IsWindow(pCompWith->m_hWnd) || !(pCompWith->IsWindowVisible())){
continue;
}
CRect rCompWith;
pCompWith->GetWindowRect(rCompWith);
if(rCompWith.PtInRect(pt)){
return 1;
}
}
return 0;
}
#include <multimon.h>
#ifdef COMPILE_MULTIMON_STUBS
#undef COMPILE_MULTIMON_STUBS
#endif
CRect& CSmartWndSizer::GetScreenRect(CRect* rtBase, BOOL* bMultiMonsOut, BOOL bForBestMonitor)
{
static CRect rtRes(0,0,0,0);
static BOOL bMultyMons=FALSE;
if(rtBase==0 && bMultiMonsOut==0){
return rtRes;
}
if(rtRes.Width()==0 && rtRes.Height()==0){
bMultyMons=FALSE;
if(rtBase!=NULL && GetSystemMetrics(80)>1){//SM_CMONITORS
bMultyMons=TRUE;
DesktopDialogRect=GetAllMonitorsRECT();
rtRes=DesktopDialogRect;
}
if(rtRes.Width()==0 && rtRes.Height()==0){
CRect DesktopDialogRect;
::SystemParametersInfo(SPI_GETWORKAREA,0,&DesktopDialogRect,0);
//DesktopDialogRect=GetAllMonitorsRECT();
rtRes=DesktopDialogRect;
}
}
if(bForBestMonitor && bMultyMons){
MONITORINFO mi;
memset(&mi,0,sizeof(mi));
mi.cbSize = sizeof(mi);
HMONITOR hMonitor=NULL;
hMonitor = MonitorFromRect(rtBase, MONITOR_DEFAULTTONEAREST);
if(hMonitor != NULL){
GetMonitorInfo(hMonitor, &mi);
rtRes=mi.rcWork;
}
}
if(bMultiMonsOut){
*bMultiMonsOut=bMultyMons;
}
return rtRes;
}
BOOL& IsScreenBordersAreFAT()
{
static BOOL b=1;
return b;
} | [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
] | [
[
[
1,
1394
]
]
] |
d7a5a645000612865c96aae3b1b5aab3d4454ea3 | f3efbdc560277c0d0b5da2fc07c6b9574f5aadd4 | / lxyppc-oled/oled/USB/Src/UsbHid.cpp | 11ac5893dc1a0133ff7b57ed6618f9ebed31486a | [] | no_license | lxyppc/lxyppc-oled | 9a686820ff6bbfa3af11d2c058c9c9144da6ecf1 | 706201693896abae91cdcce616ad7366b9fc9efa | refs/heads/master | 2016-09-05T23:21:47.259439 | 2010-04-26T09:27:31 | 2010-04-26T09:27:31 | 32,801,575 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,074 | cpp | #include "StdAfx.h"
#include "..\INC\UsbHid.h"
#include "..\INC\hidsdi++.h"
#include "..\INC\hid.h"
#include "..\INC\setupapi.h"
#include "..\INC\usb100.h"
#include <dbt.h>
#ifndef LIB_USB_DEFINE
#pragma comment(lib, "..\\USB\\LIB\\setupapi.lib")
#pragma comment(lib, "..\\USB\\LIB\\hid.lib")
#endif
xstring toXString(LPCWSTR str)
{
#ifdef UNICODE
return xstring(str);
#else
int len = ::WideCharToMultiByte(CP_ACP,0,str,-1,NULL,0,NULL,NULL);
char *pStr = new char[len+1];
::WideCharToMultiByte(CP_ACP,0,str,-1,pStr,len+1,NULL,NULL);
xstring res(pStr);
delete [] pStr;
return res;
#endif
}
xstring toXString(LPCSTR str)
{
#ifdef UNICODE
int len = ::MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
wchar_t *pStr = new wchar_t[len+1];
::MultiByteToWideChar(CP_ACP,0,str,-1,pStr,len+1);
/// InitialDevice(pStr);
xstring res(pStr);
delete [] pStr;
return res;
#else
return xstring(str);
#endif
}
LONG CUsbHid::Open(LPCTSTR lpDevice)
{
m_devicePath[0] = 0;
m_hFile = ::CreateFile(
lpDevice,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, //&SecurityAttributes, //no SECURITY_ATTRIBUTES structure
OPEN_EXISTING, //No special create flags
FILE_FLAG_OVERLAPPED, // No special attributes
NULL);
if (m_hFile == INVALID_HANDLE_VALUE){
m_hFile = NULL;
return (LONG)::GetLastError();
}
m_hevtOverlappedWorkerThread = ::CreateEvent(0,true,false,0);
if (m_hevtOverlappedWorkerThread == 0)
{
// Obtain the error information
m_lLastError = ::GetLastError();
Close();
// Return the error
return m_lLastError;
}
m_lLastError = StartListener();
if (m_lLastError != ERROR_SUCCESS)
return m_lLastError;
_tcscpy(m_devicePath,lpDevice);
return m_lLastError;
}
LONG CUsbHid::Open(WORD vid, WORD pid, HWND hParent, LPCTSTR filter /*= NULL*/)
{
m_vid = vid;
m_pid = pid;
m_filter = filter;
m_hParent = hParent;
RegisterDevice();
vector<CHidDevice> devs;
EnumHidDevice(vid,pid,devs,filter);
if(devs.size()){
_tcscpy(m_devicePath,devs[devs.size()-1].m_path.c_str());
LONG err = Open(devs[devs.size()-1].m_path.c_str());
if(err == ERROR_SUCCESS){
if(hParent){
m_bConnect = TRUE;
}
}
return err;
}
return -1;
}
LONG CUsbHid::Monitor(WORD vid, WORD pid, HWND hParent, LPCTSTR filter /*= NULL*/)
{
m_vid = vid;
m_pid = pid;
m_filter = filter;
m_hParent = hParent;
return RegisterDevice();
}
LONG CUsbHid::Open(WORD vid, WORD pid, HWND hParent, USAGE usagePage, USAGE usage, LPCTSTR filter)
{
m_usagePage = usagePage;
m_usage = usage;
m_vid = vid;
m_pid = pid;
m_filter = filter;
m_hParent = hParent;
RegisterDevice();
vector<CHidDevice> devs;
EnumHidDevice(vid,pid,devs,usagePage,usage);
if(devs.size()){
_tcscpy(m_devicePath,devs[devs.size()-1].m_path.c_str());
LONG err = Open(devs[devs.size()-1].m_path.c_str());
if(err == ERROR_SUCCESS){
if(hParent){
m_bConnect = TRUE;
}
}
return err;
}
return -1;
}
LONG CUsbHid::Monitor(WORD vid, WORD pid, HWND hParent, USAGE usagePage, USAGE usage, LPCTSTR filter)
{
m_usagePage = usagePage;
m_usage = usage;
return Monitor(vid, pid, hParent, filter);
}
LONG CUsbHid::Close()
{
StopListener(1000);
if(m_hFile){
::CloseHandle(m_hFile);
m_hFile = NULL;
}
return ERROR_SUCCESS;
}
/// Must write 8 byte every time
LONG CUsbHid::Write(const void* pData, size_t len, DWORD* realWrite)
{
/// version is higher or equal than 2.00
HANDLE hEvent = ::CreateEvent(0,true,false,0);
OVERLAPPED ov;
memset(&ov,0,sizeof(OVERLAPPED));
ov.hEvent = hEvent;
DWORD wr;
BYTE buf[64] = "";
memcpy(buf,pData,len);
if(buf[0] == 0x55){
buf[0] = 0x11;
}
BOOL res = ::WriteFile(m_hFile,buf,64,&wr,&ov);
if (::WaitForSingleObject(hEvent,2000) != WAIT_OBJECT_0){
// Set the internal error code
m_lLastError = ::GetLastError();
return m_lLastError;
}
return ERROR_SUCCESS;
}
LONG CUsbHid::Read(void* pData, size_t len, DWORD* realRead)
{
DWORD ttp;
if(realRead == NULL){
realRead = &ttp;
}
const BYTE* data = (const BYTE*)pData;
DWORD wr=0;
HANDLE hEvent = ::CreateEvent(0,true,false,0);
OVERLAPPED ov;
memset(&ov,0,sizeof(OVERLAPPED));
ov.hEvent = hEvent;
BOOL res = ::ReadFile(m_hFile,pData,2,realRead,&ov);
if (::WaitForSingleObject(hEvent,INFINITE) != WAIT_OBJECT_0)
{
// Set the internal error code
m_lLastError = ::GetLastError();
return m_lLastError;
}
return ERROR_SUCCESS;
}
LONG CUsbHid::StartListener()
{
// Check if the watcher thread was already running
if (m_hListenerThread == 0)
{
// Make sure the thread has stopped
_ASSERTE(!m_fStopping);
// Start the watcher thread
DWORD dwThreadId = 0;
m_hListenerThread = ::CreateThread(0,0,ThreadProc,LPVOID(this),0,&dwThreadId);
if (m_hListenerThread == 0)
{
// Set the error code and exit
m_lLastError = ::GetLastError();
return m_lLastError;
}
}
// Return the error
m_lLastError = ERROR_SUCCESS;
return m_lLastError;
}
LONG CUsbHid::StopListener(DWORD dwTimeout)
{
// Check if the thread is running
if (m_hListenerThread)
{
DWORD code;
::GetExitCodeThread(m_hListenerThread,&code);
if(code == STILL_ACTIVE){
// Set the flag that the thread must be stopped
m_fStopping = true;
::SetEvent(m_hevtOverlappedWorkerThread);
::CancelIo(m_hFile);
DWORD err = ::GetLastError();
if(::WaitForSingleObject(m_hListenerThread,dwTimeout) != WAIT_OBJECT_0){
::TerminateThread(m_hListenerThread,0);
}
// The thread has stopped
m_fStopping = false;
}
// Close handle to the thread
::CloseHandle(m_hListenerThread);
m_hListenerThread = NULL;
}
// Return the error
m_lLastError = ERROR_SUCCESS;
return m_lLastError;
}
DWORD WINAPI CUsbHid::ThreadProc (LPVOID lpArg)
{
return ((CUsbHid*)lpArg)->ThreadProc();
}
DWORD CUsbHid::ThreadProc (void)
{
OVERLAPPED ov;
memset(&ov,0,sizeof(OVERLAPPED));
//LPOVERLAPPED lpOverlapped = 0;
// Keep looping
do
{
DWORD read;
memset(&ov,0,sizeof(OVERLAPPED));
ov.hEvent = m_hevtOverlappedWorkerThread;
BYTE data[256]={0};
::ReadFile(m_hFile,data,64,&read,&ov);
if ((::WaitForSingleObject(m_hevtOverlappedWorkerThread,INFINITE) != WAIT_OBJECT_0))
{
// Set the internal error code
m_lLastError = ::GetLastError();
return m_lLastError;
}
if(m_fStopping){
break;
}
if(ov.InternalHigh > 0){
OnHidData(data,ov.InternalHigh);
}else{
break;
}
//if(data[0] == 0x07){
// printf("0x%X\n",data[1]);
//}
}
while (!m_fStopping);
if(!m_fStopping){
//OnDisconnect(m_devicePath);
}
// Bye bye
return 0;
}
LRESULT CUsbHid::OnDeviceChange(WPARAM wParam, LPARAM lParam)
{
TCHAR vid_str[64];
TCHAR pid_str[64];
_stprintf(vid_str,_T("VID_%04X"),m_vid);
_stprintf(pid_str,_T("PID_%04X"),m_pid);
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
PDEV_BROADCAST_DEVICEINTERFACE pDevInf;
if(DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam){
if( pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE){
pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
LPTSTR p = pDevInf->dbcc_name;
while(*p){
if(::islower(*p)){*p -= (_T('a')-_T('A'));}
p++;
}
if( ( (m_vid == 0) || (_tcsstr(pDevInf->dbcc_name, vid_str) != NULL) )
&& ( (m_pid == 0) || (_tcsstr(pDevInf->dbcc_name, pid_str) != NULL) )
&& ( (m_filter == NULL) || (_tcsstr(pDevInf->dbcc_name, m_filter) != NULL) )
)
{
if(DBT_DEVICEARRIVAL == wParam){
if(CheckUsage(xstring(pDevInf->dbcc_name),m_usagePage,m_usage)){
OnConnect(pDevInf->dbcc_name);
}
}else{
OnDisconnect(pDevInf->dbcc_name);
}
}
}
}
return 0;
}
LRESULT CUsbHid::RegisterDevice()
{
if(m_hParent){
HDEVNOTIFY hDevNotify;
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
GUID Guid;
HidD_GetHidGuid(&Guid);
NotificationFilter.dbcc_classguid = Guid;
hDevNotify = RegisterDeviceNotification(m_hParent, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if( !hDevNotify ) {
::MessageBox(NULL,_T("Can't register device notification: "),_T("Error!"),MB_OK);
}
}
return ERROR_SUCCESS;
}
BOOL CUsbHid::GetAttributes(PHIDD_ATTRIBUTES Attributes)
{
if(m_hFile){
return HidD_GetAttributes(m_hFile,Attributes);
}
return FALSE;
}
BOOL CUsbHid::GetSerialString(void * p, ULONG len)
{
if(m_hFile){
return HidD_GetSerialNumberString(m_hFile,p,len);
}
return FALSE;
}
LONG CUsbHid::IoControl(void* pData, size_t len, DWORD *realRead)
{
DWORD read;
if(realRead == NULL){
realRead = &read;
}
DWORD code = CTL_CODE(FILE_DEVICE_UNKNOWN,0x801,METHOD_BUFFERED,FILE_ANY_ACCESS);
BOOL res = DeviceIoControl(
this->m_hFile,
code,
pData,
(DWORD)len,
NULL,
0,
realRead,
NULL
);
if(res){
m_lLastError = ERROR_SUCCESS;
}else{
m_lLastError = GetLastError();
}
return m_lLastError;
}
LONG CUsbHid::SetFeature(void* pData, size_t len, DWORD *realRead)
{
BOOL res = HidD_SetFeature(m_hFile,pData,(ULONG)len);
return GetLastError();
}
LONG CUsbHid::GetFeature(void* pData, size_t len, DWORD *realRead)
{
BOOL res = HidD_GetFeature(m_hFile,pData,(ULONG)len);
return GetLastError();
}
size_t EnumHidDevice(WORD vid, WORD pid, vector<CHidDevice>& devs,LPCTSTR lpFilter /*= NULL*/)
{
devs.clear();
TCHAR Product[253];
string Prod, String;
GUID Guid;
CHidDevice temp;
temp.m_desc = _T("");
TCHAR vid_str[64];
TCHAR pid_str[64];
_stprintf(vid_str,_T("vid_%04x"),vid);
_stprintf(pid_str,_T("pid_%04x"),pid);
HidD_GetHidGuid(&Guid);
HDEVINFO info;
info=SetupDiGetClassDevs(&Guid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (info!=INVALID_HANDLE_VALUE)
{
DWORD devIndex = 0;
SP_INTERFACE_DEVICE_DATA ifData;
ifData.cbSize=sizeof(ifData);
//SetupDiEnumDeviceInterfaces(info, NULL, &Guid, devIndex, &ifData);
//devIndex = ::GetLastError();
for (devIndex=0;SetupDiEnumDeviceInterfaces(info, NULL, &Guid, devIndex, &ifData);++devIndex)
{
DWORD needed;
SetupDiGetDeviceInterfaceDetail(info, &ifData, NULL, 0, &needed, NULL);
PSP_INTERFACE_DEVICE_DETAIL_DATA detail=(PSP_INTERFACE_DEVICE_DETAIL_DATA)new BYTE[needed];
detail->cbSize=sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
SP_DEVINFO_DATA did={sizeof(SP_DEVINFO_DATA)};
if (SetupDiGetDeviceInterfaceDetail(info, &ifData, detail, needed, NULL, &did))
{
// Add the link to the list of all DFU devices
if( ( (vid == 0) || (_tcsstr(detail->DevicePath, vid_str) != NULL) )
&& ( (pid == 0) || (_tcsstr(detail->DevicePath, pid_str) != NULL) )
&& ( (lpFilter == NULL) || (_tcsstr(detail->DevicePath, lpFilter) != NULL) )
)
{
temp.m_path = detail->DevicePath;
if (SetupDiGetDeviceRegistryProperty(info, &did, SPDRP_DEVICEDESC, NULL, (PBYTE)Product, 253, NULL))
temp.m_desc = Product;
else
temp.m_desc = _T("(Unnamed HID device)");
}
}
//if(strstr(detail->DevicePath, vid_str) != NULL
// && ( (pid == 0) || (strstr(detail->DevicePath, pid_str) != NULL) )
// )
//{
//}
delete[] (PBYTE)detail;
if(temp.m_desc != _T("")){
devs.push_back(temp);
}
}
SetupDiDestroyDeviceInfoList(info);
}
return devs.size();
}
BOOL CheckUsage(xstring &path, USAGE usagePage, USAGE usage)
{
if(usagePage == 0 && usage == 0 ){
return TRUE;
}
HANDLE file = CreateFile ( path.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, // no SECURITY_ATTRIBUTES structure
OPEN_EXISTING, // No special create flags
0, // No special attributes
NULL); // No template file
if(file == INVALID_HANDLE_VALUE ){
return FALSE;
}
BOOL res = TRUE;
PHIDP_PREPARSED_DATA Ppd; // The opaque parser info describing this device
HIDP_CAPS Caps; // The Capabilities of this hid device.
if (!HidD_GetPreparsedData (file, &Ppd))
{
res = FALSE;
}
if (!HidP_GetCaps (Ppd, &Caps))
{
HidD_FreePreparsedData (Ppd);
res = FALSE;
}else{
if(usagePage){
if(Caps.UsagePage != usagePage){
res = FALSE;
}
}
if(usage){
if(Caps.Usage != usage){
res = FALSE;
}
}
}
HidD_FreePreparsedData (Ppd);
::CloseHandle(file);
return res;
}
size_t EnumHidDevice(WORD vid, WORD pid, vector<CHidDevice>& devs, USAGE usagePage, USAGE usage)
{
devs.clear();
TCHAR Product[253];
string Prod, String;
GUID Guid;
CHidDevice temp;
temp.m_desc = _T("");
TCHAR vid_str[64];
TCHAR pid_str[64];
_stprintf(vid_str,_T("vid_%04x"),vid);
_stprintf(pid_str,_T("pid_%04x"),pid);
HidD_GetHidGuid(&Guid);
HDEVINFO info;
info=SetupDiGetClassDevs(&Guid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (info!=INVALID_HANDLE_VALUE)
{
DWORD devIndex = 0;
SP_INTERFACE_DEVICE_DATA ifData;
ifData.cbSize=sizeof(ifData);
//SetupDiEnumDeviceInterfaces(info, NULL, &Guid, devIndex, &ifData);
//devIndex = ::GetLastError();
for (devIndex=0;SetupDiEnumDeviceInterfaces(info, NULL, &Guid, devIndex, &ifData);++devIndex)
{
DWORD needed;
SetupDiGetDeviceInterfaceDetail(info, &ifData, NULL, 0, &needed, NULL);
PSP_INTERFACE_DEVICE_DETAIL_DATA detail=(PSP_INTERFACE_DEVICE_DETAIL_DATA)new BYTE[needed];
detail->cbSize=sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
SP_DEVINFO_DATA did={sizeof(SP_DEVINFO_DATA)};
temp.m_desc = _T("");
if (SetupDiGetDeviceInterfaceDetail(info, &ifData, detail, needed, NULL, &did))
{
// Add the link to the list of all DFU devices
if( ( (vid == 0) || (_tcsstr(detail->DevicePath, vid_str) != NULL) )
&& ( (pid == 0) || (_tcsstr(detail->DevicePath, pid_str) != NULL) )
)
{
temp.m_path = detail->DevicePath;
if(CheckUsage(temp.m_path,usagePage,usage)){
if (SetupDiGetDeviceRegistryProperty(info, &did, SPDRP_DEVICEDESC, NULL, (PBYTE)Product, 253, NULL))
temp.m_desc = Product;
else
temp.m_desc = _T("(Unnamed HID device)");
}
}
}
//if(strstr(detail->DevicePath, vid_str) != NULL
// && ( (pid == 0) || (strstr(detail->DevicePath, pid_str) != NULL) )
// )
//{
//}
delete[] (PBYTE)detail;
if(temp.m_desc != _T("")){
devs.push_back(temp);
}
}
SetupDiDestroyDeviceInfoList(info);
}
return devs.size();
}
| [
"lxyppc@2b92f6c6-00d0-11df-bce7-934f6fdf4811"
] | [
[
[
1,
577
]
]
] |
57bde1611b99c1c3b3d9d5e82f2925f7a0e68963 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/XMLString.cpp | cebdf776ac3395f2aacaa7c4c66ca5b4649b8df0 | [] | 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 | 55,330 | cpp | /*
* Copyright 1999-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: XMLString.cpp 191834 2005-06-22 13:29:45Z cargilld $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/ArrayIndexOutOfBoundsException.hpp>
#include <xercesc/util/IllegalArgumentException.hpp>
#include <xercesc/util/NumberFormatException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/TranscodingException.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/RefArrayVectorOf.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/internal/XMLReader.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static data
//
// gConverter
// This is initialized when the user calls the platform init method,
// which calls our init method. This is the converter used for default
// conversion to/from the local code page.
// ---------------------------------------------------------------------------
static XMLLCPTranscoder* gTranscoder = 0;
static XMLCh gNullStr[] =
{
chOpenCurly, chLatin_n, chLatin_u, chLatin_l, chLatin_l, chCloseCurly, chNull
};
MemoryManager* XMLString::fgMemoryManager = 0;
// ---------------------------------------------------------------------------
// XMLString: Public static methods
// ---------------------------------------------------------------------------
void XMLString::binToText( const unsigned long toFormat
, char* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
static const char digitList[16] =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
, 'A', 'B', 'C', 'D', 'E', 'F'
};
if (!maxChars)
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_ZeroSizedTargetBuf, manager);
// Handle special case
if (!toFormat)
{
toFill[0] = '0';
toFill[1] = 0;
return;
}
// This is used to fill the temp buffer
unsigned int tmpIndex = 0;
// A copy of the conversion value that we can modify
unsigned int tmpVal = toFormat;
//
// Convert into a temp buffer that we know is large enough. This avoids
// having to check for overflow in the inner loops, and we have to flip
// the resulting XMLString anyway.
//
char tmpBuf[128];
//
// For each radix, do the optimal thing. For bin and hex, we can special
// case them and do shift and mask oriented stuff. For oct and decimal
// there isn't much to do but bull through it with divides.
//
if (radix == 2)
{
while (tmpVal)
{
if (tmpVal & 0x1UL)
tmpBuf[tmpIndex++] = '1';
else
tmpBuf[tmpIndex++] = '0';
tmpVal >>= 1;
}
}
else if (radix == 16)
{
while (tmpVal)
{
const unsigned int charInd = (tmpVal & 0xFUL);
tmpBuf[tmpIndex++] = digitList[charInd];
tmpVal >>= 4;
}
}
else if ((radix == 8) || (radix == 10))
{
while (tmpVal)
{
const unsigned int charInd = (tmpVal % radix);
tmpBuf[tmpIndex++] = digitList[charInd];
tmpVal /= radix;
}
}
else
{
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Str_UnknownRadix, manager);
}
// See if have enough room in the caller's buffer
if (tmpIndex > maxChars)
{
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_TargetBufTooSmall, manager);
}
// Reverse the tmp buffer into the caller's buffer
unsigned int outIndex = 0;
for (; tmpIndex > 0; tmpIndex--)
toFill[outIndex++] = tmpBuf[tmpIndex-1];
// And cap off the caller's buffer
toFill[outIndex] = char(0);
}
void XMLString::binToText( const unsigned int toFormat
, char* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
// Just call the unsigned long version
binToText((unsigned long)toFormat, toFill, maxChars, radix, manager);
}
void XMLString::binToText( const long toFormat
, char* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
//
// If its negative, then put a negative sign into the output and flip
// the sign of the local temp value.
//
unsigned int startInd = 0;
unsigned long actualVal;
if (toFormat < 0)
{
toFill[0] = '-';
startInd++;
actualVal = (unsigned long)(toFormat * -1);
}
else
{
actualVal = (unsigned long)(toFormat);
}
// And now call the unsigned long version
binToText(actualVal, &toFill[startInd], maxChars, radix, manager);
}
void XMLString::binToText( const int toFormat
, char* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
//
// If its negative, then put a negative sign into the output and flip
// the sign of the local temp value.
//
unsigned int startInd = 0;
unsigned long actualVal;
if (toFormat < 0)
{
toFill[0] = '-';
startInd++;
actualVal = (unsigned long)(toFormat * -1);
}
else
{
actualVal = (unsigned long)(toFormat);
}
// And now call the unsigned long version
binToText(actualVal, &toFill[startInd], maxChars, radix, manager);
}
void XMLString::catString(char* const target, const char* const src)
{
strcat(target, src);
}
int XMLString::compareIString(const char* const str1, const char* const str2)
{
return stricmp(str1, str2);
}
int XMLString::compareNString( const char* const str1
, const char* const str2
, const unsigned int count)
{
// Watch for pathological secenario
if (!count)
return 0;
return strncmp(str1, str2, count);
}
int XMLString::compareNIString( const char* const str1
, const char* const str2
, const unsigned int count)
{
if (!count)
return 0;
return strnicmp(str1, str2, count);
}
int XMLString::compareString( const char* const str1
, const char* const str2)
{
return strcmp(str1, str2);
}
void XMLString::copyString( char* const target
, const char* const src)
{
strcpy(target, src);
}
void XMLString::cut( XMLCh* const toCutFrom
, const unsigned int count)
{
#if defined(XML_DEBUG)
if (count > stringLen(toCutFrom))
{
// <TBD> This is bad of course
}
#endif
// If count is zero, then nothing to do
if (!count)
return;
XMLCh* targetPtr = toCutFrom;
XMLCh* srcPtr = toCutFrom + count;
while (*srcPtr)
*targetPtr++ = *srcPtr++;
// Cap it off at the new end
*targetPtr = 0;
}
unsigned int XMLString::hash( const char* const tohash
, const unsigned int hashModulus
, MemoryManager* const)
{
assert(hashModulus);
unsigned int hashVal = 0;
if (tohash) {
const char* curCh = tohash;
while (*curCh)
{
unsigned int top = hashVal >> 24;
hashVal += (hashVal * 37) + top + (unsigned int)(*curCh);
curCh++;
}
}
// Divide by modulus
return hashVal % hashModulus;
}
int XMLString::indexOf(const char* const toSearch, const char ch)
{
const unsigned int len = strlen(toSearch);
for (unsigned int i = 0; i < len; i++)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
int XMLString::indexOf( const char* const toSearch
, const char ch
, const unsigned int fromIndex
, MemoryManager* const manager)
{
const unsigned int len = strlen(toSearch);
// Make sure the start index is within the XMLString bounds
if ((int)fromIndex > ((int)len)-1)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (unsigned int i = fromIndex; i < len; i++)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
int XMLString::lastIndexOf(const char* const toSearch, const char ch)
{
const int len = strlen(toSearch);
for (int i = len-1; i >= 0; i--)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
int XMLString::lastIndexOf( const char* const toSearch
, const char ch
, const unsigned int fromIndex
, MemoryManager* const manager)
{
const int len = strlen(toSearch);
// Make sure the start index is within the XMLString bounds
if ((int)fromIndex > len-1)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (int i = (int)fromIndex; i >= 0; i--)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
unsigned int XMLString::replaceTokens( XMLCh* const errText
, const unsigned int maxChars
, const XMLCh* const text1
, const XMLCh* const text2
, const XMLCh* const text3
, const XMLCh* const text4
, MemoryManager* const manager)
{
//
// We have to build the string back into the source string, so allocate
// a temp string and copy the orignal text to it. We'll then treat the
// incoming buffer as a target buffer. Put a janitor on it to make sure
// it gets cleaned up.
//
XMLCh* orgText = replicate(errText, manager);
ArrayJanitor<XMLCh> janText(orgText, manager);
XMLCh* pszSrc = orgText;
unsigned int curOutInd = 0;
while (*pszSrc && (curOutInd < maxChars))
{
//
// Loop until we see a { character. Until we do, just copy chars
// from src to target, being sure not to overrun the output buffer.
//
while ((*pszSrc != chOpenCurly) && (curOutInd < maxChars))
{
if (!*pszSrc)
break;
errText[curOutInd++] = *pszSrc++;
}
// If we did not find a curly, then we are done
if (*pszSrc != chOpenCurly)
break;
//
// Probe this one to see if it matches our pattern of {x}. If not
// then copy over those chars and go back to the first loop.
//
if ((*(pszSrc+1) >= chDigit_0)
&& (*(pszSrc+1) <= chDigit_3)
&& (*(pszSrc+2) == chCloseCurly))
{
//
// Its one of our guys, so move the source pointer up past the
// token we are replacing. First though get out the token number
// character.
//
XMLCh tokCh = *(pszSrc+1);
pszSrc += 3;
// Now copy over the replacement text
const XMLCh* repText = 0;
if (tokCh == chDigit_0)
repText = text1;
else if (tokCh == chDigit_1)
repText = text2;
else if (tokCh == chDigit_2)
repText = text3;
else if (tokCh == chDigit_3)
repText = text4;
// If this one is null, copy over a null string
if (!repText)
repText = gNullStr;
while (*repText && (curOutInd < maxChars))
errText[curOutInd++] = *repText++;
}
else
{
// Escape the curly brace character and continue
errText[curOutInd++] = *pszSrc++;
}
}
// Copy over a null terminator
errText[curOutInd] = 0;
// And return the count of chars we output
return curOutInd;
}
XMLCh* XMLString::replicate(const XMLCh* const toRep)
{
// If a null string, return a null string!
XMLCh* ret = 0;
if (toRep)
{
const unsigned int len = stringLen(toRep);
ret = new XMLCh[len + 1];
memcpy(ret, toRep, (len + 1) * sizeof(XMLCh));
}
return ret;
}
char* XMLString::replicate(const char* const toRep)
{
// If a null string, return a null string
if (!toRep)
return 0;
//
// Get the len of the source and allocate a new buffer. Make sure to
// account for the nul terminator.
//
const unsigned int srcLen = strlen(toRep);
char* ret = new char[srcLen+1];
// Copy over the text, adjusting for the size of a char
memcpy(ret, toRep, (srcLen+1) * sizeof(char));
return ret;
}
char* XMLString::replicate( const char* const toRep
, MemoryManager* const manager)
{
// If a null string, return a null string
if (!toRep)
return 0;
//
// Get the len of the source and allocate a new buffer. Make sure to
// account for the nul terminator.
//
const unsigned int srcLen = strlen(toRep);
char* ret = (char*) manager->allocate((srcLen+1) * sizeof(char)); //new char[srcLen+1];
// Copy over the text, adjusting for the size of a char
memcpy(ret, toRep, (srcLen+1) * sizeof(char));
return ret;
}
bool XMLString::startsWith(const char* const toTest, const char* const prefix)
{
return (strncmp(toTest, prefix, strlen(prefix)) == 0);
}
bool XMLString::startsWithI(const char* const toTest
, const char* const prefix)
{
return (strnicmp(toTest, prefix, strlen(prefix)) == 0);
}
unsigned int XMLString::stringLen(const char* const src)
{
return strlen(src);
}
char* XMLString::transcode(const XMLCh* const toTranscode)
{
return gTranscoder->transcode(toTranscode);
}
char* XMLString::transcode(const XMLCh* const toTranscode,
MemoryManager* const manager)
{
return gTranscoder->transcode(toTranscode, manager);
}
bool XMLString::transcode( const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxChars
, MemoryManager* const manager)
{
if (!gTranscoder->transcode(toTranscode, toFill, maxChars, manager))
return false;
return true;
}
XMLCh* XMLString::transcode(const char* const toTranscode)
{
return gTranscoder->transcode(toTranscode);
}
XMLCh* XMLString::transcode(const char* const toTranscode,
MemoryManager* const manager)
{
return gTranscoder->transcode(toTranscode, manager);
}
bool XMLString::transcode( const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars
, MemoryManager* const manager)
{
if (!gTranscoder->transcode(toTranscode, toFill, maxChars, manager))
return false;
return true;
}
void XMLString::trim(char* const toTrim)
{
const unsigned int len = strlen(toTrim);
unsigned int skip, scrape;
for (skip = 0; skip < len; skip++)
{
if (! isspace(toTrim[skip]))
break;
}
for (scrape = len; scrape > skip; scrape--)
{
if (! isspace(toTrim[scrape - 1] ))
break;
}
// Cap off at the scrap point
if (scrape != len)
toTrim[scrape] = 0;
if (skip)
{
// Copy the chars down
unsigned int index = 0;
while (toTrim[skip])
toTrim[index++] = toTrim[skip++];
toTrim[index] = 0;
}
}
void XMLString::subString(char* const targetStr, const char* const srcStr
, const int startIndex, const int endIndex
, MemoryManager* const manager)
{
if (targetStr == 0)
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_ZeroSizedTargetBuf, manager);
const int srcLen = strlen(srcStr);
const int copySize = endIndex - startIndex;
// Make sure the start index is within the XMLString bounds
if ( startIndex < 0 || startIndex > endIndex || endIndex > srcLen)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (int i= startIndex; i < endIndex; i++) {
targetStr[i-startIndex] = srcStr[i];
}
targetStr[copySize] = 0;
}
bool XMLString::isValidNOTATION(const XMLCh* const name
, MemoryManager* const manager )
{
//
// NOTATATION: <URI>:<localPart>
// where URI is optional
// ':' and localPart must be present
//
int nameLen = XMLString::stringLen(name);
int colPos = XMLString::lastIndexOf(name, chColon);
if ((colPos == -1) || // no ':'
(colPos == nameLen - 1) ) // <URI>':'
return false;
// Examine localpart
if (!XMLString::isValidNCName(&name[colPos+1]))
{
return false;
}
else if (colPos == 0)
{
return true;
}
else
{
// Examine URI
XMLCh* const temp =
(XMLCh*) manager->allocate((colPos + 1) * sizeof(XMLCh));
const ArrayJanitor<XMLCh> jan(temp, manager);
copyNString(temp, name, colPos);
temp[colPos] = 0;
try
{
XMLUri newURI(temp, manager); // no relative uri support here
}
catch (const MalformedURLException&)
{
return false;
}
return true;
}
}
/**
* Deprecated: isValidNCName
* Check first char, and then the rest of the name char.
* But colon should be excluded
*/
bool XMLString::isValidNCName(const XMLCh* const name) {
return XMLChar1_0::isValidNCName(name, XMLString::stringLen(name));
}
/**
* Deprecated: isValidName
* Check first char, and then the rest of the name char
*
*/
bool XMLString::isValidName(const XMLCh* const name) {
return XMLChar1_0::isValidName(name, XMLString::stringLen(name));
}
/**
* isValidEncName
*
* [80] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
*
*/
bool XMLString::isValidEncName(const XMLCh* const name)
{
if ( XMLString::stringLen(name) == 0 )
return false;
const XMLCh* tempName = name;
XMLCh firstChar = *tempName++;
if (!isAlpha(firstChar))
return false;
while(*tempName)
{
if (( !isAlpha(*tempName)) &&
( !isDigit(*tempName)) &&
( *tempName != chPeriod) &&
( *tempName != chUnderscore) &&
( *tempName != chDash) )
return false;
tempName++;
}
return true;
}
/**
* Deprecated: isValidQName
*
*/
bool XMLString::isValidQName(const XMLCh* const name)
{
return XMLChar1_0::isValidQName(name, XMLString::stringLen(name));
}
bool XMLString::isAlpha(XMLCh const theChar)
{
if ((( theChar >= chLatin_a ) && ( theChar <= chLatin_z )) ||
(( theChar >= chLatin_A ) && ( theChar <= chLatin_Z )) )
return true;
return false;
}
bool XMLString::isDigit(XMLCh const theChar)
{
if (( theChar >= chDigit_0 ) && ( theChar <= chDigit_9 ))
return true;
return false;
}
bool XMLString::isAlphaNum(XMLCh const theChar)
{
return (isAlpha(theChar) || isDigit(theChar));
}
bool XMLString::isHex(XMLCh const theChar)
{
return (isDigit(theChar) ||
(theChar >= chLatin_a && theChar <= chLatin_f) ||
(theChar >= chLatin_A && theChar <= chLatin_F));
}
// Deprecated
bool XMLString::isAllWhiteSpace(const XMLCh* const toCheck)
{
return XMLChar1_0::isAllSpaces(toCheck, XMLString::stringLen(toCheck));
}
// ---------------------------------------------------------------------------
// Wide char versions of most of the string methods
// ---------------------------------------------------------------------------
void XMLString::binToText( const unsigned long toFormat
, XMLCh* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
static const XMLCh digitList[16] =
{
chDigit_0, chDigit_1, chDigit_2, chDigit_3, chDigit_4, chDigit_5
, chDigit_6, chDigit_7, chDigit_8, chDigit_9, chLatin_A, chLatin_B
, chLatin_C, chLatin_D, chLatin_e, chLatin_F
};
if (!maxChars)
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_ZeroSizedTargetBuf, manager);
// Handle special case
if (!toFormat)
{
toFill[0] = chDigit_0;
toFill[1] = chNull;
return;
}
// This is used to fill the temp buffer
unsigned int tmpIndex = 0;
// A copy of the conversion value that we can modify
unsigned int tmpVal = toFormat;
//
// Convert into a temp buffer that we know is large enough. This avoids
// having to check for overflow in the inner loops, and we have to flip
// the resulting sring anyway.
//
XMLCh tmpBuf[128];
//
// For each radix, do the optimal thing. For bin and hex, we can special
// case them and do shift and mask oriented stuff. For oct and decimal
// there isn't much to do but bull through it with divides.
//
if (radix == 2)
{
while (tmpVal)
{
if (tmpVal & 0x1UL)
tmpBuf[tmpIndex++] = chDigit_1;
else
tmpBuf[tmpIndex++] = chDigit_0;
tmpVal >>= 1;
}
}
else if (radix == 16)
{
while (tmpVal)
{
const unsigned int charInd = (tmpVal & 0xFUL);
tmpBuf[tmpIndex++] = digitList[charInd];
tmpVal >>= 4;
}
}
else if ((radix == 8) || (radix == 10))
{
while (tmpVal)
{
const unsigned int charInd = (tmpVal % radix);
tmpBuf[tmpIndex++] = digitList[charInd];
tmpVal /= radix;
}
}
else
{
ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Str_UnknownRadix, manager);
}
// See if have enough room in the caller's buffer
if (tmpIndex > maxChars)
{
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_TargetBufTooSmall, manager);
}
// Reverse the tmp buffer into the caller's buffer
unsigned int outIndex = 0;
for (; tmpIndex > 0; tmpIndex--)
toFill[outIndex++] = tmpBuf[tmpIndex-1];
// And cap off the caller's buffer
toFill[outIndex] = chNull;
}
void XMLString::binToText( const unsigned int toFormat
, XMLCh* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
// Just call the unsigned long version
binToText((unsigned long)toFormat, toFill, maxChars, radix, manager);
}
void XMLString::binToText( const long toFormat
, XMLCh* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
//
// If its negative, then put a negative sign into the output and flip
// the sign of the local temp value.
//
unsigned int startInd = 0;
unsigned long actualVal;
if (toFormat < 0)
{
toFill[0] = chDash;
startInd++;
actualVal = (unsigned long)(toFormat * -1);
}
else
{
actualVal = (unsigned long)(toFormat);
}
// And now call the unsigned long version
binToText(actualVal, &toFill[startInd], maxChars, radix, manager);
}
void XMLString::binToText( const int toFormat
, XMLCh* const toFill
, const unsigned int maxChars
, const unsigned int radix
, MemoryManager* const manager)
{
//
// If its negative, then put a negative sign into the output and flip
// the sign of the local temp value.
//
unsigned int startInd = 0;
unsigned long actualVal;
if (toFormat < 0)
{
toFill[0] = chDash;
startInd++;
actualVal = (unsigned long)(toFormat * -1);
}
else
{
actualVal = (unsigned long)(toFormat);
}
// And now call the unsigned long version
binToText(actualVal, &toFill[startInd], maxChars, radix, manager);
}
void XMLString::catString(XMLCh* const target, const XMLCh* const src)
{
// Get the starting point for the cat on the target XMLString
unsigned int index = stringLen(target);
// While the source is not zero, add them to target and bump
const XMLCh* pszTmp = src;
while (*pszTmp)
target[index++] = *pszTmp++;
// Cap off the target where we ended
target[index] = chNull;
}
int XMLString::compareIString( const XMLCh* const str1
, const XMLCh* const str2)
{
// Refer this one to the transcoding service
return XMLPlatformUtils::fgTransService->compareIString(str1, str2);
}
int XMLString::compareIStringASCII( const XMLCh* const str1
, const XMLCh* const str2)
{
const XMLCh* psz1 = str1;
const XMLCh* psz2 = str2;
if (psz1 == 0 || psz2 == 0) {
if (psz1 == 0) {
return 0 - XMLString::stringLen(psz2);
}
else if (psz2 == 0) {
return XMLString::stringLen(psz1);
}
}
XMLCh ch1;
XMLCh ch2;
while (true) {
if (*psz1 >= chLatin_A && *psz1 <= chLatin_Z)
ch1 = *psz1 - chLatin_A + chLatin_a;
else
ch1 = *psz1;
if (*psz2 >= chLatin_A && *psz2 <= chLatin_Z)
ch2 = *psz2 - chLatin_A + chLatin_a;
else
ch2 = *psz2;
// If an inequality, then return difference
if (ch1 != ch2)
return int(ch1) - int(ch2);
// If either ended, then both ended, so equal
if (!ch1)
break;
// Move upwards to next chars
psz1++;
psz2++;
}
return 0;
}
int XMLString::compareNString( const XMLCh* const str1
, const XMLCh* const str2
, const unsigned int maxChars)
{
const XMLCh* psz1 = str1;
const XMLCh* psz2 = str2;
unsigned int curCount = 0;
while (curCount < maxChars)
{
// If an inequality, then return difference
if (*psz1 != *psz2)
return int(*psz1) - int(*psz2);
// If either ended, then both ended, so equal
if (!*psz1)
break;
// Move upwards to next chars
psz1++;
psz2++;
//
// Bump the count of chars done.
//
curCount++;
}
// If we inspected all the maxChars, then we are equal.
return 0;
}
int XMLString::compareNIString( const XMLCh* const str1
, const XMLCh* const str2
, const unsigned int maxChars)
{
// Refer this oneto the transcoding service
return XMLPlatformUtils::fgTransService->compareNIString(str1, str2, maxChars);
}
int XMLString::compareString( const XMLCh* const str1
, const XMLCh* const str2)
{
const XMLCh* psz1 = str1;
const XMLCh* psz2 = str2;
if (psz1 == 0 || psz2 == 0) {
if (psz1 == 0) {
return 0 - XMLString::stringLen(psz2);
}
else if (psz2 == 0) {
return XMLString::stringLen(psz1);
}
}
while (true)
{
// If an inequality, then return the difference
if (*psz1 != *psz2)
return int(*psz1) - int(*psz2);
// If either has ended, then they both ended, so equal
if (!*psz1)
break;
// Move upwards for the next round
psz1++;
psz2++;
}
return 0;
}
bool XMLString::regionMatches(const XMLCh* const str1
, const int offset1
, const XMLCh* const str2
, const int offset2
, const unsigned int charCount)
{
if (!validateRegion(str1, offset1,str2, offset2, charCount))
return false;
if (compareNString(str1+offset1, str2+offset2, charCount) != 0)
return false;
return true;
}
bool XMLString::regionIMatches(const XMLCh* const str1
, const int offset1
, const XMLCh* const str2
, const int offset2
, const unsigned int charCount)
{
if (!validateRegion(str1, offset1,str2, offset2, charCount))
return false;
if (compareNIString(str1+offset1, str2+offset2, charCount) != 0)
return false;
return true;
}
void XMLString::copyString(XMLCh* const target, const XMLCh* const src)
{
if (!src)
{
*target = 0;
return;
}
XMLCh* pszOut = target;
const XMLCh* pszIn = src;
while (*pszIn)
*pszOut++ = *pszIn++;
// Capp off the target where we ended
*pszOut = 0;
}
bool XMLString::copyNString( XMLCh* const target
, const XMLCh* const src
, const unsigned int maxChars)
{
XMLCh* outPtr = target;
const XMLCh* srcPtr = src;
const XMLCh* endPtr = target + maxChars - 1;
while (*srcPtr && (outPtr <= endPtr))
*outPtr++ = *srcPtr++;
// Cap it off here
*outPtr = 0;
// Return whether we copied it all or hit the max
return (*srcPtr == 0);
}
const XMLCh* XMLString::findAny(const XMLCh* const toSearch
, const XMLCh* const searchList)
{
const XMLCh* srcPtr = toSearch;
while (*srcPtr)
{
const XMLCh* listPtr = searchList;
const XMLCh curCh = *srcPtr;
while (*listPtr)
{
if (curCh == *listPtr++)
return srcPtr;
}
srcPtr++;
}
return 0;
}
XMLCh* XMLString::findAny( XMLCh* const toSearch
, const XMLCh* const searchList)
{
XMLCh* srcPtr = toSearch;
while (*srcPtr)
{
const XMLCh* listPtr = searchList;
const XMLCh curCh = *srcPtr;
while (*listPtr)
{
if (curCh == *listPtr++)
return srcPtr;
}
srcPtr++;
}
return 0;
}
int XMLString::patternMatch( const XMLCh* const toSearch
, const XMLCh* const pattern)
{
if (!toSearch || !*toSearch )
return -1;
const int patnLen = XMLString::stringLen(pattern);
if ( !patnLen )
return -1;
const XMLCh* srcPtr = toSearch;
const XMLCh* patnStart = toSearch;
int patnIndex = 0;
while (*srcPtr)
{
if ( !(*srcPtr++ == pattern[patnIndex]))
{
patnIndex = 0;
srcPtr = ++patnStart;
}
else
{
if (++patnIndex == patnLen)
// full pattern match found
return (srcPtr - patnLen - toSearch);
}
}
return -1;
}
unsigned int XMLString::hashN( const XMLCh* const tohash
, const unsigned int n
, const unsigned int hashModulus
, MemoryManager* const)
{
assert(hashModulus);
unsigned int hashVal = 0;
if (tohash) {
const XMLCh* curCh = tohash;
int i = n;
while (i--)
{
unsigned int top = hashVal >> 24;
hashVal += (hashVal * 37) + top + (unsigned int)(*curCh);
curCh++;
}
}
// Divide by modulus
return hashVal % hashModulus;
}
int XMLString::indexOf(const XMLCh* const toSearch, const XMLCh ch)
{
if (toSearch)
{
const XMLCh* srcPtr = toSearch;
while (*srcPtr)
{
if (ch == *srcPtr)
return (int)(srcPtr - toSearch);
srcPtr++;
}
}
return -1;
}
int XMLString::indexOf( const XMLCh* const toSearch
, const XMLCh ch
, const unsigned int fromIndex
, MemoryManager* const manager)
{
const int len = stringLen(toSearch);
// Make sure the start index is within the XMLString bounds
if ((int)fromIndex > len-1)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (int i = (int)fromIndex; i < len; i++)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
int XMLString::lastIndexOf(const XMLCh ch,
const XMLCh* const toSearch,
const unsigned int toSearchLen)
{
for (int i = (int)toSearchLen-1; i >= 0; i--)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
int XMLString::lastIndexOf( const XMLCh* const toSearch
, const XMLCh ch
, const unsigned int fromIndex
, MemoryManager* const manager)
{
const int len = stringLen(toSearch);
if ((int)fromIndex > len-1)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (int i = (int)fromIndex; i >= 0; i--)
{
if (toSearch[i] == ch)
return i;
}
return -1;
}
XMLCh*
XMLString::makeUName(const XMLCh* const pszURI, const XMLCh* const pszName)
{
//
// If there is a URI, then format out the full name in the {uri}name
// form. Otherwise, just set it to the same thing as the base name.
//
XMLCh* pszRet = 0;
const unsigned int uriLen = stringLen(pszURI);
if (uriLen)
{
pszRet = new XMLCh[uriLen + stringLen(pszName) + 3];
XMLCh szTmp[2];
szTmp[1] = 0;
szTmp[0] = chOpenCurly;
copyString(pszRet, szTmp);
catString(pszRet, pszURI);
szTmp[0] = chCloseCurly;
catString(pszRet, szTmp);
catString(pszRet, pszName);
}
else
{
pszRet = replicate(pszName);
}
return pszRet;
}
bool XMLString::textToBin(const XMLCh* const toConvert, unsigned int& toFill
, MemoryManager* const manager)
{
toFill = 0;
// If no string, then its a failure
if ((!toConvert) || (!*toConvert))
return false;
XMLCh* trimmedStr = XMLString::replicate(toConvert, manager);
ArrayJanitor<XMLCh> jan1(trimmedStr, manager);
XMLString::trim(trimmedStr);
unsigned int trimmedStrLen = XMLString::stringLen(trimmedStr);
if ( !trimmedStrLen )
return false;
// we don't allow '-' sign
if (XMLString::indexOf(trimmedStr, chDash, 0, manager) != -1)
return false;
//the errno set by previous run is NOT automatically cleared
errno = 0;
char *nptr = XMLString::transcode(trimmedStr, manager);
ArrayJanitor<char> jan2(nptr, manager);
char *endptr;
//
// REVISIT: conversion of (unsigned long) to (unsigned int)
// may truncate value on IA64
toFill = (unsigned int) strtoul(nptr, &endptr, 10);
// check if all chars are valid char
// check if overflow/underflow occurs
if ( ( (endptr - nptr) != (int) trimmedStrLen) ||
(errno == ERANGE) )
return false;
return true;
}
int XMLString::parseInt(const XMLCh* const toConvert
, MemoryManager* const manager)
{
// If no string, or empty string, then it is a failure
if ((!toConvert) || (!*toConvert))
ThrowXMLwithMemMgr(NumberFormatException, XMLExcepts::XMLNUM_null_ptr, manager);
XMLCh* trimmedStr = XMLString::replicate(toConvert, manager);
ArrayJanitor<XMLCh> jan1(trimmedStr, manager);
XMLString::trim(trimmedStr);
unsigned int trimmedStrLen = XMLString::stringLen(trimmedStr);
if ( !trimmedStrLen )
ThrowXMLwithMemMgr(NumberFormatException, XMLExcepts::XMLNUM_null_ptr, manager);
//the errno set by previous run is NOT automatically cleared
errno = 0;
char *nptr = XMLString::transcode(trimmedStr, manager);
ArrayJanitor<char> jan2(nptr, manager);
char *endptr;
long retVal = strtol(nptr, &endptr, 10);
// check if all chars are valid char
if ( (endptr - nptr) != (int) trimmedStrLen)
ThrowXMLwithMemMgr(NumberFormatException, XMLExcepts::XMLNUM_Inv_chars, manager);
// check if overflow/underflow occurs
if (errno == ERANGE)
ThrowXMLwithMemMgr(NumberFormatException, XMLExcepts::Str_ConvertOverflow, manager);
//
// REVISIT: conversion of (long) to (int)
// may truncate value on IA64
return (int) retVal;
}
void XMLString::trim(XMLCh* const toTrim)
{
const unsigned int len = stringLen(toTrim);
unsigned int skip, scrape;
for (skip = 0; skip < len; skip++)
{
if (!XMLChar1_0::isWhitespace(toTrim[skip]))
break;
}
for (scrape = len; scrape > skip; scrape--)
{
if (!XMLChar1_0::isWhitespace(toTrim[scrape - 1]))
break;
}
// Cap off at the scrap point
if (scrape != len)
toTrim[scrape] = 0;
if (skip)
{
// Copy the chars down
unsigned int index = 0;
while (toTrim[skip])
toTrim[index++] = toTrim[skip++];
toTrim[index] = 0;
}
}
void XMLString::upperCase(XMLCh* const toUpperCase)
{
// Refer this one to the transcoding service
XMLPlatformUtils::fgTransService->upperCase(toUpperCase);
}
void XMLString::upperCaseASCII(XMLCh* const toUpperCase)
{
XMLCh* psz1 = toUpperCase;
if (!psz1)
return;
while (*psz1) {
if (*psz1 >= chLatin_a && *psz1 <= chLatin_z)
*psz1 = *psz1 - chLatin_a + chLatin_A;
psz1++;
}
}
void XMLString::lowerCase(XMLCh* const toLowerCase)
{
// Refer this one to the transcoding service
XMLPlatformUtils::fgTransService->lowerCase(toLowerCase);
}
void XMLString::lowerCaseASCII(XMLCh* const toLowerCase)
{
XMLCh* psz1 = toLowerCase;
if (!psz1)
return;
while (*psz1) {
if (*psz1 >= chLatin_A && *psz1 <= chLatin_Z)
*psz1 = *psz1 - chLatin_A + chLatin_a;
psz1++;
}
}
void XMLString::subString(XMLCh* const targetStr, const XMLCh* const srcStr
, const int startIndex, const int endIndex
, MemoryManager* const manager)
{
subString(targetStr, srcStr, startIndex, endIndex, stringLen(srcStr), manager);
}
void XMLString::subString(XMLCh* const targetStr, const XMLCh* const srcStr
, const int startIndex, const int endIndex
, const int srcStrLength
, MemoryManager* const manager)
{
//if (startIndex < 0 || endIndex < 0)
// ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_NegativeIndex);
if (targetStr == 0)
ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::Str_ZeroSizedTargetBuf, manager);
const int copySize = endIndex - startIndex;
// Make sure the start index is within the XMLString bounds
if ( startIndex < 0 || startIndex > endIndex || endIndex > srcStrLength)
ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::Str_StartIndexPastEnd, manager);
for (int i= startIndex; i < endIndex; i++) {
targetStr[i-startIndex] = srcStr[i];
}
targetStr[copySize] = 0;
}
BaseRefVectorOf<XMLCh>* XMLString::tokenizeString(const XMLCh* const tokenizeSrc
, MemoryManager* const manager)
{
XMLCh* orgText = replicate(tokenizeSrc, manager);
ArrayJanitor<XMLCh> janText(orgText, manager);
XMLCh* tokenizeStr = orgText;
RefArrayVectorOf<XMLCh>* tokenStack = new (manager) RefArrayVectorOf<XMLCh>(16, true, manager);
unsigned int len = stringLen(tokenizeStr);
unsigned int skip;
unsigned int index = 0;
while (index != len) {
// find the first non-space character
for (skip = index; skip < len; skip++)
{
if (!XMLChar1_0::isWhitespace(tokenizeStr[skip]))
break;
}
index = skip;
// find the delimiter (space character)
for (; skip < len; skip++)
{
if (XMLChar1_0::isWhitespace(tokenizeStr[skip]))
break;
}
// we reached the end of the string
if (skip == index)
break;
// these tokens are adopted in the RefVector and will be deleted
// when the vector is deleted by the caller
XMLCh* token = (XMLCh*) manager->allocate
(
(skip+1-index) * sizeof(XMLCh)
);//new XMLCh[skip+1-index];
XMLString::subString(token, tokenizeStr, index, skip, len, manager);
tokenStack->addElement(token);
index = skip;
}
return tokenStack;
}
//
// This method is called when we get a notation or enumeration type attribute
// to validate. We have to confirm that the passed value to find is one of
// the values in the passed list. The list is a space separated string of
// values to match against.
//
bool XMLString::isInList(const XMLCh* const toFind, const XMLCh* const enumList)
{
//
// We loop through the values in the list via this outer loop. We end
// when we hit the end of the enum list or get a match.
//
const XMLCh* listPtr = enumList;
const unsigned int findLen = XMLString::stringLen(toFind);
while (*listPtr)
{
unsigned int testInd;
for (testInd = 0; testInd < findLen; testInd++)
{
//
// If they don't match, then reset and try again. Note that
// hitting the end of the current item will cause a mismatch
// because there can be no spaces in the toFind string.
//
if (listPtr[testInd] != toFind[testInd])
break;
}
//
// If we went the distance, see if we matched. If we did, the current
// list character has to be null or space.
//
if (testInd == findLen)
{
if ((listPtr[testInd] == chSpace) || !listPtr[testInd])
return true;
}
// Run the list pointer up to the next substring
while ((*listPtr != chSpace) && *listPtr)
listPtr++;
// If we hit the end, then we failed
if (!*listPtr)
return false;
// Else move past the space and try again
listPtr++;
}
// We never found it
return false;
}
//
// a string is whitespace:replaced, is having no
// #xD Carriage Return
// #xA Line Feed
// #x9 TAB
//
bool XMLString::isWSReplaced(const XMLCh* const toCheck)
{
// If no string, then its a OK
if (( !toCheck ) || ( !*toCheck ))
return true;
const XMLCh* startPtr = toCheck;
while ( *startPtr )
{
if ( ( *startPtr == chCR) ||
( *startPtr == chLF) ||
( *startPtr == chHTab))
return false;
startPtr++;
}
return true;
}
//
// to replace characters listed below to #x20
// #xD Carriage Return
// #xA Line Feed
// #x9 TAB
//
void XMLString::replaceWS(XMLCh* const toConvert
, MemoryManager* const manager)
{
int strLen = XMLString::stringLen(toConvert);
if (strLen == 0)
return;
XMLCh* retBuf = (XMLCh*) manager->allocate
(
(strLen+1) * sizeof(XMLCh)
);//new XMLCh[strLen+1];
XMLCh* retPtr = &retBuf[0];
XMLCh* startPtr = toConvert;
while ( *startPtr )
{
if ( ( *startPtr == chCR) ||
( *startPtr == chLF) ||
( *startPtr == chHTab))
*retPtr = chSpace;
else
*retPtr = *startPtr;
retPtr++;
startPtr++;
}
retBuf[strLen] = chNull;
XMLString::moveChars(toConvert, retBuf, strLen);
manager->deallocate(retBuf);//delete[] retBuf;
return;
}
//
// a string is whitespace:collapsed, is whitespace::replaced
// and no
// leading space (#x20)
// trailing space
// no contiguous sequences of spaces
//
bool XMLString::isWSCollapsed(const XMLCh* const toCheck)
{
if (( !toCheck ) || ( !*toCheck ))
return true;
// shall be whitespace::replaced first
if ( !isWSReplaced(toCheck) )
return false;
// no leading or trailing space
if ((*toCheck == chSpace) ||
(toCheck[XMLString::stringLen(toCheck)-1] == chSpace))
return false;
const XMLCh* startPtr = toCheck;
XMLCh theChar;
bool inSpace = false;
while ( (theChar = *startPtr) != 0 )
{
if ( theChar == chSpace)
{
if (inSpace)
return false;
else
inSpace = true;
}
else
inSpace = false;
startPtr++;
}
return true;
}
//
// no leading and/or trailing spaces
// no continuous sequences of spaces
//
void XMLString::collapseWS(XMLCh* const toConvert
, MemoryManager* const manager)
{
// If no string, then its a failure
if (( !toConvert ) || ( !*toConvert ))
return;
// replace whitespace first
replaceWS(toConvert, manager);
// remove leading spaces
const XMLCh* startPtr = toConvert;
while ( *startPtr == chSpace )
startPtr++;
if (!*startPtr)
return;
// remove trailing spaces
const XMLCh* endPtr = toConvert + stringLen(toConvert);
while (*(endPtr - 1) == chSpace)
endPtr--;
//
// Work through what remains and chop continuous spaces
//
XMLCh* retBuf = (XMLCh*) manager->allocate
(
(endPtr - startPtr + 1) * sizeof(XMLCh)
);//new XMLCh[endPtr - startPtr + 1];
XMLCh* retPtr = &retBuf[0];
bool inSpace = false;
while (startPtr < endPtr)
{
if ( *startPtr == chSpace)
{
if (inSpace)
{
//discard it;
}
else
{
inSpace = true;
*retPtr = chSpace; //copy the first chSpace
retPtr++;
}
}
else
{
inSpace = false;
*retPtr = *startPtr;
retPtr++;
}
startPtr++;
}
*retPtr = chNull;
XMLString::moveChars(toConvert, retBuf, stringLen(retBuf)+1); //copy the last chNull as well
manager->deallocate(retBuf);//delete[] retBuf;
return;
}
//
// remove whitespace
//
void XMLString::removeWS(XMLCh* const toConvert
, MemoryManager* const manager)
{
// If no string, then its a failure
if (( !toConvert ) || ( !*toConvert ))
return;
XMLCh* retBuf = (XMLCh*) manager->allocate
(
(XMLString::stringLen(toConvert) + 1) * sizeof(XMLCh)
);//new XMLCh[ XMLString::stringLen(toConvert) + 1];
XMLCh* retPtr = &retBuf[0];
XMLCh* startPtr = toConvert;
while (*startPtr)
{
if ( ( *startPtr != chCR) &&
( *startPtr != chLF) &&
( *startPtr != chHTab) &&
( *startPtr != chSpace) )
{
*retPtr++ = *startPtr;
}
startPtr++;
}
*retPtr = chNull;
XMLString::moveChars(toConvert, retBuf, stringLen(retBuf)+1); //copy the last chNull as well
manager->deallocate(retBuf);//delete[] retBuf;
return;
}
void XMLString::removeChar(const XMLCh* const srcString
, const XMLCh& toRemove
, XMLBuffer& dstBuffer)
{
const XMLCh* pszSrc = srcString;
XMLCh c;
dstBuffer.reset();
while ((c=*pszSrc++)!=0)
{
if (c != toRemove)
dstBuffer.append(c);
}
}
/**
* Fixes a platform dependent absolute path filename to standard URI form.
* 1. Windows: fix 'x:' to 'file:///x:' and convert any backslash to forward slash
* 2. UNIX: fix '/blah/blahblah' to 'file:///blah/blahblah'
*/
void XMLString::fixURI(const XMLCh* const str, XMLCh* const target)
{
if (!str || !*str)
return;
int colonIdx = XMLString::indexOf(str, chColon);
// If starts with a '/' we assume
// this is an absolute (UNIX) file path and prefix it with file://
if (colonIdx == -1 && XMLString::indexOf(str, chForwardSlash) == 0) {
unsigned index = 0;
target[index++] = chLatin_f;
target[index++] = chLatin_i;
target[index++] = chLatin_l;
target[index++] = chLatin_e;
target[index++] = chColon;
target[index++] = chForwardSlash;
target[index++] = chForwardSlash;
// copy the string
const XMLCh* inPtr = str;
while (*inPtr)
target[index++] = *inPtr++;
target[index] = chNull;
}
else if (colonIdx == 1 && XMLString::isAlpha(*str)) {
// If starts with a driver letter 'x:' we assume
// this is an absolute (Windows) file path and prefix it with file:///
unsigned index = 0;
target[index++] = chLatin_f;
target[index++] = chLatin_i;
target[index++] = chLatin_l;
target[index++] = chLatin_e;
target[index++] = chColon;
target[index++] = chForwardSlash;
target[index++] = chForwardSlash;
target[index++] = chForwardSlash;
// copy the string and fix any backward slash
const XMLCh* inPtr = str;
while (*inPtr) {
if (*inPtr == chYenSign ||
*inPtr == chWonSign ||
*inPtr == chBackSlash)
target[index++] = chForwardSlash;
else
target[index++] = *inPtr;
inPtr++;
}
// cap it with null
target[index] = chNull;
}
else {
// not specific case, so just copy the string over
copyString(target, str);
}
}
void XMLString::release(char** buf)
{
delete [] *buf;
*buf = 0;
}
void XMLString::release(XMLCh** buf)
{
delete [] *buf;
*buf = 0;
}
void XMLString::release(XMLByte** buf)
{
delete [] *buf;
*buf = 0;
}
void XMLString::release(void** buf, MemoryManager* const manager)
{
manager->deallocate(*buf);
*buf = 0;
}
// ---------------------------------------------------------------------------
// XMLString: Private static methods
// ---------------------------------------------------------------------------
void XMLString::initString(XMLLCPTranscoder* const defToUse,
MemoryManager* const manager)
{
// Store away the default transcoder that we are to use
gTranscoder = defToUse;
// Store memory manager
fgMemoryManager = manager;
}
void XMLString::termString()
{
// Just clean up our local code page transcoder
delete gTranscoder;
gTranscoder = 0;
// reset memory manager
fgMemoryManager = 0;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
1970
]
]
] |
bc5e95dbba1c60e12bd6b291a0b8442d785d4640 | 555ce7f1e44349316e240485dca6f7cd4496ea9c | /DirectShowFilters/TsReader/source/DeMultiplexer.cpp | 5c244104dff99092eb66d893663809b51490e706 | [] | no_license | Yura80/MediaPortal-1 | c71ce5abf68c70852d261bed300302718ae2e0f3 | 5aae402f5aa19c9c3091c6d4442b457916a89053 | refs/heads/master | 2021-04-15T09:01:37.267793 | 2011-11-25T20:02:53 | 2011-11-25T20:11:02 | 2,851,405 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67,662 | cpp | /*
* Copyright (C) 2005-2009 Team MediaPortal
* http://www.team-mediaportal.com
*
* 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, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#pragma warning(disable:4996)
#pragma warning(disable:4995)
#include <afx.h>
#include <afxwin.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <streams.h>
#include <wmcodecdsp.h>
#include "demultiplexer.h"
#include "buffer.h"
#include "..\..\shared\adaptionfield.h"
#include "tsreader.h"
#include "audioPin.h"
#include "videoPin.h"
#include "subtitlePin.h"
#include "..\..\DVBSubtitle2\Source\IDVBSub.h"
#include "mediaFormats.h"
#include "h264nalu.h"
#include <cassert>
// For more details for memory leak detection see the alloctracing.h header
#include "..\..\alloctracing.h"
#define MAX_BUF_SIZE 8000
#define BUFFER_LENGTH 0x1000
#define READ_SIZE (1316*30)
#define INITIAL_READ_SIZE (READ_SIZE * 1024)
extern void LogDebug(const char *fmt, ...);
// *** UNCOMMENT THE NEXT LINE TO ENABLE DYNAMIC VIDEO PIN HANDLING!!!! ******
#define USE_DYNAMIC_PINS
extern int ShowBuffer;
CDeMultiplexer::CDeMultiplexer(CTsDuration& duration,CTsReaderFilter& filter)
:m_duration(duration)
,m_filter(filter)
{
m_patParser.SetCallBack(this);
m_pCurrentVideoBuffer = NULL;
m_pCurrentAudioBuffer = new CBuffer();
m_pCurrentSubtitleBuffer = new CBuffer();
m_iAudioStream = 0;
m_AudioStreamType = SERVICE_TYPE_AUDIO_UNKNOWN;
m_iSubtitleStream = 0;
m_audioPid = 0;
m_currentSubtitlePid = 0;
m_bEndOfFile = false;
m_bHoldAudio = false;
m_bHoldVideo = false;
m_bHoldSubtitle = false;
m_bShuttingDown = false;
m_iAudioIdx = -1;
m_iPatVersion = -1;
m_ReqPatVersion = -1;
m_receivedPackets = 0;
m_bSetAudioDiscontinuity = false;
m_bSetVideoDiscontinuity = false;
m_reader = NULL;
pTeletextEventCallback = NULL;
pSubUpdateCallback = NULL;
pTeletextPacketCallback = NULL;
pTeletextServiceInfoCallback = NULL;
m_iAudioReadCount = 0;
m_lastVideoPTS.IsValid = false;
m_lastAudioPTS.IsValid = false;
m_mpegParserTriggerFormatChange = false;
SetMediaChanging(false);
SetAudioChanging(false);
m_DisableDiscontinuitiesFiltering = false;
m_AudioPrevCC = -1;
m_FirstAudioSample = 0x7FFFFFFF00000000LL;
m_LastAudioSample = 0;
m_WaitHeaderPES=-1 ;
m_VideoPrevCC = -1;
m_bFirstGopFound = false;
m_bFrame0Found = false;
m_FirstVideoSample = 0x7FFFFFFF00000000LL;
m_LastVideoSample = 0;
m_LastDataFromRtsp = GetTickCount();
m_mpegPesParser = new CMpegPesParser();
}
CDeMultiplexer::~CDeMultiplexer()
{
m_bShuttingDown = true;
Flush();
delete m_pCurrentVideoBuffer;
delete m_pCurrentAudioBuffer;
delete m_pCurrentSubtitleBuffer;
delete m_mpegPesParser;
m_subtitleStreams.clear();
m_audioStreams.clear();
}
int CDeMultiplexer::GetVideoServiceType()
{
if(m_pids.videoPids.size() > 0)
{
return m_pids.videoPids[0].VideoServiceType;
}
else
{
return SERVICE_TYPE_VIDEO_UNKNOWN;
}
}
void CDeMultiplexer::SetFileReader(FileReader* reader)
{
m_reader = reader;
}
CPidTable CDeMultiplexer::GetPidTable()
{
return m_pids;
}
/// This methods selects the audio stream specified
/// and updates the audio output pin media type if needed
bool CDeMultiplexer::SetAudioStream(int stream)
{
LogDebug("SetAudioStream : %d",stream);
//is stream index valid?
if (stream < 0 || stream >= m_audioStreams.size())
return S_FALSE;
//set index
m_iAudioStream = stream;
//get the new audio stream type
int newAudioStreamType = SERVICE_TYPE_AUDIO_MPEG2;
if (m_iAudioStream >= 0 && m_iAudioStream < m_audioStreams.size())
{
newAudioStreamType = m_audioStreams[m_iAudioStream].audioType;
}
LogDebug("Old Audio %d, New Audio %d", m_AudioStreamType, newAudioStreamType);
//did it change?
if ((m_AudioStreamType == SERVICE_TYPE_AUDIO_UNKNOWN) || (m_AudioStreamType != newAudioStreamType))
{
m_AudioStreamType = newAudioStreamType;
//yes, is the audio pin connected?
if (m_filter.GetAudioPin()->IsConnected())
{
// here, stream is not parsed yet
if (!IsMediaChanging())
{
LogDebug("SetAudioStream : OnMediaTypeChanged(1)");
Flush() ;
m_filter.OnMediaTypeChanged(1);
SetMediaChanging(true);
m_filter.m_bForceSeekOnStop=true; // Force stream to be resumed after
}
else // Mpeg parser info is required or audio graph is already rebuilding.
LogDebug("SetAudioStream : Media already changing"); // just wait 1st GOP
}
}
else
{
m_filter.GetAudioPin()->SetDiscontinuity(true);
}
SetAudioChanging(false);
return S_OK;
}
bool CDeMultiplexer::GetAudioStream(__int32 &audioIndex)
{
audioIndex = m_iAudioStream;
return S_OK;
}
void CDeMultiplexer::GetAudioStreamInfo(int stream,char* szName)
{
if (stream < 0 || stream>=m_audioStreams.size())
{
szName[0] = szName[1] = szName[2] = 0;
return;
}
szName[0] = m_audioStreams[stream].language[0];
szName[1] = m_audioStreams[stream].language[1];
szName[2] = m_audioStreams[stream].language[2];
szName[3] = m_audioStreams[stream].language[3];
szName[4] = m_audioStreams[stream].language[4];
szName[5] = m_audioStreams[stream].language[5];
szName[6] = m_audioStreams[stream].language[6];
}
int CDeMultiplexer::GetAudioStreamCount()
{
return m_audioStreams.size();
}
void CDeMultiplexer::GetAudioStreamType(int stream,CMediaType& pmt)
{
if (m_iAudioStream< 0 || stream >= m_audioStreams.size())
{
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_MPEG2_AUDIO);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(MPEG2AudioFormat,sizeof(MPEG2AudioFormat));
return;
}
switch (m_audioStreams[stream].audioType)
{
// MPEG1 shouldn't be mapped to MPEG2 audio as it will break Cyberlink audio codec
// (and MPA is not working with the MPEG1 to MPEG2 mapping...)
case SERVICE_TYPE_AUDIO_MPEG1:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_MPEG1Payload);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(MPEG1AudioFormat,sizeof(MPEG1AudioFormat));
break;
case SERVICE_TYPE_AUDIO_MPEG2:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_MPEG2_AUDIO);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(MPEG2AudioFormat,sizeof(MPEG2AudioFormat));
break;
case SERVICE_TYPE_AUDIO_AAC:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_AAC);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(AACAudioFormat,sizeof(AACAudioFormat));
break;
case SERVICE_TYPE_AUDIO_LATM_AAC:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_LATM_AAC);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(AACAudioFormat,sizeof(AACAudioFormat));
break;
case SERVICE_TYPE_AUDIO_AC3:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_DOLBY_AC3);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(AC3AudioFormat,sizeof(AC3AudioFormat));
break;
case SERVICE_TYPE_AUDIO_DD_PLUS:
pmt.InitMediaType();
pmt.SetType (& MEDIATYPE_Audio);
pmt.SetSubtype (& MEDIASUBTYPE_DOLBY_DDPLUS);
pmt.SetSampleSize(1);
pmt.SetTemporalCompression(FALSE);
pmt.SetVariableSize();
pmt.SetFormatType(&FORMAT_WaveFormatEx);
pmt.SetFormat(AC3AudioFormat,sizeof(AC3AudioFormat));
break;
}
}
// This methods selects the subtitle stream specified
bool CDeMultiplexer::SetSubtitleStream(__int32 stream)
{
//is stream index valid?
if (stream < 0 || stream >= m_subtitleStreams.size())
return S_FALSE;
//set index
m_iSubtitleStream=stream;
return S_OK;
}
bool CDeMultiplexer::GetCurrentSubtitleStream(__int32 &stream)
{
stream = m_iSubtitleStream;
return S_OK;
}
bool CDeMultiplexer::GetSubtitleStreamLanguage(__int32 stream,char* szLanguage)
{
if (stream <0 || stream >= m_subtitleStreams.size())
{
szLanguage[0] = szLanguage[1] = szLanguage[2] = 0;
return S_FALSE;
}
szLanguage[0] = m_subtitleStreams[stream].language[0];
szLanguage[1] = m_subtitleStreams[stream].language[1];
szLanguage[2] = m_subtitleStreams[stream].language[2];
szLanguage[3] = m_subtitleStreams[stream].language[3];
return S_OK;
}
bool CDeMultiplexer::GetSubtitleStreamCount(__int32 &count)
{
count = m_subtitleStreams.size();
return S_OK;
}
bool CDeMultiplexer::SetSubtitleResetCallback(int(CALLBACK *cb)(int, void*, int*))
{
pSubUpdateCallback = cb;
return S_OK;
}
bool CDeMultiplexer::GetSubtitleStreamType(__int32 stream, __int32 &type)
{
if (m_iSubtitleStream< 0 || m_iSubtitleStream >= m_subtitleStreams.size())
{
// invalid stream number
return S_FALSE;
}
type = m_subtitleStreams[m_iSubtitleStream].subtitleType;
return S_OK;
}
void CDeMultiplexer::GetVideoStreamType(CMediaType &pmt)
{
if( m_pids.videoPids.size() != 0 && m_mpegPesParser != NULL)
{
pmt = m_mpegPesParser->pmt;
}
}
void CDeMultiplexer::FlushVideo()
{
LogDebug("demux:flush video");
CAutoLock lock (&m_sectionVideo);
delete m_pCurrentVideoBuffer;
m_pCurrentVideoBuffer = NULL;
ivecBuffers it = m_vecVideoBuffers.begin();
while (it != m_vecVideoBuffers.end())
{
CBuffer* videoBuffer = *it;
delete videoBuffer;
it = m_vecVideoBuffers.erase(it);
/*m_outVideoBuffer++;*/
}
// Clear PES temporary queue.
it = m_t_vecVideoBuffers.begin();
while (it != m_t_vecVideoBuffers.end())
{
CBuffer* VideoBuffer = *it;
delete VideoBuffer;
it = m_t_vecVideoBuffers.erase(it);
}
m_p.Free();
m_lastStart = 0;
m_pl.RemoveAll();
m_fHasAccessUnitDelimiters = false;
m_VideoPrevCC = -1;
m_bFirstGopFound = false;
m_bFrame0Found = false;
m_FirstVideoSample = 0x7FFFFFFF00000000LL;
m_LastVideoSample = 0;
m_lastVideoPTS.IsValid = false;
m_VideoValidPES = true;
m_mVideoValidPES = false;
m_WaitHeaderPES=-1 ;
m_bVideoAtEof=false;
m_MinVideoDelta = 10.0 ;
m_filter.m_bRenderingClockTooFast=false ;
Reset(); // PacketSync reset.
}
void CDeMultiplexer::FlushAudio()
{
LogDebug("demux:flush audio");
CAutoLock lock (&m_sectionAudio);
delete m_pCurrentAudioBuffer;
ivecBuffers it = m_vecAudioBuffers.begin();
while (it != m_vecAudioBuffers.end())
{
CBuffer* AudioBuffer = *it;
delete AudioBuffer;
it = m_vecAudioBuffers.erase(it);
}
// Clear PES temporary queue.
it = m_t_vecAudioBuffers.begin();
while (it != m_t_vecAudioBuffers.end())
{
CBuffer* AudioBuffer=*it;
delete AudioBuffer;
it=m_t_vecAudioBuffers.erase(it);
}
m_AudioPrevCC = -1;
m_FirstAudioSample = 0x7FFFFFFF00000000LL;
m_LastAudioSample = 0;
m_lastAudioPTS.IsValid = false;
m_AudioValidPES = false;
m_pCurrentAudioBuffer = new CBuffer();
m_bAudioAtEof = false;
m_MinAudioDelta = 10.0;
m_filter.m_bRenderingClockTooFast=false;
Reset(); // PacketSync reset.
}
void CDeMultiplexer::FlushSubtitle()
{
LogDebug("demux:flush subtitle");
CAutoLock lock (&m_sectionSubtitle);
delete m_pCurrentSubtitleBuffer;
ivecBuffers it = m_vecSubtitleBuffers.begin();
while (it != m_vecSubtitleBuffers.end())
{
CBuffer* subtitleBuffer = *it;
delete subtitleBuffer;
it = m_vecSubtitleBuffers.erase(it);
}
m_pCurrentSubtitleBuffer = new CBuffer();
}
/// Flushes all buffers
void CDeMultiplexer::Flush()
{
LogDebug("demux:flushing");
m_iAudioReadCount = 0;
m_LastDataFromRtsp = GetTickCount();
bool holdAudio = HoldAudio();
bool holdVideo = HoldVideo();
bool holdSubtitle = HoldSubtitle();
SetHoldAudio(true);
SetHoldVideo(true);
SetHoldSubtitle(true);
FlushAudio();
FlushVideo();
FlushSubtitle();
SetHoldAudio(holdAudio);
SetHoldVideo(holdVideo);
SetHoldSubtitle(holdSubtitle);
}
///
///Returns the next subtitle packet
// or NULL if there is none available
CBuffer* CDeMultiplexer::GetSubtitle()
{
//if there is no subtitle pid, then simply return NULL
if (m_currentSubtitlePid==0) return NULL;
if (m_bEndOfFile) return NULL;
if (m_bHoldSubtitle) return NULL;
//are there subtitle packets in the buffer?
if (m_vecSubtitleBuffers.size()!=0 )
{
//yup, then return the next one
CAutoLock lock (&m_sectionSubtitle);
ivecBuffers it =m_vecSubtitleBuffers.begin();
CBuffer* subtitleBuffer=*it;
m_vecSubtitleBuffers.erase(it);
return subtitleBuffer;
}
//no subtitle packets available
return NULL;
}
///
///Returns the next video packet
// or NULL if there is none available
CBuffer* CDeMultiplexer::GetVideo()
{
if (m_filter.GetVideoPin()->IsConnected() && ((m_iAudioStream == -1) || IsAudioChanging())) return NULL;
//if there is no video pid, then simply return NULL
if ((m_pids.videoPids.size() > 0 && m_pids.videoPids[0].Pid==0) || IsMediaChanging())
{
ReadFromFile(false,true);
return NULL;
}
// when there are no video packets at the moment
// then try to read some from the current file
while ((m_vecVideoBuffers.size()==0) || (m_FirstVideoSample.m_time >= m_LastAudioSample.m_time))
{
//if filter is stopped or
//end of file has been reached or
//demuxer should stop getting video packets
//then return NULL
if (!m_filter.IsFilterRunning()) return NULL;
if (m_filter.m_bStopping) return NULL;
if (m_bEndOfFile) return NULL;
// if (m_bHoldVideo) return NULL;
//else try to read some packets from the file
if (ReadFromFile(false,true)<READ_SIZE) break ;
}
//are there video packets in the buffer?
if (m_vecVideoBuffers.size()!=0 && !IsMediaChanging()) // && (m_FirstVideoSample.m_time < m_LastAudioSample.m_time))
{
CAutoLock lock (&m_sectionVideo);
//yup, then return the next one
ivecBuffers it =m_vecVideoBuffers.begin();
if (it!=m_vecVideoBuffers.end())
{
CBuffer* videoBuffer=*it;
m_vecVideoBuffers.erase(it);
return videoBuffer;
}
}
//no video packets available
return NULL;
}
///
///Returns the next audio packet
// or NULL if there is none available
CBuffer* CDeMultiplexer::GetAudio()
{
int SizeRead=READ_SIZE ;
if ((m_iAudioStream == -1) || IsAudioChanging()) return NULL;
// if there is no audio pid, then simply return NULL
if ((m_audioPid==0) || IsMediaChanging())
{
ReadFromFile(true,false);
return NULL;
}
// when there are no audio packets at the moment
// then try to read some from the current file
while (m_vecAudioBuffers.size()==0 || !m_bAudioVideoReady)
{
//if filter is stopped or
//end of file has been reached or
//demuxer should stop getting audio packets
//then return NULL
if (!m_filter.IsFilterRunning()) return NULL;
if (m_filter.m_bStopping) return NULL;
if (m_bEndOfFile) return NULL;
SizeRead = ReadFromFile(true,false) ;
//are there audio packets in the buffer?
if (m_vecAudioBuffers.size()==0 && SizeRead<READ_SIZE) return NULL; // No buffer and nothing to read....
if (IsMediaChanging()) return NULL;
// Goal is to start with at least 200mS audio and 400mS video ahead. ( LiveTv and RTSP as TsReader cannot go ahead by itself)
if (m_LastAudioSample.Millisecs() - m_FirstAudioSample.Millisecs() < 200) return NULL ; // Not enough audio to start.
if (!m_bAudioVideoReady && m_filter.GetVideoPin()->IsConnected())
{
if (!m_bFrame0Found) return NULL ;
if (m_LastVideoSample.Millisecs() - m_FirstAudioSample.Millisecs() < 400) return NULL ; // Not enough video & audio to start.
if (!m_filter.GetAudioPin()->m_EnableSlowMotionOnZapping || !m_filter.m_bLiveTv)
{
if (m_LastVideoSample.Millisecs() - m_FirstVideoSample.Millisecs() < 400) return NULL ; // Not enough video to start.
if (m_LastAudioSample.Millisecs() - m_FirstVideoSample.Millisecs() < 200) return NULL ; // Not enough simultaneous audio & video to start.
}
}
m_bAudioVideoReady=true ;
}
//yup, then return the next one
CAutoLock lock (&m_sectionAudio);
ivecBuffers it =m_vecAudioBuffers.begin();
CBuffer* audiobuffer=*it;
m_vecAudioBuffers.erase(it);
return audiobuffer;
}
/// Starts the demuxer
/// This method will read the file until we found the pat/sdt
/// with all the audio/video pids
void CDeMultiplexer::Start()
{
//reset some values
m_bStarting=true ;
m_receivedPackets=0;
m_mpegParserTriggerFormatChange=false;
m_bEndOfFile=false;
m_bHoldAudio=false;
m_bHoldVideo=false;
m_iPatVersion=-1;
m_ReqPatVersion=-1;
m_bSetAudioDiscontinuity=false;
m_bSetVideoDiscontinuity=false;
DWORD dwBytesProcessed=0;
DWORD m_Time = GetTickCount();
while((GetTickCount() - m_Time) < 5000)
{
int BytesRead =ReadFromFile(false,false);
if (BytesRead==0) Sleep(10);
if (dwBytesProcessed>INITIAL_READ_SIZE || GetAudioStreamCount()>0)
{
#ifdef USE_DYNAMIC_PINS
if ((!m_mpegPesParser->basicVideoInfo.isValid && m_pids.videoPids.size() > 0 &&
m_pids.videoPids[0].Pid>1) && dwBytesProcessed<INITIAL_READ_SIZE)
{
dwBytesProcessed+=BytesRead;
continue;
}
#endif
m_reader->SetFilePointer(0,FILE_BEGIN);
Flush();
m_streamPcr.Reset();
m_bStarting=false;
return;
}
dwBytesProcessed+=BytesRead;
}
m_streamPcr.Reset();
m_iAudioReadCount=0;
m_bStarting=false;
}
void CDeMultiplexer::SetEndOfFile(bool bEndOfFile)
{
m_bEndOfFile=bEndOfFile;
}
/// Returns true if we reached the end of the file
bool CDeMultiplexer::EndOfFile()
{
return m_bEndOfFile;
}
/// This method reads the next READ_SIZE bytes from the file
/// and processes the raw data
/// When a TS packet has been discovered, OnTsPacket(byte* tsPacket) gets called
// which in its turn deals with the packet
int CDeMultiplexer::ReadFromFile(bool isAudio, bool isVideo)
{
// if (m_bWeos) return 0 ;
// if (IsAudioChanging()) return 0 ; // Do not read any data during stream selection from MP C#
if (m_filter.IsSeeking()) return 0; // Ambass : to check
CAutoLock lock (&m_sectionRead);
if (m_reader==NULL) return false;
byte buffer[READ_SIZE];
int dwReadBytes=0;
bool result=false;
//if we are playing a RTSP stream
if (m_reader->IsBuffer())
{
// and, the current buffer holds data
int nBytesToRead = m_reader->HasData();
if (nBytesToRead > sizeof(buffer))
{
nBytesToRead=sizeof(buffer);
}
else
{
m_bAudioAtEof = true ;
m_bVideoAtEof = true ;
}
if (nBytesToRead)
{
//then read raw data from the buffer
m_reader->Read(buffer, nBytesToRead, (DWORD*)&dwReadBytes);
if (dwReadBytes > 0)
{
//yes, then process the raw data
result=true;
OnRawData(buffer,(int)dwReadBytes);
m_LastDataFromRtsp = GetTickCount();
}
}
else
{
if (!m_filter.IsTimeShifting())
{
//LogDebug("demux:endoffile...%d",GetTickCount()-m_LastDataFromRtsp );
//set EOF flag and return
if (GetTickCount()-m_LastDataFromRtsp > 2000 && m_filter.State() != State_Paused ) // A bit crappy, but no better idea...
{
LogDebug("demux:endoffile");
m_bEndOfFile=true;
return 0;
}
}
}
return dwReadBytes;
}
else
{
//playing a local file.
//read raw data from the file
if (SUCCEEDED(m_reader->Read(buffer,sizeof(buffer), (DWORD*)&dwReadBytes)))
{
if ((m_filter.IsTimeShifting()) && (dwReadBytes < sizeof(buffer)))
{
m_bAudioAtEof = true;
m_bVideoAtEof = true;
}
if (dwReadBytes > 0)
{
//succeeded, process data
OnRawData(buffer,(int)dwReadBytes);
}
else
{
if (!m_filter.IsTimeShifting())
{
//set EOF flag and return
LogDebug("demux:endoffile");
m_bEndOfFile=true;
return 0;
}
}
//and return
return dwReadBytes;
}
else
{
int x=123;
LogDebug("Read failed...");
}
}
//Failed to read any data
// if ( (isAudio && m_bHoldAudio) || (isVideo && m_bHoldVideo) )
// {
//LogDebug("demux:paused %d %d",m_bHoldAudio,m_bHoldVideo);
// return 0;
// }
return 0;
}
/// This method gets called via ReadFile() when a new TS packet has been received
/// if will :
/// - decode any new pat/pmt/sdt
/// - decode any audio/video packets and put the PES packets in the appropiate buffers
void CDeMultiplexer::OnTsPacket(byte* tsPacket)
{
CTsHeader header(tsPacket);
m_patParser.OnTsPacket(tsPacket);
if (m_iPatVersion==-1)
{
// First Pat not found
return;
}
// Wait for new PAT if required.
if ((m_iPatVersion & 0x0F) != (m_ReqPatVersion & 0x0F))
{
if (m_ReqPatVersion==-1)
{ // Now, unless channel change,
m_ReqPatVersion = m_iPatVersion; // Initialize Pat Request.
m_WaitNewPatTmo = GetTickCount(); // Now, unless channel change request,timeout will be always true.
}
if (GetTickCount() < m_WaitNewPatTmo)
{
// Timeout not reached.
return;
}
}
//if we have no PCR pid (yet) then there's nothing to decode, so return
if (m_pids.PcrPid==0) return;
if (header.Pid==0) return;
// 'TScrambling' check commented out - headers are never scrambled,
// so it's safe to detect scrambled payload at PES level (in FillVideo()/FillAudio())
//if (header.TScrambling) return;
//skip any packets with errors in it
if (header.TransportError) return;
if( m_pids.TeletextPid > 0 && m_pids.TeletextPid != m_currentTeletextPid )
{
IDVBSubtitle* pDVBSubtitleFilter(m_filter.GetSubtitleFilter());
if( pTeletextServiceInfoCallback )
{
std::vector<TeletextServiceInfo>::iterator vit = m_pids.TeletextInfo.begin();
while(vit != m_pids.TeletextInfo.end())
{
TeletextServiceInfo& info = *vit;
LogDebug("Calling Teletext Service info callback");
(*pTeletextServiceInfoCallback)(info.page, info.type, (byte)info.lang[0],(byte)info.lang[1],(byte)info.lang[2]);
vit++;
}
m_currentTeletextPid = m_pids.TeletextPid;
}
}
//is this the PCR pid ?
if (header.Pid==m_pids.PcrPid)
{
//yep, does it have a PCR timestamp?
CAdaptionField field;
field.Decode(header,tsPacket);
if (field.Pcr.IsValid)
{
//then update our stream pcr which holds the current playback timestamp
m_streamPcr=field.Pcr;
}
}
//as long as we dont have a stream pcr timestamp we return
if (m_streamPcr.IsValid==false)
{
return;
}
//process the ts packet further
FillSubtitle(header,tsPacket);
FillAudio(header,tsPacket);
FillVideo(header,tsPacket);
FillTeletext(header,tsPacket);
}
/// Validate TS packet discontinuity
bool CDeMultiplexer::CheckContinuity(int prevCC, CTsHeader& header)
{
if ((prevCC !=-1 ) && (prevCC != ((header.ContinuityCounter - 1) & 0x0F)))
{
return false;
}
return true;
}
/// This method will check if the tspacket is an audio packet
/// ifso, it decodes the PES audio packet and stores it in the audio buffers
void CDeMultiplexer::FillAudio(CTsHeader& header, byte* tsPacket)
{
//LogDebug("FillAudio - audio PID %d", m_audioPid );
if (IsAudioChanging() || m_iAudioStream<0 || m_iAudioStream>=m_audioStreams.size()) return;
m_audioPid=m_audioStreams[m_iAudioStream].pid;
if (m_audioPid==0 || m_audioPid != header.Pid) return;
if (m_filter.GetAudioPin()->IsConnected()==false) return;
if (header.AdaptionFieldOnly())return;
if(!CheckContinuity(m_AudioPrevCC, header))
{
LogDebug("Audio Continuity error... %x ( prev %x )", header.ContinuityCounter, m_AudioPrevCC);
if (!m_DisableDiscontinuitiesFiltering) m_AudioValidPES=false;
}
m_AudioPrevCC = header.ContinuityCounter;
CAutoLock lock (&m_sectionAudio);
//does tspacket contain the start of a pes packet?
if (header.PayloadUnitStart)
{
//yes packet contains start of a pes packet.
//does current buffer hold any data ?
if (m_pCurrentAudioBuffer->Length() > 0)
{
m_t_vecAudioBuffers.push_back(m_pCurrentAudioBuffer);
m_pCurrentAudioBuffer = new CBuffer();
}
if (m_t_vecAudioBuffers.size())
{
CBuffer *Cbuf=*m_t_vecAudioBuffers.begin();
byte *p = Cbuf->Data() ;
if ((p[0]==0) && (p[1]==0) && (p[2]==1) //Valid start code
&& ((p[3] & 0x80)!=0) //Valid stream ID
&& ((p[6] & 0xC0)==0x80) //Valid marker bits
&& ((p[6] & 0x20)!=0x20)) //Payload not scrambled
{
//get pts/dts from pes header
CPcr pts;
CPcr dts;
if (CPcr::DecodeFromPesHeader(p,0,pts,dts))
{
double diff;
if (!m_lastAudioPTS.IsValid)
m_lastAudioPTS=pts;
if (m_lastAudioPTS>pts)
diff=m_lastAudioPTS.ToClock()-pts.ToClock();
else
diff=pts.ToClock()-m_lastAudioPTS.ToClock();
if (diff>10.0)
{
LogDebug("DeMultiplexer::FillAudio pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastAudioPTS.ToClock());
m_AudioValidPES=false;
}
else
{
m_lastAudioPTS=pts;
}
Cbuf->SetPts(pts);
REFERENCE_TIME MediaTime;
m_filter.GetMediaPosition(&MediaTime);
if (m_filter.m_bStreamCompensated && m_bAudioAtEof && !m_filter.m_bRenderingClockTooFast)
{
float Delta = pts.ToClock()-(float)((double)(m_filter.Compensation.m_time+MediaTime)/10000000.0) ;
if (Delta < m_MinAudioDelta)
{
m_MinAudioDelta=Delta;
LogDebug("Demux : Audio to render %03.3f Sec", Delta);
if (Delta < 0.1)
{
LogDebug("Demux : Audio to render too late= %03.3f Sec, rendering will be paused for a while", Delta) ;
m_filter.m_bRenderingClockTooFast=true;
m_MinAudioDelta+=1.0;
m_MinVideoDelta+=1.0;
}
}
}
}
//skip pes header
int headerLen=9+p[8] ;
int len = Cbuf->Length()-headerLen;
if (len > 0)
{
byte *ps = p+headerLen;
Cbuf->SetLength(len);
while(len--) *p++ = *ps++; // memcpy could be not safe.
}
else
{
LogDebug(" No data");
m_AudioValidPES=false;
}
}
else
{
LogDebug("Pes header 0-0-1 fail");
m_AudioValidPES=false;
}
if (m_AudioValidPES)
{
if (m_bSetAudioDiscontinuity)
{
m_bSetAudioDiscontinuity=false;
Cbuf->SetDiscontinuity();
}
Cbuf->SetPcr(m_duration.FirstStartPcr(),m_duration.MaxPcr());
//yes, then move the full PES in main queue.
while (m_t_vecAudioBuffers.size())
{
ivecBuffers it;
// Check if queue is no abnormally long..
if (m_vecAudioBuffers.size()>MAX_BUF_SIZE)
{
ivecBuffers it = m_vecAudioBuffers.begin();
delete *it;
m_vecAudioBuffers.erase(it);
}
it = m_t_vecAudioBuffers.begin();
CRefTime Ref;
if((*it)->MediaTime(Ref))
{
if (Ref < m_FirstAudioSample) m_FirstAudioSample = Ref;
if (Ref > m_LastAudioSample) m_LastAudioSample = Ref;
}
m_vecAudioBuffers.push_back(*it);
m_t_vecAudioBuffers.erase(it);
}
}
else
{
while (m_t_vecAudioBuffers.size())
{
ivecBuffers it;
it = m_t_vecAudioBuffers.begin();
delete *it;
m_t_vecAudioBuffers.erase(it);
}
m_bSetAudioDiscontinuity = true;
}
}
m_AudioValidPES = true;
m_bAudioAtEof = false;
}
if (m_AudioValidPES)
{
int pos=header.PayLoadStart;
//packet contains rest of a pes packet
//does the entire data in this tspacket fit in the current buffer ?
if (m_pCurrentAudioBuffer->Length()+(188-pos)>=0x2000)
{
//no, then determine how many bytes do fit
int copyLen=0x2000-m_pCurrentAudioBuffer->Length();
//copy those bytes
m_pCurrentAudioBuffer->Add(&tsPacket[pos],copyLen);
pos+=copyLen;
m_t_vecAudioBuffers.push_back(m_pCurrentAudioBuffer);
//and create a new one
m_pCurrentAudioBuffer = new CBuffer();
}
//copy (rest) data in current buffer
if (pos>0 && pos < 188)
{
m_pCurrentAudioBuffer->Add(&tsPacket[pos],188-pos);
}
}
}
/// This method will check if the tspacket is an video packet
void CDeMultiplexer::FillVideo(CTsHeader& header, byte* tsPacket)
{
if (m_pids.videoPids.size() == 0 || m_pids.videoPids[0].Pid==0) return;
if (header.Pid!=m_pids.videoPids[0].Pid) return;
if (header.AdaptionFieldOnly()) return;
if (!CheckContinuity(m_VideoPrevCC, header))
{
LogDebug("Video Continuity error... %x ( prev %x )", header.ContinuityCounter, m_VideoPrevCC);
if (!m_DisableDiscontinuitiesFiltering) m_VideoValidPES = false;
}
m_VideoPrevCC = header.ContinuityCounter;
CAutoLock lock (&m_sectionVideo);
if (m_bShuttingDown) return;
if (m_pids.videoPids[0].VideoServiceType == SERVICE_TYPE_VIDEO_MPEG1 ||
m_pids.videoPids[0].VideoServiceType == SERVICE_TYPE_VIDEO_MPEG2)
{
FillVideoMPEG2(header, tsPacket);
}
else
{
//ParseVideoH264(header, tsPacket);
FillVideoH264(header, tsPacket);
}
}
void CDeMultiplexer::FillVideoH264(CTsHeader& header, byte* tsPacket)
{
int headerlen = header.PayLoadStart;
if(!m_p)
{
m_p.Attach(new Packet());
m_p->bDiscontinuity = false ;
m_p->rtStart = Packet::INVALID_TIME;
m_lastStart = 0;
}
if (header.PayloadUnitStart)
{
m_WaitHeaderPES = m_p->GetCount();
m_mVideoValidPES = m_VideoValidPES;
// LogDebug("DeMultiplexer::FillVideo PayLoad Unit Start");
}
CAutoPtr<Packet> p(new Packet());
if (headerlen < 188)
{
int dataLen = 188-headerlen;
p->SetCount(dataLen);
p->SetData(&tsPacket[headerlen],dataLen);
m_p->Append(*p);
}
else
return;
if (m_WaitHeaderPES >= 0)
{
int AvailablePESlength = m_p->GetCount()-m_WaitHeaderPES ;
BYTE* start = m_p->GetData() + m_WaitHeaderPES;
if (AvailablePESlength < 9)
{
LogDebug("demux:vid Incomplete PES ( Avail %d )", AvailablePESlength);
return;
}
if ((start[0]!=0) || (start[1]!=0) || (start[2]!=1) //Invalid start code
|| ((start[3] & 0x80)==0)) //Invalid stream ID
{
LogDebug("Pes 0-0-1 fail");
m_VideoValidPES=false;
m_p->rtStart = Packet::INVALID_TIME;
m_WaitHeaderPES = -1;
}
else
{
if (AvailablePESlength < 9+start[8])
{
LogDebug("demux:vid Incomplete PES ( Avail %d/%d )", AvailablePESlength, AvailablePESlength+9+start[8]) ;
return ;
}
else
{ // full PES header is available.
if ((start[6] & 0xC0)!=0x80 //Invalid marker bits
|| (start[6] & 0x20)==0x20) //Payload scrambled
{
return;
}
CPcr pts;
CPcr dts;
m_VideoValidPES=true ;
if (CPcr::DecodeFromPesHeader(start,0,pts,dts))
{
double diff;
if (!m_lastVideoPTS.IsValid)
m_lastVideoPTS=pts;
if (m_lastVideoPTS>pts)
diff=m_lastVideoPTS.ToClock()-pts.ToClock();
else
diff=pts.ToClock()-m_lastVideoPTS.ToClock();
if (diff>10.0)
{
LogDebug("DeMultiplexer::FillVideo pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastVideoPTS.ToClock());
m_VideoValidPES=false;
}
else
{
// LogDebug("DeMultiplexer::FillVideo pts : %f ", (float)pts.ToClock());
m_lastVideoPTS=pts;
}
}
m_lastStart -= 9+start[8];
m_p->RemoveAt(m_WaitHeaderPES, 9+start[8]);
m_p->rtStart = pts.IsValid ? (pts.PcrReferenceBase) : Packet::INVALID_TIME;
m_WaitHeaderPES = -1;
}
}
}
if (m_p->GetCount())
{
BYTE* start = m_p->GetData();
BYTE* end = start + m_p->GetCount();
while(start <= end-4 && *(DWORD*)start != 0x01000000) start++;
while(start <= end-4)
{
BYTE* next = start+1;
if (next < m_p->GetData() + m_lastStart)
{
next = m_p->GetData() + m_lastStart;
}
while(next <= end-4 && *(DWORD*)next != 0x01000000) next++;
if(next >= end-4)
{
m_lastStart = next - m_p->GetData();
break;
}
int size = next - start;
CH264Nalu Nalu;
Nalu.SetBuffer(start, size, 0);
CAutoPtr<Packet> p2;
while (Nalu.ReadNext())
{
DWORD dwNalLength =
((Nalu.GetDataLength() >> 24) & 0x000000ff) |
((Nalu.GetDataLength() >> 8) & 0x0000ff00) |
((Nalu.GetDataLength() << 8) & 0x00ff0000) |
((Nalu.GetDataLength() << 24) & 0xff000000);
CAutoPtr<Packet> p3(new Packet());
p3->SetCount (Nalu.GetDataLength()+sizeof(dwNalLength));
memcpy (p3->GetData(), &dwNalLength, sizeof(dwNalLength));
memcpy (p3->GetData()+sizeof(dwNalLength), Nalu.GetDataBuffer(), Nalu.GetDataLength());
if (p2 == NULL)
p2 = p3;
else
p2->Append(*p3);
}
if((*(p2->GetData()+4)&0x1f) == 0x09) m_fHasAccessUnitDelimiters = true;
if((*(p2->GetData()+4)&0x1f) == 0x09 || !m_fHasAccessUnitDelimiters && m_p->rtStart != Packet::INVALID_TIME)
{
if ((m_pl.GetCount()>0) && m_mVideoValidPES)
{
CAutoPtr<Packet> p(new Packet());
p = m_pl.RemoveHead();
// LogDebug("Output NALU Type: %d (%d)", p->GetAt(4)&0x1f,p->GetCount());
//CH246IFrameScanner iFrameScanner;
//iFrameScanner.ProcessNALU(p);
while(m_pl.GetCount())
{
CAutoPtr<Packet> p2 = m_pl.RemoveHead();
//if (!iFrameScanner.SeenEnough())
// iFrameScanner.ProcessNALU(p2);
// LogDebug("Output NALU Type: %d (%d)", p2->GetAt(4)&0x1f,p2->GetCount());
p->Append(*p2);
}
CPcr timestamp;
if(p->rtStart != Packet::INVALID_TIME )
{
timestamp.PcrReferenceBase = p->rtStart;
timestamp.IsValid=true;
}
// LogDebug("frame len %d decoded PTS %f p timestamp %f", p->GetCount(), pts.ToClock(), timestamp.ToClock());
int lastVidResX=m_mpegPesParser->basicVideoInfo.width;
int lastVidResY=m_mpegPesParser->basicVideoInfo.height;
bool Gop = m_mpegPesParser->OnTsPacket(p->GetData(), p->GetCount(), false);
if ((Gop || m_bFirstGopFound) && m_filter.GetVideoPin()->IsConnected())
{
CRefTime Ref;
CBuffer *pCurrentVideoBuffer = new CBuffer(p->GetCount());
pCurrentVideoBuffer->Add(p->GetData(), p->GetCount());
pCurrentVideoBuffer->SetPts(timestamp);
pCurrentVideoBuffer->SetPcr(m_duration.FirstStartPcr(),m_duration.MaxPcr());
pCurrentVideoBuffer->MediaTime(Ref);
// Must use p->rtStart as CPcr is UINT64 and INVALID_TIME is LONGLONG
// Too risky to change CPcr implementation at this time
if(p->rtStart != Packet::INVALID_TIME)
{
if (Gop && !m_bFirstGopFound)
{
m_bFirstGopFound=true;
LogDebug(" H.264 I-FRAME found %f ", Ref.Millisecs()/1000.0f);
m_LastValidFrameCount=0;
}
if (Ref < m_FirstVideoSample) m_FirstVideoSample = Ref;
if (Ref > m_LastVideoSample) m_LastVideoSample = Ref;
if (m_bFirstGopFound && !m_bFrame0Found && m_LastValidFrameCount>=5 /*(frame_count==0)*/)
{
LogDebug(" H.264 First supposed '0' frame found. %f ", m_FirstVideoSample.Millisecs()/1000.0f);
m_bFrame0Found = true;
}
m_LastValidFrameCount++;
}
pCurrentVideoBuffer->SetFrameType(Gop? 'I':'?');
pCurrentVideoBuffer->SetFrameCount(0);
pCurrentVideoBuffer->SetVideoServiceType(m_pids.videoPids[0].VideoServiceType);
if (m_bSetVideoDiscontinuity)
{
m_bSetVideoDiscontinuity=false;
pCurrentVideoBuffer->SetDiscontinuity();
}
REFERENCE_TIME MediaTime;
m_filter.GetMediaPosition(&MediaTime);
if (m_filter.m_bStreamCompensated && m_bVideoAtEof && !m_filter.m_bRenderingClockTooFast)
{
float Delta = (float)((double)Ref.Millisecs()/1000.0)-(float)((double)(m_filter.Compensation.m_time+MediaTime)/10000000.0) ;
if (Delta < m_MinVideoDelta)
{
m_MinVideoDelta=Delta;
LogDebug("Demux : Video to render %03.3f Sec", Delta);
if (Delta < 0.2)
{
LogDebug("Demux : Video to render too late = %03.3f Sec, rendering will be paused for a while", Delta) ;
m_filter.m_bRenderingClockTooFast=true;
m_MinAudioDelta+=1.0;
m_MinVideoDelta+=1.0;
}
}
}
m_bVideoAtEof = false;
// ownership is transfered to vector
m_vecVideoBuffers.push_back(pCurrentVideoBuffer);
}
if (lastVidResX!=m_mpegPesParser->basicVideoInfo.width || lastVidResY!=m_mpegPesParser->basicVideoInfo.height)
{
LogDebug("DeMultiplexer: %x video format changed: res=%dx%d aspectRatio=%d:%d fps=%d isInterlaced=%d",header.Pid,m_mpegPesParser->basicVideoInfo.width,m_mpegPesParser->basicVideoInfo.height,m_mpegPesParser->basicVideoInfo.arx,m_mpegPesParser->basicVideoInfo.ary,m_mpegPesParser->basicVideoInfo.fps,m_mpegPesParser->basicVideoInfo.isInterlaced);
if (m_mpegParserTriggerFormatChange)
{
LogDebug("DeMultiplexer: OnMediaFormatChange triggered by mpeg2Parser");
SetMediaChanging(true);
m_filter.OnMediaTypeChanged(3);
m_mpegParserTriggerFormatChange=false;
}
LogDebug("DeMultiplexer: triggering OnVideoFormatChanged");
m_filter.OnVideoFormatChanged(m_mpegPesParser->basicVideoInfo.streamType,m_mpegPesParser->basicVideoInfo.width,m_mpegPesParser->basicVideoInfo.height,m_mpegPesParser->basicVideoInfo.arx,m_mpegPesParser->basicVideoInfo.ary,15000000,m_mpegPesParser->basicVideoInfo.isInterlaced);
}
else
{
if (m_mpegParserTriggerFormatChange && Gop)
{
LogDebug("DeMultiplexer: Got GOP after the channel change was detected without correct mpeg header parsing, so we trigger the format change now.");
m_filter.OnMediaTypeChanged(3);
m_mpegParserTriggerFormatChange=false;
}
}
}
else
m_bSetVideoDiscontinuity = !m_mVideoValidPES;
m_pl.RemoveAll();
p2->bDiscontinuity = m_p->bDiscontinuity; m_p->bDiscontinuity = FALSE;
p2->rtStart = m_p->rtStart; m_p->rtStart = Packet::INVALID_TIME;
}
else
{
p2->bDiscontinuity = FALSE;
p2->rtStart = Packet::INVALID_TIME;
}
// LogDebug(".......> Store NALU length = %d (%d)", (*(p2->GetData()+4) & 0x1F), p2->GetCount()) ;
m_pl.AddTail(p2);
start = next;
m_lastStart = start - m_p->GetData() + 1;
}
if(start > m_p->GetData())
{
m_lastStart -= (start - m_p->GetData());
m_p->RemoveAt(0, start - m_p->GetData());
}
}
return;
}
void CDeMultiplexer::FillVideoMPEG2(CTsHeader& header, byte* tsPacket)
{
static const double frame_rate[16]={1.0/25.0, 1001.0/24000.0, 1.0/24.0, 1.0/25.0,
1001.0/30000.0, 1.0/30.0, 1.0/50.0, 1001.0/60000.0,
1.0/60.0, 1.0/25.0, 1.0/25.0, 1.0/25.0,
1.0/25.0, 1.0/25.0, 1.0/25.0, 1.0/25.0 };
static const char tc[]="XIPBXXXX";
int headerlen = header.PayLoadStart;
if(!m_p)
{
m_p.Attach(new Packet());
m_p->bDiscontinuity = false;
m_p->rtStart = Packet::INVALID_TIME;
m_lastStart = 0;
m_bInBlock=false;
}
if (header.PayloadUnitStart)
{
m_WaitHeaderPES = m_p->GetCount();
m_mVideoValidPES = m_VideoValidPES;
// LogDebug("DeMultiplexer::FillVideo PayLoad Unit Start");
}
CAutoPtr<Packet> p(new Packet());
if (headerlen < 188)
{
int dataLen = 188-headerlen;
p->SetCount(dataLen);
p->SetData(&tsPacket[headerlen],dataLen);
m_p->Append(*p);
}
else
return;
if (m_WaitHeaderPES >= 0)
{
int AvailablePESlength = m_p->GetCount()-m_WaitHeaderPES;
BYTE* start = m_p->GetData() + m_WaitHeaderPES;
if (AvailablePESlength < 9)
{
LogDebug("demux:vid Incomplete PES ( Avail %d )", AvailablePESlength);
return;
}
if ((start[0]!=0) || (start[1]!=0) || (start[2]!=1) //Invalid start code
|| ((start[3] & 0x80)==0)) //Invalid stream ID
{
LogDebug("Pes 0-0-1 fail");
m_VideoValidPES=false;
m_p->rtStart = Packet::INVALID_TIME;
m_WaitHeaderPES = -1;
}
else
{
if (AvailablePESlength < 9+start[8])
{
LogDebug("demux:vid Incomplete PES ( Avail %d/%d )", AvailablePESlength, AvailablePESlength+9+start[8]) ;
return;
}
else
{ // full PES header is available.
if ((start[6] & 0xC0)!=0x80 //Invalid marker bits
|| (start[6] & 0x20)==0x20) //Payload scrambled
{
return;
}
CPcr pts;
CPcr dts;
// m_VideoValidPES=true ;
if (CPcr::DecodeFromPesHeader(start,0,pts,dts))
{
double diff;
if (!m_lastVideoPTS.IsValid)
m_lastVideoPTS=pts;
if (m_lastVideoPTS>pts)
diff=m_lastVideoPTS.ToClock()-pts.ToClock();
else
diff=pts.ToClock()-m_lastVideoPTS.ToClock();
if (diff>10.0)
{
LogDebug("DeMultiplexer::FillVideo pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastVideoPTS.ToClock());
m_VideoValidPES=false;
}
else
{
// LogDebug("DeMultiplexer::FillVideo pts : %f ", (float)pts.ToClock());
m_lastVideoPTS=pts;
}
m_VideoPts = pts;
}
m_lastStart -= 9+start[8];
m_p->RemoveAt(m_WaitHeaderPES, 9+start[8]);
m_WaitHeaderPES = -1;
}
}
}
if (m_p->GetCount())
{
BYTE* start = m_p->GetData();
BYTE* end = start + m_p->GetCount();
// 000001B3 sequence_header_code
// 00000100 picture_start_code
while(start <= end-4)
{
if (((*(DWORD*)start & 0xFFFFFFFF) == 0xb3010000) || ((*(DWORD*)start & 0xFFFFFFFF) == 0x00010000))
{
if(!m_bInBlock)
{
if (m_VideoPts.IsValid) m_CurrentVideoPts=m_VideoPts;
m_VideoPts.IsValid=false;
m_bInBlock=true;
}
break;
}
start++;
}
if(start <= end-4)
{
BYTE* next = start+1;
if (next < m_p->GetData() + m_lastStart)
{
next = m_p->GetData() + m_lastStart;
}
while(next <= end-4 && ((*(DWORD*)next & 0xFFFFFFFF) != 0xb3010000) && ((*(DWORD*)next & 0xFFFFFFFF) != 0x00010000)) next++;
if(next >= end-4)
{
m_lastStart = next - m_p->GetData();
}
else
{
m_bInBlock=false ;
int size = next - start;
CAutoPtr<Packet> p2(new Packet());
p2->SetCount(size);
memcpy (p2->GetData(), m_p->GetData(), size);
if (*(DWORD*)p2->GetData() == 0x00010000) // picture_start_code ?
{
BYTE *p = p2->GetData() ;
char frame_type = tc[((p[5]>>3)&7)]; // Extract frame type (IBP). Just info.
int frame_count = (p[5]>>6)+(p[4]<<2); // Extract temporal frame count to rebuild timestamp ( if required )
// TODO: try to drop non I-Frames when > 2.0x playback speed
//if (frame_type != 'I')
//double rate = 0.0;
//m_filter.GetVideoPin()->GetRate(&rate);
m_pl.AddTail(p2);
// LogDebug("DeMultiplexer::FillVideo Frame length : %d %x %x", size, *(DWORD*)start, *(DWORD*)next);
if (m_VideoValidPES)
{
CAutoPtr<Packet> p(new Packet());
p = m_pl.RemoveHead();
// LogDebug("Output Type: %x %d", *(DWORD*)p->GetData(),p->GetCount());
while(m_pl.GetCount())
{
CAutoPtr<Packet> p2 = m_pl.RemoveHead();
// LogDebug("Output Type: %x %d", *(DWORD*)p2->GetData(),p2->GetCount());
p->Append(*p2);
}
// LogDebug("frame len %d decoded PTS %f (framerate %f), %c(%d)", p->GetCount(), m_CurrentVideoPts.IsValid ? (float)m_CurrentVideoPts.ToClock() : 0.0f,(float)m_curFrameRate,frame_type,frame_count);
int lastVidResX=m_mpegPesParser->basicVideoInfo.width;
int lastVidResY=m_mpegPesParser->basicVideoInfo.height;
bool Gop = m_mpegPesParser->OnTsPacket(p->GetData(), p->GetCount(), true);
if (Gop) m_LastValidFrameCount=-1;
if ((Gop || m_bFirstGopFound) && m_filter.GetVideoPin()->IsConnected())
{
CRefTime Ref;
CBuffer *pCurrentVideoBuffer = new CBuffer(p->GetCount());
pCurrentVideoBuffer->Add(p->GetData(), p->GetCount());
if (m_CurrentVideoPts.IsValid)
{ // Timestamp Ok.
m_LastValidFrameCount=frame_count;
m_LastValidFramePts=m_CurrentVideoPts;
}
else
{
if (m_LastValidFrameCount>=0) // No timestamp, but we've latest GOP timestamp.
{
double d = m_LastValidFramePts.ToClock() + (frame_count-m_LastValidFrameCount) * m_curFrameRate ;
m_CurrentVideoPts.FromClock(d); // Rebuild it from 1st frame in GOP timestamp.
m_CurrentVideoPts.IsValid=true;
}
}
pCurrentVideoBuffer->SetPts(m_CurrentVideoPts);
pCurrentVideoBuffer->SetPcr(m_duration.FirstStartPcr(),m_duration.MaxPcr());
pCurrentVideoBuffer->MediaTime(Ref);
if(m_CurrentVideoPts.IsValid)
{
if (Gop && !m_bFirstGopFound)
{
m_bFirstGopFound=true ;
LogDebug(" MPEG I-FRAME found %f ", Ref.Millisecs()/1000.0f);
}
if (m_bFirstGopFound && !m_bFrame0Found && (frame_count==0))
{
LogDebug(" MPEG First '0' frame found. %f ", Ref.Millisecs()/1000.0f);
m_bFrame0Found = true;
}
if (Ref < m_FirstVideoSample) m_FirstVideoSample = Ref;
if (Ref > m_LastVideoSample) m_LastVideoSample = Ref;
}
pCurrentVideoBuffer->SetFrameType(frame_type);
pCurrentVideoBuffer->SetFrameCount(frame_count);
pCurrentVideoBuffer->SetVideoServiceType(m_pids.videoPids[0].VideoServiceType);
if (m_bSetVideoDiscontinuity)
{
m_bSetVideoDiscontinuity=false;
pCurrentVideoBuffer->SetDiscontinuity();
}
REFERENCE_TIME MediaTime;
m_filter.GetMediaPosition(&MediaTime);
if (m_filter.m_bStreamCompensated && m_bVideoAtEof && !m_filter.m_bRenderingClockTooFast)
{
float Delta = (float)((double)Ref.Millisecs()/1000.0)-(float)((double)(m_filter.Compensation.m_time+MediaTime)/10000000.0) ;
if (Delta < m_MinVideoDelta)
{
m_MinVideoDelta=Delta;
LogDebug("Demux : Video to render %03.3f Sec", Delta);
if (Delta < 0.2)
{
LogDebug("Demux : Video to render too late = %03.3f Sec, rendering will be paused for a while", Delta) ;
m_filter.m_bRenderingClockTooFast=true ;
m_MinAudioDelta+=1.0 ;
m_MinVideoDelta+=1.0 ;
}
}
}
m_bVideoAtEof = false ;
// ownership is transfered to vector
m_vecVideoBuffers.push_back(pCurrentVideoBuffer);
}
m_CurrentVideoPts.IsValid=false ;
if (lastVidResX!=m_mpegPesParser->basicVideoInfo.width || lastVidResY!=m_mpegPesParser->basicVideoInfo.height)
{
LogDebug("DeMultiplexer: %x video format changed: res=%dx%d aspectRatio=%d:%d fps=%d isInterlaced=%d",header.Pid,m_mpegPesParser->basicVideoInfo.width,m_mpegPesParser->basicVideoInfo.height,m_mpegPesParser->basicVideoInfo.arx,m_mpegPesParser->basicVideoInfo.ary,m_mpegPesParser->basicVideoInfo.fps,m_mpegPesParser->basicVideoInfo.isInterlaced);
if (m_mpegParserTriggerFormatChange)
{
LogDebug("DeMultiplexer: OnMediaFormatChange triggered by mpeg2Parser");
SetMediaChanging(true);
m_filter.OnMediaTypeChanged(3);
m_mpegParserTriggerFormatChange=false;
}
LogDebug("DeMultiplexer: triggering OnVideoFormatChanged");
m_filter.OnVideoFormatChanged(m_mpegPesParser->basicVideoInfo.streamType,m_mpegPesParser->basicVideoInfo.width,m_mpegPesParser->basicVideoInfo.height,m_mpegPesParser->basicVideoInfo.arx,m_mpegPesParser->basicVideoInfo.ary,15000000,m_mpegPesParser->basicVideoInfo.isInterlaced);
}
else
{
if (m_mpegParserTriggerFormatChange && Gop)
{
LogDebug("DeMultiplexer: Got GOP after the channel change was detected without correct mpeg header parsing, so we trigger the format change now.");
m_filter.OnMediaTypeChanged(3);
m_mpegParserTriggerFormatChange=false;
}
}
}
else
{
m_bSetVideoDiscontinuity = true;
}
m_VideoValidPES=true ; // We've just completed a frame, set flag until problem clears it
m_pl.RemoveAll() ;
}
else // sequence_header_code
{
m_curFrameRate = frame_rate[*(p2->GetData()+7) & 0x0F] ; // Extract frame rate in seconds.
m_pl.AddTail(p2); // Add sequence header.
}
start = next;
m_lastStart = start - m_p->GetData() + 1;
}
if(start > m_p->GetData())
{
m_lastStart -= (start - m_p->GetData());
m_p->RemoveAt(0, start - m_p->GetData());
}
}
}
}
/// This method will check if the tspacket is an subtitle packet
/// if so store it in the subtitle buffers
void CDeMultiplexer::FillSubtitle(CTsHeader& header, byte* tsPacket)
{
if (header.TScrambling) return;
if (m_filter.GetSubtitlePin()->IsConnected()==false) return;
if (m_iSubtitleStream<0 || m_iSubtitleStream>=m_subtitleStreams.size()) return;
// If current subtitle PID has changed notify the DVB sub filter
if( m_subtitleStreams[m_iSubtitleStream].pid > 0 &&
m_subtitleStreams[m_iSubtitleStream].pid != m_currentSubtitlePid )
{
IDVBSubtitle* pDVBSubtitleFilter(m_filter.GetSubtitleFilter());
if( pDVBSubtitleFilter )
{
LogDebug("Calling SetSubtitlePid");
pDVBSubtitleFilter->SetSubtitlePid(m_subtitleStreams[m_iSubtitleStream].pid);
LogDebug(" done - SetSubtitlePid");
LogDebug("Calling SetFirstPcr");
pDVBSubtitleFilter->SetFirstPcr(m_duration.FirstStartPcr().PcrReferenceBase);
LogDebug(" done - SetFirstPcr");
m_currentSubtitlePid = m_subtitleStreams[m_iSubtitleStream].pid;
}
}
if (m_currentSubtitlePid==0 || m_currentSubtitlePid != header.Pid) return;
if ( header.AdaptionFieldOnly() ) return;
CAutoLock lock (&m_sectionSubtitle);
if ( false==header.AdaptionFieldOnly() )
{
if (header.PayloadUnitStart)
{
m_subtitlePcr = m_streamPcr;
//LogDebug("FillSubtitle: PayloadUnitStart -- %lld", m_streamPcr.PcrReferenceBase );
}
if (m_vecSubtitleBuffers.size()>MAX_BUF_SIZE)
{
ivecBuffers it = m_vecSubtitleBuffers.begin() ;
CBuffer* subtitleBuffer=*it;
delete subtitleBuffer ;
m_vecSubtitleBuffers.erase(it);
}
m_pCurrentSubtitleBuffer->SetPcr(m_duration.FirstStartPcr(),m_duration.MaxPcr());
m_pCurrentSubtitleBuffer->SetPts(m_subtitlePcr);
m_pCurrentSubtitleBuffer->Add(tsPacket,188);
m_vecSubtitleBuffers.push_back(m_pCurrentSubtitleBuffer);
m_pCurrentSubtitleBuffer = new CBuffer();
}
}
void CDeMultiplexer::FillTeletext(CTsHeader& header, byte* tsPacket)
{
if (header.TScrambling) return;
if (m_pids.TeletextPid==0) return;
if (header.Pid!=m_pids.TeletextPid) return;
if ( header.AdaptionFieldOnly() ) return;
if(pTeletextEventCallback != NULL)
{
(*pTeletextEventCallback)(TELETEXT_EVENT_PACKET_PCR_UPDATE,m_streamPcr.PcrReferenceBase - m_duration.FirstStartPcr().PcrReferenceBase - (m_filter.Compensation.Millisecs() * 90 ));
}
if(pTeletextPacketCallback != NULL)
{
(*pTeletextPacketCallback)(tsPacket,188);
}
}
int CDeMultiplexer::GetVideoBufferPts(CRefTime& First, CRefTime& Last)
{
First = m_FirstVideoSample;
Last = m_LastVideoSample;
return m_vecVideoBuffers.size();
}
int CDeMultiplexer::GetAudioBufferPts(CRefTime& First, CRefTime& Last)
{
First = m_FirstAudioSample;
Last = m_LastAudioSample;
return m_vecAudioBuffers.size();
}
/// This method gets called-back from the pat parser when a new PAT/PMT/SDT has been received
/// In this method we check if any audio/video/subtitle pid or format has changed
/// If not, we simply return
/// If something has changed we ask the MP to rebuild the graph
void CDeMultiplexer::OnNewChannel(CChannelInfo& info)
{
//CAutoLock lock (&m_section);
CPidTable pids=info.PidTable;
if (info.PatVersion != m_iPatVersion)
{
LogDebug("OnNewChannel pat version:%d->%d",m_iPatVersion, info.PatVersion);
if (m_filter.m_bLiveTv && ((m_ReqPatVersion & 0x0F) != (info.PatVersion & 0x0F)) && (m_iPatVersion!=-1))
{
LogDebug("Unexpected LiveTV PAT change due to provider, update m_ReqPatVersion to new PAT version : %d",m_ReqPatVersion);
// Unexpected LiveTV PAT change due to provider.
m_ReqPatVersion = info.PatVersion ;
}
m_iPatVersion=info.PatVersion;
m_bSetAudioDiscontinuity=true;
m_bSetVideoDiscontinuity=true;
Flush();
// m_filter.m_bOnZap = true ;
}
else
{
// No audio streams or channel info was not changed
if (pids.audioPids.size()==0 || m_pids == pids )
{
return; // no
}
}
//remember the old audio & video formats
int oldVideoServiceType(-1);
if(m_pids.videoPids.size()>0)
{
oldVideoServiceType=m_pids.videoPids[0].VideoServiceType;
}
m_pids=pids;
LogDebug("New channel found (PAT/PMT/SDT changed)");
m_pids.LogPIDs();
if(pTeletextEventCallback != NULL)
{
(*pTeletextEventCallback)(TELETEXT_EVENT_RESET,TELETEXT_EVENTVALUE_NONE);
}
IDVBSubtitle* pDVBSubtitleFilter(m_filter.GetSubtitleFilter());
if( pDVBSubtitleFilter )
{
// Make sure that subtitle cache is reset ( in filter & MP )
pDVBSubtitleFilter->NotifyChannelChange();
}
//update audio streams etc..
if (m_pids.PcrPid>0x1)
{
m_duration.SetVideoPid(m_pids.PcrPid);
}
else if (m_pids.videoPids.size() > 0 && m_pids.videoPids[0].Pid>0x1)
{
m_duration.SetVideoPid(m_pids.videoPids[0].Pid);
}
m_audioStreams.clear();
for(int i(0) ; i < m_pids.audioPids.size() ; i++)
{
struct stAudioStream audio;
audio.pid=m_pids.audioPids[i].Pid;
audio.language[0]=m_pids.audioPids[i].Lang[0];
audio.language[1]=m_pids.audioPids[i].Lang[1];
audio.language[2]=m_pids.audioPids[i].Lang[2];
audio.language[3]=m_pids.audioPids[i].Lang[3];
audio.language[4]=m_pids.audioPids[i].Lang[4];
audio.language[5]=m_pids.audioPids[i].Lang[5];
audio.language[6]=0;
audio.audioType = m_pids.audioPids[i].AudioServiceType;
m_audioStreams.push_back(audio);
}
m_subtitleStreams.clear();
for(int i(0) ; i < m_pids.subtitlePids.size() ; i++)
{
struct stSubtitleStream subtitle;
subtitle.pid=m_pids.subtitlePids[i].Pid;
subtitle.language[0]=m_pids.subtitlePids[i].Lang[0];
subtitle.language[1]=m_pids.subtitlePids[i].Lang[1];
subtitle.language[2]=m_pids.subtitlePids[i].Lang[2];
subtitle.language[3]=0;
m_subtitleStreams.push_back(subtitle);
}
bool changed=false;
bool videoChanged=false;
//did the video format change?
if (m_pids.videoPids.size() > 0 && oldVideoServiceType != m_pids.videoPids[0].VideoServiceType )
{
//yes, is the video pin connected?
if (m_filter.GetVideoPin()->IsConnected())
{
changed=true;
videoChanged=true;
}
}
m_iAudioStream = 0;
LogDebug ("Setting initial audio index to : %i", m_iAudioStream);
bool audioChanged=false;
//get the new audio format
int newAudioStreamType=SERVICE_TYPE_AUDIO_MPEG2;
if (m_iAudioStream>=0 && m_iAudioStream < m_audioStreams.size())
{
newAudioStreamType=m_audioStreams[m_iAudioStream].audioType;
}
//did the audio format change?
if (m_AudioStreamType != newAudioStreamType )
{
//yes, is the audio pin connected?
if (m_filter.GetAudioPin()->IsConnected())
{
changed=true;
audioChanged=true;
}
}
//did audio/video format change?
if (changed)
{
#ifdef USE_DYNAMIC_PINS
// if we have a video stream and it's format changed, let the mpeg parser trigger the OnMediaTypeChanged
if (m_pids.videoPids.size() > 0 && m_pids.videoPids[0].Pid>0x1 && videoChanged)
{
LogDebug("DeMultiplexer: We detected a new media type change which has a video stream, so we let the mpegParser trigger the event");
m_receivedPackets=0;
m_mpegParserTriggerFormatChange=true;
SetMediaChanging(true);
}
else
{
if (m_audioStreams.size() == 1)
{
if ((m_AudioStreamType == SERVICE_TYPE_AUDIO_UNKNOWN) || (m_AudioStreamType != newAudioStreamType))
{
m_AudioStreamType = newAudioStreamType ;
// notify the ITSReaderCallback. MP will then rebuild the graph
LogDebug("DeMultiplexer: Audio media types changed. Trigger OnMediaTypeChanged()...");
m_filter.OnMediaTypeChanged(1);
SetMediaChanging(true);
}
}
}
#else
if (audioChanged && videoChanged)
m_filter.OnMediaTypeChanged(3);
else
if (audioChanged)
m_filter.OnMediaTypeChanged(1);
else
m_filter.OnMediaTypeChanged(2);
#endif
}
//if we have more than 1 audio track available, tell host application that we are ready
//to receive an audio track change.
if (m_audioStreams.size() >= 1)
{
LogDebug("OnRequestAudioChange()");
SetAudioChanging(true);
m_filter.OnRequestAudioChange();
}
else
m_AudioStreamType = newAudioStreamType;
LogDebug("New Audio %d", m_AudioStreamType);
if( pSubUpdateCallback != NULL)
{
int bitmap_index = -1;
(*pSubUpdateCallback)(m_subtitleStreams.size(),(m_subtitleStreams.size() > 0 ? &m_subtitleStreams[0] : NULL),&bitmap_index);
if(bitmap_index >= 0)
{
LogDebug("Calling SetSubtitleStream from OnNewChannel: %i", bitmap_index);
SetSubtitleStream(bitmap_index);
}
}
}
///Returns whether the demuxer is allowed to block in GetAudio() or not
bool CDeMultiplexer::HoldAudio()
{
return m_bHoldAudio;
}
///Sets whether the demuxer may block in GetAudio() or not
void CDeMultiplexer::SetHoldAudio(bool onOff)
{
LogDebug("demux:set hold audio:%d", onOff);
m_bHoldAudio=onOff;
}
///Returns whether the demuxer is allowed to block in GetVideo() or not
bool CDeMultiplexer::HoldVideo()
{
return m_bHoldVideo;
}
///Sets whether the demuxer may block in GetVideo() or not
void CDeMultiplexer::SetHoldVideo(bool onOff)
{
LogDebug("demux:set hold video:%d", onOff);
m_bHoldVideo=onOff;
}
///Returns whether the demuxer is allowed to block in GetSubtitle() or not
bool CDeMultiplexer::HoldSubtitle()
{
return m_bHoldSubtitle;
}
///Sets whether the demuxer may block in GetSubtitle() or not
void CDeMultiplexer::SetHoldSubtitle(bool onOff)
{
LogDebug("demux:set hold subtitle:%d", onOff);
m_bHoldSubtitle=onOff;
}
void CDeMultiplexer::SetMediaChanging(bool onOff)
{
CAutoLock lock (&m_sectionMediaChanging);
LogDebug("demux:Wait for media format change:%d", onOff);
m_bWaitForMediaChange=onOff;
m_tWaitForMediaChange=GetTickCount() ;
}
bool CDeMultiplexer::IsMediaChanging(void)
{
CAutoLock lock (&m_sectionMediaChanging);
if (!m_bWaitForMediaChange) return false ;
else
{
if (GetTickCount()-m_tWaitForMediaChange > 5000)
{
m_bWaitForMediaChange=false;
LogDebug("demux: Alert: Wait for Media change cancelled on 5 secs timeout");
return false;
}
}
return true;
}
void CDeMultiplexer::SetAudioChanging(bool onOff)
{
CAutoLock lock (&m_sectionAudioChanging);
LogDebug("demux:Wait for Audio stream selection :%d", onOff);
m_bWaitForAudioSelection=onOff;
m_tWaitForAudioSelection=GetTickCount();
}
bool CDeMultiplexer::IsAudioChanging(void)
{
CAutoLock lock (&m_sectionAudioChanging);
if (!m_bWaitForAudioSelection) return false;
else
{
if (GetTickCount()-m_tWaitForAudioSelection > 5000)
{
m_bWaitForAudioSelection=false;
LogDebug("demux: Alert: Wait for Audio stream selection cancelled on 5 secs timeout");
return false;
}
}
return true;
}
void CDeMultiplexer::RequestNewPat(void)
{
m_ReqPatVersion++;
m_ReqPatVersion &= 0x0F;
LogDebug("Request new PAT = %d", m_ReqPatVersion);
m_WaitNewPatTmo=GetTickCount()+10000;
}
void CDeMultiplexer::ClearRequestNewPat(void)
{
m_ReqPatVersion=m_iPatVersion; // Used for AnalogTv or channel change fail.
}
bool CDeMultiplexer::IsNewPatReady(void)
{
return ((m_ReqPatVersion & 0x0F) == (m_iPatVersion & 0x0F)) ? true : false;
}
void CDeMultiplexer::ResetPatInfo(void)
{
m_pids.Reset();
}
void CDeMultiplexer::SetTeletextEventCallback(int (CALLBACK *pTeletextEventCallback)(int eventcode, DWORD64 eval))
{
this->pTeletextEventCallback = pTeletextEventCallback;
}
void CDeMultiplexer::SetTeletextPacketCallback(int (CALLBACK *pTeletextPacketCallback)(byte*, int))
{
this->pTeletextPacketCallback = pTeletextPacketCallback;
}
void CDeMultiplexer::SetTeletextServiceInfoCallback(int (CALLBACK *pTeletextSICallback)(int, byte,byte,byte,byte))
{
this->pTeletextServiceInfoCallback = pTeletextSICallback;
}
void CDeMultiplexer::CallTeletextEventCallback(int eventCode,unsigned long int eventValue)
{
if(pTeletextEventCallback != NULL)
{
(*pTeletextEventCallback)(eventCode,eventValue);
}
}
| [
[
[
1,
1
],
[
3,
3
],
[
9,
9
],
[
14,
14
],
[
17,
17
],
[
29,
29
],
[
57,
57
],
[
94,
94
],
[
99,
99
],
[
101,
102
],
[
117,
117
],
[
146,
146
],
[
148,
148
],
[
162,
162
],
[
166,
167
],
[
171,
172
],
[
187,
187
],
[
195,
195
],
[
201,
201
],
[
221,
221
],
[
223,
232
],
[
237,
237
],
[
249,
249
],
[
289,
298
],
[
309,
309
],
[
315,
315
],
[
362,
362
],
[
388,
388
],
[
393,
393
],
[
395,
396
],
[
400,
405
],
[
408,
409
],
[
412,
414
],
[
416,
417
],
[
419,
419
],
[
421,
422
],
[
424,
430
],
[
436,
436
],
[
440,
440
],
[
459,
459
],
[
491,
491
],
[
500,
500
],
[
508,
508
],
[
520,
520
],
[
522,
522
],
[
527,
527
],
[
532,
532
],
[
534,
534
],
[
538,
538
],
[
548,
548
],
[
557,
558
],
[
570,
572
],
[
577,
578
],
[
580,
583
],
[
585,
585
],
[
587,
600
],
[
602,
610
],
[
621,
622
],
[
627,
627
],
[
638,
638
],
[
641,
645
],
[
652,
652
],
[
673,
673
],
[
678,
678
],
[
681,
684
],
[
686,
686
],
[
688,
697
],
[
699,
706
],
[
711,
711
],
[
717,
719
],
[
723,
729
],
[
731,
731
],
[
736,
754
],
[
756,
762
],
[
765,
765
],
[
768,
768
],
[
779,
779
],
[
785,
785
],
[
789,
790
],
[
800,
800
],
[
817,
817
],
[
822,
825
],
[
871,
872
],
[
875,
876
],
[
878,
878
],
[
880,
880
],
[
882,
884
],
[
886,
900
],
[
902,
902
],
[
907,
921
],
[
926,
926
],
[
928,
931
],
[
934,
938
],
[
941,
943
],
[
947,
952
],
[
954,
955
],
[
959,
961
],
[
964,
967
],
[
970,
984
],
[
986,
988
],
[
991,
992
],
[
994,
994
],
[
996,
997
],
[
1000,
1001
],
[
1003,
1009
],
[
1013,
1014
],
[
1016,
1018
],
[
1020,
1044
],
[
1053,
1053
],
[
1057,
1057
],
[
1060,
1061
],
[
1063,
1064
],
[
1084,
1085
],
[
1087,
1088
],
[
1090,
1090
],
[
1101,
1102
],
[
1104,
1105
],
[
1107,
1107
],
[
1109,
1109
],
[
1111,
1114
],
[
1116,
1118
],
[
1125,
1125
],
[
1128,
1128
],
[
1131,
1139
],
[
1145,
1146
],
[
1148,
1160
],
[
1162,
1164
],
[
1166,
1168
],
[
1172,
1172
],
[
1174,
1175
],
[
1178,
1178
],
[
1180,
1181
],
[
1183,
1183
],
[
1185,
1185
],
[
1187,
1187
],
[
1193,
1193
],
[
1200,
1201
],
[
1206,
1206
],
[
1208,
1208
],
[
1210,
1214
],
[
1217,
1217
],
[
1219,
1220
],
[
1222,
1225
],
[
1228,
1229
],
[
1231,
1231
],
[
1234,
1235
],
[
1239,
1241
],
[
1244,
1246
],
[
1248,
1254
],
[
1256,
1258
],
[
1261,
1267
],
[
1269,
1274
],
[
1276,
1276
],
[
1278,
1285
],
[
1287,
1287
],
[
1289,
1296
],
[
1299,
1303
],
[
1306,
1308
],
[
1312,
1314
],
[
1317,
1319
],
[
1321,
1342
],
[
1344,
1344
],
[
1347,
1349
],
[
1353,
1354
],
[
1357,
1360
],
[
1362,
1362
],
[
1364,
1365
],
[
1367,
1367
],
[
1372,
1373
],
[
1376,
1378
],
[
1381,
1381
],
[
1383,
1385
],
[
1388,
1389
],
[
1391,
1391
],
[
1393,
1394
],
[
1397,
1398
],
[
1401,
1402
],
[
1405,
1406
],
[
1408,
1410
],
[
1412,
1414
],
[
1418,
1419
],
[
1426,
1426
],
[
1429,
1429
],
[
1432,
1436
],
[
1438,
1440
],
[
1446,
1447
],
[
1449,
1460
],
[
1466,
1467
],
[
1470,
1471
],
[
1473,
1473
],
[
1475,
1477
],
[
1479,
1492
],
[
1495,
1495
],
[
1497,
1497
],
[
1499,
1519
],
[
1521,
1521
],
[
1524,
1526
],
[
1529,
1529
],
[
1536,
1537
],
[
1539,
1540
],
[
1542,
1543
],
[
1545,
1556
],
[
1560,
1566
],
[
1569,
1574
],
[
1577,
1580
],
[
1583,
1606
],
[
1610,
1614
],
[
1617,
1626
],
[
1628,
1632
],
[
1634,
1634
],
[
1645,
1645
],
[
1647,
1647
],
[
1654,
1654
],
[
1660,
1667
],
[
1669,
1678
],
[
1681,
1681
],
[
1689,
1689
],
[
1691,
1691
],
[
1706,
1706
],
[
1708,
1708
],
[
1710,
1711
],
[
1718,
1718
],
[
1745,
1745
],
[
1749,
1749
],
[
1754,
1754
],
[
1758,
1759
],
[
1761,
1761
],
[
1765,
1766
],
[
1775,
1775
],
[
1785,
1785
],
[
1806,
1806
],
[
1813,
1813
],
[
1833,
1833
],
[
1863,
1863
],
[
1871,
1871
],
[
1873,
1873
],
[
1888,
1888
],
[
1892,
1892
],
[
1894,
1895
],
[
1901,
1902
],
[
1904,
1907
],
[
1909,
1913
],
[
1924,
1935
],
[
1941,
1941
],
[
1943,
1943
],
[
1945,
1945
],
[
1950,
1951
],
[
1954,
1956
],
[
1963,
1963
],
[
1965,
1965
],
[
1970,
1970
],
[
1976,
1976
],
[
1978,
1978
],
[
1983,
1983
],
[
1991,
1991
],
[
2000,
2000
],
[
2005,
2006
],
[
2008,
2008
],
[
2045,
2048
],
[
2053,
2056
],
[
2068,
2069
],
[
2072,
2072
],
[
2077,
2077
],
[
2082,
2082
],
[
2087,
2087
],
[
2089,
2090
]
],
[
[
2,
2
],
[
24,
25
],
[
39,
39
],
[
42,
46
],
[
48,
48
],
[
50,
51
],
[
55,
56
],
[
63,
63
],
[
66,
82
],
[
88,
93
],
[
95,
98
],
[
100,
100
],
[
103,
106
],
[
111,
111
],
[
116,
116
],
[
118,
119
],
[
124,
131
],
[
136,
136
],
[
149,
149
],
[
151,
151
],
[
155,
155
],
[
158,
159
],
[
161,
161
],
[
164,
164
],
[
168,
168
],
[
173,
182
],
[
190,
190
],
[
202,
202
],
[
204,
204
],
[
207,
213
],
[
222,
222
],
[
233,
236
],
[
238,
248
],
[
250,
255
],
[
260,
265
],
[
270,
275
],
[
280,
285
],
[
299,
308
],
[
310,
314
],
[
316,
318
],
[
320,
325
],
[
327,
343
],
[
346,
355
],
[
360,
361
],
[
363,
363
],
[
368,
387
],
[
389,
392
],
[
394,
394
],
[
397,
399
],
[
406,
407
],
[
415,
415
],
[
418,
418
],
[
420,
420
],
[
423,
423
],
[
431,
435
],
[
437,
439
],
[
441,
441
],
[
443,
445
],
[
447,
458
],
[
465,
468
],
[
471,
471
],
[
474,
474
],
[
477,
477
],
[
485,
486
],
[
488,
488
],
[
509,
510
],
[
512,
512
],
[
529,
529
],
[
536,
536
],
[
559,
559
],
[
561,
562
],
[
584,
584
],
[
586,
586
],
[
620,
620
],
[
631,
632
],
[
634,
636
],
[
639,
640
],
[
649,
649
],
[
656,
656
],
[
675,
677
],
[
687,
687
],
[
713,
715
],
[
733,
734
],
[
763,
764
],
[
766,
767
],
[
780,
784
],
[
786,
788
],
[
791,
799
],
[
818,
821
],
[
826,
826
],
[
857,
866
],
[
873,
874
],
[
877,
877
],
[
879,
879
],
[
881,
881
],
[
885,
885
],
[
901,
901
],
[
922,
925
],
[
927,
927
],
[
932,
933
],
[
939,
940
],
[
944,
946
],
[
953,
953
],
[
956,
958
],
[
962,
963
],
[
968,
969
],
[
985,
985
],
[
989,
990
],
[
993,
993
],
[
995,
995
],
[
998,
999
],
[
1002,
1002
],
[
1010,
1012
],
[
1015,
1015
],
[
1019,
1019
],
[
1047,
1047
],
[
1051,
1052
],
[
1054,
1056
],
[
1058,
1059
],
[
1062,
1062
],
[
1065,
1083
],
[
1086,
1086
],
[
1089,
1089
],
[
1092,
1099
],
[
1103,
1103
],
[
1106,
1106
],
[
1108,
1108
],
[
1110,
1110
],
[
1115,
1115
],
[
1119,
1120
],
[
1126,
1127
],
[
1129,
1129
],
[
1161,
1161
],
[
1165,
1165
],
[
1169,
1171
],
[
1173,
1173
],
[
1176,
1177
],
[
1179,
1179
],
[
1182,
1182
],
[
1184,
1184
],
[
1186,
1186
],
[
1188,
1192
],
[
1194,
1199
],
[
1202,
1205
],
[
1207,
1207
],
[
1209,
1209
],
[
1215,
1216
],
[
1218,
1218
],
[
1221,
1221
],
[
1226,
1227
],
[
1230,
1230
],
[
1232,
1233
],
[
1268,
1268
],
[
1275,
1275
],
[
1277,
1277
],
[
1286,
1286
],
[
1297,
1298
],
[
1304,
1305
],
[
1309,
1311
],
[
1315,
1315
],
[
1345,
1346
],
[
1350,
1352
],
[
1355,
1355
],
[
1361,
1361
],
[
1366,
1366
],
[
1368,
1371
],
[
1374,
1374
],
[
1379,
1380
],
[
1386,
1387
],
[
1390,
1390
],
[
1395,
1396
],
[
1400,
1400
],
[
1404,
1404
],
[
1407,
1407
],
[
1411,
1411
],
[
1415,
1416
],
[
1420,
1421
],
[
1427,
1428
],
[
1430,
1430
],
[
1437,
1437
],
[
1461,
1465
],
[
1468,
1469
],
[
1472,
1472
],
[
1474,
1474
],
[
1493,
1494
],
[
1496,
1496
],
[
1498,
1498
],
[
1520,
1520
],
[
1522,
1522
],
[
1527,
1528
],
[
1541,
1541
],
[
1558,
1558
],
[
1567,
1568
],
[
1575,
1576
],
[
1581,
1582
],
[
1608,
1609
],
[
1615,
1616
],
[
1633,
1633
],
[
1635,
1644
],
[
1646,
1646
],
[
1648,
1653
],
[
1683,
1683
],
[
1688,
1688
],
[
1690,
1690
],
[
1692,
1705
],
[
1707,
1707
],
[
1715,
1716
],
[
1720,
1723
],
[
1743,
1744
],
[
1747,
1748
],
[
1753,
1753
],
[
1755,
1757
],
[
1760,
1760
],
[
1762,
1764
],
[
1770,
1770
],
[
1773,
1774
],
[
1788,
1789
],
[
1791,
1796
],
[
1798,
1798
],
[
1801,
1805
],
[
1808,
1809
],
[
1811,
1812
],
[
1816,
1822
],
[
1828,
1828
],
[
1830,
1830
],
[
1834,
1834
],
[
1837,
1841
],
[
1845,
1845
],
[
1848,
1861
],
[
1865,
1865
],
[
1903,
1903
],
[
1908,
1908
],
[
1922,
1922
],
[
1936,
1937
],
[
1939,
1940
],
[
1944,
1944
],
[
1946,
1946
],
[
1948,
1949
],
[
1952,
1953
],
[
1972,
1972
],
[
1986,
1990
],
[
1992,
1999
],
[
2001,
2004
],
[
2007,
2007
],
[
2009,
2044
],
[
2049,
2052
],
[
2057,
2067
],
[
2070,
2071
],
[
2074,
2076
],
[
2080,
2081
],
[
2085,
2086
],
[
2088,
2088
]
],
[
[
4,
8
],
[
10,
13
],
[
15,
16
],
[
18,
20
],
[
22,
23
],
[
28,
28
],
[
30,
31
],
[
33,
37
],
[
41,
41
],
[
47,
47
],
[
49,
49
],
[
58,
62
],
[
64,
65
],
[
107,
110
],
[
112,
115
],
[
120,
123
],
[
132,
132
],
[
134,
135
],
[
137,
143
],
[
145,
145
],
[
150,
150
],
[
153,
154
],
[
156,
157
],
[
160,
160
],
[
163,
163
],
[
165,
165
],
[
169,
170
],
[
183,
186
],
[
188,
189
],
[
192,
193
],
[
198,
200
],
[
203,
203
],
[
205,
206
],
[
214,
220
],
[
256,
256
],
[
258,
258
],
[
279,
279
],
[
286,
286
],
[
288,
288
],
[
319,
319
],
[
326,
326
],
[
356,
357
],
[
359,
359
],
[
364,
367
],
[
410,
411
],
[
442,
442
],
[
460,
462
],
[
469,
470
],
[
472,
473
],
[
475,
476
],
[
478,
484
],
[
487,
487
],
[
489,
490
],
[
492,
499
],
[
501,
507
],
[
511,
511
],
[
513,
519
],
[
521,
521
],
[
523,
526
],
[
528,
528
],
[
530,
531
],
[
533,
533
],
[
535,
535
],
[
537,
537
],
[
539,
547
],
[
549,
556
],
[
563,
569
],
[
573,
576
],
[
579,
579
],
[
601,
601
],
[
611,
619
],
[
623,
626
],
[
628,
630
],
[
633,
633
],
[
637,
637
],
[
646,
648
],
[
650,
651
],
[
653,
654
],
[
657,
658
],
[
663,
672
],
[
674,
674
],
[
679,
680
],
[
685,
685
],
[
698,
698
],
[
707,
710
],
[
712,
712
],
[
716,
716
],
[
720,
722
],
[
730,
730
],
[
732,
732
],
[
735,
735
],
[
755,
755
],
[
769,
777
],
[
801,
804
],
[
810,
813
],
[
831,
853
],
[
855,
856
],
[
867,
870
],
[
1045,
1046
],
[
1048,
1050
],
[
1679,
1680
],
[
1682,
1682
],
[
1684,
1685
],
[
1687,
1687
],
[
1709,
1709
],
[
1712,
1714
],
[
1717,
1717
],
[
1719,
1719
],
[
1724,
1735
],
[
1767,
1769
],
[
1771,
1772
],
[
1776,
1778
],
[
1786,
1787
],
[
1790,
1790
],
[
1797,
1797
],
[
1799,
1800
],
[
1807,
1807
],
[
1810,
1810
],
[
1823,
1827
],
[
1829,
1829
],
[
1831,
1832
],
[
1835,
1836
],
[
1846,
1847
],
[
1862,
1862
],
[
1864,
1864
],
[
1866,
1870
],
[
1872,
1872
],
[
1880,
1887
],
[
1889,
1891
],
[
1893,
1893
],
[
1896,
1900
],
[
1958,
1962
],
[
1964,
1964
],
[
1966,
1969
],
[
1971,
1971
],
[
1973,
1975
],
[
1977,
1977
],
[
1979,
1982
],
[
1984,
1985
]
],
[
[
21,
21
],
[
32,
32
],
[
38,
38
],
[
52,
54
],
[
133,
133
],
[
358,
358
],
[
778,
778
],
[
1878,
1879
]
],
[
[
26,
27
]
],
[
[
40,
40
],
[
83,
86
],
[
344,
345
],
[
446,
446
],
[
814,
816
],
[
827,
830
],
[
854,
854
],
[
1736,
1737
],
[
1739,
1742
],
[
1746,
1746
],
[
1750,
1752
],
[
1814,
1815
],
[
1947,
1947
],
[
1957,
1957
],
[
2073,
2073
],
[
2078,
2079
],
[
2083,
2084
],
[
2091,
2092
]
],
[
[
87,
87
],
[
144,
144
],
[
147,
147
],
[
152,
152
],
[
191,
191
],
[
194,
194
],
[
196,
197
],
[
257,
257
],
[
287,
287
],
[
463,
464
],
[
560,
560
],
[
655,
655
],
[
659,
662
],
[
1842,
1844
],
[
1874,
1877
],
[
1938,
1938
],
[
1942,
1942
]
],
[
[
259,
259
],
[
266,
269
],
[
276,
278
]
],
[
[
805,
809
],
[
903,
903
],
[
1123,
1124
],
[
1143,
1144
],
[
1424,
1425
],
[
1444,
1445
],
[
1530,
1532
],
[
1534,
1535
],
[
1656,
1659
],
[
1686,
1686
],
[
1738,
1738
]
],
[
[
904,
906
],
[
1091,
1091
],
[
1100,
1100
],
[
1121,
1122
],
[
1130,
1130
],
[
1140,
1142
],
[
1147,
1147
],
[
1238,
1238
],
[
1247,
1247
],
[
1255,
1255
],
[
1259,
1260
],
[
1288,
1288
],
[
1316,
1316
],
[
1320,
1320
],
[
1343,
1343
],
[
1356,
1356
],
[
1363,
1363
],
[
1375,
1375
],
[
1382,
1382
],
[
1392,
1392
],
[
1399,
1399
],
[
1403,
1403
],
[
1417,
1417
],
[
1422,
1423
],
[
1431,
1431
],
[
1441,
1443
],
[
1448,
1448
],
[
1478,
1478
],
[
1523,
1523
],
[
1533,
1533
],
[
1538,
1538
],
[
1544,
1544
],
[
1557,
1557
],
[
1559,
1559
],
[
1607,
1607
],
[
1627,
1627
],
[
1655,
1655
],
[
1668,
1668
],
[
1779,
1784
],
[
1914,
1921
],
[
1923,
1923
]
],
[
[
1236,
1237
],
[
1242,
1243
]
]
] |
|
be786d6f863e1832d804c8739ce01bc2458970c7 | 54319da8732c447b8f196de5e98293083d3acf10 | /qt4_src/src/fxbuddy.cpp | c9fc5d665cbd1c23fa15c5a8e6a42c23bf9ec3b2 | [
"curl"
] | permissive | libfetion/libfetion-gui | 6c0ed30f9b31669048347352b292fbe02e5505f3 | a5912c7ac301830c2953378e58a4d923bc0a0a8d | refs/heads/master | 2021-01-13T02:16:46.031301 | 2010-09-19T10:42:37 | 2010-09-19T10:42:37 | 32,465,618 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,074 | cpp | /***************************************************************************
* Copyright (C) 2008 by DDD *
* [email protected] *
* *
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <assert.h>
#include "fxbuddy.h"
#include "fxsendGroupSMS.h"
#include "fxlocationparser.h"
#define recently_contact_group_no -3
#define MaxNum_recently_contact_group 10
BuddyOpt::BuddyOpt(QTreeWidget *widget, bool isMainView)
{
FX_FUNCTION
m_isMainView = isMainView;
QunItem = NULL;
have_zero_group = false;
have_recently_contact_group = false;
markedCount = 0;
assert(widget);
treeWidget = widget;
addGroupToTree();
addAccountToTree();
if (m_isMainView)
{
addQunToTree();
}
else
{
connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this,
SLOT(updateStyles(QTreeWidgetItem *, int)));
}
QList<qlonglong>* list = db_GetRecentlyContactAccountFromDB();
if (!list)
return;
QList<qlonglong>::iterator iter;
for(iter = list->begin(); iter != list->end(); iter++)
addAccountToRecentlyContactGroup(fx_get_account_by_id(*iter));
delete list;
//expandTree();
}
/**************************************************************************/
/* */
/**************************************************************************/
BuddyOpt::~BuddyOpt()
{
FX_FUNCTION
freeAllGroupdata();
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::expandTree()
{
FX_FUNCTION
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return ;
}
for (int i = 0; i < RootItem->childCount(); i++)
{
this->treeWidget->expandItem(RootItem->child(i));
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::freeAllGroupdata()
{
FX_FUNCTION
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return ;
}
int GroupCount = RootItem->childCount();
QTreeWidgetItem *groupItem = NULL;
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem)
{
continue;
}
if (isQunItem(groupItem))
{
freeAllQundata(groupItem);
continue;
}
//free all account data of this group
freeAllAccountdata(groupItem);
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info =
groupItem->data(0, Qt::UserRole).value <Group_Info * > ();
#endif
if (group_info)
{
delete group_info;
}
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::freeAllAccountdata(QTreeWidgetItem *groupItem)
{
FX_FUNCTION
if (!groupItem)
{
return ;
}
int itemCounts = groupItem->childCount();
QTreeWidgetItem *tmpItem = NULL;
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (ac_info)
{
delete ac_info;
}
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::freeAllQundata(QTreeWidgetItem *groupItem)
{
FX_FUNCTION
if (!groupItem)
{
return ;
}
int itemCounts = groupItem->childCount();
QTreeWidgetItem *tmpItem = NULL;
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Qun_Info *qun_info = (Qun_Info*)(tmpItem->data(0, Qt::UserRole)
.toUInt());
#else
Qun_Info *qun_info = tmpItem->data(0, Qt::UserRole).value <
Qun_Info * > ();
#endif
if (qun_info)
{
delete qun_info;
}
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::addQunToTree()
{
FX_FUNCTION
Fetion_Qun *qun = NULL;
Qun_Info *qun_info = NULL;
DList *tmp_qun = (DList*)fx_get_qun();
while (tmp_qun)
{
qun = (Fetion_Qun*)tmp_qun->data;
if (qun)
{
if (!QunItem)
{
QunItem = new QTreeWidgetItem(treeWidget);
QunItem->setText(0, tr("fetion qun"));
}
qun_info = new Qun_Info;
char *qun_name = fx_get_qun_show_name(qun);
qun_info->qunName = QString::fromUtf8(qun_name);
if (qun_name)
{
free(qun_name);
}
qun_info->qunID = qun->id;
#if MS_VC6
QVariant Var((uint)qun_info);
#else
QVariant Var;
Var.setValue(qun_info);
#endif
QTreeWidgetItem *item;
item = new QTreeWidgetItem(QunItem);
item->setText(0, qun_info->qunName);
item->setIcon(0, getQunIcon());
item->setData(0, Qt::UserRole, Var);
}
tmp_qun = d_list_next(tmp_qun);
}
}
/**************************************************************************/
/* */
/**************************************************************************/
bool BuddyOpt::isQunItem(QTreeWidgetItem *item)
{
FX_FUNCTION
if (QunItem)
{
return item == QunItem;
}
else
{
return false;
}
}
//add Group info to tree widget
void BuddyOpt::addGroupToTree()
{
FX_FUNCTION
Group_Info *groupinfo = NULL;
Fetion_Group *group = NULL;
DList *tmp_group = (DList*)fx_get_group();
while (tmp_group)
{
group = (Fetion_Group*)tmp_group->data;
if (group)
{
QTreeWidgetItem *item;
item = new QTreeWidgetItem(treeWidget);
if (!m_isMainView)
{
item->setCheckState(0, Qt::Unchecked);
}
QString str = QString::fromUtf8(group->name);
groupinfo = new Group_Info;
groupinfo->groupName = str;
groupinfo->groupID = group->id;
groupinfo->online_no = 0;
item->setText(0, str + "(0/0)");
#if MS_VC6
QVariant Var((uint)groupinfo);
#else
QVariant Var;
Var.setValue(groupinfo);
#endif
item->setData(0, Qt::UserRole, Var);
}
tmp_group = d_list_next(tmp_group);
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::delAccount_direct(qlonglong uid)
{
FX_FUNCTION
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return ;
}
int GroupCount = RootItem->childCount();
QTreeWidgetItem *groupItem = NULL;
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem || isQunItem(groupItem))
{
continue;
}
int itemCounts = groupItem->childCount();
QTreeWidgetItem *tmpItem = NULL;
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
continue;
}
if (ac_info->accountID == uid)
{
delAccount(tmpItem);
return ;
}
}
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::delAccount(QTreeWidgetItem *accountItem)
{
FX_FUNCTION
if (!accountItem)
{
return ;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(accountItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = accountItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
return ;
}
const Fetion_Account *account = fx_get_account_by_id(ac_info->accountID);
if (ac_info)
{
delete ac_info;
}
QTreeWidgetItem *groupItem = accountItem->parent();
if (!groupItem)
{
return ;
}
groupItem->removeChild(accountItem);
{
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value <
Group_Info * > ();
#endif
if (!group_info)
{
return ;
}
if (fx_is_on_line_by_account(account))
{
group_info->online_no--;
}
#ifdef WIN32
char online[30];
_snprintf(online, sizeof(online) - 1, "(%d/%d)", group_info
->online_no, groupItem->childCount());
QString groupShowName = group_info->groupName + online;
#else
char *online = NULL;
asprintf(&online, "(%d/%d)", group_info->online_no, groupItem
->childCount());
QString groupShowName = group_info->groupName + online;
if (online)
{
free(online);
}
#endif
groupItem->setText(0, groupShowName);
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::delAccount(qlonglong uid)
{
FX_FUNCTION
const Fetion_Account *account = fx_get_account_by_id(uid);
if (!account)
{
return ;
}
delAccount(findAccountItem(account));
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::addGroup(const char *groupname, qlonglong id)
{
Group_Info *groupinfo = new Group_Info;
groupinfo->groupName = QString::fromUtf8((char*)groupname);
groupinfo->groupID = id;
groupinfo->online_no = 0;
QTreeWidgetItem *item;
item = new QTreeWidgetItem(treeWidget);
if (!m_isMainView)
{
item->setCheckState(0, Qt::Unchecked);
}
item->setText(0, groupinfo->groupName + "(0/0)");
#if MS_VC6
QVariant Var((uint)groupinfo);
#else
QVariant Var;
Var.setValue(groupinfo);
#endif
item->setData(0, Qt::UserRole, Var);
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::delGroup(qlonglong id)
{
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return ;
}
QTreeWidgetItem *groupItem = NULL;
int GroupCount = RootItem->childCount();
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem || isQunItem(groupItem))
{
continue;
}
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value <
Group_Info * > ();
#endif
if (group_info && group_info->groupID == id)
{
//free all account data of this group
freeAllAccountdata(groupItem);
delete group_info;
RootItem->removeChild(groupItem);
return ;
}
}
}
//add account info to tree widget
void BuddyOpt::addAccountToTree()
{
const Fetion_Account *account = fx_get_first_account();
while (account)
{
addAccountToGroup(account);
account = fx_get_next_account(account);
}
}
//add account to it's group item
void BuddyOpt::addAccountToGroup(const Fetion_Account *account)
{
//remove the user's id on account from list...
if (!account)
{
return ;
}
// we need current user's account when we send scheduleSms or others
if (m_isMainView && account->id == (qlonglong)strtol(fx_get_usr_uid(), NULL, 10))
{
return ;
}
int group_no = fx_get_account_group_id(account);
if (group_no <= 0)
{
create_zero_group();
}
char *showname = fx_get_account_show_name_with_state(account, TRUE, TRUE);
QString show_name = QString::fromUtf8(showname);
int online_state = fx_get_online_status_by_account(account);
addAccountToGroup(account, show_name, online_state, group_no);
if (showname)
{
free(showname);
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::addAccountToGroup(const Fetion_Account *account, QString &name,
int online_state, int group_id)
{
if (!account)
{
return ;
}
// we need current user's account when we send scheduleSms or others
if (m_isMainView && account->id == (qlonglong)strtol(fx_get_usr_uid(), NULL, 10))
{
return ;
}
QTreeWidgetItem *groupItem = findGroupItemByID(group_id);
if (!groupItem)
{
return ;
}
Account_Info *ac_info = new Account_Info;
ac_info->accountName = name;
ac_info->accountID = account->id;
ac_info->haveUpdate = false;
QString nicename;
QString impresa;
if (GetAccountInfoFromDB(account->id, nicename, impresa))
{
if (!nicename.isEmpty())
{
fx_set_buddy_nickname_ex(account->id, nicename.toUtf8().data());
ac_info->haveUpdate = true;
}
if (!impresa.isEmpty())
{
fx_set_buddy_impresa_ex(account->id, impresa.toUtf8().data());
ac_info->haveUpdate = true;
}
}
ac_info->onlinestate = online_state;
QTreeWidgetItem *accountItem = new QTreeWidgetItem;
if (!m_isMainView)
{
accountItem->setCheckState(0, Qt::Unchecked);
}
accountItem->setText(0, name);
#if MS_VC6
QVariant Var((uint)ac_info);
#else
QVariant Var;
Var.setValue(ac_info); //vc7 up
#endif
accountItem->setData(0, Qt::UserRole, Var);
accountItem->setIcon(0, getOnlineStatusIcon(ac_info->onlinestate));
setTipsOfAccount(accountItem, account);
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt::UserRole)
.toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value <
Group_Info * > ();
#endif
if (!group_info)
{
return ;
}
groupItem->insertChild(groupItem->childCount(), accountItem);
if (fx_is_on_line_by_account(account))
{
groupItem->removeChild(accountItem);
groupItem->insertChild(group_info->online_no, accountItem);
group_info->online_no++;
}
#ifdef WIN32
char online[30];
_snprintf(online, sizeof(online) - 1, "(%d/%d)", group_info->online_no,
groupItem->childCount());
QString groupShowName = group_info->groupName + online;
#else
char *online = NULL;
asprintf(&online,
"(%d/%d)",
group_info->online_no,
groupItem->childCount());
QString groupShowName = group_info->groupName + online;
if (online)
{
free(online);
}
#endif
groupItem->setText(0, groupShowName);
}
/**************************************************************************/
/* */
/**************************************************************************/
QString BuddyOpt::createAccountTipsInfo(const Fetion_Account *account)
{
QString tips;
QString tmp;
bool hP = false;
if (account->personal)
{
hP = true;
}
QString info;
info += tr("mobile_no:");
if (hP)
{
tmp = QString::fromUtf8(account->personal->mobile_no);
if (!tmp.isEmpty())
{
info += "<b style=\"color:red; \">" + tmp + "</b>";
tips += info + "<br>";
}
}
else
{
if (!fx_is_pc_user_by_account(account))
{
char *mobile_no = fx_get_original_ID(account->id);
info += "<b style=\"color:red; \">" + QString(mobile_no) + "</b>";
if (mobile_no)
{
free(mobile_no);
}
}
info += "<b style=\"color:red; \"> </b>";
tips += info + "<br>";
}
if (fx_is_pc_user_by_account(account))
{
info = tr("fetion_no:");
info += "<b style=\"color:red; \">" + QString("%1").arg(account->id) +
"</b>";
tips += info + "<br>";
}
if (hP)
{
tmp = QString::fromUtf8(account->personal->nickname);
if (!tmp.isEmpty())
{
info = tr("nickname:");
info += "<b style=\"color:red; \">" + tmp + "</b>";
tips += info + "<br>";
}
tmp = QString::fromUtf8(account->personal->name);
if (!tmp.isEmpty())
{
info = tr("name:");
info += "<b style=\"color:red; \">" + tmp + "</b>";
tips += info + "<br>";
}
info = tr("gender:");
switch (account->personal->gender)
{
case 2:
info += "<b style=\"color:red; \">" + tr("girl") + "</b>";
tips += info + "<br>";
break;
case 1:
info += "<b style=\"color:red; \">" + tr("boy") + "</b>";
tips += info + "<br>";
break;
default:
info += "<b style=\"color:red; \">" + tr("secrecy") + "</b>";
break;
}
tmp = QString::fromUtf8(account->personal->impresa);
if (!tmp.isEmpty())
{
info = tr("impresa:");
info += "<b style=\"color:red; \">" + tmp + "</b>";
tips += info + "<br>";
}
FxLocationParser *parser = new FxLocationParser();
info = tr("province:");
info += "<b style=\"color:red; \">" +
parser->getProvinceByAlias(QString::fromUtf8(account->personal->province)) + "</b>";
tips += info + "<br>";
info = tr("city:");
info += "<b style=\"color:red; \">" +
parser->getCityByCode(account->personal->city)+
"</b>";
tips += info + "<br>";
delete parser;
}
//remove the last "<br>"
tips = tips.remove(tips.size() - strlen("<br>"), strlen("<br>"));
return tips;
}
//fix: need to....
void BuddyOpt::setTipsOfAccount(QTreeWidgetItem *accountItem, const
Fetion_Account *account)
{
if (!accountItem || !account)
{
return ;
}
QString tips = createAccountTipsInfo(account);
accountItem->setToolTip(0, tips);
}
/**************************************************************************/
/* */
/**************************************************************************/
QTreeWidgetItem *BuddyOpt::findGroupItemByID(int group_id)
{
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return NULL;
}
int GroupCount = RootItem->childCount();
QTreeWidgetItem *groupItem = NULL;
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem || isQunItem(groupItem))
{
continue;
}
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value <
Group_Info * > ();
#endif
if (!group_info)
{
continue;
}
if (group_id == group_info->groupID)
{
return groupItem;
}
}
/* didn't find the item, try it from zero group */
if (group_id != 0) {
create_zero_group();
return findGroupItemByID(0);
}
return NULL;
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::create_zero_group()
{
int group_no = 0;
if (have_zero_group)
{
return ;
}
QTreeWidgetItem *item;
item = new QTreeWidgetItem(treeWidget);
if (!m_isMainView)
{
item->setCheckState(0, Qt::Unchecked);
}
QString str = tr("un set group");
Group_Info *groupinfo = new Group_Info;
groupinfo->groupName = str;
groupinfo->groupID = group_no;
groupinfo->online_no = 0;
item->setText(0, str);
#if MS_VC6
QVariant Var((uint)groupinfo);
#else
QVariant Var;
Var.setValue(groupinfo);
#endif
item->setData(0, Qt::UserRole, Var);
have_zero_group = true;
}
void BuddyOpt::create_recently_contact_group()
{
int group_no = recently_contact_group_no;
if (have_recently_contact_group)
{
return ;
}
QTreeWidgetItem *item;
item = new QTreeWidgetItem(treeWidget);
if (!m_isMainView)
{
item->setCheckState(0, Qt::Unchecked);
}
QString str = tr("recently contact group");
Group_Info *groupinfo = new Group_Info;
groupinfo->groupName = str;
groupinfo->groupID = group_no;
groupinfo->online_no = 0;
item->setText(0, str);
#if MS_VC6
QVariant Var((uint)groupinfo);
#else
QVariant Var;
Var.setValue(groupinfo);
#endif
item->setData(0, Qt::UserRole, Var);
have_recently_contact_group = true;
}
void BuddyOpt::adjustRecentlyContactGroupNum(QTreeWidgetItem *groupItem)
{
if (!groupItem)
return;
int Numb = groupItem->childCount();
if (Numb < MaxNum_recently_contact_group)
return;
QTreeWidgetItem *tmpItem = groupItem->child(Numb - 1);
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (ac_info && ac_info->accountID)
delAccountRecentlyContactGroup(ac_info->accountID);
}
void BuddyOpt::addAccountToRecentlyContactGroup(const Fetion_Account *account)
{
create_recently_contact_group();
int group_no = recently_contact_group_no;
if (!account)
return;
if (account->id == strtol(fx_get_usr_uid(), NULL, 10))
return;
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
if (!groupItem)
return;
adjustRecentlyContactGroupNum(groupItem);
QTreeWidgetItem *accountItem = findAccountItemFromGroup(groupItem, account);
if (accountItem) {
groupItem->removeChild(accountItem);
groupItem->insertChild(0, accountItem);
return;
}
char *showname = fx_get_account_show_name_with_state(account, TRUE, TRUE);
QString show_name = QString::fromUtf8(showname);
int online_state = fx_get_online_status_by_account(account);
addAccountToGroup(account, show_name, online_state, group_no);
if (showname)
free(showname);
/* add just the pos due to addAccountToGroup will always
* put the offline user under online */
accountItem = findAccountItemFromGroup(groupItem, account);
if (accountItem) {
groupItem->removeChild(accountItem);
groupItem->insertChild(0, accountItem);
}
}
void BuddyOpt::delAccountRecentlyContactGroup(qlonglong uid)
{
int group_no = recently_contact_group_no;
const Fetion_Account *account = fx_get_account_by_id(uid);
if (!account)
{
return ;
}
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
if (!groupItem)
return;
QTreeWidgetItem *accountItem = findAccountItemFromGroup(groupItem, account);
if (!accountItem)
return;
groupItem->removeChild(accountItem);
{
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value <
Group_Info * > ();
#endif
if (!group_info)
return ;
if (fx_is_on_line_by_account(account))
{
group_info->online_no--;
}
#ifdef WIN32
char online[30];
_snprintf(online, sizeof(online) - 1, "(%d/%d)", group_info
->online_no, groupItem->childCount());
QString groupShowName = group_info->groupName + online;
#else
char *online = NULL;
asprintf(&online, "(%d/%d)", group_info->online_no, groupItem
->childCount());
QString groupShowName = group_info->groupName + online;
if (online)
{
free(online);
}
#endif
groupItem->setText(0, groupShowName);
}
}
void BuddyOpt::updateAccountInfo_RecentlyContactGroup(const Fetion_Account *account)
{
int group_no = recently_contact_group_no;
if (!have_recently_contact_group)
return;
if (!account)
return;
if (account->id == strtol(fx_get_usr_uid(), NULL, 10))
return;
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
if (!groupItem)
return;
QTreeWidgetItem *accountItem = findAccountItemFromGroup(groupItem, account);
if (!accountItem)
return;
//update the account info
setTipsOfAccount(accountItem, account);
char *showname = fx_get_account_show_name_with_state(account, TRUE, TRUE);
QString show_name = QString::fromUtf8(showname);
if (showname)
{
free(showname);
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(accountItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = accountItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
return ;
}
ac_info->accountName = show_name;
int old_online_state = ac_info->onlinestate;
ac_info->onlinestate = fx_get_online_status_by_account(account);
accountItem->setText(0, show_name);
accountItem->setIcon(0, getOnlineStatusIcon(ac_info->onlinestate));
int state = 0;
if (isOnlineStateChanged(old_online_state, ac_info->onlinestate, &state))
{
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value
< Group_Info * > ();
#endif
if (!group_info)
{
return ;
}
if (state)
{
group_info->online_no++;
}
else
{
group_info->online_no--;
}
#ifdef WIN32
char online[30];
_snprintf(online, sizeof(online) - 1, "(%d/%d)", group_info
->online_no, groupItem->childCount());
QString groupShowName = group_info->groupName + online;
#else
char *online = NULL;
asprintf(&online, "(%d/%d)", group_info->online_no, groupItem
->childCount());
QString groupShowName = group_info->groupName + online;
if (online)
{
free(online);
}
#endif
groupItem->setText(0, groupShowName);
}
}
void BuddyOpt::SaveRecentlyContactAccountToDB()
{
int group_no = recently_contact_group_no;
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
if (!groupItem)
return;
int itemCounts = groupItem->childCount();
if (!itemCounts)
return;
QList <qlonglong> *list = new QList <qlonglong>;
for (int i = 0; i < itemCounts; i++)
{
QTreeWidgetItem *tmpItem = groupItem->child(i);
if (!tmpItem)
continue;
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (ac_info && ac_info->accountID)
list->append(ac_info->accountID);
}
db_SaveRecentlyContactAccountToDB(list);
if (list)
delete list;
}
/**************************************************************************/
/* */
/**************************************************************************/
QTreeWidgetItem *BuddyOpt::findAccountItemFromGroup(QTreeWidgetItem *groupItem,
const Fetion_Account *account)
{
if (!groupItem || !account)
{
return NULL;
}
QTreeWidgetItem *tmpItem = NULL;
qlonglong account_id = (qlonglong)account->id;
int itemCounts = groupItem->childCount();
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (ac_info && account_id == ac_info->accountID)
{
return tmpItem;
}
}
return NULL;
}
/**************************************************************************/
/* */
/**************************************************************************/
QTreeWidgetItem *BuddyOpt::findAccountItem(const Fetion_Account *account)
{
if (!account)
{
return NULL;
}
int group_no = fx_get_account_group_id(account);
if (group_no <= 0)
{
group_no = 0;
}
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
return findAccountItemFromGroup(groupItem, account);
}
// return false should not changed
// true should changed
// state is 0 sub the online number
// is 1 add the online number
bool BuddyOpt::isOnlineStateChanged(int old_state, int new_state, int *state)
{
if (old_state == new_state)
{
return false;
}
if (fx_is_online_status(old_state))
//old_state is online state
{
if (!fx_is_online_status(new_state))
{
//new state is offline state
*state = 0;
return true;
}
}
else
{
//old_state is offline state
if (fx_is_online_status(new_state))
{
//new state is online state
*state = 1;
return true;
}
}
return false;
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::updateAccountInfo(const Fetion_Account *account)
{
if (!account)
return;
if (account->id == strtol(fx_get_usr_uid(), NULL, 10))
return;
QTreeWidgetItem *accountItem = findAccountItem(account);
//not find this account, so add it to Group...
if (!accountItem)
{
printf("not find the item , i will add to the group\n");
addAccountToGroup(account);
return ;
}
updateAccountInfo_RecentlyContactGroup(account);
//update the account info
setTipsOfAccount(accountItem, account);
char *showname = fx_get_account_show_name_with_state(account, TRUE, TRUE);
QString show_name = QString::fromUtf8(showname);
if (showname)
{
free(showname);
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(accountItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = accountItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
return ;
}
ac_info->accountName = show_name;
int old_online_state = ac_info->onlinestate;
ac_info->onlinestate = fx_get_online_status_by_account(account);
accountItem->setText(0, show_name);
accountItem->setIcon(0, getOnlineStatusIcon(ac_info->onlinestate));
//group name ++1
int group_no = fx_get_account_group_id(account);
if (group_no <= 0)
{
group_no = 0;
}
QTreeWidgetItem *groupItem = findGroupItemByID(group_no);
if (!groupItem)
return;
int state = 0;
if (isOnlineStateChanged(old_online_state, ac_info->onlinestate, &state))
{
#if MS_VC6
Group_Info *group_info = (Group_Info*)(groupItem->data(0, Qt
::UserRole).toUInt());
#else
Group_Info *group_info = groupItem->data(0, Qt::UserRole).value
< Group_Info * > ();
#endif
if (!group_info)
{
return ;
}
groupItem->removeChild(accountItem);
//if (groupItem->childCount() == 0)
if (group_info->online_no - 1 > 0)
{
groupItem->insertChild(group_info->online_no - 1, accountItem);
}
else
{
groupItem->insertChild(0, accountItem);
}
if (state)
{
group_info->online_no++;
}
else
{
group_info->online_no--;
}
#ifdef WIN32
char online[30];
_snprintf(online, sizeof(online) - 1, "(%d/%d)", group_info
->online_no, groupItem->childCount());
QString groupShowName = group_info->groupName + online;
#else
char *online = NULL;
asprintf(&online, "(%d/%d)", group_info->online_no, groupItem
->childCount());
QString groupShowName = group_info->groupName + online;
if (online)
{
free(online);
}
#endif
groupItem->setText(0, groupShowName);
}
if (!fx_is_auth_chat_by_account(account))
{
groupItem->removeChild(accountItem);
groupItem->insertChild(groupItem->childCount(), accountItem);
}
printf("Updata new buddy.... \n");
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::updateStyles(QTreeWidgetItem *item, int column)
{
if (!item || column != 0)
{
return ;
}
Qt::CheckState state = item->checkState(0);
QTreeWidgetItem *parent = item->parent();
if (parent)
{
// Only count style items.
if (state == Qt::Checked)
{
++markedCount;
}
else
{
--markedCount;
}
/*
//bad code...
if (markedCount > 32)
return;
*/
if (state == Qt::Checked && parent->checkState(0) == Qt::Unchecked)
{
// Mark parent items when child items are checked.
parent->setCheckState(0, Qt::Checked);
}
else if (state == Qt::Unchecked && parent->checkState(0) == Qt::Checked)
{
bool marked = false;
for (int row = 0; row < parent->childCount(); ++row)
{
if (parent->child(row)->checkState(0) == Qt::Checked)
{
marked = true;
break;
}
}
// Unmark parent items when all child items are unchecked.
if (!marked)
{
parent->setCheckState(0, Qt::Unchecked);
}
}
}
else
{
int row;
int number = 0;
for (row = 0; row < item->childCount(); ++row)
{
if (item->child(row)->checkState(0) == Qt::Checked)
{
++number;
}
}
// Mark/unmark all child items when marking/unmarking top-level
// items.
if (state == Qt::Checked && number == 0)
{
for (row = 0; row < item->childCount(); ++row)
{
if (item->child(row)->checkState(0) == Qt::Unchecked)
{
item->child(row)->setCheckState(0, Qt::Checked);
}
}
}
else if (state == Qt::Unchecked && number > 0)
{
for (row = 0; row < item->childCount(); ++row)
{
if (item->child(row)->checkState(0) == Qt::Checked)
{
item->child(row)->setCheckState(0, Qt::Unchecked);
}
}
}
}
emit m_itemChanged();
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::UpdateSkins()
{
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return ;
}
QTreeWidgetItem *groupItem = NULL;
int GroupCount = RootItem->childCount();
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem)
{
continue;
}
if (isQunItem(groupItem))
{
UpdateSkinsForQun(groupItem);
continue;
}
//update all account icon for this group
UpdateSkinsForAccount(groupItem);
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::UpdateSkinsForAccount(QTreeWidgetItem *groupItem)
{
if (!groupItem)
{
return ;
}
int itemCounts = groupItem->childCount();
QTreeWidgetItem *tmpItem = NULL;
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
continue;
}
tmpItem->setIcon(0, getOnlineStatusIcon(ac_info->onlinestate));
}
}
/**************************************************************************/
/* */
/**************************************************************************/
void BuddyOpt::UpdateSkinsForQun(QTreeWidgetItem *groupItem)
{
if (!groupItem)
{
return ;
}
QTreeWidgetItem *tmpItem = NULL;
int itemCounts = groupItem->childCount();
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
tmpItem->setIcon(0, getQunIcon());
}
}
/**************************************************************************/
/* */
/**************************************************************************/
Account_Info *BuddyOpt::fetchNoUpdateAccount()
{
QTreeWidgetItem *RootItem = this->treeWidget->invisibleRootItem();
if (!RootItem)
{
return NULL;
}
int GroupCount = RootItem->childCount();
QTreeWidgetItem *groupItem = NULL;
for (int i = 0; i < GroupCount; i++)
{
groupItem = RootItem->child(i);
if (!groupItem || isQunItem(groupItem))
{
continue;
}
int itemCounts = groupItem->childCount();
QTreeWidgetItem *tmpItem = NULL;
for (int i = 0; i < itemCounts; i++)
{
tmpItem = groupItem->child(i);
if (!tmpItem)
{
continue;
}
#if MS_VC6
Account_Info *ac_info = (Account_Info*)(tmpItem->data(0, Qt
::UserRole).toUInt());
#else
Account_Info *ac_info = tmpItem->data(0, Qt::UserRole).value <
Account_Info * > ();
#endif
if (!ac_info)
{
continue;
}
if (!ac_info->haveUpdate)
{
return ac_info;
}
}
}
return NULL;
}
| [
"alsor.zhou@3dff0f8e-6350-0410-ad39-8374e07577ec",
"libfetion@3dff0f8e-6350-0410-ad39-8374e07577ec",
"[email protected]@3dff0f8e-6350-0410-ad39-8374e07577ec"
] | [
[
[
1,
24
],
[
28,
34
],
[
36,
53
],
[
65,
556
],
[
558,
561
],
[
568,
573
],
[
575,
593
],
[
595,
598
],
[
605,
616
],
[
636,
667
],
[
671,
791
],
[
793,
802
],
[
805,
863
],
[
870,
912
],
[
1197,
1267
],
[
1270,
1271
],
[
1273,
1281
],
[
1283,
1295
],
[
1297,
1298
],
[
1300,
1300
],
[
1304,
1313
],
[
1316,
1318
],
[
1320,
1339
],
[
1341,
1353
],
[
1356,
1356
],
[
1411,
1411
],
[
1417,
1661
]
],
[
[
25,
27
],
[
35,
35
],
[
54,
64
],
[
557,
557
],
[
562,
567
],
[
574,
574
],
[
594,
594
],
[
599,
604
],
[
617,
635
],
[
668,
670
],
[
792,
792
],
[
803,
804
],
[
864,
869
],
[
913,
1196
],
[
1268,
1269
],
[
1272,
1272
],
[
1282,
1282
],
[
1296,
1296
],
[
1299,
1299
],
[
1302,
1302
],
[
1314,
1315
],
[
1319,
1319
],
[
1340,
1340
],
[
1354,
1355
],
[
1357,
1410
],
[
1412,
1416
]
],
[
[
1301,
1301
],
[
1303,
1303
]
]
] |
54c3e633468f41d3df903ee4f7144f8ef003240a | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /Labs 3 & 5/Lab05.cpp | 4cc8989fee8cff888a3847d08b210d888fa58e64 | [] | no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,232 | cpp | #include <iostream>
#include "Lab05.h"
using namespace std;
LinkedList::LinkedList()
{
// Place implementation for constructor here.
}
LinkedList::~LinkedList()
{
// Place implementation for destructor here.
}
void LinkedList::AddStudents()
{
unsigned int dNumStudents;
cout << "How many students are in the group? ";
cin >> dNumStudents;
for (int i = 0; i < dNumStudents; i++)
{
Node *tmpNode;
tmpNode = new(Node);
cout << "Enter first name of student #" << i << ": ";
cin >> tmpNode->StudentName;
tmpNode->next = NULL;
AddNodeToList(tmpNode);
}
}
void LinkedList::ChooseStudent()
{
unsigned int dSkipVal;
cout << "Enter a non-negative integer: ";
cin >> dSkipVal;
// insert code here to randomly select starting place
while (m_dNumNodes > 1 && m_Head != NULL)
{
int i = dSkipVal;
Node *nodePtr = m_Head;
while (i > 0)
{
nodePtr = nodePtr->next;
i--;
}
cout << "Removing " << nodePtr->StudentName << " from the group." << endl;
DeleteNodeFromList(nodePtr);
cout << "The current group contains:" << endl;
PrintList();
}
cout << endl << "The unlucky student is: ";
PrintList();
cout << endl;
}
void LinkedList::PrintList()
{
// Place implementation of PrintList here.
}
void LinkedList::AddNodeToEmptyList(Node *newNode)
// Precondition: The linked list is empty.
// Postcondition: The linked list contains only newNode; newNode->next
// points to itself; head and tail point to newNode,
// numNodes == 1
{
// Place implementation of AddNodeToEmptyList here.
}
void LinkedList::AddNodeToList(Node *newNode)
// Precondition: newNode is a node to add to the circularly
// linked list.
// Poscondition: newNode has been added to the list.
{
// Place implementation of AddNodeToList here.
}
void LinkedList::DeleteNodeFromList(Node *nodePtr)
// Precondition: nodePtr points to a node in the linked list.
// Postcondition: The node pointed to by nodePtr is no longer
// in the linked list, and its memory has been
// returned to the heap.
{
// Place implementation of DeleteNodeFromList here.
}
| [
"[email protected]"
] | [
[
[
1,
97
]
]
] |
199a1004afe7136f649cd691e6e19097272c37e7 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SERenderers/SE_OpenGL_Renderer/SEOpenGLRendering/SEWglRenderer.h | ac697ccf51e8cffa27ace085fa2cabfdaad6a48a | [] | 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 | GB18030 | C++ | false | false | 2,630 | 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_Wgl_Renderer_H
#define Swing_Wgl_Renderer_H
#include "SEOpenGLRendererLIB.h"
#include "SEOpenGLRenderer.h"
#include "SEWglExtensions.h"
namespace Swing
{
//----------------------------------------------------------------------------
// 说明:
// 作者:Sun Che
// 时间:20080920
//----------------------------------------------------------------------------
class SE_RENDERER_API SEWglRenderer : public SEOpenGLRenderer
{
public:
// 构造函数被应用程序层第一次调用时,传入的pixel format将被忽略掉.
// 如果multisampling被开启,渲染器和窗体必须被释放掉,
// 然后利用支持multisampling的pixel format来重新创建渲染器和窗体.
// 从SEWglApplication.cpp可以查看这个程序流程.
SEWglRenderer(HWND hWnd, SEFrameBuffer::FormatType eFormat,
SEFrameBuffer::DepthType eDepth, SEFrameBuffer::StencilType eStencil,
SEFrameBuffer::BufferingType eBuffering,
SEFrameBuffer::MultisamplingType eMultisampling, int iWidth,
int iHeight, int iPixelFormat = 0);
virtual ~SEWglRenderer(void);
virtual void ToggleFullscreen(void);
virtual void DisplayBackBuffer(void);
virtual int LoadFont(const char* acFace, int iSize, bool bBold,
bool bItalic);
// 窗体参数.
HWND GetWindow(void){ return m_hWnd; }
HDC GetDC(void){ return m_hWindowDC; }
HGLRC GetRC(void){ return m_hWindowRC; }
protected:
// 窗体参数.
HWND m_hWnd;
HDC m_hWindowDC;
HGLRC m_hWindowRC;
HGDIOBJ m_hOldFont;
// 用于支持fullscreen/window
int m_iSaveWidth, m_iSaveHeight;
};
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
74
]
]
] |
7becba8980f438553166842f98873e7ad7fd7585 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aosdesigner/view/ProjectView.hpp | 212c178b943a01207f9540c7b94e91dbd0199cfe | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | hpp | #ifndef HGUARD_AOSD_VIEW_PROJECTVIEW_HPP__
#define HGUARD_AOSD_VIEW_PROJECTVIEW_HPP__
#pragma once
#include <memory>
#include <QDockWidget>
class QTabWidget;
namespace aosd
{
namespace core { class Project; }
namespace view
{
class SequenceListView;
/** Display the basic informations about a Project and the Sequences it contains.
Allows edition of those informations.
*/
class ProjectView
: public QDockWidget
{
Q_OBJECT
public:
ProjectView();
~ProjectView();
private slots:
void react_project_open( const core::Project& );
void react_project_closed( const core::Project& );
private:
/// Tabs with different views of the informations of this project.
std::unique_ptr<QTabWidget> m_tabs;
};
}
}
#endif
| [
"klaim@localhost"
] | [
[
[
1,
49
]
]
] |
60c7e79b40c025ae9914b9a2ad996d8d0b5ecceb | dc4f8d571e2ed32f9489bafb00b420ca278121c6 | /mojo_engine/cDlgCursorBlind.cpp | c23d435b65069aac7b26613af768640e1e107be1 | [] | no_license | mwiemarc/mojoware | a65eaa4ec5f6130425d2a1e489e8bda4f6f88ec0 | 168a2d3a9f87e6c585bde4a69b97db53f72deb7f | refs/heads/master | 2021-01-11T20:11:30.945122 | 2010-01-25T00:27:47 | 2010-01-25T00:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,537 | cpp | /*************************************************************************************************
/*
/* cDlgCursorBlind.cpp
/*
/* started October 19, 2008
/*
/*************************************************************************************************/
#include "stdafx.h"
#include "cDlgCursorBlind.h"
//===============================================================================================
// DATA
//===============================================================================================
//===============================================================================================
// PROTOTYPES
//===============================================================================================
//===============================================================================================
// CODE
//===============================================================================================
//----------------------------------------------------------------------------------------------
// DIALOG PROC
//----------------------------------------------------------------------------------------------
INT_PTR CALLBACK cDlgCursorBlind::dialog_proc (HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
cWin * pWin = user_data_to_pWin ( hwnd );
cDlgCursorBlind * pThis = static_cast<cDlgCursorBlind*>(pWin);
switch ( uMessage )
{
case WM_ERASEBKGND:
return 1;
}
return cDlg::dialog_proc ( hwnd, uMessage, wParam, lParam );
}
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
5cee3d68986aaebbc5cb1cb84e36095099116c29 | 81215fde203e75b157f2a3e3507d99897c6d2020 | /src/conodegraphicsitem.cpp | 65170184b2716e42a0d41e55e79ec9e872b58041 | [] | no_license | fuyasing/RankView | fb8e039843088a54da2ad10979726234ea467712 | b4d99cdfa03699ec41f8581db9262a367306b5a4 | refs/heads/master | 2020-05-17T10:58:47.709718 | 2011-06-25T14:05:05 | 2011-06-25T14:05:05 | 1,738,411 | 0 | 1 | null | 2012-08-04T14:49:30 | 2011-05-12T13:31:00 | C++ | UTF-8 | C++ | false | false | 3,036 | cpp | #include "conodegraphicsitem.h"
#include "colinegraphicsitem.h"
#include "graphics.h"
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QRectF>
#include <QPainterPath>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsWidget>
CoNodeGraphicsItem::CoNodeGraphicsItem()
{
this->m_dataX = 0;
this->m_dataY = 0;
this->m_color = QColor(Qt::black);
this->m_examName = "";
this->m_ranks = QHash<QString, int>();
this->m_lineList = QList<CoLineGraphicsItem *>();
}
CoNodeGraphicsItem::CoNodeGraphicsItem(const QColor color, const QString examName, const int x, const int y, QHash<QString, int> ranks)
{
this->m_dataX = x;
this->m_dataY = y * 10 + 50;
this->m_tRank = y;
this->setPos(m_dataX, m_dataY);
this->m_color = color;
this->m_examName = examName;
this->m_ranks = ranks;
this->setFlags(ItemIsSelectable);
this->setAcceptHoverEvents(true);
this->setAcceptedMouseButtons(0);
}
void CoNodeGraphicsItem::addLine(CoLineGraphicsItem *line)
{
m_lineList << line;
}
QList<CoLineGraphicsItem *> CoNodeGraphicsItem::lines() const
{
return m_lineList;
}
QRectF CoNodeGraphicsItem::boundingRect() const
{
return QRectF(0,0,20,20);
}
QPainterPath CoNodeGraphicsItem::shape() const
{
QPainterPath path;
path.addEllipse(boundingRect());
return path;
}
void CoNodeGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget */*widget*/)
{
QColor fillColor = m_color;
painter->setBrush(QBrush(fillColor.darker(option->state&QStyle::State_Sunken ? 120 : 100)));
QPainterPath path = shape();
painter->drawPath(path);
QRectF rankRect(0, -20, 20, 20);
QRectF textRect(0, 550-m_dataY, 200, 100);
QFont font = painter->font();
font.setBold(0);
font.setPointSize(14);
painter->setFont(font);
painter->setPen(Qt::black);
painter->drawText(rankRect, QString(QString("%1")).arg(m_tRank));
painter->drawText(textRect, m_examName);
QLineF line(boundingRect().width()/2, boundingRect().height()/2, boundingRect().width()/2, 550 - m_dataY);
// QLineF line(m_sourcePoint,m_destPoint);
if (qFuzzyCompare(line.length(), qreal(0.)))
return;
painter->setPen(QPen(Qt::gray,1,Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));
painter->drawLine(line);
painter->save();
painter->scale(scaleFactor,scaleFactor);
painter->restore();
}
const QHash<QString, int> CoNodeGraphicsItem::getRanks() const
{
return m_ranks;
}
void CoNodeGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
emit nodeMouseEnter(m_dataX, m_dataY, m_ranks);
// QGraphicsItem::hoverEnterEvent(event);
// update();
}
void CoNodeGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
emit nodeMouseLeave();
// QGraphicsItem::hoverLeaveEvent(event);
// update();
}
| [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
e98ec60d096b84599518dd0084c50d21eba1a191 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/test/Logger.cpp | 63952ba29ce8a49a6ce923a3dee2eaf8ee8e2fb2 | [] | no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,084 | cpp | #include "Logger.h"
using namespace Test;
Logger::Logger(const char* filename)
{
SetLoggingLevel(Verbose);
m_logTimer.reset();
m_outFile.open(filename, ios_base::out);
}
Logger::~Logger()
{
m_outFile.close();
}
wstring Logger::wFormat(const wchar_t *format, ...)
{
wstring res(L"");
va_list args;
va_start(args, format);
size_t len = _vscwprintf(format, args);
res.resize(len+1);
wchar_t *buf = (wchar_t*)res.c_str();
vswprintf_s(buf, len+2, format, args);
return res.c_str();
}
wstring Logger::wvFormat(const wchar_t *format, va_list args)
{
wstring res(L"");
size_t len = _vscwprintf(format, args);
res.resize(len+2);
wchar_t* buf = (wchar_t*)res.c_str();
vswprintf_s(buf, len+2, format, args);
return res.c_str();
}
void Logger::WriteLine(LoggingLevel level, const wchar_t* fmt, ...)
{
// Don't log unneccessary stuff
if (level < m_logLevel)
return;
if (level == Error) {
const wchar_t errorString[] = L"ERROR";
m_outFile.write(errorString, wcslen(errorString));
}
// We're good, dump it out
va_list args;
va_start(args,fmt);
// Dump the time
wstring time, s;
double t = m_logTimer.getTime();
time = wFormat(L"%4.3f", t);
// Dump the actual log
s = wvFormat(fmt, args);
s = wFormat(L"%s", s.c_str());
m_outFile << setiosflags(ios::left);
m_outFile << setw(10) << time << s << endl;
m_outFile.flush();
}
void Logger::Write(LoggingLevel level, const wchar_t* fmt, ...)
{
// Don't log unneccessary stuff
if (level < m_logLevel)
return;
if (level == Error) {
const wchar_t errorString[] = L"ERROR";
m_outFile.write(errorString, wcslen(errorString));
}
// We're good, dump it out
va_list args;
va_start(args,fmt);
wstring s;
// Dump the actual log
s = wvFormat(fmt, args);
s = wFormat(L"%s", s.c_str());
m_outFile << setiosflags(ios::left);
m_outFile << s;
}
void Logger::SetLoggingLevel(LoggingLevel level)
{
m_logLevel = level;
}
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
] | [
[
[
1,
103
]
]
] |
2c4a1baf1f737dfb723d285201b85b0743190123 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/mangalore/msg/gfxaddskin.cc | bb5bf8a92537b2647804b5a65b368404ec8529cd | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | cc | //------------------------------------------------------------------------------
// msg/gfxaddskin.cc
// (C) 2006 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "msg/gfxaddskin.h"
namespace Message
{
ImplementRtti(Message::GfxAddSkin, Message::Msg);
ImplementFactory(Message::GfxAddSkin);
ImplementMsgId(GfxAddSkin);
} // namespace Message
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
12
]
]
] |
28c33b301dd426728d8e252704149733a4caa1a7 | 847cccd728e768dc801d541a2d1169ef562311cd | /src/Utils/Properties/AbstractProperty.cpp | 9cc7f33a1505ddc7fa34abddcff268a4c4c1b066 | [] | no_license | aadarshasubedi/Ocerus | 1bea105de9c78b741f3de445601f7dee07987b96 | 4920b99a89f52f991125c9ecfa7353925ea9603c | refs/heads/master | 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,648 | cpp | #include "Common.h"
#include "AbstractProperty.h"
#include "../../ResourceSystem/XMLOutput.h"
#include "../XMLConverter.h"
void AbstractProperty::ReportConvertProblem( ePropertyType wrongType ) const
{
ocError << "Can't convert property '" << GetName() << "' from '" << PropertyTypes::GetStringName(GetType()) << "' to '" << PropertyTypes::GetStringName(wrongType) << "'";
}
void AbstractProperty::ReportReadonlyProblem( void ) const
{
ocWarning << "Property '" << GetName() << "' is read-only";
}
void AbstractProperty::ReportWriteonlyProblem( void ) const
{
ocWarning << "Property '" << GetName() << "' is write-only";
}
string AbstractProperty::GetValueString(const Reflection::RTTIBaseClass* owner) const
{
switch (GetType())
{
// We generate cases for all property types and arrays of property types here.
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) case typeID: \
return StringConverter::ToString(GetValue<typeClass>(owner));
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) case typeID##_ARRAY: \
return StringConverter::ToString(GetValue<Array<typeClass>*>(owner));
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
default:
OC_NOT_REACHED();
}
return "";
}
void AbstractProperty::WriteValueXML(const RTTIBaseClass* owner, ResourceSystem::XMLOutput& output) const
{
switch (GetType())
{
// We generate cases for all property types and arrays of property types here.
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) case typeID: \
Utils::XMLConverter::WriteToXML(output, GetValue<typeClass>(owner)); break;
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) case typeID##_ARRAY: \
Utils::XMLConverter::WriteToXML(output, GetValue<Array<typeClass>*>(owner)); break;
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
default:
OC_NOT_REACHED();
}
}
void Reflection::AbstractProperty::SetValueFromString( RTTIBaseClass* owner, const string& str )
{
switch (GetType())
{
// We generate cases for all property types and arrays of property types here.
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) \
case typeID: \
SetValue(owner, StringConverter::FromString<typeClass>(str)); \
break;
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
default:
ocError << "Parsing property of type '" << PropertyTypes::GetStringName(GetType()) << "' from string is not implemented.";
}
}
template<typename T>
void ReadArrayValueXML(Reflection::AbstractProperty* prop, RTTIBaseClass* owner, ResourceSystem::XMLNodeIterator& input)
{
vector<T> vertices;
for (ResourceSystem::XMLNodeIterator vertIt = input.IterateChildren(); vertIt != input.EndChildren(); ++vertIt)
{
if ((*vertIt).compare("Item") == 0) { vertices.push_back(Utils::XMLConverter::ReadFromXML<T>(vertIt)); }
else ocError << "XML:Entity: Expected 'Item', found '" << *vertIt << "'";
}
Array<T> vertArray(vertices.size());
for (uint32 i=0; i<vertices.size(); ++i)
{
vertArray[i] = vertices[i];
}
prop->SetValue<Array<T>*>(owner, &vertArray);
}
void Reflection::AbstractProperty::ReadValueXML(RTTIBaseClass* owner, ResourceSystem::XMLNodeIterator& input)
{
switch (GetType())
{
// We generate cases for all property types and arrays of property types here.
#define SCRIPT_ONLY
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) \
case typeID: \
SetValue<typeClass>(owner, Utils::XMLConverter::ReadFromXML<typeClass>(input)); \
break;
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
#define PROPERTY_TYPE(typeID, typeClass, defaultValue, typeName, scriptSetter, cloning) \
case typeID##_ARRAY: \
ReadArrayValueXML<typeClass>(this, owner, input); \
break;
#include "Utils/Properties/PropertyTypes.h"
#undef PROPERTY_TYPE
#undef SCRIPT_ONLY
case PT_RESOURCE:
SetValue<ResourceSystem::ResourcePtr>(owner, Utils::XMLConverter::ReadFromXML<ResourceSystem::ResourcePtr>(input));
break;
case PT_RESOURCE_ARRAY:
ReadArrayValueXML<ResourceSystem::ResourcePtr>(this, owner, input);
break;
default:
ocError << "Parsing property of type '" << PropertyTypes::GetStringName(GetType()) << "' from XML is not implemented.";
}
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
5,
21
],
[
27,
27
],
[
32,
32
],
[
48,
48
],
[
53,
53
],
[
63,
64
],
[
66,
66
],
[
68,
68
],
[
71,
71
],
[
75,
75
],
[
104,
104
],
[
111,
111
],
[
119,
119
],
[
126,
126
]
],
[
[
3,
4
],
[
43,
47
],
[
49,
52
],
[
54,
62
],
[
76,
76
],
[
79,
103
],
[
105,
110
],
[
112,
118
],
[
122,
125
],
[
127,
130
]
],
[
[
22,
26
],
[
28,
31
],
[
33,
42
],
[
65,
65
],
[
67,
67
],
[
69,
70
],
[
72,
74
],
[
77,
78
],
[
120,
121
]
]
] |
40ead311219625a0b4e1da0071bee8242b181832 | 8eee4b8f879a829a01b7859538129828f6e1f9a4 | /src/Application/Application.cpp | c59d27b5694dfc543199b61b740079ae8f31aab4 | [] | no_license | mperepelkin/GameTest | 32d53220a1c66dafa5253036cc021c1f5dba0da9 | 9b91bb455f45d9ba5d69551436923d45712166f1 | refs/heads/master | 2016-09-05T10:52:31.770611 | 2011-05-01T18:50:58 | 2011-05-01T18:50:58 | 1,688,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | cpp | /**
* Application implementation.
*/
#include "assert.h"
#include "stdio.h"
#include "Application.h"
#include "GlutHelper/GlutHelper.h"
#include "GlutHelper/RenderingData.h"
#include "BulletHelper/BulletHelper.h"
#include "Timers/Timer.h"
#include "globals.h"
namespace GameTest {
// Ctor.
Application::Application()
{
}
// Dtor.
Application::~Application()
{
}
// Creates the new application instance, asserts if called more than once.
Application* Application::createInstance()
{
static Application* instance = NULL;
assert(NULL == instance);
instance = new Application();
return instance;
}
// Initializes the application and all subsystems.
void Application::init(int argc, char *argv[])
{
GTimer->init();
GBulletHelper->init();
GGlutHelper->init(argc, argv);
//GBulletHelper->addBox(btVector3(0.f, 0.f, 0.f), btVector3(0.1f, 0.1f, 0.1f), 1.f);
GBulletHelper->debugMethod();
}
// Updates the application and all subsystems.
void Application::update()
{
float dTime = GTimer->update();
GBulletHelper->update(dTime);
}
}
| [
"mperepelkin@.(none)"
] | [
[
[
1,
55
]
]
] |
257b3c09db0bd82c3590ebd3aa5d24b2e12127f2 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/tlclasses/_CLinkedListNode.h | 8bdf997b20929f693e65397edf81296e5c4be499 | [] | no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | h | #pragma once
namespace TLAPI {
#pragma pack(1)
struct LinkedListNode {
CBaseUnit* pCBaseUnit;
LinkedListNode* pNext;
LinkedListNode* pPrev;
};
#pragma pack()
};
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
] | [
[
[
1,
15
]
]
] |
5c4f5cc2621c68f8d7edd77f0ea7cfa87e91c040 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/cmd_line_parser/cmd_line_parser_kernel_abstract.h | a2f0204067c905df544142ac84aab302b3da75ed | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | 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 | 12,086 | h | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_CMD_LINE_PARSER_KERNEl_ABSTRACT_
#ifdef DLIB_CMD_LINE_PARSER_KERNEl_ABSTRACT_
#include "../algs.h"
#include <string>
#include "../interfaces/enumerable.h"
#include "../interfaces/cmd_line_parser_option.h"
namespace dlib
{
template <
typename charT
>
class cmd_line_parser : public enumerable<cmd_line_parser_option<charT> >
{
/*!
REQUIREMENTS ON charT
Must be an integral type suitable for storing characters. (e.g. char
or wchar_t)
INITIAL VALUE
parsed_line() == false
option_is_defined(x) == false, for all values of x
ENUMERATION ORDER
The enumerator will enumerate over all the options defined in *this
in alphebetical order according to the name of the option.
POINTERS AND REFERENCES TO INTERNAL DATA
parsed_line(), option_is_defined(), option(), number_of_arguments(),
operator[](), and swap() functions do not invalidate pointers or
references to internal data. All other functions have no such guarantee.
WHAT THIS OBJECT REPRESENTS
This object represents a command line parser.
The command lines must match the following BNF.
command_line ::= <program_name> { <options> | <arg> } [ -- {<word>} ]
program_name ::= <word>
arg ::= any <word> that does not start with -
option_arg ::= <sword>
option_name ::= <char>
long_option_name ::= <char> {<char> | - }
options ::= <bword> - <option_name> {<option_name>} {<option_arg>} |
<bword> -- <long_option_name> [=<option_arg>] {<bword> <option_arg>}
char ::= any character other than - or =
word ::= any string from argv where argv is the second
parameter to main()
sword ::= any suffix of a string from argv where argv is the
second parameter to main()
bword ::= This is an empty string which denotes the begining of a
<word>.
Options with arguments:
An option with N arguments will consider the next N swords to be
its arguments.
so for example, if we have an option o that expects 2 arguments
then the following are a few legal examples:
program -o arg1 arg2 general_argument
program -oarg1 arg2 general_argument
arg1 and arg2 are associated with the option o and general_argument
is not.
Arguments not associated with an option:
An argument that is not associated with an option is considered a
general command line argument and is indexed by operator[] defined
by the cmd_line_parser object. Additionally, if the string
"--" appears in the command line all by itself then all words
following it are considered to be general command line arguments.
Consider the following two examples involving a command line and
a cmd_line_parser object called parser.
Example 1:
command line: program general_arg1 -o arg1 arg2 general_arg2
Then the following is true (assuming the o option is defined
and takes 2 arguments).
parser[0] == "general_arg1"
parser[1] == "general_arg2"
parser.number_of_arguments() == 2
parser.option("o").argument(0) == "arg1"
parser.option("o").argument(1) == "arg2"
parser.option("o").count() == 1
Example 2:
command line: program general_arg1 -- -o arg1 arg2 general_arg2
Then the following is true (the -- causes everything following
it to be treated as a general argument).
parser[0] == "general_arg1"
parser[1] == "-o"
parser[2] == "arg1"
parser[3] == "arg2"
parser[4] == "general_arg2"
parser.number_of_arguments() == 5
parser.option("o").count() == 0
!*/
public:
typedef charT char_type;
typedef std::basic_string<charT> string_type;
typedef cmd_line_parser_option<charT> option_type;
// exception class
class cmd_line_parse_error : public dlib::error
{
/*!
GENERAL
This exception is thrown if there is an error detected in a
command line while it is being parsed. You can consult this
object's type and item members to determine the nature of the
error. (note that the type member is inherited from dlib::error).
INTERPRETING THIS EXCEPTION
- if (type == EINVALID_OPTION) then
- There was an undefined option on the command line
- item == The invalid option that was on the command line
- if (type == ETOO_FEW_ARGS) then
- An option was given on the command line but it was not
supplied with the required number of arguments.
- item == The name of this option.
- num == The number of arguments expected by this option.
- if (type == ETOO_MANY_ARGS) then
- An option was given on the command line such as --option=arg
but this option doesn't take any arguments.
- item == The name of this option.
!*/
public:
const std::basic_string<charT> item;
const unsigned long num;
};
// --------------------------
cmd_line_parser (
);
/*!
ensures
- #*this is properly initialized
throws
- std::bad_alloc
!*/
virtual ~cmd_line_parser (
);
/*!
ensures
- all memory associated with *this has been released
!*/
void clear(
);
/*!
ensures
- #*this has its initial value
throws
- std::bad_alloc
if this exception is thrown then #*this is unusable
until clear() is called and succeeds
!*/
void parse (
int argc,
const charT** argv
);
/*!
requires
- argv == an array of strings that was obtained from the second argument
of the function main().
(i.e. argv[0] should be the <program> token, argv[1] should be
an <options> or <arg> token, etc...)
- argc == the number of strings in argv
ensures
- parses the command line given by argc and argv
- #parsed_line() == true
- #at_start() == true
throws
- std::bad_alloc
if this exception is thrown then #*this is unusable until clear()
is called successfully
- cmd_line_parse_error
This exception is thrown if there is an error parsing the command line.
If this exception is thrown then #parsed_line() == false and all
options will have their count() set to 0 but otherwise there will
be no effect (i.e. all registered options will remain registered).
!*/
void parse (
int argc,
charT** argv
);
/*!
This just calls this->parse(argc,argv) and performs the necessary const_cast
on argv.
!*/
bool parsed_line(
) const;
/*!
ensures
- returns true if parse() has been called successfully
- returns false otherwise
!*/
bool option_is_defined (
const string_type& name
) const;
/*!
ensures
- returns true if the option has been added to the parser object
by calling add_option(name).
- returns false otherwise
!*/
void add_option (
const string_type& name,
const string_type& description,
unsigned long number_of_arguments = 0
);
/*!
requires
- parsed_line() == false
- option_is_defined(name) == false
- name does not contain any ' ', '\t', '\n', or '=' characters
- name[0] != '-'
- name.size() > 0
ensures
- #option_is_defined(name) == true
- #at_start() == true
- #option(name).count() == 0
- #option(name).description() == description
- #option(name).number_of_arguments() == number_of_arguments
throws
- std::bad_alloc
if this exception is thrown then the add_option() function has no
effect
!*/
const option_type& option (
const string_type& name
) const;
/*!
requires
- option_is_defined(name) == true
ensures
- returns the option specified by name
!*/
unsigned long number_of_arguments(
) const;
/*!
requires
- parsed_line() == true
ensures
- returns the number of arguments present in the command line.
This count does not include options or their arguments. Only
arguments unrelated to any option are counted.
!*/
const string_type& operator[] (
unsigned long N
) const;
/*!
requires
- parsed_line() == true
- N < number_of_arguments()
ensures
- returns the Nth command line argument
!*/
void swap (
cmd_line_parser& item
);
/*!
ensures
- swaps *this and item
!*/
private:
// restricted functions
cmd_line_parser(cmd_line_parser&); // copy constructor
cmd_line_parser& operator=(cmd_line_parser&); // assignment operator
};
template <
typename charT
>
inline void swap (
cmd_line_parser<charT>& a,
cmd_line_parser<charT>& b
) { a.swap(b); }
/*!
provides a global swap function
!*/
}
#endif // DLIB_CMD_LINE_PARSER_KERNEl_ABSTRACT_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
314
]
]
] |
66685b55d68baf8884bd84b33b9f645a142d6669 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/CompilerSource/general/implicit_stack.h | 515fa0ab7c86c158cd4058eec34e01fe2e7c3d90 | [] | no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,353 | h | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA 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, version 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
#include <stdlib.h>
template <typename atype>
struct implicit_stack
{
atype* safety;
atype** astack;
unsigned int ind, allocd;
void push()
{
ind++;
if (allocd<=ind)
{
int olds=allocd;
while (allocd<=ind) allocd<<=1;
atype** nar=new atype*[allocd];
if (nar==0)
{
ind--;
allocd=olds;
return;
}
if (olds>0)
{
memcpy(nar,astack,olds*sizeof(atype*));
for (unsigned int i=olds;i<allocd;i++) nar[i]=0;
}
delete []astack;
astack=nar;
}
if (astack[ind]==0) astack[ind]=new atype;
if (astack[ind]==0) ind--;
}
void pop()
{
delete astack[ind];
astack[ind]=0;
ind--;
}
atype &operator() ()
{
return *astack[ind];
}
implicit_stack()
{
ind=0;
safety = new atype;
astack=new atype*[1];
allocd=astack!=NULL;
if (safety==0 or allocd==0) exit(-18);
astack[0]=new atype;
if (astack[0]==0) exit(-18);
}
~implicit_stack()
{
if (astack != 0)
for (unsigned int i=0; i<ind; i++)
delete astack[i];
}
};
| [
"[email protected]"
] | [
[
[
1,
91
]
]
] |
c4861e35ca12bff644b680b2f2ffad26a3d90238 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch09/Fig09_11_13/CreateAndDestroy.cpp | 6614c7079ccdce1088e960e128eedcad9c0772a2 | [] | no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,951 | cpp | // Fig. 9.12: CreateAndDestroy.cpp
// CreateAndDestroy class member-function definitions.
#include <iostream>
using std::cout;
using std::endl;
#include "CreateAndDestroy.h" // include CreateAndDestroy class definition
// constructor
CreateAndDestroy::CreateAndDestroy( int ID, string messageString )
{
objectID = ID; // set object's ID number
message = messageString; // set object's descriptive message
cout << "Object " << objectID << " constructor runs "
<< message << endl;
} // end CreateAndDestroy constructor
// destructor
CreateAndDestroy::~CreateAndDestroy()
{
// output newline for certain objects; helps readability
cout << ( objectID == 1 || objectID == 6 ? "\n" : "" );
cout << "Object " << objectID << " destructor runs "
<< message << endl;
} // end ~CreateAndDestroy destructor
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
1ba6fb026c29bf066cb1c8132f19c3d0550ae3e8 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/OEBase/OEXmlMgr_Impl.h | 7f2f95bee3551379649849320e7a77436186e6df | [] | no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | h | /*!
* \file OEXmlMgr_Impl.h
* \date 24-7-2009 16:28:03
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __OEXMLMGR_IMPL_H__
#define __OEXMLMGR_IMPL_H__
#include <OEBase/IOEXmlMgr.h>
class COEXmlMgr_Impl : public IOEXmlMgr
{
public:
RTTI_DEF(COEXmlMgr_Impl, IOEXmlMgr);
COEXmlMgr_Impl();
virtual ~COEXmlMgr_Impl();
virtual bool Initialize();
virtual void Terminate();
virtual IOEXmlDocument* CreateDocument();
virtual IOEXmlDocument* CreateDocument(const tstring& strFile);
virtual IOEXmlNode* CreateNode(const tstring& strName);
virtual IOEXmlAttribute* CreateAttribute(const tstring& strName);
private:
bool Init();
void Destroy();
};
#endif // __OEXMLMGR_IMPL_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
35
]
]
] |
8c8bbe1eb702df937e0d36831652e5c13de47439 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /os/AX_Thread_Adapter.cpp | 65fed4f89cfa3a73fb155fb93217fd23c68fb2e1 | [] | 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 | UTF-8 | C++ | false | false | 3,229 | cpp |
#include "AX_Thread_Adapter.h"
#include "AX_Thread_Manager.h"
//////////////////////////////////////////////////////////////////////////
AX_Base_Thread_Adapter::AX_Base_Thread_Adapter (
AX_THR_FUNC user_func,
void *arg,
AX_THR_C_FUNC entry_point,
AX_OS_Thread_Descriptor *td
#if defined (_WIN32)
, AX_SEH_EXCEPT_HANDLER selector
, AX_SEH_EXCEPT_HANDLER handler
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
)
: arg_ (arg)
, entry_point_ (entry_point)
, thr_desc_ (td)
{
user_func_ = user_func;
//printf ("ACE_Base_Thread_Adapter::ACE_Base_Thread_Adapter");
#ifdef ACE_USES_GPROF
getitimer (ITIMER_PROF, &itimer_);
#endif // ACE_USES_GPROF
}
AX_Base_Thread_Adapter::~AX_Base_Thread_Adapter (void)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AX_Thread_Adapter::AX_Thread_Adapter (
AX_THR_FUNC user_func,
void *arg,
AX_THR_C_FUNC entry_point,
//AX_Thread_Manager *thr_mgr,
AX_Thread_Descriptor *td,
AX_Thread_Exit *exit,
AX_Thread_Hook *hook
#ifdef _WIN32
, AX_SEH_EXCEPT_HANDLER selector
, AX_SEH_EXCEPT_HANDLER handler
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
)
:AX_Base_Thread_Adapter(
user_func
, arg
, entry_point
, td
#if defined (_WIN32)
, selector
, handler
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
)
//,thr_mgr_(thr_mgr)
,exit_(exit)
,hook_(hook)
{
//printf ("AX_Thread_Adapter::AX_Thread_Adapter");
}
AX_Thread_Adapter::AX_Thread_Adapter (
AX_THR_FUNC user_func,
void *arg,
AX_THR_C_FUNC entry_point,
//AX_Thread_Manager *thr_mgr,
AX_Thread_Descriptor *td
#ifdef _WIN32
, AX_SEH_EXCEPT_HANDLER selector
, AX_SEH_EXCEPT_HANDLER handler
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
)
:AX_Base_Thread_Adapter(
user_func
, arg
, entry_point
, td
#if defined (_WIN32)
, selector
, handler
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
)
//,thr_mgr_(thr_mgr)
{
//printf ("AX_Thread_Adapter::AX_Thread_Adapter");
}
AX_Thread_Adapter::~AX_Thread_Adapter (void)
{
}
AX_thr_func_return
AX_Thread_Adapter::invoke (void)
{
return this->invoke_i ();
}
AX_thr_func_return
AX_Thread_Adapter::invoke_i (void)
{
// Extract the arguments.
AX_THR_FUNC func = this->user_func_;
void *arg = this->arg_;
#if defined (ACE_WIN32) && defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0)
AX_OS_Thread_Descriptor *thr_desc = this->thr_desc_;
#endif /* ACE_WIN32 && ACE_HAS_MFC && (ACE_HAS_MFC != 0) */
delete this;
AX_thr_func_return status = 0;
//AX_Thread_Hook *hook =
// ACE_OS_Object_Manager::thread_hook ();
if (hook_)
{
// Invoke the start hook to give the user a chance to
// perform some initialization processing before the
// <func> is invoked.
status = hook_->start (func, arg);
}
else
{
// Call thread entry point.
#ifdef _WIN32
status = (DWORD)(*func) (arg);
#else
status = (*func) (arg);
#endif
}
if (exit_)
{
exit_->run();
}
return status;
} | [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
139
]
]
] |
400989e00cabea0eb65766bfeaa46c87514e5835 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/config/test/has_tr1_mem_fn_pass.cpp | 0818fb446896cea79df85ebc5df3f86752792c06 | [
"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 | 1,024 | cpp | // This file was automatically generated on Mon Jan 24 16:31:49 2005
// by libs/config/tools/generate.cpp
// Copyright John Maddock 2002-4.
// Use, modification and distribution are 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)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_HAS_TR1_MEM_FN
// This file should compile, if it does not then
// BOOST_HAS_TR1_MEM_FN should not be defined.
// See file boost_has_tr1_mem_fn.ipp for details
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_HAS_TR1_MEM_FN
#include "boost_has_tr1_mem_fn.ipp"
#else
namespace boost_has_tr1_mem_fn = empty_boost;
#endif
int main( int, char *[] )
{
return boost_has_tr1_mem_fn::test();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
34
]
]
] |
79af6c172302308f709f9c1e4dbc4aaace2b4e51 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/projects/src/libDI8.cpp | 63be92b15624d86ea0e8a302326d5ba08794d937 | [] | no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | cpp | // libDI8.cpp : Defines the entry point for the DLL application.
//
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Fusion.h>
#include "libDI8.h"
static int refcount = 0;
static bool first = true;
Fusion *fusion = NULL;
BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
return true;
}
//===============================
// Creates the DInputDeviceDB object
//===============================
LIBDI8_API void GetInstance(Fusion &f)
{
fusion = &f;
if(refcount++ == 0 && first == true)
{
f.Input = new DI8InputDeviceDB();
if(f.Input->Initialise() == false) delete f.Input;
first = false;
}
}
//===============================
// Destroys the DInputDeviceDB object
//===============================
LIBDI8_API void DestroyInstance(void)
{
if((--refcount) == 0){
delete fusion->Input;
fusion->Input = NULL;
}
}
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] | [
[
[
1,
44
]
]
] |
048694e0664af89a738eadd6dd87e5976725ce12 | 019f72b2dde7d0b9ab0568dc23ae7a0f4a41b2d1 | /jot/MyComboBox.h | eb1a34c81fbdaee240d7754924199d52cb653e61 | [] | no_license | beketa/jot-for-X01SC | 7bb74051f494172cb18b0f6afa5df055646eed25 | 5158fde188bec3aea4f5495da0dc5dfcd4c1663b | refs/heads/master | 2020-04-05T06:29:04.125514 | 2010-07-10T05:36:49 | 2010-07-10T05:36:49 | 1,416,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | h | //
// jot - Text Editor for Windows Mobile
// Copyright (C) 2007-2008, Aquamarine Networks. <http://pandora.sblo.jp/>
//
// This program is EveryOne's ware; you can redistribute it and/or modify it
// under the terms of the NYSL version 0.9982 or later. <http://www.kmonos.net/nysl/>
//
#pragma once
// CMyComboBox
class CMyComboBox : public CComboBox
{
DECLARE_DYNAMIC(CMyComboBox)
public:
CMyComboBox();
virtual ~CMyComboBox();
protected:
DECLARE_MESSAGE_MAP()
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnCbnEditchange();
};
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
182bdc2e18d137d26ec86e07f1eb1eb1cfa4d5ac | 314fa4d6839de9abfdedb72a521a156c06522761 | /Torso/TorsoView.cpp | f44791305120c950354f277f6b92bd529e5c2522 | [] | no_license | moonjuice/moonjuice | 7b87f5a36cc696dc232cb8257e91aa60a0b5cca8 | 262bbf8e3e487191160566adf0f28771bccb375e | refs/heads/master | 2021-01-10T20:33:50.474152 | 2011-11-24T00:52:29 | 2011-11-24T00:52:29 | 32,118,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,776 | cpp | // TorsoView.cpp : implementation of the CTorsoView class
//
#include "stdafx.h"
#include "Torso.h"
#include "TorsoDoc.h"
#include "TorsoView.h"
#include ".\torsoview.h"
#include <cmath>
#include <fstream>
//#include <cstdio>
#include <cmath>
//#include "DetailDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CTorsoView
IMPLEMENT_DYNCREATE(CTorsoView, COpenGLView)
BEGIN_MESSAGE_MAP(CTorsoView, COpenGLView)
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, COpenGLView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, COpenGLView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, COpenGLView::OnFilePrintPreview)
ON_WM_CHAR()
ON_COMMAND(ID_STRUCTURE_IMPORT, OnStructureImport)
ON_COMMAND(ID_STRUCTURE_V_LINES, OnStructureOutline)
ON_COMMAND(ID_STRUCTURE_IMAGECODING, OnStructureImagecoding)
ON_WM_MOUSEMOVE()
ON_COMMAND(ID_VIEW_VIEWALL, OnViewViewall)
ON_COMMAND(ID_STRUCTURE_LEG, OnStructureConnectLeg)
ON_COMMAND(ID_STRUCTURE_FILTER3, OnStructureUpperNeckL)
ON_COMMAND(ID_STRUCTURE_H_LINES, OnStructureHorizontalLines)
ON_WM_MOUSEWHEEL()
ON_COMMAND(ID_STRUCTURE_GRID, OnStructureGrid)
ON_COMMAND(ID_STRUCTURE_ROTATERAW, OnStructureRotateraw)
ON_COMMAND(ID_STRUCTURE_EXPORTHEAD, OnStructureExporthead)
ON_COMMAND(ID_STRUCTURE_SAVETMP, OnStructureSavetmp)
ON_COMMAND(ID_STRUCTURE_MIRROR, OnStructureMirror)
ON_COMMAND(ID_STRUCTURE_CONNECTARM, OnStructureConnectArm)
END_MESSAGE_MAP()
// CTorsoView construction/destruction
std::fstream& operator<<( std::fstream& os, MyMath::CVector& V );
CTorsoView::CTorsoView()
{
m_Size = 3;
this->m_bPerspective = false;
}
CTorsoView::~CTorsoView()
{
delete this->m_pRootNode;
}
BOOL CTorsoView::PreCreateWindow(CREATESTRUCT& cs)
{
return COpenGLView::PreCreateWindow(cs);
}
// CTorsoView drawing
void CTorsoView::OnDraw(CDC* pDC)
{
CTorsoDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
COpenGLView::OnDraw( pDC );
}
// CTorsoView printing
BOOL CTorsoView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CTorsoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
void CTorsoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
// CTorsoView diagnostics
#ifdef _DEBUG
void CTorsoView::AssertValid() const
{
COpenGLView::AssertValid();
}
void CTorsoView::Dump(CDumpContext& dc) const
{
COpenGLView::Dump(dc);
}
CTorsoDoc* CTorsoView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CTorsoDoc)));
return (CTorsoDoc*)m_pDocument;
}
#endif //_DEBUG
// CTorsoView message handlers
void CTorsoView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
COpenGLView::OnChar(nChar, nRepCnt, nFlags);
}
void CTorsoView::OnStructureImport()
{
CFileDialog dlg( true );
if ( dlg.DoModal() == IDOK )
{
CTorsoDoc *pDoc = GetDocument();
pDoc->SetTitle( dlg.GetFileName() );
pDoc->m_Torso.m_strFilePath = dlg.GetPathName();
CString FolderPath = dlg.GetPathName().Left( dlg.GetPathName().GetLength()-dlg.GetFileName().GetLength() );
_chdir( FolderPath );
GetDocument()->m_pBody = NewMovNode( "torsostr.stl", m_pRootNode );
mkdir( "tmp" );
if ( GetDocument()->m_pBody->GetGeometry() )
{
m_pPick = GetDocument()->m_pBody;
m_pPickPath = NewNodePath( m_pRootNode, m_pPick, 0 );
float Diffuse[] = {251./255., 220./255., 155./255., 1.0f};
GetDocument()->m_pBody->GetGeometry()->SetDiffuse( 0, RGB(255,220,155) );
Diffuse[0] = Diffuse[1] = Diffuse[2] = 0;
GetDocument()->m_pBody->GetGeometry()->SetSpecular( 0, RGB(0,0,0) );
GetDocument()->m_pBody->GetGeometry()->SetCullMode( 0 );
}
if ( GetDocument()->m_Torso.ReadData() )
{
GetDocument()->m_Torso.GetAverage();
GetDocument()->m_Torso.GetCG();
}
GetDocument()->UpdateAllViews(NULL);
ViewAll();
}
}
void CTorsoView::OnStructureOutline()
{
CTorsoDoc *pDoc = GetDocument();
//MyMSG( "Begin" );
//MyMSG( "Bust" );
//GetDocument()->m_Torso.StraightSideLine();
pDoc->m_Torso.SideLine();
//MyMSG( "SideLine" );
pDoc->m_Torso.FrontPrincessL();
//MyMSG( "FrontPrincessL" );
pDoc->m_Torso.BackPrincessL();
//MyMSG( "BackPrincessL" );
pDoc->m_Torso.UnderBust();
////MyMSG( "UnderBust" );
pDoc->m_Torso.MiddleWaist();
//MyMSG( "MiddleWaist" );
//pDoc->m_Torso.MinWaist();
//pDoc->m_Torso.Gridding();
//CString msg;
//float len;
//len = pDoc->m_Torso.Length( 0, pDoc->m_Torso.WaistLvl, 0, pDoc->m_Torso.WaistLvl );
//msg.Format( "Length = %.1f", len );
//MessageBox( msg );
{
float diff[4] = {1,0,0,1};
CMovNode *pLShouldLine = NewMovNode( "LShouldLine.asc", pDoc->m_pBody );
pLShouldLine->GetGeometry()->SetDiffuse( 0, RGB(255,0,0) );
pLShouldLine->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
diff[0] = 1; diff[2] = 0;
CMovNode *pCutPoint = NewMovNode( "CutResult.asc", pDoc->m_pBody );
diff[1] = 1.0;
pCutPoint->GetGeometry()->SetDiffuse( 0, RGB(255,255,0) );
pCutPoint->GetGeometry()->SetPointSize( 3 );
pCutPoint = NewMovNode( "LFPrincessL.asc", pDoc->m_pBody );
diff[1] = 1.0;
pCutPoint->GetGeometry()->SetDiffuse( 0, RGB(255,255,0) );
pCutPoint->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
pCutPoint->GetGeometry()->SetPointSize( 3 );
pCutPoint = NewMovNode( "UnderBustL.asc", pDoc->m_pBody );
diff[1] = 1.0;
pCutPoint->GetGeometry()->SetDiffuse( 0, RGB(255,255,0) );
pCutPoint->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
pCutPoint->GetGeometry()->SetPointSize( 3 );
pCutPoint = NewMovNode( "MiddleWaistL.asc", pDoc->m_pBody );
diff[1] = 1.0;
pCutPoint->GetGeometry()->SetDiffuse( 0, RGB(255,255,0) );
pCutPoint->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
pCutPoint->GetGeometry()->SetPointSize( 3 );
}
{
std::ofstream fout( "measurements.txt" );
fout << "Acromial height, left = " << pDoc->m_Torso.LS(2) << "\n";
fout << "Acromial height, right = " << pDoc->m_Torso.RS(2) << "\n";
CNurbs curve;
curve.LineApproximate( 8, 0, pDoc->m_Torso.LeftHole, NULL, 2.5, true );
fout << "Acromial-radiale length, left = " << curve.Length(0, 1) << "\n";
curve.LineApproximate( 8, 0, pDoc->m_Torso.RightHole, NULL, 2.5, true );
fout << "Acromial-radiale length = " << curve.Length(0, 1) << "\n";
fout << "B-B breadth = " << Mag(pDoc->m_Torso.LBP - pDoc->m_Torso.RBP) << "\n";
fout << "chest height = " << pDoc->m_Torso.LBP(2) << "\n";
// fout << "Bust girth length = " << len << "\n";
vector<CVector> Hull;
Hull = ConvexHull( pDoc->m_Torso.m_pBustL );
curve.LineApproximate( 8, 0, Hull, NULL, 2.5, true );
pDoc->m_Torso.BustLen = curve.Length(0, 1);
fout << "Bust girth length = " << pDoc->m_Torso.BustLen << ", " << pDoc->m_Torso.m_pBustL[0](2) << "\n";
Hull = ConvexHull( pDoc->m_Torso.m_pUnderBust );
curve.LineApproximate( 8, 0, Hull, NULL, 2.5, true );
pDoc->m_Torso.UnderBustLen = curve.Length(0, 1);
fout << "UnderBust girth length = " << pDoc->m_Torso.UnderBustLen << ", " << pDoc->m_Torso.m_pUnderBust[0](2) << "\n";
curve.LineApproximate( 8, 0, pDoc->m_Torso.m_pWaistL, NULL, 2.5, true );
pDoc->m_Torso.WaistLen = curve.Length(0, 1);
fout << "Waist girth length = " << pDoc->m_Torso.WaistLen << ", " << pDoc->m_Torso.m_pWaistL[0](2) << "\n";
Hull = ConvexHull( pDoc->m_Torso.m_pHipL );
curve.LineApproximate( 8, 0, Hull, NULL, 2.5, true );
pDoc->m_Torso.HipLen = curve.Length(0, 1);
fout << "Hip girth length = " << pDoc->m_Torso.HipLen << ", " << pDoc->m_Torso.m_pHipL[0](2) << "\n";
}
pDoc->UpdateAllViews( NULL );
Invalidate( false );
}
void CTorsoView::OnStructureImagecoding()
{
if ( GetDocument()->m_Torso.HasArmHole() )
GetDocument()->m_Torso.ArmHole();
//MyMSG( "Armhole finished" );
GetDocument()->m_Torso.BuildImage();
float diff[4] = {1,0,0,1};
CMovNode *pLeftHole;// = NewMovNode( "LeftHole.asc", GetDocument()->m_pBody );
//pLeftHole->GetGeometry()->SetDiffuse( diff );
//pLeftHole->GetGeometry()->SetPointSize( 3 );
GetDocument()->UpdateAllViews( NULL );
GetDocument()->m_Torso.CenterLine();
if ( GetDocument()->m_Torso.HasArmHole() )
{
pLeftHole = NewMovNode( "LeftHole.asc", GetDocument()->m_pBody );
pLeftHole->GetGeometry()->SetDiffuse( 0, RGB(255,0,0) );
pLeftHole->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
pLeftHole = NewMovNode( "RightHole.asc", GetDocument()->m_pBody );
pLeftHole->GetGeometry()->SetDiffuse( 0, RGB(255,0,0) );
pLeftHole->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
}
GetDocument()->UpdateAllViews( NULL );
}
void CTorsoView::PreRender(void)
{
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//glDrawBuffer( GL_BACK_LEFT );
//m_pLight1->Draw();
glPushMatrix();
if ( m_bAxes )
{
double m[16];
for (int i=0;i<4;i++)
{
for (int j=0;j<3;j++)
{
m[i+j*4] = m_ViewPoint(i,j);
}
}
if ( !m_bPerspective )
{
m[0+3*4] = -m_Left*7./8.;
m[1+3*4] = -m_Left*7./8./m_Aspect;
m[2+3*4] = -m_Left*0.10f;
m[3+3*4] = 1.0;
glLoadMatrixd( m );
CNode::Draw3DAxes( 0.0f, m_Left*0.10f, 5 );
}
else
{
double x, y = -m_NearPlane*tan(m_ViewAngle/2);
x = m_Aspect*y;
m[0+3*4] = x*5.0/8.0;
m[1+3*4] = y*5.0/8.0;
m[2+3*4] = -m_NearPlane - 0.1*fabs(y);
m[3+3*4] = 1.0;
glLoadMatrixd( m );
CNode::Draw3DAxes( 0.0f, float( 0.1*fabs(y) ), 0 );
}
}
glPopMatrix();
double m[16];
for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
m[i+j*4] = m_ViewPoint(i,j);
}
glLoadMatrixd( m );
if ( m_bRight )
glTranslatef( -7.5, 0, 0 );
//if ( m_bPerspective )
//{
// if ( m_iZAxisUp == 1 )
// ::glRotatef( -90.0f, 1.0f, 0.0f, 0.0f );
// else if ( m_iZAxisUp == -1 )
// ::glRotatef( 90.0f, 1.0f, 0.0f, 0.0f );
//}
// Enable this line to get upward Z-axis
DrawGrid( -30.0f, 30.0f, 30, m_nGrid );
//glDrawBuffer( GL_BACK_RIGHT );
//BOOL bStereoAvailable;
//unsigned char ucTest;
//glGetBooleanv (GL_STEREO, &ucTest);
//if (ucTest) // yes stereo support available
// ////afxDump << "have stereo\n";
//else // stereo support not available
// ////afxDump << "noi stereo\n";
}
void CTorsoView::RenderScene(void)
{
COpenGLView::RenderScene();
CTorsoDoc *pDoc = GetDocument();
glDisable( GL_LIGHTING );
if ( pDoc->m_Torso.m_pLayer.size()==0 )
return;
float Z = (float)pDoc->m_Torso.m_pLayer[pDoc->m_nActive].m_CG(2);
glColor4f( 0, 0.75, 0, 0.25 );
glDisable( GL_CULL_FACE );
glBegin( GL_QUADS );
{
glVertex3f(-300,-250, Z );
glVertex3f( 100,-250, Z );
glVertex3f( 100, 250, Z );
glVertex3f(-300, 250, Z );
}
glEnd();
glEnable( GL_CULL_FACE );
glColor4f( 1, 0, 0, 1.0 );
glBegin( GL_LINE_LOOP );
{
glVertex3f(-300,-250, Z );
glVertex3f( 100,-250, Z );
glVertex3f( 100, 250, Z );
glVertex3f(-300, 250, Z );
}
glEnd();
CVector P = pDoc->m_Torso.m_Central1.m_Dir.Cross( pDoc->m_Torso.m_Central1.m_Moment );
glColor3f( 1, 0, 0 );
glBegin( GL_LINES );
glVertex3d( P(0), P(1), P(2) );
glVertex3d( P(0)+pDoc->m_Torso.m_Central1.m_Dir(0)*2700, P(1)+pDoc->m_Torso.m_Central1.m_Dir(1)*2700, P(2)+pDoc->m_Torso.m_Central1.m_Dir(2)*2700 );
glEnd();
P = pDoc->m_Torso.m_Central2.m_Dir.Cross( pDoc->m_Torso.m_Central2.m_Moment );
glColor3f( 0, 1, 0 );
glBegin( GL_LINES );
glVertex3d( P(0), P(1), P(2) );
glVertex3d( P(0)+pDoc->m_Torso.m_Central2.m_Dir(0)*2700, P(1)+pDoc->m_Torso.m_Central2.m_Dir(1)*2700, P(2)+pDoc->m_Torso.m_Central2.m_Dir(2)*2700 );
glEnd();
glEnable( GL_LIGHTING );
}
void CTorsoView::OnInitialUpdate()
{
COpenGLView::OnInitialUpdate();
m_pRootNode = NewRootNode( "root" );
this->m_bPerspective = false;
if ( m_pLight1 = NewLightNode() )
{
m_pLight1->m_Ambient[0] = m_pLight1->m_Ambient[1] = m_pLight1->m_Ambient[2] = 0.2f;
m_pLight1->m_Diffuse[0] = m_pLight1->m_Diffuse[1] = m_pLight1->m_Diffuse[2] = 0.3f;
m_pLight1->m_Position[0] = 0;
m_pLight1->m_Position[1] = 2000.0f;
m_pLight1->m_Position[2] = 1500;
m_pRootNode->AddChild( m_pLight1 );
}
if ( m_pLight2 = NewLightNode() )
{
m_pLight2->SetType( 0, 1, 0 );
m_pLight2->m_Diffuse[0] = m_pLight2->m_Diffuse[1] = m_pLight2->m_Diffuse[2] = 0.3f;
m_pLight2->m_Position[0] = float( 2000*sin(PI*2/3) );
m_pLight2->m_Position[1] = float( 2000*cos(PI*2/3) );
m_pLight2->m_Position[2] = 1500;
m_pRootNode->AddChild( m_pLight2 );
}
if ( m_pLight3 = NewLightNode() )
{
m_pLight3->SetType( 0, 1, 0 );
m_pLight3->m_Diffuse[0] = m_pLight3->m_Diffuse[1] = m_pLight3->m_Diffuse[2] = 0.3f;
m_pLight3->m_Position[0] =-float( 2000*sin(PI*2/3) );
m_pLight3->m_Position[1] = float( 2000*cos(PI*2/3) );
m_pLight3->m_Position[2] = 1500;
m_pRootNode->AddChild( m_pLight3 );
}
}
void CTorsoView::OnMouseMove(UINT nFlags, CPoint point)
{
COpenGLView::OnMouseMove(nFlags, point);
Invalidate( false );
}
void CTorsoView::OnViewViewall()
{
ViewAll();
}
void ExportTri( CArchive& ar, CVector& P1, CVector& P2, CVector& P3 );
void CTorsoView::OnStructureUpperNeckL() // upper neck line
{
GetDocument()->m_Torso.UpperNeckLine();
float diff[4] = {1,0,0,1};
CMovNode *pNeck = NewMovNode( "UpperNeck.asc", GetDocument()->m_pBody );
//pNeck->GetGeometry()->SetDiffuse( 0, RGB(255,0,0) );
GetDocument()->UpdateAllViews( NULL );
}
void CTorsoView::OnStructureHorizontalLines() // Horizontal lines
{
//MyMSG( "LowerNeckL" );
GetDocument()->m_Torso.LowerNeckL();
//MyMSG( "BustPoint" );
GetDocument()->m_Torso.BustPoint();
//return;
//MyMSG( "BuildShoulderImage" );
GetDocument()->m_Torso.BuildShoulderImage();
//MyMSG( "ShoulderLine" );
GetDocument()->m_Torso.ShoulderLine();
//MyMSG( "crotch pt" );
GetDocument()->m_Torso.CrotchPt();
//return;
{
float diff[4] = {1,0,1,1};
CMovNode *pBust = NewMovNode( "tmp\\Bust.asc", GetDocument()->m_pBody );
pBust->GetGeometry()->SetDiffuse( 0, RGB(255,0,255) );
pBust->GetGeometry()->SetDrawMode( GL_LINE_STRIP );
pBust->GetGeometry()->SetPointSize( 3 );
}
GetDocument()->UpdateAllViews( NULL );
Invalidate( false );
}
BOOL CTorsoView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
if ( zDelta>0 )
GetDocument()->m_nActive--;
else
GetDocument()->m_nActive++;
//Invalidate();
GetDocument()->UpdateAllViews( NULL );
return COpenGLView::OnMouseWheel(nFlags, zDelta, pt);
}
std::vector<CVector> ConvexHull( std::vector<CVector>& pData );
void CTorsoView::OnStructureGrid()
{
GetDocument()->m_Torso.Gridding();
GetDocument()->m_Torso.Triangulation( "TorsoStr" );
GetDocument()->UpdateAllViews(NULL);
GetDocument()->m_Torso.NewPic();
//GetDocument()->m_Torso.StraightShoulderLine();
//int Index[] = { -2, 10, 20, 30, 38};
//char *Tag[] = { "Crotch", "Hip", "Waist", "Undex bust", "Bust" };
//for ( int j=0; j<5; j++ )
//{
// std::vector<CVector> Crotch;
// for ( int i=0; i<80; i++ )
// {
// Crotch.push_back( GetDocument()->m_Torso.m_Grid[i][Index[j]].Pos );
// }
// std::vector<CVector> Hull = ConvexHull( Crotch );
// double Len = 0;
// for ( i=1; i<Crotch.size(); i++ )
// {
// Len += Mag( Crotch[i]-Crotch[i-1] );
// }
// Len += Mag( Crotch[0]-Crotch[i-1] );
// MyMSG( "Contour %sLen = %f", Tag[j], Len );
// Len = 0;
// for ( i=1; i<Hull.size(); i++ )
// {
// Len += Mag( Hull[i]-Hull[i-1] );
// }
// Len += Mag( Hull[0]-Hull[i-1] );
// MyMSG( "%sLen = %f", Tag[j], Len );
//}
}
void CTorsoView::OnStructureRotateraw()
{
}
void CTorsoView::OnStructureExporthead()
{
GetDocument()->m_Torso.ExportHead();
}
void CTorsoView::OnStructureSavetmp()
{
// TODO: Add your command handler code here
}
void CTorsoView::OnStructureMirror()
{
GetDocument()->m_Torso.Mirror();
}
void CTorsoView::OnStructureConnectLeg()
{
// Left
{
std::ifstream LLeg( "L_LEG_STR.asc" );
std::ifstream LFoot( "L_Simple_Foot_STR.asc" );
CVector Leg[38][26];
CVector Foot[38][5];
int i, j;
for ( j=0; j<25; j++ )
{
for ( i=0; i<38; i++ )
{
LLeg >> Leg[i][j](0) >> Leg[i][j](1) >> Leg[i][j](2);
}
}
char s;
for ( j=0; j<5; j++ )
{
for ( i=0; i<38; i++ )
{
LFoot >> Foot[i][j](0) >> Foot[i][j](1) >> Foot[i][j](2);
}
LFoot >> s;
}
for ( i=0; i<38; i++ )
{
Foot[i][0](0) = Foot[i][1](0);
Foot[i][0](1) = Foot[i][1](1);
}
{
for ( i=0; i<38; i++ )
Leg[i][24] = GetDocument()->m_Torso.m_Grid[i+1][-2].Pos;
CFile LLegStl( "L_Leg_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &LLegStl, CArchive::store );
char Msg[80] = "STLEXP left leg";
ar.Write( Msg, 80 );
i = 2*38*24;
ar << i;
for ( j=0; j<24; j++ )
{
for ( i=0; i<38; i++ )
{
ExportTri( ar, Leg[i][j], Leg[(i+1)%38][j], Leg[i][j+1] );
ExportTri( ar, Leg[(i+1)%38][j], Leg[(i+1)%38][j+1], Leg[i][j+1] );
}
}
}
{
CFile LLegStl( "L_Simple_Foot_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &LLegStl, CArchive::store );
char Msg[80] = "STLEXP left simple foot";
ar.Write( Msg, 80 );
i = 2*38*4;
ar << i;
for ( j=0; j<4; j++ )
{
for ( i=0; i<38; i++ )
{
ExportTri( ar, Foot[i][j], Foot[(i+1)%38][j], Foot[i][j+1] );
ExportTri( ar, Foot[(i+1)%38][j], Foot[(i+1)%38][j+1], Foot[i][j+1] );
}
}
}
std::ofstream fout( "L_Leg_Line.asc" );
int Key[4] = {0, 9, 19, 29};
for ( i=0; i<4; i++ )
{
CString msg;
for ( j=0; j<25; j++ )
{
msg.Format( "%f %f %f\n", Leg[Key[i]][j](0), Leg[Key[i]][j](1), Leg[Key[i]][j](2) );
fout << msg;
}
fout << "s\n";
}
}
// Right
{
std::ifstream LLeg( "R_LEG_STR.asc" );
std::ifstream LFoot( "R_Simple_Foot_STR.asc" );
CVector Leg[38][26];
CVector Foot[38][5];
int i, j;
for ( j=0; j<25; j++ )
{
for ( i=0; i<38; i++ )
{
LLeg >> Leg[i][j](0) >> Leg[i][j](1) >> Leg[i][j](2);
}
}
char s;
for ( j=0; j<5; j++ )
{
for ( i=0; i<38; i++ )
{
LFoot >> Foot[i][j](0) >> Foot[i][j](1) >> Foot[i][j](2);
}
LFoot >> s;
}
for ( i=0; i<38; i++ )
{
Foot[i][0](0) = Foot[i][1](0);
Foot[i][0](1) = Foot[i][1](1);
}
{
for ( i=0; i<38; i++ )
Leg[i][24] = GetDocument()->m_Torso.m_Grid[79-i][-2].Pos;
CFile LLegStl( "R_Leg_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &LLegStl, CArchive::store );
char Msg[80] = "STLEXP right leg";
ar.Write( Msg, 80 );
i = 2*38*24;
ar << i;
for ( j=0; j<24; j++ )
{
for ( i=0; i<38; i++ )
{
ExportTri( ar, Leg[i][j], Leg[i][j+1], Leg[(i+1)%38][j] );
ExportTri( ar, Leg[(i+1)%38][j], Leg[i][j+1], Leg[(i+1)%38][j+1] );
}
}
}
{
CFile RLegStl( "R_Simple_Foot_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &RLegStl, CArchive::store );
char Msg[80] = "STLEXP right simple foot";
ar.Write( Msg, 80 );
i = 2*38*4;
ar << i;
for ( j=0; j<4; j++ )
{
for ( i=0; i<38; i++ )
{
ExportTri( ar, Foot[i][j], Foot[i][j+1], Foot[(i+1)%38][j] );
ExportTri( ar, Foot[(i+1)%38][j], Foot[i][j+1], Foot[(i+1)%38][j+1] );
}
}
}
std::ofstream fout( "R_Leg_Line.asc" );
int Key[4] = {0, 9, 19, 29};
for ( i=0; i<4; i++ )
{
CString msg;
for ( j=0; j<25; j++ )
{
msg.Format( "%f %f %f\n", Leg[Key[i]][j](0), Leg[Key[i]][j](1), Leg[Key[i]][j](2) );
fout << msg;
}
fout << "s\n";
}
}
}
void CTorsoView::OnStructureConnectArm()
{
// Left
{
std::ifstream LArm( "LArmStructP.asc" );
CVector Arm[20][21];
int i, j;
for ( i=0; i<20; i++ )
{
for ( j=0; j<20; j++ )
{
LArm >> Arm[i][j](0) >> Arm[i][j](1) >> Arm[i][j](2);
}
}
{
CFile LArmStl( "L_Arm_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &LArmStl, CArchive::store );
char Msg[80] = "STLEXP left arm";
ar.Write( Msg, 80 );
i = 2*20*20;
ar << i;
{
Arm[0][20] = GetDocument()->m_Torso.m_Grid[15][53].Pos;
Arm[1][20] = GetDocument()->m_Torso.m_Grid[15][52].Pos;
Arm[2][20] = GetDocument()->m_Torso.m_Grid[15][51].Pos;
Arm[3][20] = GetDocument()->m_Torso.m_Grid[15][50].Pos;
Arm[4][20] = GetDocument()->m_Torso.m_Grid[15][49].Pos;
Arm[5][20] = GetDocument()->m_Torso.m_Grid[15][48].Pos;
Arm[6][20] = GetDocument()->m_Torso.m_Grid[16][47].Pos;
Arm[7][20] = GetDocument()->m_Torso.m_Grid[17][46].Pos;
Arm[8][20] = GetDocument()->m_Torso.m_Grid[18][46].Pos;
Arm[9][20] = GetDocument()->m_Torso.m_Grid[19][46].Pos;
Arm[10][20] = GetDocument()->m_Torso.m_Grid[20][46].Pos;
Arm[11][20] = GetDocument()->m_Torso.m_Grid[21][46].Pos;
Arm[12][20] = GetDocument()->m_Torso.m_Grid[22][46].Pos;
Arm[13][20] = GetDocument()->m_Torso.m_Grid[23][46].Pos;
Arm[14][20] = GetDocument()->m_Torso.m_Grid[24][47].Pos;
Arm[15][20] = GetDocument()->m_Torso.m_Grid[25][48].Pos;
Arm[16][20] = GetDocument()->m_Torso.m_Grid[25][49].Pos;
Arm[17][20] = GetDocument()->m_Torso.m_Grid[25][50].Pos;
Arm[18][20] = GetDocument()->m_Torso.m_Grid[25][51].Pos;
Arm[19][20] = GetDocument()->m_Torso.m_Grid[25][52].Pos;
}
for ( j=0; j<19; j++ )
{
for ( i=0; i<20; i++ )
{
ExportTri( ar, Arm[i][j], Arm[(i+1)%20][j], Arm[i][j+1] );
ExportTri( ar, Arm[(i+1)%20][j], Arm[(i+1)%20][j+1], Arm[i][j+1] );
}
}
j = 20;
//for ( j=0; j<20; j++ )
{
for ( i=0; i<20; i++ )
{
ExportTri( ar, Arm[i][j], Arm[(i+1)%20][j], Arm[i][0] );
ExportTri( ar, Arm[(i+1)%20][j], Arm[(i+1)%20][0], Arm[i][0] );
}
}
}
//{
// //for ( i=0; i<20; i++ )
// // Arm[i][20] = GetDocument()->m_Torso.m_Grid[i+1][-2].Pos;
// CFile LRingStl( "L_Arm_CONNECT.stl", CFile::modeCreate|CFile::modeWrite );
// CArchive ar( &LRingStl, CArchive::store );
// char Msg[80] = "STLEXP left arm connection";
// ar.Write( Msg, 80 );
// i = 2*20*1;
// ar << i;
// j=19;
// for ( i=0; i<20; i++ )
// {
// //ExportTri( ar, Foot[i][j], Foot[(i+1)%38][j], GetDocument()->m_Torso.m_Grid[i+1][-2].Pos );
// //ExportTri( ar, Foot[(i+1)%38][j], GetDocument()->m_Torso.m_Grid[(i+1)%38+1][-2].Pos, GetDocument()->m_Torso.m_Grid[i+1][-2].Pos );
// ExportTri( ar, Arm[i][j], Arm[(i+1)%20][j], Arm[i][j+1] );
// ExportTri( ar, Arm[(i+1)%20][j], Arm[(i+1)%20][j+1], Arm[i][j+1] );
// }
//}
}
//Right
{
std::ifstream RArm( "RArmStructP.asc" );
CVector Arm[20][21];
int i, j;
for ( i=0; i<20; i++ )
{
for ( j=0; j<20; j++ )
{
RArm >> Arm[i][j](0) >> Arm[i][j](1) >> Arm[i][j](2);
}
}
{
{
Arm[0][20] = GetDocument()->m_Torso.m_Grid[65][53].Pos;
Arm[1][20] = GetDocument()->m_Torso.m_Grid[65][52].Pos;
Arm[2][20] = GetDocument()->m_Torso.m_Grid[65][51].Pos;
Arm[3][20] = GetDocument()->m_Torso.m_Grid[65][50].Pos;
Arm[4][20] = GetDocument()->m_Torso.m_Grid[65][49].Pos;
Arm[5][20] = GetDocument()->m_Torso.m_Grid[65][48].Pos;
Arm[6][20] = GetDocument()->m_Torso.m_Grid[64][47].Pos;
Arm[7][20] = GetDocument()->m_Torso.m_Grid[63][46].Pos;
Arm[8][20] = GetDocument()->m_Torso.m_Grid[62][46].Pos;
Arm[9][20] = GetDocument()->m_Torso.m_Grid[61][46].Pos;
Arm[10][20] = GetDocument()->m_Torso.m_Grid[60][46].Pos;
Arm[11][20] = GetDocument()->m_Torso.m_Grid[59][46].Pos;
Arm[12][20] = GetDocument()->m_Torso.m_Grid[58][46].Pos;
Arm[13][20] = GetDocument()->m_Torso.m_Grid[57][46].Pos;
Arm[14][20] = GetDocument()->m_Torso.m_Grid[56][47].Pos;
Arm[15][20] = GetDocument()->m_Torso.m_Grid[55][48].Pos;
Arm[16][20] = GetDocument()->m_Torso.m_Grid[55][49].Pos;
Arm[17][20] = GetDocument()->m_Torso.m_Grid[55][50].Pos;
Arm[18][20] = GetDocument()->m_Torso.m_Grid[55][51].Pos;
Arm[19][20] = GetDocument()->m_Torso.m_Grid[55][52].Pos;
}
CFile RArmStl( "R_Arm_STR.stl", CFile::modeCreate|CFile::modeWrite );
CArchive ar( &RArmStl, CArchive::store );
char Msg[80] = "STLEXP right arm";
ar.Write( Msg, 80 );
i = 2*20*20;
ar << i;
for ( j=0; j<19; j++ )
{
for ( i=0; i<20; i++ )
{
ExportTri( ar, Arm[i][j], Arm[i][j+1], Arm[(i+1)%20][j] );
ExportTri( ar, Arm[(i+1)%20][j], Arm[i][j+1], Arm[(i+1)%20][j+1] );
}
}
j = 20;
{
for ( i=0; i<20; i++ )
{
ExportTri( ar, Arm[i][j], Arm[i][0], Arm[(i+1)%20][j] );
ExportTri( ar, Arm[(i+1)%20][j], Arm[i][0], Arm[(i+1)%20][0] );
}
}
}
//{
// for ( i=0; i<20; i++ )
// Arm[i][20] = GetDocument()->m_Torso.m_Grid[i+1][-2].Pos;
// CFile RRingStl( "R_Arm_CONNECT.stl", CFile::modeCreate|CFile::modeWrite );
// CArchive ar( &RRingStl, CArchive::store );
// char Msg[80] = "STLEXP right arm connection";
// ar.Write( Msg, 80 );
// i = 2*20*1;
// ar << i;
// j=19;
// for ( i=0; i<20; i++ )
// {
// //ExportTri( ar, Foot[i][j], Foot[(i+1)%38][j], GetDocument()->m_Torso.m_Grid[i+1][-2].Pos );
// //ExportTri( ar, Foot[(i+1)%38][j], GetDocument()->m_Torso.m_Grid[(i+1)%38+1][-2].Pos, GetDocument()->m_Torso.m_Grid[i+1][-2].Pos );
// ExportTri( ar, Arm[i][j], Arm[(i+1)%20][j], Arm[i][j+1] );
// ExportTri( ar, Arm[(i+1)%20][j], Arm[(i+1)%20][j+1], Arm[i][j+1] );
// }
//}
}
}
| [
"[email protected]@8026b7c3-d9ae-87c5-0fde-12bd377d1155"
] | [
[
[
1,
881
]
]
] |
9bc3b13b09580d8aaf31d0b4c5c4bf57586da9a8 | 166a15be5f6a44117e5324e8f824ea6990d07825 | /Beholder.cpp | bb5dd49e95245887d32e17ad36bcf475a3804220 | [] | no_license | pety3bi/winlirc-beholder | a1e3282ae7238b07eae13ea40fa804625118ece0 | 818ae5ec6a739fbb9dff8f658a9918a1dba75f7e | refs/heads/master | 2021-01-02T22:44:58.054739 | 2011-07-18T01:12:03 | 2011-07-18T01:12:03 | 34,176,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,154 | cpp | /*
* This file is part of the WinLIRC package, which was derived from
* LIRC (Linux Infrared Remote Control) 0.8.6.
*
* 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.
*
* Copyright (C) 2011 Artem Golubev
*/
#include "Beholder.h"
#include "Globals.h"
#include <Windows.h>
#include "hardware.h"
#include "decode.h"
IG_API int init( HANDLE exitEvent )
{
initHardwareStruct();
InitializeCriticalSection(&criticalSection);
threadExitEvent = exitEvent;
dataReadyEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
sendReceiveData = new SendReceiveData();
if( !sendReceiveData->init() ) {
return 0;
}
return 1;
}
IG_API void deinit()
{
if(sendReceiveData) {
sendReceiveData->deinit();
delete sendReceiveData;
sendReceiveData = NULL;
}
if(dataReadyEvent) {
CloseHandle( dataReadyEvent );
dataReadyEvent = NULL;
}
DeleteCriticalSection(&criticalSection);
threadExitEvent = NULL;
}
IG_API int hasGui()
{
return FALSE;
}
IG_API void loadSetupGui()
{
// @TODO
}
IG_API int sendIR( struct ir_remote *remote, struct ir_ncode *code, int repeats )
{
return 0;
}
IG_API int decodeIR( struct ir_remote *remotes, char *out )
{
if(sendReceiveData) {
sendReceiveData->waitTillDataIsReady( 0 );
if(decodeCommand(remotes,out)) {
return 1;
}
}
return 0;
}
IG_API struct hardware* getHardware() {
initHardwareStruct();
return &hw;
}
| [
"PETY3bI@e25e1f14-6f9d-6d34-a0ee-eda25bfdb41b"
] | [
[
[
1,
97
]
]
] |
28877886084176e2d4240f38f543d6dd47778ea1 | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Object/Tracer.hpp | 7ed355b186f2350903ce26035418f6f6c69873a6 | [] | no_license | saminigod/baseclasses-001 | 159c80d40f69954797f1c695682074b469027ac6 | 381c27f72583e0401e59eb19260c70ee68f9a64c | refs/heads/master | 2023-04-29T13:34:02.754963 | 2009-10-29T11:22:46 | 2009-10-29T11:22:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,698 | hpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
______________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#ifndef BASE_TRACER_HPP
#define BASE_TRACER_HPP
#include <platform/include.hpp>
#ifdef BASE_TRACE_ENABLED
#define MAX_TRACE 256
typedef enum {
levCrash = 1,
levError,
levWarning,
levInfo,
levVerbose,
} CTraceLevel;
typedef enum {
tagBuiltinMin = 1,
tagGeneric,
tagSystem,
tagMemory,
tagSocket,
tagHttp,
tagLocks,
tagDns,
tagServer,
tagDateTime,
tagReserved4,
tagBuiltinMax
} CTraceBaseTags;
extern bool s_TraceLevels[MAX_TRACE];
extern bool s_TraceTags[MAX_TRACE];
typedef struct {
long m_nTag;
char * m_szDescription;
} CInternalTraceTagDesc;
static CInternalTraceTagDesc s_TraceTagsDescriptions[] = {
{ tagBuiltinMin, "reserved tag" },
{ tagGeneric, "generic library functions" },
{ tagSystem, "general system functions" },
{ tagMemory, "memory allocation system requests" },
{ tagSocket, "socket system level requests" },
{ tagHttp, "http requests and responses" },
{ tagLocks, "locks, semaphores and mutexes" },
{ tagDns, "dns lookups, name resolution" },
{ tagServer, "tcp server" },
{ tagDateTime, "date/time" },
{ tagReserved4, "reserved tag" },
{ tagBuiltinMax, "reserved tag" }
};
static CInternalTraceTagDesc s_TraceLevelsDescriptions[] = {
{ levCrash, "crash" },
{ levError, "error" },
{ levWarning, "warning" },
{ levInfo, "information" },
{ levVerbose, "verbose" }
};
class CInternalTrace {
private:
long m_Tag;
CTraceLevel m_Level;
char * m_File;
int m_Line;
char TraceMsg[MAX_TRACE + 1];
public:
inline static bool InternalTraceCheck(long Tag, CTraceLevel Level);
void InternalTrace(char * Format, ...);
CInternalTrace(long Tag, CTraceLevel Level, char * File, int Line);
static CInternalTraceTagDesc * GetTagInfo(long Tag, CInternalTraceTagDesc pDesc[], int nSize);
static void ShowTagInfo(long Min, long Max, CInternalTraceTagDesc pDesc[], int nSize);
static inline CInternalTraceTagDesc * GetTraceLevelsDescriptions(void) { return (CInternalTraceTagDesc *) s_TraceLevelsDescriptions; }
static inline CInternalTraceTagDesc * GetTraceTagsDescriptions(void) { return (CInternalTraceTagDesc *) s_TraceTagsDescriptions; }
};
inline bool CInternalTrace :: InternalTraceCheck(long Tag, CTraceLevel Level) {
return (s_TraceTags[Tag] && s_TraceLevels[Level]);
}
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
95
]
]
] |
4544d5bc6a6806d453ad4f388f693ecceb2c0e26 | 1a671980a21ef2e96ea8907a961a200381295407 | /Rain/RainEditor/GeneratedFiles/qrc_raineditor.cpp | 9015191084a980547c1608529ebab47122ac8eba | [] | no_license | aosyang/existproj | 7061abccec18f08ea07e742cf1ac988aa9f03a0c | 78d92d81cc15234507305c83f3dff3b94edf091e | refs/heads/master | 2021-01-02T08:52:06.056633 | 2010-03-14T14:36:48 | 2010-03-14T14:36:48 | 34,500,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 727 | cpp | /****************************************************************************
** Resource object code
**
** Created: Thu Mar 11 12:19:47 2010
** by: The Resource Compiler for Qt version 4.6.0
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_raineditor)()
{
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_raineditor))
int QT_MANGLE_NAMESPACE(qCleanupResources_raineditor)()
{
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_raineditor))
| [
"aosyang@72c02e12-28e2-11df-b412-b12aa31876ca"
] | [
[
[
1,
30
]
]
] |
d8bdb511219ceddf8403c2d0ae3eeaf03c21c95d | 028fdbf6e634601077cf5a93d8494ef8453c4bcd | /Self Extractor/Self Extractor.h | ccca67df345293734ddd6efcee3833fd6b935b78 | [] | no_license | csyfek/sdl-sparks.extractor | c2c0ac55d54f3b489bc04f394aba0bab20578623 | 575aa57f829fad8173260c6b4bf00f34688c3883 | refs/heads/master | 2020-04-19T05:33:14.234652 | 2009-10-29T17:04:09 | 2009-10-29T17:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | h | // Self Extractor.h : main header file for the SELF EXTRACTOR application
//
#if !defined(AFX_SELFEXTRACTOR_H__5C3D7753_497B_11D3_A8BC_0050043A01C0__INCLUDED_)
#define AFX_SELFEXTRACTOR_H__5C3D7753_497B_11D3_A8BC_0050043A01C0__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CSelfExtractorApp:
// See Self Extractor.cpp for the implementation of this class
//
class CSelfExtractorApp : public CWinApp
{
public:
CSelfExtractorApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSelfExtractorApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CSelfExtractorApp)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SELFEXTRACTOR_H__5C3D7753_497B_11D3_A8BC_0050043A01C0__INCLUDED_)
| [
"lonicerae(at)gmail.com@localhost"
] | [
[
[
1,
47
]
]
] |
c91e81e6ef725c2f9b8506925f9bd48a25edc3ca | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/aux_/range_c/empty.hpp | 09fd5d286c14341cfe1224b619fd84f28ca5759d | [] | 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 | 981 | hpp |
#ifndef BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
#define BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-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/aux_/range_c/empty.hpp,v $
// $Date: 2006/04/17 23:48:05 $
// $Revision: 1.1 $
#include <boost/mpl/empty_fwd.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/aux_/range_c/tag.hpp>
namespace boost { namespace mpl {
template<>
struct empty_impl< aux::half_open_range_tag >
{
template< typename Range > struct apply
: equal_to<
typename Range::start
, typename Range::finish
>
{
};
};
}}
#endif // BOOST_MPL_AUX_RANGE_C_EMPTY_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
37
]
]
] |
858b16f9cff13a7840ca3ff3ef140816b9d82798 | 7369bf6a69a3e9ddc0c8412846871b2f8f39abb9 | /Managers/ofxThinker.cpp | 2bcaf57ce807e941fb10e8eaf5f1a1de9765061a | [] | no_license | MiklakDIT/ofxengine | 32fffa2b8aa988ecb0726fbe93475ef9a3c2143a | ed35d885c9f6eb626ff8963f2db5b1d61d9d5fcd | refs/heads/master | 2021-03-12T22:27:45.857535 | 2009-07-23T16:39:05 | 2009-07-23T16:39:05 | 35,221,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,435 | cpp | /***************************************************************
* File: Managers/ofxThinker.cpp
* Author: nickiannone (aka ShotgunNinja)
* Status: Complete
***************************************************************/
#include "ofxThinker.h"
//======================================================================
// class ofxThoughtKey
//======================================================================
ofxThoughtKey::ofxThoughtKey(ofxThinkable* thinkable, ofxThinker* thinker, double nextThink)
:m_thinkable(thinkable), m_thinker(thinker), m_nextThink(nextThink)
{
#ifdef OFX_THINKABLE_CANCEL_IF_NEGATIVE
/**/ if (nextThink >= 0)
/**/ {
#endif
// HACKHACK: Loop until we can lock the Thinker thread and insert the thought.
while (true) {
if (m_thinker->insert(this))
break;
}
#ifdef OFX_THINKABLE_CANCEL_IF_NEGATIVE
/**/ }
/**/ else
/**/ {
/**/ m_thinkable->cancelThink();
/**/ delete this; // Is this allowed in C++? I'm not sure...
/**/ }
#endif
}
//----------------------------------------------------------------------
ofxThoughtKey::~ofxThoughtKey()
{
// Remove us from the Thinkable's internal thoughts list, just in case.
if (m_thinkable != NULL)
(m_thinkable->m_thoughts).remove(this);
// HACKHACK: Loop until we can lock the Thinker thread and remove the thought.
while (true) {
if (m_thinker->remove(this))
break;
}
}
//----------------------------------------------------------------------
inline void ofxThoughtKey::checkThink(double timer)
{
if (timer >= m_nextThink)
{
m_thinkable->think();
delete this; // Is this allowed in C++?
}
}
//----------------------------------------------------------------------
inline double ofxThoughtKey::getThinkTime() const
{
return m_nextThink;
}
//======================================================================
// class ofxThinker
//======================================================================
ofxThinker::ofxThinker(unsigned int precision = 10)
:m_precision(precision)
{
start();
}
//----------------------------------------------------------------------
ofxThinker::~ofxThinker()
{
clear();
stop();
}
//----------------------------------------------------------------------
inline bool ofxThinker::start()
{
return startThread(true, false);
}
//----------------------------------------------------------------------
inline bool ofxThinker::stop()
{
return stopThread();
}
//----------------------------------------------------------------------
inline bool ofxThinker::isRunning() const
{
return isThreadRunning();
}
//----------------------------------------------------------------------
bool ofxThinker::remove(ofxThoughtKey* key)
{
if (!isRunning()) {
ofRemoveListener(&m_event, key, &ofxThoughtKey::checkThink);
return true;
} else {
while (isRunning()) {
if (lock()) {
ofRemoveListener(&m_event, key, &ofxThoughtKey::checkThink);
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
bool ofxThinker::clear()
{
if (!isRunning()) {
ofClearListeners(&m_event);
return true;
} else {
while (isRunning()) {
if (lock()) {
ofClearListeners(&m_event);
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
bool ofxThinker::insert()
{
if (!isRunning()) {
ofAddListener(&m_event, key, &ofxThoughtKey::checkThink);
return true;
} else {
while (isRunning()) {
if (lock()) {
ofAddListener(&m_event, key, &ofxThoughtKey::checkThink);
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
bool ofxThinker::enable()
{
if (!isRunning()) {
ofEnableEvent(&m_event);
return true;
} else {
while (isRunning()) {
if (lock()) {
ofEnableEvent(&m_event);
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
bool ofxThinker::disable()
{
if (!isRunning()) {
ofDisableEvent(&m_event);
return true;
} else {
while (isRunning()) {
if (lock()) {
ofDisableEvent(&m_event);
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
inline bool ofxThinker::isEnabled() const
{
return (ofEventIsEnabled(&m_event));
}
//----------------------------------------------------------------------
bool ofxThinker::setPrecision(unsigned int millisPerTick)
{
if (!isRunning()) {
m_precision = millisPerTick;
return true;
} else {
while (isRunning()) {
if (lock()) {
m_precision = millisPerTick;
unlock();
return true;
}
}
}
return false;
}
//----------------------------------------------------------------------
inline unsigned int ofxThinker::getPrecision() const
{
return m_precision;
}
//----------------------------------------------------------------------
void ofxThinker::threadedFunction()
{
unsigned int precision;
while (isRunning()) {
if (lock()) {
ofNotifyEvent(&m_event, ofGetElapsedTimef());
precision = m_precision;
unlock();
}
ofSleepMillis(precision);
}
} | [
"nickiannone@70296b60-74a0-11de-9207-fb4211ab666b"
] | [
[
[
1,
233
]
]
] |
17146f8effab25e1be0eb1b3ad6fb9882c39742a | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/ext/TinyOpenEngine.Net/h/toeWebRequest.h | e15c3ac4fd78c7aa2177d82e01060775eadd6373 | [] | no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,214 | h | #pragma once
#include <toeIntrusiveList.h>
extern "C"
{
#include <curl/curl.h>
}
namespace TinyOpenEngine
{
class CtoeWebRequest: public TtoeIntrusiveListItem<CtoeWebRequest>
{
protected:
CURL * m_curl;
CURLM *multi_handle;
curl_slist *m_headerlist;
public:
CtoeWebRequest();
virtual ~CtoeWebRequest();
void SetURL(const char *);
virtual void Start();
virtual bool IsActive() const;
int GetHTTPCode() const;
virtual void Update();
virtual void Wait();
void AddHeader(const char*);
void AddHeaderValue(const char*,const char*);
protected:
// This function gets called by libcurl as soon as there is data received that needs to be saved.
// The size of the data pointed to by ptr is size multiplied with nmemb, it will not be zero terminated.
// Return the number of bytes actually taken care of. If that amount differs from the amount passed to your function, it'll signal an error to the library.
virtual size_t OnWriteFunction(void *ptr, size_t size, size_t nmemb);
// This function gets called by libcurl as soon as it needs to read data in order to send it to the peer.
// The data area pointed at by the pointer ptr may be filled with at most size multiplied with nmemb number of bytes.
// Your function must return the actual number of bytes that you stored in that memory area.
// Returning 0 will signal end-of-file to the library and cause it to stop the current transfer.
virtual size_t OnReadFunction(void *ptr, size_t size, size_t nmemb);
// This function gets called by libcurl as soon as it has received header data.
// The header callback will be called once for each header and only complete header lines are passed on to the callback.
// Parsing headers should be easy enough using this. The size of the data pointed to by ptr is size multiplied with nmemb.
// Do not assume that the header line is zero terminated! The pointer named userdata is the one you set with the CURLOPT_WRITEHEADER option.
// The callback function must return the number of bytes actually taken care of.
// If that amount differs from the amount passed to your function, it'll signal an error to the library.
// This will abort the transfer and return CURL_WRITE_ERROR.
virtual size_t OnHeaderFunction(void *ptr, size_t size, size_t nmemb);
static size_t WriteFunction(void *ptr, size_t size, size_t nmemb, void *userdata);
static size_t ReadFunction(void *ptr, size_t size, size_t nmemb, void *userdata);
static size_t HeaderFunction(void *ptr, size_t size, size_t nmemb, void *userdata);
void CurlAssert(int);
};
class CtoeBufferedWebRequest: public CtoeWebRequest
{
int responseSize;
CIwArray<char> request;
CIwArray<char> response;
public:
CtoeBufferedWebRequest();
~CtoeBufferedWebRequest();
const char* GetResponseString() const;
protected:
virtual size_t OnWriteFunction(void *ptr, size_t size, size_t nmemb);
virtual size_t OnReadFunction(void *ptr, size_t size, size_t nmemb);
virtual size_t OnHeaderFunction(void *ptr, size_t size, size_t nmemb);
};
TtoeIntrusiveList<CtoeWebRequest>* toeGetActiveWebRequests();
}
| [
"[email protected]"
] | [
[
[
1,
76
]
]
] |
0612b65fc61803bc44d115d73e925109d52dd926 | a96b15c6a02225d27ac68a7ed5f8a46bddb67544 | /SetGame/GameState.cpp | daba4a92cf32569e1e0b2709d18cabf7eca7a264 | [] | 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 | 1,479 | cpp | #include "GameState.hpp"
GameState::GameState(Gaza::Application * application, Gaza::FrameSheetCollection * cardFrames) : Gaza::BaseState(application)
{
this->cardFrames = cardFrames;
score = 0;
table = new Table(cardFrames, &score, application, sf::Vector2f(5, 5));
gameControls = new GameControls(table->getWidth(), &score, application, sf::Vector2f(0.f, (float)table->getHeight()));
application->setSize(table->getWidth(), table->getHeight() + gameControls->getHeight());
}
GameState::~GameState()
{
delete table;
delete gameControls;
}
void GameState::handleEvents()
{
sf::Event event;
while(application->getRenderWindow()->GetEvent(event))
{
if(event.Type == sf::Event::Closed)
{
application->setRunning(false);
}
else if(event.Type == sf::Event::MouseButtonPressed && event.MouseButton.Button == sf::Mouse::Left)
{
table->handleClick(application->getRenderWindow()->GetInput().GetMouseX(), application->getRenderWindow()->GetInput().GetMouseY());
}
else if(event.Type == sf::Event::KeyPressed && event.Key.Code == sf::Key::Z)
{
table->highlightValidTriple();
}
}
}
void GameState::update()
{
table->update();
gameControls->update();
}
void GameState::draw()
{
application->getRenderWindow()->Clear(sf::Color(51, 153, 51));
table->draw(application->getRenderWindow());
gameControls->draw(application->getRenderWindow());
application->getRenderWindow()->Display();
} | [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
b6439e8c8d9ff861ef3265b60188ac93cfcdcde5 | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/Wrappers/renderer.cpp | 6b429676dd57f21434079c89416b4414dfd2ee31 | [] | no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp | #include <windows.h>
#include "..\Helpers\datatypes.h"
#include "renderer.h"
renderer::renderer(void) : cam(0) {}
void renderer::AttachCamera(camera * _cam)
{
if(cam)
ReleaseCamera();
cam = _cam;
}
void renderer::ReleaseCamera() { cam = 0; } | [
"[email protected]"
] | [
[
[
1,
14
]
]
] |
f27cb85750bd5a2475c1977204bfb12f16427fa9 | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Servidor/OpAgregarJugador.h | b3d0457bf897fe6d5a6f7ba018e66bdd33be448e | [] | no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | h | #ifndef _OP_AGREGARJUGADOR_H_
#define _OP_AGREGARJUGADOR_H_
#include "Operacion.h"
using namespace std;
class OpAgregarJugador : public Operacion
{
protected:
virtual bool ejecutarAccion(Socket* socket);
public:
OpAgregarJugador(int idCliente, vector<string> parametros);
virtual ~OpAgregarJugador(void);
};
#endif //_OP_AGREGARJUGADOR_H_
| [
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296"
] | [
[
[
1,
18
]
]
] |
f782f43538744351ec7d62cd1ee7f101a375e782 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/websrv/web_service_connection_api/senutils/inc/senutilsbctest.h | 742850bfa9dd5dfbb02a31167074098ab5d49726 | [] | 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 | 22,968 | 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: SenUtils test module.
*
*/
#ifndef SENUTILS_H
#define SENUTILS_H
// INCLUDES
#include <StifTestModule.h>
#include <StifLogger.h>
#include <SenParser.h>
#include <SenBaseAttribute.h>
#include <SenBaseElement.h>
#include <SenBaseFragment.h>
#include <SenDOMFragment.h>
#include <SenIdentityProvider.h>
#include <SenNamespace.h>
#include <SenSoapEnvelope.h>
#include <SenSoapFault.h>
#include <SenSoapMessage.h>
#include <SenWsSecurityHeader.h>
#include <SenXmlReader.h>
#include <SenXmlServiceDescription.h>
#include <SenDateUtils.h>
#include <SenXmlUtils.h>
#include <SenXmlConstants.h>
#include <SenTransportProperties.h>
#include <SenHttpTransportProperties.h>
//#include <SenVtcpTransportProperties.h>
#include <f32file.h>
//#include <S32FILE.H>
//#include <e32std.h>
// FORWARD DECLARATIONS
class CSenBaseAttribute;
class CSenBaseFragment;
class CSenSoapMessage;
class CSenIdentityProvider;
class CSenGuidGen;
class CSenDomFragment;
class CSenSoapFault;
class CSenXmlServiceDescription;
class CSenSoapEnvelope;
class CSenWsSecurityHeader;
class SenXmlUtils;
class CSenBaseElement;
class MSenElement;
class CSenXmlReader;
class SenDateUtils;
class CSenNamespace;
namespace{
_LIT8(KText,"text");
_LIT8(KText2,"text2");
_LIT8(KXmlSpecific, "\"&<>");
_LIT8(KFaultMessage, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Body><S:Fault><faultcode>VersionMismatch</faultcode><faultstring>some string</faultstring><faultactor>some actor</faultactor><detail>bla bla</detail></S:Fault></S:Body></S:Envelope>");
_LIT8(KSOAPMessageNS, "<tns:Envelope xmlns:tns=\"http://schemas.xmlsoap.org/soap/envelope/\"><tns:Header/><tns:Body><ab:QueryResponse xmlns:ab=\"urn:nokia:test:addrbook:2004-09\"><ab:Status code=\"OK\"/><ab:Data>Hard Coded response, alway the same</ab:Data></ab:QueryResponse></tns:Body></tns:Envelope>");
_LIT8(KSOAPMessageNSInside, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Header/><S:Body><ab:QueryResponse xmlns:ab=\"urn:nokia:test:addrbook:2004-09\"><ab:Status code=\"OK\"/><ab:Data>Hard Coded response, alway the same</ab:Data></ab:QueryResponse></S:Body></S:Envelope>");
_LIT8(KSOAPMessage, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Header/><S:Body><QueryResponse><Data>Hard Coded response, alway the same</Data></QueryResponse></S:Body></S:Envelope>");
}
// MACROS
//#define ?macro ?macro_def
#define TEST_MODULE_VERSION_MAJOR 50
#define TEST_MODULE_VERSION_MINOR 9
#define TEST_MODULE_VERSION_BUILD 38
// Logging path
_LIT( KSenUtilsLogPath, "\\logs\\testframework\\SenUtilsBCTest\\" );
// Log file
_LIT( KSenUtilsLogFile, "SenUtilsBCTest.txt" );
// Function pointer related internal definitions
// Visual studio 6.0 (__VC32__) needs different type of handling
#ifdef __VC32__
#define GETPTR
#else
#define GETPTR &
#endif
#define ENTRY(str,func) {_S(str), GETPTR func,0,0,0}
#define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0}
#define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c}
#define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c}
// FUNCTION PROTOTYPES
//?type ?function_name(?arg_list);
// FORWARD DECLARATIONS
//class ?FORWARD_CLASSNAME;
class CSenUtilsBCTest;
// DATA TYPES
//enum ?declaration
//typedef ?declaration
//extern ?data_type;
// A typedef for function that does the actual testing,
// function is a type
// TInt CSenUtilsBCTest::<NameOfFunction> ( TTestResult& aResult )
typedef TInt (CSenUtilsBCTest::* TestFunction)(TTestResult&);
// CLASS DECLARATION
/**
* An internal structure containing a test case name and
* the pointer to function doing the test
*
* @lib ?library
* @since ?Series60_version
*/
class TCaseInfoInternal
{
public:
const TText* iCaseName;
TestFunction iMethod;
TBool iIsOOMTest;
TInt iFirstMemoryAllocation;
TInt iLastMemoryAllocation;
};
// CLASS DECLARATION
/**
* A structure containing a test case name and
* the pointer to function doing the test
*
* @lib ?library
* @since ?Series60_version
*/
class TCaseInfo
{
public:
TPtrC iCaseName;
TestFunction iMethod;
TBool iIsOOMTest;
TInt iFirstMemoryAllocation;
TInt iLastMemoryAllocation;
TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
{
};
};
// CLASS DECLARATION
/**
* This a SenUtils class.
* ?other_description_lines
*
* @lib ?library
* @since ?Series60_version
*/
NONSHARABLE_CLASS(CSenUtilsBCTest) : public CTestModuleBase
{
public: // Constructors and destructor
/**
* Two-phased constructor.
*/
static CSenUtilsBCTest* NewL();
/**
* Destructor.
*/
virtual ~CSenUtilsBCTest();
public: // New functions
/**
* ?member_description.
* @since ?Series60_version
* @param ?arg1 ?description
* @return ?description
*/
//?type ?member_function( ?type ?arg1 );
public: // Functions from base classes
/**
* From CTestModuleBase InitL is used to initialize the
* SenUtils. It is called once for every instance of
* TestModuleSenUtils after its creation.
* @since ?Series60_version
* @param aIniFile Initialization file for the test module (optional)
* @param aFirstTime Flag is true when InitL is executed for first
* created instance of SenUtils.
* @return Symbian OS error code
*/
TInt InitL( TFileName& aIniFile, TBool aFirstTime );
/**
* From CTestModuleBase GetTestCasesL is used to inquiry test cases
* from SenUtils.
* @since ?Series60_version
* @param aTestCaseFile Test case file (optional)
* @param aTestCases Array of TestCases returned to test framework
* @return Symbian OS error code
*/
TInt GetTestCasesL( const TFileName& aTestCaseFile,
RPointerArray<TTestCaseInfo>& aTestCases );
/**
* From CTestModuleBase RunTestCaseL is used to run an individual
* test case.
* @since ?Series60_version
* @param aCaseNumber Test case number
* @param aTestCaseFile Test case file (optional)
* @param aResult Test case result returned to test framework (PASS/FAIL)
* @return Symbian OS error code (test case execution error, which is
* not reported in aResult parameter as test case failure).
*/
TInt RunTestCaseL( const TInt aCaseNumber,
const TFileName& aTestCaseFile,
TTestResult& aResult );
/**
* From CTestModuleBase; OOMTestQueryL is used to specify is particular
* test case going to be executed using OOM conditions
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @param aFailureType OOM failure type (optional)
* @param aFirstMemFailure The first heap memory allocation failure value (optional)
* @param aLastMemFailure The last heap memory allocation failure value (optional)
* @return TBool
*/
virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */,
TOOMFailureType& aFailureType,
TInt& /* aFirstMemFailure */,
TInt& /* aLastMemFailure */ );
/**
* From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
* test environment
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @return None
*/
virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */ );
/**
* From CTestModuleBase; OOMHandleWarningL
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @param aFailNextValue FailNextValue for OOM test execution (optional)
* @return None
*
* User may add implementation for OOM test warning handling. Usually no
* implementation is required.
*/
virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */,
TInt& /* aFailNextValue */);
/**
* From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
* test environment
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @return None
*
*/
virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */ );
/**
* Method used to log version of test module
*/
void SendTestModuleVersion();
private:
/**
* C++ default constructor.
*/
CSenUtilsBCTest();
/**
* By default Symbian 2nd phase constructor is private.
*/
void ConstructL();
// Prohibit copy constructor if not deriving from CBase.
// ?classname( const ?classname& );
// Prohibit assigment operator if not deriving from CBase.
// ?classname& operator=( const ?classname& );
/**
* Function returning test case name and pointer to test case function.
* @since ?Series60_version
* @param aCaseNumber test case number
* @return TCaseInfo
*/
const TCaseInfo Case ( const TInt aCaseNumber ) const;
void SetupL();
void Teardown();
TPtr16 ConvertToPtr16LC(CSenBaseFragment &fragment);
TPtr16 ConvertToPtr16LC(MSenElement &element);
/**
* Actual Hardcoded test case functions are listed below.
*/
/*
TInt CSenSoapEnvelope_NewLL( TTestResult& aResult );
TInt CSenSoapEnvelope_AddHeaderLL( TTestResult& aResult );
TInt CSenSoapEnvelope_BodyLL( TTestResult& aResult );
TInt CSenSoapEnvelope_BodyAsStringLL( TTestResult& aResult );
TInt CSenSoapEnvelope_DetachFaultLL( TTestResult& aResult );
TInt CSenSoapEnvelope_HeaderLL( TTestResult& aResult );
TInt CSenSoapEnvelope_SetBodyLL( TTestResult& aResult );
TInt CSenSoapEnvelope_SoapActionL( TTestResult& aResult );
TInt CSenSoapEnvelope_FaultLL( TTestResult& aResult );
TInt CSenSoapFault_NewLL( TTestResult& aResult );
TInt CSenSoapFault_NewL_1L( TTestResult& aResult );
TInt CSenSoapFault_FaultCodeL( TTestResult& aResult );
TInt CSenSoapFault_FaultStringL( TTestResult& aResult );
TInt CSenSoapFault_FaultActorL( TTestResult& aResult );
TInt CSenSoapFault_DetailL( TTestResult& aResult );
TInt CSenSoapMessage_NewLL( TTestResult& aResult );
TInt CSenWsSecurityHeader_NewLL( TTestResult& aResult );
TInt CSenWsSecurityHeader_NewL_1L( TTestResult& aResult );
TInt CSenWsSecurityHeader_UsernameTokenLL( TTestResult& aResult );
TInt CSenWsSecurityHeader_UsernameTokenL_1L( TTestResult& aResult );
TInt CSenWsSecurityHeader_XmlNsL( TTestResult& aResult );
TInt CSenWsSecurityHeader_XmlNsPrefixL( TTestResult& aResult );
TInt SenDateUtils_FromXmlDateTimeLL( TTestResult& aResult );
TInt SenDateUtils_ToXmlDateTimeUtf8LL( TTestResult& aResult );
TInt CSenSoapMessage_SetSecurityHeaderLL( TTestResult& aResult );
TInt CSenSoapMessage_AddSecurityTokenLL( TTestResult& aResult );
*/
TInt CSenSoapEnvelope_NewLL(TTestResult& aResult);
TInt CSenSoapEnvelope_SetBodyLL(TTestResult& aResult);
TInt CSenSoapEnvelope_BodyLL(TTestResult& aResult);
TInt CSenSoapEnvelope_HeaderLL(TTestResult& aResult);
TInt CSenSoapEnvelope_AddHeaderLL(TTestResult& aResult);
TInt CSenSoapEnvelope_BodyAsStringLL(TTestResult& aResult);
TInt CSenSoapEnvelope_DetachFaultLL(TTestResult& aResult);
TInt CSenSoapEnvelope_FaultLL(TTestResult& aResult);
TInt CSenSoapEnvelope_SetSoapActionLL(TTestResult& aResult);
TInt CSenSoapEnvelope_SoapActionL(TTestResult& aResult);
TInt CSenSoapEnvelope_SoapAction2L(TTestResult& aResult);
TInt CSenSoapEnvelope_HasHeaderL(TTestResult& aResult);
TInt CSenSoapEnvelope_SoapVersionL(TTestResult& aResult);
TInt CSenSoapEnvelope_HasBodyL(TTestResult& aResult);
TInt CSenSoapEnvelope_IsFaultL(TTestResult& aResult);
TInt CSenSoapEnvelope_ParseLL(TTestResult& aResult);
TInt CSenSoapFault_NewLL(TTestResult& aResult);
TInt CSenSoapFault_NewL_1L(TTestResult& aResult);
TInt CSenSoapFault_FaultCodeL(TTestResult& aResult);
TInt CSenSoapFault_FaultSubcodeL(TTestResult& aResult);
TInt CSenSoapFault_FaultStringL(TTestResult& aResult);
TInt CSenSoapFault_FaultActorL(TTestResult& aResult);
TInt CSenSoapFault_DetailL(TTestResult& aResult);
TInt CSenSoapMessage_NewLL(TTestResult& aResult);
TInt CSenSoapMessage_NewL_1L(TTestResult& aResult);
TInt CSenSoapMessage_NewL_2L(TTestResult& aResult);
TInt CSenSoapMessage_SetSecurityHeaderLL(TTestResult& aResult);
TInt CSenSoapMessage_AddSecurityTokenLL(TTestResult& aResult);
TInt CSenSoapMessage_ParseLL(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewLL(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewLCL(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewL_1L(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewLC_1L(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewL_2L(TTestResult& aResult);
TInt CSenWsSecurityHeader_NewLC_2L(TTestResult& aResult);
TInt CSenWsSecurityHeader_BinarySecurityTokenL_L(TTestResult& aResult);
TInt CSenWsSecurityHeader_BinarySecurityTokenL_1L(TTestResult& aResult);
TInt CSenWsSecurityHeader_TimestampL_L(TTestResult& aResult);
TInt CSenWsSecurityHeader_TimestampL_1L(TTestResult& aResult);
TInt CSenWsSecurityHeader_UsernameTokenLL(TTestResult& aResult);
TInt CSenWsSecurityHeader_UsernameTokenL_1L(TTestResult& aResult);
TInt CSenWsSecurityHeader_UsernameTokenL_2L(TTestResult& aResult);
TInt CSenWsSecurityHeader_UsernameTokenL_3L(TTestResult& aResult);
TInt CSenWsSecurityHeader_UsernameTokenL_4L(TTestResult& aResult);
TInt CSenWsSecurityHeader_XmlNsL(TTestResult& aResult);
TInt CSenWsSecurityHeader_XmlNsPrefixL(TTestResult& aResult);
TInt SenDateUtils_FromXmlDateTimeLL(TTestResult& aResult);
TInt SenDateUtils_ToXmlDateTimeUtf8LL(TTestResult& aResult);
TInt SenDateUtils_ToXmlDateTimeUtf82LL(TTestResult& aResult);
TInt SenTransportProperties_FileAttachmentLL(TTestResult& aResult);
//TInt SenTransportProperties_SetFileAttachmentsLL(TTestResult& aResult);
TInt SenXmlProperties_NewLL(TTestResult& aResult);
TInt SenXmlProperties_NewLCL(TTestResult& aResult);
TInt SenXmlProperties_NewL_1L(TTestResult& aResult);
TInt SenXmlProperties_NewLC_1L(TTestResult& aResult);
TInt SenXmlProperties_NewL_2L(TTestResult& aResult);
TInt SenXmlProperties_NewLC_2L(TTestResult& aResult);
TInt SenTransportProperties_NewLL(TTestResult& aResult);
TInt SenTransportProperties_NewLCL(TTestResult& aResult);
TInt SenTransportProperties_NewL_1L(TTestResult& aResult);
TInt SenTransportProperties_NewLC_1L(TTestResult& aResult);
TInt SenTransportProperties_NewL_2L(TTestResult& aResult);
TInt SenTransportProperties_NewLC_2L(TTestResult& aResult);
TInt SenTransportProperties_SetReaderL(TTestResult& aResult);
TInt SenTransportProperties_PropertiesClassTypeL(TTestResult& aResult);
TInt SenTransportProperties_WriteToLL(TTestResult& aResult);
TInt SenTransportProperties_ReadFromLL(TTestResult& aResult);
TInt SenTransportProperties_AsUtf8LL(TTestResult& aResult);
TInt SenTransportProperties_AsUtf8LCL(TTestResult& aResult);
TInt SenTransportProperties_SetPropertyLL(TTestResult& aResult);
TInt SenTransportProperties_PropertyLL(TTestResult& aResult);
TInt SenTransportProperties_SetIntPropertyLL(TTestResult& aResult);
TInt SenTransportProperties_IntPropertyLL(TTestResult& aResult);
TInt SenTransportProperties_SetBoolPropertyLL(TTestResult& aResult);
TInt SenTransportProperties_BoolPropertyLL(TTestResult& aResult);
TInt SenTransportProperties_SetOmittedLL(TTestResult& aResult);
TInt SenTransportProperties_RemovePropertyLL(TTestResult& aResult);
TInt SenTransportProperties_IsSafeToCastL(TTestResult& aResult);
TInt SenTransportProperties_CloneLL(TTestResult& aResult);
TInt SenTransportProperties_CloneL(TTestResult& aResult);
TInt SenTransportProperties_ApplyBindingLL(TTestResult& aResult);
TInt SenTransportProperties_HeartbeatLL(TTestResult& aResult);
TInt SenTransportProperties_SetHeartbeatLL(TTestResult& aResult);
TInt SenTransportProperties_IapIdLL(TTestResult& aResult);
TInt SenTransportProperties_SetIapIdLL(TTestResult& aResult);
TInt SenTransportProperties_ProxyPortLL(TTestResult& aResult);
TInt SenTransportProperties_SetProxyPortLL(TTestResult& aResult);
TInt SenTransportProperties_ProxyHostLL(TTestResult& aResult);
TInt SenTransportProperties_SetProxyHostLL(TTestResult& aResult);
TInt SenTransportProperties_ProxyUsageLL(TTestResult& aResult);
TInt SenTransportProperties_SetProxyUsageLL(TTestResult& aResult);
TInt SenTransportProperties_SecureDialogLL(TTestResult& aResult);
TInt SenTransportProperties_SetSecureDialogLL(TTestResult& aResult);
TInt SenTransportProperties_UserAgentLL(TTestResult& aResult);
TInt SenTransportProperties_SetUserAgentLL(TTestResult& aResult);
TInt SenTransportProperties_DeviceIDLL(TTestResult& aResult);
TInt SenTransportProperties_SetDeviceIDLL(TTestResult& aResult);
TInt SenTransportProperties_SoapActionLL(TTestResult& aResult);
TInt SenTransportProperties_SetSoapActionLL(TTestResult& aResult);
TInt SenTransportProperties_DownloadFolderLL(TTestResult& aResult);
TInt SenTransportProperties_SetDownloadFolderLL(TTestResult& aResult );
TInt SenTransportProperties_SetFileAttachmentLL( TTestResult& aResult);
TInt SenTransportProperties_MwsNamespaceLL(TTestResult& aResult );
TInt SenTransportProperties_SetMwsNamespaceLL(TTestResult& aResult );
TInt SenTransportProperties_MessageIdLL(TTestResult& aResult );
TInt SenTransportProperties_SetMessageIdLL( TTestResult& aResult);
TInt SenTransportProperties_OnewayMessageOnOffLL( TTestResult& aResult);
TInt SenTransportProperties_SetOnewayMessageOnOffLL(TTestResult& aResult );
TInt SenTransportProperties_SetMaxTimeToLiveLL(TTestResult& aResult);
TInt SenTransportProperties_MaxTimeToLiveLL(TTestResult& aResult);
TInt SenTransportProperties_SetMinTimeToLiveLL(TTestResult& aResult);
TInt SenTransportProperties_MinTimeToLiveLL(TTestResult& aResult);
TInt SenHttpTransportProperties_NewLL(TTestResult& aResult);
TInt SenHttpTransportProperties_NewLCL(TTestResult& aResult);
TInt SenHttpTransportProperties_NewL_1L(TTestResult& aResult);
TInt SenHttpTransportProperties_NewLC_1L(TTestResult& aResult);
TInt SenHttpTransportProperties_NewL_2L(TTestResult& aResult);
TInt SenHttpTransportProperties_NewLC_2L(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewLL(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewLCL(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewL_1L(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewLC_1L(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewL_2L(TTestResult& aResult);
TInt SenVtcpTransportProperties_NewLC_2L(TTestResult& aResult);
TInt SenVtcpTransportProperties_OnewayMessageOnOffLL( TTestResult& aResult);
TInt SenVtcpTransportProperties_SetOnewayMessageOnOffLL(TTestResult& aResult );
TInt SenVtcpTransportProperties_SetMaxTimeToLiveLL(TTestResult& aResult);
TInt SenVtcpTransportProperties_MaxTimeToLiveLL(TTestResult& aResult);
TInt SenVtcpTransportProperties_SetMinTimeToLiveLL(TTestResult& aResult);
TInt SenVtcpTransportProperties_MinTimeToLiveLL(TTestResult& aResult);
public: // Data
// ?one_line_short_description_of_data
//?data_declaration;
protected: // Data
// ?one_line_short_description_of_data
//?data_declaration;
private: // Data
// Pointer to test (function) to be executed
TestFunction iMethod;
// Pointer to logger
CStifLogger * iLog;
CSenXmlReader* iXmlReader;
// ?one_line_short_description_of_data
//?data_declaration;
// Reserved pointer for future extension
//TAny* iReserved;
public: // Friend classes
//?friend_class_declaration;
protected: // Friend classes
//?friend_class_declaration;
private: // Friend classes
//?friend_class_declaration;
};
#endif // SENUTILS_H
// End of File | [
"none@none"
] | [
[
[
1,
571
]
]
] |
d9174864f5c03df7777ce8d73bd65cd08f9862c1 | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1965.cpp | 02c3237136d89cc31f218eeb11fafc961c323ad2 | [] | no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,440 | cpp | #include<iostream>
#include<map>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
enum {
Size = 52,
};
int freq[Size];
int node[Size];
int pos;
priority_queue<int, vector<int>, greater<int> > leaf;
multimap<int,int> edge;
int root;
void traceback(int key){
multimap<int,int>::iterator first,last;
printf("%d", key);
first = edge.lower_bound(key);
last = edge.upper_bound(key);
for(;first != last; first++){
printf(" (");
traceback(first->second);
printf(")");
}
}
int fun(){
int i;
for(i=1;i<root;i++){
if(freq[i] ==0 ){
leaf.push(i);
}
}
int f, p;
i = 0;
while(! leaf.empty() ){
f = leaf.top(); leaf.pop();
p = node[i];
edge.insert( make_pair(p, f) );
if(--freq[p] == 0 && p < root-1){
leaf.push(p);
}
i++;
}
edge.erase(0);
printf("(");
traceback(root-1);
printf(")\n");
edge.clear();
}
int main(){
int num;
char c;
c = fgetc(stdin);
while(!feof(stdin)){
if( c == '\n'){
printf("(1)\n");
goto loop;
}
ungetc(c, stdin);
scanf("%d%c", &num,&c);
pos = 0;
while(c!= '\n'){
freq[num]++;
node[pos++] = num;
scanf("%d%c", &num,&c);
}
freq[num]++;
node[pos++] = num;
node[pos ] = 0;
root = num + 1;
fun();
memset(freq,0,sizeof(freq));
loop: c = fgetc(stdin);
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
91
]
]
] |
086d52173d53c3ce176ecce1f56d5b67d9786eb7 | 7b4e708809905ae003d0cb355bf53e4d16c9cbbc | /JuceLibraryCode/modules/juce_gui_extra/misc/juce_BubbleMessageComponent.h | 166c489c93340e955f9b43720671727e47bb4e45 | [] | no_license | sonic59/JulesText | ce6507014e4cba7fb0b67597600d1cee48a973a5 | 986cbea68447ace080bf34ac2b94ac3ab46faca4 | refs/heads/master | 2016-09-06T06:10:01.815928 | 2011-11-18T01:19:26 | 2011-11-18T01:19:26 | 2,796,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,111 | h | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
#define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
//==============================================================================
/**
A speech-bubble component that displays a short message.
This can be used to show a message with the tail of the speech bubble
pointing to a particular component or location on the screen.
@see BubbleComponent
*/
class JUCE_API BubbleMessageComponent : public BubbleComponent,
private Timer
{
public:
//==============================================================================
/** Creates a bubble component.
After creating one a BubbleComponent, do the following:
- add it to an appropriate parent component, or put it on the
desktop with Component::addToDesktop (0).
- use the showAt() method to show a message.
- it will make itself invisible after it times-out (and can optionally
also delete itself), or you can reuse it somewhere else by calling
showAt() again.
*/
BubbleMessageComponent (int fadeOutLengthMs = 150);
/** Destructor. */
~BubbleMessageComponent();
//==============================================================================
/** Shows a message bubble at a particular position.
This shows the bubble with its stem pointing to the given location
(co-ordinates being relative to its parent component).
For details about exactly how it decides where to position itself, see
BubbleComponent::updatePosition().
@param x the x co-ordinate of end of the bubble's tail
@param y the y co-ordinate of end of the bubble's tail
@param message the text to display
@param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
from its parent compnent. If this is 0 or less, it
will stay there until manually removed.
@param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
mouse button is pressed (anywhere on the screen)
@param deleteSelfAfterUse if true, then the component will delete itself after
it becomes invisible
*/
void showAt (int x, int y,
const String& message,
int numMillisecondsBeforeRemoving,
bool removeWhenMouseClicked = true,
bool deleteSelfAfterUse = false);
/** Shows a message bubble next to a particular component.
This shows the bubble with its stem pointing at the given component.
For details about exactly how it decides where to position itself, see
BubbleComponent::updatePosition().
@param component the component that you want to point at
@param message the text to display
@param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
from its parent compnent. If this is 0 or less, it
will stay there until manually removed.
@param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
mouse button is pressed (anywhere on the screen)
@param deleteSelfAfterUse if true, then the component will delete itself after
it becomes invisible
*/
void showAt (Component* component,
const String& message,
int numMillisecondsBeforeRemoving,
bool removeWhenMouseClicked = true,
bool deleteSelfAfterUse = false);
//==============================================================================
/** @internal */
void getContentSize (int& w, int& h);
/** @internal */
void paintContent (Graphics& g, int w, int h);
/** @internal */
void timerCallback();
private:
//==============================================================================
int fadeOutLength, mouseClickCounter;
TextLayout textLayout;
int64 expiryTime;
bool deleteAfterUse;
void init (int numMillisecondsBeforeRemoving,
bool removeWhenMouseClicked,
bool deleteSelfAfterUse);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
};
#endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
| [
"[email protected]"
] | [
[
[
1,
132
]
]
] |
49c4d3a6abe42ccef736bd9c10e94fe7d8c66785 | 155c4955c117f0a37bb9481cd1456b392d0e9a77 | /Tessa/TessaInstructions/ArrayOfInstructions.cpp | 72d812caa2b84bc57c0770a7bbede1e92279678a | [] | no_license | zwetan/tessa | 605720899aa2eb4207632700abe7e2ca157d19e6 | 940404b580054c47f3ced7cf8995794901cf0aaa | refs/heads/master | 2021-01-19T19:54:00.236268 | 2011-08-31T00:18:24 | 2011-08-31T00:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,522 | cpp | #include "TessaInstructionHeader.h"
namespace TessaInstructions {
using namespace TessaVisitors;
ArrayOfInstructions::ArrayOfInstructions(MMgc::GC* gc, TessaVM::BasicBlock* insertAtEnd)
: TessaInstruction(insertAtEnd)
{
instructions = new (gc) List<TessaInstruction*, avmplus::LIST_GCObjects> (gc);
}
void ArrayOfInstructions::addInstruction(TessaInstruction* instruction) {
instructions->add(instruction);
}
void ArrayOfInstructions::print() {
std::string outputString;
outputString += getPrintPrefix();
outputString += " ArrayOfInstructions [";
std::string arrayElements;
for (uint32_t i = 0; i < instructions->size(); i++) {
outputString += " ";
outputString += instructions->get(i)->getOperandString();
outputString += " ";
}
outputString += "]";
printf("%s\n", outputString.c_str());
}
void ArrayOfInstructions::visit(TessaVisitorInterface* tessaVisitor) {
tessaVisitor->visit(this);
}
uint32_t ArrayOfInstructions::size() {
return instructions->size();
}
TessaInstruction* ArrayOfInstructions::getInstruction(uint32_t index) {
TessaAssert(index <= size());
return instructions->get(index);
}
void ArrayOfInstructions::setInstruction(int index, TessaInstruction* instruction) {
instructions->set(index, instruction);
}
List<TessaInstruction*, avmplus::LIST_GCObjects>* ArrayOfInstructions::getInstructions() {
return instructions;
}
bool ArrayOfInstructions::isArrayOfInstructions() {
return true;
}
ArrayOfInstructions* ArrayOfInstructions::clone(MMgc::GC* gc, MMgc::GCHashtable* originalToCloneMap, TessaVM::BasicBlock* insertCloneAtEnd) {
ArrayOfInstructions* clonedArray = new (gc) ArrayOfInstructions(gc, insertCloneAtEnd);
for (uint32_t i = 0; i < size(); i++) {
TessaInstruction* clonedOperand = (TessaInstruction*) originalToCloneMap->get(this->getInstruction(i));
TessaAssert(clonedOperand != NULL);
clonedArray->addInstruction(clonedOperand);
}
return clonedArray;
}
List<TessaValue*, LIST_GCObjects>* ArrayOfInstructions::getOperands(MMgc::GC* gc) {
avmplus::List<TessaValue*, LIST_GCObjects>* operandList = new (gc) avmplus::List<TessaValue*, LIST_GCObjects>(gc);
for (uint32_t i = 0; i < size(); i++) {
//TessaInstruction* operand = (TessaInstruction*) getInstruction(i); ->resolve();
TessaInstruction* operand = (TessaInstruction*) getInstruction(i);
operandList->add(operand);
}
return operandList;
}
} | [
"[email protected]"
] | [
[
[
1,
79
]
]
] |
3b24ba979fa818726011f2e8951ab7f37c16061b | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/addons/pa/ParticleUniverse/src/ParticleObservers/ParticleUniverseOnEmissionObserver.cpp | 34289db80cb8118e08026edbea3e8fe0733e7b60 | [] | 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 | 1,000 | cpp | /*
-----------------------------------------------------------------------------------------------
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.
-----------------------------------------------------------------------------------------------
*/
#include "ParticleUniversePCH.h"
#ifndef PARTICLE_UNIVERSE_EXPORTS
#define PARTICLE_UNIVERSE_EXPORTS
#endif
#include "ParticleObservers/ParticleUniverseOnEmissionObserver.h"
namespace ParticleUniverse
{
//-----------------------------------------------------------------------
bool OnEmissionObserver::_observe (ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed)
{
if (!particle)
return false;
return particle->hasEventFlags(Particle::PEF_EMITTED);
}
}
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
2b406e196cacf5af04466f4d0300e3df85572258 | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/CodeJam/practice/GreedyGovernment.cpp | 945b4ad78c31f3886dffc410208f7df0291d1ae9 | [] | no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,193 | cpp | // BEGIN CUT HERE
// PROBLEM STATEMENT
// You live in a town which is divided into sectors, numbered
// 0 through N-1. In addition, some sectors are connected by
// roads. You must pay a toll to move between sectors. The
// government of your town is rather greedy, and it has
// decided to increase the toll along one of these roads. In
// particular, they are going to increase the toll along a
// road by tollHike dollars, such that the average cost of
// travelling from sector 0 to sector N-1 is maximized. This
// average cost is determined as the average cost over all
// distinct valid paths from sector 0 to sector N-1. Two
// paths from sector 0 to sector N-1 are distinct if they
// either visit a different number of sectors or visit
// sectors in a different order. A path is valid if it does
// not take you through any sector more than once while
// travelling from sector 0 to N-1.
//
//
// Create a class GreedyGovernment which contains a method
// maxAverageCost. You will be given a vector <string> tolls
// and an int tollHike as arguments. The j'th character in
// the i'th element of tolls indicates the toll to travel
// between sectors i and j. If the j'th character in the i'th
// element of tolls is an 'X', then it is not possible to
// travel from sector i to sector j (although you may still
// be able to travel from sector j to sector i). If there is
// no way to travel from sector 0 to sector N-1, your method
// should return 0. Otherwise, the method should return a
// double corresponding to the maximum average cost that the
// government can expect.
//
// DEFINITION
// Class:GreedyGovernment
// Method:maxAverageCost
// Parameters:vector <string>, int
// Returns:double
// Method signature:double maxAverageCost(vector <string>
// tolls, int tollHike)
//
//
// NOTES
// -Your return value must have an absolute or relative error
// less than 1e-9.
//
//
// CONSTRAINTS
// -tolls will contain between 2 and 10 elements, inclusive.
// -Each element of tolls will contain the same number of
// characters as the number of elements in tolls.
// -Each element of tolls will contain only the characters
// '1'-'9', inclusive, or the character 'X'.
// -The i'th character of the i'th element of tolls will be
// 'X' for all i.
// -tollHike will be between 1 and 100, inclusive.
//
//
// EXAMPLES
//
// 0)
// {"X324", "XXX2", "12X5", "991X"}
// 9
//
// Returns: 10.0
//
// Note that there are 4 ways to travel from sector 0 to
// sector 3:
//
// sector 0 --> sector 3
//
// sector 0 --> sector 1 --> sector 3
//
// sector 0 --> sector 2 --> sector 3
//
// sector 0 --> sector 2 --> sector 1 --> sector 3
//
//
// Any other path from sector 0 to sector 3 (for example,
// sector 0 --> sector 2 --> sector 0 --> sector 3) visits a
// sector more than once, which is not allowed in your town.
//
// 1)
// {"X324", "5X22", "12X5", "991X"}
// 57
//
// Returns: 29.2
//
// 2)
// {"X11", "2X1", "37X"}
// 76
//
// Returns: 39.5
//
// 3)
// {"X32X", "XXXX", "XXXX", "XXXX"}
// 99
//
// Returns: 0.0
//
// There is no way to travel from sector 0 to sector 3.
//
// END CUT HERE
#line 104 "GreedyGovernment.cpp"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <list>
#include <stack>
#include <set>
#include <map>
#include <cmath>
#include <valarray>
#include <numeric>
#include <functional>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector< VI > VVI;
typedef vector<char> VC;
typedef vector<string> VS;
typedef map<int,int> MII;
typedef map<string,int> MSI;
typedef stringstream SS;
typedef istringstream ISS;
typedef ostringstream OSS;
#define FOR(i,a,b) for(int i=(a);i<int(b);++i)
#define REP(i,n) FOR(i,0,n)
template<class U,class T> T cast(U x){T y; OSS a; a<<x; ISS b(a.str());b>>y;return y;}
#define ALL(v) (v).begin(),(v).end()
#define SZ(v) ((int)(v).size())
#define FOUND(v,p) (find(ALL(v),p)!=v.end())
#define DV(v) REP(i,SZ(v)) cout << v[i] << " "; cout << endl
#define SUM(v) accumulate(ALL(v),0)
#define SE(i) (i)->second
class GreedyGovernment
{
public:
double maxAverageCost(vector <string> tolls, int tollHike)
{
VVI map(SZ(tolls),VI(SZ(tolls),0));
REP(i,SZ(tolls)) REP(j,SZ(tolls[i])) if(tolls[i][j] != 'X') map[i][j] = tolls[i][j]-'0';
VI st,sp;
VI mk(SZ(tolls),0);
VVI cnt(SZ(tolls),VI(SZ(tolls),0));
st.push_back(0);sp.push_back(0);
int toll = 0;
int sum=0,count=0;
while(!st.empty()){
int p = st.back();
int s = sp.back();
mk[p]=1;
FOR(i,s+1,SZ(tolls)) if(mk[i]==0&&map[p][i]>0){
if( i==SZ(tolls)-1){
sum += toll+map[p][i];
REP(j,SZ(st)-1)cnt[st[j]][st[j+1]]++;
cnt[p][i]++;
count++;
}else{
toll += map[p][i];
st.push_back(i);
sp.push_back(0);
goto END;
}
}
mk[p] = 0;
st.erase(st.end()-1);
sp.erase(sp.end()-1);
if( !sp.empty() ){
toll-= map[st.back()][p];
sp.back()=p;
}
END:
int a=0;
}
int m=0;
REP(i,SZ(tolls))m=max(m,*max_element(ALL(cnt[i])));
return count==0?0:(double)(m*tollHike+sum)/count;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"X324", "XXX2", "12X5", "991X"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; double Arg2 = 10.0; verify_case(0, Arg2, maxAverageCost(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"X324", "5X22", "12X5", "991X"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 57; double Arg2 = 29.2; verify_case(1, Arg2, maxAverageCost(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"X11", "2X1", "37X"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 76; double Arg2 = 39.5; verify_case(2, Arg2, maxAverageCost(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"X32X", "XXXX", "XXXX", "XXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 99; double Arg2 = 0.0; verify_case(3, Arg2, maxAverageCost(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
GreedyGovernment ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
] | [
[
[
1,
208
]
]
] |
607d9e026976eab0da54e0b010f2fb6412b7774b | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/vis/properties/vis_property_names.h | cba948df7406cc66db525ded84c8e42a89e6e67e | [
"MIT",
"BSD-3-Clause"
] | permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | h | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#ifndef __SHAWN_TUBSAPPS_VIS_PROPERTY_NAMES_H
#define __SHAWN_TUBSAPPS_VIS_PROPERTY_NAMES_H
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include <string>
namespace vis
{
extern const std::string PROP_DBL_PRIORITY;
extern const std::string PROP_VEC_POSITION;
extern const std::string PROP_VEC_FG_COLOR;
extern const std::string PROP_VEC_BG_COLOR;
}
#endif
#endif
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/tubsapps/vis/properties/vis_property_names.h,v $
* Version $Revision: 1.1 $
* Date $Date: 2006/01/29 21:02:01 $
*-----------------------------------------------------------------------
* $Log: vis_property_names.h,v $
* Revision 1.1 2006/01/29 21:02:01 ali
* began vis
*
*-----------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
034593728669f48cfff80b85e5a83c7093742d3b | 975d45994f670a7f284b0dc88d3a0ebe44458a82 | /Docs/FINAIS/Fonte/cliente/Source/GameCore/CGameCore.h | 23507361f0978ff680aa909c16afeda87e912295 | [] | no_license | phabh/warbugs | 2b616be17a54fbf46c78b576f17e702f6ddda1e6 | bf1def2f8b7d4267fb7af42df104e9cdbe0378f8 | refs/heads/master | 2020-12-25T08:51:02.308060 | 2010-11-15T00:37:38 | 2010-11-15T00:37:38 | 60,636,297 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,188 | h | #pragma once
#include "GameSetup.h"
#include "PathSetup.h"
#include "CDoubleList.h"
#include "NetworkSetup.h"
#include "CBugSocket.h"
#include "CArquivoConfig.cpp"
#include "CArquivoMatrizes.cpp"
#include "CGerEventos.h"
#include "CGameData.h"
#include "CPersonagem.h"
#include "CToonShader.h"
#include "CVideoTexture.h"
#include "CHudSkin.h"
struct SPersonagemSelecao
{
int _id;
char *_nome;
int _nivel;
int _agilidade;
int _destreza;
int _forca;
int _instinto;
int _resistencia;
int _taxaAtaque;
int _tempoCarga;
int _defesa;
int _ataqueCorporal;
int _danoCorporal;
int _raioAtaque;
int _raioDano;
int _idModelo;
int _idTextura;
int _idHud;
};
class CGameCore
{
private:
typedef CDoubleList<CPersonagem> ListaPersonagem;
typedef CDoubleList<SBolsa> ListaBolsa;
IrrlichtDevice *_dispositivoGrafico;
ISoundEngine *_dispositivoAudio;
IVideoDriver *_gerenciadorVideo;
ISceneManager *_gerenciadorCena;
IGUIEnvironment *_gerenciadorHud;
CGerEventos _gerenciadorEventos;
typedef CDoubleList<IParticleSystemSceneNode> CListaParticulas;
CListaParticulas *_listaParticulas;
CHudImageSkin* _gameSkin;
IGUIFont *_gameFont[NUMHUDFONTS];
ISound* _gameMusic;
ISound* _hudFX[NUMSFXHUD];
CBugSocketClient *_gameSocket;
CBugMessage _packageToSend, // Pacote a enviar
_packageReceived; // Pacote a receber
//! Objeto para carregar as matrizes de colisão do cenário
CArquivoMatrizes *_fileMtx;
//! Objeto para carregar as configurações do jogo
CArquivoConfig *_fileCfg;
TypeCfg _gameConfig;
char _myLogin[15],
_myPassword[15];
bool _connected; // Identifica se o cliente está conectado ao servidor
int _particleCount;
ILightSceneNode *_luz;
CToonShader *_toonShader; // Classe de ToonShader
CVideoTexture *_cutScene[CS_COUNT];
//! Matriz de colisões do cenário atual
SMatrix _cenario;
//! Lista de personagens do cenário
ListaPersonagem *_listaPersonagens;
//! Lista de bolsas do cenário
ListaBolsa *_listaBolsas;
//! Identificação da lua corrente
int _sceneMoon;
//! Lista de portais para troca de cenário
SQuadrante _portal[MAXPORTAIS];
ITerrainSceneNode *_sceneTerrain;
public:
IBoneSceneNode *boneCabeca, *boneMao;
IAnimatedMeshSceneNode *capacete, *maca;
bool showContorno;
std::string SERVERHOST;
int SERVERPORT;
//= "127.0.0.1";//"warbugs.ddns.com.br";/*"189.61.169.212"; "10.16.11.31";*/ // IP do servidor
//const int SERVERPORT
ITriangleSelector* _sceneTris;
ICameraSceneNode *_gameCamera;
ISceneNode *_emptyCam; // nodo vazio para camera
float camRotVert, camRotHor; // rotações do empty da camera
int sWidth, sHeight;
CHudProgressBar* _barraLoad;
CGameData *_gameData;
//CGameScene *_gameScene;
int _numMyChars;
int _myUserID;
int _myCharID;
int _myCharSceneID;
int _myMapSceneID;
//! Ponteiro para o meu personagem
CPersonagem *_myPlayerChar;
SPersonagemSelecao _myStructChar[MAXSLOTPERSONAGEM];
IAnimatedMeshSceneNode *_myChar[MAXSLOTPERSONAGEM];
IAnimatedMesh* getMAnimMesh(int idMesh);
ITexture* getMTexture(int idTexture);
CGameCore(int &startInit);
void drop();
void loadGameData();
void loadGameData(int stage);
IrrlichtDevice * getGraphicDevice();
ISoundEngine * getSoundDevice();
CGerEventos * getEventManager();
void initToonShader();
void loadSkin(int idSkin);
void getAllManagers(IrrlichtDevice*&dispGrafico, ISoundEngine*&dispAudio, CGerEventos*&gerEventos, ISceneManager*&gerCena, IVideoDriver*&gerVideo, IGUIEnvironment*&gerHud, TypeCfg &gameCfg);
void playMusic( char* soundFile, bool looped = true, bool startPaused = false, bool track = false, E_STREAM_MODE modo = ESM_AUTO_DETECT, bool efeitos = false);
bool playCutScene( int idCutScene, int volume);
IParticleSystemSceneNode* addPaticleNode(TypeParticle tipo, int tempoVida, vector3df posicao, vector3df escala);
void loadMenuScene(c8 *sceneFile);
int getNumCharSlots();
void loadGameScene(c8 *sceneFile);
/*
void setMyMapSceneID(int idMapa);
void setMyCharSceneID(int idChar);
void setSceneQuadPortalID(int idQuadPortal1, int idQuadPortal2, int idQuadPortal3, int idQuadPortal4);
*/
//! Calcula a rotação resultante entre três eixos (X,Y,Z).
vector3df rotacaoResultante(f32 rotX, f32 rotY, f32 rotZ);
ICameraSceneNode *createCamera( vector3df posicao, vector3df target = vector3df(0,0,100) , vector3df rotacao = vector3df(0,0,0), ISceneNode *parent = 0, f32 angulo = 179.0f/*bool isOrtogonal = true*/, bool bind = true);
void createLight(ISceneNode *parent, vector3df posicao, f32 raio);
void addContour(ISceneNode* oNode, f32 fThickness = 3, SColor cColor = SColor(255,0,0,0));
void contourAll(ISceneNode* node);
//! Carrega a matriz de colisão do cenário atual
SMatrix loadSceneMatrix(int idScene);
//! Inclui uma bolsa no cenário
void addBolsa(int idBolsa, float posX, float posZ);
//! Remove uma bolsa do cenário
void removeBolsa(int idBolsa);
//! Inclui um personagem no cenário
void addPersonagem(CPersonagem *personagem);
//! Remove um personagem do cenário
void removePersonagem(int idPersonagem);
//! Atualiza a posição de um personagem
void updCharPosition(int idPersonagem, float posX, float posZ);
//! Atualiza o estado de animação de um personagem
void updCharState(int idPersonagem, int estado);
//! Atualiza o alvo de um personagem
void updCharTarget(int idPersonagem, float posX, float posZ);
//! Atualiza os itens equipados por um personagem
void updCharEquipment(int idPersonagem, int idArmadura, int idArma);
//! Atualiza a direção e a velocidade de um personagem
void updCharDirectionVelocity(int idPersonagem, int direction, int velocity);
//! Atualiza os buffs de um personagem
void updCharBuff(int idPersonagem, short buffs);
//! Atualiza os ids dos quadrantes dos portais no cenário
void updMapPortals(int idQuadPortal1, int idQuadPortal2, int idQuadPortal3, int idQuadPortal4);
//! Atualiza a lua corrente do cenário
void updMoon(int idLua);
//! Retorna a coordenada3D do centro de um quadrante
vector3df getQuadCenter(int linha, int coluna);
//! Retorna a coordenada3D do centro de um quadrante
vector3df getQuadCenter(int idQuad);
//! Retorna a coordenada3D do centro de um quadrante
vector3df getQuadCenter(vector3df posicao);
//! Retorna por parâmetros a linha e a coluna de uma posicao
void getQuadLinhaColuna(vector3df posicao, int &linha, int &coluna);
//! Retorna por parâmetros a linha e a coluna de um determinado quadrante
void getQuadLinhaColuna(int idQuad, int &linha, int &coluna);
//! Retorna o id do quadrante referente a uma posição
int getQuadID(vector3df posicao);
//! Retorna o id do quadrante referente a linha e coluna
int getQuadID(int linha, int coluna);
//! Atualiza a posição 3D de um elemento do cenário
vector3df upd3DPosition(float posX, float posZ);
float getDistancia(vector3df v1, vector3df v2);
int manhattan(int linhaO, int colunaO, int linhaD, int colunaD);
int pathfindingRTA(CPersonagem *personagem);
bool conectar(char *login, char *password);
bool isConnected();
void enviarPacote(int packageID);
void enviarPacote(int packageID, int i1);
void enviarPacote(int packageID, int i1, int i2);
void enviarPacote(int packageID, int i1, int i2, int i3);
void enviarPacote(int packageID, int i1, int i2, char *s1 );
void enviarPacote(int packageID, int i1, int i2, int i3, int i4);
void enviarPacote(int packageID, int i1, int i2, int i3, int i4, int i5, int i6);
void enviarPacote(int packageID, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9);
void enviarPacote(int packageID, int i1, char *s1);
void enviarPacote(int packageID, int i1, float f1, float f2);
void enviarPacote(int packageID, int i1, int i2, int i3, float f1, float f2);
void enviarPacote(int packageID, char *s1, char *s2);
int receberPacote();
}; | [
"[email protected]"
] | [
[
[
1,
292
]
]
] |
4407ddc6ecc1bccdf4fa60bd99cc0c0c7bbb4c3f | 016c54cb102ac6b792ee9756614d43b5687950b7 | /UiCommon/UiSwitchOption.h | ef77026b68e0b950b36130ba52ee99df5227ae48 | [] | no_license | jemyzhang/MzCommonDll | 3103fc4f5214a069c473b5aaca90aaf09d355517 | 82cbfa7eaa872809fa0bdea4531d5df73e23ca47 | refs/heads/master | 2021-01-19T14:53:26.687575 | 2010-05-20T03:18:16 | 2010-05-20T03:18:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 882 | h | #pragma once
/*
* @filename UiSwitchOption.h
* @note 开关选择, ID: 本体 ID+0x100: 开关
* @author JEMYZHANG
* @date 2009.10.16
* @ver. 1.0
* @changelog
* ver.1.0 初始化程序
*/
#include <MzCommonDll.h>
class COMMON_API UiSwitchOption : public UiButtonEx
{
MZ_DECLARE_DYNAMIC(UiSwitchOption);
public:
UiSwitchOption(void);
~UiSwitchOption(void);
public:
UiButtonEx m_Switch;
void SetPos(int x, int y, int w, int h, UINT flags=0){
m_Switch.SetPos(w-120,0,120,h,flags);
UiButtonEx::SetPos(x,y,w,h,flags);
}
void SetID(int nID){
m_Switch.SetID(nID + 0x100);
UiButtonEx::SetID(nID);
}
public:
BOOL GetSwitchStatus(){ //true: switch on
return (m_Switch.GetState() == MZCS_BUTTON_PRESSED);
}
void SetSwitchStatus(BOOL s){
m_Switch.SetState(s ? MZCS_BUTTON_PRESSED : MZCS_BUTTON_NORMAL);
}
protected:
};
| [
"jemyzhang@96341596-6814-2f4c-99ee-b9cf7f28d869"
] | [
[
[
1,
39
]
]
] |
0fa426d1ddbddf7fe6eb1d9a76c2110dba35e32f | ae0b041a5fb2170a3d1095868a7535cc82d6661f | /MFCSort/sortDlg.cpp | b4db907f37c1b3d9adefa5d1c116f04f2db4948e | [] | no_license | hexonxons/6thSemester | 59c479a1bb3cd715744543f4c2e0f8fdbf336f4a | c3c8fdea6eef49de629a7f454b91ceabd58d15d8 | refs/heads/master | 2016-09-15T17:45:13.433434 | 2011-06-08T20:57:25 | 2011-06-08T20:57:25 | 1,467,281 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,466 | cpp | // sortDlg.cpp : implementation file
//
#include "stdafx.h"
#include "sort.h"
#include "sortDlg.h"
#include "perfcounter.h"
#include "../includes/banned.h"
#include "mergesort.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// определение функции сортировки
void Sort(Sort1Array &array, CompareSort1Type cmpFunc);
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSortDlg dialog
CSortDlg::CSortDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSortDlg::IDD, pParent)
, m_sortMethod(0)
{
//{{AFX_DATA_INIT(CSortDlg)
m_FIO = _T("");
m_Date = COleDateTime::GetCurrentTime();
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CSortDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSortDlg)
DDX_Control(pDX, IDC_LIST2, m_OutputList);
DDX_Control(pDX, IDC_LIST1, m_InputList);
DDX_Text(pDX, IDC_FIO, m_FIO);
DDV_MaxChars(pDX, m_FIO, 120);
DDX_DateTimeCtrl(pDX, IDC_DATE, m_Date);
//}}AFX_DATA_MAP
DDX_CBIndex(pDX, IDC_COMBO1, m_sortMethod);
}
BEGIN_MESSAGE_MAP(CSortDlg, CDialog)
//{{AFX_MSG_MAP(CSortDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_SORT, OnSort)
ON_BN_CLICKED(IDC_ADD, OnAdd)
ON_BN_CLICKED(IDC_CLEAR_LIST, OnClearList)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSortDlg message handlers
BOOL CSortDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CSortDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CSortDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CSortDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CSortDlg::OnOK()
{
ClearSort1Array(m_Array);
CDialog::OnOK();
}
/// Нажатие на кнопку "Очистить"
void CSortDlg::OnClearList()
{
if(AfxMessageBox("Вы уверены, что хотите очистить список", MB_YESNO) == IDYES)
{
m_InputList.ResetContent();
m_OutputList.ResetContent();
ClearSort1Array(m_Array);
}
}
/// Нажатие на кнопку "Добавить"
void CSortDlg::OnAdd()
{
if(!UpdateData(TRUE))
return;
if(m_FIO.IsEmpty())
{
AfxMessageBox("Вы забыли заполнить поле!");
return;
}
CString Date = m_Date.Format("%Y.%m.%d");
Sort1 *pNew = CreateNewSort1Element(m_FIO, Date);
if(!pNew)
{
AfxMessageBox("Ошибка выделения памяти");
return;
}
m_Array.Add(pNew);
AddElementToList(pNew, m_InputList);
m_FIO.Empty();
m_Date = COleDateTime::GetCurrentTime();
UpdateData(FALSE);
}
/// Нажатие на кнопку "Сортировать"
void CSortDlg::OnSort()
{
if(!UpdateData(TRUE))
return;
if(m_sortMethod == 0)
Sort(m_Array, CompareSort1FIO);
if(m_sortMethod == 1)
Sort(m_Array, CompareSort1Date);
m_OutputList.ResetContent();
for (int i = 0; i < m_Array.GetSize(); ++i)
{
m_OutputList.AddString(m_Array.GetAt(i)->FIO + " " + m_Array[i]->Date);
}
}
int CompareByFIO (Sort1 *left, Sort1 *right)
{
return left->FIO.CompareNoCase(right->FIO) < 0;
}
int CompareByDate(Sort1 *left, Sort1 *right)
{
return left->Date.CompareNoCase(right->Date) < 0;
}
///Сортировка
void Sort(Sort1Array &array, CompareSort1Type cmpFunc)
{
if (array.GetSize() != 0)
{
MergeSort(array.GetData(), array.GetData() + array.GetSize(), cmpFunc);
}
}
| [
"[email protected]"
] | [
[
[
1,
268
]
]
] |
503543a969716f2b1a1ef12f56a0aa936a7c3a16 | b63cad17af550bc7150431b7b0d639a46a129d82 | /mcscript-expr-handler.h | f83c24627eec39c942af468b8453806fb4146aaa | [] | no_license | cjus/msgCourier | 90463028b5e6222dd5c804215fa43bc518c4a539 | 075ff724316fd28c21d842726b694806d82bf53b | refs/heads/master | 2021-01-10T19:41:02.306930 | 2010-09-05T18:47:24 | 2010-09-05T18:47:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | h | /* mcscript-expr-handler.h
Copyright (C) 2005 Carlos Justiniano
mcscript-expr-handler.h 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.
mcscript-expr-handler.h was developed by Carlos Justiniano for use on the
ChessBrain Project (http://www.chessbrain.net) and is now 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 mcscript-expr-handler.h; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
@file mcscript-expr-handler.h
@brief Message Courier Script Handlers
@author Carlos Justiniano
@attention Copyright (C) 2005 Carlos Justiniano, GNU GPL Licence (see source file header)
Message Courier Script Handlers.
*/
#ifndef _MCSCRIPT_EXPR_HANDLER_H
#define _MCSCRIPT_EXPR_HANDLER_H
#include <string>
#include "mcscript.h"
/****************
* Expr Handler *
****************/
class cMCExprHandler : public cMCScriptKeywordHandler
{
public:
int Process(cMCScript *pMCScript, cXMLLiteParser *pXML, std::string *pOutputBuffer)
{
return 0;
}
};
#endif //_MCSCRIPT_EXPR_HANDLER_H
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
7ecd83d6aad0b31667715417cbbd75ce267b3efb | fac8de123987842827a68da1b580f1361926ab67 | /src/transporter/game/gameScene.cpp | c96f666082d232dfd903928f5e01cfa043f3ff60 | [] | 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 | SHIFT_JIS | C++ | false | false | 1,134 | cpp | #include "transporter.h"
GameScene::GameScene()
{
game = NULL;
surface = NULL;
car = NULL;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
GameScene::~GameScene()
{
cleanUp();
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit GameScene::init( Game* game )
{
this->game = game;
return true;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void GameScene::cleanUp()
{
if(car)
{
delete car;
car = NULL;
}
if(surface)
{
delete surface;
surface = NULL;
}
physicsWorld.cleanUp();
visualWorld.cleanUp();
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void GameScene::createEntities()
{
surface = new Surface(game);
surface->init("surface");
car = new CarEntity(surface);
car->init("car");
} | [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
52
]
]
] |
71b9107339736e2c3728faaad93a13ee24a17ed6 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/STLPort-4.0/test/eh/TestClass.h | dccb327d0a7e22b2b4241d875f0169e1cc79d4e2 | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,194 | h | /***********************************************************************************
TestClass.h
* Copyright (c) 1997-1998
* Mark of the Unicorn, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Mark of the Unicorn makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
SUMMARY: TestClass simulates a class that uses resources. It is designed to
cause exceptions when it is constructed or copied.
***********************************************************************************/
#ifndef INCLUDED_MOTU_TestClass
#define INCLUDED_MOTU_TestClass 1
# include "Prefix.h"
# if defined (EH_NEW_HEADERS)
# include <functional>
# include <utility>
# include <climits>
# else
# include <function.h>
# include <pair.h>
# include <limits.h>
# endif
#include <iosfwd>
#include "random_number.h"
#include "nc_alloc.h"
class TestClass
{
public:
inline TestClass();
inline TestClass( int value );
inline TestClass( const TestClass& rhs );
inline ~TestClass();
inline TestClass& operator=( const TestClass& rhs );
inline int value() const;
inline TestClass operator!() const;
inline bool operator==( const TestClass& rhs ) const
{
return value() == rhs.value();
}
protected:
static inline unsigned int get_random(unsigned range = UINT_MAX);
private:
inline void Init( int value );
#if TESTCLASS_DEEP_DATA
int *p;
#else
int v;
#endif
};
#if defined( __MWERKS__ ) && __MWERKS__ <= 0x3000 && !__SGI_STL
# if defined( __MSL__ ) && __MSL__ < 0x2406
# include <iterator.h>
__MSL_FIX_ITERATORS__(TestClass);
__MSL_FIX_ITERATORS__(const TestClass);
typedef EH_STD::pair<const TestClass, TestClass> pair_testclass_testclass;
__MSL_FIX_ITERATORS__( pair_testclass_testclass );
__MSL_FIX_ITERATORS__( const pair_testclass_testclass );
# endif
#endif
inline void TestClass::Init( int value )
{
#if TESTCLASS_DEEP_DATA
p = new int( value );
#else
simulate_constructor();
v = value;
#endif
}
inline TestClass::TestClass()
{
Init( int(get_random()) );
}
inline TestClass::TestClass( int value )
{
Init( value );
}
inline TestClass::TestClass( const TestClass& rhs )
{
Init( rhs.value() );
}
inline TestClass::~TestClass()
{
#if TESTCLASS_DEEP_DATA
delete p;
#else
simulate_destructor();
#endif
}
inline TestClass& TestClass::operator=( const TestClass& rhs )
{
#if TESTCLASS_DEEP_DATA
int *newP = new int( rhs.value() );
delete p;
p = newP;
#else
simulate_possible_failure();
v = rhs.value();
#endif
return *this;
}
inline int TestClass::value() const
{
#if TESTCLASS_DEEP_DATA
return *p;
#else
return v;
#endif
}
inline TestClass TestClass::operator!() const
{
return TestClass( value()+1 );
}
inline bool operator<( const TestClass& lhs, const TestClass& rhs ) {
return lhs.value() < rhs.value();
}
inline bool operator>( const TestClass& lhs, const TestClass& rhs ) {
return rhs < lhs;
}
inline bool operator>=( const TestClass& lhs, const TestClass& rhs ) {
return !(lhs < rhs);
}
inline bool operator<=( const TestClass& lhs, const TestClass& rhs ) {
return !(rhs < lhs);
}
# if 0
inline bool operator==( const TestClass& lhs, const TestClass& rhs )
{
return lhs.value() == rhs.value();
}
# endif
inline bool operator != ( const TestClass& lhs, const TestClass& rhs ) {
return lhs.value() != rhs.value();
}
inline unsigned int TestClass::get_random( unsigned range )
{
return random_number( range );
}
# ifdef EH_NEW_IOSTREAMS
extern EH_STD::ostream& operator << ( EH_STD::ostream& s, const TestClass&);
# else
extern ostream& operator << ( ostream& s, const TestClass&);
# endif
#endif // INCLUDED_MOTU_TestClass
| [
"[email protected]"
] | [
[
[
1,
179
]
]
] |
426b346dce57e194afcdb1a23654d4cbbdecba23 | bf971db1963b088a40a39a9f72e2fc60544e711a | /zstring.h | 524853763afd0518766eec93b4d279f75fba8be7 | [] | no_license | zebraxxl/sini | 9b95ffbfd016c734af1482d49b3aab17adc751e4 | 3a679b6cf99f26e1c5f409787f502c07beee1313 | refs/heads/master | 2016-09-10T12:32:17.793675 | 2011-09-09T21:16:10 | 2011-09-09T21:16:10 | 32,348,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,894 | h | #ifndef __ZSTRING_H__
#define __ZSTRING_H__
#include "zalgoritms.h"
template <class T>
class CZString
{
private:
T *Data;
unsigned int Length;
unsigned int Allocated;
inline CZString( T *Ptr, unsigned int Len, unsigned int Alloc )
{
Data = Ptr;
Length = Len;
Allocated = Alloc;
}
inline void Resize( unsigned int NewLength )
{
if (Allocated < NewLength )
{
T *NewData = new T[NewLength];
za_memcpy<T>( NewData, Data, Length+1 );
delete [] Data;
Data = NewData;
Allocated = NewLength;
}
}
public:
static const unsigned int Nop = 0xffffffff;
inline unsigned int get_length()const{return Length;}
inline unsigned int get_allocated()const{return Allocated;}
inline const T* get_ptr()const{return Data;}
inline CZString()
{
Data = new T[16];
za_memset<T>( Data, 0, 16 );
Length = 0;
Allocated = 16;
}
inline CZString( const T *Ptr )
{
Length = za_strlen( Ptr );
Allocated = za_max( Length+1, 16 );
Data = new T[Allocated];
za_strcpy<T>( Data, Ptr );
}
inline CZString( const CZString &Other )
{
Length = Other.get_length();
Allocated = Other.get_allocated();
Data = new T[Allocated];
za_memcpy<T>( Data, Other.get_ptr(), Length+1 );
}
inline CZString( const T *Ptr, unsigned int Len )
{
Length = Len;
Allocated = za_max( Len+1, 16 );
Data = new T[Allocated];
za_memcpy<T>( Data, Ptr, Len );
Data[Len] = 0;
}
inline ~CZString()
{
delete [] Data;
}
inline const T&operator[](unsigned int i)const {return Data[i];}
inline T&operator[](unsigned int i) {return Data[i];}
inline const T& At( unsigned int i )const {return Data[i];}
inline T& At( unsigned int i ) {return Data[i];}
inline CZString &operator=(const CZString &Other )
{
delete [] Data;
Allocated = Other.get_allocated();
Data = new T[Allocated];
Length = Other.get_length();
za_memcpy<T>( Data, Other.get_ptr(), Length );
Data[Length] = 0;
return *this;
}
inline CZString operator+( const CZString &Other )const
{
unsigned int NewLen = Length + Other.Length;
unsigned int NewAllocated = za_max( NewLen+1, 16 );
T *NewData = new T[NewAllocated];
za_memcpy<T>( NewData, Data, Length );
za_memcpy<T>( &NewData[Length], Other.Data, Other.Length );
NewData[NewLen] = 0;
return CZString( NewData, NewLen, NewAllocated );
}
inline CZString operator+( const T *Other )const
{
unsigned int OtherLength = za_strlen( Other );
unsigned int NewLen = Length + OtherLength;
unsigned int NewAllocated = za_max( NewLen+1, 16 );
T *NewData = new T[NewAllocated];
za_memcpy<T>( NewData, Data, Length );
za_memcpy<T>( &NewData[Length], Other, OtherLength );
NewData[NewLen] = 0;
return CZString( NewData, NewLen, NewAllocated );
}
inline CZString &operator+=( const CZString &Other )
{
unsigned int NewLen = Length + Other.Length;
Resize( NewLen+1 );
za_memcpy( &Data[Length], Other.Data, Other.Length+1 );
Length = NewLen;
return *this;
}
inline CZString &operator+=( const T *Other )
{
unsigned int OtherLength = za_strlen<T>( Other );
unsigned int NewLen = Length + OtherLength;
Resize( NewLen+1 );
za_memcpy( &Data[Length], Other, OtherLength+1 );
Length = NewLen;
return *this;
}
inline bool operator==(const CZString& Other)const
{
if (Length != Other.Length)
return false;
for (unsigned int i = 0; i < Length; i++)
if (Data[i] != Other.Data[i])
return false;
return true;
}
inline bool operator!=(const CZString& Other)const
{
if (Length != Other.Length)
return true;
for (unsigned int i = 0; i < Length; i++)
if (Data[i] != Other.Data[i])
return true;
return false;
}
inline unsigned int IndexOf( T What, unsigned int Start = 0, unsigned int End = 0xffffffff )const
{
if (End > Length)
End = Length;
for (unsigned int i = Start; i < End; i++)
if (What == Data[i])
return i;
return Nop;
}
inline unsigned int LastIndexOf( T What, unsigned int Start = 0, unsigned int End = 0xffffffff )const
{
if (End > Length)
End = Length;
for (unsigned int i = End; i >= Start; i--)
{
if (What == Data[i])
return i;
if (i == 0)
break;
}
return Nop;
}
inline CZString SubStr( unsigned int Start, unsigned int Count = 0xffffffff )const
{
if (Count > Length - Start)
Count = Length - Start;
return CZString( &Data[Start], Count );
}
inline void Insert( const CZString &What, unsigned int Where )
{
CZString End = SubStr( Where );
Length = Where;
Data[Where] = 0;
(*this) += What + End;
}
inline bool IsEmpty()const
{
return (Data[0] == 0);
}
};
typedef CZString<char> CZStringA;
typedef CZString<wchar_t> CZStringW;
#endif //__ZSTRING_H__
| [
"zebraxxl@38bddf81-f72c-4749-2c60-6f4cd93a2835"
] | [
[
[
1,
205
]
]
] |
44c081136c28c46e2ae9f3d7efa0d0f1b4170282 | 995feb15e565ed62ed872932e02333aca400608a | /XLW2p1/InterfaceGenerator/FunctionModel.h | e635a398be1cd7be697d80bbfd1f0ccbbc1b006f | [] | no_license | wyyrepo/fann-excel | 89b34a8ab4f0a49e8152f774dcb65f4fbc274b27 | 447ba1937d59b503bf451b4d8b3d43856179b7e0 | refs/heads/master | 2021-05-29T13:33:43.841025 | 2009-08-29T18:30:53 | 2009-08-29T18:30:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | h | /*
Copyright (C) 2006 Mark Joshi
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email [email protected]
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 license for more details.
*/
#ifndef FUNCTION_MODEL_H
#define FUNCTION_MODEL_H
#include <vector>
#include <string>
class FunctionModel
{
public:
FunctionModel(std::string ReturnType_, std::string Name, std::string Description, bool Volatile_=false, bool Time_=false);
void AddArgument(std::string Type_, std::string Name_, std::string Description_);
size_t GetNumberArgs() const;
std::string GetReturnType() const
{
return ReturnType;
}
std::string GetFunctionName() const
{
return FunctionName;
}
std::string GetFunctionDescription() const
{
return FunctionDescription;
}
std::string GetArgumentReturnType(int i) const
{
return ArgumentTypes.at(i);
}
std::string GetArgumentFunctionName(int i) const
{
return ArgumentNames.at(i);
}
std::string GetArgumentFunctionDescription(int i) const
{
return ArgumentDescs.at(i);
}
bool GetVolatile() const
{
return Volatile;
}
bool DoTime() const
{
return Time;
}
void SetTime(bool doit)
{
Time=doit;
}
private:
std::string ReturnType;
std::string FunctionName;
std::string FunctionDescription;
bool Volatile;
bool Time;
std::vector<std::string > ArgumentTypes;
std::vector<std::string > ArgumentNames;
std::vector<std::string > ArgumentDescs;
};
#endif
| [
"marek.ozana@62256918-840b-11de-97a7-19ffed92f3b0"
] | [
[
[
1,
89
]
]
] |
f2ea7914308d4369ab46640c245962bbbed42e3b | eafa9c8d8ab765faea768c1a89bdeb586d629591 | /Multiplayer Bomberman/Visualisation.h | 68859cb5a95a449ecdce0aea05842bbf3f64a272 | [] | no_license | Norcinu/Demo | 1f5ec338ae9de269eb9dbfda7c787271eddfea9c | bf8f61d194b7f1435356a67671772692144ef27c | refs/heads/master | 2020-06-04T00:21:00.729640 | 2011-07-13T20:11:38 | 2011-07-13T20:11:38 | 2,043,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,284 | h | #ifndef VISUALISATION_H
#define VISUALISATION_H
#include <string>
#include <vector>
#include <cassert>
#include <SDL.h>
#include "maths.h"
#include "Rectangle.h"
class Sprite;
class Visualisation
{
public:
Visualisation(void);
~Visualisation(void);
bool Initialise(const int height, const int width, bool fscreen=false);
bool AddSprite(int * id, const std::string& file);
bool IsEmpty() const { return sprites.empty(); }
void ClearScreen();
void ClearScreen(Uint32 colour);
void FillRectangle(const SDL_Rect & rec, const std::string& col);
void SetPixel(int x, int y, const Uint32 colour);
void CalculateFPS();
void Quit(const int exit_code);
void ClearGraphicSet();
void DrawSprite(const int id, const math::Vector2& frame, /*const*/ math::Vector2& pos);
void DrawLine(math::Vector2& p1, math::Vector2& p2, Uint32 colour = 0);
void FillRectangle(const rec::Rectangle& p);
void BeginScene();
void EndScene();
Uint32 GetPixel(SDL_Surface * surface, int x, int y);
SDL_Surface * GetScreenSurface() const { return screen; }
private:
SDL_Surface * screen;
bool full_screen;
int screen_width;
int screen_height;
int screen_depth;
std::vector<Sprite*> sprites;
SDL_Rect ui_rectangle;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
8eec406f4aaa197309ed7e21874b20ec8bc61176 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/persistence2/engine/core/src/ParticleSystemObject.cpp | 5e38f895957d4b813982e2a90b012f2ee3f845ae | [
"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 | 1,864 | 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" //precompiled header
#include "ParticleSystemObject.h"
#include "Actor.h"
#include "CoreSubsystem.h"
#include "World.h"
using namespace Ogre;
namespace rl {
ParticleSystemObject::ParticleSystemObject(const String& name, const String& partSys)
{
ParticleSystem* part = CoreSubsystem::getSingletonPtr()->getWorld()
->getSceneManager()->createParticleSystem(name,partSys);
mMovableObject = part;
}
ParticleSystemObject::~ParticleSystemObject()
{
CoreSubsystem::getSingletonPtr()->getWorld()
->getSceneManager()->destroyParticleSystem(getParticleSystem());
}
ParticleSystem* ParticleSystemObject::getParticleSystem() const
{
return static_cast<ParticleSystem*>(mMovableObject);
}
String ParticleSystemObject::getObjectType() const
{
return "ParticleSystemObject";
}
void ParticleSystemObject::setActive(bool active)
{
ParticleSystem* part = getParticleSystem();
unsigned int numEmitters = part->getNumEmitters();
for (unsigned int emitterIdx = 0; emitterIdx < numEmitters; emitterIdx++)
{
part->getEmitter(emitterIdx)->setEnabled(active);
}
}
}
| [
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
62
]
]
] |
50cb5066d65061b8b09a17fe0ed3ffa6629936ca | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/ParticleUniverse/include/ParticleEventHandlers/ParticleUniverseDoAffectorEventHandlerFactory.h | dc4110a35861d548de786fc49e249cd41d1f5a53 | [] | no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,982 | h | /*
-----------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2006-2008 Henry van Merode
Usage of this program is free for non-commercial use and licensed under the
the terms of the GNU Lesser General Public License.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __PU_DO_AFFECTOR_EVENT_HANDLER_FACTORY_H__
#define __PU_DO_AFFECTOR_EVENT_HANDLER_FACTORY_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseEventHandlerFactory.h"
#include "ParticleUniverseDoAffectorEventHandlerTokens.h"
#include "ParticleUniverseDoAffectorEventHandler.h"
namespace ParticleUniverse
{
/** This factory class is responsible for creation of a DoAffectorEventHandler.
*/
class _ParticleUniverseExport DoAffectorEventHandlerFactory : public ParticleEventHandlerFactory
{
public:
DoAffectorEventHandlerFactory(void) {};
virtual ~DoAffectorEventHandlerFactory(void) {};
/** See ParticleEventHandlerFactory */
virtual Ogre::String getEventHandlerType(void) const
{
return "DoAffector";
}
/** See ParticleEventHandlerFactory */
virtual ParticleEventHandler* createEventHandler(void)
{
return _createEventHandler<DoAffectorEventHandler>();
}
/** See ParticleEventHandlerFactory */
virtual void setupTokenDefinitions(ITokenRegister* tokenRegister)
{
// Delegate to mDoAffectorEventHandlerTokens
mDoAffectorEventHandlerTokens.setupTokenDefinitions(tokenRegister);
}
protected:
DoAffectorEventHandlerTokens mDoAffectorEventHandlerTokens;
};
}
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
] | [
[
[
1,
59
]
]
] |
1944af48db4b5698198e4e8386b2150c549eecba | 8e884f5b3617ff81a593273fb23286b4d789f548 | /Source/PCL_Collection.cpp | 0690e1d50a06e47f765d0bb41b2b20d1248668a9 | [] | no_license | mau4x/PCL-1 | 76716e6af3f1e616ca99ac790ef6c5e8c36a8d46 | b440c2ce3f3016c0c6f2ecdea9643f1a9bae19cc | refs/heads/master | 2020-04-06T21:48:35.864329 | 2011-08-12T21:38:54 | 2011-08-12T21:38:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,006 | cpp | ///!
//*!===========================================================================!
//*! PCL stands for Portable Class Library and is designed for development
//*! of applications portable between different environments,
//*! first of all between MS Windows and GNU Linux.
//*!
//*! CopyFree Pulse Computer Consulting, 2001 - 2011
//*!
//*! CopyFree License Agreement:
//*! 1.You may do with this code WHATEVER YOU LIKE.
//*! 2.In NO CASE Pulse Computer Consulting is responsible for your results.
//*!
//*! E-mail: [email protected], [email protected]
//*!===========================================================================!
///!
#define PCL_IMPLEMENTATION
#include "PCL.hxx"
///! Implementation of _WCollectionHeader
_WCollectionHeader::_WCollectionHeader() : LVector(sizeof(ZCollectionHeader)) {
m_pItem = NULL;
m_itemSize = 0;
m_pDbg = new LException(ZIgnore);
}
_WCollectionHeader::~_WCollectionHeader() {
delete m_pDbg;
}
void _WCollectionHeader::AfterInsert(pvoid _pHdr, uint HdrSize) {
m_pDbg->Signal("_WCollectionHeader::AfterInsert");
pZCollectionHeader pHdr = (pZCollectionHeader)_pHdr;
if (!m_pItem) {
m_pDbg->Signal("Empty Item Insert");
pHdr->pMem = NULL;
pHdr->itemSize = 0;
}
else {
pHdr->pMem = new LMemory(m_itemSize);
memcpy(pHdr->pMem->Addr(), m_pItem, m_itemSize);
pHdr->itemSize = m_itemSize;
m_pItem = pHdr->pMem->Addr();
}
return;
}
void _WCollectionHeader::BeforeRemove(pvoid _pHdr, uint HdrSize) {
m_pDbg->Signal("_WCollectionHeader::BeforeRemove");
pZCollectionHeader pHdr = (pZCollectionHeader)_pHdr;
if (pHdr->pMem) {
delete pHdr->pMem;
pHdr->pMem = NULL;
pHdr->itemSize = 0;
}
return;
}
///! Implementation of LCollection
VIterator& LCollection::NewIterator(ZFilter pFilter) {
return *_CreateIterator(pFilter);
}
void LCollection::DeleteIterator(const VIterator& Iter) {
_RemoveIterator(const_cast<VIterator*>(&Iter));
}
VIterator * LCollection::_CreateIterator(ZFilter pFilter) {
VIterator *result = &m_cHdr.NewIterator(pFilter);
return result;
}
void LCollection::_RemoveIterator(VIterator * pIter) {
// delete pIter;
}
LCollection::LCollection(void) {
m_head = m_last = NULL;
m_itemSize = ZUintInvalid;
m_pIter[0] = &NewIterator(NULL);
m_iterCount = 1;
}
LCollection::LCollection(const pcont pContainer) {
m_head = m_last = NULL;
m_itemSize = ZUintInvalid;
m_pIter[0] = &NewIterator(NULL);
m_iterCount = 1;
Import(pContainer);
}
LCollection::~LCollection() {
for (uint i = 0; i < m_iterCount; i++) { // Remove all the iterators
_RemoveIterator(m_pIter[i]);
}
m_iterCount = 0;
RemoveAll();
}
const pcont LCollection::Export() {
XErrorSetLast(E_NOTIMPL, "Export is not implemented yet");
XErrorSignal("LCollection::Export");
return NULL;
}
void LCollection::Import(const pcont pContainer, bool AutoRelease) {
XErrorSetLast(E_NOTIMPL, "Import is not implemented yet");
XErrorSignal("LCollection::Import");
}
void LCollection::Insert(ZPosition Pos, pvoid pItem, uint ItemSize) {
if (!ItemSize && pItem) {
XErrorSetLast(E_INVALIDARG, "Zero Item Size Specified for not-NULL Item");
XErrorSignal("LCollection::Insert");
return;
}
ZCollectionHeader newHdr;
m_cHdr.m_pItem = pItem;
m_cHdr.m_itemSize = ItemSize;
m_cHdr.Insert(Pos, &newHdr);
AfterInsert(m_cHdr.m_pItem, ItemSize);
m_cHdr.m_pItem = NULL;
m_count++;
}
bool LCollection::Remove(ZPosition Pos) { // false if list is empty
if (!m_count) {
return false;
}
else if (!--m_count) { // Remove the only item: the same as Remove all
RemoveAll();
return true;
}
pZCollectionHeader pHdr = (pZCollectionHeader)m_cHdr[Pos];
BeforeRemove(pHdr->pMem->Addr(), pHdr->itemSize);
m_cHdr.Remove(Pos);
return true;
}
void LCollection::RemoveAll() {
if (!m_count) return;
// Reset all the iterators
for (uint i = 0; i < m_iterCount; i++) {
m_pIter[i]->Reset();
}
// Remove all items
m_cHdr.RemoveAll();
// Set members clear
m_head = m_last = NULL;
m_count = 0;
}
void LCollection::SwapWith(ZPosition Pos, const VIterator& Iter) {
m_cHdr.SwapWith(Pos, Iter);
}
void LCollection::Swap(const VIterator& Iter1, const VIterator& Iter2) {
m_cHdr.Swap(Iter1, Iter2);
}
void LCollection::SortAsc(ZSortOrder Greater) {
uint cnt = Count();
if (cnt < 2) return;
LCollectionIterator i1(this);
VIterator &_i1 = NewIterator(NULL);
i1.SetTo(ZHead);
_i1.SetTo(ZHead);
if (cnt == 2) {
if (Greater(i1(), (*this)[ZTail])) SwapWith(ZTail, _i1);
return;
}
VIterator &_i2 = NewIterator(NULL);
for (uint j = 0; j < cnt - 1; j++) {
i1.SetToIndex(j);
_i1.SetToIndex(j);
for (uint k = j + 1; k < cnt; k++) {
SetToIndex(k);
_i2.SetToIndex(k);
if (Greater(i1(), (*this)())) Swap(_i1, _i2);
}
}
}
void LCollection::GetCurrent(pvoid *ppItem) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])();
*ppItem = pHdr ? pHdr->pMem->Addr() : NULL;
}
pvoid LCollection::operator ()() const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])();
return pHdr ? pHdr->pMem->Addr() : NULL;
}
void LCollection::Get(ZPosition Pos, pvoid *ppItem) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Pos];
*ppItem = pHdr ? pHdr->pMem->Addr() : NULL;
}
pvoid LCollection::operator [](ZPosition Pos) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Pos];
return pHdr ? pHdr->pMem->Addr() : NULL;
}
void LCollection::GetByIndex(int Index, pvoid *ppItem) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Index];
*ppItem = pHdr ? pHdr->pMem->Addr() : NULL;
}
pvoid LCollection::operator [](int Index) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Index];
return pHdr ? pHdr->pMem->Addr() : NULL;
}
uint LCollection::ItemSize() const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])();
return pHdr ? pHdr->itemSize : ZUintInvalid;
}
uint LCollection::Count() const {
return m_pIter[0]->Count();
}
uint LCollection::ItemSizeByIndex(int Index) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Index];
return pHdr ? pHdr->itemSize : ZUintInvalid;
}
uint LCollection::ItemSizeAt(ZPosition Pos) const {
pZCollectionHeader pHdr = (pZCollectionHeader)(*m_pIter[0])[Pos];
return pHdr ? pHdr->itemSize : ZUintInvalid;
}
void LCollection::SetItemSize(uint NewSize, const VIterator& Iter) {
pZCollectionHeader pHdr = (pZCollectionHeader)Iter();
if (!pHdr) {
XErrorSetLast(E_INVALIDARG, "Current Item Undefined");
XErrorSignal("LCollection::SetItemSize");
return;
}
pHdr->itemSize = NewSize;
if (pHdr->pMem) {
if (NewSize) {
pHdr->pMem->SetSize(NewSize);
}
else {
delete pHdr->pMem;
pHdr->pMem = NULL;
}
}
else {
if (NewSize) {
pHdr->pMem = new LMemory(NewSize);
}
}
return;
}
| [
"[email protected]"
] | [
[
[
1,
258
]
]
] |
0dbd5faaaccb01573c8d5ef6ade8499a5596aa9b | 9f6c9d3f35812aafdff2f0cb929f05f2413d5d4b | /lib/NewSoftSerial/NewSoftSerial.cpp | 463ab0178199f0021ae078e4244c85c81bc424b5 | [] | no_license | joewalnes/arduino-play | 5d070e00ed321ac2f6c75b1f27005cc0b2614c94 | c311cdc09dbc7a322facd37ac3fef925a2380524 | refs/heads/master | 2023-05-29T23:28:53.191233 | 2011-09-26T18:25:50 | 2011-09-26T18:25:50 | 1,747,809 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,284 | cpp | /*
NewSoftSerial.cpp - Multi-instance software serial library
Copyright (c) 2006 David A. Mellis. All rights reserved.
-- Interrupt-driven receive and other improvements by ladyada
-- Tuning, circular buffer, derivation from class Print,
multi-instance support, porting to 8MHz processors,
various optimizations, PROGMEM delay tables, inverse logic and
direct port writing by Mikal Hart
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
The latest version of this library can always be found at
http://arduiniana.org.
*/
// When set, _DEBUG co-opts pins 11 and 13 for debugging with an
// oscilloscope or logic analyzer. Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 11
#define _DEBUG_PIN2 13
//
// Includes
//
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "WConstants.h"
#include "pins_arduino.h"
#include "NewSoftSerial.h"
// Abstractions for maximum portability between processors
// These are macros to associate pins to pin change interrupts
#if !defined(digitalPinToPCICR) // Courtesy Paul Stoffregen
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
#define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)NULL))
#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
#define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)NULL))))
#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))
#else
#define digitalPinToPCICR(p) ((uint8_t *)NULL)
#define digitalPinToPCICRbit(p) 0
#define digitalPinToPCMSK(p) ((uint8_t *)NULL)
#define digitalPinToPCMSKbit(p) 0
#endif
#endif
//
// Lookup table
//
typedef struct _DELAY_TABLE
{
long baud;
unsigned short rx_delay_centering;
unsigned short rx_delay_intrabit;
unsigned short rx_delay_stopbit;
unsigned short tx_delay;
} DELAY_TABLE;
#if F_CPU == 16000000
static const DELAY_TABLE PROGMEM table[] =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 1, 17, 17, 12, },
{ 57600, 10, 37, 37, 33, },
{ 38400, 25, 57, 57, 54, },
{ 31250, 31, 70, 70, 68, },
{ 28800, 34, 77, 77, 74, },
{ 19200, 54, 117, 117, 114, },
{ 14400, 74, 156, 156, 153, },
{ 9600, 114, 236, 236, 233, },
{ 4800, 233, 474, 474, 471, },
{ 2400, 471, 950, 950, 947, },
{ 1200, 947, 1902, 1902, 1899, },
{ 300, 3804, 7617, 7617, 7614, },
};
const int XMIT_START_ADJUSTMENT = 5;
#elif F_CPU == 8000000
static const DELAY_TABLE table[] PROGMEM =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 1, 5, 5, 3, },
{ 57600, 1, 15, 15, 13, },
{ 38400, 2, 25, 26, 23, },
{ 31250, 7, 32, 33, 29, },
{ 28800, 11, 35, 35, 32, },
{ 19200, 20, 55, 55, 52, },
{ 14400, 30, 75, 75, 72, },
{ 9600, 50, 114, 114, 112, },
{ 4800, 110, 233, 233, 230, },
{ 2400, 229, 472, 472, 469, },
{ 1200, 467, 948, 948, 945, },
{ 300, 1895, 3805, 3805, 3802, },
};
const int XMIT_START_ADJUSTMENT = 4;
#elif F_CPU == 20000000
// 20MHz support courtesy of the good people at macegr.com.
// Thanks, Garrett!
static const DELAY_TABLE PROGMEM table[] =
{
// baud rxcenter rxintra rxstop tx
{ 115200, 3, 21, 21, 18, },
{ 57600, 20, 43, 43, 41, },
{ 38400, 37, 73, 73, 70, },
{ 31250, 45, 89, 89, 88, },
{ 28800, 46, 98, 98, 95, },
{ 19200, 71, 148, 148, 145, },
{ 14400, 96, 197, 197, 194, },
{ 9600, 146, 297, 297, 294, },
{ 4800, 296, 595, 595, 592, },
{ 2400, 592, 1189, 1189, 1186, },
{ 1200, 1187, 2379, 2379, 2376, },
{ 300, 4759, 9523, 9523, 9520, },
};
const int XMIT_START_ADJUSTMENT = 6;
#else
#error This version of NewSoftSerial supports only 20, 16 and 8MHz processors
#endif
//
// Statics
//
NewSoftSerial *NewSoftSerial::active_object = 0;
char NewSoftSerial::_receive_buffer[_NewSS_MAX_RX_BUFF];
volatile uint8_t NewSoftSerial::_receive_buffer_tail = 0;
volatile uint8_t NewSoftSerial::_receive_buffer_head = 0;
//
// Debugging
//
// This function generates a brief pulse
// for debugging or measuring on an oscilloscope.
inline void DebugPulse(uint8_t pin, uint8_t count)
{
#if _DEBUG
volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));
uint8_t val = *pport;
while (count--)
{
*pport = val | digitalPinToBitMask(pin);
*pport = val;
}
#endif
}
//
// Private methods
//
/* static */
inline void NewSoftSerial::tunedDelay(uint16_t delay) {
uint8_t tmp=0;
asm volatile("sbiw %0, 0x01 \n\t"
"ldi %1, 0xFF \n\t"
"cpi %A0, 0xFF \n\t"
"cpc %B0, %1 \n\t"
"brne .-10 \n\t"
: "+r" (delay), "+a" (tmp)
: "0" (delay)
);
}
// This function sets the current object as the "active"
// one and returns true if it replaces another
bool NewSoftSerial::activate(void)
{
if (active_object != this)
{
_buffer_overflow = false;
uint8_t oldSREG = SREG;
cli();
_receive_buffer_head = _receive_buffer_tail = 0;
active_object = this;
SREG = oldSREG;
return true;
}
return false;
}
//
// The receive routine called by the interrupt handler
//
void NewSoftSerial::recv()
{
#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
asm volatile(
"push r18 \n\t"
"push r19 \n\t"
"push r20 \n\t"
"push r21 \n\t"
"push r22 \n\t"
"push r23 \n\t"
"push r26 \n\t"
"push r27 \n\t"
::);
#endif
uint8_t d = 0;
// If RX line is high, then we don't see any start bit
// so interrupt is probably not for us
if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
{
// Wait approximately 1/2 of a bit width to "center" the sample
tunedDelay(_rx_delay_centering);
DebugPulse(_DEBUG_PIN2, 1);
// Read each of the 8 bits
for (uint8_t i=0x1; i; i <<= 1)
{
tunedDelay(_rx_delay_intrabit);
DebugPulse(_DEBUG_PIN2, 1);
uint8_t noti = ~i;
if (rx_pin_read())
d |= i;
else // else clause added to ensure function timing is ~balanced
d &= noti;
}
// skip the stop bit
tunedDelay(_rx_delay_stopbit);
DebugPulse(_DEBUG_PIN2, 1);
if (_inverse_logic)
d = ~d;
// if buffer full, set the overflow flag and return
if ((_receive_buffer_tail + 1) % _NewSS_MAX_RX_BUFF != _receive_buffer_head)
{
// save new data in buffer: tail points to where byte goes
_receive_buffer[_receive_buffer_tail] = d; // save new byte
_receive_buffer_tail = (_receive_buffer_tail + 1) % _NewSS_MAX_RX_BUFF;
}
else
{
#if _DEBUG // for scope: pulse pin as overflow indictator
DebugPulse(_DEBUG_PIN1, 1);
#endif
_buffer_overflow = true;
}
}
#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
asm volatile(
"pop r27 \n\t"
"pop r26 \n\t"
"pop r23 \n\t"
"pop r22 \n\t"
"pop r21 \n\t"
"pop r20 \n\t"
"pop r19 \n\t"
"pop r18 \n\t"
::);
#endif
}
void NewSoftSerial::tx_pin_write(uint8_t pin_state)
{
if (pin_state == LOW)
*_transmitPortRegister &= ~_transmitBitMask;
else
*_transmitPortRegister |= _transmitBitMask;
}
uint8_t NewSoftSerial::rx_pin_read()
{
return *_receivePortRegister & _receiveBitMask;
}
//
// Interrupt handling
//
/* static */
inline void NewSoftSerial::handle_interrupt()
{
if (active_object)
{
active_object->recv();
}
}
#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
NewSoftSerial::handle_interrupt();
}
#endif
#if defined(PCINT1_vect)
ISR(PCINT1_vect)
{
NewSoftSerial::handle_interrupt();
}
#endif
#if defined(PCINT2_vect)
ISR(PCINT2_vect)
{
NewSoftSerial::handle_interrupt();
}
#endif
#if defined(PCINT3_vect)
ISR(PCINT3_vect)
{
NewSoftSerial::handle_interrupt();
}
#endif
//
// Constructor
//
NewSoftSerial::NewSoftSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
_rx_delay_centering(0),
_rx_delay_intrabit(0),
_rx_delay_stopbit(0),
_tx_delay(0),
_buffer_overflow(false),
_inverse_logic(inverse_logic)
{
setTX(transmitPin);
setRX(receivePin);
}
//
// Destructor
//
NewSoftSerial::~NewSoftSerial()
{
end();
}
void NewSoftSerial::setTX(uint8_t tx)
{
pinMode(tx, OUTPUT);
digitalWrite(tx, HIGH);
_transmitBitMask = digitalPinToBitMask(tx);
uint8_t port = digitalPinToPort(tx);
_transmitPortRegister = portOutputRegister(port);
}
void NewSoftSerial::setRX(uint8_t rx)
{
pinMode(rx, INPUT);
if (!_inverse_logic)
digitalWrite(rx, HIGH); // pullup for normal logic!
_receivePin = rx;
_receiveBitMask = digitalPinToBitMask(rx);
uint8_t port = digitalPinToPort(rx);
_receivePortRegister = portInputRegister(port);
}
//
// Public methods
//
void NewSoftSerial::begin(long speed)
{
_rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;
for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)
{
long baud = pgm_read_dword(&table[i].baud);
if (baud == speed)
{
_rx_delay_centering = pgm_read_word(&table[i].rx_delay_centering);
_rx_delay_intrabit = pgm_read_word(&table[i].rx_delay_intrabit);
_rx_delay_stopbit = pgm_read_word(&table[i].rx_delay_stopbit);
_tx_delay = pgm_read_word(&table[i].tx_delay);
break;
}
}
// Set up RX interrupts, but only if we have a valid RX baud rate
if (_rx_delay_stopbit)
{
if (digitalPinToPCICR(_receivePin))
{
*digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
*digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));
}
tunedDelay(_tx_delay); // if we were low this establishes the end
}
#if _DEBUG
pinMode(_DEBUG_PIN1, OUTPUT);
pinMode(_DEBUG_PIN2, OUTPUT);
#endif
activate();
}
void NewSoftSerial::end()
{
if (digitalPinToPCMSK(_receivePin))
*digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));
}
// Read data from buffer
int NewSoftSerial::read(void)
{
uint8_t d;
// A newly activated object never has any rx data
if (activate())
return -1;
// Empty buffer?
if (_receive_buffer_head == _receive_buffer_tail)
return -1;
// Read from "head"
d = _receive_buffer[_receive_buffer_head]; // grab next byte
_receive_buffer_head = (_receive_buffer_head + 1) % _NewSS_MAX_RX_BUFF;
return d;
}
uint8_t NewSoftSerial::available(void)
{
// A newly activated object never has any rx data
if (activate())
return 0;
return (_receive_buffer_tail + _NewSS_MAX_RX_BUFF - _receive_buffer_head) % _NewSS_MAX_RX_BUFF;
}
void NewSoftSerial::write(uint8_t b)
{
if (_tx_delay == 0)
return;
activate();
uint8_t oldSREG = SREG;
cli(); // turn off interrupts for a clean txmit
// Write the start bit
tx_pin_write(_inverse_logic ? HIGH : LOW);
tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);
// Write each of the 8 bits
if (_inverse_logic)
{
for (byte mask = 0x01; mask; mask <<= 1)
{
if (b & mask) // choose bit
tx_pin_write(LOW); // send 1
else
tx_pin_write(HIGH); // send 0
tunedDelay(_tx_delay);
}
tx_pin_write(LOW); // restore pin to natural state
}
else
{
for (byte mask = 0x01; mask; mask <<= 1)
{
if (b & mask) // choose bit
tx_pin_write(HIGH); // send 1
else
tx_pin_write(LOW); // send 0
tunedDelay(_tx_delay);
}
tx_pin_write(HIGH); // restore pin to natural state
}
SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);
}
#if !defined(cbi)
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
void NewSoftSerial::enable_timer0(bool enable)
{
if (enable)
#if defined(__AVR_ATmega8__)
sbi(TIMSK, TOIE0);
#else
sbi(TIMSK0, TOIE0);
#endif
else
#if defined(__AVR_ATmega8__)
cbi(TIMSK, TOIE0);
#else
cbi(TIMSK0, TOIE0);
#endif
}
void NewSoftSerial::flush()
{
if (active_object == this)
{
uint8_t oldSREG = SREG;
cli();
_receive_buffer_head = _receive_buffer_tail = 0;
SREG = oldSREG;
}
}
| [
"[email protected]"
] | [
[
[
1,
539
]
]
] |
5ec0be2b1bf91131dc6bd01b5618447894e9bb7a | 66a43ba27a2000db108ffc1fa4f8dfd057c940ae | /slang/slang.cpp | 04e6ff60c7fdb97a3357c3206215cceab9234dc5 | [] | no_license | karanjude/slang | 5531b457c88fd421f9038379b57a84441a09416b | 32cb0279bf55c0cc375d559d5eca2a0f1ab5fc9f | refs/heads/master | 2020-05-20T15:57:25.706392 | 2007-04-22T20:28:23 | 2007-04-22T20:28:23 | 2,740,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,502 | cpp | #include <conio.h>
#include <stdio.h>
#include <string.h>
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
//typedef int bool;
#define TAB '\t'
// enable the 2 flags for turbo c++
//#define true (1)
//#define false (0)
#define KEYWORDS (17)
#define MAX_STACK_SIZE (100)
#define MAX_SEGMENT_SIZE (500)
typedef char _symbol[32];
typedef _symbol symbol;
// used to count the number of lines
int _lineCounter;
// used to keep a track of labels
int _lineCount;
bool _true;
const MAX = 100;
// each item in the information segemnt is like given below
// either a
// function pointer
// a value for a variable
// or an index in the symbol table
union Code
{
void (*op)(void);
int value;
int index;
};
// out temporary data stack for our execution engine
int _stack[MAX_STACK_SIZE];
// stack pointer
int _stackp;
// program counter for our information segment
int _pc;
// used to index the names in symbol table
int _index;
// numeric value of variable
int _num;
// information segment
Code _segment[MAX_SEGMENT_SIZE];
// label pool
int _L[MAX];
// string pool : keep track of all the strings used in program
char * _strings[MAX];
// counter for messages esp used in write
int _msgCount;
// our symbol table
//symbol _symTab[1000];
symbol * _tablePtr;
/* look ahead global variable
: used to store the next token in token stream */
char _lookAhead;
// count the number of levels of identation
int _levels;
// count the number of line levels
int _lineLevel;
// used to store the current token
char _token;
// the value associated with a token
char _value[16];
// number of entries in the symbol table
int _numEntry;
// our true symbol table
_symbol _st[MAX];
// used to store the type of each qty in symbol table
char _stype[MAX];
// used to store the value of each qty in symbol table
int _svalue[MAX];
// count the number of keywords
const int NUMKEYWORDS=23;
// our keyword table
symbol _keywordList[NUMKEYWORDS] = {"","BREAK","IF","ELSE","ENDIF","WHILE","ENDWHILE",
"LOOP","ENDLOOP","REPEAT","UNTIL","FOR","DO",
"ENDFOR","TO","ENDDO","END","READ","WRITE","VAR","BEGIN","END","PROGRAM"
};
// our code for each keyword
char _keywordCode[NUMKEYWORDS+1] = "xbileweperufdeteeRWvbep";
// global file pointer
FILE * _file;
// the info showed during startup
char _info[] = "\n\n\tSLANG : Simple Language Interpreter "
"\n\tA pilot test project "
"\n\n\tTo operate in interactive mode type :"
"\n\n\t\tslang run "
"\n\n\t OR \n"
"\n\tTo operate in file mode type :"
"\n\n\t\tslang filename"
"\n\n Credits : "
"\n\t Abhishek Swami 1CR01CS003"
"\n\t Danish Sualeh 1CR01CS016"
"\n\t Dhawal 1CR01CS025"
"\n\t Karan Singh 1CR01CS035";
// list of error codes
enum {
FILE_DOES_NOT_EXIST ,
UNKNOWN_FILE_TYPE,
UNKNOWN_OPTION
};
// error strings for corresponding error codes
char * _errors[] = {
"The File Does not Exist ",
"The File type cannot be understood ",
"The option specified is not supported "
};
// function prototypes
// global driver routines which call other routines
void Initialize(void);
void Start(void);
void Execute(void);
void Process(void);
void ShowInfo(void);
void ShowError(int);
void Init();
void MainProg();
void Prog();
/* codegen*/
void SetLess (void);
void SetGreater (void);
void SetLessOrEqual(void);
void SetGreaterOrEqual(void);
void Branch(void);
void BranchFalse(void);
void BranchTrue(void);
void WriteVar(void);
void ReadVar(void);
void Store(char * name);
void Store(void);
void Ident(int);
void Clear();
void Negate();
void NotIt();
void LoadConstant(int n);
void LoadVariable(char * name);
void Push();
void PopAdd();
void PopSub();
void PopMul();
void PopDiv();
void PopModulus();
void PopAnd();
void PopOr();
void PopXor();
void SetEqual();
void SetNotEqual();
void Load(void);
void Inc(void);
// implicit executuion engine
void Eval(int);
/*output*/
void Emit (char * s);
void EmitLine(char * s);
char * NewLabel(void);
void PostLabel (char * L);
void Header();
/*parser*/
void Expression(void);
void Equal(void);
void LessOrEqual();
void NotEquals(void);
void Less(void);
void Greater(void);
void Relation(void);
void NotFactor(void);
void BoolTerm(void);
void BoolOr(void) ;
void BoolXor(void) ;
void BoolExpression(int );
void Assignment(int);
void DoIf(int,int);
void DoWhile(int,int);
void DoLoop(int,int);
void DoRepeat(int,int);
void DoFor(void);
void DoBreak(char * L,int);
void DoRead(void);
void DoWrite(int);
void Block(char * ,int,int );
void NegativeFactor(void);
void Factor(void);
void FirstFactor(void);
void Multiply(void);
void Divide(void);
void Modulus(void);
void Term1(void);
void Term(void);
void FirstTerm(void);
void Add(void);
void Substract(void);
/* scanner1.cpp*/
int LookUp(symbol * _tablePtr,char* str,int n);
void Scan (void);
void MatchString(char* str);
bool IsMulOp(char c);
bool IsOrOp (char c);
bool IsRelOp(char c);
bool IsWhite(char c);
void Match(char x);
int Locate(_symbol n);
bool InTable(_symbol n);
void AddEntry(_symbol n, char t);
void GetName(void);
void GetNum(void);
void NewLine(void);
void Decl(void);
void TopDecls(void);
void GetChar(void);
bool IsAlpha(int Char);
bool IsDigit(int Char);
bool IsAddOp(char c);
bool IsAlNum(char c);
void SkipWhite(void);
void SkipComment(void);
void ShowMessage(void);
void SkipMessage(void);
void Alloc(_symbol N);
/*error.cpp*/
void Error(char * Str);
void Abort(char * Str);
void Expected(char * Str);
void Undefined(char * str);
/*
Function Name: SetLess
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and set D0 if compare was >
*/
void SetLess (void)
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left < right;
}
/*
Function Name: SetGreater
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and set D0 if compare was <
*/
void SetGreater (void)
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left > right;
}
/*
Function Name: SetLessOrEqual
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and set D0 if compare was <=
*/
void SetLessOrEqual(void)
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left <= right;
}
/*
Function Name: SetGreaterOrEqual
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and set D0 if compare was >=
*/
void SetGreaterOrEqual(void)
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left >= right;
}
/*
Function Name: Branch
Return Type: void
Purpose: Does not return a value
Input Parameter: char *, integer
Purpose:
Function Purpose: Branch unconditional
*/
void Branch(char * L,int l = 0)
{
_pc = _L[l];
}
/*
Function Name: Branch
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Branch unconditional
*/
void Branch(void)
{
_pc = _L[_segment[_pc].value];
}
/*
Function Name: BranchFalse
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Branch false code generation
*/
void BranchFalse(void)
{
if(_stack[--_stackp] == 0)
{
_pc = _L[_segment[_pc].value];
_true=false;
}
else
{
_pc++;
_true=true;
}
}
/*
Function Name: BranchTrue
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Branch true code generation
*/
void BranchTrue(void)
{
if(_stack[--_stackp] == 1)
{
_pc = _L[_segment[_pc].value];
}
else
{
_pc= _L[_segment[_pc+1].value];
}
}
/*
Function Name: Store
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Storing of variables
*/
void Store(void)
{
_index = _segment[_pc++].index;
_svalue[_index] = _stack[--_stackp];
}
/*
Function Name: Store
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose:
Function Purpose: storing of variables
*/
void Store(char * name)
{
_index = LookUp(_st,name,_numEntry);
_svalue[_index] = _stack[--_stackp];
}
/*
Function Name: Eval
Return Type: Void
Purpose: Does not return a value
Input Parameter: integer
Purpose: Token to evaluate
Function Purpose: evalute and execute the code
*/
void Eval(int pc)
{
_pc = pc;
while(_segment[_pc].op != NULL)
{
(*_segment[_pc++].op)();
}
}
/*
Function Name: ReadVar
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Reading variable to primary register
*/
void ReadVar(void)
{
cin >> _num;
_stack[_stackp++] = _num;
_svalue[_segment[_pc++].index] = _num;
}
/*
Function Name: WriteVar
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Write variable from primary register
*/
void WriteVar(void)
{
printf("%d",_stack[--_stackp]);
}
/*
Function Name: Ident
Return Type: void
Purpose: Does not return a value
Input Parameter: integer
Purpose:
Function Purpose: To control the identation after the control statements
*/
void Ident(int line)
{
static int old_line = 1;
if(old_line != line)
{
old_line = line;
for(int i = 1;i <= _levels && !_file;i++)
printf("\t");
}
}
/*
Function Name: Clear
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Clear the Primary Register
*/
void Clear()
{
_stackp++;
}
/*
Function Name: Negate
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Negate the primary register
*/
void Negate()
{
_stack[_stackp -1 ] = - (_stack[_stackp - 1]);
}
/*
Function Name: NotIt
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Complement the primary register
*/
void NotIt()
{
_stack[_stackp -1 ] = !(_stack[_stackp - 1]);
}
/*
Function Name: LoadConstant
Return Type: void
Purpose: Does not return value
Input Parameter: integer
Purpose: used to load the token
Function Purpose: Load a Constant Value to Primary Register
*/
void LoadConstant(int n)
{
_segment[_pc++].op = Push;
_segment[_pc++].value = n;
}
/*
Function Name: LoadVariable
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose: Used to load a string
Function Purpose: Load a Variable to Primary Register
*/
void LoadVariable(char * Name)
{
if(!(InTable(Name)))
{
Undefined(Name);
}
_segment[_pc++].op = Load;
_segment[_pc++].index = _index;
}
/*
Function Name: Load
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose:
*/
void Load(void)
{
_stack[_stackp++] = _svalue[_segment[_pc++].index];
}
/*
Function Name: Inc
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose:
*/
void Inc(void)
{
_stack[_stackp] = _svalue[_segment[_pc++].index];
_stack[_stackp++]++;
}
/*
Function Name: Push
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Push Primary onto Stack
*/
void Push(void)
{
_stack[_stackp++] = _segment[_pc++].value;
}
/*
Function Name: PopAdd
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Add Top of Stack to Primary
*/
void PopAdd()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left + right;
}
/*
Function Name: PopSub
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Subtract Primary from Top of Stack
*/
void PopSub()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left - right;
}
/*
Function Name: PopMul
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Multiply Top of Stack by Primary
*/
void PopMul()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left * right;
}
/*
Function Name: PopDiv
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Divide Top of Stack by Primary
*/
void PopDiv()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
if(right == 0)
Abort("Divide by 0 error => the right term is 0");
_stack[_stackp++] = left / right;
}
/*
Function Name: PopModulus
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Modulus Top of Stack with primary
*/
void PopModulus()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
if(right == 0)
Abort("Divide by 0 error => the right term is 0");
_stack[_stackp++] = left % right;
}
/*
Function Name: PopAnd
Return Type:
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: AND Top of Stack with Primary
*/
void PopAnd()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left & right;
}
/*
Function Name: PopOr
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
function Purpose: OR Top of Stack with Primary
*/
void PopOr()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left | right;
}
/*
Function Name: PopXor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: XOR Top of Stack with Primary
*/
void PopXor()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left ^ right;
}
/*
Function Name: SetEqual
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Set D0 If Compare was =
*/
void SetEqual()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left == right;
}
/*
Function Name: SetNotEqual
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Set D0 If Compare was !=
*/
void SetNotEqual()
{
int left,right;
right = _stack[--_stackp];
left = _stack[--_stackp];
_stack[_stackp++] = left != right;
}
/*
Function Name : Error
Return Type : void
Purpose : Does not return a value
Input Parameter : char *
Purpose : String to be printed
Function Purpose : Error reporting function
*/
void Error(char * Str)
{
printf("\t Line : %d Error : %s !\n",_lineCounter,Str);
}
/*
Function Name : Abort
Return Type : void
Purpose : Does not return a value
Input Paramater : char *
Purpose : string to be printed
Function Purpose : Function to report error and exit
*/
void Abort(char * Str)
{
Error(Str);
if(_file)
fclose(_file);
exit(0);
}
/*
Function Name : Expected
Return Type : Void
Purpose : does not return a value
Input Paramater : char *
Purpose : string to be printed
Function Purpose : Used to print message in error generation
*/
void Expected(char * Str)
{
printf("\t Line : %d Error : %s ! \" Expected \" \n",_lineCounter,Str);
if(_file)
fclose(_file);
exit(0);
}
/*
Function Name: Undefined
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose: String to be printed
Function Purpose: Used to print message for undefined identifier
*/
void Undefined(char * Str)
{
printf("\n\t Line : %d Error : %s ! \" Undefined \" \n",_lineCounter,Str);
if(_file)
fclose(_file);
exit(0);
}
/*
Function Name: Header
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: For writing header info
*/
void Header()
{
_pc = 0;
_stackp = 0;
}
/*
Function Name: Emit
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose:
Function Purpose: Output a string with tab
*/
void Emit (char * s)
{
printf("\t %s\n",s);
}
/*
Function Name: EmitLine
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose:
Function Purpose: Output a string with Tab and CRLF
*/
void EmitLine(char * s)
{
Emit(s);
printf("\n");
}
/*
Function Name: NewLabel
Return Type: char *
Purpose: Return the label
Input Parameter: void
Purpose:
Function Purpose: Generate a unique label
*/
char * NewLabel(void)
{
_lineCount++;
return(NULL);
}
/*
Function Name: PostLabel
Return Type: void
Purpose: Does not return a value
Input Parameter: char *
Purpose: String to be printed
Function Purpose: Post a label to output
*/
void PostLabel (char * L)
{
printf ("\n %s :",L);
}
/*
Function Name: NegativeFactor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose:
*/
void NegativeFactor(void)
{
Match('-');
if( IsDigit(_lookAhead) )
{
GetNum();LoadConstant(atoi(_value));
}
else
{
Factor();
Negate();
}
}
/*
Function Name : Expression
Return Type : void
Purpose : Does not return a value
Input Parameter : void
Purpose : Parse and translate a mathematical expression
*/
void Expression(void)
{
FirstTerm();
while(IsAddOp(_lookAhead))
{
switch(_lookAhead)
{
case '+': Add();
break;
case '-': Substract();
break;
default: Expected("Addop");
}
}
}
/*
Function Name: Equal
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a relation equals
*/
void Equal(void)
{
Match('=');
Expression();
_segment[_pc++].op = SetEqual;
}
/*
Function Name: LessOrEqual
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a relation less than or equals
*/
void LessOrEqual(void)
{
Match('=');
Expression();
_segment[_pc++].op = SetLessOrEqual;
}
/*
Function Name: NotEquals
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a Relation "Not Equals"
*/
void NotEquals(void)
{
Match('#');
Expression();
_segment[_pc++].op = SetNotEqual;
}
/*
Function Name: Less
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a relation less than
*/
void Less(void)
{
Match('<');
switch(_lookAhead)
{
case '=': LessOrEqual();
break;
default : Expression();
_segment[_pc++].op = SetLess;
break;
}
}
/*
Function Name: Greater
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a relation greater than
*/
void Greater(void)
{
Match('>');
if (_lookAhead=='=')
{
Match('=');
Expression();
_segment[_pc++].op = SetGreaterOrEqual;
}
else
{
Expression();
_segment[_pc++].op = SetGreater;
}
}
/*
Function Name: Relation
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and translate a Relation
*/
void Relation(void)
{
Expression();
if (IsRelOp(_lookAhead))
{
switch(_lookAhead)
{
case '=' : Equal();
break;
case '#' : NotEquals();
break;
case '<' : Less();
break;
case '>' : Greater();
break;
}
}
}
/*
Function Name: NotFactor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and Translate a Boolean Factor with Leading NOT
*/
void NotFactor(void)
{
if (_lookAhead=='!')
{
Match('!');
Relation();
_segment[_pc++].op = NotIt;
}
else
Relation();
}
/*
Function Name: BoolTerm
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and Translate a Boolean Term
*/
void BoolTerm(void)
{
NotFactor();
while (_lookAhead=='&')
{
Match('&');
NotFactor();
_segment[_pc++].op = PopAnd;
}
}
/*
Function Name: BoolOr
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and Translate a Boolean OR
*/
void BoolOr(void)
{
Match('|');
BoolTerm();
_segment[_pc++].op = PopOr;
}
/*
Function Name: BoolXor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and Translate an Exclusive Or
*/
void BoolXor(void)
{
Match('^');
BoolTerm();
_segment[_pc++].op = PopXor;
}
/*
Function Name: BoolExpression
Return Type: void
Purpose: Does not return a value
Input Parameter: integer
Purpose:
Function Purpose: Parse and Translate a Boolean Expression
*/
void BoolExpression(int eval = 0)
{
int old_pc = _pc;
BoolTerm();
while (IsOrOp(_lookAhead))
{
switch(_lookAhead)
{
case '|': BoolOr();
break;
case '^': BoolXor();
break;
}
}
if(eval)
Eval(old_pc);
}
/*
Function Name : Assignment
Return Type : void
Purposee : does not return a value
Input Parameter : integer
Purpose :
Function Purpose: Parse and Translate an Assignment Statement
*/
void Assignment(int eval = 0)
{
char Name[30];
strcpy(Name,_value);
SkipWhite();
Match('=');
BoolExpression(eval);
int old_pc = _pc;
_index = LookUp(_st,Name,_numEntry);
_segment[_pc++].op = Store;
_segment[_pc++].index = _index;
if(eval)
Eval(old_pc);
}
/*
Function Name: DoIf
Return Type: void
Purpose: Does not return a value
Input Parameter: integer , integer
Purpose:
Function Purpose: Recognize and translate an IF construct
*/
void DoIf(int eval = 0,int l = 0)
{
_true = false;
_lineLevel = 1;
BoolExpression(eval);
NewLabel();
int old_pc = _pc;
int l1,l2;
l1 = _lineCount - 1;
l2 = l1;
//False code;
_segment[_pc++].op = BranchFalse;
_segment[_pc++].value = l1;
Block("",0,l);
if (_token=='l')
{
NewLabel();
l2 = _lineCount - 1;
// true code
_segment[_pc++].op = Branch;
_segment[_pc++].value = l2;
_L[l1] = _pc;
Block("",0,l);
}
_L[l2] = _pc;
MatchString("ENDIF");
_levels--;_lineLevel = 0;
if(eval)
Eval(old_pc);
}
/*
Function Name: DoWhile
Return Type: void
Purpose: Does not return a value
Input Parameter: integer , integer
Purpose:
Function Purpose: Parse and Translate a WHILE Statement
*/
void DoWhile(int eval = 0,int l = 0)
{
int l1,l2;
NewLabel();
l1 = _lineCount - 1;
NewLabel();
l2 = _lineCount - 1;
int old_pc = _pc;
_L[l1] = _pc;
BoolExpression(eval);
_segment[_pc++].op = BranchFalse;
_segment[_pc++].value = l2;
//False;
Block("",0,l2);
MatchString("ENDWHILE");
_segment[_pc++].op = Branch;
_segment[_pc++].value = l1;
//Branch(L1);
//PostLabel(L2);
_L[l2] = _pc;
_levels--;
if(eval)
Eval(old_pc);
}
/*
Function Name: DoLoop
Return Type: void
Purpose: Does not return a value
Input Parameter: integer , integer
Purpose:
Function Purpose: DoLoop is an infinite loop , normally from which a
only a break statement can cause an exit
*/
void DoLoop(int eval = 0,int l = 0)
{
int l1,l2;
// generate dynamic addresses
NewLabel();
l1 = _lineCount - 1;
NewLabel();
l2 = _lineCount - 1;
// print the start of loop block label
int old_pc = _pc;
_L[l1] = _pc;
Block("",0,l2);
// try to find the end of block
MatchString("ENDLOOP");
_segment[_pc++].op = Branch;
_segment[_pc++].value = l1;
_L[l2] = _pc;
_levels--;
if(eval)
Eval(old_pc);
}
/*
Function Name: DoRepeat
Return Type: void
Purpose: Does not return a value
Input Parameter: integer , integer
Purpose:
Function Purpose: The DoRepeat function is similar in nature to the do while
loop found in the 'c' programming language
*/
void DoRepeat(int eval = 0,int l = 0)
{
// generate dynamic addresses
int l1,l2;
NewLabel();
l1 = _lineCount - 1;
NewLabel();
l2 = _lineCount - 1;
int old_pc = _pc;
_L[l1] = _pc;
Block("",0,l2);
MatchString("UNTIL");_levels--;
BoolExpression(eval);
_segment[_pc++].op = BranchTrue;
_segment[_pc++].value = l2;
_segment[_pc++].value = l1;
_L[l2] = _pc;
if(eval)
Eval(old_pc);
}
/*
Function Name: DoFor
Return Type: void
Purpose: Does not return a value
Input Parameter: integer , integer
Purpose:
Function Purpose: The for loop construct is handled by this function it parses
for loop structure of the form
for name = expression1 expression2
where name is the variable which holds the value
of expression1 initially and then as the loop iterates till
the value of expression2
*/
void DoFor(int eval = 0,int l = 0)
{
char Name[20];
// generate dynamic addresses
int l1,l2;
NewLabel();
l1 = _lineCount - 1;
NewLabel();
l2 = _lineCount - 1;
GetName();
strcpy(Name,_value);
// for name =
Match('=');
// for name = expression1
BoolExpression(eval);
// an entry into the loop
int index;
if(!(InTable(Name)))
{
Undefined(Name);
}
index = _index;
_segment[_pc++].op = Store;
_segment[_pc++].index = index;
int old_pc;
_L[l1] = _pc;
_segment[_pc++].op = Load;
_segment[_pc++].index = index;
// for name = expression1 expression2
Scan();
MatchString("TO");
BoolExpression(eval);
// store the loop terminating expression on the stack
_segment[_pc++].op = SetLessOrEqual;
_segment[_pc++].op = BranchFalse;
_segment[_pc++].value = l2;
Block("",0,l2);
_segment[_pc++].op = Inc;
_segment[_pc++].index = index;
_segment[_pc++].op = Store;
_segment[_pc++].index = index;
MatchString("ENDFOR");
_segment[_pc++].op = Branch;
_segment[_pc++].value = l1;
_L[l2] = _pc;
_levels--;
// pop the expression2 value stored in stack
if(eval)
Eval(old_pc);
}
/*
Function Name: DoBreak
Return Type: void
Purpose: Does not return a value
Input Parameter: char * . integer
Purpose:
Function Purpose: Similar to the break statement in C
it jumps to the label L passed to it .
*/
void DoBreak(char * L,int l = 0)
{
_segment[_pc++].op = Branch;
_segment[_pc++].value = l;
}
/*
Function Name: DoRead
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Process a Read Statement
*/
void DoRead(void)
{
SkipWhite();
Match('(');
GetName();SkipWhite();
if(( _index = LookUp(_st,_value,_numEntry)) != 0)
{
_segment[_pc++].op = ReadVar;
_segment[_pc++].index = _index;
}
else Abort("Not a Valid variable !");
while (_lookAhead==',')
{
Match(',');
GetName();SkipWhite();
if(( _index = LookUp(_st,_value,_numEntry)) != 0)
{
_segment[_pc++].op = ReadVar;
_segment[_pc++].index = _index;
}
else Abort("Not a Valid variable !");
}
Match(')');
}
/*
Function Name: DoWrite
Return Type: void
Purpose: Does not return a value
Input Parameter: integer
Purpose: when eval =1 the excecution takes place
Function Purpose: Process a Write Statement
*/
void DoWrite(int eval = 0)
{
int old_pc;
SkipWhite();
Match('(');
if(_lookAhead == '"')
{
SkipMessage();
}
else
{
BoolExpression(1);SkipWhite();
old_pc = _pc;
_segment[_pc++].op = WriteVar;
//Eval(old_pc);
while (_lookAhead==',')
{
Match(',');
BoolExpression(eval);SkipWhite();
//old_pc = _pc;
_segment[_pc++].op = WriteVar;
//Eval(old_pc);
}
}
Match(')');
if(eval)
Eval(old_pc);
}
/*
Function Name: Block
Return Type: void
Purpose: Does not return a value
Input Parameter: char * , integer , integer
Purpose:
Function Purpose: Depending upon the look ahead variable the construct to be
chosen is decided and the corresponding loop is executed
*/
void Block(char * L,int eval = 0,int l = 0)
{
Scan();
while(!(_token == 'e' || _token == 'l' || _token == 'u'))
{
switch(_token)
{
case 'i': _levels++;DoIf(eval,l);
break;
case 'R': DoRead();
break;
case 'W': DoWrite(eval);
break;
case 'v': Decl();
break;
case 'w': _levels++;DoWhile(eval,l);
break;
case 'p': _levels++;DoLoop(eval,l);
break;
case 'r': _levels++;DoRepeat(eval,l);
break;
case 'f': _levels++;DoFor(eval);
break;
case 'b': DoBreak(L,l);
break;
default : Assignment(eval);
}
Scan();//Fin();
}
}
/*
Function Name: Factor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and translate a math factor
*/
void Factor(void)
{
SkipWhite();
if (_lookAhead=='(')
{
Match('(');
BoolExpression();
Match(')');
}
else if (IsAlpha(_lookAhead))
{
GetName();
LoadVariable(_value);
}
else
{
GetNum();
LoadConstant(_num);
}
SkipWhite();
}
/*
Function Name: FirstFactor
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and translate a leading factor
*/
void FirstFactor(void)
{
switch(_lookAhead)
{
case'+': Match('+');
Factor();
break;
case'-': NegativeFactor();
break;
default : Factor();
}
}
/*
Function Name: Multiply
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate multiply
*/
void Multiply(void)
{
Match('*');
Factor();
_segment[_pc++].op = PopMul;
}
/*
Function Name: Divide
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a divide
*/
void Divide(void)
{
Match('/');
Factor();
_segment[_pc++].op = PopDiv;
}
/*
Function Name: Modulus
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate modulus of a number
*/
void Modulus(void)
{
Match('%');
Factor();
_segment[_pc++].op = PopModulus;
}
/*
Function Name: Subtract
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a subtract
*/
void Substract(void)
{
Match('-');
Term();
_segment[_pc++].op = PopSub;
}
/*
Function Name: Term1
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Common code used by term and first term
*/
void Term1(void)
{
while (IsMulOp(_lookAhead))
{
switch(_lookAhead)
{
case '*': Multiply();
break;
case '%': Modulus();
break;
case '/': Divide();
break;
}
}
}
/*
Function Name: Term
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and translate a math term
*/
void Term(void)
{
Factor();
Term1();
}
/*
Function Name: FirsrTerm
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and translate a leading factor
*/
void FirstTerm(void)
{
FirstFactor();
Term1();
}
/*
Function Name: Add
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate an add
*/
void Add(void)
{
Match('+');
Term();
_segment[_pc++].op = PopAdd;
}
/*
Function Name: Subtract
Return Type: void
Purpose: Does not return a value
Input Parameter: void
Purpose:
Function Purpose: Recognize and translate a substract
*/
void Subtract(void)
{
Match('-');
Term();
PopSub();
}
/*
Function Name : SkipWhite
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Function to skip the whitespaces
*/
void SkipWhite(void)
{
while(IsWhite(_lookAhead) )
GetChar();
}
/*
Function Name : SkipComment
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Function to skip the comments
*/
void SkipComment(void)
{
_lookAhead = (_file) ? fgetc(_file) : getchar();
int oldLookAhead;
if(_lookAhead == '*')
{
oldLookAhead = _lookAhead;
_lookAhead = (_file) ? fgetc(_file) : getchar();
if(_lookAhead != '/')
{
_lookAhead = oldLookAhead;
SkipComment();
}
}
else
SkipComment();
SkipWhite();
}
/*
Function Name : ShowMessage
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Function to show message
*/
void ShowMessage(void)
{
int index = _segment[_pc++].index;
for(int i = 0;_strings[index][i] != NULL;i++)
{
if(_strings[index][i] == '\\')
{
if(_strings[index][i+1] == 't')
{
printf("\t");
i++;
}
if(_strings[index][i+1] == 'n')
{
printf("\n");
i++;
}
}
else
printf("%c",_strings[index][i]);
}
}
/*
Function Name : SkipMessage
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Function to skip Message
*/
void SkipMessage(void)
{
char string[100];
int ctr = 0;
Match('"');
while(_lookAhead != '"')
{
string[ctr++] = _lookAhead;
GetChar();
}
string[ctr] = '\0';Match('"');
if((_strings[_msgCount] = new char[ctr+1]) != NULL)
strcpy(_strings[_msgCount],string);
_segment[_pc++].op = ShowMessage;
_segment[_pc++].index = _msgCount++;
}
/*
Function Name: LookUp
Return Type: integer
Purpose: returns the table index number
Input Parameter: char , integer
Purpose: Serves as an index to the key table
Function Purpose: this function returns the index of the keyword found in the
key table , normally it starts from the bottom and goes to the
top and tries to find the index
*/
int LookUp(symbol * _tablePtr,char* str,int n)
{
int i;
bool found;
found = false;
i = n;
while (i > 0 && found == false)
{
if(strcmp(str,_tablePtr[i]) == 0)
found = true;
else
i--;
}
return i;
}
/*
Function Name: Scan
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: Get an identifier and scan it for keywords
*/
void Scan (void)
{
//if (_token=='x')
GetName();
_token = _keywordCode[LookUp(_keywordList,_value,NUMKEYWORDS - 1)]; //check
}
/*
Function Name: MatchString
Return Type: void
Purpose: does not return a value
Input Parameter: char
Purpose: matches the character
Function Purpose: Match a specific Input String
*/
void MatchString(char* str)
{
if (strcmp(_value,str) != 0)
Expected(str);
}
/*
Function Name: IsMulOp
Return Type: bool
Purpose: returns a true or false
Input Parameter: char
Purpose: matches the character
Function Purpose: check if the char is a * or a /
*/
bool IsMulOp(char c)
{
if(c == '*' || c == '/' || c == '%')
return true;
return false;
}
/*
Function Name: IsOrOp
Return Type: bool
Purpose: returns a true or false
Input Parameter: char
Purpose: matches the character
Function Purpose: Recognize a Boolean Orop
*/
bool IsOrOp (char c)
{
if (c=='|' || c=='^')
return 1;
else return 0;
}
/*
Function Name: IsRelOp
Return Type: bool
Purpose: returns a true or false
Input Parameter: char
Purpose: matches the character
Function Purpose: Recognize a Relop */
bool IsRelOp(char c)
{
switch(c)
{
case '=' :
case '#' :
case '<' :
case '>' : return 1;
}
return 0;
}
/*
Function Name: IsWhite
Return Type: bool
Purpose: returns a true or false
Input Parameter: char
Purpose: matches the character
Function Purpose: checks for whitespaces
*/
bool IsWhite(char c)
{
if (c==' '||c=='\t'||c=='\n')
{
if(c == '\n')
{
_lineCounter++;
Ident(_lineCounter);
}
return 1;
}
else return 0;
}
/*
Function Name: NewLine
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: Locate and Parse a newline
*/
void NewLine(void)
{
if (_lookAhead=='\n')
{
GetChar();
SkipWhite();
}
}
/*
Function Name: Match
Return Type: void
Purpose: does not return a value
Input Parameter: char
Purpose: matches the character
Function Purpose: match the given character from the keywordlist table
*/
void Match(char x)
{
SkipWhite();
if (_lookAhead==x)
{
GetChar();
}
else
{
printf("\n\t Line : %d Expected : %c",_lineCounter,x);exit(0);
}
if(_lookAhead != '\n')
SkipWhite();
}
/*
Function Name: Locate
Return Type: integer
Purpose: returns the index value of the symbol table
Input Parameter: _symbol
Purpose:
Function Purpose: locate symbol in table */
int Locate(_symbol n)
{
return LookUp(_st, n, MAX);
}
/*
Function Name: Intable
Return Type: bool
Purpose: returns a true or a false
Input Parameter: _symbol
Purpose:
Function Purpose: look for symbol in table. return index if not present */
bool InTable(_symbol n)
{
_index = 0;
if ((_index = LookUp(_st, n, _numEntry))!=0) return 1;
else return 0;
}
/*add a new entry to symbol table
Function Name: Add Entry
Return Type: void
Purpose: does not return a value
Input Parameter: char
Purpose:
Function Purpose: adds an entry into the symbol table
*/
void AddEntry(_symbol n, char t)
{
if( InTable(n) )
{
printf("Duplicate Identifier %s\n",n);
exit(0);
}
if( (_numEntry==MAX) )
Abort("Symbol Table Full");
_numEntry++;
strcpy(_st[_numEntry],n);
_stype[_numEntry]=t;
// set the default value to 0
_svalue[_numEntry] = 0;
}
/*
Function Name : GetName
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Get an identifier */
void GetName (void)
{
SkipWhite();
if(!IsAlpha(_lookAhead))
{
Expected("Identifier");
}
_token='x';
strcpy(_value,"");
int i = 0;
while(isalnum(_lookAhead))
{
_value[i] = toupper(_lookAhead);i++;
GetChar();
}
_value[i] = '\0';
Ident(_lineCounter);
}
/*
Function Name : GetNum
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : Get a Number*/
void GetNum(void)
{
SkipWhite();
if (!IsDigit(_lookAhead))
Expected("Number");
_token='#';
strcpy(_value,"");
int i=0;
_num = 0;
while (IsDigit(_lookAhead))
{
_num = (10 * _num) + (_lookAhead - '0');
i++;
GetChar();
}
//_value[i] = '\0';
}
/*
Function Name : GetChar
Return Type : void
Purpose : does not return a value
Input Parameter : void
Purpose :
Function Purpose : get the char from token stream and store it in _lookAhead
*/
void GetChar(void)
{
if(!_file)
_lookAhead = getchar();
else
_lookAhead = fgetc(_file);
if(_lookAhead == '/')
{
int oldLookAhead = _lookAhead;
_lookAhead = (_file) ? fgetc(_file) : getchar();
if(_lookAhead == '*')
{
SkipComment();
_lookAhead = (_file) ? fgetc(_file) : getchar();
}
else
{
ungetc(_lookAhead,(_file) ? _file : stdin);
_lookAhead = oldLookAhead;
}
}
}
/*
Function Name : IsAlpha
Return Type : bool
Purpose : Returns whether alphabet is true(1) or false(0)
Input Parameter : integer
Purpose : used to match the token.
Function Purpose : check if token is alphabet
*/
bool IsAlpha(int Char)
{
return isalpha(Char);
}
/*
Function Name : IsDigit
Return Type : bool
Purpose : Returns whether digit is true(1) or false(0)
Input Parameter : integer
Purpose : used to matcch the token
Function Purpose :check if token is digit
*/
bool IsDigit(int Char)
{
return isdigit(Char);
}
/*
Function Name : IsAddOp
Return Type : bool
Purpose : returns true if character is '+' or '-'
Input Parameter : char
Purpose : to check whether the given parameter is a valid operator or not
Function Purpose :procedure for addop
*/
bool IsAddOp(char c)
{
if (c == '+' || c == '-') //checks if the character is + or -
return true;
else
return false;
}
/*
Function Name : IsAlnum
Return Type : bool
Purpose : returns true if character typed is alphanumeric
Input Parameter : char
Purpose :
Function Purpose :function to cheak the alpha numeric value.
*/
bool IsAlNum(char c)
{
if(c == isalpha(c) || c == isdigit(c) )
return true;
else
return false;
}
/*
Function Name: Decl
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and Translate a Data Declaration
*/
void Decl(void)
{
GetName();
Alloc(_value);
while (_lookAhead==',')
{
Match(',');
GetName();
Alloc(_value);
}
}
/*
Function Name: TopDecls
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: Parse and Translate Global Declarations
*/
void TopDecls(void)
{
Scan();
while (_token!='b')
{
switch(_token)
{
case 'v': Decl();
break;
default: char temp[100];
strcpy(temp,"Unrecognized Keyword ");
strcat(temp,_value) ;
Abort(temp);
break;
}
Scan();
}
}
/*
Function Name: Alloc
Return Type: void
Purpose: does not return a value
Input Parameter: _symbol
Purpose:
Function Purpose: Allocate Storage for a Variable
*/
void Alloc(_symbol N)
{
if (InTable(N))
{
char temp[100];
strcpy(temp,"Duplicate Varible Name ");
strcat(temp,N);
Abort(temp);
}
AddEntry(N, 'v');
//printf("%s :\t DC ",N);
SkipWhite();
if (_lookAhead=='=')
{
Match('=');
if (_lookAhead=='-')
{
//printf("%c",_lookAhead);
Match('-');
}
GetNum();_svalue[_numEntry] = _num;
//printf("%d\n",_svalue[_numEntry]);
}
//printf("%d\n",_svalue[_numEntry]);
SkipWhite();
}
/*-------------------------------------------------*/
/*
Function Name: MainProg
Return Type:void
Purpose: does not return a value
Input Parameter:
Purpose:
Function Purpose: Parse and Translate a Main Program
*/
void MainProg()
{
MatchString("BEGIN");
Block("",0,_lineCount);
MatchString("END");
}
/*
Function Name: Prog
Return Type: void
Purpose: does not return a value
Input Parameter:
Purpose:
Function Purpose: Parse and Translate a Program
*/
void Prog()
{
MatchString("PROGRAM");
Header();
TopDecls();
MainProg();
Match('.');
}
/*
Function Name: Init
Return Type: void
Purpose: does not return a value
Input Parameter:
Purpose:
Function Purpose: Initialize
*/
void Init()
{
int i;
for (i=0;i<=MAX;i++)
{
strcpy(_st[i],"");
_stype[i] = ' ';
}
GetChar();
Scan();
_pc = 0;
}
/*
Function Name: Initialize
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: initialize global variables
*/
void Initialize(void)
{
_pc = 0;
_stackp = 0;
_num = 0;
_lineCounter = 1;
_lineCount = 0;
_true = false;
_levels = 0;
_lineLevel = 0;
_msgCount = 0;
}
/*
Function Name: Start
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: to start the sequence
*/
void Start(void)
{
Init();
Prog();
if (_lookAhead != '\n' && _lookAhead != EOF )
Abort("Unexpected data after . "); //check
}
/*
Function Name: Excecute
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: to start excecution
*/
void Execute(void)
{
Eval(0);
getchar();
if(_file)
fclose(_file);
}
/*
Function Name: Process
Return Type: void
Purpose: does not return a value
Input Parameter:
Purpose:
Function Purpose:
*/
void Process(void)
{
Initialize();
Start();
Execute();
for(int i = 0 ;i < _msgCount ; i++)
delete _strings[i];
}
/*
Function Name: ShowInfo
Return Type: void
Purpose: does not return a value
Input Parameter: void
Purpose:
Function Purpose: to show the initial information
*/
void ShowInfo(void)
{
puts(_info);
}
/*
Function Name: ShowErrot
Return Type: void
Purpose: does not return a value
Input Parameter: integer
Purpose:
Function Purpose: to display error messages
*/
void ShowError(int type)
{
printf("\nError : %s !",_errors[type]);
getchar();
exit(0);
}
/* Main Program */
void main(int argc,char* argv[])
{
if(argc == 1)
{
ShowInfo();
}
else if(argc == 2)
{
if(strcmp(strlwr(argv[1]),"run") == 0)
{
//_file = fopen(stdin,"r+");
//if(_file != NULL)
_file = NULL;
Process();
}
else
{
int len = strlen(argv[1]);
len--;
if(tolower(argv[1][len-2]) == '.' && tolower(argv[1][len-1]) == 's'
&& tolower(argv[1][len]) == 'l')
{
if((_file = fopen(argv[1],"r")) != NULL)
{
Process();
}
else
{
ShowError(FILE_DOES_NOT_EXIST);
}
}
else
{
ShowError(UNKNOWN_FILE_TYPE);
}
}
}
else
{
ShowError(UNKNOWN_OPTION);
}
}
| [
"karan.jude@45dc1b51-b92e-0410-8ae5-27a6066e960e"
] | [
[
[
1,
2627
]
]
] |
1f2ddaf044b311a2382eeef7988cfda44abe626f | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /lol4/gui/SaveLoadMenu.cpp | 55cde133861e26c81d3db38144ce1087a2a03c83 | [] | no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,111 | cpp | #include "SaveLoadMenu.h"
#include <GameApp.h>
#include <StandardApplication.h>
#include <functions.h>
bool NameTimeCompareFunction(const SaveLoadMenu::NameTime& first, const SaveLoadMenu::NameTime& second)
{
//returns true if the first argument goes before the second argument
//largest dates go first, therefore
return first.time > second.time;
}
SaveLoadMenu::SaveLoadMenu()
{
loadLayout("SaveLoadMenu.layout");
saveGameList = static_cast<CEGUI::Listbox*>(getWindow("saveloadwnd/savegamelist"));
nameBox = static_cast<CEGUI::Editbox*>(getWindow("saveloadwnd/namebox"));
saveBtn = static_cast<CEGUI::PushButton*>(getWindow("saveloadwnd/save"));
loadBtn = static_cast<CEGUI::PushButton*>(getWindow("saveloadwnd/load"));
deleteBtn = static_cast<CEGUI::PushButton*>(getWindow("saveloadwnd/delete"));
cancelBtn = static_cast<CEGUI::PushButton*>(getWindow("saveloadwnd/cancel"));
saveBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&SaveLoadMenu::saveClick, this));
loadBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&SaveLoadMenu::loadClick, this));
deleteBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&SaveLoadMenu::deleteClick, this));
cancelBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&SaveLoadMenu::cancelClick, this));
saveGameList->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&SaveLoadMenu::listClick, this));
saveGameList->subscribeEvent(CEGUI::Window::EventMouseDoubleClick, CEGUI::Event::Subscriber(&SaveLoadMenu::listDblClick, this));
}
SaveLoadMenu::~SaveLoadMenu()
{
destroyLayout();
}
bool SaveLoadMenu::loadClick(const CEGUI::EventArgs& e)
{
//CEGUI::Editbox *editbox = static_cast<CEGUI::Editbox*>(wmgr->getWindow("saveloadwnd/namebox"));
Ogre::String name = nameBox->getText().c_str();
if(name == "")
return true;
GameApp::getSingletonPtr()->loadGame(name);
return true;
}
bool SaveLoadMenu::saveClick(const CEGUI::EventArgs& e)
{
GameApp *app = GameApp::getSingletonPtr();
if(!app->getCurrentLevel())
return true;
Ogre::String name = nameBox->getText().c_str();
if(name == "")
return true;
app->saveGame(name);
update();
return true;
}
bool SaveLoadMenu::deleteClick(const CEGUI::EventArgs& e)
{
GameApp *app = GameApp::getSingletonPtr();
CEGUI::ListboxItem* cur = saveGameList->getFirstSelectedItem();
if(!cur)
return true;
ZipSaveFile toDel(cur->getText().c_str(),app->saveGamePath,SAVEGAME_EXTENSION);
toDel.eraseArchive();
update();
return true;
}
bool SaveLoadMenu::cancelClick(const CEGUI::EventArgs& e)
{
GameApp::getSingletonPtr()->setMenu(GameApp::GUI_MAINMENU);
return true;
}
bool SaveLoadMenu::listClick(const CEGUI::EventArgs& e)
{
CEGUI::ListboxItem *cur = saveGameList->getFirstSelectedItem();
if(!cur)
return true;
nameBox->setText(cur->getText());
return true;
}
bool SaveLoadMenu::listDblClick(const CEGUI::EventArgs& e)
{
return true;//wtf? was wollte ich hier?!
}
void SaveLoadMenu::update()
{
GameApp *app = GameApp::getSingletonPtr();
Ogre::ResourceGroupManager *resMgr = Ogre::ResourceGroupManager::getSingletonPtr();
//loading list of saves
StringVectorPtr savevector = resMgr->findResourceNames("Savegame",Ogre::String("*.")+SAVEGAME_EXTENSION);
//liste sortieren
NameTimeVector timevector;
for (Ogre::StringVector::iterator i = savevector->begin(); i != savevector->end(); ++i)
{
NameTime cur;
cur.name = *i;
cur.time = resMgr->resourceModifiedTime("Savegame",cur.name);//getFileDate( app->saveGamePath+"/"+cur.name );
timevector.push_back(cur);
}
//sortNameTimeVector(timevector);
std::sort(timevector.begin(),timevector.end(),NameTimeCompareFunction);
size_t cnt = saveGameList->getItemCount();
for(size_t i = 0;i < cnt;i++)
{
CEGUI::ListboxItem *listboxitem = saveGameList->getListboxItemFromIndex(0);
//setDebugText(String("\nremoved:")+listboxitem->getText().c_str(),true);
saveGameList->removeItem(listboxitem);
}
//saveList->subscribeEvent(CEGUI::Window::EventMouseButtonDown,CEGUI::Event::Subscriber(&EditorApp::meshListDown,this));
for (NameTimeVector::iterator i = timevector.begin(); i != timevector.end(); ++i)
{
//Ogre::String wtf = *i;
//getFileDate( saveGamePath+"/"+wtf );
Ogre::String fname, fext;
Ogre::StringUtil::splitBaseFilename((*i).name,fname,fext);
CEGUI::ListboxTextItem *listboxitem = new CEGUI::ListboxTextItem(fname.c_str());
listboxitem->setSelectionBrushImage(STYLE_GAME,"TextSelectionBrush");
//listboxitem->setTextColours(clBlack);
saveGameList->addItem(listboxitem);
}
}
void SaveLoadMenu::sortNameTimeVector(NameTimeVector &vec)
{
//bubblesort
bool done = false;
while(!done)
{
done = true;
for(size_t i = 1;i < vec.size();i++)
{
if(vec[i-1].time < vec[i].time)
{
done = false;
NameTime temp = vec[i-1];
vec[i-1] = vec[i];
vec[i] = temp;
}
}
}
} | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] | [
[
[
1,
159
]
]
] |
adf0b73b0b47f6da25fe46be114ecf8e17d9a4ba | 6ed8a7f8102c2c90baee79e086e589f553f7d2d3 | /SSC/source/SSC/SDL_CardLayout.h | e4d0842b71f0f33ba322b494683d12f7e0cf6de5 | [] | no_license | snaill/sscs | 3173c150c86b7dee7652c3547271b1f9c9b53c85 | b89f0dd9d9d34ceeeea4988550614ed36bdb1a18 | refs/heads/master | 2021-01-23T13:28:47.551752 | 2009-05-25T10:16:23 | 2009-05-25T10:16:23 | 32,121,178 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,175 | h | /*
* SDL_SimpleControls
* Copyright (C) 2008 Snaill
*
SDL_SimpleControls 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 3 of the License, or
(at your option) any later version.
SDL_SimpleControls 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 program. If not, see <http://www.gnu.org/licenses/>.
Snaill <[email protected]>
*/
#ifndef SDL_CARDLAYOUT_H_INCLUDED
#define SDL_CARDLAYOUT_H_INCLUDED
#include "SDL_Layout.h"
/// @brief 所有界面布局的基类,实现固定布局
class SDL_CardLayout : public SDL_Layout
{
// 基本属性
public:
SDL_CardLayout() { }
virtual ~SDL_CardLayout() { }
virtual const char * GetType() { return "SDL_CardLayout"; }
// 方法
public:
virtual SDL_Size GetPreferedSize() {
return GetActiveItem() ? GetActiveItem()->GetPreferedSize() : SDL_Size( 0, 0 );
}
/// @brief 设置图元所在区域
/// @param lprc 欲设置矩形位置
virtual void SetBounds( const SDL_Rect * lprc )
{
for ( std::vector<SDL_Glyph *>::iterator pos = m_aChildren.begin(); pos != m_aChildren.end(); pos ++ )
{
(*pos)->SetBounds( lprc );
}
SDL_BoundingBox::SetBounds( lprc );
}
public:
SDL_Glyph * GetActiveItem() {
if ( m_aChildren.empty() )
return 0;
return *m_aChildren.rbegin();
}
void SetActiveItem( SDL_Glyph * pActiveItem ) {
if ( m_aChildren.empty() )
return;
for ( std::vector<SDL_Glyph *>::iterator pos = m_aChildren.begin(); pos != m_aChildren.end(); pos ++ )
{
if ( pActiveItem == *pos ) {
m_aChildren.erase( pos );
}
}
m_aChildren.push_back( pActiveItem );
}
};
#endif // SDL_CARDLAYOUT_H_INCLUDED
| [
"com.chinaos.snaill@db7a99aa-9dca-11dd-b92e-bd4787f9249a"
] | [
[
[
1,
76
]
]
] |
ed38b4b8d1cf816072c94978bb681a69532ae529 | cd07acbe92f87b59260478f62a6f8d7d1e218ba9 | /src/LogInDlg.h | f1a15abfb8ebdd3c599f3df9ab11aadc60462f8c | [] | no_license | niepp/sperm-x | 3a071783e573d0c4bae67c2a7f0fe9959516060d | e8f578c640347ca186248527acf82262adb5d327 | refs/heads/master | 2021-01-10T06:27:15.004646 | 2011-09-24T03:33:21 | 2011-09-24T03:33:21 | 46,690,957 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | h | #if !defined(AFX_LOGINDLG_H__8BDFD9E8_C5D7_4FA4_864F_433801484302__INCLUDED_)
#define AFX_LOGINDLG_H__8BDFD9E8_C5D7_4FA4_864F_433801484302__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// LogInDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CLogInDlg dialog
#define USER_MSG_AFTERCONNECTDATABASE (WM_USER+103)
#define USER_MSG_SETBUTTONSTATE (WM_USER+104)
struct ConnectInfoThd{
HWND hwnd;
CString m_password;
CString m_strServerName;
CString m_strUsername;
};
class CLogInDlg : public CDialog
{
// Construction
public:
LRESULT AfterConnectDatabase(WPARAM w,LPARAM l);
const char* GetIP();
CLogInDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CLogInDlg)
enum { IDD = IDD_SYSTEM_LOGIN };
CComboBox m_cmbServerName;
CString m_strServerName;
CString m_password;
CString m_strUserName;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CLogInDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CLogInDlg)
virtual BOOL OnInitDialog();
virtual void OnOK();
afx_msg void OnButtonRegster();
afx_msg void OnDropdownComboUsername();
virtual void OnCancel();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
public:
LRESULT SetButtonState(WPARAM w,LPARAM l);
CWinThread* m_pThread;
CWinThread* m_pRegisterThread;
afx_msg void OnCbnSelchangeComboServerName();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_LOGINDLG_H__8BDFD9E8_C5D7_4FA4_864F_433801484302__INCLUDED_)
| [
"harithchen@e030fd90-5f31-5877-223c-63bd88aa7192"
] | [
[
[
1,
68
]
]
] |
b87b03ee145db565018c4b6c51128deba606b029 | dcff0f39e83ecab2ddcd482f3952ba317ee98f6c | /class-c++/project3/test.cpp | 7a6e7a9ef9e190c8b606ba6da84ced0d3ea2401b | [] | no_license | omgmovieslol/Code | f64048bc173e56538bb5f6164cce5d447cd7bd64 | d5083b416469507b685a81d07a78fec1868644b1 | refs/heads/master | 2021-01-01T18:49:25.480158 | 2010-03-08T09:25:01 | 2010-03-08T09:25:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | cpp | #include <iostream>
#include <cstring>
#include <fstream>
#define input_read 20
using namespace std;
class stack{
public:
stack() {
top = 0;
}
int isEmpty(void) {
return S.top;
}
int pop(void) {
assert(top > 0);
return data[top--];
}
int push(int x)(
data[++top] = x;
}
private:
int data[100];
int top;
}
class queue{
public:
queue() {
top = 0;
bottom = 0;
count = 0;
}
int isEmpty(void) {
return top;
}
int pull(void) {
assert(count > 0);
count--;
return data[bottom++];
}
int push(int x)(
data[++top] = x;
}
private:
int data[100];
int top, bottom, count;
}
int main() {
system("PAUSE");
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | [
[
[
1,
62
]
]
] |
7ce5bc84acc3b61ca758034aeef19d662a09c9a1 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/app/location/landmarks_ui_addedit_api/inc/BCAppLmkAddEdit.h | b514e9d7e061966e673203af02f1163d03ccbb12 | [] | 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 | 5,211 | h | /*
* Copyright (c) 2002 - 2007 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: ?Description
*
*/
#ifndef BCAPPLMKADDEDIT_H
#define BCAPPLMKADDEDIT_H
// INCLUDES
#include <StifLogger.h>
#include <TestScripterInternal.h>
#include <StifTestModule.h>
#include "BCAppLmkEditorEngine.h"
// CONSTANTS
//const ?type ?constant_var = ?constant;
// MACROS
//#define ?macro ?macro_def
#define TEST_CLASS_VERSION_MAJOR 30
#define TEST_CLASS_VERSION_MINOR 9
#define TEST_CLASS_VERSION_BUILD 38
// Logging path
_LIT( KBCAppLmkAddEditLogPath, "\\logs\\testframework\\BCAppLmkAddEdit\\" );
// Log file
_LIT( KBCAppLmkAddEditLogFile, "BCAppLmkAddEdit.txt" );
_LIT( KBCAppLmkAddEditLogFileWithTitle, "BCAppLmkAddEdit_[%S].txt" );
// FUNCTION PROTOTYPES
//?type ?function_name(?arg_list);
// FORWARD DECLARATIONS
//class ?FORWARD_CLASSNAME;
class CBCAppLmkAddEdit;
// DATA TYPES
//enum ?declaration
//typedef ?declaration
//extern ?data_type;
// CLASS DECLARATION
/**
* CBCAppLmkAddEdit test class for STIF Test Framework TestScripter.
* ?other_description_lines
*
* @lib ?library
* @since ?Series60_version
*/
NONSHARABLE_CLASS(CBCAppLmkAddEdit) : public CScriptBase
{
public: // Constructors and destructor
/**
* Two-phased constructor.
*/
static CBCAppLmkAddEdit* NewL( CTestModuleIf& aTestModuleIf );
/**
* Destructor.
*/
virtual ~CBCAppLmkAddEdit();
public: // New functions
/**
* ?member_description.
* @since ?Series60_version
* @param ?arg1 ?description
* @return ?description
*/
//?type ?member_function( ?type ?arg1 );
public: // Functions from base classes
/**
* From CScriptBase Runs a script line.
* @since ?Series60_version
* @param aItem Script line containing method name and parameters
* @return Symbian OS error code
*/
virtual TInt RunMethodL( CStifItemParser& aItem );
protected: // New functions
/**
* ?member_description.
* @since ?Series60_version
* @param ?arg1 ?description
* @return ?description
*/
//?type ?member_function( ?type ?arg1 );
protected: // Functions from base classes
/**
* From ?base_class ?member_description
*/
//?type ?member_function();
private:
/**
* C++ default constructor.
*/
CBCAppLmkAddEdit( CTestModuleIf& aTestModuleIf );
/**
* By default Symbian 2nd phase constructor is private.
*/
void ConstructL();
// Prohibit copy constructor if not deriving from CBase.
// ?classname( const ?classname& );
// Prohibit assigment operator if not deriving from CBase.
// ?classname& operator=( const ?classname& );
/**
* Frees all resources allocated from test methods.
* @since ?Series60_version
*/
void Delete();
/**
* Test methods are listed below.
*/
/**
* Example test method.
* @since ?Series60_version
* @param aItem Script line containing parameters.
* @return Symbian OS error code.
*/
virtual TInt ExampleL( CStifItemParser& aItem );
virtual TInt TestNewL( CStifItemParser& aItem );
virtual TInt TestNew2L( CStifItemParser& aItem );
virtual TInt TestExecuteLD( CStifItemParser& aItem );
virtual TInt TestSetMopParent( CStifItemParser& aItem );
virtual TInt TestSetHelpContext( CStifItemParser& aItem );
virtual TInt TestDisableMapAndNaviOptions( CStifItemParser& aItem );
//virtual TInt TestSetMoParent( CStifItemParser& aItem );
/**
* Method used to log version of test class
*/
void SendTestClassVersion();
//ADD NEW METHOD DEC HERE
//[TestMethods] - Do not remove
public: // Data
// ?one_line_short_description_of_data
//?data_declaration;
protected: // Data
// ?one_line_short_description_of_data
//?data_declaration;
private: // Data
CLmkAddEditEngine* engine;
// ?one_line_short_description_of_data
//?data_declaration;
// Reserved pointer for future extension
//TAny* iReserved;
public: // Friend classes
//?friend_class_declaration;
protected: // Friend classes
//?friend_class_declaration;
private: // Friend classes
//?friend_class_declaration;
};
#endif // BCAPPLMKADDEDIT_H
// End of File
| [
"none@none"
] | [
[
[
1,
195
]
]
] |
18f2bb50806832a19356713f51f68313fe17783e | 208475bcab65438eed5d8380f26eacd25eb58f70 | /QianExe/yx_LedChuangLi.h | 3d7ec24d0dfa6251be7acdcd3d911eda27322c55 | [] | no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 1,049 | h | #ifndef _YX_LED_CHUANGLI_H_
#define _YX_LED_CHUANGLI_H_
class CLedChuangLi
{
public:
CLedChuangLi();
virtual ~CLedChuangLi();
int Init();
int Release();
bool ComOpen();
bool ComClose();
int ComWrite(char *v_szBuf, int v_iLen);
int Deal0x42(BYTE v_bytDataType,char *v_szData, DWORD v_dwDataLen);
int Deal4208(char *v_szBuf, int v_iLen);
int TranData(char *v_szBuf, int v_iLen);
void MakeLedFrame(char v_szCmd, char v_szType, char v_szInfoNo, char *v_szInfoBuf, int v_iInfoLen, char *v_p_szFrameBuf, int &v_p_iFrameLen);
bool SendCmdForAns(char *v_szbuf, int v_iLen);
void P_ThreadRecv();
void P_ThreadWork();
void DealEvent(char v_szCmd, char v_szType, char v_szInfoNo);
bool check_crc(const byte *buf, const int len);
byte get_crc(const byte *buf, const int len);
public:
CInnerDataMng m_objWorkMng;
CInnerDataMng m_objReadMng;
private:
int m_iComPort;
byte m_bytInfoNo; // 中心下发信息的信息号
pthread_t m_pthreadRecv;
pthread_t m_pthreadWork;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
ba31660f88e80c80915ebdc0c905124e51b8e075 | 772690258e7a85244cc871d744bf54fc4e887840 | /ms22vv/Castle Defence Ogre3d/Castle Defence Ogre3d/View/Effects/CatmullRomProjectile.h | 528304fffc846d8614b4a2092cbc6c74521437f4 | [] | no_license | Argos86/dt2370 | f735d21517ab55de19cea933b467f46837bb6401 | 4a393a3c83deb3cb6df90b36a9c59e2e543917ee | refs/heads/master | 2021-01-13T00:53:43.286445 | 2010-02-01T07:43:50 | 2010-02-01T07:43:50 | 36,057,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | h | #ifndef Catmull_Rom_Projectile_H_
#define Catmull_Rom_Projectile_H_
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreVector2.h>
#include <OgreVector3.h>
#include <OgreQuaternion.h>
#include <OgreString.h>
#include <OgreBillboardSet.h>
#include <OgreSimpleSpline.h>
#include <OgreRibbonTrail.h>
#include <OgreFrameListener.h>
class CatmullRomProjectile
{
private:
Ogre::SceneNode *m_projectileNode;
Ogre::String m_uniqueName;
Ogre::BillboardSet *m_projectileBbs;
Ogre::SceneManager *m_scenemgr;
Ogre::SimpleSpline *m_spline;
Ogre::RibbonTrail *m_trail;
void CatmullRomProjectile::InitTrail();
float m_time;
float m_lifetime;
public:
CatmullRomProjectile::CatmullRomProjectile( Ogre::Vector3 a_weaponPosition, Ogre::Quaternion a_weaponOrientation, Ogre::SceneManager *a_scenemgr, Ogre::Real a_fireId, Ogre::String a_weaponName, float a_offset, int a_distance);
bool CatmullRomProjectile::Update( Ogre::Real a_timeSinceLastFrame);
CatmullRomProjectile::~CatmullRomProjectile();
};
#endif
| [
"[email protected]@3422cff2-cdd9-11de-91bf-0503b81643b9"
] | [
[
[
1,
37
]
]
] |
5860545a6bea98688f640830f5a3bb326955865b | fdfaf8e8449c5e80d93999ea665db48feaecccbe | /trunk/cg ex1/ForwardEulerSolver.h | 08d08391823d96d82908eff1a3728c2da802f2ea | [] | no_license | BackupTheBerlios/glhuji2005-svn | 879e60533f820d1bdcfa436fd27894774c27a0b7 | 3afe113b265704e385c94fabaf99a7d1ad1fdb02 | refs/heads/master | 2016-09-01T17:25:30.876585 | 2006-09-03T18:04:19 | 2006-09-03T18:04:19 | 40,673,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | h | #ifndef __FORWARD_EULER_SOLVER_H__
#define __FORWARD_EULER_SOLVER_H__
#include "NumericalSolver.h"
class ForwardEulerSolver : public NumericalSolver
{
public:
ForwardEulerSolver();
~ForwardEulerSolver();
virtual void step( double h );
protected:
Vector3d *mAccel;
};
#endif //__FORWARD_EULER_SOLVER_H__ | [
"playmobil@c8a6d0be-e207-0410-856a-d97b7f264bab",
"itai@c8a6d0be-e207-0410-856a-d97b7f264bab"
] | [
[
[
1,
2
],
[
9,
11
],
[
13,
15
],
[
18,
18
]
],
[
[
3,
8
],
[
12,
12
],
[
16,
17
]
]
] |
db1fcbc1c487013536a85f3e8042118d498e1a1a | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/internal/XSerializationException.hpp | 46a5bbe86bf29770bd4e343cf21c7d0a29f6df42 | [
"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 | 1,248 | 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: XSerializationException.hpp,v $
* Revision 1.2 2004/09/08 13:56:14 peiyongz
* Apache License Version 2.0
*
* Revision 1.1 2003/09/18 18:31:24 peiyongz
* OSU: Object Serialization Utilities
*
* $Id: XSerializationException.hpp,v 1.2 2004/09/08 13:56:14 peiyongz Exp $
*
*/
#if !defined(XSERIALIZATION_EXCEPTION_HPP)
#define XSERIALIZATION_EXCEPTION_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
MakeXMLException(XSerializationException, XMLUTIL_EXPORT)
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
cd535b48fe05082b18bfd6c1b4192e1c9fbd7cb3 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/SkinEditor/BackgroundControl.h | 24da6b96cdccd8a7f285b6f62543d758cf7433a9 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,074 | h | /*!
@file
@author Albert Semenov
@date 08/2010
*/
#ifndef __BACKGROUND_CONTROL_H__
#define __BACKGROUND_CONTROL_H__
#include "BaseLayout/BaseLayout.h"
#include "Property.h"
#include "ColourPanel.h"
namespace tools
{
class BackgroundControl :
public wraps::BaseLayout
{
public:
BackgroundControl(MyGUI::Widget* _parent);
virtual ~BackgroundControl();
MyGUI::Widget* getCanvas()
{
return mCanvas;
}
private:
void notifyComboChangePosition(MyGUI::ComboBox* _sender, size_t _index);
void notifyMouseButtonClick(MyGUI::Widget* _sender);
void notifyChangePosition();
void notifyEndDialog(Dialog* _sender, bool _result);
void fillColours(MyGUI::ComboBox* _combo);
void updateColourByPresets();
void updateColours();
private:
MyGUI::ComboBox* mBackgroundColour;
MyGUI::Widget* mBackground;
MyGUI::Widget* mBackgroundButton;
MyGUI::Widget* mCanvas;
ColourPanel* mColourPanel;
MyGUI::Colour mCurrentColour;
};
} // namespace tools
#endif // __BACKGROUND_CONTROL_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
53
]
]
] |
adb5f5d2c34e1da4c6664ff000b95095a8470ee4 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleAffectors/ParticleUniverseSineForceAffectorFactory.h | ad3daa8e6e49e2a69d21dba7f94974f12694ffaa | [] | 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,140 | 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_SINE_FORCE_AFFECTOR_FACTORY_H__
#define __PU_SINE_FORCE_AFFECTOR_FACTORY_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseSineForceAffectorTokens.h"
#include "ParticleUniverseSineForceAffector.h"
#include "ParticleUniverseAffectorFactory.h"
namespace ParticleUniverse
{
/** Factory class responsible for creating the SineForceAffector.
*/
class _ParticleUniverseExport SineForceAffectorFactory : public ParticleAffectorFactory
{
public:
SineForceAffectorFactory(void) {};
virtual ~SineForceAffectorFactory(void) {};
/** See ParticleAffectorFactory */
Ogre::String getAffectorType(void) const
{
return "SineForce";
}
/** See ParticleAffectorFactory */
ParticleAffector* createAffector(void)
{
return _createAffector<SineForceAffector>();
}
/** See ScriptReader */
virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node)
{
return mSineForceAffectorTranslator.translateChildProperty(compiler, node);
};
/** See ScriptReader */
virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node)
{
return mSineForceAffectorTranslator.translateChildObject(compiler, node);
};
/* */
virtual void write(ParticleScriptSerializer* serializer , const IElement* element)
{
// Delegate
mSineForceAffectorWriter.write(serializer, element);
}
protected:
SineForceAffectorWriter mSineForceAffectorWriter;
SineForceAffectorTranslator mSineForceAffectorTranslator;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
b45a0bdeac190118fdbb0749f7d8a4748b21b4df | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Intersection/WmlIntrLin2Box2.cpp | 27b0ee5f5426e638ebf4c6f84982138268bb88b2 | [] | 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 | 10,946 | 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 "WmlIntrLin2Box2.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Segment2<Real>& rkSegment,
const Box2<Real>& rkBox)
{
Real fAWdU[2], fADdU[2], fRhs;
Vector2<Real> kSDir = ((Real)0.5)*rkSegment.Direction();
Vector2<Real> kSCen = rkSegment.Origin() + kSDir;
Vector2<Real> kDiff = kSCen - rkBox.Center();
fAWdU[0] = Math<Real>::FAbs(kSDir.Dot(rkBox.Axis(0)));
fADdU[0] = Math<Real>::FAbs(kDiff.Dot(rkBox.Axis(0)));
fRhs = rkBox.Extent(0) + fAWdU[0];
if ( fADdU[0] > fRhs )
return false;
fAWdU[1] = Math<Real>::FAbs(kSDir.Dot(rkBox.Axis(1)));
fADdU[1] = Math<Real>::FAbs(kDiff.Dot(rkBox.Axis(1)));
fRhs = rkBox.Extent(1) + fAWdU[1];
if ( fADdU[1] > fRhs )
return false;
Vector2<Real> kPerp = rkSegment.Direction().Perp();
Real fLhs = Math<Real>::FAbs(kPerp.Dot(kDiff));
Real fPart0 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(0)));
Real fPart1 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(1)));
fRhs = rkBox.Extent(0)*fPart0 + rkBox.Extent(1)*fPart1;
return fLhs <= fRhs;
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Ray2<Real>& rkRay, const Box2<Real>& rkBox)
{
Real fWdU[2], fAWdU[2], fDdU[2], fADdU[2], fRhs;
Vector2<Real> kDiff = rkRay.Origin() - rkBox.Center();
fWdU[0] = rkRay.Direction().Dot(rkBox.Axis(0));
fAWdU[0] = Math<Real>::FAbs(fWdU[0]);
fDdU[0] = kDiff.Dot(rkBox.Axis(0));
fADdU[0] = Math<Real>::FAbs(fDdU[0]);
if ( fADdU[0] > rkBox.Extent(0) && fDdU[0]*fWdU[0] >= 0.0f )
return false;
fWdU[1] = rkRay.Direction().Dot(rkBox.Axis(1));
fAWdU[1] = Math<Real>::FAbs(fWdU[1]);
fDdU[1] = kDiff.Dot(rkBox.Axis(1));
fADdU[1] = Math<Real>::FAbs(fDdU[1]);
if ( fADdU[1] > rkBox.Extent(1) && fDdU[1]*fWdU[1] >= 0.0f )
return false;
Vector2<Real> kPerp = rkRay.Direction().Perp();
Real fLhs = Math<Real>::FAbs(kPerp.Dot(kDiff));
Real fPart0 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(0)));
Real fPart1 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(1)));
fRhs = rkBox.Extent(0)*fPart0 + rkBox.Extent(1)*fPart1;
return fLhs <= fRhs;
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Line2<Real>& rkLine,
const Box2<Real>& rkBox)
{
Vector2<Real> kDiff = rkLine.Origin() - rkBox.Center();
Vector2<Real> kPerp = rkLine.Direction().Perp();
Real fLhs = Math<Real>::FAbs(kPerp.Dot(kDiff));
Real fPart0 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(0)));
Real fPart1 = Math<Real>::FAbs(kPerp.Dot(rkBox.Axis(1)));
Real fRhs = rkBox.Extent(0)*fPart0 + rkBox.Extent(1)*fPart1;
return fLhs <= fRhs;
}
//----------------------------------------------------------------------------
template <class Real>
static bool Clip (Real fDenom, Real fNumer, Real& rfT0, Real& rfT1)
{
// Return value is 'true' if line segment intersects the current test
// plane. Otherwise 'false' is returned in which case the line segment
// is entirely clipped.
if ( fDenom > (Real)0.0 )
{
if ( fNumer > fDenom*rfT1 )
return false;
if ( fNumer > fDenom*rfT0 )
rfT0 = fNumer/fDenom;
return true;
}
else if ( fDenom < (Real)0.0 )
{
if ( fNumer > fDenom*rfT0 )
return false;
if ( fNumer > fDenom*rfT1 )
rfT1 = fNumer/fDenom;
return true;
}
else
{
return fNumer <= (Real)0.0;
}
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::FindIntersection (const Vector2<Real>& rkOrigin,
const Vector2<Real>& rkDirection, const Real afExtent[3], Real& rfT0,
Real& rfT1)
{
Real fSaveT0 = rfT0, fSaveT1 = rfT1;
bool bNotEntirelyClipped =
Clip(+rkDirection.X(),-rkOrigin.X()-afExtent[0],rfT0,rfT1) &&
Clip(-rkDirection.X(),+rkOrigin.X()-afExtent[0],rfT0,rfT1) &&
Clip(+rkDirection.Y(),-rkOrigin.Y()-afExtent[1],rfT0,rfT1) &&
Clip(-rkDirection.Y(),+rkOrigin.Y()-afExtent[1],rfT0,rfT1);
return bNotEntirelyClipped && ( rfT0 != fSaveT0 || rfT1 != fSaveT1 );
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::FindIntersection (const Segment2<Real>& rkSegment,
const Box2<Real>& rkBox, int& riQuantity, Vector2<Real> akPoint[2])
{
// convert segment to box coordinates
Vector2<Real> kDiff = rkSegment.Origin() - rkBox.Center();
Vector2<Real> kOrigin(
kDiff.Dot(rkBox.Axis(0)),
kDiff.Dot(rkBox.Axis(1))
);
Vector2<Real> kDirection(
rkSegment.Direction().Dot(rkBox.Axis(0)),
rkSegment.Direction().Dot(rkBox.Axis(1))
);
Real fT0 = (Real)0.0, fT1 = (Real)1.0;
bool bIntersects = FindIntersection(kOrigin,kDirection,rkBox.Extents(),
fT0,fT1);
if ( bIntersects )
{
if ( fT0 > (Real)0.0 )
{
if ( fT1 < (Real)1.0 )
{
riQuantity = 2;
akPoint[0] = rkSegment.Origin() + fT0*rkSegment.Direction();
akPoint[1] = rkSegment.Origin() + fT1*rkSegment.Direction();
}
else
{
riQuantity = 1;
akPoint[0] = rkSegment.Origin() + fT0*rkSegment.Direction();
}
}
else // fT0 == 0
{
if ( fT1 < (Real)1.0 )
{
riQuantity = 1;
akPoint[0] = rkSegment.Origin() + fT1*rkSegment.Direction();
}
else // fT1 == 1
{
// segment entirely in box
riQuantity = 0;
}
}
}
else
{
riQuantity = 0;
}
return bIntersects;
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::FindIntersection (const Ray2<Real>& rkRay, const Box2<Real>& rkBox,
int& riQuantity, Vector2<Real> akPoint[2])
{
// convert ray to box coordinates
Vector2<Real> kDiff = rkRay.Origin() - rkBox.Center();
Vector2<Real> kOrigin(
kDiff.Dot(rkBox.Axis(0)),
kDiff.Dot(rkBox.Axis(1))
);
Vector2<Real> kDirection(
rkRay.Direction().Dot(rkBox.Axis(0)),
rkRay.Direction().Dot(rkBox.Axis(1))
);
Real fT0 = (Real)0.0, fT1 = Math<Real>::MAX_REAL;
bool bIntersects = FindIntersection(kOrigin,kDirection,rkBox.Extents(),
fT0,fT1);
if ( bIntersects )
{
if ( fT0 > (Real)0.0 )
{
riQuantity = 2;
akPoint[0] = rkRay.Origin() + fT0*rkRay.Direction();
akPoint[1] = rkRay.Origin() + fT1*rkRay.Direction();
}
else // fT0 == 0
{
riQuantity = 1;
akPoint[0] = rkRay.Origin() + fT1*rkRay.Direction();
}
}
else
{
riQuantity = 0;
}
return bIntersects;
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::FindIntersection (const Line2<Real>& rkLine,
const Box2<Real>& rkBox, int& riQuantity, Vector2<Real> akPoint[2])
{
// convert line to box coordinates
Vector2<Real> kDiff = rkLine.Origin() - rkBox.Center();
Vector2<Real> kOrigin(
kDiff.Dot(rkBox.Axis(0)),
kDiff.Dot(rkBox.Axis(1))
);
Vector2<Real> kDirection(
rkLine.Direction().Dot(rkBox.Axis(0)),
rkLine.Direction().Dot(rkBox.Axis(1))
);
Real fT0 = -Math<Real>::MAX_REAL, fT1 = Math<Real>::MAX_REAL;
bool bIntersects = FindIntersection(kOrigin,kDirection,rkBox.Extents(),
fT0,fT1);
if ( bIntersects )
{
if ( fT0 != fT1 )
{
riQuantity = 2;
akPoint[0] = rkLine.Origin() + fT0*rkLine.Direction();
akPoint[1] = rkLine.Origin() + fT1*rkLine.Direction();
}
else
{
riQuantity = 1;
akPoint[0] = rkLine.Origin() + fT0*rkLine.Direction();
}
}
else
{
riQuantity = 0;
}
return bIntersects;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template WML_ITEM bool TestIntersection<float> (const Segment2<float>&,
const Box2<float>&);
template WML_ITEM bool TestIntersection<float> (const Ray2<float>&,
const Box2<float>&);
template WML_ITEM bool TestIntersection<float> (const Line2<float>&,
const Box2<float>&);
template WML_ITEM bool FindIntersection<float> (const Vector2<float>&,
const Vector2<float>&, const float[2], float&, float&);
template WML_ITEM bool FindIntersection<float> (const Segment2<float>&,
const Box2<float>&, int&, Vector2<float>[2]);
template WML_ITEM bool FindIntersection<float> (const Ray2<float>&,
const Box2<float>&, int&, Vector2<float>[2]);
template WML_ITEM bool FindIntersection<float> (const Line2<float>&,
const Box2<float>&, int&, Vector2<float>[2]);
template WML_ITEM bool TestIntersection<double> (const Segment2<double>&,
const Box2<double>&);
template WML_ITEM bool TestIntersection<double> (const Ray2<double>&,
const Box2<double>&);
template WML_ITEM bool TestIntersection<double> (const Line2<double>&,
const Box2<double>&);
template WML_ITEM bool FindIntersection<double> (const Vector2<double>&,
const Vector2<double>&, const double[2], double&, double&);
template WML_ITEM bool FindIntersection<double> (const Segment2<double>&,
const Box2<double>&, int&, Vector2<double>[2]);
template WML_ITEM bool FindIntersection<double> (const Ray2<double>&,
const Box2<double>&, int&, Vector2<double>[2]);
template WML_ITEM bool FindIntersection<double> (const Line2<double>&,
const Box2<double>&, int&, Vector2<double>[2]);
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
306
]
]
] |
a9870fa44a2ee62a9e63826b6b30a5beba463fee | cea7035f95c521eea60de884c12377e7d816c6e9 | /c/Robot/Accelerometer.cpp | 3a0c19ffbb2c2ab9835bac02aac28c159fe50502 | [] | no_license | mjcoss/usfirst-panther-robotics-303 | 7bc73321a38d951810d84104b019b9854b1091ac | 3b3f4ba479e72890cc6ac1157426daa831e5363c | refs/heads/master | 2021-01-19T10:31:34.858413 | 2009-11-18T04:38:14 | 2009-11-18T04:38:14 | 32,275,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Accelerometer.h"
#include "AnalogChannel.h"
#include "AnalogModule.h"
#include "Timer.h"
#include "Utility.h"
#include "WPIStatus.h"
/**
* Common function for initializing the accelerometer.
*/
void Accelerometer::InitAccelerometer()
{
m_voltsPerG = kVoltsPerG;
m_zeroGVoltage = kZeroVoltage;
m_analogChannel->SetAverageBits(kAverageBits);
m_analogChannel->SetOversampleBits(kOversampleBits);
float sampleRate = kSamplesPerSecond *
(1 << (kAverageBits + kOversampleBits));
m_analogChannel->GetModule()->SetSampleRate(sampleRate);
Wait(1.0);
}
/**
* Create a new instance of an accelerometer.
*
* The accelerometer is assumed to be in the first analog module in the given analog channel. The
* constructor allocates desired analog channel.
*/
Accelerometer::Accelerometer(UINT32 channel)
{
m_analogChannel = new AnalogChannel(channel);
m_allocatedChannel = true;
InitAccelerometer();
}
/**
* Create new instance of accelerometer.
*
* Make a new instance of the accelerometer given a module and channel. The constructor allocates
* the desired analog channel from the specified module
*/
Accelerometer::Accelerometer(UINT32 slot, UINT32 channel)
{
m_analogChannel = new AnalogChannel(slot, channel);
m_allocatedChannel = true;
InitAccelerometer();
}
/**
* Create a new instance of Accelerometer from an existing AnalogChannel.
* Make a new instance of accelerometer given an AnalogChannel. This is particularly
* useful if the port is going to be read as an analog channel as well as through
* the Accelerometer class.
*/
Accelerometer::Accelerometer(AnalogChannel *channel)
{
if (channel == NULL)
{
wpi_fatal(NullParameter);
}
else
{
m_analogChannel = channel;
InitAccelerometer();
}
m_allocatedChannel = false;
}
/**
* Delete the analog components used for the accelerometer.
*/
Accelerometer::~Accelerometer()
{
if (m_allocatedChannel)
{
delete m_analogChannel;
}
}
/**
* Return the acceleration in Gs.
*
* The acceleration is returned units of Gs.
*
* @return The current acceleration of the sensor in Gs.
*/
float Accelerometer::GetAcceleration()
{
return (m_analogChannel->GetAverageVoltage() - m_zeroGVoltage) / m_voltsPerG;
}
/**
* Set the accelerometer sensitivity.
*
* This sets the sensitivity of the accelerometer used for calculating the acceleration.
* The sensitivity varys by accelerometer model. There are constants defined for various models.
*
* @param sensitivity The sensitivity of accelerometer in Volts per G.
*/
void Accelerometer::SetSensitivity(float sensitivity)
{
m_voltsPerG = sensitivity;
}
/**
* Set the voltage that corresponds to 0 G.
*
* The zero G voltage varys by accelerometer model. There are constants defined for various models.
*
* @param zero The zero G voltage.
*/
void Accelerometer::SetZero(float zero)
{
m_zeroGVoltage = zero;
}
/**
* Get the Acceleration for the PID Source parent.
*
* @return The current acceleration in Gs.
*/
double Accelerometer::PIDGet()
{
return GetAcceleration();
}
| [
"mjcoss@e39f0ed2-d3fb-11de-bb02-e302c5db49d5"
] | [
[
[
1,
132
]
]
] |
326a5b79fe62afdae58ad88008808e255fe0b6f8 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/vis/properties/double/vis_properties_double_init.h | e723f829040e11b8461737a83e7b9bdebd598dc1 | [
"MIT",
"BSD-3-Clause"
] | permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | h | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#ifndef __SHAWN_TUBSAPPS_VIS_PROPERTIES_DOUBLE_INIT_H
#define __SHAWN_TUBSAPPS_VIS_PROPERTIES_DOUBLE_INIT_H
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
namespace shawn
{ class SimulationController; }
namespace vis
{
void init_vis_double_properties( shawn::SimulationController& );
}
#endif
#endif
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/tubsapps/vis/properties/double/vis_properties_double_init.h,v $
* Version $Revision: 1.1 $
* Date $Date: 2006/01/31 12:44:00 $
*-----------------------------------------------------------------------
* $Log: vis_properties_double_init.h,v $
* Revision 1.1 2006/01/31 12:44:00 ali
* *** empty log message ***
*
*-----------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
f6df7067a1f91c4362d223764fa255b4841804f3 | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /lol4edit/gui/moc_GenericSelectDialog.cpp | 70a56b48a2677cfe5e724d3f0290cf71fd3b0017 | [] | no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,784 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'GenericSelectDialog.h'
**
** Created: Sat 23. Jul 21:19:24 2011
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "GenericSelectDialog.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'GenericSelectDialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_GenericSelectDialog[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
26, 21, 20, 20, 0x0a,
60, 20, 20, 20, 0x0a,
69, 20, 20, 20, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_GenericSelectDialog[] = {
"GenericSelectDialog\0\0item\0"
"acceptSelection(QListWidgetItem*)\0"
"accept()\0reject()\0"
};
const QMetaObject GenericSelectDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_GenericSelectDialog,
qt_meta_data_GenericSelectDialog, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &GenericSelectDialog::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *GenericSelectDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *GenericSelectDialog::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_GenericSelectDialog))
return static_cast<void*>(const_cast< GenericSelectDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int GenericSelectDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: acceptSelection((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break;
case 1: accept(); break;
case 2: reject(); break;
default: ;
}
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] | [
[
[
1,
85
]
]
] |
8f696d13117f2a5ad5d73c9007e1882fefe637e7 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/spirit/fusion/test/transform_tests.cpp | 4b6a60060bcad4fa481e62192947844b332f7b0a | [
"BSL-1.0"
] | permissive | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,931 | cpp | /*=============================================================================
Copyright (c) 2003 Joel de Guzman
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)
==============================================================================*/
#include <boost/test/minimal.hpp>
#include <boost/spirit/fusion/sequence/tuple.hpp>
#include <boost/spirit/fusion/sequence/io.hpp>
#include <boost/spirit/fusion/sequence/make_tuple.hpp>
#include <boost/spirit/fusion/sequence/equal_to.hpp>
#include <boost/spirit/fusion/sequence/type_sequence.hpp>
#include <boost/spirit/fusion/algorithm/transform.hpp>
#include <boost/type_traits/is_class.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/spirit/fusion/sequence/generate.hpp>
struct square
{
template <typename T>
struct apply
{
typedef int type;
};
template <typename T>
int operator()(T x) const
{
return x * x;
}
};
int
test_main(int, char*[])
{
using namespace boost::fusion;
using boost::mpl::range_c;
std::cout << tuple_open('[');
std::cout << tuple_close(']');
std::cout << tuple_delimiter(", ");
/// Testing the transform
{
typedef range_c<int, 5, 9> mpl_list1;
typedef type_sequence<mpl_list1> sequence_type;
sequence_type sequence;
std::cout << transform(sequence, square()) << std::endl;
BOOST_TEST((transform(sequence, square()) == make_tuple(25, 36, 49, 64)));
}
{
typedef range_c<int, 5, 9> mpl_list1;
std::cout << transform(mpl_list1(), square()) << std::endl;
BOOST_TEST((transform(mpl_list1(), square()) == make_tuple(25, 36, 49, 64)));
}
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
65
]
]
] |
9b7260a34314919bb262e8b47fa28d12eb5acf93 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/GRAPHICS/gropenglextension.cpp | 354ba997a1dcf035374299bfe5be867fef3fc9d0 | [] | no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,298 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Graphics/GrOpenGLExtension.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:41 $
* $Author: Spearhawk $
*
* source for extension implementation in OpenGL
*
* $Log: gropenglextension.cpp,v $
* Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 20:47:07 Darkhill
* no message
*
* Revision 1.1 2004/05/24 07:25:32 taylor
* filename case change
*
* Revision 2.3 2004/04/13 01:55:41 phreak
* put in the correct fields for the CVS comments to register
* fixed a glowmap problem that occured when rendering glowmapped and non-glowmapped ships
*
*
* $NoKeywords: $
*/
#include <windows.h>
#include "globalincs/pstypes.h"
#include "graphics/gl/gl.h"
#include "graphics/gropengl.h"
#include "graphics/gropenglextension.h"
#include "osapi/outwnd.h"
char *OGL_extension_string;
/*
typedef struct ogl_extension
{
int enabled; //is this extension enabled
const char* extension_name; //name found in extension string
int required_to_run; //is this extension required for use
} ogl_extension;
ogl_extension GL_Extensions[GL_NUM_EXTENSIONS]=
{
{0, "GL_EXT_fog_coord",0},
{0, "GL_ARB_multitexture",1}, //required for glow maps
{0, "GL_ARB_texture_env_add", 1}, //required for glow maps
{0, "GL_ARB_texture_compression",0},
{0, "GL_EXT_texture_compression_s3tc",0},
{0, "GL_EXT_texture_filter_anisotropic", 0},
{0, "GL_NV_fog_distance", 0},
{0, "GL_EXT_secondary_color", 0},
{0, "GL_ARB_texture_env_combine",0},
{0, "GL_EXT_texture_env_combine",0},
{0, "GL_EXT_compiled_vertex_array",0},
{0, "GL_ARB_transpose_matrix",1},
{0, "GL_ARB_vertex_buffer_object",0}
};*/
ogl_extension GL_Extensions[GL_NUM_EXTENSIONS]=
{
{0, NULL, "glFogCoordfEXT", "GL_EXT_fog_coord",0},
{0, NULL, "glFogCoordPointerEXT", "GL_EXT_fog_coord",0},
{0, NULL, "glMultiTexCoord2fARB", "GL_ARB_multitexture",1}, //required for glow maps
{0, NULL, "glActiveTextureARB", "GL_ARB_multitexture",1}, //required for glow maps
{0, NULL, NULL, "GL_ARB_texture_env_add", 1}, //required for glow maps
{0, NULL, "glCompressedTexImage2D", "GL_ARB_texture_compression",0},
{0, NULL, NULL, "GL_EXT_texture_compression_s3tc",0},
{0, NULL, NULL, "GL_EXT_texture_filter_anisotropic", 0},
{0, NULL, NULL, "GL_NV_fog_distance", 0},
{0, NULL, "glSecondaryColor3fvEXT", "GL_EXT_secondary_color", 0},
{0, NULL, "glSecondaryColor3ubvEXT", "GL_EXT_secondary_color", 0},
{0, NULL, NULL, "GL_ARB_texture_env_combine",0},
{0, NULL, NULL, "GL_EXT_texture_env_combine",0},
{0, NULL, "glLockArraysEXT", "GL_EXT_compiled_vertex_array",0},
{0, NULL, "glUnlockArraysEXT", "GL_EXT_compiled_vertex_array",0},
{0, NULL,"glLoadTransposeMatrixfARB","GL_ARB_transpose_matrix", 1},
{0, NULL, "glMultTransposeMatrixfARB", "GL_ARB_transpose_matrix",1},
{0, NULL, "glClientActiveTextureARB", "GL_ARB_multitexture",1},
{0, NULL, "glBindBufferARB", "GL_ARB_vertex_buffer_object",0},
{0, NULL, "glDeleteBuffersARB", "GL_ARB_vertex_buffer_object",0},
{0, NULL, "glGenBuffersARB", "GL_ARB_vertex_buffer_object",0},
{0, NULL, "glBufferDataARB", "GL_ARB_vertex_buffer_object",0}
};
//tries to find a certain extension
static inline int opengl_find_extension(const char* ext_to_find)
{
return (strstr(OGL_extension_string,ext_to_find)!=NULL);
}
void opengl_print_extensions()
{
//print out extensions
const char*OGL_extensions=(const char*)glGetString(GL_EXTENSIONS);
char *extlist;
char *curext;
extlist=(char*)malloc(strlen(OGL_extensions));
memcpy(extlist, OGL_extensions, strlen(OGL_extensions));
curext=strtok(extlist, " ");
while (curext)
{
mprintf(( "%s\n", curext ));
curext=strtok(NULL, " ");
}
free(extlist);
}
int opengl_extension_is_enabled(int idx)
{
if ((idx < 0) || (idx >= GL_NUM_EXTENSIONS)) return 0;
return GL_Extensions[idx].enabled;
}
//finds OGL extension functions
//returns number found
int opengl_get_extensions()
{
OGL_extension_string = (char*)glGetString(GL_EXTENSIONS);
int num_found=0;
ogl_extension *cur=NULL;
for (int i=0; i < GL_NUM_EXTENSIONS; i++)
{
cur=&GL_Extensions[i];
if (opengl_find_extension(cur->extension_name))
{
//some extensions do not have functions
if (cur->function_name==NULL)
{
mprintf(("found extension %s\n", cur->extension_name));
cur->enabled=1;
num_found++;
continue;
}
cur->func_pointer=(uint)wglGetProcAddress(cur->function_name);
if (cur->func_pointer)
{
cur->enabled=1;
mprintf(("found extension function: %s -- extension: %s\n", cur->function_name, cur->extension_name));
num_found++;
}
else
{
mprintf(("found extension, but not function: %s -- extension:%s\n", cur->function_name, cur->extension_name));
}
}
else
{
mprintf(("did not find extension: %s\n", cur->extension_name));
if (cur->required_to_run)
{
Error(__FILE__,__LINE__,"The required OpenGL extension %s is not supported by your graphics card, please use the Glide or Direct3D rendering engines.\n\n",cur->extension_name);
}
}
}
return num_found;
}
/*
//finds OGL extension functions
//returns number found
int opengl_get_extensions()
{
int num_found=0;
ogl_extension *cur=NULL;
OGL_extension_string=(char*)glGetString(GL_EXTENSIONS);
for (int i=0; i < GL_NUM_EXTENSIONS; i++)
{
cur=&GL_Extensions[i];
if (opengl_find_extension(cur->extension_name))
{
num_found++;
cur->enabled = 1;
}
else
{
mprintf(("did not find extension: %s\n", cur->extension_name));
if (cur->required_to_run)
{
Error(__FILE__,__LINE__,"The required OpenGL extension %s is not supported by your graphics card, please use the Glide or Direct3D rendering engines.\n\n",cur->extension_name);
}
}
}
return num_found;
}
*/
//Extension Implementation Functions
//ifdef this out if compiling for linux | [
"[email protected]"
] | [
[
[
1,
208
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.