blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
914071714554ebf15d83c3ba80173a58749c088e
c436aa4235117da3d21fafeeafd96076ee8fea78
/globaldata.cpp
f7e3a36df387cd9686aceff5a0406bd2312eee35
[]
no_license
tinku99/ahkmingw
95bb91840b5b596f7c9c2e42b9fd6f554dc99623
8ee59d8a0c4262bab2069953514bda8ed116116d
refs/heads/master
2020-12-30T14:56:10.907187
2010-02-16T10:37:34
2010-02-16T10:37:34
290,514
3
1
null
null
null
null
UTF-8
C++
false
false
42,030
cpp
/* AutoHotkey Copyright 2003-2008 Chris Mallett ([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. */ #include "stdafx.h" // pre-compiled headers // These includes should probably a superset of those in globaldata.h: #include "hook.h" // For KeyHistoryItem and probably other things. #include "clipboard.h" // For the global clipboard object #include "script.h" // For the global script object and g_ErrorLevel #include "os_version.h" // For the global OS_Version object // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HINSTANCE g_hInstance = NULL; // Set by WinMain(). DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. CRITICAL_SECTION g_CriticalRegExCache; bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. bool g_NoEnv = false; // BOOL vs. bool didn't help performance in spite of the frequent accesses to it. bool g_NoTrayIcon = false; #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_AllowSameLineComments = true; bool g_MainTimerExists = false; bool g_UninterruptibleTimerExists = false; bool g_AutoExecTimerExists = false; bool g_InputTimerExists = false; bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. bool g_AllowInterruption = true; bool g_DeferMessagesForUnderlyingPump = false; int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; bool g_IdleIsPaused = false; int g_MaxHistoryKeys = 40; // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = 10; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. HotCriterionType g_HotCriterion = HOT_NO_CRITERION; char *g_HotWinTitle = ""; // In spite of the above being the primary indicator, char *g_HotWinText = ""; // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; int g_nMessageBoxes = 0; int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType *g_gui[MAX_GUI_WINDOWS] = {NULL}; HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; char g_delimiter = ','; char g_DerefChar = '%'; char g_EscapeChar = '`'; // Hot-string vars (initialized when ResetHook() is first called): char g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; char g_EndChars[HS_MAX_END_CHARS + 1] = "-()[]{}:;'\"/\\,.?!\n \t"; // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. input_type g_input; Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_MAIN : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_MAIN) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; DWORD g_OriginalTimeout; global_struct g, g_default; // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: char g_WorkingDir[MAX_PATH] = ""; char *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; bool g_ForceKeybdHook = false; ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for it's 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say its best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {"", 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {"=", 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {":=", 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {"", 1, 1, 1, {1, 0}} , {"+=", 2, 3, 3, {2, 0}} , {"-=", 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {"*=", 2, 2, 2, {2, 0}} , {"/=", 2, 2, 2, {2, 0}} // This command is never directly parsed, but we need to have it here as a translation // target for the old "repeat" command. This is because that command treats a zero // first-param as an infinite loop. Since that param can be a dereferenced variable, // there's no way to reliably translate each REPEAT command into a LOOP command at // load-time. Thus, we support both types of loops as actual commands that are // handled separately at runtime. , {"Repeat", 0, 1, 1, {1, 0}} // Iteration Count: was mandatory in AutoIt2 but doesn't seem necessary here. , {"Else", 0, 0, 0, NULL} , {"between", 1, 3, 3, NULL}, {"not between", 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {"in", 2, 2, 2, NULL}, {"not in", 2, 2, 2, NULL} , {"contains", 2, 2, 2, NULL}, {"not contains", 2, 2, 2, NULL} // Very similar to "in" and "not in" , {"is", 2, 2, 2, NULL}, {"is not", 2, 2, 2, NULL} , {"", 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {"=", 1, 2, 2, NULL}, {"<>", 1, 2, 2, NULL}, {">", 1, 2, 2, NULL} , {">=", 1, 2, 2, NULL}, {"<", 1, 2, 2, NULL}, {"<=", 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {"IfWinExist", 0, 4, 4, NULL}, {"IfWinNotExist", 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {"IfWinActive", 0, 4, 4, NULL}, {"IfWinNotActive", 0, 4, 4, NULL} // same , {"IfInString", 2, 2, 2, NULL} // String var, search string , {"IfNotInString", 2, 2, 2, NULL} // String var, search string , {"IfExist", 1, 1, 1, NULL} // File or directory. , {"IfNotExist", 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {"IfMsgBox", 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {"MsgBox", 0, 4, 3, {4, 0}} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {"InputBox", 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {"SplashTextOn", 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {"SplashTextOff", 0, 0, 0, NULL} , {"Progress", 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {"SplashImage", 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {"ToolTip", 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {"TrayTip", 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {"Input", 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {"Transform", 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {"StringLeft", 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {"StringRight", 3, 3, 3, {3, 0}} // same , {"StringMid", 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {"StringTrimLeft", 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {"StringTrimRight", 3, 3, 3, {3, 0}} // same , {"StringLower", 2, 3, 3, NULL} // output var, input var, T = Title Case , {"StringUpper", 2, 3, 3, NULL} // output var, input var, T = Title Case , {"StringLen", 2, 2, 2, NULL} // output var, input var , {"StringGetPos", 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {"StringReplace", 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {"StringSplit", 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {"SplitPath", 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {"Sort", 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {"EnvGet", 2, 2, 2 H, NULL} // OutputVar, EnvVar , {"EnvSet", 1, 2, 2, NULL} // EnvVar, Value , {"EnvUpdate", 0, 0, 0, NULL} , {"RunAs", 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {"Run", 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {"RunWait", 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {"URLDownloadToFile", 2, 2, 2, NULL} // URL, save-as-filename , {"GetKeyState", 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {"Send", 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {"SendRaw", 1, 1, 1, NULL} // , {"SendInput", 1, 1, 1, NULL} // , {"SendPlay", 1, 1, 1, NULL} // , {"SendEvent", 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {"ControlSend", 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {"ControlSendRaw", 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {"ControlClick", 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {"ControlMove", 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {"ControlGetPos", 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {"ControlFocus", 0, 5, 5, NULL} // Control, std. 4 window params , {"ControlGetFocus", 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {"ControlSetText", 0, 6, 6, NULL} // Control, new text, std. 4 window params , {"ControlGetText", 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {"Control", 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {"ControlGet", 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {"SendMode", 1, 1, 1, NULL} , {"CoordMode", 1, 2, 2, NULL} // Attribute, screen|relative , {"SetDefaultMouseSpeed", 1, 1, 1, {1, 0}} // speed (numeric) , {"Click", 0, 1, 1, NULL} // Flex-list of options. , {"MouseMove", 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {"MouseClick", 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {"MouseClickDrag", 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {"MouseGetPos", 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {"StatusBarGetText", 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {"StatusBarWait", 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {"ClipWait", 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {"KeyWait", 1, 2, 2, NULL} // KeyName, Options , {"Sleep", 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {"Random", 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {"Goto", 1, 1, 1, NULL} , {"Gosub", 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {"OnExit", 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {"Hotkey", 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {"SetTimer", 1, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {"Critical", 0, 1, 1, NULL} // On|Off , {"Thread", 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {"Return", 0, 1, 1, {1, 0}} , {"Exit", 0, 1, 1, {1, 0}} // ExitCode , {"Loop", 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {"Break", 0, 0, 0, NULL}, {"Continue", 0, 0, 0, NULL} , {"{", 0, 0, 0, NULL}, {"}", 0, 0, 0, NULL} , {"WinActivate", 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {"WinActivateBottom", 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {"WinWait", 0, 5, 5, {3, 0}}, {"WinWaitClose", 0, 5, 5, {3, 0}} , {"WinWaitActive", 0, 5, 5, {3, 0}}, {"WinWaitNotActive", 0, 5, 5, {3, 0}} , {"WinMinimize", 0, 4, 2, NULL}, {"WinMaximize", 0, 4, 2, NULL}, {"WinRestore", 0, 4, 2, NULL} // std. 4 params , {"WinHide", 0, 4, 2, NULL}, {"WinShow", 0, 4, 2, NULL} // std. 4 params , {"WinMinimizeAll", 0, 0, 0, NULL}, {"WinMinimizeAllUndo", 0, 0, 0, NULL} , {"WinClose", 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {"WinKill", 0, 5, 2, {3, 0}} // same as WinClose. , {"WinMove", 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {"WinMenuSelectItem", 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {"Process", 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {"WinSet", 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {"WinSetTitle", 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {"WinGetTitle", 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {"WinGetClass", 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {"WinGet", 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {"WinGetPos", 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {"WinGetText", 1, 5, 5 H, NULL} // Output var, std 4 window params. , {"SysGet", 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {"PostMessage", 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {"SendMessage", 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {"PixelGetColor", 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {"PixelSearch", 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {"ImageSearch", 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {"GroupAdd", 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {"GroupActivate", 1, 2, 2, NULL} , {"GroupDeactivate", 1, 2, 2, NULL} , {"GroupClose", 1, 2, 2, NULL} , {"DriveSpaceFree", 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {"Drive", 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {"DriveGet", 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {"SoundGet", 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {"SoundSet", 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {"SoundGetWaveVolume", 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {"SoundSetWaveVolume", 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {"SoundBeep", 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {"SoundPlay", 1, 2, 2, NULL} // Filename [, wait] , {"FileAppend", 0, 2, 2, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {"FileRead", 2, 2, 2 H, NULL} // Output variable, filename , {"FileReadLine", 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {"FileDelete", 1, 1, 1, NULL} // filename or pattern , {"FileRecycle", 1, 1, 1, NULL} // filename or pattern , {"FileRecycleEmpty", 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {"FileInstall", 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {"FileCopy", 2, 3, 3, {3, 0}} // source, dest, flag , {"FileMove", 2, 3, 3, {3, 0}} // source, dest, flag , {"FileCopyDir", 2, 3, 3, {3, 0}} // source, dest, flag , {"FileMoveDir", 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {"FileCreateDir", 1, 1, 1, NULL} // dir name , {"FileRemoveDir", 1, 2, 1, {2, 0}} // dir name, flag , {"FileGetAttrib", 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {"FileSetAttrib", 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {"FileGetTime", 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {"FileSetTime", 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {"FileGetSize", 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {"FileGetVersion", 1, 2, 2 H, NULL} // OutputVar, Filespec , {"SetWorkingDir", 1, 1, 1, NULL} // New path , {"FileSelectFile", 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {"FileSelectFolder", 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {"FileGetShortcut", 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {"FileCreateShortcut", 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {"IniRead", 4, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) , {"IniWrite", 4, 4, 4, NULL} // Value, Filespec, Section, Key , {"IniDelete", 2, 3, 3, NULL} // Filespec, Section, Key // These require so few parameters due to registry loops, which provide the missing parameter values // automatically. In addition, RegRead can't require more than 1 param since the 2nd param is // an option/obsolete parameter: , {"RegRead", 1, 5, 5 H, NULL} // output var, (ValueType [optional]), RegKey, RegSubkey, ValueName , {"RegWrite", 0, 5, 5, NULL} // ValueType, RegKey, RegSubKey, ValueName, Value (set to blank if omitted?) , {"RegDelete", 0, 3, 3, NULL} // RegKey, RegSubKey, ValueName , {"OutputDebug", 1, 1, 1, NULL} , {"SetKeyDelay", 0, 3, 3, {1, 2, 0}} // Delay in ms (numeric, negative allowed), PressDuration [, Play] , {"SetMouseDelay", 1, 2, 2, {1, 0}} // Delay in ms (numeric, negative allowed) [, Play] , {"SetWinDelay", 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {"SetControlDelay", 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {"SetBatchLines", 1, 1, 1, NULL} // Can be non-numeric, such as 15ms, or a number (to indicate line count). , {"SetTitleMatchMode", 1, 1, 1, NULL} // Allowed values: 1, 2, slow, fast , {"SetFormat", 1, 2, 2, NULL} // Float|Integer, FormatString (for float) or H|D (for int) , {"FormatTime", 1, 3, 3 H, NULL} // OutputVar, YYYYMMDDHH24MISS, Format (format is last to avoid having to escape commas in it). , {"Suspend", 0, 1, 1, NULL} // On/Off/Toggle/Permit/Blank (blank is the same as toggle) , {"Pause", 0, 2, 2, NULL} // On/Off/Toggle/Blank (blank is the same as toggle), AlwaysAffectUnderlying , {"AutoTrim", 1, 1, 1, NULL} // On/Off , {"StringCaseSense", 1, 1, 1, NULL} // On/Off/Locale , {"DetectHiddenWindows", 1, 1, 1, NULL} // On/Off , {"DetectHiddenText", 1, 1, 1, NULL} // On/Off , {"BlockInput", 1, 1, 1, NULL} // On/Off , {"SetNumlockState", 0, 1, 1, NULL} // On/Off/AlwaysOn/AlwaysOff or blank (unspecified) to return to normal. , {"SetScrollLockState", 0, 1, 1, NULL} // same , {"SetCapslockState", 0, 1, 1, NULL} // same , {"SetStoreCapslockMode", 1, 1, 1, NULL} // On/Off , {"KeyHistory", 0, 2, 2, NULL}, {"ListLines", 0, 0, 0, NULL} , {"ListVars", 0, 0, 0, NULL}, {"ListHotkeys", 0, 0, 0, NULL} , {"Edit", 0, 0, 0, NULL} , {"Reload", 0, 0, 0, NULL} , {"Menu", 2, 6, 6, NULL} // tray, add, name, label, options, future use , {"Gui", 1, 4, 4, NULL} // Cmd/Add, ControlType, Options, Text , {"GuiControl", 0, 3, 3 H, NULL} // Sub-cmd (defaults to "contents"), ControlName/ID, Text , {"GuiControlGet", 1, 4, 4, NULL} // OutputVar, Sub-cmd (defaults to "contents"), ControlName/ID (defaults to control assoc. with OutputVar), Text/FutureUse , {"ExitApp", 0, 1, 1, NULL} // Optional exit-code , {"Shutdown", 1, 1, 1, {1, 0}} // Seems best to make the first param (the flag/code) mandatory. }; // Below is the most maintainable way to determine the actual count? // Due to C++ lang. restrictions, can't easily make this a const because constants // automatically get static (internal) linkage, thus such a var could never be // used outside this module: int g_ActionCount = sizeof(g_act) / sizeof(Action); Action g_old_act[] = { {"", 0, 0, 0, NULL} // OLD_INVALID. , {"SetEnv", 1, 2, 2, NULL} , {"EnvAdd", 2, 3, 3, {2, 0}}, {"EnvSub", 1, 3, 3, {2, 0}} // EnvSub (but not Add) allow 2nd to be blank due to 3rd param. , {"EnvMult", 2, 2, 2, {2, 0}}, {"EnvDiv", 2, 2, 2, {2, 0}} , {"IfEqual", 1, 2, 2, NULL}, {"IfNotEqual", 1, 2, 2, NULL} , {"IfGreater", 1, 2, 2, NULL}, {"IfGreaterOrEqual", 1, 2, 2, NULL} , {"IfLess", 1, 2, 2, NULL}, {"IfLessOrEqual", 1, 2, 2, NULL} , {"LeftClick", 2, 2, 2, {1, 2, 0}}, {"RightClick", 2, 2, 2, {1, 2, 0}} , {"LeftClickDrag", 4, 4, 4, {1, 2, 3, 4, 0}}, {"RightClickDrag", 4, 4, 4, {1, 2, 3, 4, 0}} , {"HideAutoItWin", 1, 1, 1, NULL} // Allow zero params, unlike AutoIt. These params should match those for REPEAT in the above array: , {"Repeat", 0, 1, 1, {1, 0}}, {"EndRepeat", 0, 0, 0, NULL} , {"WinGetActiveTitle", 1, 1, 1, NULL} // <Title Var> , {"WinGetActiveStats", 5, 5, 5, NULL} // <Title Var>, <Width Var>, <Height Var>, <Xpos Var>, <Ypos Var> }; int g_OldActionCount = sizeof(g_old_act) / sizeof(Action); key_to_vk_type g_key_to_vk[] = { {"Numpad0", VK_NUMPAD0} , {"Numpad1", VK_NUMPAD1} , {"Numpad2", VK_NUMPAD2} , {"Numpad3", VK_NUMPAD3} , {"Numpad4", VK_NUMPAD4} , {"Numpad5", VK_NUMPAD5} , {"Numpad6", VK_NUMPAD6} , {"Numpad7", VK_NUMPAD7} , {"Numpad8", VK_NUMPAD8} , {"Numpad9", VK_NUMPAD9} , {"NumpadMult", VK_MULTIPLY} , {"NumpadDiv", VK_DIVIDE} , {"NumpadAdd", VK_ADD} , {"NumpadSub", VK_SUBTRACT} // , {"NumpadEnter", VK_RETURN} // Must do this one via scan code, see below for explanation. , {"NumpadDot", VK_DECIMAL} , {"Numlock", VK_NUMLOCK} , {"ScrollLock", VK_SCROLL} , {"CapsLock", VK_CAPITAL} , {"Escape", VK_ESCAPE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"Esc", VK_ESCAPE} , {"Tab", VK_TAB} , {"Space", VK_SPACE} , {"Backspace", VK_BACK} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"BS", VK_BACK} // These keys each have a counterpart on the number pad with the same VK. Use the VK for these, // since they are probably more likely to be assigned to hotkeys (thus minimizing the use of the // keyboard hook, and use the scan code (SC) for their counterparts. UPDATE: To support handling // these keys with the hook (i.e. the sc_takes_precedence flag in the hook), do them by scan code // instead. This allows Numpad keys such as Numpad7 to be differentiated from NumpadHome, which // would otherwise be impossible since both of them share the same scan code (i.e. if the // sc_takes_precedence flag is set for the scan code of NumpadHome, that will effectively prevent // the hook from telling the difference between it and Numpad7 since the hook is currently set // to handle an incoming key by either vk or sc, but not both. // Even though ENTER is probably less likely to be assigned than NumpadEnter, must have ENTER as // the primary vk because otherwise, if the user configures only naked-NumPadEnter to do something, // RegisterHotkey() would register that vk and ENTER would also be configured to do the same thing. , {"Enter", VK_RETURN} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"Return", VK_RETURN} , {"NumpadDel", VK_DELETE} , {"NumpadIns", VK_INSERT} , {"NumpadClear", VK_CLEAR} // same physical key as Numpad5 on most keyboards? , {"NumpadUp", VK_UP} , {"NumpadDown", VK_DOWN} , {"NumpadLeft", VK_LEFT} , {"NumpadRight", VK_RIGHT} , {"NumpadHome", VK_HOME} , {"NumpadEnd", VK_END} , {"NumpadPgUp", VK_PRIOR} , {"NumpadPgDn", VK_NEXT} , {"PrintScreen", VK_SNAPSHOT} , {"CtrlBreak", VK_CANCEL} // Might want to verify this, and whether it has any peculiarities. , {"Pause", VK_PAUSE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"Break", VK_PAUSE} // Not really meaningful, but kept for as a synonym of Pause for backward compatibility. See CtrlBreak. , {"Help", VK_HELP} // VK_HELP is probably not the extended HELP key. Not sure what this one is. , {"Sleep", VK_SLEEP} , {"AppsKey", VK_APPS} // UPDATE: For the NT/2k/XP version, now doing these by VK since it's likely to be // more compatible with non-standard or non-English keyboards: , {"LControl", VK_LCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"RControl", VK_RCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"LCtrl", VK_LCONTROL} // Abbreviated versions of the above. , {"RCtrl", VK_RCONTROL} // , {"LShift", VK_LSHIFT} , {"RShift", VK_RSHIFT} , {"LAlt", VK_LMENU} , {"RAlt", VK_RMENU} // These two are always left/right centric and I think their vk's are always supported by the various // Windows API calls, unlike VK_RSHIFT, etc. (which are seldom supported): , {"LWin", VK_LWIN} , {"RWin", VK_RWIN} // The left/right versions of these are handled elsewhere since their virtual keys aren't fully API-supported: , {"Control", VK_CONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {"Ctrl", VK_CONTROL} // An alternate for convenience. , {"Alt", VK_MENU} , {"Shift", VK_SHIFT} /* These were used to confirm the fact that you can't use RegisterHotkey() on VK_LSHIFT, even if the shift modifier is specified along with it: , {"LShift", VK_LSHIFT} , {"RShift", VK_RSHIFT} */ , {"F1", VK_F1} , {"F2", VK_F2} , {"F3", VK_F3} , {"F4", VK_F4} , {"F5", VK_F5} , {"F6", VK_F6} , {"F7", VK_F7} , {"F8", VK_F8} , {"F9", VK_F9} , {"F10", VK_F10} , {"F11", VK_F11} , {"F12", VK_F12} , {"F13", VK_F13} , {"F14", VK_F14} , {"F15", VK_F15} , {"F16", VK_F16} , {"F17", VK_F17} , {"F18", VK_F18} , {"F19", VK_F19} , {"F20", VK_F20} , {"F21", VK_F21} , {"F22", VK_F22} , {"F23", VK_F23} , {"F24", VK_F24} // Mouse buttons: , {"LButton", VK_LBUTTON} , {"RButton", VK_RBUTTON} , {"MButton", VK_MBUTTON} // Supported in only in Win2k and beyond: , {"XButton1", VK_XBUTTON1} , {"XButton2", VK_XBUTTON2} // Custom/fake VKs for use by the mouse hook (supported only in WinNT SP3 and beyond?): , {"WheelDown", VK_WHEEL_DOWN} , {"WheelUp", VK_WHEEL_UP} , {"Browser_Back", VK_BROWSER_BACK} , {"Browser_Forward", VK_BROWSER_FORWARD} , {"Browser_Refresh", VK_BROWSER_REFRESH} , {"Browser_Stop", VK_BROWSER_STOP} , {"Browser_Search", VK_BROWSER_SEARCH} , {"Browser_Favorites", VK_BROWSER_FAVORITES} , {"Browser_Home", VK_BROWSER_HOME} , {"Volume_Mute", VK_VOLUME_MUTE} , {"Volume_Down", VK_VOLUME_DOWN} , {"Volume_Up", VK_VOLUME_UP} , {"Media_Next", VK_MEDIA_NEXT_TRACK} , {"Media_Prev", VK_MEDIA_PREV_TRACK} , {"Media_Stop", VK_MEDIA_STOP} , {"Media_Play_Pause", VK_MEDIA_PLAY_PAUSE} , {"Launch_Mail", VK_LAUNCH_MAIL} , {"Launch_Media", VK_LAUNCH_MEDIA_SELECT} , {"Launch_App1", VK_LAUNCH_APP1} , {"Launch_App2", VK_LAUNCH_APP2} // Probably safest to terminate it this way, with a flag value. (plus this makes it a little easier // to code some loops, maybe). Can also calculate how many elements are in the array using sizeof(array) // divided by sizeof(element). UPDATE: Decided not to do this in case ever decide to sort this array; don't // want to rely on the fact that this will wind up in the right position after the sort (even though it // should): //, {"", 0} }; key_to_sc_type g_key_to_sc[] = // Even though ENTER is probably less likely to be assigned than NumpadEnter, must have ENTER as // the primary vk because otherwise, if the user configures only naked-NumPadEnter to do something, // RegisterHotkey() would register that vk and ENTER would also be configured to do the same thing. { {"NumpadEnter", SC_NUMPADENTER} , {"Delete", SC_DELETE} , {"Del", SC_DELETE} , {"Insert", SC_INSERT} , {"Ins", SC_INSERT} // , {"Clear", SC_CLEAR} // Seems unnecessary because there is no counterpart to the Numpad5 clear key? , {"Up", SC_UP} , {"Down", SC_DOWN} , {"Left", SC_LEFT} , {"Right", SC_RIGHT} , {"Home", SC_HOME} , {"End", SC_END} , {"PgUp", SC_PGUP} , {"PgDn", SC_PGDN} // If user specified left or right, must use scan code to distinguish *both* halves of the pair since // each half has same vk *and* since their generic counterparts (e.g. CONTROL vs. L/RCONTROL) are // already handled by vk. Note: RWIN and LWIN don't need to be handled here because they each have // their own virtual keys. // UPDATE: For the NT/2k/XP version, now doing these by VK since it's likely to be // more compatible with non-standard or non-English keyboards: /* , {"LControl", SC_LCONTROL} , {"RControl", SC_RCONTROL} , {"LShift", SC_LSHIFT} , {"RShift", SC_RSHIFT} , {"LAlt", SC_LALT} , {"RAlt", SC_RALT} */ }; // Can calc the counts only after the arrays are initialized above: int g_key_to_vk_count = sizeof(g_key_to_vk) / sizeof(key_to_vk_type); int g_key_to_sc_count = sizeof(g_key_to_sc) / sizeof(key_to_sc_type); KeyHistoryItem *g_KeyHistory = NULL; // Array is allocated during startup. int g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE bool g_KeyHistoryToFile = false; #endif // These must be global also, since both the keyboard and mouse hook functions, // in addition to KeyEvent() when it's logging keys with only the mouse hook installed, // MUST refer to the same variables. Otherwise, the elapsed time between keyboard and // and mouse events will be wrong: DWORD g_HistoryTickNow = 0; DWORD g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. HWND g_HistoryHwndPrev = NULL; // Also hook related: DWORD g_TimeLastInputPhysical = GetTickCount(); HKL g_HKL = GetKeyboardLayout(0); // ahkx
[ [ [ 1, 765 ] ] ]
2c62ae90891531ec593f8978445e009b1d7cd90c
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
/tags/last_qt3_support_release/avcut/ttaudiocut.h
739b5c251ffd46dc96ca0bc8b1accc9d0bee2ad7
[]
no_license
BackupTheBerlios/ttcut-svn
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
958032e74e8bb144a96b6eb7e1d63bc8ae762096
refs/heads/master
2020-04-22T12:08:57.640316
2009-02-08T16:14:00
2009-02-08T16:14:00
40,747,642
0
0
null
null
null
null
UTF-8
C++
false
false
4,917
h
/*----------------------------------------------------------------------------*/ /* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */ /*----------------------------------------------------------------------------*/ /* PROJEKT : TTCUT 2005 */ /* FILE : ttaudiocut.h */ /*----------------------------------------------------------------------------*/ /* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/23/2005 */ /* MODIFIED: b. altendorf DATE: 03/01/2005 */ /* MODIFIED: b. altendorf DATE: 03/31/2005 */ /* MODIFIED: DATE: */ /*----------------------------------------------------------------------------*/ // ---------------------------------------------------------------------------- // TAUDIOSCHNITT // ---------------------------------------------------------------------------- /*----------------------------------------------------------------------------*/ /* Die Klasse TAudioSchnitt entstammt dem Projekt "MPEG2Schnitt" von Martin */ /* Dienert und wurde von mir nach C++ portiert und an mein Projekt angepasst. */ /* Copyright (C) 2003 Martin Dienert */ /* Homepage: http:www.mdienert.de/mpeg2schnitt/ */ /* E-Mail: [email protected] */ /* Martin Dienert ist nicht verantwortlich fuer diese Quellen und leistet */ /* diesbezueglich auch keinen Support. */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* 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. */ /*----------------------------------------------------------------------------*/ #ifndef TTAUDIOCUT_H #define TTAUDIOCUT_H #include <qstring.h> #include "../gui/ttcut.h" #include "../gui/ttprogressbar.h" #include "../compat/theader.h" #include "../compat/tmpegaudio.h" #include "../compat/tdateipuffer.h" #include "../compat/ttcutposition.h" //bool VideoSchnittAnhalten; // -------------------------------------------------------------------------------- // TAudioschnitt: Class // -------------------------------------------------------------------------------- class TAudioSchnitt { public: TAudioSchnitt( TTProgressBar* pBar = NULL ); ~TAudioSchnitt(); void setProgressBar( TTProgressBar* pbar ); void IndexDateiSpeichern(QString Name, TListe* Liste); void ZielDateiOeffnen(QString ZielDatei); void QuellDateiOeffnen(TSchnittPunkt* SchnittPunkt); void QuellDateiSchliessen(); void ZielDateiSchliessen(); int Schneiden(TTVideoCutList* SchnittListe); void KopiereSegment(long AnfangsIndex, long EndIndex); void createIndexFile( bool index ); private: TTProgressBar* progressBar; QString DateiName; //STRING QString ZielDateiName; //STRING QString indexFileName; TDateiPuffer* DateiStream; //TDateiPuffer TDateiPuffer* SpeicherStream; //TDateiPuffer TListe* Liste; //TListe TListe* AudioListe; //TListe TListe* NeueListe; //TListe bool Anhalten; //Boolean bool IndexDatei_erstellen; //Boolean QString TextString; //STRING TAudioHeader* AudioHeader; //TAudioHeader int Versatz; //Integer }; #endif //TTAUDIOCUT_H
[ "tritime@7763a927-590e-0410-8f7f-dbc853b76eaa" ]
[ [ [ 1, 102 ] ] ]
e5813490c325e775d334e170629642da4ef02a29
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/sdk/include/sdk/StyleInfo.h
dc5d164257cf0141133db932c40c38f2b53f8214
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,723
h
/* * This file is part of FBIde project * * FBIde 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 3 of the License, or * (at your option) any later version. * * FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>. * * Author: Albert Varaksin <[email protected]> * Copyright (C) The FBIde development team */ #ifndef EDITORSTYLEINFO_H_INCLUDED #define EDITORSTYLEINFO_H_INCLUDED #define STYLE_DEFAULT_FONT_SIZE 10 #define STYLE_DEFAULT_FG _T("black") #define STYLE_DEFAULT_BG _T("white") #define STYLE_DEFAULT_FONT _T("Courier New") namespace fb { /** * Contains info about the styling * * @todo add opacity and width */ struct DLLIMPORT CStyleInfo { bool isOk; bool bold; bool italic; bool underlined; int size; int width; int opacity; wxString font; wxColor fg; wxColor bg; wxColor outline; CStyleInfo () : isOk(false), bold(false), italic(false), underlined(false), size(STYLE_DEFAULT_FONT_SIZE), width(0), opacity(0), font(STYLE_DEFAULT_FONT) {} /** * Get style info as string */ wxString AsString () const { wxString tmp; // font-weight tmp << _T("font-weight : "); if (bold) tmp << _T("bold"); else tmp << _T("normal"); tmp << _T(";\n"); // font-style tmp << _T("font-style : "); if (italic) tmp << _T("italic"); else tmp << _T("normal"); tmp << _T(";\n"); // text decoration tmp << _T("text-decoration : "); if (underlined) tmp << _T("underline"); else tmp << _T("none"); tmp << _T(";\n"); // font size tmp << _T("font-size : "); tmp << size << _T("px"); tmp << _T(";\n"); // width tmp << _T("width : "); tmp << width << _T("px"); tmp << _T(";\n"); // fg tmp << _T("color : "); tmp << fg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX); tmp << _T(";\n"); // bg tmp << _T("background-color : "); tmp << bg.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX); tmp << _T(";\n"); // border tmp << _T("outline-color : "); tmp << outline.GetAsString(wxC2S_NAME | wxC2S_HTML_SYNTAX); tmp << _T(";\n"); // opacity tmp << _T("opacity : "); tmp << opacity; tmp << _T(";"); return tmp; } }; /** * Styles manager */ class DLLIMPORT CStyleParser { public : // construct the style info object CStyleParser (const wxString & filename); // Parse the file void LoadFile (const wxString & filename); // Add CSS rule void SetCssRule ( const wxString & selector, const wxString & rule, const wxArrayString & values, const wxString & inheritFrom = _T(".default") ); // Add CSS rule // Same as above but only one value void SetCssRule ( const wxString & selector, const wxString & rule, const wxString & value, const wxString & inheritFrom = _T(".default") ); // check if path exists bool PathExists (const wxString & selector); // Get styles for the selector CStyleInfo GetStyle (const wxString & selector, const wxString & inherit = _T(".default")); private : // private data implementation "pimpl" struct CData; std::auto_ptr<CData> m_data; }; }; #endif // EDITORSTYLEINFO_H_INCLUDED
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 164 ] ] ]
64d0c211a00488512eda14ce9c8d8272607104df
05869e5d7a32845b306353bdf45d2eab70d5eddc
/soft/application/CoolSimulator/coolrgbquad.h
1513346653fcc18f57f6ee5acb024ed42301cb9f
[]
no_license
shenfahsu/sc-fix
beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a
ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd
refs/heads/master
2020-07-14T16:13:47.424654
2011-07-22T16:46:45
2011-07-22T16:46:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
891
h
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. ///////////////////////////////////////////////////////////////////////////// // CCoolRGBQuad wrapper class class CCoolRGBQuad : public COleDispatchDriver { public: CCoolRGBQuad() {} // Calls COleDispatchDriver default constructor CCoolRGBQuad(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CCoolRGBQuad(const CCoolRGBQuad& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: short GetRgbBlue(); void SetRgbBlue(short); short GetRgbGreen(); void SetRgbGreen(short); short GetRgbRed(); void SetRgbRed(short); short GetRgbReserved(); void SetRgbReserved(short); // Operations public: };
[ "windyin@2490691b-6763-96f4-2dba-14a298306784" ]
[ [ [ 1, 29 ] ] ]
616950e232721771890a8b7a69a7959e2c51d97c
fd518ed0226c6a044d5e168ab50a0e4a37f8efa9
/iAuthor/AmpSdk/wmvgen/src/Common/seekutil.cpp
2344f09afd6794c5f5c0bc23744a3db7925fbe0d
[]
no_license
shilinxu/iprojects
e2e2394df9882afaacfb9852332f83cbef6a8c93
79bc8e45596577948c45cf2afcff331bc71ab026
refs/heads/master
2020-05-17T19:15:43.197685
2010-04-02T15:58:11
2010-04-02T15:58:11
41,959,151
0
0
null
null
null
null
UTF-8
C++
false
false
4,533
cpp
//------------------------------------------------------------------------------ // File: SeekUtil.cpp // // Desc: DirectShow sample code - utility functions. // // Copyright (c) 2000-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include "stdafx.h" #include <dshow.h> // // Constants // const int TICKLEN=100, TIMERID=55; // // Global data // static REFERENCE_TIME g_rtTotalTime=0; static UINT_PTR g_wTimerID=0; static HWND g_hwnd=0; HRESULT ConfigureSeekbar(IMediaSeeking *pMS, CSliderCtrl Seekbar, CStatic& strPosition); void StartSeekTimer(); void StopSeekTimer(); void UpdatePosition(IMediaSeeking *pMS, REFERENCE_TIME rtNow, CStatic& strPosition); void ReadMediaPosition(IMediaSeeking *pMS, CSliderCtrl& Seekbar, CStatic& strPosition); void HandleTrackbar(IMediaControl *pMC, IMediaSeeking *pMS, CSliderCtrl& Seekbar, CStatic& strPosition, WPARAM wReq); HRESULT ConfigureSeekbar(IMediaSeeking *pMS, CSliderCtrl Seekbar, CStatic& strPosition, HWND hwndOwner) { HRESULT hr; // Disable seekbar for new file and reset tracker/position label Seekbar.SetPos(0); Seekbar.EnableWindow(FALSE); g_rtTotalTime=0; strPosition.SetWindowText(_T("Position: 00m:00s\0")); DWORD dwSeekCaps = AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanGetDuration; // Can we seek this file? If so, enable trackbar. if (pMS && (S_OK == pMS->CheckCapabilities(&dwSeekCaps))) { hr = pMS->GetDuration(&g_rtTotalTime); Seekbar.EnableWindow(TRUE); } g_hwnd = hwndOwner; return hr; } void StartSeekTimer() { // Cancel any pending timer event StopSeekTimer(); // Create a new timer g_wTimerID = SetTimer(g_hwnd, TIMERID, TICKLEN, NULL); } void StopSeekTimer() { // Cancel the timer if(g_wTimerID) { KillTimer(g_hwnd, g_wTimerID); g_wTimerID = 0; } } void ReadMediaPosition(IMediaSeeking *pMS, CSliderCtrl& Seekbar, CStatic& strPosition) { HRESULT hr; REFERENCE_TIME rtNow; // Read the current stream position hr = pMS->GetCurrentPosition(&rtNow); if (FAILED(hr)) return; // Convert position into a percentage value and update slider position long lTick = (long)((rtNow * 100) / g_rtTotalTime); Seekbar.SetPos(lTick); // Update the 'current position' string on the main dialog UpdatePosition(pMS, rtNow, strPosition); } void UpdatePosition(IMediaSeeking *pMS, REFERENCE_TIME rtNow, CStatic& strPosition) { HRESULT hr; // If no reference time was passed in, read the current position if (rtNow == 0) { // Read the current stream position hr = pMS->GetCurrentPosition(&rtNow); if (FAILED(hr)) return; } // Convert the LONGLONG duration into human-readable format unsigned long nTotalMS = (unsigned long) rtNow / 10000; // 100ns -> ms int nSeconds = nTotalMS / 1000; int nMinutes = nSeconds / 60; nSeconds %= 60; // Update the display TCHAR szPosition[24]; wsprintf(szPosition, _T("Position: %02dm:%02ds\0"), nMinutes, nSeconds); strPosition.SetWindowText(szPosition); } void HandleTrackbar(IMediaControl *pMC, IMediaSeeking *pMS, CSliderCtrl& Seekbar, CStatic& strPosition, WPARAM wReq) { HRESULT hr; static OAFilterState state; static BOOL bStartOfScroll = TRUE; // If the file is not seekable, the trackbar is disabled. DWORD dwPosition = Seekbar.GetPos(); // Pause when the scroll action begins. if (bStartOfScroll) { hr = pMC->GetState(10, &state); bStartOfScroll = FALSE; hr = pMC->Pause(); } // Update the position continuously. REFERENCE_TIME rtNew = (g_rtTotalTime * dwPosition) / 100; hr = pMS->SetPositions(&rtNew, AM_SEEKING_AbsolutePositioning, NULL, AM_SEEKING_NoPositioning); // Restore the state at the end. if (wReq == TB_ENDTRACK) { if (state == State_Stopped) hr = pMC->Stop(); else if (state == State_Running) hr = pMC->Run(); bStartOfScroll = TRUE; } // Update the 'current position' string on the main dialog. UpdatePosition(pMS, rtNew, strPosition); }
[ [ [ 1, 162 ] ] ]
4700b7b3b2ee0183b72be4fe8b6057cae63ff8bd
f4e20d6ad5d3a6ef3406d66d3eb4bb1fdc6c1088
/CarMP_OpenGL/OGLTexture.cpp
21c53966819304504deecb11b22af3bc3657ff49
[]
no_license
WildGenie/carmp
c19cfbac3dda7dfcdc6ca7de8c0fb274e07efe5b
7d1e41acabbafa87298de745563a16b9ce7cd9b0
refs/heads/master
2021-01-12T07:31:33.858240
2011-10-05T23:31:31
2011-10-05T23:31:31
null
0
0
null
null
null
null
MacCentralEurope
C++
false
false
4,529
cpp
#include "OGLTexture.h" OGLTexture::OGLTexture(const char* pByteArray, int pStride) { this->LoadImageFromByteArray(pByteArray, pStride); } OGLTexture::OGLTexture(const char* pPath) { this->LoadImageFromPath(pPath); } OGLTexture::~OGLTexture() { // KILL IT! } void OGLTexture::SetDimensions(OGL_RECT pRect) { if(currentRect.x != pRect.x || currentRect.y != pRect.y || currentRect.width != pRect.width || currentRect.height != pRect.height) { currentRect = pRect; m_sprite.SetPosition(pRect.x, pRect.y); m_sprite.Resize(pRect.width, pRect.height); } } void OGLTexture::InternalDraw(sf::RenderWindow* renderer) { renderer->Draw(m_sprite); return; float x2 = currentRect.x + currentRect.width; float y2 = currentRect.y + currentRect.height; //glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); //glUniform1i(m_textureId, 0); glBegin(GL_QUADS); /* glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f, 0.0f);*/ /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, (int)GL_MODULATE); */ glTexCoord2f(0.0f, 0.0f); glVertex2f(currentRect.x, currentRect.y); glTexCoord2f(0.0f, 1.0f); glVertex2f(currentRect.x, y2); glTexCoord2f(1.0f, 1.0f); glVertex2f(x2, y2); glTexCoord2f(1.0f, 0.0f); glVertex2f(x2, currentRect.y); glEnd(); /*glGenTextures(1, texture); glBindTexture(GL_TEXTURE_2D, texture[0]); */ } bool OGLTexture::LoadImageFromByteArray(const char* byteArray, int stride) { return true; } bool OGLTexture::LoadImageFromPath(const char* filename) { char tempCopy[600]; strcpy(tempCopy, filename); if(!m_texture.LoadFromFile(filename)) return false; m_sprite.SetTexture(m_texture); return true; /*glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // m_textureId = ilutOglLoadImage(filename); //m_textureId = ilutGLLoadImage(tempCopy); /* We want all images to be loaded in a consistent manner */ //ilEnable(IL_ORIGIN_SET); ///* In the next section, we load one image */ //ilGenImages(1, & handle); //ilBindImage(handle); //ILboolean loaded = ilLoadImage(filename); //if (loaded == IL_FALSE) //return -1; /* error encountered during loading */ ///* Letรญs spy on it a little bit */ //width = ilGetInteger(IL_IMAGE_WIDTH); // getting image width //height = ilGetInteger(IL_IMAGE_HEIGHT); // and height // ///* how much memory will we need? */ //int memory_needed = width * height * 3 * sizeof(unsigned char); // ///* We multiply by 3 here because we want 3 components per pixel */ //ILubyte * data = (ILubyte *)malloc(memory_needed); // ///* finally get the image data */ //ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, IL_UNSIGNED_BYTE, data); // /////* And maybe we want to save that all... */ ////ilSetPixels(0, 0, 0, w, h, 1, IL_RGB, IL_UNSIGNED_BYTE, data); /////* and dump them to the disc... */ ////ilSaveImage("our_result.png"); ///* Finally, clean the mess! */ // //glGenTextures(1, &m_textureId); // glBindTexture(GL_TEXTURE_2D, m_textureId); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // //GLuint ilutOglBindTexImage(); ////glTexImage2D( //// GL_TEXTURE_2D, 0, /* target, level of detail */ //// GL_RGB8, /* internal format */ //// width, height, 0, /* width, height, border */ //// GL_BGR, GL_UNSIGNED_BYTE, /* external format, type */ //// data /* pixels */ //// ); //GLenum err = glGetError(); //if(err != GL_NO_ERROR) //{ // //} // //Utils::ShowInfoLog( //ilDeleteImages(1, & handle); //free(data); data = NULL; return 0; }
[ "[email protected]@d4bd84e2-f980-fb58-ec8a-1c4e3f86fd2c" ]
[ [ [ 1, 153 ] ] ]
cba0ada66cfe17b3bc539fe0c26c4f7815455026
83818f21703024dc3183b9b3ffd8cc6013fe3b9f
/Src_GPU/loadprogram.cpp
f236928852d1b6ad3400c1c566248f2c6db61e64
[]
no_license
baupetit/FireMonkeys
5a68e9cfb6ffa108ce60318fb6095ec18f25d2e6
b7cb72bf2101a5aeed2895e3f8245f858fa3db17
refs/heads/master
2020-05-03T05:21:40.963418
2010-06-15T09:55:01
2010-06-15T09:55:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,101
cpp
/*************************************************************************** * Copyright (C) 2007 Antony Martin * * * * 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., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <GL/glew.h> #include <GL/glut.h> #include "loadprogram.h" /* charge le code source d'un shader */ static char* LoadSource(const char *filename) { char *src = NULL; /* code source de notre shader */ FILE *fp = NULL; /* fichier */ long size; /* taille du fichier */ long i; /* compteur */ /* on ouvre le fichier */ fp = fopen(filename, "r"); /* on verifie si l'ouverture a echoue */ if(fp == NULL) { fprintf(stderr, "impossible d'ouvrir le fichier '%s'\n", filename); return NULL; } /* on recupere la longueur du fichier */ fseek(fp, 0, SEEK_END); size = ftell(fp); /* on se replace au debut du fichier */ rewind(fp); /* on alloue de la memoire pour y placer notre code source */ src = (char*)malloc(size+1); /* +1 pour le caractere de fin de chaine '\0' */ if(src == NULL) { fclose(fp); fprintf(stderr, "erreur d'allocation de memoire!\n"); return NULL; } /* lecture du fichier */ for(i=0; i<size; i++) src[i] = fgetc(fp); /* on place le dernier caractere a '\0' */ src[size] = '\0'; fclose(fp); return src; } GLuint LoadProgram(const char *vsname, const char *psname) { GLuint prog = 0; GLuint vs = 0, ps = 0; GLint link_status = GL_TRUE; GLint logsize = 0; char *log = NULL; /* verification des arguments */ if(vsname == NULL && psname == NULL) { fprintf(stderr, "creation d'un program demande, mais aucuns " "noms de fichiers source envoye, arret.\n"); return 0; } /* chargement des shaders */ if(vsname != NULL) { vs = LoadShader(GL_VERTEX_SHADER, vsname); if(vs == 0) return 0; } if(psname != NULL) { ps = LoadShader(GL_FRAGMENT_SHADER, psname); if(ps == 0) { if(glIsShader(vs)) glDeleteShader(vs); return 0; } } /* creation du program */ prog = glCreateProgram(); /* on envoie nos shaders a notre program */ if(vs) glAttachShader(prog, vs); if(ps) glAttachShader(prog, ps); /* on lie le tout */ glLinkProgram(prog); /* on verifie que tout s'est bien passe */ glGetProgramiv(prog, GL_LINK_STATUS, &link_status); if(link_status != GL_TRUE) { glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logsize); log = (char*)malloc(logsize + 1); if(log == NULL) { glDeleteProgram(prog); glDeleteShader(vs); glDeleteShader(ps); fprintf(stderr, "impossible d'allouer de la memoire!\n"); return 0; } memset(log, '\0', logsize + 1); glGetProgramInfoLog(prog, logsize, &logsize, log); fprintf(stderr, "impossible de lier le program :\n%s", log); free(log); glDeleteProgram(prog); glDeleteShader(vs); glDeleteShader(ps); return 0; } /* les shaders sont dans le program maintenant, on en a plus besoin */ glDeleteShader(vs); glDeleteShader(ps); return prog; } GLuint LoadShader(GLenum type, const char *filename) { GLuint shader = 0; GLsizei logsize = 0; GLint compile_status = GL_TRUE; char *log = NULL; char *src = NULL; /* creation d'un shader de sommet */ shader = glCreateShader(type); if(shader == 0) { fprintf(stderr, "impossible de creer le shader\n"); return 0; } /* chargement du code source */ src = LoadSource(filename); if(src == NULL) { /* theoriquement, la fonction LoadSource a deja affiche un message d'erreur, nous nous contenterons de supprimer notre shader et de retourner 0 */ glDeleteShader(shader); return 0; } /* assignation du code source */ glShaderSource(shader, 1, (const GLchar**)&src, NULL); /* compilation du shader */ glCompileShader(shader); /* liberation de la memoire du code source */ free(src); src = NULL; /* verification du succes de la compilation */ glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status); if(compile_status != GL_TRUE) { /* erreur a la compilation recuperation du log d'erreur */ /* on recupere la taille du message d'erreur */ glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logsize); /* on alloue un esapce memoire dans lequel OpenGL ecrira le message */ log = (char*)malloc(logsize + 1); if(log == NULL) { fprintf(stderr, "impossible d'allouer de la memoire!\n"); return 0; } /* initialisation du contenu */ memset(log, '\0', logsize + 1); glGetShaderInfoLog(shader, logsize, &logsize, log); fprintf(stderr, "impossible de compiler le shader '%s' :\n%s", filename, log); /* ne pas oublier de liberer la memoire et notre shader */ free(log); glDeleteShader(shader); return 0; } return shader; }
[ "iron@iron-laptop.(none)" ]
[ [ [ 1, 248 ] ] ]
bda470d82c5267ba16c608fadc2cfb01187b8434
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/26042005/fusionutil/FusionUtil.cpp
fad7e73859df89460720479c67f4f43b19070449
[]
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
630
cpp
#include <Fusion.h> #include <FusionUtil.h> #include <virtualfs/VFSHandle_ZIP.h> /********************************** * Fusion Utility functions **********************************/ void UnzipFusion(char *arc) { fusion->InitSystem(Fusion::VFS,CreateVFS); fusion->vfs->LoadPlugin(CreateZIP,NULL,NULL); VFSHandle *h = fusion->vfs->OpenLocation(arc); h->Copyfile("*.*", "file://system"); fusion->vfs->Close(h); } void CleanupFusion(void) { fusion->UnloadModules(); //fusion->vfs->UnloadModules(); VFSHandle *h = fusion->vfs->OpenLocation("file://"); h->DeleteDir("system",true); DestroyVFS(); }
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 26 ] ] ]
0dcd479e3efa698ed169511bd0b0ffa4a84c24bc
d64ed1f7018aac768ddbd04c5b465c860a6e75fa
/pubsub.cpp
27d5f43983d299844a4f81f5367cb1206254f164
[]
no_license
roc2/archive-freepcb-codeproject
68aac46d19ac27f9b726ea7246cfc3a4190a0136
cbd96cd2dc81a86e1df57b86ce540cf7c120c282
refs/heads/master
2020-03-25T00:04:22.712387
2009-06-13T04:36:32
2009-06-13T04:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
#include "stdafx.h" #include "pubsub.h" CPublisher::CPublisher() { m_curSub = &m_LIST_Sub; } CPublisher::~CPublisher() { for( m_curSub = m_LIST_Sub.next; m_curSub != &m_LIST_Sub; m_curSub = m_curSub->next ) { _Remove(*static_cast<CSubscriber *>( m_curSub )); } } void CPublisher::Update() const { for( m_curSub = m_LIST_Sub.next; m_curSub != &m_LIST_Sub; m_curSub = m_curSub->next ) { _Update(static_cast<CSubscriber *>( m_curSub )); } } void CPublisher::_Add(CSubscriber &sub) { m_LIST_Sub.insert_after(&sub); _Update(&sub); } void CPublisher::_Remove(CSubscriber &sub) { // Update the publisher's update iterator if necessary if (&sub == m_curSub) { m_curSub = m_curSub->prev; } sub.DLinkList_remove(); }
[ "jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314" ]
[ [ [ 1, 40 ] ] ]
532e11cdb3f3c841b9ed64ae9f42b326df347daa
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qcursor.h
1bc11241908c54d7444f9ab0b2cefe599605913d
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,717
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QCURSOR_H #define QCURSOR_H #include <QtCore/qpoint.h> #include <QtGui/qwindowdefs.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QVariant; /* ### The fake cursor has to go first with old qdoc. */ #ifdef QT_NO_CURSOR class Q_GUI_EXPORT QCursor { public: static QPoint pos(); static void setPos(int x, int y); inline static void setPos(const QPoint &p) { setPos(p.x(), p.y()); } private: QCursor(); }; #endif // QT_NO_CURSOR #ifndef QT_NO_CURSOR struct QCursorData; class QBitmap; class QPixmap; #if defined(Q_WS_MAC) void qt_mac_set_cursor(const QCursor *c, const QPoint &p); #endif class Q_GUI_EXPORT QCursor { public: QCursor(); QCursor(Qt::CursorShape shape); QCursor(const QBitmap &bitmap, const QBitmap &mask, int hotX=-1, int hotY=-1); QCursor(const QPixmap &pixmap, int hotX=-1, int hotY=-1); QCursor(const QCursor &cursor); ~QCursor(); QCursor &operator=(const QCursor &cursor); operator QVariant() const; Qt::CursorShape shape() const; void setShape(Qt::CursorShape newShape); const QBitmap *bitmap() const; const QBitmap *mask() const; QPixmap pixmap() const; QPoint hotSpot() const; static QPoint pos(); static void setPos(int x, int y); inline static void setPos(const QPoint &p) { setPos(p.x(), p.y()); } #ifdef qdoc HCURSOR_or_HANDLE handle() const; QCursor(HCURSOR cursor); QCursor(Qt::HANDLE cursor); #endif #ifndef qdoc #if defined(Q_WS_WIN) HCURSOR handle() const; QCursor(HCURSOR cursor); #elif defined(Q_WS_X11) Qt::HANDLE handle() const; QCursor(Qt::HANDLE cursor); static int x11Screen(); #elif defined(Q_WS_MAC) Qt::HANDLE handle() const; #elif defined(Q_WS_QWS) int handle() const; #endif #endif private: QCursorData *d; #if defined(Q_WS_MAC) friend void qt_mac_set_cursor(const QCursor *c, const QPoint &p); #endif }; #ifdef QT3_SUPPORT // CursorShape is defined in X11/X.h #ifdef CursorShape #define X_CursorShape CursorShape #undef CursorShape #endif typedef Qt::CursorShape QCursorShape; #ifdef X_CursorShape #define CursorShape X_CursorShape #endif #endif /***************************************************************************** QCursor stream functions *****************************************************************************/ #ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &outS, const QCursor &cursor); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &inS, QCursor &cursor); #endif #endif // QT_NO_CURSOR QT_END_NAMESPACE QT_END_HEADER #endif // QCURSOR_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 160 ] ] ]
9eab88d69f48fc90d0785dd72f9e44f9e097b911
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Engine/sdk/inc/physics/coordinate_frame.h
2784bd76b2238e3b4a46b02ed1864d1007197b2d
[]
no_license
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
25,163
h
#ifndef __COORDINATE_FRAME_H__ #define __COORDINATE_FRAME_H__ #ifndef __MATH_PHYS_H__ #include "math_phys.h" #endif //---------------------------------------------------------------------------// /*! The LTBasis data type uses a 3x3 orthogonal matrix to represent a local orientation, and provides methods for rotation and transformation. Used for: Math. */ class LTBasis { public: //!The columns of m_M are the base vectors. LTMatrix3f m_M; public: //!The default constructor creates an identity LTBasis. LTBasis() { m_M.Identity(); } /*! \param q A unit quaternion Construct from a unit quaternion. Used for: Math. */ LTBasis( const LTQuaternionf& q ) : m_M(q)//convert to a matrix {} /*! \param m A 3x3 matrix Construct from a 3x3 matrix whose columns are the x,y and z local axes Used for: Math. */ LTBasis( const LTMatrix3f& m ) : m_M(m)//base vectors in columns {} /*! \param x Local x-axis \param y Local y-axis \param x Local z-axis Construct the 3 local axes. Used for: Math. */ LTBasis( const LTVector3f& x, const LTVector3f& y, const LTVector3f& z ) : m_M(x, y, z) {} /*! \param pitch Rotation about world x-axis in radians \param yaw Rotation about world y-axis in radians \param roll Rotation about world z-axis in radians Given pitch, roll and yaw, construct the composite Euler rotation. Used for: Math. */ LTBasis( const float pitch, const float yaw, const float roll ); /*! \param f The unnormalized "forward" reference direction \param u The unnormalized "upward" reference direction Given two unnormalized vectors \f${\bf f}\f$ and \f${\bf u}\f$, create a LTBasis that corresponds to the orthonormal basis \f$\left\{ {{\bf R}^0 ,{\bf R}^1 ,{\bf R}^2} \right\}\f$, where \f[ \begin{array}{l} {\bf R}^2 = \frac{ {\bf v}_f }{ ||{\bf v}_f|| } \\ {\bf R}^1 = \frac{{{\bf \hat v}_u - ({\bf \hat v}_u \cdot {\bf R}^2 ){\bf R}^2 }} {{\left| {{\bf \hat v}_u - ({\bf \hat v}_u \cdot {\bf R}^2 ){\bf R}^2 } \right|}} \\ {\bf R}^0 = {\bf R}^1 \times {\bf R}^2 \\ \end{array} \f] Used for: Math. */ LTBasis( const LTVector3f& f, const LTVector3f& u ); /*! \return \b true if the LTBasis's are equal, \b false otherwise Used for: Math. */ bool operator == ( const LTBasis& B ) const { return m_M == B.m_M; } /*! \param B An LTBasis Set the orientation. Used For: Math. */ void Orientation( const LTBasis& B ) { this->m_M = B.m_M; } /*! Create an identity LTBasis. Used For: Math. */ void Init() { m_M.Identity(); } /*! \return the local x-axis. Used for: Math. */ const LTVector3f X() const { return m_M(0); } /*! \return the local y-axis. Used for: Math. */ const LTVector3f Y() const { return m_M(1); } /*! \return the local z-axis. Used for: Math. */ const LTVector3f Z() const { return m_M(2); } /*! Convert to a quaternion. Used for: Math. */ operator LTQuaternionf () const { return m_M; } /*! Convert to a 3x3 matrix. Used for: Math. */ operator LTMatrix3f() const { return m_M; } /*! \param a the angle through which to rotate \param u the unit axis about which to rotate Rotate through an angle \f$a\f$ about a unit axis \f$ {\bf \hat u} \f$. Used for: Math. */ void Rotate( const float a, const LTVector3f& u ); /*! \param v the rotation "vector" Rotate through an angle \f$ a=||v|| \f$ about a unit axis \f$ {\bf \hat v} \f$. Used for: Math. */ void Rotate( const LTVector3f& v ) { float a = v.Dot(v);//square of the angle if( 0 != a )//don't divide by 0 { a = sqrtf( a );//angle through which to Rotate this->Rotate( a, v/a );//u = v/a } } /*! \param a the angle through which to rotate in radians Rotate this about its x-axis. Used for: Math. */ void RotateAboutX( const float a ); /*! \param a the angle through which to rotate in radians Rotate this about its y-axis. Used for: Math. */ void RotateAboutY( const float a ); /*! \param a the angle through which to rotate in radians Rotate this about its z-axis. Used for: Math. */ void RotateAboutZ( const float a ); /*! \param v the vector to transform \return \f$ {\bf v_{parent}} \f$ Transform a vector \f$ {\bf v_{local}} \f$ from the local frame to the parent frame. Used for: Math. */ const LTVector3f TransformVectorToParent( const LTVector3f& v ) const { return m_M * v; } /*! \param v the vector to transform \return \f$ {\bf v_{local}} \f$ Transform a vector \f$ {\bf v_{parent}} \f$ from the parent frame to the local frame. Used for: Math. */ const LTVector3f TransformVectorToLocal( const LTVector3f& v ) const { return v * m_M; } /*! \param B another LTBasis Given two bases \b A and \b B both specified with respect to the same parent frame, transform \b A to be in \b B's local frame (so that a vector \b v in \b A's frame will be in \b B's frame after A.TransformVectorToParent( v ) is called). \see LTBasis::TransformToParent() Used For: Math. */ const LTBasis TransformToLocal( const LTBasis& B ) const { //transform each base vector of A to B's local frame const LTMatrix3f M = B.m_M.Transpose() * m_M; return LTBasis( M ); } /*! \param B another LTBasis Given a basis \b A specified with respect to the basis \b B, transform \b A to be in \b B's parent frame (so that a vector \b v in \b A's frame will be in \b B's parent frame after A.TransformVectorToParent( v ) is called). \see LTBasis::TransformToLocal() Used For: Math. */ const LTBasis TransformToParent( const LTBasis& B ) const { //transform each base vector of A to B's parent frame const LTMatrix3f M = B.m_M * this->m_M; return LTBasis( M ); } /*! \param R0 the LTBasis at \f$u=0\f$ \param R1 the LTBasis at \f$u=1\f$ \param u the interpolation parameter \f$ u \in [0,1] \f$ \return Ru the interpolated LTBasis Given two LTBasis's \f${\bf R}_0\f$ and \f${\bf R}_1\f$ and a parameter \f$ u \in [0,1] \f$, spherically linearly interpolate an LTBasis \f${\bf a}_u\f$. \see Slerp() Used for: Math. */ friend const LTBasis Interpolate ( const LTBasis& R0, const LTBasis& R1, const float u ) { const LTQuaternionf q0 = R0.m_M; const LTQuaternionf q1 = R1.m_M; return Slerp( q0, q1, u ); } #ifdef __PHYS_RIGHT_HANDED_Z_UP__ //don't double-document this stuff #ifndef DOXYGEN_SHOULD_SKIP_THIS void Init( const LTVector3f& r, const LTVector3f& f, const LTVector3f& u ) { //convert basis vectors to a quaternion m_M = LTMatrix3f( r, f, u ); } const LTVector3f Right() const { return X(); } const LTVector3f Forward() const { return Y(); } const LTVector3f Up() const { return Z(); } void RotateRight( const float a ) { RotateAboutZ( -a ); } void RotateUp( const float a ) { RotateAboutX( a ); } void RollClockwise( const float a ) { RotateAboutY( a ); } #endif #else//left-handed, y-up /*! \param r right \param f forward \param u up Given the three orthonormal vectors \f$ \left\{ {\bf \hat r},{\bf \hat f}, {\bf \hat u} \right\} \f$ initialize the local axes. Used for: Math. */ void Init( const LTVector3f& r, const LTVector3f& f, const LTVector3f& u ) { //convert basis vectors to a quaternion m_M = LTMatrix3f( r, u, f ); } /*! \return the local rightward direction. Used For: Math. */ const LTVector3f Right() const { return X(); } /*! \return the local forward direction. Used For: Math. */ const LTVector3f Forward() const { return Z(); } /*! \return the local upward direction. Used For: Math. */ const LTVector3f Up() const { return Y(); } /*! \param a the angle through which to rotate in radians Rotate about the upward direction. Used For: Math. */ void RotateRight( const float a ) { RotateAboutY( a ); } /*! \param a the angle through which to rotate, radians Rotate about the rightward direction. Used For: Math. */ void RotateUp( const float a ) { RotateAboutX( -a ); } /*! \param a the angle through which to rotate, radians Rotate about the forward direction. Used For: Math. */ void RollClockwise( const float a ) { RotateAboutZ( -a ); } #endif }; //---------------------------------------------------------------------------// /*! The LTOrientation data type uses unit quaternion to represent a local orientation, and provides methods for rotation and transformation. Used for: Math. */ class LTOrientation { public: LTQuaternionf m_Q;//a unit quaternion public: /*! The default constructor creates an identity transformation. */ LTOrientation() : m_Q(1,0,0,0) {} /*! \param q a unit quaternion Construct from a unit quaternion. Used for: Math. */ LTOrientation( const LTQuaternionf& q ) : m_Q( q ) {} /*! \param m a 3x3 matrix Construct from a 3x3 matrix whose columns are the x,y and z local axes Used for: Math. */ LTOrientation( const LTMatrix3f& m ) : m_Q( m )//convert to a quaternion {} /*! \param R A LTBasis Construct from a LTBasis object. Used for: Math. */ LTOrientation( const LTBasis& R ) : m_Q( R.m_M )//convert to a quaternion {} /*! \param x Local x-axis. \param y Local y-axis. \param z Local z-axis. Construct the 3 local axes. Used for: Math. */ LTOrientation( const LTVector3f& x, const LTVector3f& y, const LTVector3f& z ) : m_Q( LTMatrix3f(x,y,z) )//convert to a quaternion {} /*! \param ax The rotation about x, in radians. \param ay The rotation about y, in radians. \param az The rotation about z, in radians. Given three Euler rotations \f${\theta}_x\f$, \f${\theta}_y\f$, and \f${\theta}_z\f$ (in radians), construct the composite Euler rotation. Used for: Math. */ LTOrientation( const float ax, const float ay, const float az ) { m_Q = LTBasis(ax,ay,az);//convert to a quaternion } /*! \param f The unnormalized "forward" reference direction. \param u The unnormalized "upward" reference direction. Given two unnormalized vectors \f${\bf f}\f$ and \f${\bf u}\f$, create a LTOrientation that corresponds to the orthonormal basis \f$\left\{ {{\bf R}^0 ,{\bf R}^1 ,{\bf R}^2} \right\}\f$, where \f[ \begin{array}{l} {\bf R}^2 = \frac{{{\bf v}_f }}{{\left|{{\bf v}_f }\right|}} \\ {\bf R}^1 = \frac{{{\bf \hat v}_u - ({\bf \hat v}_u \cdot {\bf R}^2 ){\bf R}^2 }} {{\left| {{\bf \hat v}_u - ({\bf \hat v}_u \cdot {\bf R}^2 ){\bf R}^2 } \right|}} \\ {\bf R}^0 = {\bf R}^1 \times {\bf R}^2 \\ \end{array} \f] Used for: Math. */ LTOrientation( const LTVector3f& f, const LTVector3f& u ); /*! \param R an LTOrientation Set the orientation. Used For: Math. */ void Orientation( const LTOrientation& R ) { this->m_Q = R.m_Q; } /*! Create an identity orientation. Used For: Math. */ void Init() { //corresponds to identity this->m_Q.r = 1; this->m_Q.v.Init(); } /*! \return the local x-axis. Used for: Math. */ const LTVector3f X() const { //NOTE: optimizer eliminates these temps const float r = m_Q.r; const float x = m_Q.v.x; const float y = m_Q.v.y; const float z = m_Q.v.z; //column 0 return LTVector3f( 1 - 2*y*y - 2*z*z, 2*x*y + 2*z*r, 2*x*z - 2*y*r ); } /*! \return the local y-axis. Used for: Math. */ const LTVector3f Y() const { const float r = m_Q.r; const float x = m_Q.v.x; const float y = m_Q.v.y; const float z = m_Q.v.z; //column 1 return LTVector3f( 2*x*y - 2*z*r, 1 - 2*x*x - 2*z*z, 2*y*z + 2*x*r ); } /*! \return the local z-axis. Used for: Math. */ const LTVector3f Z() const { const float r = m_Q.r; const float x = m_Q.v.x; const float y = m_Q.v.y; const float z = m_Q.v.z; //column 2 return LTVector3f( 2*x*z + 2*y*r, 2*y*z - 2*x*r, 1 - 2*x*x - 2*y*y ); } /*! Convert to a quaternion. Used for: Math. */ operator LTQuaternionf () const { return m_Q; } /*! Convert to a 3x3 matrix. Used for: Math. */ operator LTMatrix3f() const { return m_Q; } /*! Convert to a LTBasis. Used for: Math. */ operator LTBasis() const { return LTBasis( m_Q ); } /*! \return \b true if the LTOrientation's are equal \b false otherwise Used for: Math. */ bool operator == ( const LTOrientation& q ) const { return m_Q == q.m_Q; } /*! \param a The angle through which to rotate. \param u The unit axis about which to rotate. Rotate through an angle \f$ a \f$ about a unit axis \f$ {\bf \hat u} \f$. Used for: Math. */ void Rotate( const float a, const LTVector3f& u ) { LTQuaternionf q( cosf(0.5f * a), u * sinf(0.5f * a) ); m_Q = q * m_Q; } /*! \param v The rotation vector. Rotate through an angle \f$ a=||v|| \f$ about a unit axis \f$ {\bf \hat v} \f$. Used for: Math. */ void Rotate( const LTVector3f& v ) { float a = v.Dot(v);//square of the angle if( 0 != a )//don't divide by 0 { a = sqrtf( a );//angle through which to Rotate this->Rotate( a, v/a );//unit vector is axis } } /*! \param a The angle through which to rotate, in radians. Rotate this about its x-axis. Used for: Math. */ void RotateAboutX( const float a ) { this->Rotate( a, this->X() ); } /*! \param a The angle through which to rotate, in radians. Rotate this about its y-axis. Used for: Math. */ void RotateAboutY( const float a ) { this->Rotate( a, this->Y() ); } /*! \param a The angle through which to rotate, in radians. Rotate this about its z-axis. Used for: Math. */ void RotateAboutZ( const float a ) { this->Rotate( a, this->Z() ); } /*! \param v the vector to transform \return \f$ {\bf v_{parent}} \f$ Transform a vector \f$ {\bf v_{local}} \f$ from the local frame to the parent frame. Used for: Math. */ const LTVector3f TransformVectorToParent( const LTVector3f& v ) const { return m_Q * v * m_Q.Conjugate(); } /*! \param v the vector to transform \return \f$ {\bf v_{local}} \f$ Transform a vector \f$ {\bf v_{parent}} \f$ from the parent frame to the local frame. Used for: Math. */ const LTVector3f TransformVectorToLocal( const LTVector3f& v ) const { return m_Q.Conjugate() * v * m_Q; } /*! \param B another LTOrientation Given two orientations \b A and \b B both specified with respect to the same parent frame, transform \b A to be in \b B's local frame (so that a vector \b v in \b A's frame will be in \b B's frame after A.TransformVectorToParent( v ) is called). \see LTOrientation::TransformToParent() Used For: Math. */ const LTOrientation TransformToLocal( const LTOrientation& B ) const { const LTQuaternionf q = B.m_Q.Conjugate() * this->m_Q; return LTOrientation( q ); } /*! \param B another LTOrientation Given an orientation \b A specified with respect to the orientation \b B, transform \b A to be in \b B's parent frame (so that a vector \b v in \b A's frame will be in \b B's parent frame after A.TransformVectorToParent( v ) is called). \see LTOrientation::TransformToLocal() Used For: Math. */ const LTOrientation TransformToParent( const LTOrientation& B ) const { const LTQuaternionf q = B.m_Q * this->m_Q; return LTOrientation( q ); } /*! \param R0 the LTOrientation at \f$u=0\f$ \param R1 the LTOrientation at \f$u=1\f$ \param u the interpolation parameter \f$ u \in [0,1] \f$ \return Ru the interpolated LTOrientation Given two LTOrientation's \f${\bf R}_0\f$ and \f${\bf R}_1\f$ and a parameter \f$ u \in [0,1] \f$, spherically linearly interpolate an LTOrientation \f${\bf a}_u\f$. \see Slerp() Used for: Math. */ friend const LTOrientation Interpolate ( const LTOrientation& R0, const LTOrientation& R1, const float u ) { return Slerp( R0.m_Q, R1.m_Q, u ); } #ifdef __PHYS_RIGHT_HANDED_Z_UP__ //don't double-document this stuff #ifndef DOXYGEN_SHOULD_SKIP_THIS void Init( const LTVector3f& r, const LTVector3f& f, const LTVector3f& u ) { //convert basis vectors to a quaternion m_Q = LTMatrix3f( r, f, u ); } const LTVector3f Right() const { return X(); } const LTVector3f Forward() const { return Y(); } const LTVector3f Up() const { return Z(); } void RotateRight( const float a ) { RotateAboutZ( -a ); } void RotateUp( const float a ) { RotateAboutX( a ); } void RollClockwise( const float a ) { RotateAboutY( a ); } #endif #else//left-handed, y-up /*! \param r right \param f forward \param u up Given the three orthonormal vectors \f$ \left\{ {\bf \hat r},{\bf \hat f}, {\bf \hat u} \right\} \f$ initialize the local axes. Used for: Math. */ void Init( const LTVector3f& r, const LTVector3f& f, const LTVector3f& u ) { //convert basis vectors to a quaternion m_Q = LTMatrix3f( r, u, f ); } /*! \return the rightward direction. Used For: Math. */ const LTVector3f Right() const { return X(); } /*! \return the forward direction. Used For: Math. */ const LTVector3f Forward() const { return Z(); } /*! \return the upward direction. Used For: Math. */ const LTVector3f Up() const { return Y(); } /*! \param a the angle through which to rotate in radians Rotate about the upward direction. Used For: Math. */ void RotateRight( const float a ) { RotateAboutY( a ); } /*! \param a the angle through which to rotate in radians Rotate about the rightward direction. Used For: Math. */ void RotateUp( const float a ) { RotateAboutX( -a ); } /*! \param a the angle through which to rotate in radians Rotate about the forward direction. Used For: Math. */ void RollClockwise( const float a ) { RotateAboutZ( -a ); } #endif }; //---------------------------------------------------------------------------// /*! The LTCoordinateFrame data type represents a local coordinate frame, and provides methods for rotations, translations and transformations. */ template< class T > class LTCoordinateFrame : public T { public: //!The origin (position) with respect to the parent frame. LTVector3f m_O; public: LTCoordinateFrame() : m_O(0,0,0) {} /*! \param o the origin (position) \param R the orientation Construct from a positon and a LTBasis. Used for: Math. */ LTCoordinateFrame( const LTVector3f& o, const LTBasis& R ) : T( R.m_M ), m_O( o ) {} /*! \param o the origin (position) \param R the orientation Construct from a positon and a LTOrientation. Used for: Math. */ LTCoordinateFrame( const LTVector3f& o, const LTOrientation& R ) : T( R.m_Q ), m_O( o ) {} /*! \param o local origin (position) \param R0 local x-axis \param R1 local y-axis \param R2 local z-axis Construct from a positon and 3 orthonormal vectors. Used for: Math. */ LTCoordinateFrame ( const LTVector3f& o, //origin const LTVector3f& R0, //first basis vector const LTVector3f& R1, //second basis vector const LTVector3f& R2 //third basis vector ) : T( R0, R1, R2 ), m_O( o ) {} /*! \return the position of the coordinate frame Used For: Math. */ const LTVector3f& Position() const { return m_O; } /*! \param p a position Set the position of the coordinate frame. Used For: Math. */ void Position( const LTVector3f& p ) { m_O = p; } /*! \param p a point in the parent frame Transform \b p to the local frame. Used For: Math. */ const LTVector3f TransformPointToLocal( const LTVector3f& p ) const { //Translate to this frame's origin, then project onto this LTBasis return TransformVectorToLocal( p - m_O ); } /*! \param p a point in the local frame Transform \b p to the parent frame. Used For: Math. */ const LTVector3f TransformPointToParent( const LTVector3f& p ) const { //transform the coordinate vector and Translate by this origin return TransformVectorToParent( p ) + m_O; } /*! \param B another LTCoordinateFrame Given two frames \b A and \b B both specified with respect to the same parent frame, transform \b A to be in \b B's local frame (so that a point \b p in \b A's frame will be in \b B's frame after A.TransformPointToParent( p ) is called). \see LTCoordinateFrame::TransformToParent() Used For: Math. */ const LTCoordinateFrame TransformToLocal( const LTCoordinateFrame& B ) const { //origin and orientation with respect to local coordinates const LTVector3f O = B.TransformPointToLocal( m_O ); const T R = B.T::TransformToLocal( *this );//properly resolve function name return LTCoordinateFrame( O, R ); } /*! \param B another LTCoordinateFrame Given a coordinate frame \b A specified with respect to the frame \b B, transform \b A to be in \b B's parent frame (so that a point \b p in \b A's frame will be in \b B's parent frame after A.TransformPointToParent( p ) is called). \see LTCoordinateFrame::TransformToLocal() Used For: Math. */ const LTCoordinateFrame TransformToParent( const LTCoordinateFrame& B ) const { //origin and orientation with respect to local coordinates const LTVector3f O = B.TransformPointToParent( m_O ); const T R = B.T::TransformToParent( *this );//properly resolve function name return LTCoordinateFrame( O, R ); } /*! \param v translation vector Translate the position of the frame by the given vector. Used For: Math. */ void Translate( const LTVector3f& v ) { m_O += v; } //NOTE: For some reason, the MS compiler can't resolve //the two functions below, even though it can resolve //RotateAboutX(), etc. /*! \param a The angle through which to rotate. \param u The unit axis about which to rotate. Rotate through an angle \f$ a \f$ about a unit axis \f$ {\bf \hat u} \f$. Used for: Math. */ void Rotate( const float a, const LTVector3f& u ) { //rotate the local axes T::Rotate( a, u ); } /*! \param v The rotation vector. Rotate through an angle \f$ a=||v|| \f$ about a unit axis \f$ {\bf \hat v} \f$. Used for: Math. */ void Rotate( const LTVector3f& v ) { T::Rotate( v ); } /*! \param a the angle through which to rotate this frame \param u the axis about which to rotate this frame \param p0 a point on the line about which to rotate this frame Rotate this coordinate frame through and angle \f$a\f$ about a line passing through \f$ {\bf p}_0 \f$ in the direction of \f$ \hat {\bf u} \f$. Used For: Math. */ void Rotate( const float a, const LTVector3f& u, const LTVector3f& p0 ) { //rotate the position of the coordinate frame about the axis const LTMatrix3f M = RotationMatrix( a, u ); const LTMatrix3f v = M * (this->m_O - p0); this->m_O = p0 + v;//new position //rotate the local axes this->Rotate( a, u ); } /*! \param v \param p0 Rotate this coordinate frame through and angle \f$a=||{\bf v}||\f$ about a line passing through \f$ {\bf p}_0 \f$ in the direction of \f$ \hat{\bf u}=\frac{ {\bf v} }{ ||{\bf v}|| }\f$. Used For: Math. */ void Rotate( const LTVector3f& v, const LTVector3f& p0 ) { float a = v.Dot(v);//square of the angle if( 0 != a )//don't divide by 0 { a = sqrtf( a );//angle through which to Rotate this->Rotate( a, v/a, p0 );//u = v/a } } //given u \in [0,1], linearly interpolate between F0 and F1 friend const LTCoordinateFrame Interpolate ( const LTCoordinateFrame& F0, const LTCoordinateFrame& F1, const float u ) { const LTVector3f O = Lerp( F0.m_O, F1.m_O, u ); //NOTE: cast allows proper resolution of Interpolate(), //otherwise infinite recursion occurs const T R = Interpolate( (T&)F0, (T&)F1, u ); return LTCoordinateFrame( O, R ); } }; /*! Lithtech defines two types of coordinate frame data types: LTCoordinateFrameM, which derives from LTBasis and thus uses a 3x3 matrix to store orientation, and LTCoordinateFrameQ, which derives from LTOrientation and thus uses a unit quaternion to store orientation. LTCoordinateFrameM transforms vectors and points more quickly, but uses 48 bytes. LTCoordinateFrameQ uses only 28 bytes but transforms points and vectors less quickly. */ typedef LTCoordinateFrame<LTBasis> LTCoordinateFrameM; typedef LTCoordinateFrame<LTOrientation> LTCoordinateFrameQ; #endif //EOF
[ [ [ 1, 1154 ] ] ]
66c279cb816fc9972b0568861537068cdcc1cc00
925e7b0a9f5757cad97981b37c6af180c30b2f6e
/nntpServer/nntpServer/socket.cpp
bfcff3ae0151a50307e310c588fb9503a81069fc
[]
no_license
jmg/nttp-server
08c2b6be2183b00989c8e4ea35dffaef3947385a
0308abe74e793fe0c16676e797ae16150566e1d6
refs/heads/master
2016-09-05T10:53:25.116857
2011-07-16T01:28:32
2011-07-16T01:28:32
2,739,107
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
cpp
#ifndef Socket_CPP #define Socket_CPP #define DllExport __declspec(dllexport) #include <winsock2.h> #include <stdio.h> #include "thread.h" #include "Utils/Logs.h" class ServerSocket { private: static const int MAXSOCKETS = 5; WSADATA wsaData; SOCKET sock; sockaddr_in addr; int NumConnections; int addr_size; Thread thread; public: ServerSocket() { if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { WSACleanup(); puts("Error at WSAStartup()\n"); LogFileLogEntry(MAINPROCESSNAME, NOTHREADID, LOGTYPEERROR, "Error de inicializacion del socket", NOPARMS); LogFileLogEndSession(); exit(1); } if (wsaData.wVersion != 0x0202) { WSACleanup(); puts("error version"); LogFileLogEntry(MAINPROCESSNAME, NOTHREADID, LOGTYPEERROR, "Error de version del socket", NOPARMS); LogFileLogEndSession(); exit(1); } sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } void Listen(int port, unsigned (__stdcall * target)(void*)) { addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (LPSOCKADDR)&addr, sizeof(addr)) == SOCKET_ERROR) { WSACleanup(); puts("No se pudo bindear el socket"); LogFileLogEntry(MAINPROCESSNAME, NOTHREADID, LOGTYPEERROR, "No se pudo bindear el socket", NOPARMS); LogFileLogEndSession(); exit(1); } if (listen(sock, MAXSOCKETS) == SOCKET_ERROR) { WSACleanup(); puts("No se pudo escuchar el puerto"); LogFileLogEntry(MAINPROCESSNAME, NOTHREADID, LOGTYPEERROR, "No se pudo escuchar el puerto", NOPARMS); LogFileLogEndSession(); exit(1); } for (;;) { SOCKET socketClient; socketClient = accept(sock, NULL, NULL); if (socketClient == INVALID_SOCKET) { WSACleanup (); puts("Error de coneccion del cliente"); LogFileLogEntry(MAINPROCESSNAME, NOTHREADID, LOGTYPEERROR, "Error de coneccion del cliente", NOPARMS); } else { thread = NewThread(); ThreadRun(thread, target, socketClient); ThreadWaitForFinish(thread); ThreadDestroy(thread); } } } }; #endif
[ "jmg.utn@208282a9-e914-21dd-f66b-6e6d9519d739" ]
[ [ [ 1, 86 ] ] ]
2c09be0c168d830e77e2802fcf538162c57261e9
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Windows/include/WinMapControl.h
59fbeadb0c9aa694197da306edf2b2800ace6486
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,184
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WINMAPCONTROL_H #define WINMAPCONTROL_H /* forward declarations */ class WinTCPConnectionHandler; class HttpClientConnection; class WinTileMapToolkit; class WinBitmap; class MC2Point; class TileMapHandler; class TileMapHandlerClickResult; class SharedHttpDBufRequester; class MemoryDBufRequester; class MC2Coordinate; class TileMapTextSettings; class PixelBox; #include "config.h" #include "WinMapPlotter.h" #include <windows.h> #include "Cursor.h" /* Handles the connection to the TMap Server and the drawing of the Map */ class WinMapControl : public Cursor { /** data **/ private: /* the main window */ HWND m_hwnd; /* the width and height of the control */ int32 m_width, m_height; /* the map plotter */ isab::WinMapPlotter* m_plotter; /* the platform toolkit */ WinTileMapToolkit* m_toolkit; /* the TCP Connection handler */ WinTCPConnectionHandler* m_connHandler; /* the HTTP Connection handler */ HttpClientConnection* m_httpConn; /* the HTTP requester */ SharedHttpDBufRequester* m_httpReq; /* the memory caching requester */ MemoryDBufRequester* m_memReq; /* the Tile Map Handler */ TileMapHandler* m_mapHandler; /** methods **/ private: /* private constructor */ WinMapControl(HWND parent); /* second-phase constructor */ bool construct(LPCREATESTRUCTW cParams, const char* mapServer, int portNum, const char* sessionId, const char* sessionKey); public: /* allocator */ static WinMapControl* allocate(HWND parent, LPCREATESTRUCTW cParams, const char* mapServer, int portNum, const char* sessionId, const char* sessionKey); /* destructor */ ~WinMapControl(); /* gets the handle to the internal window */ HWND getWindow() const; /* displays the map-drawing buffer on the specified DC */ void blitTo(HDC destDC, int32 dx, int32 dy); /* moves the map */ void moveMap(int32 dx, int32 dy); /* rotates the map */ void rotateMap(int32 angle); /* zooms the map */ void zoomMap(float32 factor); /* resets the map rotation to zero degrees */ void resetRotation(); /* request a repaint from the handler */ void doRepaint(); /* resizes the control to the specified dimensions returns true on success, false on error */ bool resize(int32 nW, int32 nH); /* gets the name of the feature at the specified location */ const char* getFeatureName(const MC2Point& pos); /* gets the lat\lon location of the feature at the specified point */ void getFeatureLocation(const MC2Point& pos, MC2Coordinate& outLoc); /* gets the screen position of the feature at the specified coordinate */ void getFeaturePosition(const MC2Coordinate& loc, MC2Point& outPos); void setBlitPoint(int x, int y) { m_plotter->setBlitPoint(x, y); return; } /* gets the width of the control */ int32 width() const { isab::Rectangle rect; m_plotter->getMapSizePixels(rect); return( rect.getWidth() ); } /* gets the height of the control */ int32 height() const { isab::Rectangle rect; m_plotter->getMapSizePixels(rect); return( rect.getHeight() ); } /* gets a reference to the internal TileMapHandler */ TileMapHandler& getHandler() const { return(*m_mapHandler); } /* gets a reference to the internal MapPlotter */ isab::WinMapPlotter& getPlotter() const { return(*m_plotter); } /* gets all info for the feature at the specified point */ void getFeatureInfo(const MC2Point& pos, TileMapHandlerClickResult& result); /** * Sets the text settings ( fonts ) for text placement * in maps. */ void setTextSettings( const TileMapTextSettings& settings ); /** * Get the toolkit. */ WinTileMapToolkit* getToolkit() { return m_toolkit; } /** * Implements abstract method in Cursor. * Currently doesn't do anything. */ void setHighlight( bool highlight ); /** * Implements abstract method in Cursor. * Currently doesn't do anything. */ void setCursorPos( const MC2Point& pos ); /** * Implements abstract method in Cursor. * Get the current cursor position. * @return The cursor position. */ MC2Point getCursorPos() const; /** * Implements abstract method in Cursor. * Set if the cursor should be visible or hidden. * @param visible If true, the cursor is visible, * otherwise hidden. */ void setCursorVisible( bool visible ); /** * Implements abstract method in Cursor. * Get the box of the cursor. * @param box PixelBox that will be set to the current * box of the cursor. */ void getCursorBox( PixelBox& box ) const; }; #endif
[ [ [ 1, 213 ] ] ]
f88c87bec779ed1c78e074bf8d224cd301aad358
c70941413b8f7bf90173533115c148411c868bad
/core/src/vtxNetServer.cpp
b22e4b8e81dc4cb7271eec419023706711a0ecae
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "vtxNetServer.h" namespace vtx { //----------------------------------------------------------------------- //----------------------------------------------------------------------- }
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 36 ] ] ]
939025a401fccc01deaaf47a4f7b1c04d5e10aaa
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/android/third_party/gecko-1.9.0.11/win32/include/nsIX509CertValidity.h
af59f515604f74a700548dda12030971eb3c9be1
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
8,609
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/security/manager/ssl/public/nsIX509CertValidity.idl */ #ifndef __gen_nsIX509CertValidity_h__ #define __gen_nsIX509CertValidity_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIX509CertValidity */ #define NS_IX509CERTVALIDITY_IID_STR "e701dfd8-1dd1-11b2-a172-ffa6cc6156ad" #define NS_IX509CERTVALIDITY_IID \ {0xe701dfd8, 0x1dd1, 0x11b2, \ { 0xa1, 0x72, 0xff, 0xa6, 0xcc, 0x61, 0x56, 0xad }} /** * Information on the validity period of a X.509 certificate. * * @status FROZEN */ class NS_NO_VTABLE NS_SCRIPTABLE nsIX509CertValidity : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IX509CERTVALIDITY_IID) /** * The earliest point in time where * a certificate is valid. */ /* readonly attribute PRTime notBefore; */ NS_SCRIPTABLE NS_IMETHOD GetNotBefore(PRTime *aNotBefore) = 0; /** * "notBefore" attribute formatted as a time string * according to the environment locale, * according to the environment time zone. */ /* readonly attribute AString notBeforeLocalTime; */ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalTime(nsAString & aNotBeforeLocalTime) = 0; /** * The day portion of "notBefore" * formatted as a time string * according to the environment locale, * according to the environment time zone. */ /* readonly attribute AString notBeforeLocalDay; */ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalDay(nsAString & aNotBeforeLocalDay) = 0; /** * "notBefore" attribute formatted as a string * according to the environment locale, * displayed as GMT / UTC. */ /* readonly attribute AString notBeforeGMT; */ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeGMT(nsAString & aNotBeforeGMT) = 0; /** * The latest point in time where * a certificate is valid. */ /* readonly attribute PRTime notAfter; */ NS_SCRIPTABLE NS_IMETHOD GetNotAfter(PRTime *aNotAfter) = 0; /** * "notAfter" attribute formatted as a time string * according to the environment locale, * according to the environment time zone. */ /* readonly attribute AString notAfterLocalTime; */ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalTime(nsAString & aNotAfterLocalTime) = 0; /** * The day portion of "notAfter" * formatted as a time string * according to the environment locale, * according to the environment time zone. */ /* readonly attribute AString notAfterLocalDay; */ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalDay(nsAString & aNotAfterLocalDay) = 0; /** * "notAfter" attribute formatted as a time string * according to the environment locale, * displayed as GMT / UTC. */ /* readonly attribute AString notAfterGMT; */ NS_SCRIPTABLE NS_IMETHOD GetNotAfterGMT(nsAString & aNotAfterGMT) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIX509CertValidity, NS_IX509CERTVALIDITY_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIX509CERTVALIDITY \ NS_SCRIPTABLE NS_IMETHOD GetNotBefore(PRTime *aNotBefore); \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalTime(nsAString & aNotBeforeLocalTime); \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalDay(nsAString & aNotBeforeLocalDay); \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeGMT(nsAString & aNotBeforeGMT); \ NS_SCRIPTABLE NS_IMETHOD GetNotAfter(PRTime *aNotAfter); \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalTime(nsAString & aNotAfterLocalTime); \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalDay(nsAString & aNotAfterLocalDay); \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterGMT(nsAString & aNotAfterGMT); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIX509CERTVALIDITY(_to) \ NS_SCRIPTABLE NS_IMETHOD GetNotBefore(PRTime *aNotBefore) { return _to GetNotBefore(aNotBefore); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalTime(nsAString & aNotBeforeLocalTime) { return _to GetNotBeforeLocalTime(aNotBeforeLocalTime); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalDay(nsAString & aNotBeforeLocalDay) { return _to GetNotBeforeLocalDay(aNotBeforeLocalDay); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeGMT(nsAString & aNotBeforeGMT) { return _to GetNotBeforeGMT(aNotBeforeGMT); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfter(PRTime *aNotAfter) { return _to GetNotAfter(aNotAfter); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalTime(nsAString & aNotAfterLocalTime) { return _to GetNotAfterLocalTime(aNotAfterLocalTime); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalDay(nsAString & aNotAfterLocalDay) { return _to GetNotAfterLocalDay(aNotAfterLocalDay); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterGMT(nsAString & aNotAfterGMT) { return _to GetNotAfterGMT(aNotAfterGMT); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIX509CERTVALIDITY(_to) \ NS_SCRIPTABLE NS_IMETHOD GetNotBefore(PRTime *aNotBefore) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotBefore(aNotBefore); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalTime(nsAString & aNotBeforeLocalTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotBeforeLocalTime(aNotBeforeLocalTime); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeLocalDay(nsAString & aNotBeforeLocalDay) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotBeforeLocalDay(aNotBeforeLocalDay); } \ NS_SCRIPTABLE NS_IMETHOD GetNotBeforeGMT(nsAString & aNotBeforeGMT) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotBeforeGMT(aNotBeforeGMT); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfter(PRTime *aNotAfter) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotAfter(aNotAfter); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalTime(nsAString & aNotAfterLocalTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotAfterLocalTime(aNotAfterLocalTime); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterLocalDay(nsAString & aNotAfterLocalDay) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotAfterLocalDay(aNotAfterLocalDay); } \ NS_SCRIPTABLE NS_IMETHOD GetNotAfterGMT(nsAString & aNotAfterGMT) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotAfterGMT(aNotAfterGMT); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsX509CertValidity : public nsIX509CertValidity { public: NS_DECL_ISUPPORTS NS_DECL_NSIX509CERTVALIDITY nsX509CertValidity(); private: ~nsX509CertValidity(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsX509CertValidity, nsIX509CertValidity) nsX509CertValidity::nsX509CertValidity() { /* member initializers and constructor code */ } nsX509CertValidity::~nsX509CertValidity() { /* destructor code */ } /* readonly attribute PRTime notBefore; */ NS_IMETHODIMP nsX509CertValidity::GetNotBefore(PRTime *aNotBefore) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notBeforeLocalTime; */ NS_IMETHODIMP nsX509CertValidity::GetNotBeforeLocalTime(nsAString & aNotBeforeLocalTime) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notBeforeLocalDay; */ NS_IMETHODIMP nsX509CertValidity::GetNotBeforeLocalDay(nsAString & aNotBeforeLocalDay) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notBeforeGMT; */ NS_IMETHODIMP nsX509CertValidity::GetNotBeforeGMT(nsAString & aNotBeforeGMT) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRTime notAfter; */ NS_IMETHODIMP nsX509CertValidity::GetNotAfter(PRTime *aNotAfter) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notAfterLocalTime; */ NS_IMETHODIMP nsX509CertValidity::GetNotAfterLocalTime(nsAString & aNotAfterLocalTime) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notAfterLocalDay; */ NS_IMETHODIMP nsX509CertValidity::GetNotAfterLocalDay(nsAString & aNotAfterLocalDay) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute AString notAfterGMT; */ NS_IMETHODIMP nsX509CertValidity::GetNotAfterGMT(nsAString & aNotAfterGMT) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIX509CertValidity_h__ */
[ "alexber@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 220 ] ] ]
d000b18f233150c17f9547f05c027b923b981cfe
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/rnsgameplay/ncgpthrowable.cc
dc608d07232155cbbe43a4ee66dbe5931a2fd725
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
770
cc
//----------------------------------------------------------------------------- // ncgpthrowable.cc // (C) 2006 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchrnsgameplay.h" #include "rnsgameplay/ncgpthrowable.h" //------------------------------------------------------------------------------ nNebulaComponentObjectAbstract(ncGPThrowable,ncGameplay); //------------------------------------------------------------------------------ NSCRIPT_INITCMDS_BEGIN(ncGPThrowable) NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 17 ] ] ]
d87b82c072e993c2d36f526581e5aae232223e44
9fa5057ec9fb06dcecc57f636d6189e820d3b778
/hruStat.h
86a5a75f277eac0fd001620d540402ed31d026ee
[]
no_license
andriybun/grid2hru
7582e98c29dd37b65a7ddff5fb9bed08ef1b47f2
d2a4ed4f7c19246cbd0a31a0fa15e1b8820caec8
refs/heads/master
2016-09-06T07:14:29.112085
2009-10-20T18:41:19
2009-10-20T18:41:19
32,204,774
0
0
null
null
null
null
UTF-8
C++
false
false
2,410
h
// Name: hruStat class // Author: Andriy Bun // Date: 20.10.09 class hruStat { private: // Type needed for calculation of average value // pair.first - total sum of values // pair.second - number of components // => avg = pair.first / pair.second typedef pair<float, float> pairAvg; typedef vector<pairAvg> pairAvgV; vector<pairAvgV> data; vector<char> flags; // Data containers: // Array containing resulting average values double *grid; // 2D array - map of HRU: gridMap<int> hruMap; // 2D array - weight: gridMap<double> weight; int NumTimePeriods; // numbers of time periods in file int statType; // statistics type bool emptyHRU, emptyGrid, emptyW; // property of containers: if true - container is filled with data // Functions for data processing: double getStat(unsigned char timePer, int hruID); // returns statistics value double * summary(); // returns vector of results public: // Class constructor: input parameters: // hruMapFileName - name of file with HRU map; // if its extension is "*.bin", it assumes that the data is stored in binary grid format of // gridMap class; else - text file is read; // stat - statistics type: SUM - sum; AVG - average; AVGW - weightet awg; // VAL - value; // weightFileName (optional) - name of file with map of weights, stored in // binary grid format of gridMap class; hruStat(string hruMapFileName, string stat, string weightFileName); ~hruStat(); // Updating data stored in memory for HRU with hruID, for time period // timePer. Value val is summed, or multiplied with weight and summed // depends on statistics type. 4th param. weight is optional (default = 1) void update(unsigned char timePer, int hruID, float val, float weight); // Reading data from "X Y data" file, without header. There may be any // number of columns with data corresponding to time points 2000, 2010... // with a period of 10 years void readXYdata(double xMin, double yMin, double cellSize, string fileName); // Storing result of conversion in own binary format void SaveToFile_bin(string fileName); // Storing result of conversion in "[HRU ID] data" text file void SaveToFile(string fileName); };
[ "andr.bun@986c60fa-aebb-11de-ae21-b99107b3ee63" ]
[ [ [ 1, 51 ] ] ]
7dc8880e51521d60739cb4044ddfde8db3a44eec
ca1eec7f5a6382b133a45f7c50ff4b838484c159
/II Proyecto (13 de dic)/datafile.h
cea8499cc2c538cff64554ad49cf82713688311c
[]
no_license
josecastellanos/OrganizaciondeArchivos_Watchmen
7e55c587c11fd11cd8c4e9b3ddea6f5a6d920c90
d2621ada6d53da3a1530c3cc20f00502b680b242
refs/heads/master
2021-01-01T17:00:58.384806
2010-12-13T15:25:35
2010-12-13T15:25:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,049
h
#ifndef DATAFILE_H #define DATAFILE_H #include "avl.h" #include "btree.h" #include "QString" #include "QStringList" #include <QTableWidget> #include "hash.h" #include <ctime> #include <iostream> using namespace std; const int blocks=320; class nodo_data { public: nodo_data() { id=-1; time=-1; strcpy(source,""); strcpy(destino,""); strcpy(protocolo,""); strcpy(info,""); } long int id; double time; char source[15]; char destino[15]; char protocolo[20]; char info[255]; }; class dataFile { public: dataFile(char *_name, QTextEdit *log); void create(int cuantos); void add(long int id, double time, char *source, char *destino, char *protocolo, char *info); //void deleteRecord(long int id); void searchAVL(char *protocolo, QTableWidget *tb); void searchHashDestino(char *destino, QTableWidget *tb); void searchHashSource(char *source, QTableWidget *tb); //Para el Timer clock_t inicio, final; void iniciar(); void detener(); double getMS(); //Funciones Para Regresar Tiempo double timeLlavesPrimarias(); double timeLlavesSecundarias(); double timeSearchHD(); // destino double timeSearchHS(); // Source double timeSearchAV(); // void resetTime(); private: void search(char *info, QList<long> *list, QTableWidget *tb); fstream disco; QString name; btree *arbolB; avl *arbolAVL; hash *hashDestino; hash *hashSource; QTextEdit *log; //Variables Para El Tiempo double timeAddLlavesPrimarias; double timeAddLlavesSecundarias; double timeSearchHashDestino; double timeSearchHashSource; double timeSearchAvl; }; #endif // DATAFILE_H
[ [ [ 1, 82 ] ] ]
74891a60ee50794d4bc50118cbe8ce58f8cf238e
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/util/wsiMap.h
aae790d936bf075c646ac3af5280c84680539e62
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
190
h
#pragma once #include <wcpp/lang/wsiObject.h> template <typename K , typename V> class wsiMap : public wsiObject { public: static const ws_iid sIID; public: ; };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 15 ] ] ]
83efe2277255ef777dbea7ae36908a5863cec08e
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/sax/ErrorHandler.hpp
47de8510cacc855493702be07faaccf6d6874fbb
[ "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
6,930
hpp
/* * Copyright 1999-2000,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: ErrorHandler.hpp,v $ * Revision 1.6 2004/09/08 13:56:19 peiyongz * Apache License Version 2.0 * * Revision 1.5 2003/12/01 23:23:26 neilg * fix for bug 25118; thanks to Jeroen Witmond * * Revision 1.4 2003/05/30 16:11:44 gareth * Fixes so we compile under VC7.1. Patch by Alberto Massari. * * Revision 1.3 2003/03/07 18:10:06 tng * Return a reference instead of void for operator= * * Revision 1.2 2002/11/04 14:56:25 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.6 2000/04/27 19:33:15 rahulj * Included <util/XercesDefs.hpp> as suggested by David N Bertoni. * * Revision 1.5 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.4 2000/02/12 03:31:55 rahulj * Removed duplicate CVS Log entries. * * Revision 1.3 2000/02/12 01:27:19 aruna1 * Documentation updated * * Revision 1.2 2000/02/06 07:47:57 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:45 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:00 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef ERRORHANDLER_HPP #define ERRORHANDLER_HPP #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN class SAXParseException; /** * Basic interface for SAX error handlers. * * <p>If a SAX application needs to implement customized error * handling, it must implement this interface and then register an * instance with the SAX parser using the parser's setErrorHandler * method. The parser will then report all errors and warnings * through this interface.</p> * * <p> The parser shall use this interface instead of throwing an * exception: it is up to the application whether to throw an * exception for different types of errors and warnings. Note, * however, that there is no requirement that the parser continue to * provide useful information after a call to fatalError (in other * words, a SAX driver class could catch an exception and report a * fatalError).</p> * * <p>The HandlerBase class provides a default implementation of this * interface, ignoring warnings and recoverable errors and throwing a * SAXParseException for fatal errors. An application may extend * that class rather than implementing the complete interface * itself.</p> * * @see Parser#setErrorHandler * @see SAXParseException#SAXParseException * @see HandlerBase#HandlerBase */ class SAX_EXPORT ErrorHandler { public: /** @name Constructors and Destructor */ //@{ /** Default constructor */ ErrorHandler() { } /** Desctructor */ virtual ~ErrorHandler() { } //@} /** @name The error handler interface */ //@{ /** * Receive notification of a warning. * * <p>SAX parsers will use this method to report conditions that * are not errors or fatal errors as defined by the XML 1.0 * recommendation. The default behaviour is to take no action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end.</p> * * @param exc The warning information encapsulated in a * SAX parse exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see SAXParseException#SAXParseException */ virtual void warning(const SAXParseException& exc) = 0; /** * Receive notification of a recoverable error. * * <p>This corresponds to the definition of "error" in section 1.2 * of the W3C XML 1.0 Recommendation. For example, a validating * parser would use this callback to report the violation of a * validity constraint. The default behaviour is to take no * action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end. If the * application cannot do so, then the parser should report a fatal * error even if the XML 1.0 recommendation does not require it to * do so.</p> * * @param exc The error information encapsulated in a * SAX parse exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see SAXParseException#SAXParseException */ virtual void error(const SAXParseException& exc) = 0; /** * Receive notification of a non-recoverable error. * * <p>This corresponds to the definition of "fatal error" in * section 1.2 of the W3C XML 1.0 Recommendation. For example, a * parser would use this callback to report the violation of a * well-formedness constraint.</p> * * <p>The application must assume that the document is unusable * after the parser has invoked this method, and should continue * (if at all) only for the sake of collecting addition error * messages: in fact, SAX parsers are free to stop reporting any * other events once this method has been invoked.</p> * * @param exc The error information encapsulated in a * SAX parse exception. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see SAXParseException#SAXParseException */ virtual void fatalError(const SAXParseException& exc) = 0; /** * Reset the Error handler object on its reuse * * <p>This method helps in reseting the Error handler object * implementational defaults each time the Error handler is begun.</p> * */ virtual void resetErrors() = 0; //@} private : /* Unimplemented constructors and operators */ /* Copy constructor */ ErrorHandler(const ErrorHandler&); /* Assignment operator */ ErrorHandler& operator=(const ErrorHandler&); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 207 ] ] ]
4e69e460ee9c8e454f9e27354182d528ab6160fa
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/teststdlib/src/tstdlibblocks.cpp
4cd28f46fff004e39f189c17a483562ff95e77be
[]
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
206,096
cpp
/* * Copyright (c) 2006-2008 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: * */ /* * ============================================================================== * Name : tstdlibblocks.cpp * Part of : teststdlib * * Description : ?Description * Version: 0.5 * */ #include "tstdlib.h" #include "sysif.h" //Backend() #include <unistd.h> #include <errno.h> #include <stdio.h> #include <e32std.h> #include <stdlib.h> #include <string.h> #include <limits.h> //MB_LEN_MAX #include <monetary.h> #include <locale.h> #include <test/TestExecuteStepBase.h> #include <limits.h> #include <e32def.h> #include <stdio.h> #include <wchar.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #include <assert.h> #include <wctype.h> #include <inttypes.h> #include <c32comm.h> #include <math.h> #include <e32math.h> #include <fcntl.h> //O_APPEND, O_RDWR, O_CREAT #include <sys/stat.h> //S_ISWUSR #include <sys/syslimits.h> //PATH_MAX #include <pthread.h> //pthread_create #include <getopt.h> //getopt, getopt_long #include <signal.h> #include <setjmp.h> #include <iconv.h> #include <grp.h> #define MAX_SIZE 50 #define BUF_SIZE 100 // ============================ GLOBAL FUNCTIONS =============================== void exitfunc0(void) { } void exitfunc1(void) { } void exitfunc2(void) { } void exitfunc3(void) { } void exitfunc4(void) { } void exitfunc5(void) { } void exitfunc6(void) { } void exitfunc7(void) { } void exitfunc8(void) { } void exitfunc9(void) { } void exitfunc10(void) { } void exitfunc11(void) { } void exitfunc12(void) { } void exitfunc13(void) { } void exitfunc14(void) { } void exitfunc15(void) { } void exitfunc16(void) { } void exitfunc17(void) { } void exitfunc18(void) { } void exitfunc19(void) { } void exitfunc20(void) { } void exitfunc21(void) { } void exitfunc22(void) { } void exitfunc23(void) { } void exitfunc24(void) { } void exitfunc25(void) { } void exitfunc26(void) { } void exitfunc27(void) { } void exitfunc28(void) { } void exitfunc29(void) { } void exitfunc30(void) { } void exitfunc31(void) { } void exitfunc32(void) { } // ----------------------------------------------------------------------------- // ReadStringParam :Reads path name given the buffer // Returns: KErrNone: On Success // KErrGeneral: On Failure // ----------------------------------------------------------------------------- // void CTestStdlib::ReadStringParam(char* expected) { _LIT( KaKey, "Param%d" ); TBuf<8> pNameBuf; TPtrC string; pNameBuf.Format(KaKey,++iParamCnt); TBool res = GetStringFromConfig(ConfigSection(), pNameBuf, string); if(!res) { _LIT(Kerr , "Unable to retrieve string parameter") ; INFO_PRINTF1(Kerr); } TBuf8<256> bufstring; bufstring.Copy(string); TInt paramLength=string.Length(); char* text=(char *)(bufstring.Ptr()); *(text+paramLength)='\0'; strcpy(expected,text); return; } // ----------------------------------------------------------------------------- // ReadIntParam :Reads an inteeger value given the buffer // Returns: KErrNone: On Success // KErrGeneral: On Failure // ----------------------------------------------------------------------------- // void CTestStdlib::ReadIntParam(TInt &aInt) { _LIT( Kparam, "Param%d" ); TBuf<8> pNameBuf; TPtrC string; pNameBuf.Format(Kparam,++iParamCnt); TBool res = GetIntFromConfig(ConfigSection(), pNameBuf, aInt); if(!res) { _LIT(Kerr , "Unable to retrieve integer parameter") ; INFO_PRINTF1(Kerr); } return; } // ----------------------------------------------------------------------------- //Function Name :malloc_Test0 //API Tested :malloc //TestCase Description:malloc returns -> pointer to unitialized mem locn // ----------------------------------------------------------------------------- TInt CTestStdlib::malloc_Test0() { __UHEAP_MARK; INFO_PRINTF1(_L("In malloc_Test0L")); //-------------------------- char *pc = (char *)malloc( sizeof(char) * 3); //-------------------------- INFO_PRINTF1(_L("{Expected: some char}")); if (pc == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrGeneral; } int i = 0; for(i = 0; i < 3; i++) { INFO_PRINTF2(_L(" %c"), pc[i]); } free(pc); __UHEAP_MARKEND; return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :malloc_Test1 //API Tested :malloc //TestCase Description:malloc returns -> NULL // ----------------------------------------------------------------------------- TInt CTestStdlib::malloc_Test1() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In malloc_Test1L")); errno = 0; //-------------------------- char *pc = (char *)malloc(1024 * 1024); //-------------------------- bool i = (pc == NULL); INFO_PRINTF2(_L("{Expected: 1} %d"), (int)i); free(pc); if (i != true || errno != ENOMEM) { INFO_PRINTF2(_L("errno was set to - %d"), errno); ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :malloc_Test2 //API Tested :malloc //TestCase Description:malloc returns -> NULL // ----------------------------------------------------------------------------- TInt CTestStdlib::malloc_Test2() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In malloc_Test2L")); //-------------------------- char *pc = (char *)malloc(NULL); //-------------------------- bool i = (pc == NULL); INFO_PRINTF2(_L("{Expected: 1} %d"), (int)i); free(pc); if (i != true) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :calloc_Test0 //API Tested :calloc //TestCase Description:calloc returns -> pointer to mem locn intialized to zero // ----------------------------------------------------------------------------- TInt CTestStdlib::calloc_Test0() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In calloc_Test0L")); //-------------------------- int *pint = (int *)calloc(2, sizeof (int) * 2); //-------------------------- if (pint == NULL) { INFO_PRINTF1(_L("calloc failed to allocate memory")); return KErrNoMemory; } INFO_PRINTF1(_L("{Expected: zeros}")); int i = 0; for(i = 0; i < 4; i++) { INFO_PRINTF2(_L(" %d"), pint[i]); } for(i = 0; i < 4; i++) { if (pint[i] != 0) { ret = KErrGeneral; } } free(pint); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :calloc_Test1 //API Tested :calloc //TestCase Description:calloc returns -> NULL // ----------------------------------------------------------------------------- TInt CTestStdlib::calloc_Test1() { __UHEAP_MARK; INFO_PRINTF1(_L("In calloc_Test1L")); //-------------------------- char *pc = (char *)calloc(3, 1024 * 1024); bool i = (pc == NULL); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), (int)i); free(pc); __UHEAP_MARKEND; if (i != true) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :calloc_Test2 //API Tested :calloc //TestCase Description:calloc returns -> NULL // ----------------------------------------------------------------------------- TInt CTestStdlib::calloc_Test2() { __UHEAP_MARK; INFO_PRINTF1(_L("In calloc_Test2L")); //-------------------------- char *pc = (char *)calloc(0, 1); bool i = (pc == NULL); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), (int)i); free(pc); __UHEAP_MARKEND; if (i != true) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :realloc_Test0 //API Tested :realloc //TestCase Description:realloc returns -> pointer to mem locn with old contents //unchanged and the new -unintialized. // ----------------------------------------------------------------------------- TInt CTestStdlib::realloc_Test0() { __UHEAP_MARK; INFO_PRINTF1(_L("In realloc_Test0L")); //-------------------------- int *pint = (int *)calloc(2, sizeof (int) * 2); pint = (int *)realloc(pint, (sizeof (int) * 6) ); if (pint == NULL) { INFO_PRINTF1(_L("realloc failed to allocate memory")); return KErrNoMemory; } //-------------------------- INFO_PRINTF1(_L("{Expected: zeros(4) and some uninitialized values}")); int i = 0; for(i = 0; i < 6; i++) { INFO_PRINTF2(_L(" %d"), pint[i]); } for(i = 0; i < 4; i++) { if (pint[i] != 0) { free(pint); __UHEAP_MARKEND; return KErrGeneral; } } free(pint); __UHEAP_MARKEND; return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :realloc_Test1 //API Tested :realloc //TestCase Description:realloc returns -> pointer to mem locn with old contents //unchanged and the new -unintialized. // ----------------------------------------------------------------------------- TInt CTestStdlib::realloc_Test1() { __UHEAP_MARK; INFO_PRINTF1(_L("In realloc_Test1L")); //-------------------------- int *pint = (int *)calloc(2, sizeof (int) * 2); pint = (int *)realloc(pint, (sizeof (int) ) ); if (pint == NULL) { INFO_PRINTF1(_L("realloc failed to allocate memory")); return KErrNoMemory; } //-------------------------- INFO_PRINTF1(_L("{Expected: zeros}")); int i = 0; for(i = 0; i < 1; i++) { INFO_PRINTF2(_L(" %d"), pint[i]); } for(i = 0; i < 1; i++) { if (pint[i] != 0) { free(pint); __UHEAP_MARKEND; return KErrGeneral; } } free(pint); __UHEAP_MARKEND; return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :realloc_Test2 //API Tested :realloc //TestCase Description:realloc returns -> pointer that could be freed. // ----------------------------------------------------------------------------- TInt CTestStdlib::realloc_Test2() { __UHEAP_MARK; INFO_PRINTF1(_L("In realloc_Test2L")); //-------------------------- int *pint = (int *)calloc(1, sizeof(int) * 3); if (pint == NULL) { INFO_PRINTF1(_L("calloc failed to allocate memory")); return KErrNoMemory; } pint = (int *)realloc(pint, 0); //-------------------------- INFO_PRINTF2(_L("{Expected: some int value} %d"), pint[0]); free(pint); __UHEAP_MARKEND; return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :realloc_Test3 //API Tested :realloc //TestCase Description:realloc returns -> pointer to mem locn unintialized. // ----------------------------------------------------------------------------- TInt CTestStdlib::realloc_Test3() { __UHEAP_MARK; INFO_PRINTF1(_L("In realloc_Test3L")); //-------------------------- int *pint = (int *)realloc(NULL, ( sizeof(int) * 2 ) ); if (pint == NULL) { INFO_PRINTF1(_L("realloc failed to allocate memory")); return KErrNoMemory; } //-------------------------- INFO_PRINTF1(_L("{Expected: some int values}")); int i = 0; for(i = 0; i < 2; i++) { INFO_PRINTF2(_L(" %d"), pint[i]); } free(pint); __UHEAP_MARKEND; return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :realloc_Test4 //API Tested :realloc //TestCase Description:realloc returns -> NULL but leaves the old mem block //unchanged. // ----------------------------------------------------------------------------- TInt CTestStdlib::realloc_Test4() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In realloc_Test4L")); //-------------------------- int *pint = (int *)calloc(1, sizeof(int) * 3); if (pint == NULL) { INFO_PRINTF1(_L("calloc failed to allocate memory")); return KErrNoMemory; } int *pint_realloc = (int *)realloc(pint, 1024 * 1024); bool b = (pint_realloc == NULL); //-------------------------- INFO_PRINTF2(_L("{Expected: zeros, 1} %d"), (int)b); int i = 0; for(i = 0; i < 3; i++) { INFO_PRINTF2(_L(" %d"), pint[i]); } for(i = 0; i < 3; i++) { if (pint[i] != 0) { ret = KErrGeneral; } } if (b != 1) { ret = KErrGeneral; } free(pint); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :free_Test0 //API Tested :free //TestCase Description:free returns -> nothing //(check the total available heap space, allocate a chunk of mem check that //the available heap space is reduced, free the memory and check that the //the available heap space is equal to what it was before the memory was //allocated and freed) // ----------------------------------------------------------------------------- TInt CTestStdlib::free_Test0() { INFO_PRINTF1(_L("In free_Test0L")); //-------------------------- RHeap& heap_handle = User::Heap(); TInt largest_free_block; TInt heap_available1 = heap_handle.Available(largest_free_block); int *pint = (int *)malloc(200); TInt heap_available2 = heap_handle.Available(largest_free_block); if(heap_available2 >= heap_available1) { INFO_PRINTF3(_L("{heap_avail1 = %d, heap_avail2 = %d}"), heap_available1, heap_available2); INFO_PRINTF1(_L("available memory is not as expected after malloc...\ free not tested!")); return KErrGeneral; } free(pint); TInt heap_available3 = heap_handle.Available(largest_free_block); if(heap_available3 != heap_available1) { INFO_PRINTF3(_L("{heap_avail1 = %d, heap_avail3 = %d}"), heap_available1, heap_available3); INFO_PRINTF1(_L("available memory is not as expected after free!")); return KErrGeneral; } //-------------------------- INFO_PRINTF1(_L("{Expected: heapavail1 should be equal to heapavail3}")); INFO_PRINTF4(_L("heap_avail1 = %d, heap_avail2 = %d, heap_avail3 = %d"), heap_available1, heap_available2, heap_available3); return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :getenv_Test0 //API Tested :getenv //TestCase Description:getenv returns -> NULL when the input env variable //doesn't exist // ----------------------------------------------------------------------------- TInt CTestStdlib::getenv_Test0() { INFO_PRINTF1(_L("In getenv_Test0L")); //-------------------------- unsetenv("path"); char * aenv = getenv("path"); bool b = (aenv == NULL); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), (int)b); if (b != true) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :getenv_Test1 //API Tested :getenv //TestCase Description:getenv returns -> the value of the env variable when //it does exist // ----------------------------------------------------------------------------- TInt CTestStdlib::getenv_Test1() { INFO_PRINTF1(_L("In getenv_Test1")); //-------------------------- setenv("path", ".;/c:/bin;", 1); char *psc = getenv("path"); char *ps = NULL; if (psc != NULL) { ps = (char *)malloc( strlen(psc) + 1 ); if (ps == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrNoMemory; } strcpy(ps, psc); } //-------------------------- INFO_PRINTF1(_L("{Expected: \".;/c:/bin;\"}")); int i = 0; for (i = 0; ps[i] != '\0'; i++) { INFO_PRINTF2(_L(" %c"), ps[i]); } free(ps); if ( strcmp(psc, ".;/c:/bin;") != 0 ) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :setenv_Test0 //API Tested :setenv //TestCase Description:setenv returns -> 0 (successfully set the non-existing //env variable) // ----------------------------------------------------------------------------- TInt CTestStdlib::setenv_Test0() { INFO_PRINTF1(_L("In setenv_Test0L")); //-------------------------- unsetenv("home"); int iret = setenv("home", "/home", 0); char *psc = getenv("home"); char *ps = NULL; if (psc != NULL) { ps = (char *)malloc( strlen(psc) + 1 ); if (ps == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrNoMemory; } strcpy(ps, psc); } //-------------------------- INFO_PRINTF2(_L("{Expected: 0, \"/home\"} %d"), iret); int i = 0; for (i = 0; ps[i] != '\0'; i++) { INFO_PRINTF2(_L(" %c"), ps[i]); } free(ps); if ( strcmp(psc, "/home") != 0 || iret != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :setenv_Test1 //API Tested :setenv //TestCase Description:setenv returns -> 0 (succesfully set the existing env //var by overwriting it) // ----------------------------------------------------------------------------- TInt CTestStdlib::setenv_Test1() { INFO_PRINTF1(_L("In setenv_Test1L")); //-------------------------- setenv("home", "/home", 1); int iret2 = setenv("home", "/check", 1); char *psc = getenv("home"); char *ps = NULL; if (psc != NULL) { ps = (char *)malloc( strlen(psc) + 1 ); if (ps == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrNoMemory; } strcpy(ps, psc); } //-------------------------- INFO_PRINTF2(_L("{Expected: 0, \"/check\"} %d"), iret2); int i = 0; for (i = 0; ps[i] != '\0'; i++) { INFO_PRINTF2(_L(" %c"), ps[i]); } free(ps); if ( strcmp(psc, "/check") != 0 || iret2 != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :setenv_Test2 //API Tested :setenv //TestCase Description:setenv returns -> 0 (without overwriting the existing //env var) // ----------------------------------------------------------------------------- TInt CTestStdlib::setenv_Test2() { INFO_PRINTF1(_L("In setenv_Test2L")); //-------------------------- setenv("home", "/home", 1); int iret2 = setenv("home", "/check", 0); char *psc = getenv("home"); char *ps = NULL; if (psc != NULL) { ps = (char *)malloc( strlen(psc) + 1 ); if (ps == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrNoMemory; } strcpy(ps, psc); } //-------------------------- INFO_PRINTF2(_L("{Expected: 0, \"/home\"} %d"), iret2); int i = 0; for (i = 0; ps[i] != '\0'; i++) { INFO_PRINTF2(_L(" %c"), ps[i]); } free(ps); if ( strcmp(psc, "/home") != 0 || iret2 != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :setenv_Test3 //API Tested :setenv //TestCase Description:setenv returns -> -1 (invalid argument) // ----------------------------------------------------------------------------- TInt CTestStdlib::setenv_Test3() { TInt ret = KErrNone; INFO_PRINTF1(_L("In setenv_Test3L")); //-------------------------- setenv("home", "/home", 1); errno = 0; int ret1 = setenv(NULL, "/some", 1); if (errno != EINVAL) { INFO_PRINTF1(_L("{setenv1: errno not set to EINVAL")); ret = KErrGeneral; } char *psc1 = getenv("home"); errno = 0; int ret2 = setenv("", "/some", 1); if (errno != EINVAL) { INFO_PRINTF1(_L("{setenv2: errno not set to EINVAL")); ret = KErrGeneral; } char *psc2 = getenv("home"); errno = 0; int ret3 = setenv("hom=e", "/some", 1); if (errno != EINVAL) { INFO_PRINTF1(_L("{setenv3: errno not set to EINVAL")); ret = KErrGeneral; } char *psc3 = getenv("home"); //-------------------------- INFO_PRINTF2(_L("{Expected: -1, \"/home\"} %d"), ret1); INFO_PRINTF2(_L("{Expected: -1, \"/home\"} %d"), ret2); INFO_PRINTF2(_L("{Expected: -1, \"/home\"} %d"), ret3); if ( strcmp(psc1, "/home") != 0 || ret1 != -1 || strcmp(psc2, "/home") != 0 || ret2 != -1 || strcmp(psc3, "/home") != 0 || ret3 != -1 ) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :setenv_Test4 //API Tested :putenv //TestCase Description:setenv returns -> -1 (no sufficient memory) // ----------------------------------------------------------------------------- TInt CTestStdlib::setenv_Test4() { TInt ret = KErrNone; INFO_PRINTF1(_L("In setenv_Test4L")); #ifdef _DEBUG //-------------------------- unsetenv("noexist"); RHeap *heap_handle = Backend()->Heap(); heap_handle->__DbgMarkStart(); heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgSetAllocFail(RAllocator::EFailNext, 1); int iret = setenv("noexist", "/check", 1); INFO_PRINTF2(_L("setenv errno: %d"), errno); if (errno != ENOMEM) { INFO_PRINTF1(_L("{putenv: errno not set to ENOMEM")); ret = KErrGeneral; } heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgMarkEnd(0); //-------------------------- INFO_PRINTF2(_L("{Expected: -1} %d"), iret); if ( iret != -1 ) { ret = KErrGeneral; } #else INFO_PRINTF1(_L("This test case executes all code only for DEBUG build \ as it can simulate memory failure only in DEBUG build")); #endif //_DEBUG return ret; } // ----------------------------------------------------------------------------- //Function Name :putenv_Test0 //API Tested :putenv //TestCase Description:putenv returns -> 0 (successfully set the non-existing //env variable) // ----------------------------------------------------------------------------- TInt CTestStdlib::putenv_Test0() { INFO_PRINTF1(_L("In putenv_Test0L")); //-------------------------- unsetenv("home"); int iret = putenv("home=/home/xyz"); char *psc = getenv("home"); //-------------------------- INFO_PRINTF2(_L("{Expected: 0, \"/home/xyz\"} %d"), iret); if ( strcmp(psc, "/home/xyz") != 0 || iret != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :putenv_Test1 //API Tested :putenv //TestCase Description:putenv returns -> 0 (successfully set the existing //env variable) // ----------------------------------------------------------------------------- TInt CTestStdlib::putenv_Test1() { INFO_PRINTF1(_L("In putenv_Test1L")); //-------------------------- int iret1 = setenv("home", "/check", 1); int iret = putenv("home=/home/xyz/chk"); char *psc = getenv("home"); //-------------------------- INFO_PRINTF2(_L("{Expected: 0, \"/home/xyz/chk\"} %d"), iret); if ( strcmp(psc, "/home/xyz/chk") != 0 || iret != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :putenv_Test2 //API Tested :putenv //TestCase Description:putenv returns -> -1 (invalid argument) // ----------------------------------------------------------------------------- TInt CTestStdlib::putenv_Test2() { TInt ret = KErrNone; INFO_PRINTF1(_L("In putenv_Test2L")); //-------------------------- int iret1 = setenv("home", "/check", 1); errno = 0; int iret = putenv("home/home/xyz/chk"); if (errno != EINVAL) { INFO_PRINTF1(_L("{putenv: errno not set to EINVAL")); ret = KErrGeneral; } char *psc = getenv("home"); //-------------------------- INFO_PRINTF2(_L("{Expected: -1, \"/check\"} %d"), iret); if ( strcmp(psc, "/check") != 0 || iret != -1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :putenv_Test3 //API Tested :putenv //TestCase Description:putenv returns -> -1 (invalid argument) // ----------------------------------------------------------------------------- TInt CTestStdlib::putenv_Test3() { TInt ret = KErrNone; INFO_PRINTF1(_L("In putenv_Test3L")); errno = 0; #ifdef _DEBUG //-------------------------- int iret = setenv("home", "/check", 1); errno = 0; //1st allocation failure //__UHEAP_MARK; //__UHEAP_RESET; //__UHEAP_FAILNEXT(1); RHeap *heap_handle = Backend()->Heap(); heap_handle->__DbgMarkStart(); heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgSetAllocFail(RAllocator::EFailNext, 1); int iret1 = putenv("home=/home/xyz/chk"); if (errno != ENOMEM) { INFO_PRINTF1(_L("{putenv: errno not set to ENOMEM")); ret = KErrGeneral; } errno = 0; //2nd allocation failure //__UHEAP_FAILNEXT(2); heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgSetAllocFail(RAllocator::EFailNext, 1); int iret2 = putenv("home=/home/xyz/chk"); if (errno != ENOMEM) { INFO_PRINTF1(_L("{putenv: errno not set to ENOMEM")); ret = KErrGeneral; } heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgMarkEnd(0); //__UHEAP_RESET; //__UHEAP_MARKEND; char *psc = getenv("home"); //-------------------------- INFO_PRINTF3(_L("{Expected: -1, -1, \"/check\"} %d"), iret1, iret2); if ( strcmp(psc, "/check") != 0 || iret1 != -1 || iret2 != -1 ) { ret = KErrGeneral; } #else INFO_PRINTF1(_L("This test case executes all code only for DEBUG build \ as it can simulate memory failure only in DEBUG build")); #endif //_DEBUG return ret; } // ----------------------------------------------------------------------------- //Function Name :unsetenv_Test0 //API Tested :unsetenv //TestCase Description:unsetenv returns -> nothing // ----------------------------------------------------------------------------- TInt CTestStdlib::unsetenv_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In unsetenv_Test0L")); //-------------------------- setenv("home", "/home", 1); char *psc1 = getenv("home"); char *ps1 = NULL; if (psc1 != NULL) { ps1 = (char *)malloc( strlen(psc1) + 1 ); if (ps1 == NULL) { INFO_PRINTF1(_L("malloc failed to allocate memory")); return KErrNoMemory; } strcpy(ps1, psc1); } if ( strcmp(psc1, "/home") != 0 ) { ret = KErrGeneral; } unsetenv("home"); char *psc2 = getenv("home"); bool b = (psc2 == NULL); if (b != true) { ret = KErrGeneral; } //-------------------------- INFO_PRINTF1(_L("{Expected: \"/home\", 1}")); int i = 0; for(i = 0; ps1[i] != '\0'; i++) { INFO_PRINTF2(_L(" %c"), ps1[i]); } INFO_PRINTF2(_L(" %d"), (int)b); free(ps1); return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test0 //API Tested :system //TestCase Description: system returns -> 1 (the exit code from the called //executable) when the input is a valid executable name with a valid path. // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test0L")); //-------------------------- TPtrC scfgarg; int exitcode; _LIT( Kscfgarg, "scfgarg" ); TBool res = GetStringFromConfig(ConfigSection(), Kscfgarg, scfgarg ); if(!res) { INFO_PRINTF1(_L("unable to read the parameters from the cfg file!")); return KErrGeneral; } _LIT( Kexitcode, "exitcode" ); res = GetIntFromConfig(ConfigSection(), Kexitcode, exitcode); if(!res) { INFO_PRINTF1(_L("unable to read the parameters from the cfg file!")); return KErrGeneral; } TBuf8<100> string; string.Copy(scfgarg); char* command = (char*) string.Ptr(); command[string.Length()]='\0'; int i = system(command); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), i); if (i != exitcode) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test1 //API Tested :system //TestCase Description:system returns -> -1 (command not found) when the //input command is not supported // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test1() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test1L")); int i = system("date"); INFO_PRINTF2(_L("{Expected: -1} %d"), i); if (i != -1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test2 //API Tested :system //TestCase Description:system returns -> 1 (system is supported) when the //input is NULL // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test2() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test2L")); int i = system(NULL); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), i); if (i != 1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test3 //API Tested :system //TestCase Description:system returns -> 1 (exit code of the executable) //when the valid input command has leading white spaces. // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test3() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test3L")); TPtrC scfgarg; int exitcode; _LIT( Kscfgarg, "scfgarg" ); TBool res = GetStringFromConfig(ConfigSection(), Kscfgarg, scfgarg ); if(!res) { INFO_PRINTF1(_L("unable to read the parameters from the cfg file!")); return KErrGeneral; } _LIT( Kexitcode, "exitcode" ); res = GetIntFromConfig(ConfigSection(), Kexitcode, exitcode); if(!res) { INFO_PRINTF1(_L("unable to read the parameters from the cfg file!")); return KErrGeneral; } TBuf8<100> string; string.Copy(scfgarg); char command[64] = " "; char* comname = (char*) string.Ptr(); comname[string.Length()]='\0'; strcat(command, comname); int i = system(command); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), i); if (i != exitcode) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test4 //API Tested :system //TestCase Description:system returns -> -1 (command not found) when the //input command has a tab character. // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test4() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test4L")); int i = system("c:\\sys\\bin\\tstdlib_hello\\tworld.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: -1} %d"), i); if (i != -1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test5 //API Tested :system //TestCase Description:system returns -> -1 (command not found) when the input //execuatble doesn't exist. // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test5() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test5L")); int i = system("c:\\tstdlib_noexist.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: -1} %d"), i); if (i != -1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :system_Test6 //API Tested :system //TestCase Description:system returns -> -1 (command not found) when the input //execuatble doesn't exist. // ----------------------------------------------------------------------------- TInt CTestStdlib::system_Test6() { TInt ret = KErrNone; INFO_PRINTF1(_L("In system_Test6L")); int i = system("c:\\sys\\bin\\tstdlib_testsystem.exe a b c"); //-------------------------- INFO_PRINTF2(_L("{Expected: 4} %d"), i); if (i != 4) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :abort_Test0 //API Tested :abort //TestCase Description:abort never returns //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::abort_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In abort_Test0L")); int i = system("c:\\sys\\bin\\tstdlib_testabort.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: 1} %d"), i); if (i != 1) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :exit_Test0 //API Tested :exit //TestCase Description:exit never returns but we are having exit() call in a //stand alone application that we call using the API system(). so, we expect //that the system's return value is same as the exitcode that we used in the //application that is made to exit. also, we expect the functions registered //with atexit to be called in the reverse order of registration before the //application exits. //input --> exitcode is 1 {exit(1)} // ----------------------------------------------------------------------------- TInt CTestStdlib::exit_Test0() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In exit_Test0L")); int i = system("c:\\sys\\bin\\tstdlib_testexit.exe"); char buf1[64]; char buf2[64]; FILE *fp = fopen("c:\\some.txt", "r"); if(fp) { fscanf(fp, "%s", buf1); fgetc(fp); //skip the space fscanf(fp, "%s", buf2); } TBuf8<50> tempString1((TUint8 *)&buf1); TBuf8<50> tempString2((TUint8 *)&buf2); TBuf<50> displayString1; TBuf<50> displayString2; displayString1.Copy(tempString1); displayString2.Copy(tempString2); INFO_PRINTF3(_L("{Executing exitfunc3.: %S %S}"), &displayString1, &displayString2); strcat(buf1, " "); strcat(buf1, buf2); if(strcmp(buf1, "Executing exitfunc3.") != 0) { ret = KErrGeneral; } if(fp) { fgetc(fp); //skip the newline fscanf(fp, "%s", buf1); fgetc(fp); //skip the space fscanf(fp, "%s", buf2); } tempString1 = (TUint8 *)buf1; tempString2 = (TUint8 *)buf2; displayString1.Copy(tempString1); displayString2.Copy(tempString2); INFO_PRINTF3(_L("{Executing exitfunc2.: %S %S}"), &displayString1, &displayString2); strcat(buf1, " "); strcat(buf1, buf2); if(strcmp(buf1, "Executing exitfunc2.") != 0) { ret = KErrGeneral; } if(fp) { fgetc(fp); //skip the newline fscanf(fp, "%s", buf1); fgetc(fp); //skip the space fscanf(fp, "%s", buf2); } tempString1 = (TUint8 *)buf1; tempString2 = (TUint8 *)buf2; displayString1.Copy(tempString1); displayString2.Copy(tempString2); INFO_PRINTF3(_L("{Executing exitfunc1.: %S %S}"), &displayString1, &displayString2); strcat(buf1, " "); strcat(buf1, buf2); if(strcmp(buf1, "Executing exitfunc1.") != 0) { ret = KErrGeneral; } if(fp) { fclose(fp); } if (i != 1) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :exit_Test1 //API Tested :exit //TestCase Description:exit never returns but we are having exit() call in a //stand alone application that we call using the API system(). so, we expect //that the system's return value is same as the exitcode that we used in the //application that is made to exit. we don't have any functions registered with //atexit for this case. //input --> exitcode is 3 {exit(3)} // ----------------------------------------------------------------------------- TInt CTestStdlib::exit_Test1() { TInt ret = KErrNone; INFO_PRINTF1(_L("In exit_Test1L")); int i = system("c:\\sys\\bin\\tstdlib_testexitec.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: 3} %d"), i); if (i != 3) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :_exitE_Test0 //API Tested :exit //TestCase Description:exit never returns but we are having exit() call in a //stand alone application that we call using the API system(). so, we expect //that the system's return value is same as the exitcode that we used in the //application that is made to exit. we don't have any functions registered with //atexit for this case. //input --> exitcode is 3 {exit(3)} // ----------------------------------------------------------------------------- TInt CTestStdlib::_exitE_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In _exitE_Test0L")); int i = system("c:\\sys\\bin\\tstdlib_test_exitE.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: 5} %d"), i); if (i != 5) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :_exit_Test0 //API Tested :exit //TestCase Description:exit never returns but we are having exit() call in a //stand alone application that we call using the API system(). so, we expect //that the system's return value is same as the exitcode that we used in the //application that is made to exit. we don't have any functions registered with //atexit for this case. //input --> exitcode is 3 {exit(3)} // ----------------------------------------------------------------------------- TInt CTestStdlib::_exit_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In _exit_Test0L")); int i = system("c:\\sys\\bin\\tstdlib_test_exit.exe"); //-------------------------- INFO_PRINTF2(_L("{Expected: 6} %d"), i); if (i != 6) { ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :atexit_Test0 //API Tested :atexit //TestCase Description:atexit returns non-zero on registration failure //atexit fails when malloc fails! as the first 32 funs are allocated statically //and the rest, dynamically. //input --> function pointer to an exit function. //This test case executes all code only for DEBUG build as it can simulate //memory failure only in DEBUG build // ----------------------------------------------------------------------------- TInt CTestStdlib::atexit_Test0() { TInt ret = KErrNone; INFO_PRINTF1(_L("In atexit_Test0L")); #ifdef _DEBUG //call some stdlib API to make sure that reent structure will be //created successfully char dummy[20]; sprintf(dummy, "%s", "Dummy"); vfuncp func_table[] = { exitfunc0, exitfunc1, exitfunc2, exitfunc3, exitfunc4, exitfunc5, exitfunc6, exitfunc7, exitfunc8, exitfunc9, exitfunc10, exitfunc11, exitfunc12, exitfunc13, exitfunc14, exitfunc15, exitfunc16, exitfunc17, exitfunc18, exitfunc19, exitfunc20, exitfunc21, exitfunc22, exitfunc23, exitfunc24, exitfunc25, exitfunc26, exitfunc27, exitfunc28, exitfunc29, exitfunc30, exitfunc31, exitfunc32 }; int i = 0, atexitret1 = 0, atexitret2 = 0; int count = 0; int numfuncs = sizeof(func_table)/sizeof(vfuncp); // loop until no more can be added while(count < LEAST_ATEXIT && (atexitret1 = atexit(func_table[3])) >= 0) { INFO_PRINTF2(_L("Registered exitfunc%d with atexit()\n"), i); count++; i = (i+1) % numfuncs; } INFO_PRINTF2(_L("funcs reg with atexit --> {Expected: 32} %d"), count); INFO_PRINTF2(_L("{Expected: zero} %d"), atexitret1); if(KErrNone == atexitret1) { RHeap *heap_handle = Backend()->Heap(); //Make sure that u will be calling 33rd exit function if( (atexitret2 = atexit(func_table[numfuncs])) != -1) { INFO_PRINTF1(_L("Registration of the 33rd exit function didn't fail")); ret = KErrNone; } heap_handle->__DbgSetAllocFail(RAllocator::ENone, 1); heap_handle->__DbgMarkEnd(0); } else { ERR_PRINTF1(_L("Registration of one of the 32 exit functions failed")); ret = KErrGeneral; } INFO_PRINTF2(_L("{Expected: non-zero} %d"), atexitret2); #else INFO_PRINTF1(_L("This test case executes all code only for DEBUG build \ as it can simulate memory failure only in DEBUG build")); #endif //_DEBUG return ret; } // ----------------------------------------------------------------------------- //Function Name :atexit_Test1 //API Tested :atexit //TestCase Description:atexit returns 0 on successful registration //input --> function pointer to an exit function. // ----------------------------------------------------------------------------- TInt CTestStdlib::atexit_Test1() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In atexit_Test1L")); vfuncp func_table[] = { exitfunc0, exitfunc1, exitfunc2, exitfunc3, exitfunc4, exitfunc5, exitfunc6, exitfunc7, exitfunc8, exitfunc9, exitfunc10, exitfunc11, exitfunc12, exitfunc13, exitfunc14, exitfunc15, exitfunc16, exitfunc17, exitfunc18, exitfunc19, exitfunc20, exitfunc21, exitfunc22, exitfunc23, exitfunc24, exitfunc25, exitfunc26, exitfunc27, exitfunc28, exitfunc29, exitfunc30, exitfunc31 }; int i = 0, atexitret1 = 0; int count = 0; int numfuncs = sizeof(func_table)/sizeof(vfuncp); // loop until no more can be added while(count < LEAST_ATEXIT && (atexitret1 = atexit(func_table[i])) >= 0) { INFO_PRINTF2(_L("Registered exitfunc%d with atexit()\n"), i); count++; i = (i+1) % numfuncs; } INFO_PRINTF2(_L("funcs reg with atexit --> {Expected: 32} %d"), count); if (atexitret1 != 0 ) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :abs_neg_max //API Tested :abs //TestCase Description: abs(x) returns the absolute value of x. // This case finds the absolute value of the maximum negative // value in the acceptable range. And compares result with // the expected value(i.e. INT_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::abs_neg_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In abs(max_negative_value)")); int j=abs(INT_MIN+1); INFO_PRINTF1(_L("abs(maximum negative value acceptable)")); INFO_PRINTF2(_L("abs(INT_MIN+1)-> %d"),j); __UHEAP_MARKEND; if(j==INT_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :abs_good_param //API Tested :abs //TD TestCase Number :1_11_2_1213 //TD TestCase Identifier :1213 //TestCase Description: abs(x) returns the absolute value of x. // This case finds the absolute value of the some integer // value in the acceptable range passed through parameter. // And compares result with the expected value which is // also among the parameters. //Entry Into Source: // ----------------------------------------------------------------------------- TInt CTestStdlib::abs_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In abs(good_parameters)")); int intVal1=0, intVal2=0; _LIT( KintVal1, "intVal1" ); TBool res1 = GetIntFromConfig(ConfigSection(), KintVal1, intVal1); _LIT( KintVal2, "intVal2" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal2, intVal2); if (res1 && res2) { INFO_PRINTF3(_L("Tstdlib: Input->%d Expected-> %d"), intVal1, intVal2); __UHEAP_MARK; int j=abs(intVal1); __UHEAP_MARKEND; INFO_PRINTF3(_L("abs(%d)-> %d"), intVal1, j); INFO_PRINTF2(_L("Expected-> %d"), intVal2); if(j!=intVal2) { return KErrGeneral; } else { return KErrNone; } } else { INFO_PRINTF1(_L("Expected Param: <integer-input> <expected-value>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :abs_pos_max //API Tested :abs //TestCase Description: abs(x) returns the absolute value of x // This case finds the absolute value of the maximum positive // value in the acceptable range using abs().And compares result with // the expected value (i.e. INT_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::abs_pos_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In abs(+ve_maximum)")); INFO_PRINTF1(_L("In abs(+ve_maximum)")); int j=abs(INT_MAX); INFO_PRINTF1(_L("abs(maximum positive value acceptable)")); INFO_PRINTF2(_L("abs(INT_MAX)-> %d"), j); __UHEAP_MARKEND; if(j==INT_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :labs_neg_max //API Tested :labs //TestCase Description: labs(x) returns the absolute value of x // This case finds the absolute value of the maximum negative // value in the acceptable range. And compares result with // the expected value (i.e. LONG_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::labs_neg_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In labs(max_negative_value)")); long int j=labs(LONG_MIN+1); INFO_PRINTF1(_L("labs(maximum negative value acceptable)")); INFO_PRINTF2(_L("labs(LONG_MIN+1)-> %d"),j); __UHEAP_MARKEND; if(j==LONG_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :labs_good_param //API Tested :labs //TestCase Description: labs(x) returns the absolute value of x // This case finds the absolute value of the some integer // value in the acceptable range passed through parameter. // And compares result with the expected value which is // also among the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::labs_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In labs(good_parameters)")); int intVal1=0, intVal2=0; _LIT( KintVal1, "intVal1" ); TBool res1 = GetIntFromConfig(ConfigSection(), KintVal1, intVal1); _LIT( KintVal2, "intVal2" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal2, intVal2); if (res1 && res2) { INFO_PRINTF3(_L("Tstdlib: Input->%d Expected-> %d"), intVal1, intVal2); __UHEAP_MARK; long int j=labs(intVal1); __UHEAP_MARKEND; INFO_PRINTF3(_L("labs(%d)-> %d"), intVal1, j); INFO_PRINTF2(_L("Expected-> %d"), intVal2); if(j!=intVal2) { return KErrGeneral; } else { return KErrNone; } } else { INFO_PRINTF1(_L("Expected Param: <integer-input> <expected-value>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :labs_pos_max //API Tested :labs //TestCase Description: labs(x) returns the absolute value of x // This case finds the absolute value of the maximum positive // value in the acceptable range using abs().And compares result with // the expected value (ie. LONG_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::labs_pos_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In labs(+ve_maximum)") ); long int j=labs(LONG_MAX); INFO_PRINTF1(_L("labs(maximum positive value acceptable)")); INFO_PRINTF2(_L("labs(LONG_MAX)-> %d"), j); __UHEAP_MARKEND; if(j==LONG_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :llabs_pos_max //API Tested :llabs //TestCase Description: llabs(x) returns the absolute value of x // This case finds the absolute value of the maximum positive // value in the acceptable range using abs().And compares result with // the expected value (ie. LLONG_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::llabs_pos_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In llabs(+ve_maximum)") ); long long j=llabs(LLONG_MAX); INFO_PRINTF1(_L("llabs(maximum positive value acceptable)")); INFO_PRINTF2(_L("llabs(LLONG_MAX)-> %ld"), j); __UHEAP_MARKEND; if(j==LLONG_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :llabs_neg_max //API Tested :llabs //TestCase Description: llabs(x) returns the absolute value of x // This case finds the absolute value of the maximum negative // value in the acceptable range. And compares result with // the expected value (i.e. LLONG_MAX). // ----------------------------------------------------------------------------- TInt CTestStdlib::llabs_neg_max( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In labs(max_negative_value)")); long long j=llabs(LLONG_MIN+1); INFO_PRINTF1(_L("llabs(maximum negative value acceptable)")); INFO_PRINTF2(_L("llabs(LLONG_MIN+1)-> %ld"),j); __UHEAP_MARKEND; if(j==LLONG_MAX) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :llabs_good_param //API Tested :llabs //TestCase Description: llabs(x) returns the absolute value of x // This case finds the absolute value of the some integer // value in the acceptable range passed through parameter. // And compares result with the expected value which is // also among the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::llabs_good_param( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In llabs(good_parameters)") ); long long int x = 4294967396; long long int y = 5343546758; long long int i = llabs(x); long long int j = llabs(-y); INFO_PRINTF3(_L("Expected-> %ld, %ld"), x, y); __UHEAP_MARKEND; if((i != x) || (j != y)) { return KErrGeneral; } else { return KErrNone; } } // ----------------------------------------------------------------------------- //Function Name :atoi_null_string //API Tested :atoi //TestCase Description: // atoi(x) returns the converted value (ascii to int) // if the value can be represented. // This case finds the conversion of NULL string. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::atoi_null_string( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In atoi(NULL string)") ); int i=atoi(""); INFO_PRINTF2(_L("atoi(\"\")-> %d"), i); __UHEAP_MARKEND; if(i==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :atoi_good_param //API Tested :atoi //TestCase Description: // atoi(x) returns the converted value (ascii to int) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atoi_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In atoi(good_parameters)")); int intVal = 0; TPtrC string; _LIT( Kstring, "string" ); TBool res1 = GetStringFromConfig(ConfigSection(), Kstring, string ); _LIT( KintVal, "intVal" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal, intVal); if(res1 && res2 ) { INFO_PRINTF3(_L("Tstdlib: Input-> %S: Expected-> %d"), &string, intVal ); TBuf8<100> buf; buf.Copy(string); char* ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; __UHEAP_MARK; int atoiret=atoi(ptr); __UHEAP_MARKEND; if(atoiret!=intVal) { INFO_PRINTF3(_L("atoi(\"%S\")-> %d"),&string, atoiret); INFO_PRINTF2(_L("%d was the expected output"), intVal); return KErrGeneral; } else { INFO_PRINTF3(_L("atoi(\"%S\")-> %d"),&string, atoiret); INFO_PRINTF2(_L("Expected -> %d "), intVal); return KErrNone; } } else { INFO_PRINTF1(_L("Expected Parameters in the configuration file->")); INFO_PRINTF1(_L("<input_string> <expected_output>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :atof_null_string //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double), // if the value can be represented. // This case finds the conversion of NULL string. // And compares result with 0.000000,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_null_string( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In atof(NULL_string)") ); double i=atof(""); INFO_PRINTF2(_L("atof(\"\")-> %f"), i); __UHEAP_MARKEND; if(i==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :atof_pos_floatnum //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "0.76786"and compares the result with the expected // value which is the second member in the structure // as in the test case below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_pos_floatnum( ) { INFO_PRINTF1(_L("Tstdlib: In atof(+ve_float_num_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"0.76786",0.767860}, {"1.787800",1.787800}, {"67.78",67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_neg_floatnum //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "-0.76786" (i.e negative float no.s)and compares the // result with the expected value which is the second // member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_neg_floatnum( ) { INFO_PRINTF1(_L("Tstdlib:atof(-ve_float_num_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"-0.76786",-0.767860}, {"-75478.987987",-75478.987987}, {"-67.78",-67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_alpha //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "abcdef" (i.e alphanumeric input)and compares the // result with the expected value which is the second // member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_alpha( ) { INFO_PRINTF1(_L("Tstdlib: atof(alphanumeric_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"fgdsfg",0.000000}, {"abcd",0.000000}, {"efgh",0.000000}, }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_alpha_floatnum //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "abcdef789.9" (i.e combination of alphanumeric and float no.s) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_alpha_floatnum( ) { INFO_PRINTF1(_L("Tstdlib: atof(alpha_floatnum_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"fgdsfg4.56",0.000000}, {"abcd5656.8",0.000000}, {"efgh76786.78790",0.000000}, }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_pos_floatnum_alpha //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "789.9abcdef" (i.e combination of alphanumeric and float no.s) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_pos_floatnum_alpha( ) { INFO_PRINTF1(_L("Tstdlib: atof(+ve_float_num_alpha_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"+54.4ghds",54.4}, {"75478.987987uff",75478.987987}, {"67.78gtye",67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_neg_floatnum_alpha //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "-789.9abcdef" (i.e combination of alphanumeric and float no.s) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_neg_floatnum_alpha( ) { INFO_PRINTF1(_L("Tstdlib: atof(-ve_float_num_alpha_string)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"-0.76786fgsd",-0.767860}, {"-75478.987987hguyh",-75478.987987}, {"-67.78hihru",-67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_leading_zero //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "000000789.9" (i.e float no. string with leading zeroes) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_leading_zero( ) { INFO_PRINTF1(_L("Tstdlib: atof(string_leading zeroes)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"+000000765.787",765.787000}, {"+00075478.987987",75478.987987}, {"000000067.78",67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_neg_leading_zero //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "-000000789.9" (i.e -ve float no. string with leading zeroes) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_neg_leading_zero( ) { INFO_PRINTF1(_L("Tstdlib: atof(string_-ve_leading zeroes)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"-000000765.787",-765.787000}, {"-00075478.987987",-75478.987987}, {"-000000067.78",-67.780000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_pos_floatnum_pos_expo //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "8798e3" (i.e +ve float no. string in exponential(+ve) form) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_pos_floatnum_pos_expo( ) { INFO_PRINTF1(_L("Tstdlib: atof(+ve_floatnum_+ve_expo)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"+9e4", 90000.000000}, {"86778E2",8677800.000000}, {"67e3",67000.000000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_neg_floatnum_pos_expo //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "-8798e3" (i.e -ve float no. string in exponential(+ve) form) // and compares the result with the expected value which is // ---------------------------------------------------------------------------- TInt CTestStdlib::atof_neg_floatnum_pos_expo( ) { INFO_PRINTF1(_L("Tstdlib: atof(-ve_floatnum_+ve_expo)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"-9e4", -90000.000000}, {"-86778E2",-8677800.000000}, {"-67e3",-67000.000000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_pos_floatnum_neg_expo //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "8798e-3" (i.e +ve float no. string in exponential(-ve) form) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_pos_floatnum_neg_expo( ) { INFO_PRINTF1(_L("Tstdlib: atof(+ve_floatnum_-ve_expo)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"9e-4", 0.000900}, {"86778E-2",867.780000}, {"67e-3",0.067000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atof_neg_floatnum_neg_expo //API Tested :atof //TestCase Description: // atof(x) returns the converted value (ascii to double) // if the value can be represented. // This case finds the conversion of input strings like // "-8798e-3" (i.e -ve float no. string in exponential(-ve) form) // and compares the result with the expected value which is // the second member in the structure as in the testcase below. // ----------------------------------------------------------------------------- TInt CTestStdlib::atof_neg_floatnum_neg_expo( ) { INFO_PRINTF1(_L("Tstdlib: atof(-ve_floatnum_-ve_expo)")); struct test_neg_float { char* float_string; double doubleVal; }; struct test_neg_float test[3]= { {"-9e-4", -0.000900}, {"-86778E-2",-867.780000}, {"-67e-3",-0.067000} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; double ret = atof(test[i].float_string); __UHEAP_MARKEND; INFO_PRINTF3(_L("atof(\"%lf\")-> %lf"),test[i].doubleVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].doubleVal); if( ret != test[i].doubleVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atol_null_string //API Tested :atol //TestCase Description: // atol(x) returns the converted value (ascii to long) // if the value can be represented. // This case finds the conversion of NULL string. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::atol_null_string( ) { __UHEAP_MARK; INFO_PRINTF1(_L("Tstdlib: In atol(NULL string)") ); int i=atol(""); INFO_PRINTF2(_L("atol(\"\")-> %d"), i); __UHEAP_MARKEND; if(i==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :atol_good_param //API Tested :atoi //TestCase Description: // atol(x) returns the converted value (ascii to long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atol_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In atol(good_parameters)") ); int intVal; TPtrC string; _LIT( Kstring, "string" ); TBool res1 = GetStringFromConfig(ConfigSection(), Kstring, string ); _LIT( KintVal, "intVal" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal, intVal); if(res1 && res2) { INFO_PRINTF3(_L("Tstdlib: Input-> %S, Expected -> %d"), &string, intVal ); TBuf8<100> buf; buf.Copy(string); char* ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; __UHEAP_MARK; long atolret=atol(ptr); __UHEAP_MARKEND; if(atolret!=intVal) { INFO_PRINTF3(_L("atol(\"%S\")-> %d"),&string, atolret); INFO_PRINTF2(_L("Expected-> %d") , intVal); return KErrGeneral; } else { INFO_PRINTF3(_L("atol(\"%S\")-> %d"),&string, atolret); INFO_PRINTF1(_L("No error")); return KErrNone; } } else { INFO_PRINTF1(_L("Expected Parameters in the configuration file-> ")); INFO_PRINTF1(_L("<input_string> <expected_output_longNum>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :atollbasic //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollbasic() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollbasicL")); long long l = atoll("32677788998"); INFO_PRINTF2(_L("{Expected: 32677788998 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 32677788998) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollspacecheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollspacecheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollspacecheckL")); long long l = atoll(" 32677788998"); INFO_PRINTF2(_L("{Expected: 32677788998 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 32677788998) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollsignedsrc //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollsignedsrc() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollsignedsrcL")); long long l = atoll("-32677788998"); INFO_PRINTF2(_L("{Expected: -32677788998 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != -32677788998) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atolloctalcheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atolloctalcheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atolloctalcheckL")); long long l = atoll("010"); INFO_PRINTF2(_L("{Expected: 10 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 10) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollhexcheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollhexcheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollhexcheckL")); long long l = atoll("0xa"); INFO_PRINTF2(_L("{Expected: 0 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atolldigitfirstcheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atolldigitfirstcheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atolldigitfirstcheckL")); long long l = atoll("6454756356bs"); INFO_PRINTF2(_L("{Expected: 6454756356 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 6454756356) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollalphafirstcheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollalphafirstcheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollalphafirstcheckL")); long long l = atoll("fgsdf64547"); INFO_PRINTF2(_L("{Expected: 0 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollalphacheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollalphacheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollalphacheckL")); long long l = atoll("hsgdfhaff"); INFO_PRINTF2(_L("{Expected: 0 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :atollleadingzeroscheck //API Tested :atoll //TestCase Description: // atoll(x) returns the converted value (ascii to long long) // if the value can be represented. // This case finds the conversion of input strings like // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh".. // And compares the result with the expected value as passed // in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::atollleadingzeroscheck() { __UHEAP_MARK; INFO_PRINTF1(_L("In atollleadingzeroscheckL")); long long l = atoll("-00000005324532657"); INFO_PRINTF2(_L("{Expected: -5324532657 Obtained: %ld}"), l); __UHEAP_MARKEND; if(l != -5324532657) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :div_good_param //API Tested :div //TestCase Description: // div(a,b) divides a by b and return a structure of type div_t, // comprising both the quotient and the remainder(integer type) // This case finds the conversion of input integers, example: // div(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::div_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In div(good_parameters)") ); int intVal1; int intVal2; TInt ret1=KErrNone, ret2 = KErrNone; div_t j; _LIT( KintVal1, "intVal1" ); TBool res1 = GetIntFromConfig(ConfigSection(), KintVal1, intVal1); _LIT( KintVal2, "intVal2" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal2, intVal2); if( res1 && res2 && ret1==KErrNone && ret2==KErrNone) { if(intVal2!=0) { __UHEAP_MARK; j=div(intVal1,intVal2); __UHEAP_MARKEND; INFO_PRINTF3(_L("div( %d, %d )"),intVal1, intVal2); INFO_PRINTF3(_L("Result->Quotient=%d Remainder=%d"),j.quot,j.rem); int result = (intVal2 * j.quot) + j.rem; if( result == intVal1 ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } else { INFO_PRINTF1(_L("This causes an exception")); return KErrNone; } } else { INFO_PRINTF1(_L("Expected input: <Dividend> <Divisor>..")); INFO_PRINTF1(_L("<Expected-quotient> <Expected-remainder>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :ldiv_good_param //API Tested :ldiv //TestCase Description: // ldiv(a,b) divides a by b and return a structure of type ldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // ldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::ldiv_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In ldiv(good_parameters)") ); int intVal1; int intVal2; ldiv_t j; _LIT( KintVal1, "intVal1" ); TBool res1 = GetIntFromConfig(ConfigSection(), KintVal1, intVal1); _LIT( KintVal2, "intVal2" ); TBool res2 = GetIntFromConfig(ConfigSection(), KintVal2, intVal2); if(res1 && res2) { if(intVal2!=0) { __UHEAP_MARK; j=ldiv(intVal1,intVal2); __UHEAP_MARKEND; INFO_PRINTF3(_L("ldiv( %d, %d )"),intVal1, intVal2); INFO_PRINTF3(_L("Result->Quotient=%d Remainder=%d"),j.quot,j.rem); int result = (intVal2 * j.quot) + j.rem; if( result == intVal1 ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } else { INFO_PRINTF1(_L("This causes an exception")); return KErrNone; } } else { INFO_PRINTF1(_L("Expected input: <Dividend> <Divisor>..")); INFO_PRINTF1(_L("<Expected-quotient> <Expected-remainder>")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :lldiv_good_param0 //API Tested :lldiv //TestCase Description: // lldiv(a,b) divides a by b and return a structure of type lldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // lldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::lldiv_good_param0( ) { INFO_PRINTF1(_L("Tstdlib: In lldiv(+ve_dividend_+ve_divisor)") ); long long numer = pow(2, 40); long long denom = 3; __UHEAP_MARK; lldiv_t x = lldiv(numer, denom); INFO_PRINTF3(_L("Result->Quotient=%ld Remainder=%ld"), x.quot, x.rem); long long exp_numer = (denom * x.quot) + x.rem; __UHEAP_MARKEND; if( exp_numer == numer ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :lldiv_good_param1 //API Tested :lldiv //TestCase Description: // lldiv(a,b) divides a by b and return a structure of type lldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // lldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::lldiv_good_param1( ) { INFO_PRINTF1(_L("Tstdlib: In lldiv(-ve_dividend_+ve_divisor)") ); long long numer = pow(2, 40); long long denom = 3; __UHEAP_MARK; lldiv_t x = lldiv(-numer, denom); INFO_PRINTF3(_L("Result->Quotient=%ld Remainder=%ld"), x.quot, x.rem); long long exp_numer = (denom * x.quot) + x.rem; __UHEAP_MARKEND; if( exp_numer == (-numer) ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :lldiv_good_param2 //API Tested :lldiv //TestCase Description: // lldiv(a,b) divides a by b and return a structure of type lldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // lldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::lldiv_good_param2( ) { INFO_PRINTF1(_L("Tstdlib: In lldiv(+ve_dividend_-ve_divisor)") ); long long numer = pow(2, 40); long long denom = -3; __UHEAP_MARK; lldiv_t x = lldiv(numer, denom); INFO_PRINTF3(_L("Result->Quotient=%ld Remainder=%ld"), x.quot, x.rem); long long exp_numer = (denom * x.quot) + x.rem; __UHEAP_MARKEND; if( exp_numer == (numer) ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :lldiv_good_param3 //API Tested :lldiv //TestCase Description: // lldiv(a,b) divides a by b and return a structure of type lldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // lldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::lldiv_good_param3( ) { INFO_PRINTF1(_L("Tstdlib: In lldiv(-ve_dividend_-ve_divisor)") ); long long numer = pow(2, 40); long long denom = -3; __UHEAP_MARK; lldiv_t x = lldiv(-numer, denom); INFO_PRINTF3(_L("Result->Quotient=%ld Remainder=%ld"), x.quot, x.rem); long long exp_numer = (denom * x.quot) + x.rem; __UHEAP_MARKEND; if( exp_numer == (-numer) ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :lldiv_good_param4 //API Tested :lldiv //TestCase Description: // lldiv(a,b) divides a by b and return a structure of type lldiv_t, // comprising both the quotient and the remainder(all long type). // This case finds the conversion of input integers, example: // lldiv(7,2) which should return 3 and 1 respectively in the // structure members.And compares the result with the expected // value as passed in the parameters. // ----------------------------------------------------------------------------- TInt CTestStdlib::lldiv_good_param4( ) { INFO_PRINTF1(_L("Tstdlib: In lldiv(zero_dividend)") ); long long numer = 0; long long denom = 3; INFO_PRINTF1(_L("in lldiv_good_param4L...")); __UHEAP_MARK; lldiv_t x = lldiv(-numer, denom); INFO_PRINTF3(_L("Result->Quotient=%ld Remainder=%ld"), x.quot, x.rem); long long exp_numer = (denom * x.quot) + x.rem; __UHEAP_MARKEND; if( exp_numer == (numer) ) { return KErrNone; } else { INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :rand //API Tested :rand //TestCase Description: // The rand() function shall compute a sequence of pseudo-random integers // in range [0,{RAND_MAX}].This case generates random numbers 20 times // and checks whetther there was repeatition. // ----------------------------------------------------------------------------- TInt CTestStdlib::randL( ) { INFO_PRINTF1(_L("Tstdlib: In rand()") ); TInt randArray[20]; TInt i=0,j,k, flag=0; __UHEAP_MARK; while(i<20) { randArray[i]=rand(); INFO_PRINTF2(_L("%d "),randArray[i]); i++; } for(j=0;j<20;j++) { for(k=0;k<20;k++) { if((j!=k) && (randArray[j]==randArray[k])) { INFO_PRINTF1(_L("Repeatition of random no.s within 20 iterations")); flag=1; break; } } } __UHEAP_MARKEND; if(flag==0) { INFO_PRINTF1(_L("No repeatition")); return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :srand //API Tested :srand //TestCase Description: // The srand() function sets the seed for the rand function to compute a // sequence of pseudo-random integers in range [0,{RAND_MAX}].This // case generates random numbers 20 times and checks whetther there // was repeatition. // ----------------------------------------------------------------------------- TInt CTestStdlib::srandL( ) { INFO_PRINTF1(_L("Tstdlib: In srand(seed_val)") ); TInt retVal=KErrNone; int seedVal; int randVal; _LIT( KseedVal, "seedVal" ); TBool res = GetIntFromConfig(ConfigSection(), KseedVal, seedVal); if(res) { __UHEAP_MARK; srand(seedVal); randVal=rand(); __UHEAP_MARKEND; INFO_PRINTF2(_L("Seed Value given %d"), seedVal); INFO_PRINTF2(_L("Random Value returned is %d"), randVal); if(randVal<seedVal) { INFO_PRINTF1(_L("rand() returned a value less than the seed.")); retVal = KErrGeneral; } } else { INFO_PRINTF1(_L("Expected as parameter: <seed_value>")); retVal = KErrGeneral; } return retVal; } // ----------------------------------------------------------------------------- //Function Name :strtol_null_string //API Tested :strtol //TestCase Description: // These functions shall convert the initial portion of the string // pointed to by str to a type long representation. // This case finds the conversion of NULL string. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtol_null_string( ) { INFO_PRINTF1(_L("Tstdlib: In strtol(NULL_string)") ); char *endpt; TInt endptr,base; _LIT( Kendptr, "endptr" ); TBool res1 = GetIntFromConfig(ConfigSection(), Kendptr, endptr); _LIT( Kbase, "base" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kbase, base); long converted; if(endptr==0) { endpt=NULL; } __UHEAP_MARK; if(res1 && res2) { converted = strtol("", &endpt,base); INFO_PRINTF1(_L("Whatever be the value of argument2 and argument3..")); INFO_PRINTF1(_L("if the first argument is :\"\",")); INFO_PRINTF2(_L("the result always is %d"),converted); } else { converted =strtol("", (char **)NULL, 0); INFO_PRINTF1(_L("if the first argument is :\"\",")); INFO_PRINTF2(_L("the result always is %d"),converted); } __UHEAP_MARKEND; if(converted==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :strtol_good_param //API Tested :strtol //TestCase Description: // These functions shall convert the initial portion of the string // pointed to by str to a type long respectively. // This case finds the conversion // "321","-354","fghsdf","254jhjh","000073ewg","-0000377jh" "0x123".. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtol_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In strtol()") ); TInt endptr,base; TInt expected; TPtrC string; long converted=0; char *endpt; _LIT( Kstring, "string" ); TBool res1 = GetStringFromConfig(ConfigSection(), Kstring, string); _LIT( Kendptr, "endptr" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kendptr, endptr); _LIT( Kbase, "base" ); TBool res3 = GetIntFromConfig(ConfigSection(), Kbase, base); _LIT( Kexpected, "expected" ); TBool res4 = GetIntFromConfig(ConfigSection(), Kexpected, expected); if(res1 && res2 && res3 && res4) { if(endptr==0) { endpt=NULL; } TBuf8<100> buf; buf.Copy(string); char* ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; __UHEAP_MARK; converted = strtol(ptr,&endpt,base); __UHEAP_MARKEND; if(base<0 || base >36) { INFO_PRINTF1(_L("Base should be between 0-36 for meaningful output")); INFO_PRINTF2(_L(" Error No: %d"), errno); if(errno == 0) { INFO_PRINTF1(_L("No conversion performed")); } return KErrNone; } if(converted == LONG_MIN || converted == LONG_MAX) { INFO_PRINTF1(_L("Return value cannot be represented...")); INFO_PRINTF1(_L("....at the destination type")); INFO_PRINTF2(_L(" Error No: %d"), errno); } else if(converted == expected) { INFO_PRINTF2(_L(" Expected %i"), expected); } else { INFO_PRINTF3(_L("Input: %S Result: %f"), &string, converted ); INFO_PRINTF2(_L(" Expected %f"), expected); INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } else { INFO_PRINTF1(_L("Expected input-> <string> <endptr(0/1)> <base(0-36)>..")); INFO_PRINTF1(_L("<expected_value>")); INFO_PRINTF1(_L("If endptr is given as 0, the respective argument is set..")); INFO_PRINTF1(_L("to NULL,if any other integer specified,it is left unchanged")); return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :strtod_null_string //API Tested :strtod //TestCase Description: // This function shall convert the initial portion of the string // pointed to by str to a type double representation. // This case finds the conversion of NULL string. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_null_string( ) { INFO_PRINTF1(_L("Tstdlib: In strtod(NULL_string)")); char *endpt; TInt endptr; _LIT( Kendptr, "endptr" ); TBool res = GetIntFromConfig(ConfigSection(), Kendptr, endptr); double converted; if(endptr==0) { endpt=NULL; } __UHEAP_MARK; if(res) { converted = strtod("", &endpt); INFO_PRINTF1(_L("Whatever be the value of argument2 ..")); INFO_PRINTF1(_L("..if the first argument is :\"\"...")); INFO_PRINTF2(_L("the result always is %d"), converted); } else { converted =strtol("", (char **)NULL, 0); INFO_PRINTF1(_L("..if the first argument is :\"\"...")); INFO_PRINTF2(_L("the result always is %d"), converted); } __UHEAP_MARKEND; if(converted==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :strtod_good_param //API Tested :strtod //TestCase Description: // These functions shall convert the initial portion of the string // pointed to by str to a type long representation. // This case finds the conversion "321.879","-354.87","fghsdf87.89" // "254.9jhjh","000073ewg","-0000377.9jh" "0x123".. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In strtod()") ); TInt endptr; TInt floatVal1,floatVal2; double floatVal; TPtrC string; double converted; char *endpt; _LIT( Kstring, "string" ); TBool res1 = GetStringFromConfig(ConfigSection(), Kstring, string ); _LIT( Kendptr, "endptr" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kendptr, endptr); _LIT( KfloatVal1, "floatVal1" ); TBool res3 = GetIntFromConfig(ConfigSection(), KfloatVal1, floatVal1); _LIT( KfloatVal2, "floatVal2" ); TBool res4 = GetIntFromConfig(ConfigSection(), KfloatVal2, floatVal2); if(res1 && res2 && res4 && res3) { int dividend = 1; TInt temp = floatVal2; do { temp /= 10; dividend *= 10; }while( temp ); if(floatVal1>=0) { floatVal=(double) (floatVal1)+(double)((double)floatVal2/dividend); } else { floatVal=(double) (floatVal1)-(double)((double)floatVal2/dividend); } if(endptr==0) { endpt=NULL; } TBuf8<100> buf; buf.Copy(string); char* ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; __UHEAP_MARK; converted = strtod(ptr,&endpt); __UHEAP_MARKEND; if(converted == floatVal) { INFO_PRINTF2(_L(" Expected %f"), floatVal); return KErrNone; } else { INFO_PRINTF3(_L("Input: %S Result: %f"), &string, converted ); INFO_PRINTF2(_L(" Expected %f"), floatVal); INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } else { INFO_PRINTF1(_L("Expected input-> <string> <endptr(0/1)> ..")); INFO_PRINTF1(_L("<integral_part_expected> <decimal_part_expected>")); INFO_PRINTF1(_L("If endptr is 0,the respective arg is set to NULL,..")); INFO_PRINTF1(_L("if any other integer specified, it is left unchanged")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :strtod_nan //API Tested :strtod //TestCase Description: NaN input to strtod // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_nan() { __UHEAP_MARK; INFO_PRINTF1(_L("In strtod(NAN)")); char *endpt1, *endpt2; //-------------------------- double d1 = strtod("NAN", NULL); double d2 = strtod("nan(dffgh)rty", &endpt1); double d3 = strtod("-NAN123", &endpt2); INFO_PRINTF4(_L("{Expected: NaN, NaN, NaN} %f %f %f"), d1, d2, d3); //-------------------------- __UHEAP_MARKEND; if (!isnan(d1) || !isnan(d2)| !isnan(d3)) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :strtod_inf //API Tested :strtod //TestCase Description: NaN input to strtod // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_inf() { __UHEAP_MARK; INFO_PRINTF1(_L("In strtod(INFINITY)")); //-------------------------- char *endpt1, *endpt2; double d1 = strtod("INFINITY123", &endpt1); double d2 = strtod("INF", NULL); double d3 = strtod("-INFabc", &endpt2); INFO_PRINTF4(_L("{Expected: Inf, Inf, -Inf} %f %f %f"), d1, d2, d3); __UHEAP_MARKEND; //-------------------------- if ( (strcmp(endpt1, "123") != 0) || (strcmp(endpt2, "abc") != 0) ) { return KErrGeneral; } if ((isinf(d1) != 1) || (isinf(d2) != 1) || (isinf(d3) != -1)) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :strtod_neg_case //API Tested :strtod //TestCase Description: NaN input to strtod // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_neg_cases() { __UHEAP_MARK; INFO_PRINTF1(_L("In strtod(neg_cases)")); TInt ret = KErrNone; //-------------------------- char *endpt1, *endpt2, *endpt3, *endpt4, *endpt5, *endpt6; double d1 = strtod("4752364536550er674635jkjk", &endpt1); INFO_PRINTF2(_L("{Expected: 4752364536550.0} %f"), d1); //underflow errno = 0; double d2 = strtod("4752364536550478678e-674635jkjk", &endpt2); INFO_PRINTF2(_L("{Expected: 0.0} %f"), d2); if (errno != ERANGE) { INFO_PRINTF1(_L("{case2: errno not set to ERANGE")); ret = KErrGeneral; } //overflow (-HUGE_VAL) errno = 0; double d3 = strtod("-1.652364536550478678e+674635jkjk", &endpt3); INFO_PRINTF2(_L("{Expected: -Inf} %f"), d3); if (errno != ERANGE) { INFO_PRINTF1(_L("{case3: errno not set to ERANGE")); ret = KErrGeneral; } errno = 0; double d4 = strtod("1.652364536550478678e.674635jkjk", &endpt4); INFO_PRINTF2(_L("{Expected: 1.65236453655047867} %f"), d4); double d5 = strtod("1.65236453655047.8678e+674635jkjk", &endpt5); INFO_PRINTF2(_L("{Expected: 1.65236453655047} %f"), d5); //overflow (HUGE_VAL) errno = 0; double d6 = strtod("1.652364536550478678e+674635jkjk", &endpt6); INFO_PRINTF2(_L("{Expected: Inf} %f"), d6); if (errno != ERANGE) { INFO_PRINTF1(_L("{case3: errno not set to ERANGE")); ret = KErrGeneral; } errno = 0; //-------------------------- if ( (strcmp(endpt1, "er674635jkjk") != 0) || (strcmp(endpt2, "jkjk") != 0) || (strcmp(endpt3, "jkjk") != 0) || (strcmp(endpt4, "e.674635jkjk") != 0) || (strcmp(endpt5, ".8678e+674635jkjk") != 0) || (strcmp(endpt6, "jkjk") != 0) ) { ret = KErrGeneral; } if (d1 != 4752364536550.0 || d2 != KMinTReal || d3 != -HUGE_VAL || d4 != 1.652364536550478678 || d5 != 1.65236453655047 || d6 != HUGE_VAL) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :strtod_misc_case //API Tested :strtod //TestCase Description: NaN input to strtod // ----------------------------------------------------------------------------- TInt CTestStdlib::strtod_misc_cases() { __UHEAP_MARK; INFO_PRINTF1(_L("In strtod(misc_cases)")); TInt ret = KErrNone; //-------------------------- char *endpt2, *endpt3, *endpt4, *endpt5, *endpt6; char *endpt7, *endpt8, *endpt9, *endpt10, *endpt11; double d1 = strtod("-9", NULL); INFO_PRINTF2(_L("{Expected: -9.0} %f"), d1); double d2 = strtod("-INfabc", &endpt2); INFO_PRINTF2(_L("{Expected: -Inf} %f"), d2); double d3 = strtod("91+0e876465478299",&endpt3); INFO_PRINTF2(_L("{Expected: 91.0} %f"), d3); double d4 = strtod("1.E788jhhg+e8767743dbn",&endpt4); INFO_PRINTF2(_L("{Expected: Inf} %f"), d4); double d5 = strtod("-000e123knvbcyhdr", &endpt5); INFO_PRINTF2(_L("{Expected: -0.0} %f"), d5); double d6 = strtod("0x00e123bhduitri", &endpt6); INFO_PRINTF2(_L("{Expected: 922171.0} %f"), d6); double d7 = strtod("00x12e01klui", &endpt7); INFO_PRINTF2(_L("{Expected: 0.0} %f"), d7); double d8 = strtod("0000000000000",&endpt8); INFO_PRINTF2(_L("{Expected: 0.0} %f"), d8); double d9 = strtod("-0.000e123nndfuu",&endpt9); INFO_PRINTF2(_L("{Expected: -0.0} %f"), d9); double d10 = strtod("0x10p+",&endpt10); INFO_PRINTF2(_L("{Expected: 16.0} %f"), d10); double d11 = strtod("0x", NULL); INFO_PRINTF2(_L("{Expected: 0.0} %f"), d11); double d12 = strtod(" -23.45e-+3", &endpt11); INFO_PRINTF2(_L("{Expected: 0.0} %f"), d12); //-------------------------- if ( (strcmp(endpt2, "abc") != 0) || (strcmp(endpt3, "+0e876465478299") != 0) || (strcmp(endpt4, "jhhg+e8767743dbn") != 0) || (strcmp(endpt5, "knvbcyhdr") != 0) || (strcmp(endpt6, "hduitri") != 0) || (strcmp(endpt7, "x12e01klui") != 0) || (strcmp(endpt9, "nndfuu") != 0) || (strcmp(endpt10, "p+") != 0) || (strcmp(endpt11, "e-+3") != 0) ) { ret = KErrGeneral; } if (d1 != -9.0 || isinf(d2) != -1 || d3 != 91.0 || isinf(d4) != 1 || d5 != -0.0 || d6 != 922171.0 || d7 != 0.0 || d8 != 0.0 || d9 != -0.0 || d10 != 16.0 || d11 != 0.0 || d12 != -23.45 ) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :strtoul_null_string //API Tested :strtoul //TestCase Description: // This function shall convert the initial portion of the string // pointed to by str to a type unsigned long representation. // This case finds the conversion of NULL string. // And compares result with 0,the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtoul_null_string( ) { INFO_PRINTF1(_L("Tstdlib: In strtoul(NULL_string)") ); char *endpt; TInt endptr, base; _LIT( Kendptr, "endptr" ); TBool res1 = GetIntFromConfig(ConfigSection(), Kendptr, endptr); _LIT( Kbase, "base" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kbase, base); unsigned long converted; if(endptr==0) { endpt=NULL; } __UHEAP_MARK; if(res1 && res2) { converted = strtoul("", &endpt,base); INFO_PRINTF1(_L("Whatever be the value of argument2 and argument3..")); INFO_PRINTF1(_L("..if the first argument is :\"\"...")); INFO_PRINTF2(_L("...the result always is %d"), converted); } else { converted =strtoul("", (char **)NULL, 0); INFO_PRINTF1(_L("..if the first argument is :\"\"...")); INFO_PRINTF2(_L("...the result always is %d"), converted); } __UHEAP_MARKEND; if(converted==0) { return KErrNone; } else { return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :strtoul_good_param //API Tested :strtod // These functions shall convert the initial portion of the string // pointed to by str to a type long representation. // This case finds the conversion "321879","-35487","fghsdf8789", // "2549jhjh","000073ewg","-00003779jh" "0x123cv".. // And compares result with the expected value. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtoul_good_param( ) { INFO_PRINTF1(_L("Tstdlib: In strtoul()") ); TInt endptr,base; TInt expected1; TPtrC string; unsigned long converted; char *endpt; _LIT( Kstring, "string"); TBool res1 = GetStringFromConfig(ConfigSection(), Kstring, string ); _LIT( Kendptr, "endptr" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kendptr, endptr); _LIT( Kbase, "base"); TBool res3 = GetIntFromConfig(ConfigSection(), Kbase, base); _LIT( Kexpected1, "expected1"); TBool res4 = GetIntFromConfig(ConfigSection(), Kexpected1, expected1); TUint expected = (TUint) expected1; if(res1 && res2 && res3 && res4) { if(endptr==0) { endpt=NULL; } TBuf8<100> buf; buf.Copy(string); char* ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; __UHEAP_MARK; converted = strtoul(ptr,&endpt,base); __UHEAP_MARKEND; if(base<0 || base >36) { INFO_PRINTF1(_L("Base should be between 0-36 for meaningful output")); INFO_PRINTF2(_L(" Error No: %d"), errno); if(errno == 0) { INFO_PRINTF1(_L("No conversion performed")); } } if(converted == expected) { INFO_PRINTF2(_L(" Expected %d"), &expected); return KErrNone; } else { INFO_PRINTF2(_L(" Expected %d"), &expected); INFO_PRINTF1(_L("Unexpected output")); return KErrGeneral; } } else { INFO_PRINTF1(_L("Expected input-> <string> <endptr(0/1)> <base>..")); INFO_PRINTF1(_L("<expected_value>")); INFO_PRINTF1(_L("If endptr is given as 0,the respective argument is set..")); INFO_PRINTF1(_L("to NULL, if any other integer specified, it is left unchanged")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :strtoul_neg_num_alpha //API Tested :strtod //TestCase Description: // These functions shall convert the initial portion of the string // pointed to by str to a type long representation. // This case finds the conversion of strings like "-35487". // And compares result with the expected value as in the // unsigned long member of the structure. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtoul_neg_num_alpha( ) { INFO_PRINTF1(_L("Tstdlib: In strtoul(-ve_num_alpha)") ); struct test_neg_long { char* long_string; int base; unsigned long longVal; }; struct test_neg_long test[3]= { {" -8998", 36, 4294582052u}, {"-10hguyh",10, 4294967286u}, {"-98ghjh",18, 4294911911u} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; unsigned long ret = strtoul(test[i].long_string,(char **)NULL,test[i].base); __UHEAP_MARKEND; INFO_PRINTF3(_L("strtoul(\"%u\")-> %u"),test[i].longVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].longVal); if( ret != test[i].longVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :strtoul_neg_leading_zeroes //API Tested :strtod //TestCase Description: // These functions shall convert the initial portion of the string // pointed to by str to a type long representation. // This case finds the conversion of the strings like // "-0000035487","-00003779jh" // And compares result with the expected value as in the // unsigned long member of the structure. // ----------------------------------------------------------------------------- TInt CTestStdlib::strtoul_neg_leading_zeroes( ) { INFO_PRINTF1(_L("Tstdlib: In strtoul(-ve_leading_zeroes)") ); struct test_neg_long { char* long_string; int base; unsigned long longVal; }; struct test_neg_long test[3]= { {" -000008998",36,4294582052u}, {"-000010",10,4294967286u}, {"-0000098ghjh",18,4294911911u} }; TInt i=0; for(i=0;i<3;i++) { __UHEAP_MARK; unsigned long ret = strtoul(test[i].long_string,(char **)NULL,test[i].base); __UHEAP_MARKEND; INFO_PRINTF3(_L("strtoul(\"%u\")-> %u"),test[i].longVal, ret); INFO_PRINTF2(_L("Expected -> %f"),test[i].longVal); if( ret != test[i].longVal ) { INFO_PRINTF1(_L("Unexpected return value from atof()")); return KErrGeneral; } } return KErrNone; } int sort_function(const void* a,const void* b) { int* p1 = (int*) a; int val1 = *p1; int* p2 = (int*) b; int val2 = *p2; int x = -1; if(val1 > val2 ) { x=1; } else if(val1 == val2 ) { x=0; } return x; } // ----------------------------------------------------------------------------- //Function Name :qsort_integers //API Tested :qsort //TestCase Description: // The qsort() function shall sort an array of 'nel' objects, the initial // element of which is pointed to by 'base'. The size of each object, in // bytes, is specified by the 'width' argument. the function 'compare' is // to be written by the user. all these quoted ones are arguments to qsort. // respectively.This case sorts a sets of integers as passed by user and // manually makes a check of whether the array is sorted. // ----------------------------------------------------------------------------- TInt CTestStdlib::qsort_integers( ) { INFO_PRINTF1(_L("Tstdlib: In quicksort()") ); int array[100]; int temp=0; int notSorted=0; TInt i,j; _LIT( Kelem1, "elem1" ); _LIT( Kelem2, "elem2" ); _LIT( Kelem3, "elem3" ); _LIT( Kelem4, "elem4" ); _LIT( Kelem5, "elem5" ); _LIT( Kelem6, "elem6" ); TBool res1 = GetIntFromConfig(ConfigSection(), Kelem1, array[0]); TBool res2 = GetIntFromConfig(ConfigSection(), Kelem2, array[1]); TBool res3 = GetIntFromConfig(ConfigSection(), Kelem3, array[2]); TBool res4 = GetIntFromConfig(ConfigSection(), Kelem4, array[3]); TBool res5 = GetIntFromConfig(ConfigSection(), Kelem5, array[4]); TBool res6 = GetIntFromConfig(ConfigSection(), Kelem6, array[5]); i=6; if(i!=0) { INFO_PRINTF2(_L(" i: %d "),i); int save=i; for(j=0;j<save;j++) { INFO_PRINTF2(_L(" %d "),array[j]); } __UHEAP_MARK; qsort((void *)array,i,sizeof(array[0]),sort_function); __UHEAP_MARKEND; INFO_PRINTF1(_L("Array after sort")); for(j=0;j<save;j++) { INFO_PRINTF2(_L(" %d "),array[j]); } temp=array[0]; for(j=1;j<save;j++) { if(temp>array[j]) { notSorted=1; } else { temp=array[j]; } } if(notSorted) { return KErrGeneral; } return KErrNone; } else { INFO_PRINTF1(_L("Expected Parameters: <integer-1> <interger-2>..")); return KErrGeneral; } } int sort_function1( const void *a, const void *b) { return( strcmp((char *)a,(char *)b) ); } // ----------------------------------------------------------------------------- //Function Name :qsort_strings //API Tested :qsort //TestCase Description: // The qsort() function shall sort an array of 'nel' objects, the initial // element of which is pointed to by 'base'. The size of each object, in // bytes, is specified by the 'width' argument. the function 'compare' is // to be written by the user. all these quoted ones are arguments to qsort. // respectively.This case sorts a sets of strings as passed by user and // manually makes a check of whether the array is sorted. // ----------------------------------------------------------------------------- TInt CTestStdlib::qsort_strings( ) { INFO_PRINTF1(_L("Tstdlib: In quicksort(strings)") ); int retVal=KErrNone; int notSorted=0; char array[10][50]; TPtrC string[6]; int j=0; int i; _LIT( Kelem1, "elem1" ); _LIT( Kelem2, "elem2" ); _LIT( Kelem3, "elem3" ); _LIT( Kelem4, "elem4" ); _LIT( Kelem5, "elem5" ); _LIT( Kelem6, "elem6" ); TBool res1 = GetStringFromConfig(ConfigSection(), Kelem1, string[0]); TBool res2 = GetStringFromConfig(ConfigSection(), Kelem2, string[1]); TBool res3 = GetStringFromConfig(ConfigSection(), Kelem3, string[2]); TBool res4 = GetStringFromConfig(ConfigSection(), Kelem4, string[3]); TBool res5 = GetStringFromConfig(ConfigSection(), Kelem5, string[4]); TBool res6 = GetStringFromConfig(ConfigSection(), Kelem6, string[5]); for(i=0;i<6;i++) { TBuf8<50> buf; char* ptr; buf.Copy(string[i]); ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; strcpy(array[i],ptr); array[i][buf.Length()]=0; if(retVal == KErrNone) { INFO_PRINTF2(_L("%S"), &string[i]); } else { break; } } if(i!=0) { int save=i; __UHEAP_MARK; qsort((void *)array,i,sizeof(array[0]),sort_function1); __UHEAP_MARKEND; INFO_PRINTF1(_L("Array after sorting")); for(j=0;j<save;j++) { TBuf8<50> tempString((TUint8 *)&array[j]); TBuf<50> displayString; displayString.Copy(tempString); INFO_PRINTF2(_L("%S"),&displayString); } for(j=1;j<save;j++) { if(strcmp(array[j-1],array[j])>1) { notSorted=1; } } if(notSorted) { return KErrGeneral; } return KErrNone; } else { INFO_PRINTF1(_L("Expected Param: <string-1> <string-2> <string-3>...")); return KErrGeneral; } } int search_function(const void* a,const void* b) { return(*(int *)a - *(int *)b); } // ----------------------------------------------------------------------------- //Function Name :binsearch_integers //API Tested :bsearch //TestCase Description: // The bsearch() function shall search an array of 'nel' objects, the initial // element of which is pointed to by 'base' for a given 'key'. The size of // each object, in bytes, is specified by the 'width' argument. the function // 'compare' is to be written by the user. all these quoted ones are arguments // to qsort.respectively.This case sorts a sets of integers as passed by user and // manually makes a check of whether the array has the key or not. // ----------------------------------------------------------------------------- TInt CTestStdlib::binsearch_integers( ) { INFO_PRINTF1(_L("Tstdlib: In binsearch()") ); TInt i,key; int array[100],j; int* element=NULL; int flag=0; _LIT( Kkey, "key" ); TBool res = GetIntFromConfig(ConfigSection(), Kkey, key); if(res) { _LIT( Kelem1, "elem1" ); TBool res1 = GetIntFromConfig(ConfigSection(), Kelem1, array[0]); _LIT( Kelem2, "elem2" ); TBool res2 = GetIntFromConfig(ConfigSection(), Kelem2, array[1]); _LIT( Kelem3, "elem3" ); TBool res3 = GetIntFromConfig(ConfigSection(), Kelem3, array[2]); _LIT( Kelem4, "elem4" ); TBool res4 = GetIntFromConfig(ConfigSection(), Kelem4, array[3]); _LIT( Kelem5, "elem5" ); TBool res5 = GetIntFromConfig(ConfigSection(), Kelem5, array[4]); _LIT( Kelem6, "elem6" ); TBool res6 = GetIntFromConfig(ConfigSection(), Kelem6, array[5]); i=6; if(i!=0) { int save=i; for(j=0;j<save;j++) { INFO_PRINTF2(_L(" %d "),array[j]); } __UHEAP_MARK; element=(int *)bsearch(&key,(void *)array,i,sizeof(array[0]), search_function); __UHEAP_MARKEND; if(element!=NULL) { INFO_PRINTF2(_L(" %d is in the array"),*element); } else { INFO_PRINTF2(_L(" Element %d not found "), key); } for(j=0;j<save;j++) { if(key==array[j]||!element) { flag=1; } } if(flag) { return KErrNone; } INFO_PRINTF1(_L(" Unexpected behaviour")); return KErrGeneral; } else { INFO_PRINTF1(_L("Expected Param: <search_key> <array_ele-1>..")); INFO_PRINTF1(_L("<array_ele-2> <array_ele-3>....")); return KErrGeneral; } } else { INFO_PRINTF1(_L("Expected Parameters: <search_key> <array_ele-1>..")); INFO_PRINTF1(_L("<array_ele-2> <array_ele-3>....")); return KErrGeneral; } } int search_function1(const void* a,const void* b) { return(strcmp((char *)a,(char *) b)); } // ----------------------------------------------------------------------------- //Function Name :binsearch_strings //API Tested :bsearch //TestCase Description: // The bsearch() function shall search an array of 'nel' objects, the initial // element of which is pointed to by 'base' for a given 'key'. The size of // each object, in bytes, is specified by the 'width' argument. the function // 'compare' is to be written by the user. all these quoted ones are arguments // to qsort.respectively.This case sorts a sets of strings as passed by user and // manually makes a check of whether the array has the key or not. // ----------------------------------------------------------------------------- TInt CTestStdlib::binsearch_strings( ) { INFO_PRINTF1(_L("Tstdlib: In binsearch(strings)") ); int retVal=KErrNone; char array[10][50]; TPtrC string[6], string_key; int j=0; int i; _LIT( Kstring_key, "string_key" ); TBool res = GetStringFromConfig(ConfigSection(), Kstring_key, string_key); _LIT( Kelem1, "elem1"); _LIT( Kelem2, "elem2"); _LIT( Kelem3, "elem3"); _LIT( Kelem4, "elem4"); _LIT( Kelem5, "elem5"); TBool res1 = GetStringFromConfig(ConfigSection(), Kelem1, string[0]); TBool res2 = GetStringFromConfig(ConfigSection(), Kelem2, string[1]); TBool res3 = GetStringFromConfig(ConfigSection(), Kelem3, string[2]); TBool res4 = GetStringFromConfig(ConfigSection(), Kelem4, string[3]); TBool res5 = GetStringFromConfig(ConfigSection(), Kelem5, string[4]); if(res) { TBuf8<50> buf_key; char* ptr_key; buf_key.Copy(string_key); INFO_PRINTF2(_L("%S"), &string_key); ptr_key = (char*) buf_key.Ptr(); ptr_key[buf_key.Length()]='\0'; for(i=0;i<5;i++) { TBuf8<50> buf; char* ptr; buf.Copy(string[i]); ptr = (char*) buf.Ptr(); ptr[buf.Length()]='\0'; strcpy(array[i],ptr); array[i][buf.Length()]=0; if(retVal==KErrNone) { INFO_PRINTF2(_L("%S"), &string); } else { break; } } if(i!=0) { int save=i; __UHEAP_MARK; char* element=(char *)bsearch((void *)ptr_key,(void *)array,i, sizeof(array[0]), search_function1); __UHEAP_MARKEND; INFO_PRINTF1(_L("Search result:")); if(element!=NULL) { TBuf8<50> tempString((TUint8 *)&*element); TBuf<50> ele_key; ele_key.Copy(tempString); INFO_PRINTF2(_L("\"%S\" is in the array "),&ele_key); } else { INFO_PRINTF2(_L("Element \"%S\" not found "),&string_key); } int flag=0; for(j=0;j<save;j++) { if(strcmp(ptr_key,array[j])||!element) { flag=1; } } if(flag) { return KErrNone; } INFO_PRINTF1(_L(" Unexpected behaviour")); return KErrGeneral; } else { INFO_PRINTF1(_L("Expected Parameters: <search_key> <array_str-1> ..")); INFO_PRINTF1(_L("<array_str-2> <array_str-3>....")); return KErrGeneral; } } else { INFO_PRINTF1(_L("Expected Parameters: <search_key> <array_str-1> ..")); INFO_PRINTF1(_L("<array_str-2> <array_str-3>....")); return KErrGeneral; } } // ----------------------------------------------------------------------------- //Function Name :isatty_Test0 //API Tested :isatty //TestCase Description: isatty returns -> 1 (stdin, stdout, stderr) // ----------------------------------------------------------------------------- TInt CTestStdlib::isatty_Test0() { __UHEAP_MARK; INFO_PRINTF1(_L("In isatty_Test0L")); //-------------------------- int i = isatty(0); int j = isatty(1); int k = isatty(2); //-------------------------- INFO_PRINTF4(_L("{Expected: 1 1 1} %d %d %d"), i, j, k); __UHEAP_MARKEND; if (i != 1 || j != 1 || k != 1) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :isatty_Test1 //API Tested :isatty //TestCase Description: isatty returns -> 0 (data file, pipe fds) // ----------------------------------------------------------------------------- TInt CTestStdlib::isatty_Test1() { __UHEAP_MARK; INFO_PRINTF1(_L("In isatty_Test1L")); //-------------------------- int i = isatty(5); int fd_file = open("c:\\some.txt", O_APPEND); int j = isatty(fd_file); int fd_pipe[3]; int p = pipe(fd_pipe); int k = isatty(fd_pipe[1]); //-------------------------- close(fd_file); close(fd_pipe[0]); close(fd_pipe[1]); INFO_PRINTF4(_L("{Expected: 0 0 0} %d %d %d"), i, j, k); unlink("c:\\some.txt"); __UHEAP_MARKEND; if (i != 0 || j != 0 || k != 0) { return KErrGeneral; } return KErrNone; } // ----------------------------------------------------------------------------- //Function Name :usleep_Test0 //API Tested :usleep //TestCase Description: To test whether the usleep call gives the desired results // for unsigned long numbers // ----------------------------------------------------------------------------- TInt CTestStdlib::usleep_Test0( ) { INFO_PRINTF1(_L("In usleep_Test0L")); int input=0; _LIT( Kinput, "input" ); TBool res = GetIntFromConfig(ConfigSection(), Kinput, input); unsigned long t = (unsigned long)input; int i = usleep(t); INFO_PRINTF2(_L("expected: 0 usleep returned: %d"), i); if(i != 0) { return KErrGeneral; } else { return KErrNone; } } // ----------------------------------------------------------------------------- //Function Name :usleep_Test1 //API Tested :usleep //TestCase Description: To test whether the usleep call gives the desired results // for fractional numbers // ----------------------------------------------------------------------------- TInt CTestStdlib::usleep_Test1( ) { INFO_PRINTF1(_L("In usleep_Test1L")); unsigned long t = 1.23331; int i = usleep(t); INFO_PRINTF2(_L("expected: 0 usleep returned: %d"), i); if(i != 0) { return KErrGeneral; } else { return KErrNone; } } // ----------------------------------------------------------------------------- //Function Name :usleep_Test2 //API Tested :usleep //TestCase Description: To test whether the usleep call gives the desired results // for zero input // ----------------------------------------------------------------------------- TInt CTestStdlib::usleep_Test2( ) { INFO_PRINTF1(_L("In usleep_Test2L")); int input=0; _LIT( Kinput, "input" ); TBool res = GetIntFromConfig(ConfigSection(), Kinput, input); unsigned long t = (unsigned long)input; int i = usleep(t); INFO_PRINTF2(_L("expected: 0 usleep returned: %d"), i); if(i != 0) { return KErrGeneral; } else { return KErrNone; } } // ----------------------------------------------------------------------------- //Function Name :getcwd_Test0 //API Tested :getcwd //TestCase Description: To test whether the getcwd call gives the desired results // for current working directory // ----------------------------------------------------------------------------- TInt CTestStdlib::getcwd_Test0( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In getcwd_Test0L")); TInt ret = KErrNone; int c = chdir("c:\\"); long size=BUF_SIZE; char *buf = (char *)malloc((size_t)size); char *ptr = NULL; if (buf != NULL && c == 0) { ptr = getcwd(buf, (size_t)size); } if (strcasecmp(ptr, "c:") != 0) { ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getcwd_Test1 //API Tested :getcwd //TestCase Description: To test whether the getcwd call gives the desired results // after changing current working directory // ----------------------------------------------------------------------------- TInt CTestStdlib::getcwd_Test1( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In getcwd_Test1L")); TInt ret = KErrNone; TPtrC string; _LIT( Kstring, "string" ); TBool res = GetStringFromConfig(ConfigSection(), Kstring, string ); TBuf8<100> buf1; buf1.Copy(string); char* path = (char*) buf1.Ptr(); path[buf1.Length()]='\0'; int c = chdir(path); long size=BUF_SIZE; char *buf = (char *)malloc((size_t)size); char *ptr = NULL; if (buf != NULL && c == 0) { ptr = getcwd(buf, (size_t)size); } if (strcasecmp(ptr, path) != 0) { ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getcwd_Test2 //API Tested :getcwd //TestCase Description: To test whether the getcwd call sets ERANGE // ----------------------------------------------------------------------------- TInt CTestStdlib::getcwd_Test2( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In getcwd_Test2L")); TInt ret = KErrNone; int c = chdir("c:\\logs\\"); char *buf = (char *)malloc(2); char *ptr = NULL; errno = 0; if (buf != NULL && c == 0) { ptr = getcwd(buf, 2); } if (ptr != NULL || errno != ERANGE) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getcwd_Test3 //API Tested :getcwd //TestCase Description: To test whether the getcwd call sets EINVAL // ----------------------------------------------------------------------------- TInt CTestStdlib::getcwd_Test3( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In getcwd_Test3L")); TInt ret = KErrNone; long size = BUF_SIZE; char *buf = (char *)malloc((size_t)size); char *ptr = NULL; errno = 0; if (buf != NULL) { ptr = getcwd(buf, 0); } if (ptr != NULL || errno != EINVAL) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name : tmpfile_Test0 //API Tested : tmpfile //TestCase Description : To test functionality of tmpfile // ----------------------------------------------------------------------------- TInt CTestStdlib::tmpfile_Test0() { INFO_PRINTF1(_L("In tmpfile_Test0")); TInt ret = KErrNone; char buf[2000]; FILE* fp = tmpfile(); if(fp) { int chars = fprintf(fp, "%s", "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello"); if(chars != 2000) { INFO_PRINTF1(_L("error in fprintf")); fclose(fp); return KErrGeneral; } fflush(fp); fseek(fp, -2000, SEEK_CUR); //beg of the file fscanf(fp, "%s", buf); if(strlen(buf) != 2000) { INFO_PRINTF1(_L("error in fscanf")); fclose(fp); return KErrGeneral; } fflush(fp); if ( (strcmp(buf, "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello") != 0) || fp == NULL ) { INFO_PRINTF1(_L("strcmp failed, hence test case failed")); fclose(fp); return KErrGeneral; } fclose(fp); } else { INFO_PRINTF1(_L("tmpfile() returned NULL, test case failed")); ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :tmpfile_Test1 //API Tested :getcwd //TestCase Description: To test whether the tmpfile creates a temp file // ----------------------------------------------------------------------------- TInt CTestStdlib::tmpfile_Test1( ) { INFO_PRINTF1(_L("In tmpfile_Test1")); TInt ret = KErrNone; char buf[10]; FILE* fp = tmpfile(); if(fp) { int bytes = fprintf(fp, "%s", "world"); if(bytes != 5) { INFO_PRINTF1(_L("fprintf failed")); fclose(fp); return KErrGeneral; } fflush(fp); fseek(fp, 0, SEEK_SET); //beg of the file fscanf(fp, "%s", buf); fflush(fp); if(strlen(buf) != 5) { INFO_PRINTF1(_L("error in fscanf")); fclose(fp); return KErrGeneral; } if(strcmp(buf, "world")) { INFO_PRINTF1(_L("String read from file does not match the string - world")); ret = KErrGeneral; } fclose(fp); } else { INFO_PRINTF1(_L("tmpfile() returned NULL, test case failed")); ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :tmpnam_Test0 //API Tested :getcwd //TestCase Description: To test whether the tmpname returns a temporary file name // ----------------------------------------------------------------------------- TInt CTestStdlib::tmpnam_Test0( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In tmpnam_Test0L")); TInt ret = KErrNone; mkdir("c:\\system\\temp", S_IWUSR); char buf[L_tmpnam]; char rbuf[10]; char *rval = tmpnam(buf); FILE *fp = fopen(buf, "w"); if (fp == NULL) { INFO_PRINTF2(_L("fopen of file returned by tmpnam() failed - errno %d "), errno); ret = KErrGeneral; } if(fp) { fprintf(fp, "%s", "check"); fclose(fp); } fp = fopen(buf, "r"); if(fp) { fscanf(fp, "%s", rbuf); fclose(fp); } if ( buf != rval || (strcmp(buf, rval) != 0) || (strcmp(rbuf, "check") != 0) ) { ret = KErrGeneral; } unlink(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :tmpnam_Test1 //API Tested :getcwd //TestCase Description: To test whether the tmpname returns a temporary file name // when the input buf is NULL. // ----------------------------------------------------------------------------- TInt CTestStdlib::tmpnam_Test1( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In tmpnam_Test1L")); TInt ret = KErrNone; mkdir("c:\\system\\temp", S_IWUSR); char rbuf[10]; char *rval = tmpnam(NULL); FILE *fp = fopen(rval, "w"); if (fp == NULL) { INFO_PRINTF2(_L("fopen of file returned by tmpnam() failed - errno %d "), errno); ret = KErrGeneral; } if(fp) { fprintf(fp, "%s", "check"); fclose(fp); } fp = fopen(rval, "r"); if(fp) { fscanf(fp, "%s", rbuf); fclose(fp); } INFO_PRINTF2(_L("read from file: %s"), rbuf); if ( strcmp(rbuf, "check") != 0 ) { ret = KErrGeneral; } unlink(rval); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :realpath_Test0 //API Tested :realpath //TestCase Description: To test if realpath sets ENOENT // ----------------------------------------------------------------------------- TInt CTestStdlib::realpath_Test0( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In realpath_Test0L")); TInt ret = KErrNone; char resolvepath[PATH_MAX]; FILE *fp = fopen("c:\\xyz.txt", "w"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); ret = KErrGeneral; } errno = 0; char *rpath = realpath("\\xyz\\some.txt", resolvepath); if (errno != ENOENT) { INFO_PRINTF2(_L("errno was not set to ENOENT - errno %d "), errno); ret = KErrGeneral; } if ( rpath != NULL ) { ret = KErrGeneral; } fclose(fp); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :realpath_Test1 //API Tested :realpath //TestCase Description: To test if realpath resolves '. and '..' // ----------------------------------------------------------------------------- TInt CTestStdlib::realpath_Test1( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In realpath_Test1L")); TInt ret = KErrNone; char resolvepath[PATH_MAX]; FILE *fp = fopen("c:\\xyz.txt", "w"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); ret = KErrGeneral; } mkdir("c:\\tmdir", S_IWUSR); int c = chdir("c:\\"); if(c == -1) { INFO_PRINTF1(_L("chdir failed!!")); ret = KErrGeneral; } //------------ char *rpath = realpath("c:\\tmdir\\..\\xyz.txt", resolvepath); if ( rpath == NULL || (strcasecmp(rpath, "c:\\xyz.txt") != 0) ) { ret = KErrGeneral; } //------------ rpath = realpath(".\\tmdir\\..\\xyz.txt", resolvepath); if ( rpath == NULL || (strcasecmp(rpath, "c:\\xyz.txt") != 0) ) { ret = KErrGeneral; } //------------ rpath = realpath("xyz.txt", resolvepath); if ( rpath == NULL || (strcasecmp(rpath, "c:\\xyz.txt") != 0) ) { ret = KErrGeneral; } fclose(fp); rmdir("c:\\tmdir"); unlink("c:\\xyz.txt"); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :realpath_Test2 //API Tested :realpath //TestCase Description:To test if realpath resolves symlinks // ----------------------------------------------------------------------------- TInt CTestStdlib::realpath_Test2( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In realpath_Test2L")); TInt ret = KErrNone; char resolvepath[PATH_MAX]; mkdir("c:\\tdir", S_IWUSR); FILE *fp = fopen("c:\\tdir\\xyz.txt", "w"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); ret = KErrGeneral; } fclose(fp); unlink("c:\\linkname.txt"); int isymlink = symlink("c:\\tdir\\xyz.txt", "c:\\linkname.txt"); if (isymlink == -1) { INFO_PRINTF1(_L("symlink failed!!")); ret = KErrGeneral; } char *rpath = realpath("c:\\linkname.txt", resolvepath); if ( rpath == NULL || (strcasecmp(rpath, "c:\\tdir\\xyz.txt") != 0) ) { ret = KErrGeneral; } int c = chdir("c:\\"); if (c == -1) { INFO_PRINTF1(_L("chdir failed!!")); ret = KErrGeneral; } rpath = realpath("linkname.txt", resolvepath); if ( rpath == NULL || (strcasecmp(rpath, "c:\\tdir\\xyz.txt") != 0) ) { ret = KErrGeneral; } unlink("c:\\tdir\\xyz.txt"); rmdir("c:\\tdir"); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :realpath_Test3 //API Tested :realpath //TestCase Description: To test if realpaths sets EINVAL // ----------------------------------------------------------------------------- TInt CTestStdlib::realpath_Test3( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In realpath_Test3L")); TInt ret = KErrNone; errno = 0; char *rpath1 = realpath("c:\\", NULL); if ( rpath1 != NULL || errno != EINVAL ) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } char resolvepath[PATH_MAX]; char *rpath2 = realpath(NULL, resolvepath); if ( rpath2 != NULL || errno != EINVAL ) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :realpath_Test4 //API Tested :realpath //TestCase Description: To test if realpaths sets EACCES // ----------------------------------------------------------------------------- TInt CTestStdlib::realpath_Test4( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In realpath_Test4L")); TInt ret = KErrNone; char resolvepath[PATH_MAX]; mkdir("c:\\nodir", S_IWUSR); FILE *fp = fopen("c:\\nodir\\xyz.txt", "w"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); ret = KErrGeneral; } fclose(fp); int ichmod = chmod("c:\\nodir", S_IRUSR); if(ichmod == -1) { INFO_PRINTF1(_L("chmod failed!!")); ret = KErrGeneral; } char *rpath = realpath("..\\..\\nodir\\xyz.txt", resolvepath); chmod("c:\\nodir", S_IWUSR); unlink("c:\\nodir\\xyz.txt"); rmdir("c:\\nodir"); if ( rpath != NULL || errno != EACCES ) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } //------------------------------------------------------------------------------- //Function Name : CTestStdlib::perror_Test0L //API Tested : perror //TestCase Description: The test if perror prints the error messages //------------------------------------------------------------------------------- TInt CTestStdlib::perror_Test0( ) { __UHEAP_MARK; INFO_PRINTF1(_L("In perror_Test0L")); TInt ret = KErrNone; chmod("c:\\err.txt", S_IWUSR); unlink("c:\\err.txt"); int fd = open("c:\\err.txt", O_RDWR | O_CREAT, 0666); if(fd == -1) { INFO_PRINTF1(_L("open failed!!")); return KErrGeneral; } close(2); //closing stderr int newfd = dup(fd); errno = ENOENT; perror("checking ENOENT"); errno = ENOMEM; perror("checking ENOMEM"); int ic1 = close(fd); int ic2 = close(newfd); if(ic1 == -1 || ic2 == -1) { INFO_PRINTF1(_L("close failed!!")); return KErrGeneral; } FILE *fp = fopen("c:\\err.txt", "r"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); return KErrGeneral; } char buf[50]; int iread = fread(buf, 1, 42, fp); buf[42] = '\0'; INFO_PRINTF2(_L("read from file: %s"), buf); INFO_PRINTF2(_L("read count: %d"), iread); if( strcmp(buf, "checking ENOENT: No such file or directory") != 0) { ret = KErrGeneral; } fgetc(fp); //skip a char iread = fread(buf, 1, 39, fp); buf[39] = '\0'; INFO_PRINTF2(_L("read from file: %s"), buf); INFO_PRINTF2(_L("read count: %d"), iread); if( strcmp(buf, "checking ENOMEM: Cannot allocate memory") != 0) { ret = KErrGeneral; } fclose(fp); unlink("c:\\err.txt"); __UHEAP_MARKEND; return ret; } TInt CTestStdlib::Testlseek() { INFO_PRINTF1(_L("Open file for reading!")); int fd = open("c:\\data.txt", O_RDONLY); if (fd<0) { INFO_PRINTF1(_L("fopen failed!!")); return KErrGeneral; } char buf1[1024]; TInt ret; INFO_PRINTF1(_L("Read the file!")); for (int i = 0; i < 1024; ++i) { ret = lseek(fd , 0 ,SEEK_SET) ; //Seek to beginning of file int nCnt = read(fd, buf1,1024 ); ret = lseek(fd , 1024 ,SEEK_CUR) ; nCnt = read( fd, buf1, 1024); ret = lseek(fd , 0 ,SEEK_SET) ; nCnt = read( fd, buf1, 512); } INFO_PRINTF1(_L("read successful!")); close(fd); return ret; } // ----------------------------------------------------------------------------- //Function Name : mkstemp_Test0 //API Tested : mkstemp //TestCase Description : To test whether the tmpfile creates a temp file // ----------------------------------------------------------------------------- TInt CTestStdlib::mkstemp_Test0( ) { INFO_PRINTF1(_L("In mkstemp_Test0")); TInt ret = KErrNone; char arr[] = "c:\\someXXXXXX"; char buf[10]; int fd = mkstemp(arr); if(fd != -1) { int bytes = write(fd, "hello", 5); if(bytes != 5) { INFO_PRINTF1(_L("write failed")); close(fd); return KErrGeneral; } lseek(fd, 0, SEEK_SET); //beg of the file bytes = read(fd, buf, 5); if(bytes != 5) { INFO_PRINTF1(_L("read failed")); close(fd); return KErrGeneral; } buf[5] = '\0'; if ((strcmp(buf, "hello") != 0) || fd == -1) { INFO_PRINTF1(_L("The string read from temp file is not hello")); ret = KErrGeneral; } close(fd); unlink(arr); } else { INFO_PRINTF1(_L("mkstemp returned invalid fd, test case failed")); ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name : mkstemp_Test1 //API Tested : mkstemp //TestCase Description : To test that tmpfile fails to create a temp file when // the template is incorrect // ----------------------------------------------------------------------------- TInt CTestStdlib::mkstemp_Test1( ) { INFO_PRINTF1(_L("In mkstemp_Test1")); TInt ret = KErrNone; char arr[] = "c:\\someXXXX"; errno = 0; int fd = mkstemp(arr); if(fd != -1 || errno != EINVAL) { INFO_PRINTF2(_L("errno was set to - %d "), errno); ret = KErrGeneral; } return ret; } // ----------------------------------------------------------------------------- //Function Name :confstr_Test0 //API Tested :confstr //TestCase Description:confstr returns configuration dependant string variable //_CS_PATH //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::confstr_Test0() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In confstr_Test0L")); int n = confstr(_CS_PATH, NULL, 0); INFO_PRINTF2(_L("{Expected: 0} %d"), n); if( n == 0 ) { ret = KErrGeneral; } char *buf = (char *)malloc(n); if ( buf == NULL ) { INFO_PRINTF1(_L("malloc failed!!")); return KErrGeneral; } int len = confstr(_CS_PATH, buf, n); INFO_PRINTF2(_L("PATH in buffer: %s"), buf); INFO_PRINTF2(_L("length: %d"), len); if( len != n ) { ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :confstr_Test1 //API Tested :confstr //TestCase Description:confstr returns 0 and sets errno to EINVAL //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::confstr_Test1() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In confstr_Test1L")); #define _CS_INV 15 int n = 10; char *buf = (char *)malloc(n); if ( buf == NULL ) { INFO_PRINTF1(_L("malloc failed!!")); return KErrGeneral; } errno = 0; int len = confstr(_CS_INV, buf, n); if (len != 0 || errno != EINVAL) { INFO_PRINTF2(_L("errno was set to - %d"), errno); ret = KErrGeneral; } free(buf); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :fpathconf_Test0 //API Tested :fpathconf //TestCase Description:fpathconf returns configuration option name //input --> _PC_XXXX_XXXX constants // ----------------------------------------------------------------------------- TInt CTestStdlib::fpathconf_Test0() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In fpathconf_Test0L")); int dummy_fd = 100; int n = fpathconf(dummy_fd, _PC_LINK_MAX); INFO_PRINTF2(_L("{Expected: (> _POSIX_LINK_MAX) } %d"), n); if( n < _POSIX_LINK_MAX ) { ret = KErrGeneral; } n = fpathconf(dummy_fd, _PC_NAME_MAX); INFO_PRINTF2(_L("{Expected: (> _POSIX_NAME_MAX) } %d"), n); if( n < _POSIX_NAME_MAX ) { ret = KErrGeneral; } n = fpathconf(dummy_fd, _PC_PATH_MAX); INFO_PRINTF2(_L("{Expected: (> _POSIX_PATH_MAX) } %d"), n); if( n < _POSIX_PATH_MAX ) { ret = KErrGeneral; } n = fpathconf(dummy_fd, _PC_PIPE_BUF); INFO_PRINTF2(_L("{Expected: (> _POSIX_PIPE_BUF) } %d"), n); if( n < _POSIX_PIPE_BUF ) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :fpathconf_Test1 //API Tested :fpathconf //TestCase Description:fpathconf sets EINVAL when invalid constant is the input //input --> _PC_XXXX_XXXX constants // ----------------------------------------------------------------------------- TInt CTestStdlib::fpathconf_Test1() { __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In fpathconf_Test1L")); int dummy_fd = 100; #define _PC_INV_CONST 100 errno = 0; int n = fpathconf(dummy_fd, _PC_INV_CONST); INFO_PRINTF2(_L("{Expected: -1 } %d"), n); if( n != -1 || errno != EINVAL) { INFO_PRINTF2(_L("errno was set to - %d"), errno); ret = KErrGeneral; } __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :somefun //API Tested :filelocks -it is an internal function to test file locks //input --> filehandle // ----------------------------------------------------------------------------- void* somefun(void* args) { FILE *fp = (FILE *)args; flockfile(fp); fputc('a', fp); fputc('b', fp); fputc('c', fp); funlockfile(fp); return((void *)NULL); } // ----------------------------------------------------------------------------- //Function Name :filelock_Test0 //API Tested :flockfile, funlockfile //TestCase Description:confstr returns 0 and sets errno to EINVAL //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::filelock_Test0() { pthread_self(); __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In filelock_Test0L")); pthread_t obj; char buf[10]; FILE *fp = fopen("c:\\chk.txt", "w"); if(fp) { flockfile(fp); INFO_PRINTF1(_L("aquired lock in thread 1!")); fputc('x', fp); INFO_PRINTF1(_L("after writing 'x' from thread 1")); int ichk = pthread_create(&obj, NULL, somefun, fp); if(ichk != 0) { INFO_PRINTF1(_L("thread creation failure!")); return KErrGeneral; } INFO_PRINTF1(_L("after calling thread 2 from thread 1")); fputc('y', fp); INFO_PRINTF1(_L("after writing 'y' from thread 1")); fputc('z', fp); INFO_PRINTF1(_L("after writing 'z' from thread 1")); funlockfile(fp); INFO_PRINTF1(_L("gave up the lock in thread 1")); sleep(2); fclose(fp); } fp = fopen("c:\\chk.txt", "r"); if(fp) { fscanf(fp, "%s", buf); fclose(fp); } INFO_PRINTF2(_L("buf read: %s"), buf); if ( (strcmp(buf, "xyzabc") != 0) ) { ret = KErrGeneral; } unlink("c:\\chk.txt"); pthread_join(obj, NULL); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :filelock_Test1 //API Tested :flockfile, funlockfile //TestCase Description:confstr returns 0 and sets errno to EINVAL //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::filelock_Test1() { pthread_self(); __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In filelock_Test1L")); pthread_t obj; char buf[10]; FILE *fp = fopen("c:\\chk.txt", "w"); if(fp) { flockfile(fp); INFO_PRINTF1(_L("1 - aquired lock in thread 1!")); fputc('x', fp); INFO_PRINTF1(_L("after writing 'x' from thread 1")); int ichk = pthread_create(&obj, NULL, somefun, fp); if(ichk != 0) { INFO_PRINTF1(_L("thread creation failure!")); return KErrGeneral; } INFO_PRINTF1(_L("after calling thread 2 from thread 1")); funlockfile(fp); INFO_PRINTF1(_L("1 - gave up the lock in thread 1")); sleep(1); flockfile(fp); INFO_PRINTF1(_L("2 - aquired lock in thread 1!")); fputc('y', fp); INFO_PRINTF1(_L("after writing 'y' from thread 1")); fputc('z', fp); INFO_PRINTF1(_L("after writing 'z' from thread 1")); funlockfile(fp); INFO_PRINTF1(_L("2 - gave up the lock in thread 1")); fclose(fp); } fp = fopen("c:\\chk.txt", "r"); if(fp) { fscanf(fp, "%s", buf); fclose(fp); } INFO_PRINTF2(_L("buf read: %s"), buf); if ( (strcmp(buf, "xabcyz") != 0) ) { ret = KErrGeneral; } unlink("c:\\chk.txt"); pthread_join(obj, NULL); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :filelock_Test2 //API Tested :ftrylockfile, flockfile, funlockfile //TestCase Description:confstr returns 0 and sets errno to EINVAL //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::filelock_Test2() { pthread_self(); __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In filelock_Test2L")); pthread_t obj; char buf[10]; int retVal=KErrNone; FILE *fp = fopen("c:\\chk.txt", "w"); if(fp) { retVal = ftrylockfile(fp); if (retVal == 0) { INFO_PRINTF1(_L("aquired lock in thread 1!")); fputc('x', fp); INFO_PRINTF1(_L("after writing 'x' from thread 1")); fputc('y', fp); INFO_PRINTF1(_L("after writing 'y' from thread 1")); int ichk = pthread_create(&obj, NULL, somefun, fp); if(ichk != 0) { INFO_PRINTF1(_L("thread creation failure!")); return KErrGeneral; } INFO_PRINTF1(_L("after calling thread 2 from thread 1")); fputc('z', fp); INFO_PRINTF1(_L("after writing 'z' from thread 1")); funlockfile(fp); INFO_PRINTF1(_L("gave up the lock in thread 1")); } else { INFO_PRINTF1(_L("couldn't acquire the lock in thread 1")); } sleep(2); fclose(fp); } fp = fopen("c:\\chk.txt", "r"); if(fp) { fscanf(fp, "%s", buf); fclose(fp); } INFO_PRINTF2(_L("buf read: %s"), buf); if ( (strcmp(buf, "xyzabc") != 0) || retVal != 0) { ret = KErrGeneral; } unlink("c:\\chk.txt"); pthread_join(obj, NULL); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :somefun //API Tested :filelocks -it is an internal function to test file locks //input --> filehandle // ----------------------------------------------------------------------------- void* sometryfun(void* args) { FILE *fp = (FILE *)args; flockfile(fp); fputc('a', fp); fputc('b', fp); fputc('c', fp); sleep(5); funlockfile(fp); return ((void*)NULL); } // ----------------------------------------------------------------------------- //Function Name :filelock_Test3 //API Tested :ftrylockfile, flockfile, funlockfile //TestCase Description:confstr returns 0 and sets errno to EINVAL //input --> void // ----------------------------------------------------------------------------- TInt CTestStdlib::filelock_Test3() { pthread_self(); __UHEAP_MARK; TInt ret = KErrNone; INFO_PRINTF1(_L("In filelock_Test3L")); pthread_t obj; char buf[10]; int retVal=KErrNone; FILE *fp = fopen("c:\\chk1.txt", "w"); if(fp) { int ichk = pthread_create(&obj, NULL, sometryfun, fp); if(ichk != 0) { INFO_PRINTF1(_L("thread creation failure!")); return KErrGeneral; } INFO_PRINTF1(_L("after calling thread 2 from thread 1")); sleep(1); retVal = ftrylockfile(fp); if (retVal == 0) { INFO_PRINTF1(_L("aquired lock in thread 1!")); fputc('x', fp); INFO_PRINTF1(_L("after writing 'x' from thread 1")); fputc('y', fp); INFO_PRINTF1(_L("after writing 'y' from thread 1")); fputc('z', fp); INFO_PRINTF1(_L("after writing 'z' from thread 1")); funlockfile(fp); INFO_PRINTF1(_L("gave up the lock in thread 1")); } else { INFO_PRINTF1(_L("couldn't acquire the lock in thread 1")); } sleep(5); fclose(fp); } fp = fopen("c:\\chk1.txt", "r"); if(fp) { fscanf(fp, "%s", buf); fclose(fp); } INFO_PRINTF2(_L("buf read: %s"), buf); if ( (strcmp(buf, "abc") != 0) || retVal == 0 ) { ret = KErrGeneral; } unlink("c:\\chk1.txt"); pthread_join(obj, NULL); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt1 //API Tested :getopt //TestCase Description:To test getopt for all the options in optstr // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest1( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 6; char *argv[] = {"getopt","-a","hi","-b","-c","hello" }; TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; int ch; INFO_PRINTF1(_L ("options expected option 'a', option 'b', option 'c' \n ")); ch = getopt ( argc, argv, "a:bc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument or the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, "a:bc"); } //end while buf1 = '\0'; if( ( strcmp( buf, "abc" )) != 0 ) { ret = KErrGeneral; } INFO_PRINTF1(_L ("non option ARGV elements expected: argv[5] == hello \n ")); if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); optind++; } } if( ( strcmp ( argv[5], "hello")) != 0 ) { ret = KErrGeneral; } free( buf ); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt2 //API Tested :getopt //TestCase Description:To test getopt for missing argument // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest2( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 2; char *argv[] = { "getopt", "-a" }; //optstring "a:b", returns ? ...shell returns ( option requires an argument ) TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; int ch; INFO_PRINTF1(_L (" expected output : an option not in optstring or missing arg.. \n ")); ch = getopt ( argc, argv, "a:bc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L (" an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument or the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, "a:bc"); } //end while buf1 = '\0'; if( ( strcmp( buf, "?" )) != 0 ) { ret = KErrGeneral; } if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); } } free( buf ); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt3 //API Tested :getopt //TestCase Description:To test getopt for an option which is not there in optstr // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest3( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 2; char *argv[] = { "getopt", "-g" }; //optstring "a:b", returns ? ...shell returns ( option requires an argument ) INFO_PRINTF1(_L (" expected output : an option not in optstring or missing arg.. \n ")); TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; int ch; ch = getopt ( argc, argv, "a:bc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L (" an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument or the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, "a:bc"); } //end while buf1 = '\0'; if( ( strcmp( buf, "?" )) != 0 ) { ret = KErrGeneral; } if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); } } free ( buf ); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt4 //API Tested :getopt //TestCase Description:To test getopt if the options are after the nonoption argument // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest4( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 7; char *argv[] = {"getopt","-a","hi","-b","hello","-c","nokia" }; int ch; TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; INFO_PRINTF1(_L ("options expected option 'a', option 'b'\n ")); ch = getopt ( argc, argv, "a:bc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument or the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, "a:bc"); } //end while buf1 = '\0'; if( ( strcmp( buf, "ab" )) != 0 ) { ret = KErrGeneral; } INFO_PRINTF1(_L ("non option ARGV elements expected: argv[4] == hello,argv[5]==-c,argv[6] ==nokia \n ")); if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); optind++; } } if( (strcmp ( argv[4], "hello") ) || ( strcmp( argv[5],"-c")) || ( strcmp( argv[6], "nokia")) ) { ret = KErrGeneral; } __UHEAP_MARK; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt5 //API Tested :getopt //TestCase Description:To test getopt for missing argument and(&&)optstring contains 1st character as : // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest5( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 2; char *argv[] = { "getopt", "-a" }; //optstring "a:b", returns ? ...shell returns ( option requires an argument ) int ch; TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; ch = getopt ( argc, argv, ":a:bc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L (" an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument and the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, ":a:bc"); } //end while buf1 = '\0'; if( ( strcmp( buf, ":" )) != 0 ) { ret = KErrGeneral; } if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); } } free ( buf ); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt6 //API Tested :getopt //TestCase Description:To test getopt to evaluate single set of arguments multiple times : // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest6( ) { __UHEAP_MARK; optind = 1; opterr = 1; int argc = 3; char *argv[] = { "getopt", "-a", "-b" }; //optstring "a:b", returns ? ...shell returns ( option requires an argument ) int ch; TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; int flag = 0; ch = getopt ( argc, argv, "abc"); while ( ch != -1 ) { switch ( ch ) { case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n ")); if ( flag == 0 ) { optind = 1; optreset = 1; flag = 1; } break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n ")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n ")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L (" an option not in optstring or missing arg..\n ")); break; case ':': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("missing argument and the 1st charcter of optstring is : \n ")); break; }//end switch ch = getopt ( argc, argv, "abc"); } //end while buf1 = '\0'; if( ( strcmp( buf, "aab" )) != 0 ) { ret = KErrGeneral; } if ( optind < argc ) { INFO_PRINTF1(_L ("non option ARGV elements actual:\n ")); while ( optind < argc ) { INFO_PRINTF2(_L ("argv[%d]=="),optind); } } INFO_PRINTF2(_L ("optopt == %c "),optopt); free ( buf ); __UHEAP_MARKEND; return ret; } // ----------------------------------------------------------------------------- //Function Name :getopt_long1 //API Tested :getopt_long //TestCase Description:To test getopt_long for all the long options // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest_long1( ) { __UHEAP_MARK; optind = 1; opterr = 1; int c; int argc = 4; char *argv[] = { "getopt", "--add","hi", "hello" }; TInt ret = KErrNone; int digit_optind = 0; INFO_PRINTF1(_L ("expected : option add non option ARGV elements : hello \n ")); while( 1 ) { int this_option_optind = optind ? optind : 1 ; int option_index = 0; static const struct option long_options[] = { {"add", 1, 0, 0 }, {"append",0,0, 0}, {"delete",1,0,0 }, {"verbose",0,0,0 }, {"create",1,0,'a'}, {"file",1,0,0 }, {0,0,0,0 } }; c = getopt_long( argc, argv, "abc:d:012", long_options, &option_index ); if ( c== -1 ) { break; } switch( c ) { case 0: if( ( strcmp(long_options[option_index].name , "add") ) || ( strcmp ( optarg, "hi"))) { ret = KErrGeneral; } break; case '0': case '1': case '2': if( digit_optind != 0 && digit_optind != this_option_optind ) { INFO_PRINTF1(_L ("digits occur in two different argv elements \n")); } digit_optind = this_option_optind; INFO_PRINTF2(_L("option %c\n"),c ); break; case 'a': INFO_PRINTF1(_L ("option 'a' \n")); break; case '?': break; } //end of switch } //end of while if( optind < argc ) { INFO_PRINTF1(_L ("non-option ARGV elements:")); while ( optind < argc ) { optind++; } } if( strcmp( argv[3], "hello")) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; }//end of function // ----------------------------------------------------------------------------- //Function Name :getopt_long2 //API Tested :getopt_long //TD Test case ID:1_14_2_1455 //TestCase Description:To test getopt_long for all the long options //Entry Into Source:\src\LPOSIX\SYSCALLS.CPP // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest_long2( ) { __UHEAP_MARK; optind = 1; opterr = 1; int c; int argc = 4; char *argv[] = { "getopt", "--create","hi", "nokia" }; int digit_optind = 0; TInt ret = KErrNone; INFO_PRINTF1(_L ("expected : option a, non option ARGV elements: hi, nokia \n ")); while( 1 ) { int this_option_optind = optind ? optind : 1 ; int option_index = 0; static const struct option long_options[] = { {"add", 1, 0, 0 }, {"append",0,0, 0}, {"delete",1,0,0 }, {"verbose",0,0,0 }, {"create",0,0,'a'}, {"file",1,0,0 }, {0,0,0,0 } }; c = getopt_long( argc, argv, "abc:d:012", long_options, &option_index ); if ( c== -1 ) { break; } switch( c ) { case 0: INFO_PRINTF2(_L("option %s\n"), long_options[option_index].name ); if( optarg ) { INFO_PRINTF2(_L("with arg %s\n"), optarg ); } break; case '0': case '1': case '2': if( digit_optind != 0 && digit_optind != this_option_optind ) { INFO_PRINTF1(_L ("digits occur in two different argv elements \n")); } digit_optind = this_option_optind; INFO_PRINTF2(_L("option %c\n"),c ); break; case 'a': INFO_PRINTF1(_L ("option 'a' \n")); break; case '?': INFO_PRINTF2(_L("?? getopt returned character code 0%o"),c ); break; } //end of switch } //end of while if( optind < argc ) { INFO_PRINTF1(_L ("non-option ARGV elements:")); while ( optind < argc ) { TBuf<MAX_SIZE> buf; TInt len = strlen(argv[optind]); for (TInt j =0; j<len;j++) { buf.Append(argv[optind][j]); } // INFO_PRINTF2(_L("%s\n"),argv[ optind++]); INFO_PRINTF2(_L("%s\n"),&buf); optind++; } } if( strcmp( argv[2], "hi") || strcmp( argv[3], "nokia" )) { ret = KErrGeneral; } __UHEAP_MARKEND; return ret; }//end of function // ----------------------------------------------------------------------------- //Function Name :getopt_long3 //API Tested :getopt_long //TestCase Description:To test getopt_long for short options // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest_long3( ) { __UHEAP_MARK; optind = 1; opterr = 1; int ch; int argc = 5; TInt ret = KErrNone; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; char *argv[] = { "getopt", "-a","-c", "nokia","india" }; int digit_optind = 0; INFO_PRINTF1(_L ("expected : option 'a', option 'c' non option ARGV elements : india \n ")); while( 1 ) { int this_option_optind = optind ? optind : 1 ; int option_index = 0; static const struct option long_options[] = { {"add", 1, 0, 0 }, {"append",0,0, 0}, {"delete",1,0,0 }, {"verbose",0,0,0 }, {"create",0,0,'a'}, {"file",1,0,0 }, {0,0,0,0 } }; ch = getopt_long( argc, argv, "abc:d:012", long_options, &option_index ); if ( ch== -1 ) break; switch( ch ) { case 0: INFO_PRINTF2(_L("option %s\n"), long_options[option_index].name ); if( optarg ) INFO_PRINTF2(_L("with arg %s\n"), optarg ); break; case '0': case '1': case '2': if( digit_optind != 0 && digit_optind != this_option_optind ) INFO_PRINTF1(_L ("digits occur in two different argv elements \n")); digit_optind = this_option_optind; INFO_PRINTF2(_L("option %c\n"),ch ); break; case 'a': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'a' \n")); break; case 'b': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'b' \n")); break; case 'c': sprintf(buf1++,"%c",ch); INFO_PRINTF1(_L ("option 'c' \n")); break; case '?': sprintf(buf1++,"%c",ch); INFO_PRINTF2(_L("?? getopt returned character code 0%o"),ch ); break; } //end of switch } //end of while buf1 ='\0'; if( ( strcmp( buf, "ac" )) != 0 ) ret = KErrGeneral; if( optind < argc ) { INFO_PRINTF1(_L ("non-option ARGV elements:")); while ( optind < argc ) { TBuf<MAX_SIZE> buf; TInt len = strlen(argv[optind]); for (TInt j =0; j<len;j++) { buf.Append(argv[optind][j]); } // INFO_PRINTF2(_L("%s\n"),argv[ optind++]); INFO_PRINTF2(_L("%s\n"),&buf); optind++; } } if( ( strcmp ( argv[4], "india")) != 0 ) ret = KErrGeneral; free(buf); __UHEAP_MARKEND; return ret; }//end of function // ----------------------------------------------------------------------------- //Function Name :getopt_long4 //API Tested :getopt_long //TD Test case ID:1_14_2_1457 //TestCase Description:To test getopt_long for digits //Entry Into Source:\src\LPOSIX\SYSCALLS.CPP // ----------------------------------------------------------------------------- TInt CTestStdlib::getoptTest_long4( ) { __UHEAP_MARK; optind = 1; opterr = 1; int ch; int argc = 4; TInt ret = KErrNone; char *argv[] = { "getopt", "-1", "-2","nokia" }; char *buf = ( char* ) malloc ( 20 ); char *buf1 = buf; int digit_optind = 0; INFO_PRINTF1(_L ("expected : option 1, option 2 \n ")); while( 1 ) { int this_option_optind = optind ? optind : 1 ; int option_index = 0; static const struct option long_options[] = { {"add", 1, 0, 0 }, {"append",0,0, 0}, {"delete",1,0,0 }, {"verbose",0,0,0 }, {"create",0,0,'a'}, {"file",1,0,0 }, {0,0,0,0 } }; ch = getopt_long( argc, argv, "abc:d:012", long_options, &option_index ); if ( ch== -1 ) { break; } switch( ch ) { case 0: INFO_PRINTF2(_L("option %s\n"), long_options[option_index].name ); if( optarg ) { INFO_PRINTF2(_L("with arg %s\n"), optarg ); } break; case '0': case '1': case '2': case '3': sprintf(buf1++,"%c",ch); if( digit_optind != 0 && digit_optind != this_option_optind ) { INFO_PRINTF1(_L ("digits occur in two different argv elements \n")); } digit_optind = this_option_optind; INFO_PRINTF2(_L("option %c\n"),ch ); break; case 'a': INFO_PRINTF1(_L ("option 'a' \n")); break; case 'b': INFO_PRINTF1(_L ("option 'b' \n")); break; case 'c': INFO_PRINTF1(_L ("option 'c' \n")); break; case '?': INFO_PRINTF2(_L("?? getopt returned character code 0%o"),ch ); break; } //end of switch } //end of while buf1 = '\0'; if( ( strcmp( buf, "12" )) != 0 ) { ret = KErrGeneral; } if( optind < argc ) { INFO_PRINTF1(_L ("non-option ARGV elements:")); } while ( optind < argc ) { TBuf<MAX_SIZE> buf; TInt len = strlen(argv[optind]); for (TInt j =0; j<len;j++) { buf.Append(argv[optind][j]); } // INFO_PRINTF2(_L("%s\n"),argv[ optind++]); INFO_PRINTF2(_L("%s\n"),&buf); optind++; } if( ( strcmp ( argv[3], "nokia")) != 0 ) { ret = KErrGeneral; } free( buf ); __UHEAP_MARKEND; return ret; } TInt CTestStdlib::Testsigemptyset() { __UHEAP_MARK; int ret=0; sigset_t sigset; INFO_PRINTF1(_L("In Testsigemptyset")); ret=sigemptyset(&sigset); INFO_PRINTF2(_L("sigemptyset returned %d"),ret); __UHEAP_MARKEND; return ret; } TInt CTestStdlib::strfmon1( ) { __UHEAP_MARK; TInt res = KErrNone; INFO_PRINTF1(_L("Tstdlib: In strfmon_test\n")); char string[31]; if (setlocale(LC_MONETARY, "en_US.ISO-8859-1") == NULL) { INFO_PRINTF1(_L("error in setlocale. locale not changed\n")); return KErrGeneral; } ssize_t ret = strfmon(string, sizeof(string), "[%^=*#6n][%=*#6i]",1234.567, 1234.567); if (strcmp(string, "[$**1234.57][**1,234.57]") == 0) { INFO_PRINTF1(_L("strfmon successful \n")); INFO_PRINTF2(_L("%s\n"), string); } else { return KErrGeneral; } ret = strfmon(string, sizeof(string), "%=*#5n",123.45); if (strcmp(string, "$***123.45") == 0) { INFO_PRINTF1(_L("strfmon successful \n")); INFO_PRINTF2(_L("%s\n"), string); } else { return KErrGeneral; } __UHEAP_MARKEND; return res; }//end of function // ----------------------------------------------------------------------------- //Function Name :TestRealPath5 //API Tested :realpath //TestCase Description: To test if realpath with different input file names // ----------------------------------------------------------------------------- TInt CTestStdlib::TestRealPath5() { __UHEAP_MARK; INFO_PRINTF1(_L("RealPathTest5")); TInt ret = KErrNone; TInt expdRet = KErrNone; char resolvepath[PATH_MAX]; char file1[512]; ReadStringParam(file1); if(chdir("c:\\") < 0 ) { ERR_PRINTF1(_L("Failed to change working directory")); return KErrGeneral; } rmdir(file1); if(mkdir(file1 , 0666) < 0 ) { ERR_PRINTF1(_L("Directory creation failed")); return KErrGeneral; } char file2[512]; ReadStringParam(file2); FILE *fp = fopen(file2, "w"); if(!fp) { INFO_PRINTF1(_L("fopen failed!!")); ret = KErrGeneral; } fclose(fp); char file3[512]; ReadStringParam(file3); char *rpath = realpath(file3, resolvepath); ReadStringParam(file3); if ( rpath == NULL || strcmp(rpath, file3) != 0) { ret = KErrGeneral; } ReadIntParam(expdRet); if (expdRet == ret) { ret = KErrNone; } else { ret = KErrGeneral; } unlink(file2); rmdir(file1); __UHEAP_MARKEND; return ret; } TInt CTestStdlib::Testlseek1() { TInt x; struct stat buf1 ; x=open("c:\\testlseek.txt",O_CREAT|O_APPEND); if(x==-1) { INFO_PRINTF1(_L("open failed!!")); return KErrGeneral; } lseek(x,20,SEEK_SET); stat("c:\\testlseek.txt",&buf1); close(x); _LIT(KTestLseek,"The size of the file after lseek %d "); INFO_PRINTF2(KTestLseek,buf1.st_size); if(buf1.st_size == 0) { INFO_PRINTF1(_L("lseek passed!!")); unlink("c:\\testlseek.txt"); return KErrNone; } INFO_PRINTF1(_L("lseek failed!!")); unlink("c:\\testlseek.txt"); return KErrGeneral; } TInt CTestStdlib::Testlseek2() { TInt x; struct stat buf1 ; x=open("c:\\testlseek.txt",O_CREAT|O_APPEND|O_RDWR); if(x==-1) { INFO_PRINTF1(_L("open failed!!")); return KErrGeneral; } write(x,"tallam",7); lseek(x,20,SEEK_SET); write(x,"revanthkumar",13); stat("c:\\testlseek.txt",&buf1); close(x); _LIT(KTestLseek,"The size of the file after lseek %d "); INFO_PRINTF2(KTestLseek,buf1.st_size); if(buf1.st_size == 33) { INFO_PRINTF1(_L("lseek passed!!")); unlink("c:\\testlseek.txt"); return KErrNone; } INFO_PRINTF1(_L("lseek failed!!")); unlink("c:\\testlseek.txt"); return KErrGeneral; } TInt CTestStdlib::getoptTest_long5( ) { __UHEAP_MARK; optind = 1; opterr = 1; int c; int argc = 4; char *argv[] = { "getopt", "--add","hi",NULL }; TInt ret = KErrGeneral; int this_option_optind = optind ? optind : 1 ; int option_index = 0; static const struct option long_options[] = { {"add", 1, 0, 1 }, {"append",0,0, 0}, {"delete",1,0,0 }, {"verbose",0,0,0 }, {"create",1,0,'a'}, {"file",1,0,0 }, {0,0,0,0 } }; c = getopt_long( argc, argv, "abc:d:012", long_options, &option_index ); if(c==1)// returns "val" if flag is "NULL" { ret = KErrNone; } __UHEAP_MARKEND; return ret; }//end of function /* *Test name :setjmpTest *API :setjmp *Description :set jump point for a non-local goto. *If the return is from a direct invocation, setjmp() shall return 0. *If the return is from a call to longjmp(), setjmp() shall return a non-zero value. */ TInt CTestStdlib::setjmpTest() { jmp_buf jmpbuffer; static bool done = true; TInt ret = setjmp(jmpbuffer); if (!ret) { longjmp(jmpbuffer, 0); } else { if(done) { done = false; longjmp(jmpbuffer, 1); } } return KErrNone; } /* *Test Name :abortTest *API :abort *Description :generate an abnormal process abort and it does not return any value. *If myfile.txt does not exist, a message is printed and abort is called. */ TInt CTestStdlib::abortTest() { const char* command = "Z:\\sys\\bin\\abort_test.exe"; const char* mode ="r"; FILE* fp = popen(command, mode); if(fp==NULL) { return KErrGeneral; } pclose(fp); return KErrNone; } /* *Test Name :chownTest *API :chown *Descripetion :change owner and group of a file and and on success returns non negative integer. */ TInt CTestStdlib::chownTest() { TInt err; FILE* pFile; char name[15]= "c:\\myfile.txt"; pFile = fopen (name,"w+"); if (pFile == NULL) { INFO_PRINTF1(_L("file opening error")); } uid_t own = 13; gid_t grp = 23; err = chown(name,own,grp); if(err <0) { return KErrGeneral; } fclose(pFile); unlink(name); return KErrNone; } /* *Test Name :iconvTestL *API :iconv *Description :The iconv utility converts the characters or sequences of *characters in file from one code set to another and writes the results to standard output. *If an error occurs iconv() returns (size_t)-1 */ TInt CTestStdlib::iconvTest() { iconv_t cd = NULL; char utf8[12] = "abcd"; char iso[12]; const char *inbuf; char *outbuf; size_t err; size_t inbytes = 4; size_t outbytes = 4; inbuf = (const char*) utf8; outbuf = (char *) iso; cd = iconv_open("UTF-8", "ISO-8859-1"); if(cd == (iconv_t) -1) { INFO_PRINTF1(_L("Unbale to create a conversion descriptor0")); return KErrGeneral; } err=iconv (cd, &inbuf, &inbytes, &outbuf, &outbytes); if(err == (size_t)-1) { INFO_PRINTF1(_L("Unbale to create a conversion descriptor0")); return KErrGeneral; } iconv_close(cd); return KErrNone; } /* *Testcase Name :getgrentTest() *API :getgrent(),setgrent() and endgrent() *Description :get the group database entry and The getgrent() function returns a pointer to a structure containing the broken-out fields of an entry in the group database. */ TInt CTestStdlib::setgrentTest() { struct group *name; INFO_PRINTF1(_L("call to getgrent\n")); setgrent(); name = (struct group*)getgrent(); if(name == NULL) { return KErrGeneral; } free(name->gr_mem); free(name); endgrent(); return KErrNone; } /* *Testcase Name :wcreatTest *API :wcreat *Description :it creates a file in current working directory(if file exists then it is truncated). *Returns a non-negative value upon success. */ TInt CTestStdlib::wcreatTest() { TInt fd = 0; fd = wcreat(L"Example.txt" ,0666); if(fd < 0 ) { INFO_PRINTF1(_L("File creation failed \n")); return KErrGeneral; } return KErrNone; }
[ "none@none" ]
[ [ [ 1, 7856 ] ] ]
eed9e35ebac310bd51554fec056a850447af4fcf
ae395aec108ca518a46a867842b9b83c0c39f8a2
/cs2310/ICEditor/Gui/Transition.cpp
58082d0f80a250ad721fc0b3690b3ca8dfa47e7d
[]
no_license
coolboy/iceditor
df8d580f32f77e7b67e2f48e84d3957b1ad8959d
ff1c626ee4f7038a7479b52f32d2585779390f46
refs/heads/master
2020-06-04T19:22:34.229941
2011-01-01T21:24:41
2011-01-01T21:24:41
32,131,682
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
#include "StdAfx.h" #include "Transition.h" extern QRegExp regexp/*("((\"\\s+\")|\")")*/; Transition::Transition(void):Id(-1),srcId(-1),targetId(-1) { } Transition::~Transition(void) { } Transition::Transitions Transition::load( QStringList strLs ) { Transitions ret; foreach (QString str, strLs) { QStringList sls = str.split(regexp); qDebug()<<sls; Transition tran; tran.Id = sls[1].toInt(); tran.Type = sls[2]; tran.srcId = sls[3].toInt(); tran.targetId = sls[4].toInt(); ret.push_back(tran); } return ret; }
[ "angelucci.louis@8e7f2bb0-d97f-11de-8314-133c20781edd" ]
[ [ [ 1, 34 ] ] ]
dcb38855c9ce9e11bb827f5658ec2f67649f2bbd
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/qt/Api/qwebpage.h
4e1be13988bf517dcb7a15f43a3340b4f2ba8d7d
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,656
h
/* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) Copyright (C) 2007 Staikos Computing Services Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef QWEBPAGE_H #define QWEBPAGE_H #include "qwebsettings.h" #include "qwebkitglobal.h" #include <QtCore/qobject.h> #include <QtCore/qurl.h> #include <QtGui/qwidget.h> QT_BEGIN_NAMESPACE class QNetworkProxy; class QUndoStack; class QMenu; class QNetworkRequest; class QNetworkReply; class QNetworkAccessManager; QT_END_NAMESPACE class QWebElement; class QWebFrame; class QWebNetworkRequest; class QWebHistory; class QWebFrameData; class QWebHistoryItem; class QWebHitTestResult; class QWebNetworkInterface; class QWebPagePrivate; class QWebPluginFactory; class QtViewportConfigurationPrivate; namespace WebCore { class ChromeClientQt; class EditorClientQt; class FrameLoaderClientQt; class InspectorClientQt; class InspectorFrontendClientQt; class NotificationPresenterClientQt; class GeolocationPermissionClientQt; class ResourceHandle; class HitTestResult; class QNetworkReplyHandler; struct FrameLoadRequest; } class QWEBKIT_EXPORT QWebPage : public QObject { Q_OBJECT Q_PROPERTY(bool modified READ isModified) Q_PROPERTY(QString selectedText READ selectedText) Q_PROPERTY(QSize viewportSize READ viewportSize WRITE setViewportSize) Q_PROPERTY(QSize preferredContentsSize READ preferredContentsSize WRITE setPreferredContentsSize) Q_PROPERTY(bool forwardUnsupportedContent READ forwardUnsupportedContent WRITE setForwardUnsupportedContent) Q_PROPERTY(LinkDelegationPolicy linkDelegationPolicy READ linkDelegationPolicy WRITE setLinkDelegationPolicy) Q_PROPERTY(QPalette palette READ palette WRITE setPalette) Q_PROPERTY(bool contentEditable READ isContentEditable WRITE setContentEditable) Q_ENUMS(LinkDelegationPolicy NavigationType WebAction) public: enum NavigationType { NavigationTypeLinkClicked, NavigationTypeFormSubmitted, NavigationTypeBackOrForward, NavigationTypeReload, NavigationTypeFormResubmitted, NavigationTypeOther }; enum WebAction { NoWebAction = - 1, OpenLink, OpenLinkInNewWindow, OpenFrameInNewWindow, DownloadLinkToDisk, CopyLinkToClipboard, OpenImageInNewWindow, DownloadImageToDisk, CopyImageToClipboard, Back, Forward, Stop, Reload, Cut, Copy, Paste, Undo, Redo, MoveToNextChar, MoveToPreviousChar, MoveToNextWord, MoveToPreviousWord, MoveToNextLine, MoveToPreviousLine, MoveToStartOfLine, MoveToEndOfLine, MoveToStartOfBlock, MoveToEndOfBlock, MoveToStartOfDocument, MoveToEndOfDocument, SelectNextChar, SelectPreviousChar, SelectNextWord, SelectPreviousWord, SelectNextLine, SelectPreviousLine, SelectStartOfLine, SelectEndOfLine, SelectStartOfBlock, SelectEndOfBlock, SelectStartOfDocument, SelectEndOfDocument, DeleteStartOfWord, DeleteEndOfWord, SetTextDirectionDefault, SetTextDirectionLeftToRight, SetTextDirectionRightToLeft, ToggleBold, ToggleItalic, ToggleUnderline, InspectElement, InsertParagraphSeparator, InsertLineSeparator, SelectAll, ReloadAndBypassCache, PasteAndMatchStyle, RemoveFormat, ToggleStrikethrough, ToggleSubscript, ToggleSuperscript, InsertUnorderedList, InsertOrderedList, Indent, Outdent, AlignCenter, AlignJustified, AlignLeft, AlignRight, StopScheduledPageRefresh, WebActionCount }; enum FindFlag { FindBackward = 1, FindCaseSensitively = 2, FindWrapsAroundDocument = 4, HighlightAllOccurrences = 8 }; Q_DECLARE_FLAGS(FindFlags, FindFlag) enum LinkDelegationPolicy { DontDelegateLinks, DelegateExternalLinks, DelegateAllLinks }; enum WebWindowType { WebBrowserWindow, WebModalDialog }; enum PermissionPolicy { PermissionGranted, PermissionUnknown, PermissionDenied }; enum PermissionDomain { NotificationsPermissionDomain, GeolocationPermissionDomain }; class ViewportConfiguration { public: ViewportConfiguration(); ViewportConfiguration(const QWebPage::ViewportConfiguration& other); ~ViewportConfiguration(); QWebPage::ViewportConfiguration& operator=(const QWebPage::ViewportConfiguration& other); inline qreal initialScaleFactor() const { return m_initialScaleFactor; }; inline qreal minimumScaleFactor() const { return m_minimumScaleFactor; }; inline qreal maximumScaleFactor() const { return m_maximumScaleFactor; }; inline qreal devicePixelRatio() const { return m_devicePixelRatio; }; inline bool isUserScalable() const { return m_isUserScalable; }; inline bool isValid() const { return m_isValid; }; inline QSize size() const { return m_size; }; private: QSharedDataPointer<QtViewportConfigurationPrivate> d; qreal m_initialScaleFactor; qreal m_minimumScaleFactor; qreal m_maximumScaleFactor; qreal m_devicePixelRatio; bool m_isUserScalable; bool m_isValid; QSize m_size; friend class WebCore::ChromeClientQt; friend class QWebPage; }; explicit QWebPage(QObject *parent = 0); ~QWebPage(); QWebFrame *mainFrame() const; QWebFrame *currentFrame() const; QWebFrame* frameAt(const QPoint& pos) const; QWebHistory *history() const; QWebSettings *settings() const; void setView(QWidget *view); QWidget *view() const; bool isModified() const; #ifndef QT_NO_UNDOSTACK QUndoStack *undoStack() const; #endif void setNetworkAccessManager(QNetworkAccessManager *manager); QNetworkAccessManager *networkAccessManager() const; void setPluginFactory(QWebPluginFactory *factory); QWebPluginFactory *pluginFactory() const; quint64 totalBytes() const; quint64 bytesReceived() const; QString selectedText() const; #ifndef QT_NO_ACTION QAction *action(WebAction action) const; #endif virtual void triggerAction(WebAction action, bool checked = false); QSize viewportSize() const; void setViewportSize(const QSize &size) const; ViewportConfiguration viewportConfigurationForSize(QSize availableSize) const; QSize preferredContentsSize() const; void setPreferredContentsSize(const QSize &size) const; virtual bool event(QEvent*); bool focusNextPrevChild(bool next); QVariant inputMethodQuery(Qt::InputMethodQuery property) const; bool findText(const QString &subString, FindFlags options = 0); void setForwardUnsupportedContent(bool forward); bool forwardUnsupportedContent() const; void setLinkDelegationPolicy(LinkDelegationPolicy policy); LinkDelegationPolicy linkDelegationPolicy() const; void setPalette(const QPalette &palette); QPalette palette() const; void setContentEditable(bool editable); bool isContentEditable() const; #ifndef QT_NO_CONTEXTMENU bool swallowContextMenuEvent(QContextMenuEvent *event); #endif void updatePositionDependentActions(const QPoint &pos); QMenu *createStandardContextMenu(); void setUserPermission(QWebFrame* frame, PermissionDomain domain, PermissionPolicy policy); enum Extension { ChooseMultipleFilesExtension, ErrorPageExtension }; class ExtensionOption {}; class ExtensionReturn {}; class ChooseMultipleFilesExtensionOption : public ExtensionOption { public: QWebFrame *parentFrame; QStringList suggestedFileNames; }; class ChooseMultipleFilesExtensionReturn : public ExtensionReturn { public: QStringList fileNames; }; enum ErrorDomain { QtNetwork, Http, WebKit }; class ErrorPageExtensionOption : public ExtensionOption { public: QUrl url; QWebFrame* frame; ErrorDomain domain; int error; QString errorString; }; class ErrorPageExtensionReturn : public ExtensionReturn { public: ErrorPageExtensionReturn() : contentType(QLatin1String("text/html")), encoding(QLatin1String("utf-8")) {}; QString contentType; QString encoding; QUrl baseUrl; QByteArray content; }; virtual bool extension(Extension extension, const ExtensionOption *option = 0, ExtensionReturn *output = 0); virtual bool supportsExtension(Extension extension) const; inline QWebPagePrivate* handle() const { return d; } public Q_SLOTS: bool shouldInterruptJavaScript(); Q_SIGNALS: void loadStarted(); void loadProgress(int progress); void loadFinished(bool ok); void linkHovered(const QString &link, const QString &title, const QString &textContent); void statusBarMessage(const QString& text); void selectionChanged(); void frameCreated(QWebFrame *frame); void geometryChangeRequested(const QRect& geom); void repaintRequested(const QRect& dirtyRect); void scrollRequested(int dx, int dy, const QRect& scrollViewRect); void windowCloseRequested(); void printRequested(QWebFrame *frame); void linkClicked(const QUrl &url); void toolBarVisibilityChangeRequested(bool visible); void statusBarVisibilityChangeRequested(bool visible); void menuBarVisibilityChangeRequested(bool visible); void unsupportedContent(QNetworkReply *reply); void downloadRequested(const QNetworkRequest &request); void microFocusChanged(); void contentsChanged(); void databaseQuotaExceeded(QWebFrame* frame, QString databaseName); void saveFrameStateRequested(QWebFrame* frame, QWebHistoryItem* item); void restoreFrameStateRequested(QWebFrame* frame); void viewportChangeRequested(); void requestPermissionFromUser(QWebFrame* frame, QWebPage::PermissionDomain domain); void checkPermissionFromUser(QWebFrame* frame, QWebPage::PermissionDomain domain, QWebPage::PermissionPolicy& policy); void cancelRequestsForPermission(QWebFrame* frame, QWebPage::PermissionDomain domain); protected: virtual QWebPage *createWindow(WebWindowType type); virtual QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues); virtual bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type); virtual QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); virtual void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); virtual bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); virtual bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); virtual void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); virtual QString userAgentForUrl(const QUrl& url) const; private: Q_PRIVATE_SLOT(d, void _q_onLoadProgressChanged(int)) #ifndef QT_NO_ACTION Q_PRIVATE_SLOT(d, void _q_webActionTriggered(bool checked)) #endif Q_PRIVATE_SLOT(d, void _q_cleanupLeakMessages()) QWebPagePrivate *d; friend class QWebFrame; friend class QWebPagePrivate; friend class QWebView; friend class QWebViewPrivate; friend class QGraphicsWebView; friend class QGraphicsWebViewPrivate; friend class QWebInspector; friend class WebCore::ChromeClientQt; friend class WebCore::EditorClientQt; friend class WebCore::FrameLoaderClientQt; friend class WebCore::InspectorClientQt; friend class WebCore::InspectorFrontendClientQt; friend class WebCore::NotificationPresenterClientQt; friend class WebCore::GeolocationPermissionClientQt; friend class WebCore::ResourceHandle; friend class WebCore::QNetworkReplyHandler; friend class DumpRenderTreeSupportQt; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QWebPage::FindFlags) #endif
[ [ [ 1, 438 ] ] ]
610d83e5e228c419db4ae7da974411d93a1cc298
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/l_clscript.cpp
ef7a995c2f936d3b3ed74a9fafbec08057622f80
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
14,455
cpp
/* ** Lua binding: clscript ** Generated automatically by tolua++-1.0.92 on 07/31/10 10:40:47. */ #ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h" /* Exported function */ TOLUA_API int tolua_clscript_open (lua_State* tolua_S); #include "cltpch.h" #include "tolua++.h" #pragma warning(disable : 4800) //forcing value to bool warning #include "clScriptFunction.h" #include "ClRegisterClass.h" #include "GameDefine.h" using namespace Script; /* function to register type */ static void tolua_reg_types (lua_State* tolua_S) { } /* function: ui_reg_char_info */ #ifndef TOLUA_DISABLE_tolua_clscript_ui_reg_char_info00 static int tolua_clscript_ui_reg_char_info00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { ui_reg_char_info(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'ui_reg_char_info'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: to_learn_skill */ #ifndef TOLUA_DISABLE_tolua_clscript_to_learn_skill00 static int tolua_clscript_to_learn_skill00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isboolean(tolua_S,3,1,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); unsigned int uActID = ((unsigned int) tolua_tonumber(tolua_S,2,0)); bool toUi = ((bool) tolua_toboolean(tolua_S,3,false)); { to_learn_skill(uEntID,uActID,toUi); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'to_learn_skill'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: to_bind_weapon */ #ifndef TOLUA_DISABLE_tolua_clscript_to_bind_weapon00 static int tolua_clscript_to_bind_weapon00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isstring(tolua_S,3,0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); unsigned int uWeaponID = ((unsigned int) tolua_tonumber(tolua_S,2,0)); const char* sNode = ((const char*) tolua_tostring(tolua_S,3,0)); { to_bind_weapon(uEntID,uWeaponID,sNode); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'to_bind_weapon'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_default_action */ #ifndef TOLUA_DISABLE_tolua_clscript_set_default_action00 static int tolua_clscript_set_default_action00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uActID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { set_default_action(uActID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_default_action'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_default_action_factory */ #ifndef TOLUA_DISABLE_tolua_clscript_set_default_action_factory00 static int tolua_clscript_set_default_action_factory00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { set_default_action_factory(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_default_action_factory'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_ui_monster_hp */ #ifndef TOLUA_DISABLE_tolua_clscript_set_ui_monster_hp00 static int tolua_clscript_set_ui_monster_hp00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { set_ui_monster_hp(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_ui_monster_hp'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_ui_player_hp */ #ifndef TOLUA_DISABLE_tolua_clscript_set_ui_player_hp00 static int tolua_clscript_set_ui_player_hp00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { set_ui_player_hp(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_ui_player_hp'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_ui_player_exp */ #ifndef TOLUA_DISABLE_tolua_clscript_set_ui_player_exp00 static int tolua_clscript_set_ui_player_exp00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { set_ui_player_exp(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_ui_player_exp'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: post_gameresult */ #ifndef TOLUA_DISABLE_tolua_clscript_post_gameresult00 static int tolua_clscript_post_gameresult00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isboolean(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { bool bFlag = ((bool) tolua_toboolean(tolua_S,1,0)); { post_gameresult(bFlag); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'post_gameresult'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_pathway */ #ifndef TOLUA_DISABLE_tolua_clscript_set_pathway00 static int tolua_clscript_set_pathway00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); unsigned int uPathwayID = ((unsigned int) tolua_tonumber(tolua_S,2,0)); { set_pathway(uEntID,uPathwayID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_pathway'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: add_item */ #ifndef TOLUA_DISABLE_tolua_clscript_add_item00 static int tolua_clscript_add_item00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); unsigned int uItemGID = ((unsigned int) tolua_tonumber(tolua_S,2,0)); { add_item(uEntID,uItemGID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'add_item'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: addin_minimap */ #ifndef TOLUA_DISABLE_tolua_clscript_addin_minimap00 static int tolua_clscript_addin_minimap00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { unsigned int uEntID = ((unsigned int) tolua_tonumber(tolua_S,1,0)); { addin_minimap(uEntID); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'addin_minimap'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: add_success_factor */ #ifndef TOLUA_DISABLE_tolua_clscript_add_success_factor00 static int tolua_clscript_add_success_factor00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnoobj(tolua_S,1,&tolua_err) ) goto tolua_lerror; else #endif { { add_success_factor(); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'add_success_factor'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: add_failure_factor */ #ifndef TOLUA_DISABLE_tolua_clscript_add_failure_factor00 static int tolua_clscript_add_failure_factor00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnoobj(tolua_S,1,&tolua_err) ) goto tolua_lerror; else #endif { { add_failure_factor(); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'add_failure_factor'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_success_factors */ #ifndef TOLUA_DISABLE_tolua_clscript_set_success_factors00 static int tolua_clscript_set_success_factors00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { int nCount = ((int) tolua_tonumber(tolua_S,1,0)); { set_success_factors(nCount); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_success_factors'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_failure_factors */ #ifndef TOLUA_DISABLE_tolua_clscript_set_failure_factors00 static int tolua_clscript_set_failure_factors00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isnumber(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { int nCount = ((int) tolua_tonumber(tolua_S,1,0)); { set_failure_factors(nCount); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_failure_factors'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* function: set_task_explain */ #ifndef TOLUA_DISABLE_tolua_clscript_set_task_explain00 static int tolua_clscript_set_task_explain00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isstring(tolua_S,1,0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { const char* pExplain = ((const char*) tolua_tostring(tolua_S,1,0)); { set_task_explain(pExplain); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'set_task_explain'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* Open function */ TOLUA_API int tolua_clscript_open (lua_State* tolua_S) { tolua_open(tolua_S); tolua_reg_types(tolua_S); tolua_module(tolua_S,NULL,0); tolua_beginmodule(tolua_S,NULL); tolua_function(tolua_S,"ui_reg_char_info",tolua_clscript_ui_reg_char_info00); tolua_function(tolua_S,"to_learn_skill",tolua_clscript_to_learn_skill00); tolua_function(tolua_S,"to_bind_weapon",tolua_clscript_to_bind_weapon00); tolua_function(tolua_S,"set_default_action",tolua_clscript_set_default_action00); tolua_function(tolua_S,"set_default_action_factory",tolua_clscript_set_default_action_factory00); tolua_function(tolua_S,"set_ui_monster_hp",tolua_clscript_set_ui_monster_hp00); tolua_function(tolua_S,"set_ui_player_hp",tolua_clscript_set_ui_player_hp00); tolua_function(tolua_S,"set_ui_player_exp",tolua_clscript_set_ui_player_exp00); tolua_function(tolua_S,"post_gameresult",tolua_clscript_post_gameresult00); tolua_function(tolua_S,"set_pathway",tolua_clscript_set_pathway00); tolua_function(tolua_S,"add_item",tolua_clscript_add_item00); tolua_function(tolua_S,"addin_minimap",tolua_clscript_addin_minimap00); tolua_function(tolua_S,"add_success_factor",tolua_clscript_add_success_factor00); tolua_function(tolua_S,"add_failure_factor",tolua_clscript_add_failure_factor00); tolua_function(tolua_S,"set_success_factors",tolua_clscript_set_success_factors00); tolua_function(tolua_S,"set_failure_factors",tolua_clscript_set_failure_factors00); tolua_function(tolua_S,"set_task_explain",tolua_clscript_set_task_explain00); tolua_constant(tolua_S,"id_cl_entity",id_cl_entity); tolua_constant(tolua_S,"id_bullet_factor",id_bullet_factor); tolua_constant(tolua_S,"id_summon_factor",id_summon_factor); tolua_constant(tolua_S,"id_chain_factor",id_chain_factor); tolua_constant(tolua_S,"id_normal_factor",id_normal_factor); tolua_constant(tolua_S,"id_collapsar_factor",id_collapsar_factor); tolua_constant(tolua_S,"id_level_cl",id_level_cl); tolua_constant(tolua_S,"id_player",id_player); tolua_endmodule(tolua_S); return 1; } #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501 TOLUA_API int luaopen_clscript (lua_State* tolua_S) { return tolua_clscript_open(tolua_S); }; #endif
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 20 ], [ 22, 66 ], [ 68, 88 ], [ 149, 521 ], [ 524, 538 ], [ 541, 555 ] ], [ [ 21, 21 ], [ 67, 67 ], [ 89, 148 ], [ 522, 523 ], [ 539, 540 ] ] ]
bca9fb8fc0c3dad44c5bdd67bb82574f54b8ae4d
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/theme/basic/CheckBoxTheme.h
546c4caafb318b19dc77bad5a5e2bc8cf9f06e2f
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,542
h
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BASICCHECKBOXTHEME_H #define BASICCHECKBOXTHEME_H #include "./ButtonTheme.h" #include "../../Icon.h" namespace ui { namespace theme { namespace basic { class CheckBoxTheme : public ButtonTheme { public: void installTheme(Component *comp); private: class SelectedIcon : public Icon { public: SelectedIcon(); int getIconHeight() const; int getIconWidth() const; void paint(const Component *comp, Graphics &g, int x, int y) const; private: util::Color foreground; util::Color background; }; class DefaultIcon : public Icon { public: DefaultIcon(); int getIconHeight() const; int getIconWidth() const; void paint(const Component *comp, Graphics &g, int x, int y) const; private: util::Color foreground; util::Color background; }; DefaultIcon defaultIcon; SelectedIcon selectedIcon; }; } } } #endif
[ "bs@bram.(none)" ]
[ [ [ 1, 77 ] ] ]
ddf2f3136b5befe729b7063ba291770355a66c02
c8f467a4cee0b4067b93936574c884c9de0b36cf
/source/Irrlicht/CImageLoaderPCX.h
55f5dc1b333b765769a086cc527e441442570d13
[ "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-other-permissive" ]
permissive
flaithbheartaigh/mirrlicht
1ff418d29017e55e5f4a27a70dcfd5a88cb244b5
ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b
refs/heads/master
2021-01-10T11:29:49.569701
2009-01-12T21:08:31
2009-01-12T21:08:31
49,994,212
0
0
null
null
null
null
UTF-8
C++
false
false
2,274
h
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_IMAGE_LOADER_PCX_H_INCLUDED__ #define __C_IMAGE_LOADER_PCX_H_INCLUDED__ #include "IImageLoader.h" namespace irr { namespace video { // byte-align structures #if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) # pragma pack( push, packing ) # pragma pack( 1 ) # define PACK_STRUCT #elif defined( __GNUC__ ) # define PACK_STRUCT __attribute__((packed)) #elif defined(__SYMBIAN32__) # if defined(__WINS__) # define PACK_STRUCT # pragma pack(1) # else # define PACK_STRUCT __attribute__((packed,aligned(1))) # endif #else # error compiler not supported #endif struct SPCXHeader { u8 Manufacturer; u8 Version; u8 Encoding; u8 BitsPerPixel; u16 XMin; u16 YMin; u16 XMax; u16 YMax; u16 HorizDPI; u16 VertDPI; u8 Palette[48]; u8 Reserved; u8 Planes; u16 BytesPerLine; u16 PaletteType; u16 HScrSize; u16 VScrSize; u8 Filler[54]; } PACK_STRUCT; // Default alignment #if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) # pragma pack( pop, packing ) #elif defined(__SYMBIAN32__) && defined(__WINS__) # pragma pack(4) //default alignment in Project settings #endif #undef PACK_STRUCT /*! Image Loader for Windows PCX bitmaps. This loader was written and sent in by Dean P. Macri. I modified only some small bits of it. */ class CImageLoaderPCX : public IImageLoader { public: //! constructor CImageLoaderPCX(); //! destructor virtual ~CImageLoaderPCX(); //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".tga") virtual bool isALoadableFileExtension(const c8* fileName); //! returns true if the file maybe is able to be loaded by this class virtual bool isALoadableFileFormat(irr::io::IReadFile* file); //! creates a surface from the file virtual IImage* loadImage(irr::io::IReadFile* file); private: u8* PCXData; s32* PaletteData; }; } // end namespace video } // end namespace irr #endif
[ "limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf" ]
[ [ [ 1, 104 ] ] ]
5b444c4a877e3df578c05955f050cf8c6e1628e2
88f4b257863d50044212e6036dd09a25ec65a1ff
/src/jingxian/string/stringOps.h
0ffb6af0ef20f0ad228a106a69323cca8b39065a
[]
no_license
mei-rune/jx-proxy
bb1ee92f6b76fb21fdf2f4d8a907823efd05e17b
d24117ab62b10410f2ad05769165130a9f591bfb
refs/heads/master
2022-08-20T08:56:54.222821
2009-11-14T07:01:08
2009-11-14T07:01:08
null
0
0
null
null
null
null
GB18030
C++
false
false
13,537
h
#ifndef _STRINGOPS_H_ #define _STRINGOPS_H_ #include "jingxian/config.h" #if !defined (JINGXIAN_LACKS_PRAGMA_ONCE) # pragma once #endif /* JINGXIAN_LACKS_PRAGMA_ONCE */ // Include files # include "jingxian/string/os_string.h" _jingxian_begin namespace detail { template< typename charT > class StringOp { public: static charT* malloc(size_t size) { return (charT*)::my_malloc(size); } static charT* dup(const charT* p) { return string_traits< charT>::strdup(p); } static void free(void* p) { ::my_free(p); } }; }; /** * symbol[var] */ inline bool square_pattern(const tstring& src , tstring& symbol , tstring& var) { if (src.size() < 2) return false; tstring::size_type square_start = src.find('['); if (tstring::npos == square_start) { symbol = src; return true; } tstring::size_type square_end = src.find(']' , square_start); if (tstring::npos == square_end) { symbol = src.substr(0, square_start); return true; } symbol = src.substr(0, square_start); var = src.substr(square_start + 1, square_end - square_start - 1); return true; } ///** // * ๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒๅฟฝ็•ฅๅคงๅฐๆŸฅๆ‰พๅญ—็ฌฆ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆ // * @param[ in ] offest ๅ็งป๏ผŒไปฅ0ๅผ€ๅง‹ // * @return ๆ‰พๅˆฐ่ฟ”ๅ›žๅฎƒไปฅ0ๅผ€ๅง‹็š„ไฝ็ฝฎ๏ผŒๆฒกๆœ‰่ฟ”ๅ›žnpos // */ //inline //tstring::size_type //casefind (const tstring &s, // tchar what, // tstring::size_type offset /* = 0 */ ) //{ // ASSERT (offset >= 0); // ASSERT ((size_t) offset <= s.size ()); // // const tchar *begin = s.c_str (); // // // const tchar *end = begin + s.size (); // const tchar *p = begin + offset; // // for (tstring::size_type ch = _totlower ( what ); p != end; ++p) // if (_totlower ( *p) == ch ) // return p - begin; // return tstring::npos; // } // ///** // * ๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒๅฟฝ็•ฅๅคงๅฐๆŸฅๆ‰พๅญ—็ฌฆไธฒ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆไธฒ // * @param[ in ] len whatๅญ—็ฌฆไธฒ็š„้•ฟๅบฆ // * @param[ in ] offest ๅ็งป๏ผŒไปฅ0ๅผ€ๅง‹ // * @return ๆ‰พๅˆฐ่ฟ”ๅ›žๅฎƒไปฅ0ๅผ€ๅง‹็š„ไฝ็ฝฎ๏ผŒๆฒกๆœ‰่ฟ”ๅ›žnpos // */ //inline //tstring::size_type //casefind (const tstring &s, // const tchar *what, // tstring::size_type len, // tstring::size_type offset /* = 0 */ ) //{ // ASSERT ((size_t) offset <= s.size ()); // ASSERT (what || !len); // // if (s.size () - offset < len) // return tstring::npos; // // if (! what ) // return offset; // // const tchar *begin = s.c_str (); // const tchar *end = begin + s.size (); // const tchar *p = begin + offset; // // for ( ; p <= end-len; ++p) // if (! _tcsnicmp (p, what, len)) // return p - begin; // return tstring::npos; //} // ///** // * ๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒ็š„ๆŒ‡ๅฎš็š„ๅๅค„ๅ‘ๅทฆๅฟฝ็•ฅๅคงๅฐๆŸฅๆ‰พๅญ—็ฌฆ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆ // * @param[ in ] offest ๅ็งป๏ผŒไปฅ0ๅผ€ๅง‹ // * @return ๆ‰พๅˆฐ่ฟ”ๅ›žๅฎƒไปฅ0ๅผ€ๅง‹็š„ไฝ็ฝฎ๏ผŒๆฒกๆœ‰่ฟ”ๅ›žnpos // */ //inline //tstring::size_type //caserfind (const tstring &s, // tchar what, // tstring::size_type offset /* = tstring::npos*/) //{ // ASSERT ((size_t) offset <= s.size ()); // // const tchar *begin = s.c_str (); // const tchar *p = begin + offset + 1; // for (tstring::size_type ch = _totlower ( what); p != begin; --p) // if (_totlower ( p[tstring::npos]) == ch) // return p - begin - 1; // return tstring::npos; //} // ///** // * ๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒ็š„ๆŒ‡ๅฎš็š„ๅๅค„ๅ‘ๅทฆๅฟฝ็•ฅๅคงๅฐๆŸฅๆ‰พๅญ—็ฌฆไธฒ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆไธฒ // * @param[ in ] len whatๅญ—็ฌฆไธฒ็š„้•ฟๅบฆ // * @param[ in ] offest ๅ็งป๏ผŒไปฅ0ๅผ€ๅง‹ // * @return ๆ‰พๅˆฐ่ฟ”ๅ›žๅฎƒไปฅ0ๅผ€ๅง‹็š„ไฝ็ฝฎ๏ผŒๆฒกๆœ‰่ฟ”ๅ›žnpos // */ //inline //tstring::size_type //caserfind (const tstring &s, // const tchar *what, // tstring::size_type len, // tstring::size_type offset /* = tstring::npos*/) //{ // ASSERT ((size_t) offset <= s.size ()); // ASSERT (!what || !len); // // if (s.size () < len) // return tstring::npos; // // if (s.size () - len < (size_t) offset) // offset = s.size () - len; // // if (! what) // return offset; // // const char *begin = s.c_str (); // const char *p = begin + offset + 1; // // for ( ; p != begin; --p) // if (! _tcsnicmp ( p, what, len)) // return p - begin - 1; // return tstring::npos; //} // ///** // * ๆ‰พๅ‡บๅŒ…ๅซๆŒ‡ๅฎšๅญ—็ฌฆไธฒ็š„ๆ‰€ๆœ‰ๅญ—็ฌฆไธฒ // * @param[ in ] items ๅญ—็ฌฆไธฒๆ•ฐ็ป„ // * @param[ in ] what ๅญ—็ฌฆไธฒ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ //inline //StringList //grep (const StringList &items, // const tstring &what, // bool CaseInsensitive /* = false */) //{ // StringList result; // if( CaseInsensitive ) // { // for (size_t i = 0; i < items.size (); ++i) // if (casefind (items [i], what.c_str (), what.size () ,0 ) != tstring::npos ) // result.push_back (items [i]); // } // else // { // for (size_t i = 0; i < items.size (); ++i) // if (items[i].find ( what ) != tstring::npos ) // result.push_back (items [i]); // } // // return result; //} // ///** // * ่ฎก็ฎ—ๆŒ‡ๅฎšๅญ—็ฌฆๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒไธญๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ //inline //tstring::size_type //contains (const tstring &s, // tchar what, // bool Casesensitive /* = false */) //{ // tstring::size_type n = 0; // tstring::size_type index = 0; // if( Casesensitive ) // { // while ((index = casefind (s, what, index )) != tstring::npos ) // ++n, ++index; // } // else // { // while ((index = s.find ( what, index )) != tstring::npos ) // ++n, ++index; // } // return n; //} // ///** // * ่ฎก็ฎ—ๆŒ‡ๅฎšๅญๅญ—็ฌฆไธฒๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒไธญๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญๅญ—็ฌฆไธฒ // * @param[ in ] len ๅญๅญ—็ฌฆไธฒ็š„้•ฟๅบฆ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ //inline //tstring::size_type //contains (const tstring &s, // const tchar *what, // tstring::size_type len, // bool Casesensitive /* = false */) //{ // ASSERT( what != 0 ); // ASSERT( *what != 0 ); // tstring::size_type n = 0; // tstring::size_type index = 0; // if( Casesensitive ) // { // while ((index = casefind (s, what, len, index )) != tstring::npos ) // ++n, ++index; // } // else // { // while ((index = s.find ( what, len, index )) != tstring::npos ) // ++n, ++index; // } // return n; //} // ///** // * ่ฎก็ฎ—ๆŒ‡ๅฎšๅญๅญ—็ฌฆไธฒๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒไธญๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญๅญ—็ฌฆไธฒ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ //inline //tstring::size_type //contains (const tstring &s, // const tchar *what, // bool Casesensitive /* = false */) //{ // size_t len = strlen (what); // return contains( s,what,len,Casesensitive); //} // ///** // * ่ฎก็ฎ—ๆŒ‡ๅฎšๅญๅญ—็ฌฆไธฒๅœจๆŒ‡ๅฎšๅญ—็ฌฆไธฒไธญๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญๅญ—็ฌฆไธฒ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ //inline tstring::size_type //contains (const tstring &s, // const tstring &what, // bool Casesensitive /* = false */) //{ // return contains( s, what.c_str(), what.size(), Casesensitive ); //} // /////** //// * ็”จwithๅญๅญ—็ฌฆไธฒๆ›ฟๆขsๅญ—็ฌฆไธฒไธญๆŒ‡ๅฎšๅ็งปๅŽ็š„ๆ‰€ๆœ‰ๆŒ‡ๅฎš็š„whatๅญๅญ—็ฌฆไธฒ //// * @param[ in ] s ๅญ—็ฌฆไธฒ //// * @param[ in ] offset ๅ็งป้‡ //// * @param[ in ] what ๅญๅญ—็ฌฆไธฒ //// * @param[ in ] with ๅญๅญ—็ฌฆไธฒ //// * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) //// * @return ่ฟ”ๅ›žๆ›ฟๆขๅŽ็š„ๅญ—็ฌฆไธฒใ€‚ //// */ ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// const tchar* what, //// tstring::size_type whatlen, //// const tchar* with, //// tstring::size_type withlen, //// bool Casesensitive ) ////{ //// tstring result (s); //// if( Casesensitive ) //// { //// while (true) //// { //// if ((offset = casefind( result, what, whatlen, offset) ) == tstring::npos ) //// break; //// result.replace( offset, whatlen, with , with + withlen ); //// offset += ( withlen + 1 ); //// } //// } //// else //// { //// while (true) //// { //// if ((offset = result.find( what, offset, whatlen ) ) == tstring::npos ) //// break; //// result.replace( offset, whatlen, with , with + withlen ); //// offset += ( withlen + 1 ); //// } //// } //// return result; ////} //// ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// tchar what, //// const tchar* with, //// tstring::size_type len, //// bool Casesensitive ) ////{ //// return replace( s, offset, &what, 1, with, len, Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// tchar what, //// const tchar* with, //// bool Casesensitive ) ////{ //// return replace( s, offset, //// &what, 1, //// with, _tcslen( with ), //// Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// tchar what, //// const tstring &with, //// bool Casesensitive ) ////{ //// return replace( s, offset, //// what, //// with.c_str(),with.size(), //// Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// const tchar* what, //// const tchar* with, //// bool Casesensitive ) ////{ //// return replace( s, offset, //// what,_tcslen( what ), //// with, _tcslen( with ), //// Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// tstring::size_type offset, //// const tstring& what, //// const tstring& with, //// bool Casesensitive ) ////{ //// return replace( s, offset, //// what.c_str(),what.size( ), //// with.c_str(), with.size( ), //// Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// const tchar* what, //// const tchar* with, //// bool Casesensitive ) ////{ //// return replace( s, 0, //// what,_tcslen( what ), //// with, _tcslen( with ), //// Casesensitive ); ////} //// ////inline ////tstring ////replace (const tstring &s, //// const tstring &what, //// const tstring &with, //// bool Casesensitive ) ////{ //// return replace (s, 0, //// what.c_str(), what.size(), //// with.c_str(), with.size(), //// Casesensitive ); ////} // ///** // * ๅˆ ้™คๅญ—็ฌฆไธฒไธญๆŒ‡ๅฎšๅ็งปๅŽ็š„ๆ‰€ๆœ‰ๆŒ‡ๅฎš็š„ๅญ—็ฌฆ // * @param[ in ] s ๅญ—็ฌฆไธฒ // * @param[ in ] what ๅญ—็ฌฆ // * @param[ in ] Casesensitive ๆ˜ฏๅฆๅŒบๅˆ†ๅคงๅฐๅ†™๏ผŒ( true ๅŒบๅˆ†๏ผŒ false ไธๅŒบๅˆ† ) // * @return ่ฟ”ๅ›žๆ‰€ๆœ‰ๅŒ…ๅซwhatๅญ—็ฌฆไธฒ็š„ๅญ—็ฌฆไธฒใ€‚ // */ ////inline ////tstring ////remove (const tstring &s, //// tchar what, //// tstring::size_type offset /* = 0 */) ////{ return replace (s, offset, what, "",0); } //// ////tstring ////remove (const tstring &s, //// const tstring &what, //// tstring::size_type offset /* = 0 */) ////{ return replace (s, offset, what.c_str(),what.size(), "",0); } // //inline //bool startwith( const tchar* str, const tchar* with ) //{ // if( str == 0 || *str == 0 ) // return false; // if( with == 0 || *with == 0 ) // return true; // // while( *with == *str ) // { // if( *with == 0 ) // return true; // if( *str == 0 ) // return false; // with ++; // str ++; // } // return false; //} // //inline //bool endwith( const tchar* str, const tchar* with ) //{ // if( str == 0 || *str == 0 ) // return false; // if( with == 0 || *with == 0 ) // return true; // // const char* s = str; // while( *s != 0 ) s ++; // const char* w = with; // while( *w != 0 ) w ++; // // while( *w == *s ) // { // if( w == with ) // return true; // if( str == s ) // return false; // w --; // s --; // } // return false; //} _jingxian_end #endif // _STRINGOPS_H_
[ "[email protected]@53e742d2-d0ea-11de-97bf-6350044336de" ]
[ [ [ 1, 513 ] ] ]
78b3367b5311052a8a3ecf5891dbb22f48705a45
305f56324b8c1625a5f3ba7966d1ce6c540e9d97
/src/lister/TransGuideGrid.cpp
05f2d61807f0a4fae16d33a4ee4ec777c3a5137d
[]
no_license
radtek/lister
be45f7ac67da72c1c2ac0d7cd878032c9648af7b
71418c72b31823624f545ad86cc804c43b6e9426
refs/heads/master
2021-01-01T19:56:30.878680
2011-06-22T17:04:13
2011-06-22T17:04:13
41,946,076
0
0
null
null
null
null
UTF-8
C++
false
false
1,552
cpp
/*********************************************************************************************** * lister - TransGuideGrid.cpp * * I can't remember what this was for. For macro translation? We have taskdriver and other * objects, so we may drop. * Author: Jeff Humphreys * * 2011 * http://code.google.com/p/lister/ * http://lister.googlecode.com/svn/trunk/ lister-read-only * I used http://sourceforge.net/projects/win32svn/ * I recommend http://tortoisesvn.tigris.org/ for SVN Client use from Windows Explorer * ***********************************************************************************************/ #include "TransGuideGrid.h" //============================================================================================== TransGuideGrid::TransGuideGrid(GridType gridType) { } //============================================================================================== void TransGuideGrid::Build(Connection *pconnection) { //select count (distinct colno) from transguidemap where transguideid = 5 and looped is true; //select colno, max(tagname) as tagname from transguidemap where transguideid = 5 and looped is true group by colno order by colno; // for i = 1 to nofcols // AddColumn(tagName, } //============================================================================================== void TransGuideGrid::Load() { //select * from transguidemap where transguideid = 5 and looped is true order by loopno, colno // while not eof // fetch }
[ "jeffshumphreys@97668ed5-8355-0e3d-284e-ab2976d7b0b4" ]
[ [ [ 1, 39 ] ] ]
a0f75890bc51f937debf10488dbbfd8324ee18ee
ccc3e2995bc64d09b9e88fea8c1c7e2029a60ed8
/SO/Trabalhos/Trabalho 2/tmp_src/31401/GestordePistas/Trabalho2/source/Plane.cpp
960df7b0d89221e73a181388d8ae33bba9b67ee5
[]
no_license
masterzdran/semestre5
e559e93017f5e40c29e9f28466ae1c5822fe336e
148d65349073f8ae2f510b5659b94ddf47adc2c7
refs/heads/master
2021-01-25T10:05:42.513229
2011-02-20T17:46:14
2011-02-20T17:46:14
35,061,115
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
#include "..\headers\Semaforo.h" class Plane{ int id; Semaforo *sPlane; public: Plane(){ id = GetCurrentThreadId(); sPlane = new Semaforo(0); } ~Plane(){ id= 0; delete(sPlane); } };
[ "nuno.cancelo@b139f23c-5e1e-54d6-eab5-85b03e268133" ]
[ [ [ 1, 16 ] ] ]
4779fd8181c2def83cace394dac2753de9e5b09a
5efbd0cc4133aabbf0fa25a55e81bd8efe9040fd
/include/sp_ext_define.h
c4d788e8dda3528030518466684396a714a16cca
[]
no_license
electri/spext
b4041dea8e1b3f7f92fa8dd01b038165836b74cb
352809d2fba8f5528cdff7195a3ecdcc08be7ba4
refs/heads/master
2016-09-02T05:56:10.173821
2011-07-18T14:35:58
2011-07-18T14:35:58
35,587,658
0
0
null
null
null
null
GB18030
C++
false
false
6,115
h
/** Copyright (c) 2008-2010 * All rights reserved. * * ๆ–‡ไปถๅ็งฐ: aot_inet_define.h * ๆ‘˜ ่ฆ: ๅฐ่ฃ…็ฝ‘็ปœ้€š่ฎฏ็š„ๆ“ไฝœๆŽฅๅฃ * * ๅฝ“ๅ‰็‰ˆๆœฌ๏ผš 1.0 * ไฝœ ่€…: ้™ˆๅญฆๆœฏ * ๆ“ ไฝœ: ๆ–ฐๅปบ * ๅฎŒๆˆๆ—ฅๆœŸ: 2010ๅนด03ๆœˆ07ๆ—ฅ */ #ifndef __SP_EXT_DEFINE_H__ #define __SP_EXT_DEFINE_H__ #include <string> #include <Windows.h> #include <time.h> #include <WinSock.h> namespace sp_ext{ #ifdef WIN32 typedef UINT8 uint8_t; typedef UINT16 uint16_t; typedef UINT32 uint32_t; typedef UINT64 uint64_t; #else #include <ace\basic_types.h> typedef ACE_UINT8 uint8_t; typedef ACE_UINT16 uint16_t; typedef ACE_UINT32 uint32_t; typedef ACE_UINT64 uint64_t; #endif #define __SP_EXT_INT32_B0(n) ((uint8_t)((uint32_t)(n) & 0xff)) #define __SP_EXT_INT32_B1(n) ((uint8_t) (((uint32_t)(n) & 0xff00) >> 8)) #define __SP_EXT_INT32_B2(n) ((uint8_t) (((uint32_t)(n) & 0xff0000) >> 16)) #define __SP_EXT_INT32_B3(n) ((uint8_t) (((uint32_t)(n) & 0xff000000) >> 24)) enum { e_ret_ok = 0, e_ret_failed = -1, e_ret_again = -2, }; struct inet_addr_t { /// host byte order unsigned long ip; /// host byte order unsigned short port; }; struct inet_time_t { long sec; /// ็ง’ long usec; /// ๅพฎ็ง’ }; #pragma warning(disable:4996) /// ip, port : ไธปๆœบๅญ—่Š‚ๅบ inline char* inet_addr_to_str(unsigned long ip, unsigned short port, char* buf) { ip = ::htonl(ip); unsigned char* p = (unsigned char*)(&ip); sprintf(buf, "%d.%d.%d.%d:%d", // 192.168.1.134 p[0], p[1], p[2], p[3], port); return buf; } inline std::string inet_addr_to_str(unsigned long ip, unsigned short port) { ip = ::htonl(ip); unsigned char* p = (unsigned char*)(&ip); char buf[64]; sprintf(buf, "%d.%d.%d.%d:%d", p[0], p[1], p[2], p[3], port); return buf; } inline std::string inet_addr_to_str(unsigned long ip) { ip = ::htonl(ip); unsigned char* p = (unsigned char*)(&ip); char buf[64]; sprintf(buf, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); return buf; } inline std::string inet_addr_to_str(const inet_addr_t* addr) { return inet_addr_to_str(addr->ip, addr->port); } inline char* inet_addr_to_str(unsigned long ip, char* buf) { ip = ::htonl(ip); unsigned char* p = (unsigned char*)(&ip); sprintf(buf, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); return buf; } //////////////////////////////////////////////////////////////////// // inet_time_t ่พ…ๅŠฉๅ‡ฝๆ•ฐ //////////////////////////////////////////////////////////////////// inline bool operator<(const inet_time_t& t1, const inet_time_t& t2) { return t1.sec==t2.sec? t1.usec<t2.usec : t1.sec<t2.sec; } inline inet_time_t operator-(const inet_time_t& t1, const inet_time_t& t2) { inet_time_t t; t.sec = t1.sec - t2.sec; t.usec = t1.usec - t2.usec; if( t.usec<0 ) { t.usec +=1000000; t.sec--; } return t; } inline inet_time_t& operator+=(inet_time_t& t1, const inet_time_t& t2) { t1.sec += t2.sec; t1.usec += t2.usec; if( t1.usec>=1000000 ) { t1.usec-=1000000; t1.sec++; } return t1; } /// ่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด inline int get_timeofday(inet_time_t* t, void* p = NULL) { #if 0 if( t==NULL ) return -1; FILETIME ft; GetSystemTimeAsFileTime (&ft); uint64_t tim = filetime_to_unix_epoch (&ft); t->sec = (long) (tim / 1000000L); t->tv_usec = (long) (tim % 1000000L); return 0; #else if( t ) { t->sec = (long)time(NULL); t->usec = (GetTickCount()%1000) *1000; } return -1; #endif } inline char* get_datetime(char* buf, const time_t& tv) { struct tm t; if( localtime_s(&t, &tv)==0 ) { sprintf(buf, "%04d/%02d/%02d %02d:%02d:%02d", t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); } else { strcpy(buf, "0000/0000/0000 00:00:00"); } return buf; } template<class interface_type> class iobj_auto_ptr { public: typedef iobj_auto_ptr< interface_type > this_type; typedef interface_type param_type; public: iobj_auto_ptr() : obj_(NULL) {} iobj_auto_ptr(interface_type* p) : obj_(p) {} ~iobj_auto_ptr() { if( this->obj_ ) this->obj_->destroy();} /// operator void**() { return (void**)&this->obj_; } operator interface_type**() { return (interface_type**)&this->obj_; } operator interface_type*() { return this->obj_; } operator const interface_type*() const { return this->obj_; } interface_type* operator->() { return this->obj_; } interface_type* operator*() { return this->obj_; } void reset(interface_type* p) { if( this->obj_ ) this->obj_->destroy(); this->obj_ = p; } interface_type* detach() { interface_type* p = this->obj_; this->obj_ = NULL; return p; } interface_type* get(){ return this->obj_; } private: /// ไธบไฝฟ็”จ็ฎ€ๅ•่ตท่ง๏ผŒ ็ฆๆญขๆ™บ่ƒฝๆŒ‡้’ˆไน‹้—ด่ต‹ๅ€ผไปฅๅŠ่ฐƒ็”จๆ‹ท่ดๆž„้€ ๅ‡ฝๆ•ฐ iobj_auto_ptr(const this_type&); iobj_auto_ptr& operator = (const this_type&); private: interface_type* obj_; }; class interface_base { public: interface_base() { this->ref_cnt_ = 1; } protected: virtual ~interface_base(){;} public: virtual void destroy() { if( 0 == dec_ref() ) delete this; } virtual bool query_interface(void** out, const char* key) = 0; virtual const char* interface_name() = 0; virtual bool query_interface_by_iid(void** out, int key){ return false; } virtual int interface_iid(){ return 0; } virtual long inc_ref(){ return InterlockedIncrement(&this->ref_cnt_); } virtual long dec_ref(){ return InterlockedDecrement(&this->ref_cnt_); } protected: long ref_cnt_; }; template<class iobj_type> class iobj_auto_lock { public: iobj_auto_lock(iobj_type* t) : obj_(t) { obj_->lock(); } ~iobj_auto_lock() { obj_->unlock(); } private: iobj_type* obj_; }; template<class iobj_type> class iobj_null_auto_lock { public: iobj_null_auto_lock(iobj_type* t) { } ~iobj_null_auto_lock() { } }; #pragma warning(default:4996) } /// end namespace sp_ext #endif /// __SP_EXT_DEFINE_H__
[ "monkeycn@01c74763-b75b-5a55-715c-6f18d641bb61", "[email protected]@01c74763-b75b-5a55-715c-6f18d641bb61" ]
[ [ [ 1, 17 ], [ 19, 183 ], [ 273, 278 ] ], [ [ 18, 18 ], [ 184, 272 ] ] ]
cc55682bdf461791ad5dd38232484828bc2d6424
8b68ff41fd39c9cf20d27922bb9f8b9d2a1c68e9
/TWL/include/gdiext.h
4ccf260ab37bfa329d81b0218066605a1e4f9124
[]
no_license
dandycheung/dandy-twl
2ec6d500273b3cb7dd6ab9e5a3412740d73219ae
991220b02f31e4ec82760ece9cd974103c7f9213
refs/heads/master
2020-12-24T15:06:06.260650
2009-05-20T14:46:07
2009-05-20T14:46:07
32,625,192
0
0
null
null
null
null
UTF-8
C++
false
false
58,407
h
////////////////////////////////////////////////////////////////////////// // This is a part of the Tiny Window Library(TWL). // Copyright (C) 2003-2005 Dandy Cheung // [email protected] // All rights reserved. // #ifndef __GDIEXT_H__ #define __GDIEXT_H__ #define GE_INLINE inline #pragma once #ifndef __cplusplus #error TWL requires C++ compilation (use a .cpp suffix) #endif namespace TWL { /// Part 1: Windows GDI API overload extensions typedef struct tagRECT2 { LONG left; LONG top; LONG width; LONG height; } RECT2, *PRECT2, *LPRECT2; // 1. /* BOOL AlphaBlend( HDC hdcDest, // handle to destination DC int nXOriginDest, // x-coord of upper-left corner int nYOriginDest, // y-coord of upper-left corner int nWidthDest, // destination width int nHeightDest, // destination height HDC hdcSrc, // handle to source DC int nXOriginSrc, // x-coord of upper-left corner int nYOriginSrc, // y-coord of upper-left corner int nWidthSrc, // source width int nHeightSrc, // source height BLENDFUNCTION blendFunction // alpha-blending function ); //*/ GE_INLINE BOOL AlphaBlend( HDC hdcDest, POINT ptOriginDest, SIZE sizOriginDest, HDC hdcSrc, POINT ptOriginSrc, SIZE sizOriginSrc, BLENDFUNCTION blendFunction ) { return ::AlphaBlend(hdcDest, ptOriginDest.x, ptOriginDest.y, sizOriginDest.cx, sizOriginDest.cy, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, sizOriginSrc.cx, sizOriginSrc.cy, blendFunction); } GE_INLINE BOOL AlphaBlend( HDC hdcDest, POINT ptOriginDest, int nWidthDest, int nHeightDest, HDC hdcSrc, POINT ptOriginSrc, int nWidthSrc, int nHeightSrc, BLENDFUNCTION blendFunction ) { return ::AlphaBlend(hdcDest, ptOriginDest.x, ptOriginDest.y, nWidthDest, nHeightDest, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, nWidthSrc, nHeightSrc, blendFunction); } GE_INLINE BOOL AlphaBlend( HDC hdcDest, int nXOriginDest, int nYOriginDest, SIZE sizOriginDest, HDC hdcSrc, int nXOriginSrc, int nYOriginSrc, SIZE sizOriginSrc, BLENDFUNCTION blendFunction ) { return ::AlphaBlend(hdcDest, nXOriginDest, nYOriginDest, sizOriginDest.cx, sizOriginDest.cy, hdcSrc, nXOriginSrc, nYOriginSrc, sizOriginSrc.cx, sizOriginSrc.cy, blendFunction); } GE_INLINE BOOL AlphaBlend( HDC hdcDest, PRECT prcDest, HDC hdcSrc, PRECT prcSrc, BLENDFUNCTION blendFunction ) { return ::AlphaBlend(hdcDest, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, hdcSrc, prcSrc->left, prcSrc->top, prcSrc->right - prcSrc->left, prcSrc->bottom - prcSrc->top, blendFunction); } GE_INLINE BOOL AlphaBlend( HDC hdcDest, PRECT2 prcDest, HDC hdcSrc, PRECT2 prcSrc, BLENDFUNCTION blendFunction ) { return ::AlphaBlend(hdcDest, prcDest->left, prcDest->top, prcDest->width, prcDest->height, hdcSrc, prcSrc->left, prcSrc->top, prcSrc->width, prcSrc->height, blendFunction); } // 2. /* BOOL BitBlt( HDC hdcDest, // handle to destination DC int nXDest, // x-coord of destination upper-left corner int nYDest, // y-coord of destination upper-left corner int nWidth, // width of destination rectangle int nHeight, // height of destination rectangle HDC hdcSrc, // handle to source DC int nXSrc, // x-coordinate of source upper-left corner int nYSrc, // y-coordinate of source upper-left corner DWORD dwRop // raster operation code ); // */ GE_INLINE BOOL BitBlt( HDC hdcDest, POINT ptDest, int nWidth, int nHeight, HDC hdcSrc, POINT ptSrc, DWORD dwRop ) { return ::BitBlt(hdcDest, ptDest.x, ptDest.y, nWidth, nHeight, hdcSrc, ptSrc.x, ptSrc.y, dwRop); } GE_INLINE BOOL BitBlt( HDC hdcDest, int nXDest, int nYDest, SIZE size, HDC hdcSrc, int nXSrc, int nYSrc, DWORD dwRop ) { return ::BitBlt(hdcDest, nXDest, nYDest, size.cx, size.cy, hdcSrc, nXSrc, nYSrc, dwRop); } GE_INLINE BOOL BitBlt( HDC hdcDest, POINT ptDest, SIZE size, HDC hdcSrc, POINT ptSrc, DWORD dwRop ) { return ::BitBlt(hdcDest, ptDest.x, ptDest.y, size.cx, size.cy, hdcSrc, ptSrc.x, ptSrc.y, dwRop); } GE_INLINE BOOL BitBlt( HDC hdcDest, PRECT prcDest, HDC hdcSrc, POINT ptSrc, DWORD dwRop ) { return ::BitBlt(hdcDest, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, hdcSrc, ptSrc.x, ptSrc.y, dwRop); } // 3. /* HBITMAP CreateBitmap( int nWidth, // bitmap width, in pixels int nHeight, // bitmap height, in pixels UINT cPlanes, // number of color planes UINT cBitsPerPel, // number of bits to identify color CONST VOID *lpvBits // color data array ); // */ GE_INLINE HBITMAP CreateBitmap( SIZE size, UINT cPlanes, UINT cBitsPerPel, CONST VOID *lpvBits ) { return ::CreateBitmap(size.cx, size.cy, cPlanes, cBitsPerPel, lpvBits); } // 4. /* HBITMAP CreateCompatibleBitmap( HDC hdc, // handle to DC int nWidth, // width of bitmap, in pixels int nHeight // height of bitmap, in pixels ); // */ GE_INLINE HBITMAP CreateCompatibleBitmap( HDC hdc, SIZE size ) { return ::CreateCompatibleBitmap(hdc, size.cx, size.cy); } // 5. /* HBITMAP CreateDiscardableBitmap( HDC hdc, // handle to DC int nWidth, // bitmap width int nHeight // bitmap height ); // */ GE_INLINE HBITMAP CreateDiscardableBitmap( HDC hdc, SIZE size ) { return ::CreateDiscardableBitmap(hdc, size.cx, size.cy); } // 6. /* BOOL ExtFloodFill( HDC hdc, // handle to DC int nXStart, // starting x-coordinate int nYStart, // starting y-coordinate COLORREF crColor, // fill color UINT fuFillType // fill type ); // */ GE_INLINE BOOL ExtFloodFill( HDC hdc, POINT pt, COLORREF crColor, UINT fuFillType ) { return ::ExtFloodFill(hdc, pt.x, pt.y, crColor, fuFillType); } // 7. /* BOOL FloodFill( HDC hdc, // handle to DC int nXStart, // starting x-coordinate int nYStart, // starting y-coordinate COLORREF crFill // fill color ); // */ GE_INLINE BOOL FloodFill( HDC hdc, POINT pt, COLORREF crFill ) { return ::FloodFill(hdc, pt.x, pt.y, crFill); } // 9. /* COLORREF GetPixel( HDC hdc, // handle to DC int nXPos, // x-coordinate of pixel int nYPos // y-coordinate of pixel ); // */ GE_INLINE COLORREF GetPixel( HDC hdc, POINT pt ) { return ::GetPixel(hdc, pt.x, pt.y); } // 10. /* BOOL MaskBlt( HDC hdcDest, // handle to destination DC int nXDest, // x-coord of destination upper-left corner int nYDest, // y-coord of destination upper-left corner int nWidth, // width of source and destination int nHeight, // height of source and destination HDC hdcSrc, // handle to source DC int nXSrc, // x-coord of upper-left corner of source int nYSrc, // y-coord of upper-left corner of source HBITMAP hbmMask, // handle to monochrome bit mask int xMask, // horizontal offset into mask bitmap int yMask, // vertical offset into mask bitmap DWORD dwRop // raster operation code ); // */ GE_INLINE BOOL MaskBlt( HDC hdcDest, POINT ptDest, int nWidth, int nHeight, HDC hdcSrc, POINT ptSrc, HBITMAP hbmMask, POINT ptMask, DWORD dwRop ) { return ::MaskBlt(hdcDest, ptDest.x, ptDest.y, nWidth, nHeight, hdcSrc, ptSrc.x, ptSrc.y, hbmMask, ptMask.x, ptMask.y, dwRop); } GE_INLINE BOOL MaskBlt( HDC hdcDest, int nXDest, int nYDest, SIZE size, HDC hdcSrc, int nXSrc, int nYSrc, HBITMAP hbmMask, int xMask, int yMask, DWORD dwRop ) { return ::MaskBlt(hdcDest, nXDest, nYDest, size.cx, size.cy, hdcSrc, nXSrc, nYSrc, hbmMask, xMask, yMask, dwRop); } GE_INLINE BOOL MaskBlt( HDC hdcDest, POINT ptDest, SIZE size, HDC hdcSrc, POINT ptSrc, HBITMAP hbmMask, POINT ptMask, DWORD dwRop ) { return ::MaskBlt(hdcDest, ptDest.x, ptDest.y, size.cx, size.cy, hdcSrc, ptSrc.x, ptSrc.y, hbmMask, ptMask.x, ptMask.y, dwRop); } GE_INLINE BOOL MaskBlt( HDC hdcDest, PRECT prcDest, HDC hdcSrc, POINT ptSrc, HBITMAP hbmMask, POINT ptMask, DWORD dwRop ) { return ::MaskBlt(hdcDest, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, hdcSrc, ptSrc.x, ptSrc.y, hbmMask, ptMask.x, ptMask.y, dwRop); } // 11. /* BOOL PlgBlt( HDC hdcDest, // handle to destination DC CONST POINT *lpPoint, // destination vertices HDC hdcSrc, // handle to source DC int nXSrc, // x-coord of source upper-left corner int nYSrc, // y-coord of source upper-left corner int nWidth, // width of source rectangle int nHeight, // height of source rectangle HBITMAP hbmMask, // handle to bitmask int xMask, // x-coord of bitmask upper-left corner int yMask // y-coord of bitmask upper-left corner ); // */ GE_INLINE BOOL PlgBlt( HDC hdcDest, CONST POINT *lpPoint, HDC hdcSrc, POINT ptSrc, int nWidth, int nHeight, HBITMAP hbmMask, POINT ptMask ) { return ::PlgBlt(hdcDest, lpPoint, hdcSrc, ptSrc.x, ptSrc.y, nWidth, nHeight, hbmMask, ptMask.x, ptMask.y); } GE_INLINE BOOL PlgBlt( HDC hdcDest, CONST POINT *lpPoint, HDC hdcSrc, int nXSrc, int nYSrc, SIZE size, HBITMAP hbmMask, int xMask, int yMask ) { return ::PlgBlt(hdcDest, lpPoint, hdcSrc, nXSrc, nYSrc, size.cx, size.cy, hbmMask, xMask, yMask); } GE_INLINE BOOL PlgBlt( HDC hdcDest, CONST POINT *lpPoint, HDC hdcSrc, POINT ptSrc, SIZE size, HBITMAP hbmMask, POINT ptMask ) { return ::PlgBlt(hdcDest, lpPoint, hdcSrc, ptSrc.x, ptSrc.y, size.cx, size.cy, hbmMask, ptMask.x, ptMask.y); } GE_INLINE BOOL PlgBlt( HDC hdcDest, CONST POINT *lpPoint, HDC hdcSrc, PRECT prcSrc, HBITMAP hbmMask, POINT ptMask ) { return ::PlgBlt(hdcDest, lpPoint, hdcSrc, prcSrc->left, prcSrc->top, prcSrc->right - prcSrc->left, prcSrc->bottom - prcSrc->top, hbmMask, ptMask.x, ptMask.y); } // 12. (return?) /* BOOL SetBitmapDimensionEx( HBITMAP hBitmap, // handle to bitmap int nWidth, // bitmap width in .01-mm units int nHeight, // bitmap height in .01-mm units LPSIZE lpSize // original dimensions ); // */ GE_INLINE BOOL SetBitmapDimensionEx( HBITMAP hBitmap, SIZE size, LPSIZE lpSize = NULL ) { return ::SetBitmapDimensionEx(hBitmap, size.cx, size.cy, lpSize); } GE_INLINE BOOL SetBitmapDimension( HBITMAP hBitmap, int nWidth, int nHeight, LPSIZE lpSize = NULL ) { return ::SetBitmapDimensionEx(hBitmap, nWidth, nHeight, lpSize); } GE_INLINE BOOL SetBitmapDimension( HBITMAP hBitmap, SIZE size, LPSIZE lpSize = NULL ) { return ::SetBitmapDimensionEx(hBitmap, size.cx, size.cy, lpSize); } #define SetBitmapSize SetBitmapDimension // 13. /* int SetDIBitsToDevice( HDC hdc, // handle to DC int XDest, // x-coord of destination upper-left corner int YDest, // y-coord of destination upper-left corner DWORD dwWidth, // source rectangle width DWORD dwHeight, // source rectangle height int XSrc, // x-coord of source lower-left corner int YSrc, // y-coord of source lower-left corner UINT uStartScan, // first scan line in array UINT cScanLines, // number of scan lines CONST VOID *lpvBits, // array of DIB bits CONST BITMAPINFO *lpbmi, // bitmap information UINT fuColorUse // RGB or palette indexes ); // */ GE_INLINE int SetDIBitsToDevice( HDC hdc, POINT ptDest, DWORD dwWidth, DWORD dwHeight, POINT ptSrc, UINT uStartScan, UINT cScanLines, CONST VOID *lpvBits, CONST BITMAPINFO *lpbmi, UINT fuColorUse ) { return ::SetDIBitsToDevice(hdc, ptDest.x, ptDest.y, dwWidth, dwHeight, ptSrc.x, ptSrc.y, uStartScan, cScanLines, lpvBits, lpbmi, fuColorUse); } GE_INLINE int SetDIBitsToDevice( HDC hdc, int XDest, int YDest, SIZE size, int XSrc, int YSrc, UINT uStartScan, UINT cScanLines, CONST VOID *lpvBits, CONST BITMAPINFO *lpbmi, UINT fuColorUse ) { return ::SetDIBitsToDevice(hdc, XDest, YDest, size.cx, size.cy, XSrc, YSrc, uStartScan, cScanLines, lpvBits, lpbmi, fuColorUse); } GE_INLINE int SetDIBitsToDevice( HDC hdc, POINT ptDest, SIZE size, POINT ptSrc, UINT uStartScan, UINT cScanLines, CONST VOID *lpvBits, CONST BITMAPINFO *lpbmi, UINT fuColorUse ) { return ::SetDIBitsToDevice(hdc, ptDest.x, ptDest.y, size.cx, size.cy, ptSrc.x, ptSrc.y, uStartScan, cScanLines, lpvBits, lpbmi, fuColorUse); } GE_INLINE int SetDIBitsToDevice( HDC hdc, PRECT prcDest, POINT ptSrc, UINT uStartScan, UINT cScanLines, CONST VOID *lpvBits, CONST BITMAPINFO *lpbmi, UINT fuColorUse ) { return ::SetDIBitsToDevice(hdc, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, ptSrc.x, ptSrc.y, uStartScan, cScanLines, lpvBits, lpbmi, fuColorUse); } // 14. /* COLORREF SetPixel( HDC hdc, // handle to DC int X, // x-coordinate of pixel int Y, // y-coordinate of pixel COLORREF crColor // pixel color ); // */ GE_INLINE COLORREF SetPixel( HDC hdc, POINT pt, COLORREF crColor ) { return ::SetPixel(hdc, pt.x, pt.y, crColor); } // 15. /* BOOL SetPixelV( HDC hdc, // handle to device context int X, // x-coordinate of pixel int Y, // y-coordinate of pixel COLORREF crColor // new pixel color ); // */ GE_INLINE BOOL SetPixelV( HDC hdc, POINT pt, COLORREF crColor ) { return ::SetPixelV(hdc, pt.x, pt.y, crColor); } // 16. /* BOOL StretchBlt( HDC hdcDest, // handle to destination DC int nXOriginDest, // x-coord of destination upper-left corner int nYOriginDest, // y-coord of destination upper-left corner int nWidthDest, // width of destination rectangle int nHeightDest, // height of destination rectangle HDC hdcSrc, // handle to source DC int nXOriginSrc, // x-coord of source upper-left corner int nYOriginSrc, // y-coord of source upper-left corner int nWidthSrc, // width of source rectangle int nHeightSrc, // height of source rectangle DWORD dwRop // raster operation code ); // */ GE_INLINE BOOL StretchBlt( HDC hdcDest, POINT ptOriginDest, int nWidthDest, int nHeightDest, HDC hdcSrc, POINT ptOriginSrc, int nWidthSrc, int nHeightSrc, DWORD dwRop ) { return ::StretchBlt(hdcDest, ptOriginDest.x, ptOriginDest.y, nWidthDest, nHeightDest, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, nWidthSrc, nHeightSrc, dwRop); } GE_INLINE BOOL StretchBlt( HDC hdcDest, int nXOriginDest, int nYOriginDest, SIZE sizDest, HDC hdcSrc, int nXOriginSrc, int nYOriginSrc, SIZE sizSrc, DWORD dwRop ) { return ::StretchBlt(hdcDest, nXOriginDest, nYOriginDest, sizDest.cx, sizDest.cy, hdcSrc, nXOriginSrc, nYOriginSrc, sizSrc.cx, sizSrc.cy, dwRop); } GE_INLINE BOOL StretchBlt( HDC hdcDest, POINT ptOriginDest, SIZE sizDest, HDC hdcSrc, POINT ptOriginSrc, SIZE sizSrc, DWORD dwRop ) { return ::StretchBlt(hdcDest, ptOriginDest.x, ptOriginDest.y, sizDest.cx, sizDest.cy, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, sizSrc.cx, sizSrc.cy, dwRop); } GE_INLINE BOOL StretchBlt( HDC hdcDest, PRECT prcDest, HDC hdcSrc, PRECT prcSrc, DWORD dwRop ) { return ::StretchBlt(hdcDest, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, hdcSrc, prcSrc->left, prcSrc->top, prcSrc->right - prcSrc->left, prcSrc->bottom - prcSrc->top, dwRop); } // 17. /* int StretchDIBits( HDC hdc, // handle to DC int XDest, // x-coord of destination upper-left corner int YDest, // y-coord of destination upper-left corner int nDestWidth, // width of destination rectangle int nDestHeight, // height of destination rectangle int XSrc, // x-coord of source upper-left corner int YSrc, // y-coord of source upper-left corner int nSrcWidth, // width of source rectangle int nSrcHeight, // height of source rectangle CONST VOID *lpBits, // bitmap bits CONST BITMAPINFO *lpBitsInfo, // bitmap data UINT iUsage, // usage options DWORD dwRop // raster operation code ); // */ GE_INLINE int StretchDIBits( HDC hdc, POINT ptDest, int nDestWidth, int nDestHeight, POINT ptSrc, int nSrcWidth, int nSrcHeight, CONST VOID *lpBits, CONST BITMAPINFO *lpBitsInfo, UINT iUsage, DWORD dwRop ) { return ::StretchDIBits(hdc, ptDest.x, ptDest.y, nDestWidth, nDestHeight, ptSrc.x, ptSrc.y, nSrcWidth, nSrcHeight, lpBits, lpBitsInfo, iUsage, dwRop); } GE_INLINE int StretchDIBits( HDC hdc, int XDest, int YDest, SIZE sizDest, int XSrc, int YSrc, SIZE sizSrc, CONST VOID *lpBits, CONST BITMAPINFO *lpBitsInfo, UINT iUsage, DWORD dwRop ) { return ::StretchDIBits(hdc, XDest, YDest, sizDest.cx, sizDest.cy, XSrc, YSrc, sizSrc.cx, sizSrc.cy, lpBits, lpBitsInfo, iUsage, dwRop); } GE_INLINE int StretchDIBits( HDC hdc, POINT ptDest, SIZE sizDest, POINT ptSrc, SIZE sizSrc, CONST VOID *lpBits, CONST BITMAPINFO *lpBitsInfo, UINT iUsage, DWORD dwRop ) { return ::StretchDIBits(hdc, ptDest.x, ptDest.y, sizDest.cx, sizDest.cy, ptSrc.x, ptSrc.y, sizSrc.cx, sizSrc.cy, lpBits, lpBitsInfo, iUsage, dwRop); } GE_INLINE int StretchDIBits( HDC hdc, PRECT prcDest, PRECT prcSrc, CONST VOID *lpBits, CONST BITMAPINFO *lpBitsInfo, UINT iUsage, DWORD dwRop ) { return ::StretchDIBits(hdc, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, prcSrc->left, prcSrc->top, prcSrc->right - prcSrc->left, prcSrc->bottom - prcSrc->top, lpBits, lpBitsInfo, iUsage, dwRop); } // 18. /* BOOL TransparentBlt( HDC hdcDest, // handle to destination DC int nXOriginDest, // x-coord of destination upper-left corner int nYOriginDest, // y-coord of destination upper-left corner int nWidthDest, // width of destination rectangle int hHeightDest, // height of destination rectangle HDC hdcSrc, // handle to source DC int nXOriginSrc, // x-coord of source upper-left corner int nYOriginSrc, // y-coord of source upper-left corner int nWidthSrc, // width of source rectangle int nHeightSrc, // height of source rectangle UINT crTransparent // color to make transparent ); // */ GE_INLINE BOOL TransparentBlt( HDC hdcDest, POINT ptOriginDest, int nWidthDest, int hHeightDest, HDC hdcSrc, POINT ptOriginSrc, int nWidthSrc, int nHeightSrc, UINT crTransparent ) { return ::TransparentBlt(hdcDest, ptOriginDest.x, ptOriginDest.y, nWidthDest, hHeightDest, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, nWidthSrc, nHeightSrc, crTransparent); } GE_INLINE BOOL TransparentBlt( HDC hdcDest, int nXOriginDest, int nYOriginDest, SIZE sizDest, HDC hdcSrc, int nXOriginSrc, int nYOriginSrc, SIZE sizSrc, UINT crTransparent ) { return ::TransparentBlt(hdcDest, nXOriginDest, nYOriginDest, sizDest.cx, sizDest.cy, hdcSrc, nXOriginSrc, nYOriginSrc, sizSrc.cx, sizSrc.cy, crTransparent); } GE_INLINE BOOL TransparentBlt( HDC hdcDest, POINT ptOriginDest, SIZE sizDest, HDC hdcSrc, POINT ptOriginSrc, SIZE sizSrc, UINT crTransparent ) { return ::TransparentBlt(hdcDest, ptOriginDest.x, ptOriginDest.y, sizDest.cx, sizDest.cy, hdcSrc, ptOriginSrc.x, ptOriginSrc.y, sizSrc.cx, sizSrc.cy, crTransparent); } GE_INLINE BOOL TransparentBlt( HDC hdcDest, PRECT prcDest, HDC hdcSrc, PRECT prcSrc, UINT crTransparent ) { return ::TransparentBlt(hdcDest, prcDest->left, prcDest->top, prcDest->right - prcDest->left, prcDest->bottom - prcDest->top, hdcSrc, prcSrc->left, prcSrc->top, prcSrc->right - prcSrc->left, prcSrc->bottom - prcSrc->top, crTransparent); } // 20. /* BOOL PatBlt( HDC hdc, // handle to DC int nXLeft, // x-coord of upper-left rectangle corner int nYLeft, // y-coord of upper-left rectangle corner int nWidth, // width of rectangle int nHeight, // height of rectangle DWORD dwRop // raster operation code ); // */ GE_INLINE BOOL PatBlt( HDC hdc, POINT pt, SIZE size, DWORD dwRop ) { return ::PatBlt(hdc, pt.x, pt.y, size.cx, size.cy, dwRop); } GE_INLINE BOOL PatBlt( HDC hdc, PRECT prc, DWORD dwRop ) { return ::PatBlt(hdc, prc->left, prc->top, prc->right - prc->left, prc->bottom - prc->top, dwRop); } // 21. (return?) /* BOOL SetBrushOrgEx( HDC hdc, // handle to device context int nXOrg, // x-coord of new origin int nYOrg, // y-coord of new origin LPPOINT lppt // points to previous brush origin ); // */ GE_INLINE BOOL SetBrushOrgEx( HDC hdc, POINT ptOrg, LPPOINT lppt = NULL ) { return ::SetBrushOrgEx(hdc, ptOrg.x, ptOrg.y, lppt); } GE_INLINE BOOL SetBrushOrg( HDC hdc, int nXOrg, int nYOrg, LPPOINT lppt = NULL ) { return ::SetBrushOrgEx(hdc, nXOrg, nYOrg, lppt); } GE_INLINE BOOL SetBrushOrg( HDC hdc, POINT ptOrg, LPPOINT lppt = NULL ) { return ::SetBrushOrgEx(hdc, ptOrg.x, ptOrg.y, lppt); } // 22. /* int ExcludeClipRect( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner int nTopRect, // y-coord of upper-left corner int nRightRect, // x-coord of lower-right corner int nBottomRect // y-coord of lower-right corner ); // */ GE_INLINE int ExcludeClipRect( HDC hdc, PRECT prc ) { return ::ExcludeClipRect(hdc, prc->left, prc->top, prc->right, prc->bottom); } // 24. /* int IntersectClipRect( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner int nTopRect, // y-coord of upper-left corner int nRightRect, // x-coord of lower-right corner int nBottomRect // y-coord of lower-right corner ); // */ GE_INLINE int IntersectClipRect( HDC hdc, PRECT prc ) { return ::IntersectClipRect(hdc, prc->left, prc->top, prc->right, prc->bottom); } // 25. /* int OffsetClipRgn( HDC hdc, // handle to DC int nXOffset, // offset along x-axis int nYOffset // offset along y-axis ); // */ GE_INLINE int OffsetClipRgn( HDC hdc, POINT pt ) { return ::OffsetClipRgn(hdc, pt.x, pt.y); } GE_INLINE int OffsetClipRgn( HDC hdc, SIZE size ) { return ::OffsetClipRgn(hdc, size.cx, size.cy); } // 26. /* BOOL PtVisible( HDC hdc, // handle to DC int X, // x-coordinate of point int Y // y-coordinate of point ); // */ GE_INLINE BOOL PtVisible( HDC hdc, POINT pt ) { return ::PtVisible(hdc, pt.x, pt.y); } // 28. /* BOOL ClientToScreen( HWND hWnd, // handle to window LPPOINT lpPoint // screen coordinates ); // */ GE_INLINE BOOL ClientToScreen( HWND hWnd, LPRECT lpRect ) { return ::ClientToScreen(hWnd, (LPPOINT)lpRect) && ::ClientToScreen(hWnd, ((LPPOINT)lpRect) + 1); } // 29. /* BOOL DPtoLP( HDC hdc, // handle to device context LPPOINT lpPoints, // array of points int nCount // count of points in array ); // */ GE_INLINE BOOL DPtoLP( HDC hdc, LPRECT lpRect ) { return ::DPtoLP(hdc, (LPPOINT)lpRect, 2); } // 35. /* BOOL LPtoDP( HDC hdc, // handle to device context LPPOINT lpPoints, // array of points int nCount // count of points in array ); // */ GE_INLINE BOOL LPtoDP( HDC hdc, LPRECT lpRect ) { return ::DPtoLP(hdc, (LPPOINT)lpRect, 2); } // 36. (return?) /* BOOL OffsetViewportOrgEx( HDC hdc, // handle to device context int nXOffset, // horizontal offset int nYOffset, // vertical offset LPPOINT lpPoint // original origin ); // */ GE_INLINE BOOL OffsetViewportOrgEx( HDC hdc, POINT ptOffset, LPPOINT lpPoint = NULL ) { return ::OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, lpPoint); } GE_INLINE BOOL OffsetViewportOrgEx( HDC hdc, SIZE sizOffset, LPPOINT lpPoint = NULL ) { return ::OffsetViewportOrgEx(hdc, sizOffset.cx, sizOffset.cy, lpPoint); } GE_INLINE BOOL OffsetViewportOrg( HDC hdc, int nXOffset, int nYOffset, LPPOINT lpPoint = NULL ) { return ::OffsetViewportOrgEx(hdc, nXOffset, nYOffset, lpPoint); } GE_INLINE BOOL OffsetViewportOrg( HDC hdc, POINT ptOffset, LPPOINT lpPoint = NULL ) { return ::OffsetViewportOrgEx(hdc, ptOffset.x, ptOffset.y, lpPoint); } GE_INLINE BOOL OffsetViewportOrg( HDC hdc, SIZE sizOffset, LPPOINT lpPoint = NULL ) { return ::OffsetViewportOrgEx(hdc, sizOffset.cx, sizOffset.cy, lpPoint); } // 37. (return?) /* BOOL OffsetWindowOrgEx( HDC hdc, // handle to device context int nXOffset, // horizontal offset int nYOffset, // vertical offset LPPOINT lpPoint // original origin ); // */ GE_INLINE BOOL OffsetWindowOrgEx( HDC hdc, POINT ptOffset, LPPOINT lpPoint = NULL ) { return ::OffsetWindowOrgEx(hdc, ptOffset.x, ptOffset.y, lpPoint); } GE_INLINE BOOL OffsetWindowOrgEx( HDC hdc, SIZE sizOffset, LPPOINT lpPoint = NULL ) { return ::OffsetWindowOrgEx(hdc, sizOffset.cx, sizOffset.cy, lpPoint); } GE_INLINE BOOL OffsetWindowOrg( HDC hdc, int nXOffset, int nYOffset, LPPOINT lpPoint = NULL ) { return ::OffsetWindowOrgEx(hdc, nXOffset, nYOffset, lpPoint); } GE_INLINE BOOL OffsetWindowOrg( HDC hdc, POINT ptOffset, LPPOINT lpPoint = NULL ) { return ::OffsetWindowOrgEx(hdc, ptOffset.x, ptOffset.y, lpPoint); } GE_INLINE BOOL OffsetWindowOrg( HDC hdc, SIZE sizOffset, LPPOINT lpPoint = NULL ) { return ::OffsetWindowOrgEx(hdc, sizOffset.cx, sizOffset.cy, lpPoint); } // 40. /* BOOL ScreenToClient( HWND hWnd, // handle to window LPPOINT lpPoint // screen coordinates ); // */ GE_INLINE BOOL ScreenToClient( HWND hWnd, LPRECT lpRect ) { return ::ScreenToClient(hWnd, (LPPOINT)lpRect) && ::ScreenToClient(hWnd, ((LPPOINT)lpRect) + 1); } // 41. (return?) /* BOOL SetViewportExtEx( HDC hdc, // handle to device context int nXExtent, // new horizontal viewport extent int nYExtent, // new vertical viewport extent LPSIZE lpSize // original viewport extent ); // */ GE_INLINE BOOL SetViewportExtEx( HDC hdc, SIZE sizExtent, LPSIZE lpSize = NULL ) { return ::SetViewportExtEx(hdc, sizExtent.cx, sizExtent.cy, lpSize); } GE_INLINE BOOL SetViewportExt( HDC hdc, int nXExtent, int nYExtent, LPSIZE lpSize = NULL ) { return ::SetViewportExtEx(hdc, nXExtent, nYExtent, lpSize); } GE_INLINE BOOL SetViewportExt( HDC hdc, SIZE sizExtent, LPSIZE lpSize = NULL ) { return ::SetViewportExtEx(hdc, sizExtent.cx, sizExtent.cy, lpSize); } // 42. (return?) /* BOOL SetViewportOrgEx( HDC hdc, // handle to device context int X, // new x-coordinate of viewport origin int Y, // new y-coordinate of viewport origin LPPOINT lpPoint // original viewport origin ); // */ GE_INLINE BOOL SetViewportOrgEx( HDC hdc, POINT ptOrg, LPPOINT lpPoint = NULL ) { return ::SetViewportOrgEx(hdc, ptOrg.x, ptOrg.y, lpPoint); } GE_INLINE BOOL SetViewportOrg( HDC hdc, int X, int Y, LPPOINT lpPoint = NULL ) { return ::SetViewportOrgEx(hdc, X, Y, lpPoint); } GE_INLINE BOOL SetViewportOrg( HDC hdc, POINT ptOrg, LPPOINT lpPoint = NULL ) { return ::SetViewportOrgEx(hdc, ptOrg.x, ptOrg.y, lpPoint); } // 43. (return?) /* BOOL SetWindowExtEx( HDC hdc, // handle to device context int nXExtent, // new horizontal window extent int nYExtent, // new vertical window extent LPSIZE lpSize // original window extent ); // */ GE_INLINE BOOL SetWindowExtEx( HDC hdc, SIZE sizExtent, LPSIZE lpSize = NULL ) { return ::SetWindowExtEx(hdc, sizExtent.cx, sizExtent.cy, lpSize); } GE_INLINE BOOL SetWindowExt( HDC hdc, int nXExtent, int nYExtent, LPSIZE lpSize = NULL ) { return ::SetWindowExtEx(hdc, nXExtent, nYExtent, lpSize); } GE_INLINE BOOL SetWindowExt( HDC hdc, SIZE sizExtent, LPSIZE lpSize = NULL ) { return ::SetWindowExtEx(hdc, sizExtent.cx, sizExtent.cy, lpSize); } // 44. (return?) /* BOOL SetWindowOrgEx( HDC hdc, // handle to device context int X, // new x-coordinate of window origin int Y, // new y-coordinate of window origin LPPOINT lpPoint // original window origin ); // */ GE_INLINE BOOL SetWindowOrgEx( HDC hdc, POINT pt, LPPOINT lpPoint = NULL ) { return ::SetWindowOrgEx(hdc, pt.x, pt.y, lpPoint); } GE_INLINE BOOL SetWindowOrg( HDC hdc, int X, int Y, LPPOINT lpPoint = NULL ) { return ::SetWindowOrgEx(hdc, X, Y, lpPoint); } GE_INLINE BOOL SetWindowOrg( HDC hdc, POINT pt, LPPOINT lpPoint = NULL ) { return ::SetWindowOrgEx(hdc, pt.x, pt.y, lpPoint); } // 46. /* BOOL Chord( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect, // y-coord of lower-right corner of rectangle int nXRadial1, // x-coord of first radial's endpoint int nYRadial1, // y-coord of first radial's endpoint int nXRadial2, // x-coord of second radial's endpoint int nYRadial2 // y-coord of second radial's endpoint ); // */ GE_INLINE BOOL Chord( HDC hdc, PRECT prc, int nXRadial1, int nYRadial1, int nXRadial2, int nYRadial2 ) { return ::Chord(hdc, prc->left, prc->top, prc->right, prc->bottom, nXRadial1, nYRadial1, nXRadial2, nYRadial2); } GE_INLINE BOOL Chord( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, POINT ptRadial1, POINT ptRadial2 ) { return ::Chord(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } GE_INLINE BOOL Chord( HDC hdc, PRECT prc, POINT ptRadial1, POINT ptRadial2 ) { return ::Chord(hdc, prc->left, prc->top, prc->right, prc->bottom, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } // 47. /* BOOL Ellipse( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect // y-coord of lower-right corner of rectangle ); // */ GE_INLINE BOOL Ellipse( HDC hdc, PRECT prc ) { return ::Ellipse(hdc, prc->left, prc->top, prc->right, prc->bottom); } // 51. /* BOOL Pie( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect, // y-coord of lower-right corner of rectangle int nXRadial1, // x-coord of first radial's endpoint int nYRadial1, // y-coord of first radial's endpoint int nXRadial2, // x-coord of second radial's endpoint int nYRadial2 // y-coord of second radial's endpoint ); // */ GE_INLINE BOOL Pie( HDC hdc, PRECT prc, int nXRadial1, int nYRadial1, int nXRadial2, int nYRadial2 ) { return ::Pie(hdc, prc->left, prc->top, prc->right, prc->bottom, nXRadial1, nYRadial1, nXRadial2, nYRadial2); } GE_INLINE BOOL Pie( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, POINT ptRadial1, POINT ptRadial2 ) { return ::Pie(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } GE_INLINE BOOL Pie( HDC hdc, PRECT prc, POINT ptRadial1, POINT ptRadial2 ) { return ::Pie(hdc, prc->left, prc->top, prc->right, prc->bottom, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } // 52. /* BOOL Rectangle( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect // y-coord of lower-right corner of rectangle ); // */ GE_INLINE BOOL Rectangle( HDC hdc, PRECT prc ) { return ::Rectangle(hdc, prc->left, prc->top, prc->right, prc->bottom); } // 53. /* BOOL RoundRect( HDC hdc, // handle to DC int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect, // y-coord of lower-right corner of rectangle int nWidth, // width of ellipse int nHeight // height of ellipse ); // */ GE_INLINE BOOL RoundRect( HDC hdc, PRECT prc, int nWidth, int nHeight ) { return ::RoundRect(hdc, prc->left, prc->top, prc->right, prc->bottom, nWidth, nHeight); } GE_INLINE BOOL RoundRect( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, SIZE size ) { return ::RoundRect(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect, size.cx, size.cy); } GE_INLINE BOOL RoundRect( HDC hdc, PRECT prc, SIZE size ) { return ::RoundRect(hdc, prc->left, prc->top, prc->right, prc->bottom, size.cx, size.cy); } // 59. /* LONG TabbedTextOut( HDC hDC, // handle to DC int X, // x-coord of start int Y, // y-coord of start LPCTSTR lpString, // character string int nCount, // number of characters int nTabPositions, // number of tabs in array CONST LPINT lpnTabStopPositions, // array of tab positions int nTabOrigin // start of tab expansion ); // */ GE_INLINE LONG TabbedTextOut( HDC hDC, POINT pt, LPCTSTR lpString, int nCount, int nTabPositions, CONST LPINT lpnTabStopPositions, int nTabOrigin ) { return ::TabbedTextOut(hDC, pt.x, pt.y, lpString, nCount, nTabPositions, lpnTabStopPositions, nTabOrigin); } // 60. /* BOOL TextOut( HDC hdc, // handle to DC int nXStart, // x-coordinate of starting position int nYStart, // y-coordinate of starting position LPCTSTR lpString, // character string int cbString // number of characters ); // */ GE_INLINE BOOL TextOut( HDC hdc, POINT pt, LPCTSTR lpString, int cbString ) { return ::TextOut(hdc, pt.x, pt.y, lpString, cbString); } // 61. /* BOOL AngleArc( HDC hdc, // handle to device context int X, // x-coordinate of circle's center int Y, // y-coordinate of circle's center DWORD dwRadius, // circle's radius FLOAT eStartAngle, // arc's start angle FLOAT eSweepAngle // arc's sweep angle ); // */ GE_INLINE BOOL AngleArc( HDC hdc, POINT pt, DWORD dwRadius, FLOAT eStartAngle, FLOAT eSweepAngle ) { return ::AngleArc(hdc, pt.x, pt.y, dwRadius, eStartAngle, eSweepAngle); } // 62. /* BOOL Arc( HDC hdc, // handle to device context int nLeftRect, // x-coord of rectangle's upper-left corner int nTopRect, // y-coord of rectangle's upper-left corner int nRightRect, // x-coord of rectangle's lower-right corner int nBottomRect, // y-coord of rectangle's lower-right corner int nXStartArc, // x-coord of first radial ending point int nYStartArc, // y-coord of first radial ending point int nXEndArc, // x-coord of second radial ending point int nYEndArc // y-coord of second radial ending point ); // */ GE_INLINE BOOL Arc( HDC hdc, PRECT prc, int nXStartArc, int nYStartArc, int nXEndArc, int nYEndArc ) { return ::Arc(hdc, prc->left, prc->top, prc->right, prc->bottom, nXStartArc, nYStartArc, nXEndArc, nYEndArc); } GE_INLINE BOOL Arc( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, POINT ptStartArc, POINT ptEndArc ) { return ::Arc(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect, ptStartArc.x, ptStartArc.y, ptEndArc.x, ptEndArc.y); } GE_INLINE BOOL Arc( HDC hdc, PRECT prc, POINT ptStartArc, POINT ptEndArc ) { return ::Arc(hdc, prc->left, prc->top, prc->right, prc->bottom, ptStartArc.x, ptStartArc.y, ptEndArc.x, ptEndArc.y); } // 63. /* BOOL ArcTo( HDC hdc, // handle to device context int nLeftRect, // x-coord of rectangle's upper-left corner int nTopRect, // y-coord of rectangle's upper-left corner int nRightRect, // x-coord of rectangle's lower-right corner int nBottomRect, // y-coord of rectangle's lower-right corner int nXRadial1, // x-coord of first radial ending point int nYRadial1, // y-coord of first radial ending point int nXRadial2, // x-coord of second radial ending point int nYRadial2 // y-coord of second radial ending point ); // */ GE_INLINE BOOL ArcTo( HDC hdc, PRECT prc, int nXRadial1, int nYRadial1, int nXRadial2, int nYRadial2 ) { return ::ArcTo(hdc, prc->left, prc->top, prc->right, prc->bottom, nXRadial1, nYRadial1, nXRadial2, nYRadial2); } GE_INLINE BOOL ArcTo( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, POINT ptRadial1, POINT ptRadial2 ) { return ::ArcTo(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } GE_INLINE BOOL ArcTo( HDC hdc, PRECT prc, POINT ptRadial1, POINT ptRadial2 ) { return ::ArcTo(hdc, prc->left, prc->top, prc->right, prc->bottom, ptRadial1.x, ptRadial1.y, ptRadial2.x, ptRadial2.y); } // 64. /* BOOL LineDDA( int nXStart, // x-coordinate of starting point int nYStart, // y-coordinate of starting point int nXEnd, // x-coordinate of ending point int nYEnd, // y-coordinate of ending point LINEDDAPROC lpLineFunc, // callback function LPARAM lpData // application-defined data ); // */ GE_INLINE BOOL LineDDA( POINT ptStart, POINT ptEnd, LINEDDAPROC lpLineFunc, LPARAM lpData ) { return ::LineDDA(ptStart.x, ptStart.y, ptEnd.x, ptEnd.y, lpLineFunc, lpData); } // 65. /* BOOL LineTo( HDC hdc, // device context handle int nXEnd, // x-coordinate of ending point int nYEnd // y-coordinate of ending point ); // */ GE_INLINE BOOL LineTo( HDC hdc, POINT pt ) { return ::LineTo(hdc, pt.x, pt.y); } // 66. /* BOOL MoveToEx( HDC hdc, // handle to device context int X, // x-coordinate of new current position int Y, // y-coordinate of new current position LPPOINT lpPoint // old current position ); // */ GE_INLINE BOOL MoveTo( HDC hdc, int X, int Y, LPPOINT lpPoint = NULL ) { return ::MoveToEx(hdc, X, Y, lpPoint); } GE_INLINE BOOL MoveToEx( HDC hdc, POINT pt, LPPOINT lpPoint = NULL ) { return ::MoveToEx(hdc, pt.x, pt.y, lpPoint); } GE_INLINE BOOL MoveTo( HDC hdc, POINT pt, LPPOINT lpPoint = NULL ) { return MoveToEx(hdc, pt, lpPoint); } // 67. /* HMONITOR MonitorFromPoint( POINT pt, // point DWORD dwFlags // determine return value ); // */ GE_INLINE HMONITOR MonitorFromPoint( int x, int y, DWORD dwFlags ) { POINT pt = { x, y }; return ::MonitorFromPoint(pt, dwFlags); } // 73. /* BOOL DrawState( HDC hdc, // handle to device context HBRUSH hbr, // handle to brush DRAWSTATEPROC lpOutputFunc, // callback function LPARAM lData, // image information WPARAM wData, // more image information int x, // horizontal location int y, // vertical location int cx, // image width int cy, // image height UINT fuFlags // image type and state ); // */ GE_INLINE BOOL DrawState( HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, POINT pt, int cx, int cy, UINT fuFlags ) { return ::DrawState(hdc, hbr, lpOutputFunc, lData, wData, pt.x, pt.y, cx, cy, fuFlags); } GE_INLINE BOOL DrawState( HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, int x, int y, SIZE size, UINT fuFlags ) { return ::DrawState(hdc, hbr, lpOutputFunc, lData, wData, x, y, size.cx, size.cy, fuFlags); } GE_INLINE BOOL DrawState( HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, POINT pt, SIZE size, UINT fuFlags ) { return ::DrawState(hdc, hbr, lpOutputFunc, lData, wData, pt.x, pt.y, size.cx, size.cy, fuFlags); } GE_INLINE BOOL DrawState( HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, PRECT prc, UINT fuFlags ) { return ::DrawState(hdc, hbr, lpOutputFunc, lData, wData, prc->left, prc->top, prc->right - prc->left, prc->bottom - prc->top, fuFlags); } // 77. /* BOOL GrayString( HDC hDC, // handle to DC HBRUSH hBrush, // handle to the brush GRAYSTRINGPROC lpOutputFunc, // callback function LPARAM lpData, // application-defined data int nCount, // number of characters int X, // horizontal position int Y, // vertical position int nWidth, // width int nHeight // height ); // */ GE_INLINE BOOL GrayString( HDC hDC, HBRUSH hBrush, GRAYSTRINGPROC lpOutputFunc, LPARAM lpData, int nCount, POINT pt, int nWidth, int nHeight ) { return ::GrayString(hDC, hBrush, lpOutputFunc, lpData, nCount, pt.x, pt.y, nWidth, nHeight); } GE_INLINE BOOL GrayString( HDC hDC, HBRUSH hBrush, GRAYSTRINGPROC lpOutputFunc, LPARAM lpData, int nCount, int X, int Y, SIZE size ) { return ::GrayString(hDC, hBrush, lpOutputFunc, lpData, nCount, X, Y, size.cx, size.cy); } GE_INLINE BOOL GrayString( HDC hDC, HBRUSH hBrush, GRAYSTRINGPROC lpOutputFunc, LPARAM lpData, int nCount, POINT pt, SIZE size ) { return ::GrayString(hDC, hBrush, lpOutputFunc, lpData, nCount, pt.x, pt.y, size.cx, size.cy); } GE_INLINE BOOL GrayString( HDC hDC, HBRUSH hBrush, GRAYSTRINGPROC lpOutputFunc, LPARAM lpData, int nCount, PRECT prc ) { return ::GrayString(hDC, hBrush, lpOutputFunc, lpData, nCount, prc->left, prc->top, prc->right - prc->left, prc->bottom - prc->top); } // 84. /* BOOL InflateRect( LPRECT lprc, // rectangle int dx, // amount to adjust width int dy // amount to adjust height ); // */ GE_INLINE BOOL InflateRect( LPRECT lprc, SIZE size ) { return ::InflateRect(lprc, size.cx, size.cy); } GE_INLINE BOOL InflateRect( LPRECT lprc, int dxLeft, int dyTop, int dxRight, int dyBottom ) { if(lprc == NULL) return FALSE; lprc->left -= dxLeft; lprc->top -= dyTop; lprc->right += dxRight; lprc->bottom += dyBottom; return TRUE; } GE_INLINE BOOL DeflateRect( LPRECT lprc, // rectangle int dx, // amount to adjust width int dy // amount to adjust height ) { return ::InflateRect(lprc, -dx, -dy); } GE_INLINE BOOL DeflateRect( LPRECT lprc, SIZE size ) { return ::InflateRect(lprc, -size.cx, -size.cy); } GE_INLINE BOOL DeflateRect( LPRECT lprc, int dxLeft, int dyTop, int dxRight, int dyBottom ) { if(lprc == NULL) return FALSE; lprc->left += dxLeft; lprc->top += dyTop; lprc->right -= dxRight; lprc->bottom -= dyBottom; return TRUE; } // 87. /* BOOL OffsetRect( LPRECT lprc, // rectangle int dx, // horizontal offset int dy // vertical offset ); // */ GE_INLINE BOOL OffsetRect( LPRECT lprc, POINT pt ) { return ::OffsetRect(lprc, pt.x, pt.y); } GE_INLINE BOOL OffsetRect( LPRECT lprc, SIZE siz ) { return ::OffsetRect(lprc, siz.cx, siz.cy); } // 92. /* HRGN CreateEllipticRgn( int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect // y-coord of lower-right corner of rectangle ); // */ GE_INLINE HRGN CreateEllipticRgn( PRECT prc ) { return ::CreateEllipticRgn(prc->left, prc->top, prc->right, prc->bottom); } // 93. /* HRGN CreateRectRgn( int nLeftRect, // x-coordinate of upper-left corner int nTopRect, // y-coordinate of upper-left corner int nRightRect, // x-coordinate of lower-right corner int nBottomRect // y-coordinate of lower-right corner ); // */ GE_INLINE HRGN CreateRectRgn( PRECT prc ) { return ::CreateRectRgn(prc->left, prc->top, prc->right, prc->bottom); } // 94. /* HRGN CreateRoundRectRgn( int nLeftRect, // x-coordinate of upper-left corner int nTopRect, // y-coordinate of upper-left corner int nRightRect, // x-coordinate of lower-right corner int nBottomRect, // y-coordinate of lower-right corner int nWidthEllipse, // height of ellipse int nHeightEllipse // width of ellipse ); // */ GE_INLINE HRGN CreateRoundRectRgn( PRECT prc, int nWidthEllipse, int nHeightEllipse ) { return ::CreateRoundRectRgn(prc->left, prc->top, prc->right, prc->bottom, nWidthEllipse, nHeightEllipse); } GE_INLINE HRGN CreateRoundRectRgn( int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, SIZE size ) { return ::CreateRoundRectRgn(nLeftRect, nTopRect, nRightRect, nBottomRect, size.cx, size.cy); } GE_INLINE HRGN CreateRoundRectRgn( PRECT prc, SIZE size ) { return ::CreateRoundRectRgn(prc->left, prc->top, prc->right, prc->bottom, size.cx, size.cy); } // 96. /* int OffsetRgn( HRGN hrgn, // handle to region int nXOffset, // offset along x-axis int nYOffset // offset along y-axis ); // */ GE_INLINE int OffsetRgn( HRGN hrgn, POINT pt ) { return ::OffsetRgn(hrgn, pt.x, pt.y); } GE_INLINE int OffsetRgn( HRGN hrgn, SIZE size ) { return ::OffsetRgn(hrgn, size.cx, size.cy); } // 97. /* BOOL PtInRegion( HRGN hrgn, // handle to region int X, // x-coordinate of point int Y // y-coordinate of point ); // */ GE_INLINE BOOL PtInRegion( HRGN hrgn, POINT pt ) { return ::PtInRegion(hrgn, pt.x, pt.y); } // 99. /* BOOL SetRectRgn( HRGN hrgn, // handle to region int nLeftRect, // x-coordinate of upper-left corner of rectangle int nTopRect, // y-coordinate of upper-left corner of rectangle int nRightRect, // x-coordinate of lower-right corner of rectangle int nBottomRect // y-coordinate of lower-right corner of rectangle ); // */ GE_INLINE BOOL SetRectRgn( HRGN hrgn, PRECT prc ) { return ::SetRectRgn(hrgn, prc->left, prc->top, prc->right, prc->bottom); } ////////////////////////////////////////////////////////////////////////// // 8. /* BOOL GetBitmapDimensionEx( HBITMAP hBitmap, // handle to bitmap LPSIZE lpDimension // dimensions ); // */ GE_INLINE SIZE GetBitmapDimensionEx( HBITMAP hBitmap ) { SIZE size = { 0, 0 }; ::GetBitmapDimensionEx(hBitmap, &size); return size; } GE_INLINE BOOL GetBitmapDimension( HBITMAP hBitmap, LPSIZE lpDimension ) { return ::GetBitmapDimensionEx(hBitmap, lpDimension); } GE_INLINE SIZE GetBitmapDimension( HBITMAP hBitmap ) { SIZE size = { 0, 0 }; ::GetBitmapDimensionEx(hBitmap, &size); return size; } #define GetBitmapSize GetBitmapDimension // 19. /* BOOL GetBrushOrgEx( HDC hdc, // handle to DC LPPOINT lppt // coordinates of origin ); // */ GE_INLINE POINT GetBrushOrgEx( HDC hdc ) { POINT pt = { 0, 0 }; ::GetBrushOrgEx(hdc, &pt); return pt; } GE_INLINE BOOL GetBrushOrg( HDC hdc, LPPOINT lppt ) { return ::GetBrushOrgEx(hdc, lppt); } GE_INLINE POINT GetBrushOrg( HDC hdc ) { POINT pt = { 0, 0 }; ::GetBrushOrgEx(hdc, &pt); return pt; } // 30. /* BOOL GetCurrentPositionEx( HDC hdc, // handle to device context LPPOINT lpPoint // current position ); // */ GE_INLINE POINT GetCurrentPositionEx( HDC hdc ) { POINT pt = { 0, 0 }; ::GetCurrentPositionEx(hdc, &pt); return pt; } GE_INLINE BOOL GetCurrentPosition( HDC hdc, LPPOINT lpPoint ) { return ::GetCurrentPositionEx(hdc, lpPoint); } GE_INLINE POINT GetCurrentPosition( HDC hdc ) { POINT pt = { 0, 0 }; ::GetCurrentPositionEx(hdc, &pt); return pt; } // 31. /* BOOL GetViewportExtEx( HDC hdc, // handle to device context LPSIZE lpSize // viewport dimensions ); // */ GE_INLINE SIZE GetViewportExtEx( HDC hdc ) { SIZE size = { 0, 0 }; ::GetViewportExtEx(hdc, &size); return size; } GE_INLINE BOOL GetViewportExt( HDC hdc, LPSIZE lpSize ) { return ::GetViewportExtEx(hdc, lpSize); } GE_INLINE SIZE GetViewportExt( HDC hdc ) { SIZE size = { 0, 0 }; ::GetViewportExtEx(hdc, &size); return size; } // 32. /* BOOL GetViewportOrgEx( HDC hdc, // handle to device context LPPOINT lpPoint // viewport origin ); // */ GE_INLINE POINT GetViewportOrgEx( HDC hdc ) { POINT pt = { 0, 0 }; ::GetViewportOrgEx(hdc, &pt); return pt; } GE_INLINE BOOL GetViewportOrg( HDC hdc, LPPOINT lpPoint ) { return ::GetViewportOrgEx(hdc, lpPoint); } GE_INLINE POINT GetViewportOrg( HDC hdc ) { POINT pt = { 0, 0 }; ::GetViewportOrgEx(hdc, &pt); return pt; } // 33. /* BOOL GetWindowExtEx( HDC hdc, // handle to device context LPSIZE lpSize // window extents ); // */ GE_INLINE SIZE GetWindowExtEx( HDC hdc ) { SIZE size = { 0, 0 }; ::GetWindowExtEx(hdc, &size); return size; } GE_INLINE BOOL GetWindowExt( HDC hdc, LPSIZE lpSize ) { return ::GetWindowExtEx(hdc, lpSize); } GE_INLINE SIZE GetWindowExt( HDC hdc ) { SIZE size = { 0, 0 }; ::GetWindowExtEx(hdc, &size); return size; } // 34. /* BOOL GetWindowOrgEx( HDC hdc, // handle to device context LPPOINT lpPoint // window origin ); // */ GE_INLINE POINT GetWindowOrgEx( HDC hdc ) { POINT pt = { 0, 0 }; ::GetWindowOrgEx(hdc, &pt); return pt; } GE_INLINE BOOL GetWindowOrg( HDC hdc, LPPOINT lpPoint ) { return ::GetWindowOrgEx(hdc, lpPoint); } GE_INLINE POINT GetWindowOrg( HDC hdc ) { POINT pt = { 0, 0 }; ::GetWindowOrgEx(hdc, &pt); return pt; } // 38. (return?) /* BOOL ScaleViewportExtEx( HDC hdc, // handle to device context int Xnum, // horizontal multiplicand int Xdenom, // horizontal divisor int Ynum, // vertical multiplicand int Ydenom, // vertical divisor LPSIZE lpSize // previous viewport extents ); // */ GE_INLINE SIZE ScaleViewportExtEx( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom ) { SIZE size = { 0, 0 }; ::ScaleViewportExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, &size); return size; } GE_INLINE BOOL ScaleViewportExt( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom, LPSIZE lpSize ) { return ::ScaleViewportExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, lpSize); } GE_INLINE SIZE ScaleViewportExt( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom ) { SIZE size = { 0, 0 }; ::ScaleViewportExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, &size); return size; } // 39. (return?) /* BOOL ScaleWindowExtEx( HDC hdc, // handle to device context int Xnum, // horizontal multiplicand int Xdenom, // horizontal divisor int Ynum, // vertical multiplicand int Ydenom, // vertical divisor LPSIZE lpSize // previous window extents ); // */ GE_INLINE SIZE ScaleWindowExtEx( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom ) { SIZE size = { 0, 0 }; ::ScaleWindowExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, &size); return size; } GE_INLINE BOOL ScaleWindowExt( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom, LPSIZE lpSize ) { return ::ScaleWindowExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, lpSize); } GE_INLINE SIZE ScaleWindowExt( HDC hdc, int Xnum, int Xdenom, int Ynum, int Ydenom ) { SIZE size = { 0, 0 }; ::ScaleWindowExtEx(hdc, Xnum, Xdenom, Ynum, Ydenom, &size); return size; } // 45. /* BOOL GetDCOrgEx( HDC hdc, // handle to a DC LPPOINT lpPoint // translation origin ); // */ GE_INLINE POINT GetDCOrgEx( HDC hdc ) { POINT pt = { 0, 0 }; ::GetDCOrgEx(hdc, &pt); return pt; } GE_INLINE BOOL GetDCOrg( HDC hdc, LPPOINT lpPoint ) { return ::GetDCOrgEx(hdc, lpPoint); } GE_INLINE POINT GetDCOrg( HDC hdc ) { POINT pt = { 0, 0 }; ::GetDCOrgEx(hdc, &pt); return pt; } // 54. /* BOOL GetTextExtentExPoint( HDC hdc, // handle to DC LPCTSTR lpszStr, // character string int cchString, // number of characters int nMaxExtent, // maximum width of formatted string LPINT lpnFit, // maximum number of characters LPINT alpDx, // array of partial string widths LPSIZE lpSize // string dimensions ); // */ GE_INLINE SIZE GetTextExtentExPoint( HDC hdc, LPCTSTR lpszStr, int cchString, int nMaxExtent, LPINT lpnFit, LPINT alpDx ) { SIZE size = { 0, 0 }; ::GetTextExtentExPoint(hdc, lpszStr, cchString, nMaxExtent, lpnFit, alpDx, &size); return size; } #if (_WIN32_WINNT >= 0x0500) // 55. /* BOOL GetTextExtentExPointI( HDC hdc, // handle to DC LPWORD pgiIn, // array of glyph indices int cgi, // number of glyphs in array int nMaxExtent, // maximum width of formatted string LPINT lpnFit, // maximum number of characters LPINT alpDx, // array of partial string widths LPSIZE lpSize // string dimensions ); // */ GE_INLINE SIZE GetTextExtentExPointI( HDC hdc, LPWORD pgiIn, int cgi, int nMaxExtent, LPINT lpnFit, LPINT alpDx ) { SIZE size = { 0, 0 }; ::GetTextExtentExPointI(hdc, pgiIn, cgi, nMaxExtent, lpnFit, alpDx, &size); return size; } #endif // _WIN32_WINNT >= 0x0500 // 56. /* BOOL GetTextExtentPoint( HDC hdc, // handle to DC LPCTSTR lpString, // text string int cbString, // number of characters in string LPSIZE lpSize // string size ); // */ GE_INLINE SIZE GetTextExtentPoint( HDC hdc, LPCTSTR lpString, int cbString ) { SIZE size = { 0, 0 }; ::GetTextExtentPoint(hdc, lpString, cbString, &size); return size; } // 57. /* BOOL GetTextExtentPoint32( HDC hdc, // handle to DC LPCTSTR lpString, // text string int cbString, // characters in string LPSIZE lpSize // string size ); // */ GE_INLINE SIZE GetTextExtentPoint32( HDC hdc, LPCTSTR lpString, int cbString ) { SIZE size = { 0, 0 }; ::GetTextExtentPoint32(hdc, lpString, cbString, &size); return size; } #if (_WIN32_WINNT >= 0x0500) // 58. /* BOOL GetTextExtentPointI( HDC hdc, // handle to DC LPWORD pgiIn, // glyph indices int cgi, // number of indices in array LPSIZE lpSize // string size ); // */ GE_INLINE SIZE GetTextExtentPointI( HDC hdc, LPWORD pgiIn, int cgi ) { SIZE size = { 0, 0 }; ::GetTextExtentPointI(hdc, pgiIn, cgi, &size); return size; } #endif // _WIN32_WINNT >= 0x0500 /// Part 2: Windows GDI API utility extensions GE_INLINE BOOL FillSolidRect(HDC hdc, int x, int y, int cx, int cy, COLORREF clr) { SetBkColor(hdc, clr); RECT rc = { x, y, x + cx, y + cy }; return ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL); } GE_INLINE BOOL FillSolidRect(HDC hdc, PRECT prc, COLORREF clr) { // Fill background SetBkColor(hdc, clr); return ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, prc, NULL, 0, NULL); } GE_INLINE BOOL Draw3dRect(HDC hdc, int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight) { FillSolidRect(hdc, x, y, cx - 1, 1, clrTopLeft); FillSolidRect(hdc, x, y, 1, cy - 1, clrTopLeft); FillSolidRect(hdc, x + cx, y, -1, cy, clrBottomRight); FillSolidRect(hdc, x, y + cy, cx, -1, clrBottomRight); return TRUE; } GE_INLINE BOOL Draw3dRect(HDC hdc, PRECT prc, COLORREF clrTopLeft, COLORREF clrBottomRight) { return Draw3dRect(hdc, prc->left, prc->top, prc->right - prc->left, prc->bottom - prc->top, clrTopLeft, clrBottomRight); } /// Part 3: Common control API extensions GE_INLINE BOOL ImageList_Draw(HIMAGELIST himl, int i, HDC hdcDst, POINT pt, UINT fStyle) { return ::ImageList_Draw(himl, i, hdcDst, pt.x, pt.y, fStyle); } }; // namespace TWL #endif // __GDIEXT_H__
[ "dandycheung@9b253700-4547-11de-82b9-170f4fd74ac7" ]
[ [ [ 1, 2702 ] ] ]
5987e64a076bfb48ec4ce03fb0be9f9c01961942
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Common/String/Utf8.hpp
e871b14a81ee9b14a641592e4bf7c262e1f3a017
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
233
hpp
#ifndef UTF8_HPP #define UTF8_HPP #include "../../Core/Sp_DataTypes.hpp" namespace Spiral { namespace Common { namespace String { wString ConvertUtf8_to_Wchar( const cString& str ); } // Common } // String } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 14 ] ] ]
60aae7bc3fa8944bf3b4c7bd6051850e759cd591
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qsystemsemaphore.h
6cf0b75bb66d209c357cd403b34922d870bbb9f7
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,081
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QSYSTEMSEMAPHORE_H #define QSYSTEMSEMAPHORE_H #include <QtCore/qstring.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Core) #ifndef QT_NO_SYSTEMSEMAPHORE class QSystemSemaphorePrivate; class Q_CORE_EXPORT QSystemSemaphore { public: enum AccessMode { Open, Create }; enum SystemSemaphoreError { NoError, PermissionDenied, KeyError, AlreadyExists, NotFound, OutOfResources, UnknownError }; QSystemSemaphore(const QString &key, int initialValue = 0, AccessMode mode = Open); ~QSystemSemaphore(); void setKey(const QString &key, int initialValue = 0, AccessMode mode = Open); QString key() const; bool acquire(); bool release(int n = 1); SystemSemaphoreError error() const; QString errorString() const; private: Q_DISABLE_COPY(QSystemSemaphore) QSystemSemaphorePrivate *d; }; #endif // QT_NO_SYSTEMSEMAPHORE QT_END_NAMESPACE QT_END_HEADER #endif // QSYSTEMSEMAPHORE_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 102 ] ] ]
5f999ad6b9ed48329db5b5ba7b83dfdcfd56be16
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Server/DatabaseServer/DatabaseServer.cpp
5400743142721d0d129167611ee2f778480c468b
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
1,171
cpp
// DatabaseServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Common/Network/kpnServer.h" #include "Common/Network/kpnListenSocket.h" #include "Common/Utility/kpuLinkedList.h" extern DispatchFunction s_pPacketHandlers[]; kpuLinkedList g_lServerList; int _tmain(int argc, _TCHAR* argv[]) { kpnBaseSocket::Initialize(); kpnBaseSocket* pSocket = new kpnBaseSocket(DATABASE_SERVER_PORT); printf("Database Server running on port: %d\n", DATABASE_SERVER_PORT); while( 1 ) { // Update the bound socket pSocket->Update(s_pPacketHandlers); // Update the server lists kpuLinkedList* pIter = g_lServerList.Next(); while( pIter ) { kpnServer* pServer = (kpnServer*)pIter->GetPointer(); pServer->Update(s_pPacketHandlers); if( pServer->GetState() == kpnServer::eSS_Closed ) { // Connection closed, remove it from the list kpuLinkedList* pKill = pIter; pIter = pIter->Prev(); delete pServer; delete pKill; } pIter = pIter->Next(); } // Play nice with others Sleep(1); } kpnBaseSocket::Shutdown(); return 0; }
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 50 ] ] ]
ddbb8d5084897b746faed0b48021802d397ba7c8
655546c6474a2fddc31b9327c983de55f729d78a
/seismicu/seismicu.h
6a4a17eb1b2d073eaec8af6373bfac3c548e6d31
[]
no_license
edvelezg/repotmp
23b25eb7bc418d971d76722254fb01df96b572b5
71610bf58114bc04ae5c6220e8ec5fe294c982cb
refs/heads/master
2016-09-06T16:29:33.097481
2008-12-18T12:58:54
2008-12-18T12:58:54
33,052,988
0
0
null
null
null
null
UTF-8
C++
false
false
511
h
#ifndef SEISMICU_H #define SEISMICU_H #include <QDialog> #include <QProcess> #include "ui_seismicu.h" class SeismicU : public QDialog, private Ui::SeismicU { Q_OBJECT public: SeismicU(QWidget *parent = 0); private slots: void processFinished(int exitCode, QProcess::ExitStatus exitStatus); void runScript(); void updateOutputTextEdit(); void processError(QProcess::ProcessError error); private: QProcess process; QString targetFile; }; #endif
[ "EdVelez.G@c7d15216-b18b-11dd-89d2-dfb2a00067cc" ]
[ [ [ 1, 28 ] ] ]
5fd62a9f442ffe28d5676337544c0653d61cdcc9
583d876ec2e0577f03d27033c44a731cb5883219
/Robot_ReachingDlg.cpp
421ed0ddabe1d46b7b79168ffe90f4c81bc889a7
[]
no_license
BGCX067/eyerobot-hg-to-git
6950df8a76cd536682843eb6c1232833735be7ee
f25681efe96f205fb0dac74b0072a5ac08070467
refs/heads/master
2016-09-01T08:50:07.262989
2010-07-09T18:40:57
2010-07-09T18:40:57
48,706,126
0
0
null
null
null
null
UTF-8
C++
false
false
35,308
cpp
// Robot_ReachingDlg.cpp : implementation file // /************************************************ Robot Reaching: initializes robot arm and moves it to preset locations CAUTION: double check locations and origin in robot firmware - it will crash into smth if locations are incorrect Outputs data in SAM ascii format **************************************************/ #include "stdafx.h" #include "Robot_Reaching.h" #include "Robot_ReachingDlg.h" #include "luautils.h" //polhemus stuff... //#include "PDI.h" //#include "pdifunc.h" #include <time.h> #include <mmsystem.h> #include <algorithm> #include <vector> #include <sstream> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #endif #define BUFFER_SIZE 1000000000 BYTE BUFFER[BUFFER_SIZE]; //in mm #define CENTERX 380.0 #define CENTERY 0.0 #define CENTERZ 300.0 #define YOFFSET 100.0 // y offset of the hand from the base #define ZOFFSET 100.0 // z offset of the hand from the base #define DATA_LENGTH 12 #define WAIT 2500 //how long the robot stays at target #define MOVWAIT 1000 //wait for the robot to finish moving #define LEDONTIME 2000 //led on at fixation point #define ROBOT2TARGET 300 //max time(guesstimate) taken to target location #define TONE2END 3000 //from start tone to end of trial(robot back to initial) #define LED2TONE 1000 #define TONE2LED 200 //time that LED goes off after the tone #define SPEED 90 //ROBOT speed #define FPS 240 using namespace std; //PDIFunc pdi;//tracker //PBYTE pbeg, pcur, pfin;//tracker CStdioFile fp; std:: vector < double > data[DATA_LENGTH]; //data from tracker float curData[DATA_LENGTH]; //data from 1 sensor int newTime; int oldTime = -1; int sensors = 0; //number of sensors used int counter = 1; //trial counter; int framec = 0; //frame counter int trialNum[4] = {90, 90, 90, 90}; //fabian note; total no of trials, can change to alter the number of trials int withinTrialTargetNum; //fabian note; total no of trials, can change to alter the number of trials int targetSeq[MAXEVENTS][MAXEVENTS]; int condNum[4] = {1, 1, 2, 3};//the LED sequence. DO NOT CHANGE //bool flag = false; //flag for recording state (i.e. recording if !flag) bool initialized = false; //flag for usage of tracker, false if tracker not used CString str, name(""); //UINT __cdecl threadFoo( LPVOID pParam ); // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CRobot_ReachingDlg dialog CRobot_ReachingDlg::CRobot_ReachingDlg(CWnd* pParent /*=NULL*/) : CDialog(CRobot_ReachingDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CRobot_ReachingDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_RADIO1, radbut1); DDX_Control(pDX, IDC_RADIO2, radbut2); DDX_Control(pDX, IDC_RADIO3, radbut3); DDX_Control(pDX, IDC_RADIO4, radbut4); DDX_Control(pDX, IDC_COMBO1, m_combo1); DDX_Control(pDX, IDC_COMBO2, m_combo2); DDX_Control(pDX, IDC_COMBO3, m_combo3); DDX_Control(pDX, IDC_COMBO4, m_combo4); DDX_Control(pDX, IDC_COMBO5, m_combo5); DDX_Control(pDX, IDC_COMBO6, m_combo6); DDX_Control(pDX, IDC_COMBO7, m_combo7); DDX_Control(pDX, IDC_COMBO8, m_combo8); } BEGIN_MESSAGE_MAP(CRobot_ReachingDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDOK, &CRobot_ReachingDlg::OnBnClickedOk) ON_BN_CLICKED(IDC_BUTTON1, &CRobot_ReachingDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CRobot_ReachingDlg::OnBnClickedButton2) //ON_BN_CLICKED(IDC_BUTTON3, &CRobot_ReachingDlg::OnBnClickedButton3) ON_WM_DESTROY() ON_BN_CLICKED(IDC_BUTTON4, &CRobot_ReachingDlg::OnBnClickedButton4) END_MESSAGE_MAP() // CRobot_ReachingDlg message handlers BOOL CRobot_ReachingDlg::OnInitDialog() { Robot = NULL; current_trial_counter = 0; //reset trial counter currentTarget = 0; /*init repetition tracker*/ for ( int i=0;i<LOCATIONNUM-1;i++){ repetitions[i] = 0; } for ( int i=0;i< trialNum[condition_type - 1] / 2;i++){ for ( int j=0;j<2;j++){ current_trial[2*i+j] = j; }} CDialog::OnInitDialog(); /*turn off 'Next Trial', 'redo trial' and 'Stop Recording'*/ CWnd * pbutton = GetDlgItem( IDC_BUTTON1); pbutton->EnableWindow(false); pbutton = GetDlgItem( IDC_BUTTON3); pbutton->EnableWindow(false); pbutton = GetDlgItem( IDC_BUTTON4); pbutton->EnableWindow(false); radbut1.SetCheck(BST_CHECKED); //Set one of the radiobuttons to be selected m_combo1.AddString(_T("Control")); m_combo1.AddString(_T("Parkinsons DBS")); m_combo1.SetCurSel(0); m_combo2.AddString(_T("Right")); m_combo2.AddString(_T("Left")); m_combo2.SetCurSel(1); /*Robot*/ m_combo3.AddString(_T("Robot")); m_combo3.AddString(_T("Hand")); m_combo3.AddString(_T("Thumb")); m_combo3.AddString(_T("Index")); m_combo3.AddString(_T("Middle")); m_combo3.AddString(_T("Wrist")); m_combo3.AddString(_T("Elbow")); m_combo3.AddString(_T("Shoulder")); m_combo3.AddString(_T("Forearm")); m_combo3.AddString(_T("Upperarm")); m_combo3.AddString(_T("none")); m_combo3.SetCurSel(0); /*Hand*/ m_combo4.AddString(_T("Robot")); m_combo4.AddString(_T("Hand")); m_combo4.AddString(_T("Thumb")); m_combo4.AddString(_T("Index")); m_combo4.AddString(_T("Middle")); m_combo4.AddString(_T("wrist")); m_combo4.AddString(_T("elbow")); m_combo4.AddString(_T("shoulder")); m_combo4.AddString(_T("Forearm")); m_combo4.AddString(_T("Upperarm")); m_combo4.AddString(_T("none")); m_combo4.SetCurSel(1); /*Wrist*/ m_combo5.AddString(_T("Robot")); m_combo5.AddString(_T("Hand")); m_combo5.AddString(_T("Thumb")); m_combo5.AddString(_T("Index")); m_combo5.AddString(_T("Middle")); m_combo5.AddString(_T("wrist")); m_combo5.AddString(_T("elbow")); m_combo5.AddString(_T("shoulder")); m_combo5.AddString(_T("Forearm")); m_combo5.AddString(_T("Upperarm")); m_combo5.AddString(_T("none")); m_combo5.SetCurSel(5); /*Elbow*/ m_combo6.AddString(_T("Robot")); m_combo6.AddString(_T("Hand")); m_combo6.AddString(_T("Thumb")); m_combo6.AddString(_T("Index")); m_combo6.AddString(_T("Middle")); m_combo6.AddString(_T("wrist")); m_combo6.AddString(_T("elbow")); m_combo6.AddString(_T("shoulder")); m_combo6.AddString(_T("Forearm")); m_combo6.AddString(_T("Upperarm")); m_combo6.AddString(_T("none")); m_combo6.SetCurSel(6); /*shoulder*/ m_combo7.AddString(_T("Robot")); m_combo7.AddString(_T("Hand")); m_combo7.AddString(_T("Thumb")); m_combo7.AddString(_T("Index")); m_combo7.AddString(_T("Middle")); m_combo7.AddString(_T("wrist")); m_combo7.AddString(_T("elbow")); m_combo7.AddString(_T("shoulder")); m_combo7.AddString(_T("Forearm")); m_combo7.AddString(_T("Upperarm")); m_combo7.AddString(_T("none")); m_combo7.SetCurSel(7); m_combo8.AddString(_T("Robot")); m_combo8.AddString(_T("Hand")); m_combo8.AddString(_T("Thumb")); m_combo8.AddString(_T("Index")); m_combo8.AddString(_T("Middle")); m_combo8.AddString(_T("wrist")); m_combo8.AddString(_T("elbow")); m_combo8.AddString(_T("shoulder")); m_combo8.AddString(_T("Forearm")); m_combo8.AddString(_T("Upperarm")); m_combo8.AddString(_T("none")); m_combo8.SetCurSel(10); // 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 CRobot_ReachingDlg::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 CRobot_ReachingDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CRobot_ReachingDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } int CRobot_ReachingDlg::Initialize_locations() { temploc = Robot->GetLocation("reach_eye.v3", "n_1"); locations[0].x = temploc->Getx(); locations[0].y = temploc->Gety(); locations[0].z = temploc->Getz(); locations[0].rotatex = temploc->Getxrot(); locations[0].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_2"); locations[1].x = temploc->Getx(); locations[1].y = temploc->Gety(); locations[1].z = temploc->Getz(); locations[1].rotatex = temploc->Getxrot(); locations[1].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_3"); locations[2].x = temploc->Getx(); locations[2].y = temploc->Gety(); locations[2].z = temploc->Getz(); locations[2].rotatex = temploc->Getxrot(); locations[2].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_4"); locations[3].x = temploc->Getx(); locations[3].y = temploc->Gety(); locations[3].z = temploc->Getz(); locations[3].rotatex = temploc->Getxrot(); locations[3].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_5"); locations[4].x = temploc->Getx(); locations[4].y = temploc->Gety(); locations[4].z = temploc->Getz(); locations[4].rotatex = temploc->Getxrot(); locations[4].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_6"); locations[5].x = temploc->Getx(); locations[5].y = temploc->Gety(); locations[5].z = temploc->Getz(); locations[5].rotatex = temploc->Getxrot(); locations[5].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_7"); locations[6].x = temploc->Getx(); locations[6].y = temploc->Gety(); locations[6].z = temploc->Getz(); locations[6].rotatex = temploc->Getxrot(); locations[6].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_8"); locations[7].x = temploc->Getx(); locations[7].y = temploc->Gety(); locations[7].z = temploc->Getz(); locations[7].rotatex = temploc->Getxrot(); locations[7].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_9"); locations[8].x = temploc->Getx(); locations[8].y = temploc->Gety(); locations[8].z = temploc->Getz(); locations[8].rotatex = temploc->Getxrot(); locations[8].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_10"); locations[9].x = temploc->Getx(); locations[9].y = temploc->Gety(); locations[9].z = temploc->Getz(); locations[9].rotatex = temploc->Getxrot(); locations[9].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_11"); locations[10].x = temploc->Getx(); locations[10].y = temploc->Gety(); locations[10].z = temploc->Getz(); locations[10].rotatex = temploc->Getxrot(); locations[10].rotatey = temploc->Getyrot(); temploc = Robot->GetLocation("reach_eye.v3", "n_12"); locations[11].x = temploc->Getx(); locations[11].y = temploc->Gety(); locations[11].z = temploc->Getz(); locations[11].rotatex = temploc->Getxrot(); locations[11].rotatey = temploc->Getyrot(); /* initial position */ temploc = Robot->GetLocation("reach_eye.v3", "initial3"); locations[12].x= temploc->Getx(); locations[12].y= temploc->Gety(); locations[12].z= temploc->Getz(); locations[12].rotatex= temploc->Getxrot(); locations[12].rotatey= temploc->Getyrot(); /* safety position */ temploc = Robot->GetLocation("reach_eye.v3", "n_safe_l"); locations[13].x= temploc->Getx(); locations[13].y= temploc->Gety(); locations[13].z= temploc->Getz(); locations[13].rotatex= temploc->Getxrot(); locations[13].rotatey= temploc->Getyrot(); /* another safety position */ temploc = Robot->GetLocation("reach_eye.v3", "n_safe_r"); locations[14].x= temploc->Getx(); locations[14].y= temploc->Gety(); locations[14].z= temploc->Getz(); locations[14].rotatex= temploc->Getxrot(); locations[14].rotatey= temploc->Getyrot(); return 1; } void CRobot_ReachingDlg::Randomize_trials() { vector<int> Numbers; // Initialize vector Numbers for (int i=0; i < 2; i++) for (int j = 0; j < (trialNum[condition_type - 1] / 2); j++) Numbers.push_back(i); random_shuffle(Numbers.begin(),Numbers.end()); for ( int i=0;i<trialNum[condition_type - 1];i++) current_trial[i]= (int) Numbers[i] ; CStdioFile fp1; CFileException fileException; CString tempstr_folder(""); tempstr_folder.Format(_T("%s\\LogRobot.txt"),name); if ( !fp1.Open( tempstr_folder, CFile::modeCreate | CFile::modeReadWrite, &fileException ) ) { ::AfxMessageBox(fileException.m_cause, 0, 0 ); } /*Write coordinates and trial sequence in the file*/ CString tempstr1(""); for( int i =0; i<3; i++){ tempstr1.Format(_T("Location %d: x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f\n"), i+1, locations[i].x, locations[i].y, locations[i].z, locations[i].rotatex, locations[i].rotatey); SetDlgItemText(IDC_STATIC2, tempstr1 ); fp1.WriteString( tempstr1 ); } for ( int i=0;i<trialNum[condition_type - 1];i++){ tempstr1.Format(_T("Trial %d: location %d\n"), i+1, current_trial[i]+1); fp1.WriteString( tempstr1 ); } fp1.Flush(); fp1.Close(); } void CRobot_ReachingDlg::RandomizeLeds() { vector<int> Num; // Initialize vector Numbers for (int i=0; i < condNum[condition_type - 1]; i++) { for (int j = 0; j < (trialNum[condition_type - 1] / condNum[condition_type - 1]); j++) { Num.push_back(i); } } random_shuffle(Num.begin(),Num.end()); for ( int i=0;i<trialNum[condition_type - 1];i++) current_leds[i]= (int) Num[i]; CStdioFile fp1; CFileException fileException; CString tempstr_folder(""); tempstr_folder.Format(_T("%s\\LedSequence.txt"),name); if ( !fp1.Open( tempstr_folder, CFile::modeCreate | CFile::modeReadWrite, &fileException ) ) { ::AfxMessageBox(fileException.m_cause, 0, 0 ); } /*Write coordinates and trial sequence in the file*/ CString tempstr1(""); //for( int i = 0; i < 3; i++){ // tempstr1.Format(_T("LED Sequence %d: x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f\n"), i+1, // locations[i].x, locations[i].y, locations[i].z, locations[i].rotatex, locations[i].rotatey); //SetDlgItemText(IDC_STATIC2, tempstr1 ); //fp1.WriteString( tempstr1 ); //} for ( int i=0;i<trialNum[condition_type - 1];i++){ tempstr1.Format(_T("Trial %d: LED sequence %d\n"), i+1, current_leds[i]+1); SetDlgItemText(IDC_STATIC2, tempstr1 ); fp1.WriteString( tempstr1 ); } fp1.Flush(); fp1.Close(); } void CRobot_ReachingDlg::OnBnClickedOk() { OnOK(); } void CRobot_ReachingDlg::DoEvent(int type, int para) { /*** Robot operations ***/ //move to next location, play sound, record data until next trial is pressed again float x,y,z,xro,yro; int t; switch (type) { case 0: t = targetSeq[current_trial_counter][currentTarget] - 1; x = (float) locations[t].x; y = (float) locations[t].y; z = (float) locations[t].z; xro = (float) locations[t].rotatex; yro = (float) locations[t].rotatey; Robot->MoveTo_Actual_Point(x, y, z, xro, yro); currentTarget++; break; case 1: Robot->GPIO(15, para); break; case 2: Robot->GPIO(14, para); break; } } /*************** Start Trial ****************/ void CRobot_ReachingDlg::OnBnClickedButton1() { /*turn off 'Next Trial' and 'redo trial'*/ CWnd * pbutton = GetDlgItem( IDC_BUTTON1); LARGE_INTEGER sample1, sample2, frequency; LONGLONG elapsedTime; pbutton->EnableWindow(false); pbutton = GetDlgItem( IDC_BUTTON4); pbutton->EnableWindow(false); if( radbut1.GetCheck() == BST_CHECKED) //condition condition_type = 1; else if( radbut2.GetCheck() == BST_CHECKED) condition_type = 2; else if (radbut3.GetCheck() == BST_CHECKED) condition_type = 3; else { condition_type = 4; } radbut1.EnableWindow( false ); radbut2.EnableWindow( false ); radbut3.EnableWindow( false ); radbut4.EnableWindow( false ); /*** Tracker operations: "name\name_conditiontype_currtrial_target#_rep#.dat ***/ str.Format( _T("%s\\%s_cond_%d_%d_%d_%d.dat"), name, name, condition_type, current_trial_counter+1, current_trial[current_trial_counter]+1, repetitions[current_trial[current_trial_counter]] ); SetDlgItemText(IDC_EDIT1, str ); //flag = false; //reset the falg for new recording CFileException fileException; if ( !fp.Open( str, CFile::modeCreate | CFile::modeReadWrite, &fileException ) ) { ::AfxMessageBox(fileException.m_cause, 0, 0 ); } //pdi.ClearBuffer(); //buffer goes back to the beginning //Sleep(100); //give some time to clear buffer /*** Header for the file ***/ CString fstr ("info: 8\n"); //#of subseq. lines fp.WriteString( fstr ); fstr.Format(_T("subject_name %s\n"),name); //subj. name fp.WriteString( fstr ); if( radbut1.GetCheck() == BST_CHECKED) //condition fstr.Format(_T("condition 1\n")); else if( radbut2.GetCheck() == BST_CHECKED) fstr.Format(_T("condition 2\n")); else fstr.Format(_T("condition 3\n")); fp.WriteString( fstr ); int nIndex = m_combo1.GetCurSel(); //classification CString tstr; m_combo1.GetLBText(nIndex, tstr); fstr.Format( _T("classification %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo2.GetCurSel(); //hand m_combo2.GetLBText(nIndex, tstr); fstr.Format( _T("hand %s\n"),tstr); fp.WriteString(fstr); fstr.Format( _T("sample_rate %d\n"), FPS); //frames per second fp.WriteString(fstr); CTime t = CTime::GetCurrentTime(); //date and time fstr = t.Format( "Date %m/%d/%y\nTime %H.%M.%S\n\n" ); fp.WriteString(fstr); fstr.Format( _T("channels: %d\n"),sensors ); fp.WriteString(fstr); nIndex = m_combo3.GetCurSel(); //channel 0 m_combo3.GetLBText(nIndex, tstr); fstr.Format( _T("1 vector %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo4.GetCurSel(); //channel 1 m_combo4.GetLBText(nIndex, tstr); fstr.Format( _T("2 vector %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo5.GetCurSel(); //channel 2 m_combo5.GetLBText(nIndex, tstr); fstr.Format( _T("3 vector %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo6.GetCurSel(); //channel 3 m_combo6.GetLBText(nIndex, tstr); fstr.Format( _T("4 vector %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo7.GetCurSel(); //channel 4 m_combo7.GetLBText(nIndex, tstr); fstr.Format( _T("5 vector %s\n"),tstr); fp.WriteString(fstr); nIndex = m_combo8.GetCurSel(); //channel 5 m_combo8.GetLBText(nIndex, tstr); fstr.Format( _T("6 vector %s\n\n"),tstr); fp.WriteString(fstr); fstr.Format( _T("connections: 5\n0 3\n1 3\n2 3\n3 4\n4 5\n\nsamples:\n")); fp.WriteString(fstr); CString str(""); /*call thread function*/ //AfxBeginThread( threadFoo, 0, 0, 0, 0, NULL); str += "Recording data...\n"; SetDlgItemText(IDC_STATIC2, str ); /*inc repetition for current location*/ repetitions[current_trial[current_trial_counter]]++; CString tempstr(""); // tempstr.Format(_T("Trial #%d / %d \nMoving to: location #%d:\n x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f"), // current_trial_counter+1,trialNum[condition_type - 1], current_trial[current_trial_counter]+1, x, y, z, xro, yro); SetDlgItemText(IDC_STATIC2, tempstr ); QueryPerformanceCounter (&sample1); QueryPerformanceFrequency (&frequency); //::AfxMessageBox(tempstr, 0, 0 ); if(condition_type==1)// remembered target, 100 ms target, no tone { for (int i=0; i<eventCount; ++i ) { if (eventTime[i] < 0.001) { DoEvent(eventType[i], eventPara[i]); continue; } do { QueryPerformanceCounter(&sample2); elapsedTime = (sample2.QuadPart - sample1.QuadPart) / frequency.QuadPart; } while (elapsedTime <= eventTime[i]);//Sleep(1000); DoEvent(eventType[i], eventPara[i]); } //hand LED on for 1 sec //if(current_trial[current_trial_counter]==2)// || current_trial[current_trial_counter]==3) //{ // //robot moves out of the way // Robot->MoveTo_Actual_Point(locations[4].x, locations[4].y, locations[4].z, locations[4].rotatex, locations[4].rotatey); //} //else //{ // //robot moves out of the way // Robot->MoveTo_Actual_Point(locations[3].x, locations[3].y, locations[3].z, locations[3].rotatex, locations[3].rotatey); //} //back to initial position //Sleep(TONE2END); Robot->MoveTo_Actual_Point(locations[12].x, locations[12].y, locations[12].z, locations[12].rotatex, locations[12].rotatey); CString str(""); str.Format(_T("\nBack to initial position:\nMoving to: x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f"), locations[12].x, locations[12].y, locations[12].z, locations[12].rotatex, locations[12].rotatey); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); current_trial_counter++; currentTarget = 0; } else if (condition_type==2) { switch (current_trial[current_trial_counter] + 1) { case 1: Robot->MoveTo_Actual_Point(locations[0].x, locations[0].y, locations[0].z, locations[0].rotatex, locations[0].rotatey); break; case 2: Robot->MoveTo_Actual_Point(locations[1].x, locations[1].y, locations[1].z, locations[1].rotatex, locations[1].rotatey); break; } switch (current_leds[current_trial_counter] + 1) { case 1: // if the current LED sequence == Condition 2.2 Sleep(1000); Robot->GPIO(14, 1); Sleep(4900); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Sleep(5000); Robot->GPIO(14, 0); break; } Robot->MoveTo_Actual_Point(locations[2].x, locations[2].y, locations[2].z, locations[2].rotatex, locations[2].rotatey); CString str(""); str.Format(_T("\n\nLED condition 2.2")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); current_trial_counter++; } else if (condition_type==3) // actual target { switch (current_trial[current_trial_counter] + 1) { case 1: Robot->MoveTo_Actual_Point(locations[0].x, locations[0].y, locations[0].z, locations[0].rotatex, locations[0].rotatey); break; case 2: Robot->MoveTo_Actual_Point(locations[1].x, locations[1].y, locations[1].z, locations[1].rotatex, locations[1].rotatey); break; } switch (current_leds[current_trial_counter] + 1) { case 1: // if the current LED sequence = condition 2.1 str.Format(_T("\n\nLED condition 2.1")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); Sleep(1000); Robot->GPIO(14, 1); Sleep(9900); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Robot->GPIO(14, 0); break; case 2: // if the current LED sequence == condition 2.3 str.Format(_T("\n\nLED condition 2.3")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); Sleep(1000); Robot->GPIO(14, 1); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Sleep(9900); Robot->GPIO(14, 0); break; } Robot->MoveTo_Actual_Point(locations[2].x, locations[2].y, locations[2].z, locations[2].rotatex, locations[2].rotatey); current_trial_counter++; } else if (condition_type == 4) { switch (current_trial[current_trial_counter] + 1) { case 1: Robot->MoveTo_Actual_Point(locations[0].x, locations[0].y, locations[0].z, locations[0].rotatex, locations[0].rotatey); break; case 2: Robot->MoveTo_Actual_Point(locations[1].x, locations[1].y, locations[1].z, locations[1].rotatex, locations[1].rotatey); break; } switch (current_leds[current_trial_counter] + 1) { case 1: // if the current LED sequence == #1 str.Format(_T("\n\nLED condition 2.1")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); Sleep(1000); Robot->GPIO(14, 1); Sleep(9900); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Robot->GPIO(14, 0); break; case 2: // if the current LED sequence == #2 str.Format(_T("\n\nLED condition 2.2")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); Sleep(1000); Robot->GPIO(14, 1); Sleep(4900); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Sleep(5000); Robot->GPIO(14, 0); break; case 3: // if the current LED sequence == #3 str.Format(_T("\n\nLED condition 2.3")); tempstr += str; SetDlgItemText(IDC_STATIC2, tempstr ); Sleep(1000); Robot->GPIO(14, 1); Robot->GPIO(15, 1); Sleep(100); Robot->GPIO(15, 0); Sleep(9900); Robot->GPIO(14, 0); break; } Robot->MoveTo_Actual_Point(locations[2].x, locations[2].y, locations[2].z, locations[2].rotatex, locations[2].rotatey); current_trial_counter++; } if(current_trial_counter>=MAXTRIALS){ AfxMessageBox(_T("Done with this trial condition"), MB_OK, -1); radbut1.EnableWindow( true ); radbut2.EnableWindow( true ); radbut3.EnableWindow( true ); current_trial_counter = 1; } /*turn on 'Stop Recording'*/ //pbutton = GetDlgItem( IDC_BUTTON3); //pbutton->EnableWindow(true); //} /******** Stop Trial ************/ //void CRobot_ReachingDlg::OnBnClickedButton3() //{ //pdi.ClearBuffer(); //clear buffer to start from new time //flag = true; //set flag for no recording //Sleep(500); //sleep for 100 ms so that all IO is done before closing the file fp.Flush(); //flush just in case:-) fp.Close(); //close old file Sleep(500); //sleep for 100 ms so that all IO is done before closing the file //pdi.ClearBuffer(); //clear buffer to start from new time CString endstr(""); endstr.Format(_T("Stopped recording trial #%d / %d"),current_trial_counter, trialNum[condition_type - 1] ); SetDlgItemText(IDC_STATIC2, endstr); /*turn on "Next Trial" and "redo trial", turn off "Stop Recording" button*/ pbutton= GetDlgItem( IDC_BUTTON1); pbutton->EnableWindow(true); pbutton->SetFocus(); pbutton = GetDlgItem( IDC_BUTTON3); pbutton->EnableWindow(false); pbutton = GetDlgItem( IDC_BUTTON4); pbutton->EnableWindow(true); } /*********** Initialize ****************/ void CRobot_ReachingDlg::OnBnClickedButton2() { /*check for condition*/ if( radbut1.GetCheck() == BST_CHECKED) condition_type = 1; else if( radbut2.GetCheck() == BST_CHECKED) condition_type = 2; else if (radbut3.GetCheck() == BST_CHECKED) condition_type = 3; else if (radbut4.GetCheck() == BST_CHECKED) condition_type = 4; radbut1.EnableWindow( false ); radbut2.EnableWindow( false ); radbut3.EnableWindow( false ); radbut4.EnableWindow( false ); /*copy name of subject*/ CWnd * pitem = GetDlgItem( IDC_EDIT1); str =""; GetDlgItemTextW(IDC_EDIT1, name); if( name.IsEmpty() ){ AfxMessageBox(_T("Enter the subject name!"), MB_OK, -1); return; } /*CString ctype(""); CString folderName(""); GetDlgItemTextW(IDC_COMBO1, ctype); CreateDirectory( ctype, NULL ); folderName.Format( _T("%s\\%s"), ctype, name); CreateDirectory( folderName, NULL ); folderName.Format( _T("%s\\%s\\condition%d"), ctype, name,condition_type, name, condition_type, current_trial_counter); */ HANDLE hDir = NULL; //hDir = CreateFile ( folderName, GENERIC_READ, hDir = CreateFile ( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); /*if folder exists*/ if( hDir != INVALID_HANDLE_VALUE ){ if( IDNO == AfxMessageBox(_T ("Folder exists!Do you want to overwrite files?"), MB_YESNO, -1)){ return;} } /* initialize Lua */ L = lua_open(); /* load Lua base libraries */ luaL_openlibs(L); /* run the script */ luaL_dofile(L, ".//config.lua"); /* Read the number of images */ int luaInd = 888; luaInd = lua_intexpr( L, "#config.eventType", &eventCount ) ; for (int i=0; i<eventCount; ++i ) { char expr[64] = "" ; sprintf( expr, "config.eventTime[%d]", i+1 ); lua_numberexpr( L, expr, &eventTime[i] ); sprintf( expr, "config.eventType[%d]", i+1 ); lua_intexpr( L, expr, &eventType[i] ); sprintf( expr, "config.eventPara[%d]", i+1 ); lua_intexpr( L, expr, &eventPara[i] ); } lua_intexpr( L, "config.trialNum", &trialNum[condition_type - 1] ); lua_intexpr( L, "config.withinTrialTargetNum", &withinTrialTargetNum ); for (int i = 0; i < trialNum[condition_type - 1]; i++) { for (int j = 0; j < withinTrialTargetNum; j++) { char expr[64] = "" ; sprintf( expr, "config.targetSeq[%d]", i * withinTrialTargetNum + j + 1); lua_intexpr( L, expr, &targetSeq[i][j] ); } } /* cleanup Lua */ lua_close(L); pitem->EnableWindow(false); //CreateDirectory( folderName, NULL ); CreateDirectory( name, NULL ); //name = folderName; str.Format( _T("%s\\%s_cond_%d_%d_%d_%d.dat"), name, name, condition_type, current_trial_counter, current_trial[current_trial_counter], repetitions[current_trial[current_trial_counter]]); SetDlgItemText(IDC_EDIT1, str ); /*turn on "Next Trial", turn off "Init Robot" button*/ CWnd * pbutton = GetDlgItem( IDC_BUTTON2); pbutton->EnableWindow(false); //initialized = true; //set flag if connected to tracker CString tempstr,str(""); tempstr.Format(_T("eventCount = %d\n"), eventCount); // tempstr.Format(_T("config.targetSeq[%d][%d] = %d\n"), 0, 1, targetSeq[0][1]); tempstr = _T("=>Time of events = ") + tempstr + _T("\n\n=>Connecting to the Robot...\n"); SetDlgItemText(IDC_STATIC2, tempstr ); /*Connect to robot*/ Robot = new Robot_Control(); int x = Robot->Initialize(); Initialize_locations(); //Randomize_trials(); RandomizeLeds(); //Robot->Ready(); //move robot into Ready position /*move to initial position*/ Robot->MoveTo_Actual_Point(locations[12].x, locations[12].y, locations[12].z, locations[12].rotatex, locations[12].rotatey); tempstr += "Connected to the Robot...\n"; SetDlgItemText(IDC_STATIC2, tempstr ); tempstr += "=>Connecting to the tracker...\n"; SetDlgItemText(IDC_STATIC2, tempstr ); //pdi.Connect(); //connect to the device //str.Format( _T("Connected to the tracker...\nTrial #%d\n"),current_trial_counter); //tempstr += str; //SetDlgItemText(IDC_STATIC2, tempstr ); CString tempstr1(""), tstr(""); tempstr1.Format(_T("Trial #%d / %d \nMoving to: location #%d:\n x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f"), current_trial_counter+1, trialNum[condition_type - 1], current_trial[current_trial_counter]+1, locations[current_trial[current_trial_counter]].x, locations[current_trial[current_trial_counter]].y, locations[current_trial[current_trial_counter]].z, locations[current_trial[current_trial_counter]].rotatex, locations[current_trial[current_trial_counter]].rotatey); tstr += tempstr1; tempstr1.Format(_T("\nSafe: \nMoving to: x:%.2f, y:%.2f, z:%.2f, xrot:%.2f, yrot:%.2f"), locations[12].x, locations[12].y, locations[12].z, locations[12].rotatex, locations[12].rotatey); tstr += tempstr1; SetDlgItemText(IDC_STATIC2, tstr ); //pdi.StartCapture( BUFFER, BUFFER_SIZE); //initialize data buffer, ready to record data //pdi.ClearBuffer(); //buffer goes back to the beginning //sensors = pdi.GetSennum(); //get number of connected sensors /* pfin = pdi.GetCurBuf(); pdi.GetCurFrmTim( pfin, 1, &newTime ); for(int i=0;i<sensors;i++){ pdi.GetCurData( pfin, i, curData ); for(int j=0;j<DATA_LENGTH;j++){ data[i].push_back(curData[j]); } } */ /*turn on "Next Trial", turn off "Init Robot" button*/ pbutton = GetDlgItem( IDC_BUTTON1); pbutton->EnableWindow(true); } void CRobot_ReachingDlg::OnDestroy() { /*release control and lock axes*/ if( Robot ){ delete Robot; } /* if ( initialized ){ //if user stoped recording => she was recording:-) pdi.ClearBuffer(); //clear buffer to start from new time pdi.StopCapture(); pdi.Disconnect(); } */ CDialog::OnDestroy(); // TODO: Add your message handler code here } /******* Redo Trial ****************/ void CRobot_ReachingDlg::OnBnClickedButton4() { CString tstr(""); current_trial_counter--; //dec counter repetitions[current_trial[current_trial_counter]]--; if (current_trial_counter < 0){ current_trial_counter = 0; } tstr.Format( _T("%s\\%s_cond_%d_%d_%d_%d_bad.dat"), name, name, condition_type, current_trial_counter+1, current_trial[current_trial_counter]+1, repetitions[current_trial[current_trial_counter]]); str.Format( _T("%s\\%s_cond_%d_%d_%d_%d.dat"), name, name, condition_type, current_trial_counter+1, current_trial[current_trial_counter]+1, repetitions[current_trial[current_trial_counter]]); CWnd* pbutton = GetDlgItem( IDC_BUTTON4); pbutton->EnableWindow(false); try { CFile::Rename( str, tstr ); ::AfxMessageBox( _T("Push \"Start recording\" to re-record trial"), 0, 0 ); //CWnd* pbutton = GetDlgItem( IDC_BUTTON4); //pbutton->EnableWindow(false); } catch(CFileException* pEx ){ ::AfxMessageBox( _T("Unable to redo the last trial. "), 0, 0 ); current_trial_counter++; //inc counter repetitions[current_trial[current_trial_counter]]++; return; } SetDlgItemText(IDC_EDIT1, str ); Sleep(100); //give some time to copy file }
[ "devnull@localhost" ]
[ [ [ 1, 1186 ] ] ]
ece4fcc5b8ec34b82bdae048e94f37054854f9e1
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/physics/physics.cpp
c52ed494fff154985ebda8697fefe9b9ee3623d5
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
11,608
cpp
#include "precompiled.h" #include "physics/physics.h" #include "physics/jsphysics.h" #include "physics/cook.h" #include "settings/settings.h" #include "timer/timer.h" #include "render/render.h" #include "render/shapes.h" #include "entity/interfaces.h" #include "physics/xmlloader.h" #include <NxPhysics.h> #include <NxCooking.h> #include <NxCharacter.h> #include <NxControllerManager.h> #include "component/component.h" #include "component/actorcomponent.h" #include "entity/entity.h" #define NX_DBG_EVENTGROUP_MYOBJECTS 0x00100000 #define NX_DBG_EVENTMASK_MYOBJECTS 0x00100000 namespace physics { namespace details { class PhysicsOutputStream : public NxUserOutputStream { void reportError(NxErrorCode code, const char* message, const char* file, int line) { ERROR("ERROR %d: \"%s\" (%s:%d)", code, message, file, line); } NxAssertResponse reportAssertViolation(const char *message, const char *file, int line) { ERROR("ASSERT \"%s\" (%s:%d)", message, file, line); return NX_AR_CONTINUE; } void print(const char* message) { LOG("\"%s\"", message); } }; class PhysicsAllocator : public NxUserAllocator { void* mallocDEBUG(size_t size, const char* fileName, int line) { return malloc(size); } void* malloc(size_t size) { return ::malloc(size); } void* realloc(void* memory, size_t size) { return ::realloc(memory, size); } void free(void* memory) { ::free(memory); } }; } // these classes have to exist during global destruction, hence the 'leak' details::PhysicsOutputStream* g_physicsOutput = new details::PhysicsOutputStream(); details::PhysicsAllocator* g_physicsAllocator = new details::PhysicsAllocator(); // initialize statics int PhysicsManager::s_attachDebugger = 1; int PhysicsManager::s_useHardwarePhysics = 1; float PhysicsManager::s_gravity = -9.8f; float PhysicsManager::s_maxTimestep = 1.0f / 60.0f; int PhysicsManager::s_maxIterations = 16; int PhysicsManager::s_renderDebug = 0; } using namespace physics; REGISTER_STARTUP_FUNCTION(physics, PhysicsManager::InitSettings, 10); void PhysicsManager::InitSettings() { settings::addsetting("system.physics.attach_debug", settings::TYPE_INT, 0, NULL, NULL, &PhysicsManager::s_attachDebugger); settings::addsetting("system.physics.render_debug", settings::TYPE_INT, 0, NULL, NULL, &PhysicsManager::s_renderDebug); settings::addsetting("system.physics.gravity", settings::TYPE_FLOAT, 0, NULL, NULL, &PhysicsManager::s_gravity); settings::addsetting("system.physics.s_maxTimestep", settings::TYPE_FLOAT, 0, NULL, NULL, &PhysicsManager::s_maxTimestep); settings::addsetting("system.physics.s_maxIterations", settings::TYPE_INT, 0, NULL, NULL, &PhysicsManager::s_maxIterations); settings::addsetting("system.physics.use_hw", settings::TYPE_INT, 0, NULL, NULL, &PhysicsManager::s_useHardwarePhysics); } void NxMat34ToD3DXMatrix( const NxMat34* in, D3DXMATRIX* out ) { in->getColumnMajor44((NxF32*)out); } void D3DXMatrixToNxMat34(const D3DXMATRIX* in, NxMat34* out) { out->setColumnMajor44((NxF32*)in); } PhysicsManager::PhysicsManager(scene::Scene *scene) : m_scene(scene), m_physicsSDK(NULL), m_physicsScene(NULL) { NxSDKCreateError errorCode; m_physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, g_physicsOutput, NxPhysicsSDKDesc(), &errorCode); if (!m_physicsSDK) { LOG("ERROR: failed to initialize physics sdk: error code %i", errorCode); return; } else LOG("physics initialized"); if (s_attachDebugger) { m_debugger = m_physicsSDK->getFoundationSDK().getRemoteDebugger(); m_debugger->connect("localhost"); if (!m_debugger->isConnected()) LOG("WARNING: debugger failed to attach"); NX_DBG_CREATE_OBJECT(m_scene, NX_DBG_OBJECTTYPE_CAMERA, "Player", NX_DBG_EVENTGROUP_MYOBJECTS); NX_DBG_CREATE_PARAMETER(NxVec3(render::cam_pos.x, render::cam_pos.y, render::cam_pos.z), m_scene, "Origin", NX_DBG_EVENTGROUP_MYOBJECTS); NX_DBG_CREATE_PARAMETER(NxVec3(0, 0, 0), m_scene, "Target", NX_DBG_EVENTGROUP_MYOBJECTS); //NX_DBG_CREATE_PARAMETER(NxVec3(0, 1, 0), render::scene, "Up", NX_DBG_EVENTGROUP_MYOBJECTS); } m_cookingInterface = NxGetCookingLib(NX_PHYSICS_SDK_VERSION); m_cookingInterface->NxInitCooking(NULL, g_physicsOutput); m_physicsSDK->setParameter(NX_SKIN_WIDTH, 0.0005f); //bool ccdEnabled = 1; //gPhysicsSDK->setParameter(NX_CONTINUOUS_CD, ccdEnabled); //gPhysicsSDK->setParameter(NX_CCD_EPSILON, 0.01f); //gPhysicsSDK->setParameter(NX_DEFAULT_SLEEP_LIN_VEL_SQUARED, 0.15*0.15*SCALE*SCALE); //gPhysicsSDK->setParameter(NX_BOUNCE_THRESHOLD, -2*SCALE); //gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 0.5*SCALE); NxSceneDesc sceneDesc; NxVec3 gDefaultGravity(0, s_gravity, 0); sceneDesc.gravity = gDefaultGravity; if(s_useHardwarePhysics && m_physicsSDK->getHWVersion() != NX_HW_VERSION_NONE) { sceneDesc.simType = NX_SIMULATION_HW; LOG("using hardware physics"); } //sceneDesc.upAxis = 1; //sceneDesc.maxBounds->min.x = render::scene-> m_physicsScene = m_physicsSDK->createScene(sceneDesc); m_physicsScene->setTiming(s_maxTimestep, s_maxIterations); // set the contact reporter for collisions m_physicsScene->setUserContactReport(this); // Create the default material NxMaterial* defaultMaterial = m_physicsScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create a bouncy material for spheres NxMaterial* bouncyMaterial = m_physicsScene->getMaterialFromIndex(1); defaultMaterial->setRestitution(0.75f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); m_controllerManager = NxCreateControllerManager(g_physicsAllocator); startSimulation(); // prime the pump getResults(); m_scriptObject = createScriptObject(); // create the script object } PhysicsManager::~PhysicsManager() { m_cookingInterface->NxCloseCooking(); NxReleaseControllerManager(m_controllerManager); m_physicsSDK->release(); if(m_scriptObject) destroyScriptObject(); } void PhysicsManager::startSimulation() { ASSERT(m_physicsSDK && m_physicsScene); m_physicsScene->simulate(timer::delta_s); m_physicsScene->flushStream(); if (NX_DBG_IS_CONNECTED()) { D3DXVECTOR3 campos = render::cam_pos + render::cam_offset; NX_DBG_SET_PARAMETER((NxVec3)campos, m_scene, "Origin", NX_DBG_EVENTGROUP_MYOBJECTS); D3DXMATRIX mat; D3DXMatrixRotationYawPitchRoll(&mat, D3DXToRadian(render::cam_rot.y), D3DXToRadian(render::cam_rot.x), D3DXToRadian(render::cam_rot.z)); D3DXVECTOR3 lookat; D3DXVec3TransformCoord(&lookat, &D3DXVECTOR3(0, 0, 10), &mat); lookat += render::cam_pos + render::cam_offset; NX_DBG_SET_PARAMETER((NxVec3)lookat, m_scene, "Target", NX_DBG_EVENTGROUP_MYOBJECTS); NX_DBG_FLUSH(); NX_DBG_FRAME_BREAK(); } } void PhysicsManager::getResults() { ASSERT(m_physicsSDK && m_physicsScene); m_physicsScene->fetchResults(NX_ALL_FINISHED, true); if (s_renderDebug) { m_debugRenderable = m_physicsScene->getDebugRenderable(); } else m_debugRenderable = NULL; // handle any buffered contact callbacks for(vector<pair<weak_reference<component::ActorComponent>, component::ContactCallbackEventArgs>>::iterator it = m_contactBuffer.begin(); it != m_contactBuffer.end(); it++) if(it->first) it->first->contactCallback->onContact((*it).first.get(), (*it).second); m_contactBuffer.clear(); } void PhysicsManager::setGravity(float value) { s_gravity = value; if (m_physicsScene) { m_physicsScene->setGravity(NxVec3(0, value, 0)); for (int i = 0; i < m_physicsScene->getNbActors(); i++) if (m_physicsScene->getActors()[i]->isDynamic()) m_physicsScene->getActors()[i]->wakeUp(); } } void PhysicsManager::setTimestep(float value) { s_maxTimestep = value; if (m_physicsScene) m_physicsScene->setTiming(s_maxTimestep, s_maxIterations); } void PhysicsManager::setMaxIter(float value) { s_maxIterations = value; if (m_physicsScene) m_physicsScene->setTiming(s_maxTimestep, s_maxIterations); } void PhysicsManager::setParameter(int parameter, float value) { m_physicsSDK->setParameter((NxParameter)parameter, value); } void PhysicsManager::setGroupCollisionFlag(int group1, int group2, bool enable) { m_physicsScene->setGroupCollisionFlag(group1, group2, enable); } vector<component::Component*> PhysicsManager::getActorsInSphere(D3DXVECTOR3 origin, float radius) { NxShape* shapes[1000]; NxSphere sphere((NxVec3)origin, radius); int shapecount = m_physicsScene->overlapSphereShapes(sphere, NX_DYNAMIC_SHAPES, 1000, &shapes[0], NULL); vector<component::Component*> actors; for(int i = 0; i < shapecount; i++) { component::Component* c = (component::Component*)(shapes[i]->getActor().userData); if(c) actors.push_back(c); } return actors; } component::Component* PhysicsManager::getFirstActorInRay(D3DXVECTOR3 origin, D3DXVECTOR3 direction, float distance) { NxRay ray((NxVec3)origin, (NxVec3)direction); NxRaycastHit hit; NxShape* shape = m_physicsScene->raycastClosestShape(ray, NX_ALL_SHAPES, hit); if(shape && hit.distance <= distance) { component::Component* c; NxActor& actor = shape->getActor(); c = (component::Component*)actor.userData; return c ? c : NULL; } return NULL; } void PhysicsManager::renderDebugView() { if (!m_debugRenderable || !s_renderDebug) return; NxU32 NbLines = m_debugRenderable->getNbLines(); const NxDebugLine* Lines = m_debugRenderable->getLines(); vector<render::LineVertex> verts; verts.reserve(NbLines * 2); while (NbLines--) { verts.push_back(render::LineVertex(Lines->p0.x, Lines->p0.y, Lines->p0.z, Lines->color)); verts.push_back(render::LineVertex(Lines->p1.x, Lines->p1.y, Lines->p1.z, Lines->color)); Lines++; } if(!verts.empty()) render::drawLineSegments(&verts.front(), verts.size() / 2); } ShapeEntry PhysicsManager::getShapeEntry(const string& name) { ShapeMap::iterator it = m_shapeCache.find(name); if (it == m_shapeCache.end()) { ShapeEntry entry = loadDynamicsXML(name); if(!entry) { INFO("ERROR: unable to load shape data from %s", name.c_str()); return entry; } m_shapeCache[name] = entry; return entry; } return it->second; } void PhysicsManager::onContactNotify(NxContactPair& pair, NxU32 events) { component::Component* component1 = (component::Component*)pair.actors[0]->userData; component::Component* component2 = (component::Component*)pair.actors[1]->userData; component::ActorComponent* ac; if(component1 && (ac = dynamic_cast<component::ActorComponent*>(component1)) && ac->contactCallback) m_contactBuffer.push_back(make_pair(ac, component::ContactCallbackEventArgs(component2, *((D3DXVECTOR3*)&pair.sumNormalForce)))); if(component2 && (ac = dynamic_cast<component::ActorComponent*>(component2)) && ac->contactCallback) m_contactBuffer.push_back(make_pair(ac, component::ContactCallbackEventArgs(component1, *((D3DXVECTOR3*)&pair.sumNormalForce)))); } JSObject* PhysicsManager::createScriptObject() { return jsphysics::CreatePhysicsManagerObject(this); } void PhysicsManager::destroyScriptObject() { jsphysics::DestroyPhysicsManagerObject(this); m_scriptObject = NULL; }
[ "tstivers@localhost", "[email protected]" ]
[ [ [ 1, 2 ], [ 5, 8 ], [ 11, 14 ], [ 18, 23 ], [ 28, 28 ], [ 33, 33 ], [ 39, 39 ], [ 44, 44 ], [ 46, 46 ], [ 48, 48 ], [ 81, 82 ], [ 84, 84 ], [ 86, 86 ], [ 93, 94 ], [ 96, 96 ], [ 98, 99 ], [ 101, 101 ], [ 104, 104 ], [ 112, 112 ], [ 114, 116 ], [ 118, 118 ], [ 120, 120 ], [ 124, 125 ], [ 129, 131 ], [ 134, 134 ], [ 136, 143 ], [ 145, 145 ], [ 151, 152 ], [ 155, 155 ], [ 159, 159 ], [ 161, 165 ], [ 167, 170 ], [ 172, 173 ], [ 177, 178 ], [ 190, 190 ], [ 192, 192 ], [ 195, 198 ], [ 200, 204 ], [ 206, 210 ], [ 212, 212 ], [ 216, 216 ], [ 218, 218 ], [ 220, 221 ], [ 242, 243 ], [ 252, 252 ], [ 256, 257 ], [ 259, 259 ], [ 261, 262 ], [ 264, 264 ], [ 266, 267 ], [ 269, 269 ], [ 284, 285 ], [ 301, 301 ], [ 303, 303 ], [ 305, 306 ], [ 312, 312 ], [ 329, 329 ], [ 332, 333 ], [ 336, 336 ], [ 339, 339 ] ], [ [ 3, 4 ], [ 9, 10 ], [ 15, 17 ], [ 24, 27 ], [ 29, 32 ], [ 34, 38 ], [ 40, 43 ], [ 45, 45 ], [ 47, 47 ], [ 49, 80 ], [ 83, 83 ], [ 85, 85 ], [ 87, 92 ], [ 95, 95 ], [ 97, 97 ], [ 100, 100 ], [ 102, 103 ], [ 105, 111 ], [ 113, 113 ], [ 117, 117 ], [ 119, 119 ], [ 121, 123 ], [ 126, 128 ], [ 132, 133 ], [ 135, 135 ], [ 144, 144 ], [ 146, 150 ], [ 153, 154 ], [ 156, 158 ], [ 160, 160 ], [ 166, 166 ], [ 171, 171 ], [ 174, 176 ], [ 179, 189 ], [ 191, 191 ], [ 193, 194 ], [ 199, 199 ], [ 205, 205 ], [ 211, 211 ], [ 213, 215 ], [ 217, 217 ], [ 219, 219 ], [ 222, 241 ], [ 244, 251 ], [ 253, 255 ], [ 258, 258 ], [ 260, 260 ], [ 263, 263 ], [ 265, 265 ], [ 268, 268 ], [ 270, 283 ], [ 286, 300 ], [ 302, 302 ], [ 304, 304 ], [ 307, 311 ], [ 313, 328 ], [ 330, 331 ], [ 334, 335 ], [ 337, 338 ], [ 340, 364 ] ] ]
974785088f3e8423cbf0e9c9e3bde70769fb7f1a
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Mac OS X/include/idk_ut_TCollection.h
d86f72bebd096c19550e8813a13212b60701c1d5
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
6,483
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: idk_ut_TCollection.h,v 1.4 2003/06/02 08:03:41 tomoto Exp $ */ #ifndef _IDK_UT_TCOLLECTION_H_ #define _IDK_UT_TCOLLECTION_H_ #include <idk_ut_Types.h> #include <idk_ut_TVectorUtil.h> /** @file The definition of idk_ut_TConstCollection, idk_ut_TCollection, idk_ut_TArrayCollection, idk_ut_TConstArrayCollection. */ /** Provides an abstract collection of const pointer. @param T Type of the pointed object. @see idk_ut_TArrayCollection, idk_ut_TConstArrayCollection */ template<class T> class IDK_DECL idk_ut_TConstCollection : public idk_ut_RealObject { public: /** Smartpointer type to this class */ typedef idk_ut_TSharedPtr<idk_ut_TConstCollection<T> > Ptr; /** Const pointer type to T */ typedef const T* ConstObjectType; protected: idk_ut_TConstCollection() {} public: ~idk_ut_TConstCollection() {} /** Returns the size of the collection */ virtual int size() const = 0; /** Returns the <i>i</i>th item of the collection. @return Const pointer to T which points to the <i>i</i>th item. */ virtual ConstObjectType get(int i) const = 0; }; /** Provides an abstract collection of mutable pointer. <p>Note that this class can be casted to idk_ut_TConstCollection<T> also. @param T Type of the pointed object. @see idk_ut_TArrayCollection */ template<class T> class IDK_DECL idk_ut_TCollection : public idk_ut_TConstCollection<T> { public: /** Smartpointer type to this class */ typedef idk_ut_TSharedPtr<idk_ut_TCollection<T> > Ptr; /** Mutable pointer type to T */ typedef T* ObjectType; /** Const pointer type to T (declared in the parent class)*/ typedef typename idk_ut_TConstCollection<T>::ConstObjectType ConstObjectType; protected: idk_ut_TCollection() {} public: ~idk_ut_TCollection() {} virtual ConstObjectType get(int i) const = 0; // actually this method is declared in the parent class, but // VC++ reported compilation error without declaring here... /** Returns the <i>i</i>th item of the collection. @return Mutable pointer to T which points to the <i>i</i>th item. */ virtual ObjectType get(int i) = 0; }; /** Implementation of a collection using an array. <p>There are cases where this class is more useful than STL's vector. Since this class is reference-semantics, you can write natural code to share a collection among pointers or to transfer the ownership of a collection. Also, you can share a collection hiding the implementation details. The example below shows how to share a collection of smartpointers as if it is that of simple pointers. <p>Example: <pre> class MyClass { private: // A collection of MyChildPtr. However, on the abstract interface, // the element is seen as MyChild*. idk_ut_TArrayCollection<MyChild, MyChildPtr> m_childrenPtr; public: MyClass() { m_childrenPtr = new idk_ut_TArrayCollection<MyChild, MyChildPtr>(); m_childrenPtr->add(new MyChild(...)); m_childrenPtr->add(new MyChild(...)); ... } idk_ut_TConstCollection<MyChild>* getChildren() const { // although the collection is actually that of the smartpointer, // it naturally can be casted to that of const pointer. return m_childrenPtr; } idk_ut_TCollection<MyChild>* getChildren() { // although the collection is actually that of the smartpointer, // it naturally can be casted to that of mutable pointer. return m_childrenPtr; } }; </pre> @param T Type of the pointed object on the abstract interface. @param VT Actual type of the element of the array. This should be either smartpointer or mutable pointer type to T. @todo More operations (e.g. remove) may be helpful. */ template<class T, class VT> class IDK_DECL idk_ut_TArrayCollection : public idk_ut_TCollection<T> { public: /** Smartpointer to this class. */ typedef idk_ut_TSharedPtr<idk_ut_TArrayCollection<T, VT> > Ptr; /** Actual type of the element of the array. */ typedef VT HeldValueType; /** Const pointer type to T (declared in the parent class) */ typedef typename idk_ut_TConstCollection<T>::ConstObjectType ConstObjectType; /** Mutable pointer type to T (declared in the parent class) */ typedef typename idk_ut_TCollection<T>::ObjectType ObjectType; private: IDK_UT_VECTOR(HeldValueType) m_values; public: ~idk_ut_TArrayCollection() {} /** Creates an object. */ idk_ut_TArrayCollection() {} int size() const { return m_values.size(); } ConstObjectType get(int i) const { return (ConstObjectType)m_values[i]; } ObjectType get(int i) { return (ObjectType)m_values[i]; } /** Provides direct access to the array element. @return Mutable reference to the <i>i</i>th item. */ HeldValueType& getRaw(int i) { return m_values[i]; } /** Adds an element to the collection. */ void add(const HeldValueType& value) { idk_ut_TVectorUtil<HeldValueType>::growCapacity(&m_values); m_values.push_back(value); } /** Clears the collection. */ void clear() { m_values.clear(); } }; /** Implementation of a collection using an array, which allows only const access. This class can be used when you have only const pointers of aggregated objects. @param T Type of the pointed object. */ template<class T> class IDK_DECL idk_ut_TConstArrayCollection : public idk_ut_TConstCollection<T> { public: /** Smartpointer to this class. */ typedef idk_ut_TSharedPtr<idk_ut_TConstArrayCollection<T> > Ptr; /** Const pointer type to T (declared in the parent class)*/ typedef typename idk_ut_TConstCollection<T>::ConstObjectType ConstObjectType; private: IDK_UT_VECTOR(ConstObjectType) m_values; public: ~idk_ut_TConstArrayCollection() {} /** Creates an object. */ idk_ut_TConstArrayCollection() {} int size() const { return m_values.size(); } ConstObjectType get(int i) const { return m_values[i]; } /** Adds an element to the collection. */ void add(const ConstObjectType& value) { idk_ut_TVectorUtil<ConstObjectType>::growCapacity(&m_values); m_values.push_back(value); } }; #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 222 ] ] ]
abfdcd84f30be42f58d307938df9253374d6eafb
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/shared/so2/weapon_ak47.cpp
ba2c074efab8bc8b2dcc183482ecad4330cae937
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
UTF-8
C++
false
false
2,177
cpp
#include "cbase.h" #include "weapon_sobase_machinegun.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef CLIENT_DLL #define CWeaponAK47 C_WeaponAK47 #endif class CWeaponAK47 : public CSOMachineGun { public: DECLARE_CLASS( CWeaponAK47, CSOMachineGun ); CWeaponAK47(); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); void AddViewKick( void ); int GetMinBurst( void ) { return 1; } int GetMaxBurst( void ) { return 1; } float GetFireRate( void ) { return 0.1f; } // 10Hz Activity GetPrimaryAttackActivity( void ); virtual const Vector& GetBulletSpread( void ) { static Vector cone; cone = VECTOR_CONE_4DEGREES; return cone; } const WeaponProficiencyInfo_t *GetProficiencyValues(); // Add support for CS:S player animations const char *GetWeaponSuffix( void ) { return "AK"; } private: CWeaponAK47( const CWeaponAK47 & ); }; IMPLEMENT_NETWORKCLASS_ALIASED( WeaponAK47, DT_WeaponAK47 ) BEGIN_NETWORK_TABLE( CWeaponAK47, DT_WeaponAK47 ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponAK47 ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( weapon_ak47, CWeaponAK47 ); PRECACHE_WEAPON_REGISTER( weapon_ak47 ); CWeaponAK47::CWeaponAK47() { m_fMinRange1 = 0; // in inches; no minimum range m_fMaxRange1 = 11811; // in inches; about 300 meters } Activity CWeaponAK47::GetPrimaryAttackActivity( void ) { return ACT_VM_PRIMARYATTACK; } void CWeaponAK47::AddViewKick( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) return; #define EASY_DAMPEN 0.5f #define MAX_VERTICAL_KICK 8.0f // in degrees #define SLIDE_LIMIT 0.5f // in seconds DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, m_fFireDuration, SLIDE_LIMIT ); } const WeaponProficiencyInfo_t *CWeaponAK47::GetProficiencyValues() { static WeaponProficiencyInfo_t proficiencyTable[] = { { 7.0, 0.75 }, { 5.00, 0.75 }, { 3.0, 0.85 }, { 5.0/3.0, 0.75 }, { 1.00, 1.0 }, }; COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1 ); return proficiencyTable; }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 94 ] ] ]
75402ddd2d5ac914904397f38e23f83ade8edc48
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/Platforms/MacOS/MacPosixFile.cpp
190cd58a4be824b6b4c858a446c26fb740a93f60
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
4,751
cpp
/* * Copyright 1999-2000,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: MacPosixFile.cpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/Janitor.hpp> #include <limits.h> #include <stdio.h> #include <xercesc/util/Platforms/MacOS/MacPosixFile.hpp> XERCES_CPP_NAMESPACE_BEGIN //---------------------------------------------------------------------------- // XMLMacPosixFile methods //---------------------------------------------------------------------------- XMLMacPosixFile::XMLMacPosixFile() : mFile(NULL) { } XMLMacPosixFile::~XMLMacPosixFile() { if (mFile) close(); } unsigned int XMLMacPosixFile::currPos() { if (!mFile) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); long curPos = ftell(mFile); if (curPos == -1) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetSize); return (unsigned int)curPos; } void XMLMacPosixFile::close() { if (!mFile) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); if (fclose(mFile)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile); mFile = NULL; } unsigned int XMLMacPosixFile::size() { if (mFile == NULL) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); // Get the current position long curPos = ftell(mFile); if (curPos == -1) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos); // Seek to the end and save that value for return if (fseek(mFile, 0, SEEK_END)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotSeekToEnd); long retVal = ftell(mFile); if (retVal == -1) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotSeekToEnd); // And put the pointer back if (fseek(mFile, curPos, SEEK_SET)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotSeekToPos); return (unsigned int)retVal; } bool XMLMacPosixFile::open(const XMLCh* const path, bool toWrite) { if (!path) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); // Transcode the unicode path to UTF8, which is what the Mac posix routines want char tmpPath[kMaxMacStaticPathChars]; std::size_t len = TranscodeUniCharsToUTF8(path, tmpPath, XMLString::stringLen(path), kMaxMacStaticPathChars-1); tmpPath[len] = 0; // Call through to the char version to do the work return open(tmpPath, toWrite); } bool XMLMacPosixFile::open(const char* const path, bool toWrite) { if (!path) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); const char* perms = (toWrite) ? "w" : "r"; mFile = fopen(path, perms); return (mFile != NULL); } unsigned int XMLMacPosixFile::read(const unsigned int byteCount, XMLByte* const buffer) { if (!mFile || !buffer) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); size_t bytesRead = 0; if (byteCount > 0) { bytesRead = fread((void*)buffer, 1, byteCount, mFile); if (ferror(mFile)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile); } return (unsigned int)bytesRead; } void XMLMacPosixFile::write(long byteCount, const XMLByte* buffer) { if (!mFile || !buffer) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); while (byteCount > 0) { size_t bytesWritten = fwrite(buffer, sizeof(XMLByte), byteCount, mFile); if (ferror(mFile)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile); buffer += bytesWritten; byteCount -= bytesWritten; } } void XMLMacPosixFile::reset() { if (!mFile) ThrowXML(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero); // Seek to the start of the file if (fseek(mFile, 0, SEEK_SET)) ThrowXML(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile); } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 184 ] ] ]
b27dde0f5974ac963d89e9a48da53321e908dda7
b86d7c8f28a0c243b4c578821e353d5efcaf81d2
/clearcasehelper/CustomListCtrl/DropWnd.h
b9dfe5abba41cedef20431b1857ff1492e67cb70
[]
no_license
nk39/mototool
dd4998d38348e0e2d010098919f68cf2c982f26a
34a0698fd274ae8b159fc8032f3065877ba2114d
refs/heads/master
2021-01-10T19:26:23.675639
2008-01-04T04:47:54
2008-01-04T04:47:54
34,927,428
1
1
null
null
null
null
UTF-8
C++
false
false
3,760
h
///////////////////////////////////////////////////////////////////////////// // DropWnd.h : header file // // CAdvComboBox Control // Version: 2.1 // Date: September 2002 // Author: Mathias Tunared // Email: [email protected] // Copyright (c) 2002. All Rights Reserved. // // This code, in compiled form or as source code, may be redistributed // unmodified 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. // // 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. // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_DROPWND_H__F873AF0A_BD7D_4B20_BDF6_1EBB973AA348__INCLUDED_) #define AFX_DROPWND_H__F873AF0A_BD7D_4B20_BDF6_1EBB973AA348__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DropWnd.h : header file // #pragma warning( disable : 4251 ) #pragma warning( disable : 4786 ) #include <list> #include <string> using namespace std; typedef struct _LIST_ITEM { string strText; BOOL bDisabled; BOOL bChecked; void* vpItemData; _LIST_ITEM() { strText = ""; bDisabled = FALSE; bChecked = FALSE; vpItemData = NULL; } BOOL operator <(_LIST_ITEM other) { if( strText < other.strText ) return TRUE; else return FALSE; } } LIST_ITEM, *PLIST_ITEM; #include "DropListBox.h" #include "DropScrollBar.h" ///////////////////////////////////////////////////////////////////////////// // CDropWnd window class CDropWnd : public CWnd { // Construction public: CDropWnd( CWnd* pComboParent, list<LIST_ITEM> &itemlist, DWORD dwACBStyle ); // Attributes public: CDropListBox* GetListBoxPtr() { return m_listbox; } CDropScrollBar* GetScrollBarPtr() { return m_scrollbar; } // Operations public: list<LIST_ITEM>& GetList() { return m_list; } // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDropWnd) public: virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); virtual BOOL DestroyWindow(); protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CDropWnd(); // Generated message map functions protected: //{{AFX_MSG(CDropWnd) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnPaint(); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnActivateApp(BOOL bActive, DWORD hTask); //}}AFX_MSG afx_msg LONG OnSetCapture( WPARAM wParam, LPARAM lParam ); afx_msg LONG OnReleaseCapture( WPARAM wParam, LPARAM lParam ); DECLARE_MESSAGE_MAP() private: CDropListBox* m_listbox; CRect m_rcList; CDropScrollBar* m_scrollbar; CRect m_rcScroll; CRect m_rcSizeHandle; CWnd* m_pComboParent; CFont* m_pListFont; list<LIST_ITEM> m_list; list<LIST_ITEM>::iterator m_iter; bool m_bResizing; CPoint m_ptLastResize; int m_nMouseDiffX; int m_nMouseDiffY; DWORD m_dwACBStyle; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DROPWND_H__F873AF0A_BD7D_4B20_BDF6_1EBB973AA348__INCLUDED_)
[ "netnchen@631d5421-cb3f-0410-96e9-8590a48607ad" ]
[ [ [ 1, 138 ] ] ]
2c1e99ba3ea13267582c0a36a089a3bf5f613cec
a4bb94cfe9c0bee937a6ec584e10f6fe126372ff
/Include/Drivers/Video/Console/Console.h
a99b74cf9b77b8ce369f9d01802b52b5adb90318
[]
no_license
MatiasNAmendola/magneto
564d0bdb3534d4b7118e74cc8b50601afaad10a0
33bc34a49a34923908883775f94eb266be5af0f9
refs/heads/master
2020-04-05T23:36:22.535156
2009-07-04T09:14:01
2009-07-04T09:14:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,891
h
/* * Module Name: Console * File: Include\Console\Console.h * */ #include "x86.h" #include "ctype.h" #include "mem.h" #include "defs.h" #include "Drivers\Keyboard\Keyboard.h" #include "iostream.h" #include "Kore\kmsgs.h" #if !defined ( __Console_H_ ) #define __Console_H_ #define TEXT_40x25 425 #define TEXT_40x50 450 #define TEXT_80x25 825 #define TEXT_80x50 850 #define TEXT_90x30 930 #define TEXT_90x60 960 #define MODE_NOT_SUPPORTED 0x1 #define CONSOLE_ALREADY_INITIALIZED 0x2 #define CONSOLE_NOT_INITIALIZED 0x3 #define COLOR_CARD 0x4 #define MONO_CARD 0x5 #define TAB 0x5 #if !defined(COLORS) #define COLORS #define BLACK 0 #define BLUE 1 #define GREEN 2 #define CYAN 3 #define RED 4 #define MAGENTA 5 #define BROWN 6 #define LIGHTGRAY 7 #define DARKGRAY 8 #define LIGHTBLUE 9 #define LIGHTGREEN 10 #define LIGHTCYAN 11 #define PINK 12 #define LIGHTMAGENTA 13 #define YELLOW 14 #define WHITE 15 #endif #define BLINK 0x80 #define VGA_AC_INDEX 0x3C0 #define VGA_AC_WRITE 0x3C0 #define VGA_AC_READ 0x3C1 #define VGA_MISC_WRITE 0x3C2 #define VGA_SEQ_INDEX 0x3C4 #define VGA_SEQ_DATA 0x3C5 #define VGA_DAC_READ_INDEX 0x3C7 #define VGA_DAC_WRITE_INDEX 0x3C8 #define VGA_DAC_DATA 0x3C9 #define VGA_MISC_READ 0x3CC #define VGA_GC_INDEX 0x3CE #define VGA_GC_DATA 0x3CF /* COLOR emulation MONO emulation */ #define VGA_CRTC_INDEX 0x3D4 /* 0x3B4 */ #define VGA_CRTC_DATA 0x3D5 /* 0x3B5 */ #define VGA_INSTAT_READ 0x3DA #define VGA_NUM_SEQ_REGS 5 #define VGA_NUM_CRTC_REGS 25 #define VGA_NUM_GC_REGS 9 #define VGA_NUM_AC_REGS 21 #define VGA_NUM_REGS (1 + VGA_NUM_SEQ_REGS + VGA_NUM_CRTC_REGS + \ VGA_NUM_GC_REGS + VGA_NUM_AC_REGS) extern unsigned char _40x25_text[], _40x50_text[], _80x25_text[], _80x50_text[], _90x30_text[], _90x60_text[], g_8x8_font[2048], g_8x16_font[4096]; extern const char * CONSOLE_ID; class Console { private: static char is_console; static unsigned int last_result; static unsigned char * vid_mem; static unsigned int curr_x, curr_y, c_maxx, c_maxy, textattrib, fgcolor, bgcolor; int detect_card_type(); void update_cursor(); void scroll_line_up(); void write_regs(unsigned char *); public: Console(); ~Console(); int init(); int set_res(unsigned int); void settextbackground(int); void settextcolor(int); void settextattrib(int); int gettextcolor(); int gettextbgcolor(); int gettextattrib(); int wherex(); int wherey(); int getmaxx(); int getmaxy(); void gotoxy(unsigned int, unsigned int); void clrscr(); int writeln(const char *); void putch(const unsigned char); void writeint(const unsigned int); void writeint(const int); }; extern Console console; #endif
[ [ [ 1, 124 ] ] ]
7d717129feb7b485064a40a219edac165552b691
5df145c06c45a6181d7402279aabf7ce9376e75e
/src/boardtabbar.h
af465302758f1cfd31d2abbc365d1f4cf3e5425b
[]
no_license
plus7/openjohn
89318163f42347bbac24e8272081d794449ab861
1ffdcc1ea3f0af43b9033b68e8eca048a229305f
refs/heads/master
2021-03-12T22:55:57.315977
2009-05-15T11:30:00
2009-05-15T11:30:00
152,690
1
1
null
null
null
null
UTF-8
C++
false
false
870
h
#ifndef BOARDTABBAR_H #define BOARDTABBAR_H #include <QTabBar> class QStackedWidget; class BoardView; class QUrl; class ThreadTabBar; class BoardTabBar : public QTabBar { Q_OBJECT public: BoardTabBar(); void setStackedWidget(QStackedWidget *widget); void setThreadTabBar(ThreadTabBar *tabbar); int addTab(const QString& text, BoardView* bv); int addTab(const QString& text, const QUrl& url); int insertTab(int index, const QString& text, BoardView* bv); int insertTab(int index, const QString& text, const QUrl& url); public slots: void openBoard(const QUrl& url); //void tabChanged(const QUrl& url); private: QStackedWidget *m_sw; ThreadTabBar *m_thtab; }; #endif // BOARDTABBAR_H
[ [ [ 1, 35 ] ] ]
95481e2c9401e0291e10b5be76a9262cb256fdb6
d113c82a1659efa5a3dca516f9bcf011a45653d5
/Box2D/Dynamics/b2World.cpp
0dc2c5b01e3d4e08eb082d32f1bdcae99fa3e279
[]
no_license
FrancisVarga/wck
fd2bd3508749484315ea4d9407018164e8183089
0a5b1c946f690111d6c28adfb8f5b21480ffc363
refs/heads/master
2021-01-17T15:55:25.114003
2010-05-17T00:54:18
2010-05-17T00:54:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,027
cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.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. */ #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2Island.h> #include <Box2D/Dynamics/Joints/b2PulleyJoint.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2BroadPhase.h> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <new> b2World::b2World(const b2Vec2& gravity, bool doSleep) { m_destructionListener = NULL; m_debugDraw = NULL; m_bodyList = NULL; m_jointList = NULL; m_bodyCount = 0; m_jointCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_allowSleep = doSleep; m_gravity = gravity; m_flags = 0; m_inv_dt0 = 0.0f; m_contactManager.m_allocator = &m_blockAllocator; } b2World::~b2World() { } void b2World::SetDestructionListener(b2DestructionListener* listener) { m_destructionListener = listener; } void b2World::SetContactFilter(b2ContactFilter* filter) { m_contactManager.m_contactFilter = filter; } void b2World::SetContactListener(b2ContactListener* listener) { m_contactManager.m_contactListener = listener; } void b2World::SetDebugDraw(b2DebugDraw* debugDraw) { m_debugDraw = debugDraw; } b2Body* b2World::CreateBody(const b2BodyDef* def) { b2Assert(IsLocked() == false); if (IsLocked()) { return NULL; } void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); b2Body* b = new (mem) b2Body(def, this); // Add to world doubly linked list. b->m_prev = NULL; b->m_next = m_bodyList; if (m_bodyList) { m_bodyList->m_prev = b; } m_bodyList = b; ++m_bodyCount; return b; } void b2World::DestroyBody(b2Body* b) { b2Assert(m_bodyCount > 0); b2Assert(IsLocked() == false); if (IsLocked()) { return; } // Delete the attached joints. b2JointEdge* je = b->m_jointList; while (je) { b2JointEdge* je0 = je; je = je->next; if (m_destructionListener) { m_destructionListener->SayGoodbye(je0->joint); } DestroyJoint(je0->joint); } b->m_jointList = NULL; // Delete the attached contacts. b2ContactEdge* ce = b->m_contactList; while (ce) { b2ContactEdge* ce0 = ce; ce = ce->next; m_contactManager.Destroy(ce0->contact); } b->m_contactList = NULL; // Delete the attached fixtures. This destroys broad-phase proxies. b2Fixture* f = b->m_fixtureList; while (f) { b2Fixture* f0 = f; f = f->m_next; if (m_destructionListener) { m_destructionListener->SayGoodbye(f0); } f0->DestroyProxy(&m_contactManager.m_broadPhase); f0->Destroy(&m_blockAllocator); f0->~b2Fixture(); m_blockAllocator.Free(f0, sizeof(b2Fixture)); } b->m_fixtureList = NULL; b->m_fixtureCount = 0; // Remove world body list. if (b->m_prev) { b->m_prev->m_next = b->m_next; } if (b->m_next) { b->m_next->m_prev = b->m_prev; } if (b == m_bodyList) { m_bodyList = b->m_next; } --m_bodyCount; b->~b2Body(); m_blockAllocator.Free(b, sizeof(b2Body)); } b2Joint* b2World::CreateJoint(const b2JointDef* def) { b2Assert(IsLocked() == false); if (IsLocked()) { return NULL; } b2Joint* j = b2Joint::Create(def, &m_blockAllocator); // Connect to the world list. j->m_prev = NULL; j->m_next = m_jointList; if (m_jointList) { m_jointList->m_prev = j; } m_jointList = j; ++m_jointCount; // Connect to the bodies' doubly linked lists. j->m_edgeA.joint = j; j->m_edgeA.other = j->m_bodyB; j->m_edgeA.prev = NULL; j->m_edgeA.next = j->m_bodyA->m_jointList; if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; j->m_bodyA->m_jointList = &j->m_edgeA; j->m_edgeB.joint = j; j->m_edgeB.other = j->m_bodyA; j->m_edgeB.prev = NULL; j->m_edgeB.next = j->m_bodyB->m_jointList; if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; j->m_bodyB->m_jointList = &j->m_edgeB; b2Body* bodyA = def->bodyA; b2Body* bodyB = def->bodyB; // If the joint prevents collisions, then flag any contacts for filtering. if (def->collideConnected == false) { b2ContactEdge* edge = bodyB->GetContactList(); while (edge) { if (edge->other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge->contact->FlagForFiltering(); } edge = edge->next; } } // Note: creating a joint doesn't wake the bodies. return j; } void b2World::DestroyJoint(b2Joint* j) { b2Assert(IsLocked() == false); if (IsLocked()) { return; } bool collideConnected = j->m_collideConnected; // Remove from the doubly linked list. if (j->m_prev) { j->m_prev->m_next = j->m_next; } if (j->m_next) { j->m_next->m_prev = j->m_prev; } if (j == m_jointList) { m_jointList = j->m_next; } // Disconnect from island graph. b2Body* bodyA = j->m_bodyA; b2Body* bodyB = j->m_bodyB; // Wake up connected bodies. bodyA->SetAwake(true); bodyB->SetAwake(true); // Remove from body 1. if (j->m_edgeA.prev) { j->m_edgeA.prev->next = j->m_edgeA.next; } if (j->m_edgeA.next) { j->m_edgeA.next->prev = j->m_edgeA.prev; } if (&j->m_edgeA == bodyA->m_jointList) { bodyA->m_jointList = j->m_edgeA.next; } j->m_edgeA.prev = NULL; j->m_edgeA.next = NULL; // Remove from body 2 if (j->m_edgeB.prev) { j->m_edgeB.prev->next = j->m_edgeB.next; } if (j->m_edgeB.next) { j->m_edgeB.next->prev = j->m_edgeB.prev; } if (&j->m_edgeB == bodyB->m_jointList) { bodyB->m_jointList = j->m_edgeB.next; } j->m_edgeB.prev = NULL; j->m_edgeB.next = NULL; b2Joint::Destroy(j, &m_blockAllocator); b2Assert(m_jointCount > 0); --m_jointCount; // If the joint prevents collisions, then flag any contacts for filtering. if (collideConnected == false) { b2ContactEdge* edge = bodyB->GetContactList(); while (edge) { if (edge->other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge->contact->FlagForFiltering(); } edge = edge->next; } } } // Find islands, integrate and solve constraints, solve position constraints void b2World::Solve(const b2TimeStep& step) { // Size the island for the worst case. b2Island island(m_bodyCount, m_contactManager.m_contactCount, m_jointCount, &m_stackAllocator, m_contactManager.m_contactListener); // Clear all the island flags. for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_flags &= ~b2Body::e_islandFlag; } for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { c->m_flags &= ~b2Contact::e_islandFlag; } for (b2Joint* j = m_jointList; j; j = j->m_next) { j->m_islandFlag = false; } // Build and simulate all awake islands. int32 stackSize = m_bodyCount; b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) { if (seed->m_flags & b2Body::e_islandFlag) { continue; } if (seed->IsAwake() == false || seed->IsActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed->GetType() == b2_staticBody) { continue; } // Reset island and stack. island.Clear(); int32 stackCount = 0; stack[stackCount++] = seed; seed->m_flags |= b2Body::e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. b2Body* b = stack[--stackCount]; b2Assert(b->IsActive() == true); island.Add(b); // Make sure the body is awake. if (b->IsAwake() == false) { b->SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b->GetType() == b2_staticBody) { continue; } // Search all contacts connected to this body. for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) { // Has this contact already been added to an island? if (ce->contact->m_flags & b2Contact::e_islandFlag) { continue; } // Is this contact solid and touching? if (ce->contact->IsSensor() == true || ce->contact->IsEnabled() == false || ce->contact->IsTouching() == false) { continue; } island.Add(ce->contact); ce->contact->m_flags |= b2Contact::e_islandFlag; b2Body* other = ce->other; // Was the other body already added to this island? if (other->m_flags & b2Body::e_islandFlag) { continue; } b2Assert(stackCount < stackSize); stack[stackCount++] = other; other->m_flags |= b2Body::e_islandFlag; } // Search all joints connect to this body. for (b2JointEdge* je = b->m_jointList; je; je = je->next) { if (je->joint->m_islandFlag == true) { continue; } b2Body* other = je->other; // Don't simulate joints connected to inactive bodies. if (other->IsActive() == false) { continue; } island.Add(je->joint); je->joint->m_islandFlag = true; if (other->m_flags & b2Body::e_islandFlag) { continue; } b2Assert(stackCount < stackSize); stack[stackCount++] = other; other->m_flags |= b2Body::e_islandFlag; } } island.Solve(step, m_gravity, m_allowSleep); // Post solve cleanup. for (int32 i = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. b2Body* b = island.m_bodies[i]; if (b->GetType() == b2_staticBody) { b->m_flags &= ~b2Body::e_islandFlag; } } } m_stackAllocator.Free(stack); // Synchronize fixtures, check for out of range bodies. for (b2Body* b = m_bodyList; b; b = b->GetNext()) { if (b->IsAwake() == false || b->IsActive() == false) { continue; } if (b->GetType() == b2_staticBody) { continue; } // Update fixtures (for broad-phase). b->SynchronizeFixtures(); } // Look for new contacts. m_contactManager.FindNewContacts(); } // Find TOI contacts and solve them. void b2World::SolveTOI(const b2TimeStep& step) { // Reserve an island and a queue for TOI island solution. b2Island island(m_bodyCount, b2_maxTOIContactsPerIsland, b2_maxTOIJointsPerIsland, &m_stackAllocator, m_contactManager.m_contactListener); //Simple one pass queue //Relies on the fact that we're only making one pass //through and each body can only be pushed/popped once. //To push: // queue[queueStart+queueSize++] = newElement; //To pop: // poppedElement = queue[queueStart++]; // --queueSize; int32 queueCapacity = m_bodyCount; b2Body** queue = (b2Body**)m_stackAllocator.Allocate(queueCapacity* sizeof(b2Body*)); for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_flags &= ~b2Body::e_islandFlag; b->m_sweep.t0 = 0.0f; } for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { // Invalidate TOI c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); } for (b2Joint* j = m_jointList; j; j = j->m_next) { j->m_islandFlag = false; } // Find TOI events and solve them. for (;;) { // Find the first TOI. b2Contact* minContact = NULL; float32 minTOI = 1.0f; for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { // Can this contact generate a solid TOI contact? if (c->IsSensor() == true || c->IsEnabled() == false || c->IsContinuous() == false) { continue; } // TODO_ERIN keep a counter on the contact, only respond to M TOIs per contact. float32 toi = 1.0f; if (c->m_flags & b2Contact::e_toiFlag) { // This contact has a valid cached TOI. toi = c->m_toi; } else { // Compute the TOI for this contact. b2Fixture* s1 = c->GetFixtureA(); b2Fixture* s2 = c->GetFixtureB(); b2Body* b1 = s1->GetBody(); b2Body* b2 = s2->GetBody(); if ((b1->GetType() != b2_dynamicBody || b1->IsAwake() == false) && (b2->GetType() != b2_dynamicBody || b2->IsAwake() == false)) { continue; } // Put the sweeps onto the same time interval. float32 t0 = b1->m_sweep.t0; if (b1->m_sweep.t0 < b2->m_sweep.t0) { t0 = b2->m_sweep.t0; b1->m_sweep.Advance(t0); } else if (b2->m_sweep.t0 < b1->m_sweep.t0) { t0 = b1->m_sweep.t0; b2->m_sweep.Advance(t0); } b2Assert(t0 < 1.0f); // Compute the time of impact. toi = c->ComputeTOI(b1->m_sweep, b2->m_sweep); b2Assert(0.0f <= toi && toi <= 1.0f); // If the TOI is in range ... if (0.0f < toi && toi < 1.0f) { // Interpolate on the actual range. toi = b2Min((1.0f - toi) * t0 + toi, 1.0f); } c->m_toi = toi; c->m_flags |= b2Contact::e_toiFlag; } if (b2_epsilon < toi && toi < minTOI) { // This is the minimum TOI found so far. minContact = c; minTOI = toi; } } if (minContact == NULL || 1.0f - 100.0f * b2_epsilon < minTOI) { // No more TOI events. Done! break; } // Advance the bodies to the TOI. b2Fixture* s1 = minContact->GetFixtureA(); b2Fixture* s2 = minContact->GetFixtureB(); b2Body* b1 = s1->GetBody(); b2Body* b2 = s2->GetBody(); b2Sweep backup1 = b1->m_sweep; b2Sweep backup2 = b2->m_sweep; b1->Advance(minTOI); b2->Advance(minTOI); // The TOI contact likely has some new contact points. minContact->Update(m_contactManager.m_contactListener); minContact->m_flags &= ~b2Contact::e_toiFlag; // Is the contact solid? if (minContact->IsSensor() == true || minContact->IsEnabled() == false) { // Restore the sweeps. b1->m_sweep = backup1; b2->m_sweep = backup2; b1->SynchronizeTransform(); b2->SynchronizeTransform(); continue; } // Did numerical issues prevent a contact point from being generated? if (minContact->IsTouching() == false) { // Give up on this TOI. continue; } // Build the TOI island. We need a dynamic seed. b2Body* seed = b1; if (seed->GetType() != b2_dynamicBody) { seed = b2; } // Reset island and queue. island.Clear(); int32 queueStart = 0; // starting index for queue int32 queueSize = 0; // elements in queue queue[queueStart + queueSize++] = seed; seed->m_flags |= b2Body::e_islandFlag; // Perform a breadth first search (BFS) on the contact/joint graph. while (queueSize > 0) { // Grab the next body off the stack and add it to the island. b2Body* b = queue[queueStart++]; --queueSize; island.Add(b); // Make sure the body is awake. if (b->IsAwake() == false) { b->SetAwake(true); } // To keep islands as small as possible, we don't // propagate islands across static or kinematic bodies. if (b->GetType() != b2_dynamicBody) { continue; } // Search all contacts connected to this body. for (b2ContactEdge* cEdge = b->m_contactList; cEdge; cEdge = cEdge->next) { // Does the TOI island still have space for contacts? if (island.m_contactCount == island.m_contactCapacity) { break; } // Has this contact already been added to an island? if (cEdge->contact->m_flags & b2Contact::e_islandFlag) { continue; } // Skip separate, sensor, or disabled contacts. if (cEdge->contact->IsSensor() == true || cEdge->contact->IsEnabled() == false || cEdge->contact->IsTouching() == false) { continue; } island.Add(cEdge->contact); cEdge->contact->m_flags |= b2Contact::e_islandFlag; // Update other body. b2Body* other = cEdge->other; // Was the other body already added to this island? if (other->m_flags & b2Body::e_islandFlag) { continue; } // Synchronize the connected body. if (other->GetType() != b2_staticBody) { other->Advance(minTOI); other->SetAwake(true); } b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other->m_flags |= b2Body::e_islandFlag; } for (b2JointEdge* jEdge = b->m_jointList; jEdge; jEdge = jEdge->next) { if (island.m_jointCount == island.m_jointCapacity) { continue; } if (jEdge->joint->m_islandFlag == true) { continue; } b2Body* other = jEdge->other; if (other->IsActive() == false) { continue; } island.Add(jEdge->joint); jEdge->joint->m_islandFlag = true; if (other->m_flags & b2Body::e_islandFlag) { continue; } // Synchronize the connected body. if (other->GetType() != b2_staticBody) { other->Advance(minTOI); other->SetAwake(true); } b2Assert(queueStart + queueSize < queueCapacity); queue[queueStart + queueSize] = other; ++queueSize; other->m_flags |= b2Body::e_islandFlag; } } b2TimeStep subStep; subStep.warmStarting = false; subStep.dt = (1.0f - minTOI) * step.dt; subStep.inv_dt = 1.0f / subStep.dt; subStep.dtRatio = 0.0f; subStep.velocityIterations = step.velocityIterations; subStep.positionIterations = step.positionIterations; island.SolveTOI(subStep); // Post solve cleanup. for (int32 i = 0; i < island.m_bodyCount; ++i) { // Allow bodies to participate in future TOI islands. b2Body* b = island.m_bodies[i]; b->m_flags &= ~b2Body::e_islandFlag; if (b->IsAwake() == false) { continue; } if (b->GetType() == b2_staticBody) { continue; } // Update fixtures (for broad-phase). b->SynchronizeFixtures(); // Invalidate all contact TOIs associated with this body. Some of these // may not be in the island because they were not touching. for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) { ce->contact->m_flags &= ~b2Contact::e_toiFlag; } } for (int32 i = 0; i < island.m_contactCount; ++i) { // Allow contacts to participate in future TOI islands. b2Contact* c = island.m_contacts[i]; c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); } for (int32 i = 0; i < island.m_jointCount; ++i) { // Allow joints to participate in future TOI islands. b2Joint* j = island.m_joints[i]; j->m_islandFlag = false; } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.FindNewContacts(); } m_stackAllocator.Free(queue); } void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) { // If new fixtures were added, we need to find the new contacts. if (m_flags & e_newFixture) { m_contactManager.FindNewContacts(); m_flags &= ~e_newFixture; } m_flags |= e_locked; b2TimeStep step; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. This is where some contacts are destroyed. m_contactManager.Collide(); // Integrate velocities, solve velocity constraints, and integrate positions. if (step.dt > 0.0f) { Solve(step); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0f) { SolveTOI(step); } if (step.dt > 0.0f) { m_inv_dt0 = step.inv_dt; } m_flags &= ~e_locked; } void b2World::ClearForces() { for (b2Body* body = m_bodyList; body; body = body->GetNext()) { body->m_force.SetZero(); body->m_torque = 0.0f; } } struct b2WorldQueryWrapper { bool QueryCallback(int32 proxyId) { b2Fixture* fixture = (b2Fixture*)broadPhase->GetUserData(proxyId); return callback->ReportFixture(fixture); } b2BroadPhase* broadPhase; b2QueryCallback* callback; }; void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) { b2WorldQueryWrapper wrapper; wrapper.broadPhase = &m_contactManager.m_broadPhase; wrapper.callback = callback; m_contactManager.m_broadPhase.Query(&wrapper, aabb); } struct b2WorldRayCastWrapper { float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) { void* userData = broadPhase->GetUserData(proxyId); b2Fixture* fixture = (b2Fixture*)userData; b2RayCastOutput output; bool hit = fixture->RayCast(&output, input); if (hit) { float32 fraction = output.fraction; b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; return callback->ReportFixture(fixture, point, output.normal, fraction); } return input.maxFraction; } b2BroadPhase* broadPhase; b2RayCastCallback* callback; }; void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) { b2WorldRayCastWrapper wrapper; wrapper.broadPhase = &m_contactManager.m_broadPhase; wrapper.callback = callback; b2RayCastInput input; input.maxFraction = 1.0f; input.p1 = point1; input.p2 = point2; m_contactManager.m_broadPhase.RayCast(&wrapper, input); } void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) { switch (fixture->GetType()) { case b2Shape::e_circle: { b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); b2Vec2 center = b2Mul(xf, circle->m_p); float32 radius = circle->m_radius; b2Vec2 axis = xf.R.col1; m_debugDraw->DrawSolidCircle(center, radius, axis, color); } break; case b2Shape::e_polygon: { b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); int32 vertexCount = poly->m_vertexCount; b2Assert(vertexCount <= b2_maxPolygonVertices); b2Vec2 vertices[b2_maxPolygonVertices]; for (int32 i = 0; i < vertexCount; ++i) { vertices[i] = b2Mul(xf, poly->m_vertices[i]); } m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); } break; } } void b2World::DrawJoint(b2Joint* joint) { b2Body* b1 = joint->GetBodyA(); b2Body* b2 = joint->GetBodyB(); const b2Transform& xf1 = b1->GetTransform(); const b2Transform& xf2 = b2->GetTransform(); b2Vec2 x1 = xf1.position; b2Vec2 x2 = xf2.position; b2Vec2 p1 = joint->GetAnchorA(); b2Vec2 p2 = joint->GetAnchorB(); b2Color color(0.5f, 0.8f, 0.8f); switch (joint->GetType()) { case e_distanceJoint: m_debugDraw->DrawSegment(p1, p2, color); break; case e_pulleyJoint: { b2PulleyJoint* pulley = (b2PulleyJoint*)joint; b2Vec2 s1 = pulley->GetGroundAnchorA(); b2Vec2 s2 = pulley->GetGroundAnchorB(); m_debugDraw->DrawSegment(s1, p1, color); m_debugDraw->DrawSegment(s2, p2, color); m_debugDraw->DrawSegment(s1, s2, color); } break; case e_mouseJoint: // don't draw this break; default: m_debugDraw->DrawSegment(x1, p1, color); m_debugDraw->DrawSegment(p1, p2, color); m_debugDraw->DrawSegment(x2, p2, color); } } void b2World::DrawDebugData() { if (m_debugDraw == NULL) { return; } uint32 flags = m_debugDraw->GetFlags(); if (flags & b2DebugDraw::e_shapeBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { const b2Transform& xf = b->GetTransform(); for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { if (b->IsActive() == false) { DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); } else if (b->GetType() == b2_staticBody) { DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); } else if (b->GetType() == b2_kinematicBody) { DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); } else if (b->IsAwake() == false) { DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); } else { DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); } } } } if (flags & b2DebugDraw::e_jointBit) { for (b2Joint* j = m_jointList; j; j = j->GetNext()) { DrawJoint(j); } } if (flags & b2DebugDraw::e_pairBit) { b2Color color(0.3f, 0.9f, 0.9f); for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) { b2Fixture* fixtureA = c->GetFixtureA(); b2Fixture* fixtureB = c->GetFixtureB(); b2Vec2 cA = fixtureA->GetAABB().GetCenter(); b2Vec2 cB = fixtureB->GetAABB().GetCenter(); m_debugDraw->DrawSegment(cA, cB, color); } } if (flags & b2DebugDraw::e_aabbBit) { b2Color color(0.9f, 0.3f, 0.9f); b2BroadPhase* bp = &m_contactManager.m_broadPhase; for (b2Body* b = m_bodyList; b; b = b->GetNext()) { if (b->IsActive() == false) { continue; } for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { b2AABB aabb = bp->GetFatAABB(f->m_proxyId); b2Vec2 vs[4]; vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); m_debugDraw->DrawPolygon(vs, 4, color); } } } if (flags & b2DebugDraw::e_centerOfMassBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { b2Transform xf = b->GetTransform(); xf.position = b->GetWorldCenter(); m_debugDraw->DrawTransform(xf); } } } int32 b2World::GetProxyCount() const { return m_contactManager.m_broadPhase.GetProxyCount(); }
[ [ [ 1, 1158 ] ] ]
2628c6df5e7d67f6be76e8c8059cbb279d3183b5
e776dbbd4feab1ce37ad62e5608e22a55a541d22
/MMOGame/Engine/asockio.cpp
87d84e0faf9499e39ad413b1091455ac203847bb
[]
no_license
EmuxEvans/sailing
80f2e2b0ae0f821ce6da013c3f67edabc8ca91ec
6d3a0f02732313f41518839376c5c0067aea4c0f
refs/heads/master
2016-08-12T23:47:57.509147
2011-04-06T03:39:19
2011-04-06T03:39:19
43,952,647
0
0
null
null
null
null
UTF-8
C++
false
false
22,331
cpp
#include <winsock2.h> #include <mswsock.h> #include <stdlib.h> #include <tchar.h> #include <list> #include "asockio.h" using namespace std; #define STATUS_SUCCESS ((DWORD)0x00000000) #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #ifdef _DEBUG #define new DEBUG_NEW #endif #define SIOP_IDLE 0 #define SIOP_ACCEPT 1 #define SIOP_CONNECT 2 #define SIOP_DISCONNECT 3 #define SIOP_RECV 4 #define SIOP_SEND 5 #define SIOP_RECVFROM 6 #define SIOP_SENDTO 7 struct AIO_CONTEXT : WSAOVERLAPPED { INT operation; HEP hep; HCONNECT hconn; HPOOL hpool; WSABUF wsabuf; }; typedef AIO_CONTEXT *PAIO_CONTEXT; #define BufOfCtx(ctx) ((LPBYTE)ctx+sizeof(AIO_CONTEXT)) #define CtxOfBuf(buf) ((PAIO_CONTEXT)((LPBYTE)buf-sizeof(AIO_CONTEXT))) struct IO_BUFFER_POOL { SIZE_T input_size; DWORD input_count; list<PAIO_CONTEXT> input_buffers; CRITICAL_SECTION cs_input; SIZE_T output_size; DWORD output_count; list<PAIO_CONTEXT> output_buffers; CRITICAL_SECTION cs_output; }; typedef IO_BUFFER_POOL *PIO_BUFFER_POOL; HPOOL AllocIoBufferPool(SIZE_T isize, UINT icount, SIZE_T osize, UINT ocount) { PIO_BUFFER_POOL ppool = new IO_BUFFER_POOL; if(ppool) { ppool->input_size = isize; for(ppool->input_count=0; ppool->input_count<icount; ++ppool->input_count) { ppool->input_buffers.push_back((PAIO_CONTEXT)malloc(sizeof(AIO_CONTEXT)+isize)); } InitializeCriticalSectionAndSpinCount(&ppool->cs_input, 4000); ppool->output_size = osize; for(ppool->output_count=0; ppool->output_count<ocount; ++ppool->output_count) { ppool->output_buffers.push_back((PAIO_CONTEXT)malloc(sizeof(AIO_CONTEXT)+osize)); } InitializeCriticalSectionAndSpinCount(&ppool->cs_output, 4000); } return((HPOOL)ppool); } VOID FreeIoBufferPool(HPOOL hpool) { PIO_BUFFER_POOL ppool = (PIO_BUFFER_POOL)hpool; while(ppool->input_buffers.size()!=ppool->input_count) Sleep(0); while(ppool->output_buffers.size()!=ppool->output_count) Sleep(0); while(!ppool->input_buffers.empty()) { free(ppool->input_buffers.front()); ppool->input_buffers.pop_front(); } DeleteCriticalSection(&ppool->cs_input); while(!ppool->output_buffers.empty()) { free(ppool->output_buffers.front()); ppool->output_buffers.pop_front(); } DeleteCriticalSection(&ppool->cs_output); delete(ppool); } static LPBYTE LockInputBuffer(HPOOL hpool) { PAIO_CONTEXT p = NULL; PIO_BUFFER_POOL ppool = (PIO_BUFFER_POOL)hpool; EnterCriticalSection(&ppool->cs_input); if(!ppool->input_buffers.empty()) { p = ppool->input_buffers.front(); ppool->input_buffers.pop_front(); } LeaveCriticalSection(&ppool->cs_input); if(!p) { p = (PAIO_CONTEXT)malloc(sizeof(AIO_CONTEXT)+ppool->input_size); if(!p) { return(NULL); } else { InterlockedIncrement((LONG *)&ppool->input_count); } } ZeroMemory(p, sizeof(AIO_CONTEXT)); p->hpool = hpool; p->wsabuf.len = (ULONG)ppool->input_size; return((LPBYTE)(p->wsabuf.buf = (char *)BufOfCtx(p))); } static VOID UnlockInputBuffer(LPBYTE buf) { PAIO_CONTEXT p = CtxOfBuf(buf); PIO_BUFFER_POOL ppool = (PIO_BUFFER_POOL)p->hpool; EnterCriticalSection(&ppool->cs_input); ppool->input_buffers.push_front(p); LeaveCriticalSection(&ppool->cs_input); } LPBYTE LockOutputBuffer(HPOOL hpool) { PAIO_CONTEXT p = NULL; PIO_BUFFER_POOL ppool = (PIO_BUFFER_POOL)hpool; EnterCriticalSection(&ppool->cs_output); if(!ppool->output_buffers.empty()) { p = ppool->output_buffers.front(); ppool->output_buffers.pop_front(); } LeaveCriticalSection(&ppool->cs_output); if(!p) { p = (PAIO_CONTEXT)malloc(sizeof(AIO_CONTEXT)+ppool->output_size); if(!p) { return(NULL); } else { InterlockedIncrement((LONG *)&ppool->output_count); } } ZeroMemory(p, sizeof(AIO_CONTEXT)); p->hpool = hpool; p->wsabuf.len = (ULONG)ppool->output_size; return((LPBYTE)(p->wsabuf.buf = (char *)BufOfCtx(p))); } VOID UnlockOutputBuffer(LPBYTE buf) { PAIO_CONTEXT p = CtxOfBuf(buf); PIO_BUFFER_POOL ppool = (PIO_BUFFER_POOL)p->hpool; EnterCriticalSection(&ppool->cs_output); ppool->output_buffers.push_front(p); LeaveCriticalSection(&ppool->cs_output); } static BOOL debug_winsock = FALSE; static BOOL need_broadcast = FALSE; VOID GetDefTCPOpt(PTCP_OPTION popt) { popt->recvbuf = -1; popt->sndbuf = -1; popt->reuse_addr = TRUE; popt->conditional_accept = FALSE; popt->keep_alive = FALSE; popt->linger = -1; popt->nodelay = FALSE; } VOID GetDefUDPOpt(PUDP_OPTION popt) { popt->recvbuf = -1; popt->sndbuf = -1; popt->broadcast = need_broadcast; } static LPFN_ACCEPTEX lpfnAcceptEx = NULL; static LPFN_GETACCEPTEXSOCKADDRS lpfnGetAcceptExSockaddrs = NULL; static LPFN_CONNECTEX lpfnConnectEx = NULL; static LPFN_DISCONNECTEX lpfnDisconnectEx = NULL; static VOID ApplyTcpOption(SOCKET s, PTCP_OPTION popt) { if(debug_winsock) { setsockopt(s, SOL_SOCKET, SO_DEBUG, (const char *)&debug_winsock, sizeof(debug_winsock)); } if(popt->recvbuf!=-1) { setsockopt(s, SOL_SOCKET, SO_RCVBUF, (const char *)&popt->recvbuf, sizeof(popt->recvbuf)); } if(popt->sndbuf!=-1) { setsockopt(s, SOL_SOCKET, SO_SNDBUF, (const char *)&popt->sndbuf, sizeof(popt->sndbuf)); } if(popt->reuse_addr) { setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&popt->reuse_addr, sizeof(popt->reuse_addr)); } if(popt->conditional_accept) { setsockopt(s, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (const char *)&popt->conditional_accept, sizeof(popt->conditional_accept)); } if(popt->keep_alive) { setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (const char *)&popt->keep_alive, sizeof(popt->keep_alive)); } if(popt->linger!=-1) { LINGER linger; linger.l_onoff = 1; linger.l_linger = popt->linger; setsockopt(s, SOL_SOCKET, SO_LINGER, (const char *)&linger, sizeof(linger)); } else { BOOL flag = TRUE; setsockopt(s, SOL_SOCKET, SO_DONTLINGER, (const char *)&flag, sizeof(flag)); } if(popt->nodelay) { setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char *)&popt->nodelay, sizeof(popt->nodelay)); } DWORD dwBytes; if(!lpfnAcceptEx) { GUID GuidAcceptEx = WSAID_ACCEPTEX; WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidAcceptEx, sizeof(GuidAcceptEx), &lpfnAcceptEx, sizeof(lpfnAcceptEx), &dwBytes, NULL, NULL); } if(!lpfnGetAcceptExSockaddrs) { GUID GuidGetAcceptExSockAddrs = WSAID_GETACCEPTEXSOCKADDRS; WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidGetAcceptExSockAddrs, sizeof(GuidGetAcceptExSockAddrs), &lpfnGetAcceptExSockaddrs, sizeof(lpfnGetAcceptExSockaddrs), &dwBytes, NULL, NULL); } if(!lpfnConnectEx) { GUID GuidConnectEx = WSAID_CONNECTEX; WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidConnectEx, sizeof(GuidConnectEx), &lpfnConnectEx, sizeof(lpfnConnectEx), &dwBytes, NULL, NULL); } if(!lpfnDisconnectEx) { GUID GuidDisconnectEx = WSAID_DISCONNECTEX; WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidDisconnectEx, sizeof(GuidDisconnectEx), &lpfnDisconnectEx, sizeof(lpfnDisconnectEx), &dwBytes, NULL, NULL); } } static VOID ApplyUdpOption(SOCKET s, PUDP_OPTION popt) { DWORD dwBytesReturned = 0; BOOL bNewBehavior = FALSE; WSAIoctl(s, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), NULL, 0, &dwBytesReturned, NULL, NULL); if(debug_winsock) { setsockopt(s, SOL_SOCKET, SO_DEBUG, (const char *)&debug_winsock, sizeof(debug_winsock)); } if(popt->recvbuf!=-1) { setsockopt(s, SOL_SOCKET, SO_RCVBUF, (const char *)&popt->recvbuf, sizeof(popt->recvbuf)); } if(popt->sndbuf!=-1) { setsockopt(s, SOL_SOCKET, SO_SNDBUF, (const char *)&popt->sndbuf, sizeof(popt->sndbuf)); } if(popt->broadcast) { setsockopt(s, SOL_SOCKET, SO_BROADCAST, (const char *)&popt->broadcast, sizeof(popt->broadcast)); } } static DWORD total_oconns = 0; static list<HCONNECT> free_oconns; static CRITICAL_SECTION cs_free_olist; struct CONNECTION { HEP hep; SOCKET s; HPOOL pool; LPVOID key; BOOL rcving; TCP_EP_HANDLER handler; VOID Send(DWORD, LPBYTE); VOID Recv(PAIO_CONTEXT = NULL); }; typedef CONNECTION *PCONNECTION; struct ACCEPT_CONTEXT : AIO_CONTEXT { BYTE buf[(sizeof(SOCKADDR_IN)+16)*2]; }; typedef ACCEPT_CONTEXT *PACCEPT_CONTEXT; struct TCP_END_POINT { BOOL flag; SOCKET s; HPOOL pool; LPVOID key; TCP_EP_HANDLER handler; ACCEPT_CONTEXT ctx; DWORD total_conns; list<HCONNECT> free_conns; CRITICAL_SECTION cs_free_list; TCP_OPTION tcpopt; VOID Accept(); ~TCP_END_POINT(); }; typedef TCP_END_POINT *PTCP_END_POINT; struct UDP_END_POINT { BOOL flag; SOCKET s; HPOOL pool; LPVOID key; UDP_EP_HANDLER handler; SOCKADDR_IN sainSrc; INT sainLen; VOID SendDatagram(PSOCKADDR_IN, DWORD, LPBYTE); VOID RecvFrom(PAIO_CONTEXT = NULL); }; typedef UDP_END_POINT *PUDP_END_POINT; HPOOL GetPoolHandleOfEndPoint(HEP hep) { return(((PTCP_END_POINT)hep)->pool); } HPOOL GetPoolHandleOfConnection(HCONNECT hconn) { return(((PCONNECTION)hconn)->pool); } HEP GetEndPointHandleOfConnection(HCONNECT hconn) { return(((PCONNECTION)hconn)->hep); } DWORD GetConnPeerIp(HCONNECT hconn) { SOCKADDR_IN sain; int sainlen = sizeof(sain); getpeername(((PCONNECTION)hconn)->s, (sockaddr *)&sain, &sainlen); return(sain.sin_addr.s_addr); } VOID GetConnPeerEp(HCONNECT hconn, DWORD& ip, WORD& port) { SOCKADDR_IN sain; int sainlen = sizeof(sain); getpeername(((PCONNECTION)hconn)->s, (sockaddr *)&sain, &sainlen); ip = sain.sin_addr.s_addr; port = sain.sin_port; } VOID SetConnectionKey(HCONNECT hconn, LPVOID key) { ((PCONNECTION)hconn)->key = key; } LPVOID GetConnectionKey(HCONNECT hconn) { return(((PCONNECTION)hconn)->key); } static VOID CALLBACK SocketIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) { PAIO_CONTEXT pctx = (PAIO_CONTEXT)lpOverlapped; switch(pctx->operation) { case SIOP_ACCEPT: { PACCEPT_CONTEXT pactx = (PACCEPT_CONTEXT)pctx; PTCP_END_POINT pep = (PTCP_END_POINT)pctx->hep; PCONNECTION pconn = (PCONNECTION)pctx->hconn; PSOCKADDR_IN psainLocal, psainRemote; INT llen, rlen; if(dwErrorCode==STATUS_SUCCESS) { setsockopt(pconn->s, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char *)&pep->s, sizeof(pep->s)); lpfnGetAcceptExSockaddrs(pactx->buf, 0, sizeof(SOCKADDR_IN)+16, sizeof(SOCKADDR_IN)+16, (LPSOCKADDR *)&psainLocal, &llen, (LPSOCKADDR *)&psainRemote, &rlen); pconn->rcving = TRUE; if(pconn->handler.OnConnect((HCONNECT)pconn, psainLocal, psainRemote, pconn->key)) { pconn->Recv(); } else { pconn->rcving = FALSE; Disconnect((HCONNECT)pconn); } } else { EnterCriticalSection(&pep->cs_free_list); pep->free_conns.push_front((HCONNECT)pconn); LeaveCriticalSection(&pep->cs_free_list); } pep->Accept(); } break; case SIOP_CONNECT: { PCONNECTION pconn = (PCONNECTION)pctx->hconn; SOCKADDR_IN sainLocal, sainRemote; INT llen, rlen; if(dwErrorCode==STATUS_SUCCESS) { setsockopt(pconn->s, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0); llen = rlen = sizeof(SOCKADDR_IN); getsockname(pconn->s, (PSOCKADDR)&sainLocal, &llen); getpeername(pconn->s, (PSOCKADDR)&sainRemote, &rlen); pconn->rcving = TRUE; if(pconn->handler.OnConnect((HCONNECT)pconn, &sainLocal, &sainRemote, pconn->key)) { pconn->Recv(pctx); } else { pconn->rcving = FALSE; Disconnect((HCONNECT)pconn); UnlockInputBuffer(BufOfCtx(pctx)); } } else { pconn->handler.OnConnectFailed(pconn->key); EnterCriticalSection(&cs_free_olist); free_oconns.push_front((HCONNECT)pconn); LeaveCriticalSection(&cs_free_olist); UnlockInputBuffer(BufOfCtx(pctx)); } } break; case SIOP_DISCONNECT: { PTCP_END_POINT pep = (PTCP_END_POINT)pctx->hep; PCONNECTION pconn = (PCONNECTION)pctx->hconn; if(dwErrorCode==STATUS_SUCCESS) { while(pconn->rcving) SwitchToThread(); pconn->handler.OnDisconnect((HCONNECT)pconn, pconn->key); if(pep) { EnterCriticalSection(&pep->cs_free_list); pep->free_conns.push_front((HCONNECT)pconn); LeaveCriticalSection(&pep->cs_free_list); } else { EnterCriticalSection(&cs_free_olist); free_oconns.push_front((HCONNECT)pconn); LeaveCriticalSection(&cs_free_olist); } } UnlockOutputBuffer(BufOfCtx(pctx)); } break; case SIOP_RECV: { PCONNECTION pconn = (PCONNECTION)pctx->hconn; if(dwErrorCode==STATUS_SUCCESS && dwNumberOfBytesTransfered) { pconn->handler.OnData((HCONNECT)pconn, dwNumberOfBytesTransfered, BufOfCtx(pctx), pconn->key); pconn->Recv(pctx); } else { pconn->rcving = FALSE; Disconnect((HCONNECT)pconn); UnlockInputBuffer(BufOfCtx(pctx)); } } break; case SIOP_RECVFROM: { PUDP_END_POINT pep = (PUDP_END_POINT)pctx->hep; if(dwErrorCode==STATUS_SUCCESS && dwNumberOfBytesTransfered) { pep->handler.OnDatagram((HEP)pep, &pep->sainSrc, dwNumberOfBytesTransfered, BufOfCtx(pctx), pep->key); pep->RecvFrom(pctx); } else { UnlockInputBuffer(BufOfCtx(pctx)); } } break; case SIOP_SEND: case SIOP_SENDTO: UnlockOutputBuffer(BufOfCtx(pctx)); break; } } VOID CONNECTION::Send(DWORD dwLen, LPBYTE buf) { DWORD dwXfer; PAIO_CONTEXT pctx = CtxOfBuf(buf); pctx->operation = SIOP_SEND; pctx->hep = hep; pctx->hconn = (HCONNECT)this; pctx->wsabuf.len = dwLen; if(SOCKET_ERROR==WSASend(s, &pctx->wsabuf, 1, &dwXfer, 0, pctx, NULL) && WSAGetLastError()!=ERROR_IO_PENDING) { UnlockOutputBuffer(buf); } } VOID CONNECTION::Recv(PAIO_CONTEXT pctx) { DWORD dwXfer, dwFlag = 0; LPBYTE buf; if(pctx) { buf = BufOfCtx(pctx); } else { buf = LockInputBuffer(pool); pctx = CtxOfBuf(buf); } pctx->operation = SIOP_RECV; pctx->hep = hep; pctx->hconn = (HCONNECT)this; if(SOCKET_ERROR==WSARecv(s, &pctx->wsabuf, 1, &dwXfer, &dwFlag, pctx, NULL) && WSAGetLastError()!=ERROR_IO_PENDING) { rcving = FALSE; UnlockInputBuffer(buf); } } VOID TCP_END_POINT::Accept() { PCONNECTION pconn = NULL; DWORD dwXfer; EnterCriticalSection(&cs_free_list); if(!free_conns.empty()) { pconn = (PCONNECTION)free_conns.front(); free_conns.pop_front(); } LeaveCriticalSection(&cs_free_list); if(!pconn) { pconn = new CONNECTION; if(!pconn) return; pconn->hep = (HEP)this; pconn->s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(pconn->s==INVALID_SOCKET) { delete(pconn); return; } ApplyTcpOption(pconn->s, &tcpopt); if(!BindIoCompletionCallback((HANDLE)pconn->s, SocketIOCompletionRoutine, 0)) { closesocket(pconn->s); delete(pconn); return; } ++total_conns; pconn->pool = pool; pconn->handler = handler; } pconn->key = key; ZeroMemory(&ctx, sizeof(ctx)); ctx.operation = SIOP_ACCEPT; ctx.hep = (HEP)this; ctx.hconn = (HCONNECT)pconn; if(!lpfnAcceptEx(s, pconn->s, ctx.buf, 0, sizeof(SOCKADDR_IN)+16, sizeof(SOCKADDR_IN)+16, &dwXfer, &ctx) && WSAGetLastError()!=ERROR_IO_PENDING) { EnterCriticalSection(&cs_free_list); free_conns.push_front((HCONNECT)pconn); LeaveCriticalSection(&cs_free_list); } } TCP_END_POINT::~TCP_END_POINT() { PCONNECTION pconn; while(!free_conns.empty()) { pconn = (PCONNECTION)free_conns.front(); free_conns.pop_front(); closesocket(pconn->s); delete(pconn); } } VOID UDP_END_POINT::SendDatagram(PSOCKADDR_IN psain, DWORD dwLen, LPBYTE buf) { DWORD dwXfer; PAIO_CONTEXT pctx = CtxOfBuf(buf); pctx->operation = SIOP_SENDTO; pctx->hep = (HEP)this; pctx->wsabuf.len = dwLen; if(SOCKET_ERROR==WSASendTo(s, &pctx->wsabuf, 1, &dwXfer, 0, (PSOCKADDR)psain, sizeof(SOCKADDR_IN), pctx, NULL) && WSAGetLastError()!=ERROR_IO_PENDING) { UnlockOutputBuffer(buf); } } VOID UDP_END_POINT::RecvFrom(PAIO_CONTEXT pctx) { DWORD dwXfer, dwFlag = 0; LPBYTE buf; if(pctx) { buf = BufOfCtx(pctx); } else { buf = LockInputBuffer(pool); pctx = CtxOfBuf(buf); } pctx->operation = SIOP_RECVFROM; pctx->hep = (HEP)this; sainLen = sizeof(sainSrc); if(SOCKET_ERROR==WSARecvFrom(s, &pctx->wsabuf, 1, &dwXfer, &dwFlag, (PSOCKADDR)&sainSrc, &sainLen, pctx, NULL) && WSAGetLastError()!=ERROR_IO_PENDING) { UnlockInputBuffer(buf); } } HEP RegisterTcpEndPoint(PSOCKADDR_IN psain, PTCP_EP_HANDLER phandler, PTCP_OPTION popt, HPOOL hpool, LPVOID key) { PTCP_END_POINT pep = NULL; if(!psain || !phandler || !hpool) return(NULL); pep = new TCP_END_POINT; if(pep) { pep->s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(pep->s==INVALID_SOCKET) { delete(pep); pep = NULL; } else { if(popt) { pep->tcpopt = *popt; } else { GetDefTCPOpt(&pep->tcpopt); } ApplyTcpOption(pep->s, &pep->tcpopt); if(!BindIoCompletionCallback((HANDLE)pep->s, SocketIOCompletionRoutine, 0) || bind(pep->s, (PSOCKADDR)psain, sizeof(SOCKADDR_IN))==SOCKET_ERROR || listen(pep->s, SOMAXCONN)==SOCKET_ERROR || !InitializeCriticalSectionAndSpinCount(&pep->cs_free_list, 4000)) { closesocket(pep->s); delete(pep); pep = NULL; } else { pep->flag = TRUE; pep->pool = hpool; pep->key = key; pep->handler = *phandler; pep->total_conns = 0; pep->Accept(); } } } return((HEP)pep); } static VOID UnregisterTcpEndPoint(PTCP_END_POINT ptep) { closesocket(ptep->s); DWORD timeleft = 15000; while(ptep->free_conns.size()!=ptep->total_conns && timeleft) { Sleep(100); timeleft -= 100; } DeleteCriticalSection(&ptep->cs_free_list); delete(ptep); } HEP RegisterUdpEndPoint(PSOCKADDR_IN psain, PUDP_EP_HANDLER phandler, PUDP_OPTION popt, HPOOL hpool, LPVOID key) { PUDP_END_POINT pep = NULL; UDP_OPTION opt; if(!psain || !phandler || !hpool) return(NULL); pep = new UDP_END_POINT; if(pep) { pep->s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(pep->s==INVALID_SOCKET) { delete(pep); pep = NULL; } else { if(popt) { ApplyUdpOption(pep->s, popt); } else { GetDefUDPOpt(&opt); ApplyUdpOption(pep->s, &opt); } if(!BindIoCompletionCallback((HANDLE)pep->s, SocketIOCompletionRoutine, 0) || bind(pep->s, (PSOCKADDR)psain, sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(pep->s); delete(pep); pep = NULL; } else { pep->flag = FALSE; pep->pool = hpool; pep->key = key; pep->handler = *phandler; pep->RecvFrom(); } } } return((HEP)pep); } static VOID UnregisterUdpEndPoint(PUDP_END_POINT puep) { closesocket(puep->s); delete(puep); } VOID UnregisterEndPoint(HEP hep) { PTCP_END_POINT ptep = (PTCP_END_POINT)hep; PUDP_END_POINT puep = (PUDP_END_POINT)hep; if(ptep->flag) { UnregisterTcpEndPoint(ptep); } else { UnregisterUdpEndPoint(puep); } } BOOL Connect(PSOCKADDR_IN psain, PTCP_EP_HANDLER phandler, PTCP_OPTION popt, HPOOL hpool, LPVOID key) { TCP_OPTION opt; SOCKADDR_IN sain; PCONNECTION pconn = NULL; if(!psain || !phandler || !hpool) return(FALSE); EnterCriticalSection(&cs_free_olist); if(!free_oconns.empty()) { pconn = (PCONNECTION)free_oconns.front(); free_oconns.pop_front(); } LeaveCriticalSection(&cs_free_olist); if(!pconn) { pconn = new CONNECTION; if(!pconn) return(FALSE); pconn->s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(pconn->s==INVALID_SOCKET) { delete(pconn); return(FALSE); } if(popt) { ApplyTcpOption(pconn->s, popt); } else { GetDefTCPOpt(&opt); ApplyTcpOption(pconn->s, &opt); } pconn->hep = NULL; ZeroMemory(&sain, sizeof(sain)); sain.sin_family = AF_INET; if(!BindIoCompletionCallback((HANDLE)pconn->s, SocketIOCompletionRoutine, 0) || bind(pconn->s, (PSOCKADDR)&sain, sizeof(sain))==SOCKET_ERROR) { closesocket(pconn->s); delete(pconn); return(FALSE); } InterlockedIncrement((LONG *)&total_oconns); } pconn->pool = hpool; pconn->key = key; pconn->handler = *phandler; LPBYTE buf = LockInputBuffer(hpool); PAIO_CONTEXT pctx = CtxOfBuf(buf); pctx->operation = SIOP_CONNECT; pctx->hconn = (HCONNECT)pconn; if(!lpfnConnectEx(pconn->s, (PSOCKADDR)psain, sizeof(SOCKADDR_IN), NULL, 0, NULL, pctx) && WSAGetLastError()!=ERROR_IO_PENDING) { UnlockInputBuffer(buf); EnterCriticalSection(&cs_free_olist); free_oconns.push_front((HCONNECT)pconn); LeaveCriticalSection(&cs_free_olist); return(FALSE); } return(TRUE); } BOOL Disconnect(HCONNECT hconn) { PCONNECTION pconn = (PCONNECTION)hconn; LPBYTE buf = LockOutputBuffer(pconn->pool); PAIO_CONTEXT pctx = CtxOfBuf(buf); pctx->operation = SIOP_DISCONNECT; pctx->hep = pconn->hep; pctx->hconn = hconn; if(!lpfnDisconnectEx(pconn->s, pctx, TF_REUSE_SOCKET, 0) && WSAGetLastError()!=ERROR_IO_PENDING) { UnlockOutputBuffer(buf); return(FALSE); } return(TRUE); } VOID SendData(HCONNECT hconn, DWORD dwLen, LPBYTE buf) { ((PCONNECTION)hconn)->Send(dwLen, buf); } VOID SendDatagram(HEP hep, PSOCKADDR_IN psain, DWORD dwLen, LPBYTE buf) { ((PUDP_END_POINT)hep)->SendDatagram(psain, dwLen, buf); } BOOL ASockIOInit() { InitializeCriticalSectionAndSpinCount(&cs_free_olist, 4000); WSADATA wsaData; return(0==WSAStartup(0x0202, &wsaData)); } VOID ASockIOFini() { while(free_oconns.size()!=total_oconns) Sleep(0); PCONNECTION pconn; while(!free_oconns.empty()) { pconn = (PCONNECTION)free_oconns.front(); free_oconns.pop_front(); closesocket(pconn->s); delete(pconn); } WSACleanup(); DeleteCriticalSection(&cs_free_olist); } DWORD StringToIP(LPCTSTR szHost) { CHAR buf[256]; #ifdef _UNICODE wcstombs(buf, szHost, 256); #else strcpy(buf, szHost); #endif DWORD ret = inet_addr(buf); if(ret==INADDR_NONE) { hostent *phe = gethostbyname(buf); if(phe) { ret = *(DWORD *)(phe->h_addr); } } return(ret); }
[ "gamemake@74c81372-9d52-0410-afc2-f743258a769a" ]
[ [ [ 1, 785 ] ] ]
2b64ba3c100c790559ff86fac2fd6870d6b06062
191d4160cba9d00fce9041a1cc09f17b4b027df5
/ZeroLag2/ZeroLag/ServerManageUIHandler.cpp
c01d98dd28f4f586be8231f5966cb92cf6bda72b
[]
no_license
zapline/zero-lag
f71d35efd7b2f884566a45b5c1dc6c7eec6577dd
1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4
refs/heads/master
2021-01-22T16:45:46.430952
2011-05-07T13:22:52
2011-05-07T13:22:52
32,774,187
3
2
null
null
null
null
GB18030
C++
false
false
2,079
cpp
#include "ServerManageUIHandler.h" #include "stdafx.h" #include "MainWnd.h" CServerManageUIHandler::CServerManageUIHandler(void) { } CServerManageUIHandler::~CServerManageUIHandler(void) { } void CServerManageUIHandler::init( CMainWnd *p ) { pMain = p; DWORD dwStyle = WS_CHILD|LVS_REPORT|LVS_SHOWSELALWAYS|LVS_SINGLESEL|LVS_OWNERDRAWFIXED; if( ServerManageListCtrl.Create( pMain->GetRichWnd(), NULL, NULL, dwStyle, 0, 2001 ) ) { DWORD dwExStyle = LVS_EX_FULLROWSELECT; dwExStyle |= ServerManageListCtrl.GetExtendedListViewStyle(); ServerManageListCtrl.SetExtendedListViewStyle(dwExStyle); ServerManageListCtrl.InsertColumn( 0, _T("ๆœๅŠกๅ็งฐ"), LVCFMT_LEFT, 250); ServerManageListCtrl.InsertColumn( 1, _T("ๆœๅŠกๆ่ฟฐ"), LVCFMT_LEFT, 400); ServerManageListCtrl.InsertColumn( 2, _T("ๆœๅŠก็Šถๆ€"), LVCFMT_LEFT, 100); ServerManageListCtrl.Init(); ServerManageHide = FALSE; ServerManageFlush(); } } void CServerManageUIHandler::ServerManageFlush() { //็ฒๅพ—้šฑ่—ๆœช้‹่กŒ่ค‡้ธๆก†็š„็‹€ๆ…‹ ServerManageListCtrl.DeleteAllItems(); ENUM_SERVICE_STATUS* lpservice = NULL; DWORD servicesReturned = 0; ServerManage.EnumServername(&lpservice,SERVICE_WIN32|SERVICE_DRIVER,SERVICE_STATE_ALL,&servicesReturned); unsigned j=0; for(unsigned i=0;i < servicesReturned;i++) { if (lpservice[i].ServiceStatus.dwCurrentState == SERVICE_RUNNING) { ServerManageListCtrl.InsertItem(j, ""); ServerManageListCtrl.SetItemText(j,0,lpservice[i].lpServiceName); ServerManageListCtrl.SetItemText(j,1,lpservice[i].lpDisplayName); ServerManageListCtrl.SetItemText(j,2, "ๆญฃ่ฟ่กŒ"); j++; } else if (ServerManageHide == FALSE) { ServerManageListCtrl.InsertItem(j, ""); ServerManageListCtrl.SetItemText(j,0,lpservice[i].lpServiceName); ServerManageListCtrl.SetItemText(j,1,lpservice[i].lpDisplayName); ServerManageListCtrl.SetItemText(j,2, "ๅทฒๅœๆญข"); j++; } } } void CServerManageUIHandler::OnServerManageFlush() { ServerManageFlush(); }
[ "Administrator@PC-200201010241" ]
[ [ [ 1, 75 ] ] ]
4b105b0b3e68a06f5cf18d66abded3f740b639a0
1dba10648f60dea02c9be242c668f3488ae8dec4
/program/src/fnwidget.h
37823421250fecde9fb9e43ce1d319d1c1cc6ec5
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,416
h
/******************************************************************** Projekt z przedmiotu : Sztuczna Inteligencja i Sensoryka stworzono: 17:12:2006 16:52 plik: fnwidget autorzy: Tomasz Huczek, Andrzej Jasiล„ski cel: *********************************************************************/ #ifndef __FNWIDGET_H__ #define __FNWIDGET_H__ ////////////////////////////////////////////////////////////////////////// #include <qwidget.h> ////////////////////////////////////////////////////////////////////////// class QPushButton; class QLineEdit; class QString; ////////////////////////////////////////////////////////////////////////// /// kotrolka wyboru pliku z dysku, skladajaca sie z pola edycji, /// oraz przycisku, po ktoergo wcisnieciu pokazuje sie dialog z /// wyborem pliku class fnWidget: public QWidget { Q_OBJECT public: fnWidget( QWidget* parent=0, const char* name=0, WFlags f=0 ); virtual ~fnWidget(); public: /// \return nazwa pliku QString get_filename(); /// metoda ustawia wartos pola edycji void setText( QString txt ); signals: void textChanged(); protected slots: void select_file(); void inTextChanged( const QString & ); private: QPushButton * btn_browse; QLineEdit * edt_filename; }; ////////////////////////////////////////////////////////////////////////// #endif // __FNWIDGET_H__
[ "tomasz.huczek@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 57 ] ] ]
b265a2eefda202e2e75e5afe54ac9fe1f627bd17
27bf1951e08b36c01374014a6da855a706680f7b
/USACO-Solution/src/1.4.2.cpp
5cd5165a0942a0b21de5df52e9dba83da7462b6e
[]
no_license
zinking/algorithm-exercise
4c520fd3ff6c14804d32e4ea427e5f7809cc7315
c58902709e9f12146d3d1f66610306e5ff19cfff
refs/heads/master
2016-09-05T22:27:19.791962
2009-07-24T04:45:18
2009-07-24T04:45:18
32,133,027
0
0
null
null
null
null
UTF-8
C++
false
false
3,227
cpp
/* ID: zinking1 PROG: packrec LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace std; ofstream fout ("packrec.out"); ifstream fin ("packrec.in"); int max(int a, int b, int c){ return max(max(a, b), c); } int max(int a, int b, int c, int d){ return max(max(a, b, c), d); } struct Rect{ int w; int h; Rect():w(0),h(0){} Rect(int width, int height):w(width),h(height){} void Tidy(){ if( w > h ) swap( w, h ); } int getArea(){ return w*h; } void fileout(){ fout << w << " " << h << endl; } }; Rect rect[4]; int smallestRectArea = 65535; typedef vector<Rect> VRECT; VRECT small_rects; VRECT::iterator vit; void updateSmallestRect( int w, int h){ Rect r(w,h); if( r.getArea() < smallestRectArea ){ small_rects.clear(); small_rects.push_back( r ); smallestRectArea = r.getArea(); } else if( r.getArea() == smallestRectArea ){ small_rects.push_back( r ); } } void calculateArea(int x[], int i){ int h0 = rect[x[0]].h; int w0 = rect[x[0]].w; int h1 = rect[x[1]].h; int w1 = rect[x[1]].w; int h2 = rect[x[2]].h; int w2 = rect[x[2]].w; int h3 = rect[x[3]].h; int w3 = rect[x[3]].w; if ((i & 1) == 1) swap(h0, w0); if ((i & 2) == 2) swap(h1, w1); if ((i & 4) == 4) swap(h2, w2); if ((i & 8) == 8) swap(h3, w3);//i bit wise operation to get All combination of transposes int tot_w, tot_h; //1 tot_h = max(h0, h1, h2, h3); tot_w = w0 + w1 + w2 + w3; updateSmallestRect( tot_w, tot_h ); //2 tot_h = max(h0, h1, h2) + h3; tot_w = max(w0 + w1 + w2, w3); updateSmallestRect( tot_w, tot_h ); //3 tot_h = max(max(h0, h1) + h3, h2); tot_w = max(w0 + w1, w3) + w2; updateSmallestRect( tot_w, tot_h ); //4 tot_h = max(h0 + h1, h2, h3); tot_w = max(w0, w1) + w2 + w3; updateSmallestRect( tot_w, tot_h ); //5 tot_h = max(h0 + h1, h2 + h3); tot_w = max(w0 + w3, w1 + w2); if (h0 + h2 > tot_h && w0 + w2 > tot_w) return; if (h1 + h3 > tot_h && w1 + w3 > tot_w) return; updateSmallestRect( tot_w, tot_h ); } void getPermutation(int x[], int p){ if (p >= 4) { for (int i = 0; i <= 15; i++) calculateArea(x, i); return; } for (int i = p; i < 4; i++) { swap(x[i], x[p]); getPermutation(x, p + 1); } } bool compare_rect( const Rect& r1, const Rect& r2){ return r1.w < r2.w; } bool rect_equal( const Rect& r1, const Rect& r2){ return ( r1.w == r2.w ) && ( r1.h == r2.h ); } int main() { for (int i = 0; i < 4; i++) fin >> rect[i].w >> rect[i].h; int x[4] = {0,1,2,3}; getPermutation(x,0);//permuatate all rects; for( int i=0; i<small_rects.size(); i++ ) small_rects[i].Tidy(); sort( small_rects.begin(),small_rects.end(), compare_rect ); vit = unique( small_rects.begin(),small_rects.end(), rect_equal); small_rects.resize( vit - small_rects.begin() ); fout << smallestRectArea << endl; for( int i=0; i<small_rects.size(); i++ ) small_rects[i].fileout(); return 0; }
[ "zinking3@e423e194-685c-11de-ba0c-230037762ff9" ]
[ [ [ 1, 142 ] ] ]
913f9c5b1764b4ff07a397644dc34daf47d0dcf9
694894e5fd2a4600a2bd3fd04d4f36d9dddf252d
/AccordsCalculator/Testing/main.cpp
9bdda29fef7a6ecbf83b6f8fc924080938aac7e5
[]
no_license
dodikk/Akkords-Calculator
a419b7e775f46b254c738b67850587d118880e98
67fb819040f41fb26c249596fe7a26ff5e791982
refs/heads/master
2021-01-01T05:34:37.538194
2010-01-31T14:11:35
2010-01-31T14:11:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
609
cpp
#include "stdafx.h" #include <tchar.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> #include "NoteHeightOperatorsTest.h" CPPUNIT_TEST_SUITE_REGISTRATION(NoteHeightOperatorsTest); #include "AkkordsBuilderTest.h" CPPUNIT_TEST_SUITE_REGISTRATION(AkkordsBuilderTest); int _tmain(int argc, _TCHAR* argv[]) { //unit tests CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); return !runner.run("", false); }
[ [ [ 1, 25 ] ] ]
dddbb1b74ffe3f42cc2eade98c9faee5e46eb06d
cb68cabf2417c69ae78563330727a10f7007d148
/gui/inc/menumodel.h
419c7946717a16a9a39c78f637e549d06db829fe
[]
no_license
qVlad/ikey_next
373d5e3eeaf0b29d5cee0dee504b3c6366aedc60
a4055954b08e07d1acdc1ece9b8a0d0724358da1
refs/heads/master
2020-05-02T05:48:27.222366
2011-10-02T22:24:31
2011-10-02T22:24:31
2,463,007
0
0
null
null
null
null
UTF-8
C++
false
false
862
h
#ifndef MENUMODEL_H #define MENUMODEL_H #include <QAbstractListModel> #include <QStringList> class MenuElement { public: MenuElement(const QString &fullName, const int &value); QString fullName() const; int value() const; private: QString m_fullName; int m_value; }; class MenuModel: public QAbstractListModel { Q_OBJECT public: enum MenuElementRoles { FullNameRole = Qt::UserRole + 1, ValueRole }; MenuModel(QObject *parent = 0); void addMenuElement(const MenuElement &MenuElement); int rowCount(const QModelIndex & parent = QModelIndex()) const; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; public slots: void dd(){qDebug("Message from QML");} private: QList<MenuElement> m_elements; }; #endif // MENUMODEL_H
[ "vlad@vladislav-PC.(none)" ]
[ [ [ 1, 40 ] ] ]
1633ef7f9bf87839d7de94bf170846ee2a0efe08
3e69b159d352a57a48bc483cb8ca802b49679d65
/trunk/pcbnew/export_gencad.cpp
730b6a37e64ff78d3395ac566ebaa62b9fac1a3f
[]
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
25,341
cpp
/***************************************************/ /* export_gencad.cpp - export en formay GenCAD 1.4 */ /***************************************************/ #include "fctsys.h" #include "common.h" #include "pcbnew.h" #include "trigo.h" #include "bitmaps.h" #include "protos.h" #include "id.h" bool CreateHeaderInfoData(FILE * file, WinEDA_PcbFrame * frame); static int * CreateTracksInfoData(FILE * file, BOARD * pcb); static void CreateBoardSection(FILE * file, BOARD * pcb); static void CreateComponentsSection(FILE * file, BOARD * pcb); static void CreateDevicesSection(FILE * file, BOARD * pcb); static void CreateRoutesSection(FILE * file, BOARD * pcb); static void CreateSignalsSection(FILE * file, BOARD * pcb); static void CreateShapesSection(FILE * file, BOARD * pcb); static void CreatePadsShapesSection(FILE * file, BOARD * pcb); static void ModuleWriteShape( FILE * File, MODULE * module ); wxString GenCAD_Layer_Name[32] // layer name pour extensions fichiers de trace = { wxT("BOTTOM"), wxT("INNER1"), wxT("INNER2"), wxT("INNER3"), wxT("INNER4"), wxT("INNER5"), wxT("INNER6"), wxT("INNER7"), wxT("INNER8"), wxT("INNER9"), wxT("INNER10"), wxT("INNER11"), wxT("INNER12"), wxT("INNER13"), wxT("INNER14"), wxT("TOP"), wxT("adhecu"), wxT("adhecmp"), wxT("SOLDERPASTE_BOTTOM"), wxT("SOLDERPASTE_TOP"), wxT("SILKSCREEN_BOTTOM"), wxT("SILKSCREEN_TOP"), wxT("SOLDERMASK_BOTTOM"), wxT("SOLDERMASK_TOP"), wxT("drawings"), wxT("comments"), wxT("eco1"), wxT("eco2"), wxT("edges"), wxT("--"), wxT("--"), wxT("--") }; int offsetX, offsetY; D_PAD * PadList; /* routines de conversion des coord ( sous GenCAD axe Y vers le haut) */ static int mapXto(int x) { return x - offsetX; } static int mapYto(int y) { return offsetY - y; } /***********************************************************/ void WinEDA_PcbFrame::ExportToGenCAD(wxCommandEvent& event) /***********************************************************/ /* Exporte le board au format GenCAD 1.4 */ { wxString FullFileName = GetScreen()->m_FileName; wxString msg, std_ext, mask; FILE * file; std_ext = wxT(".gcd"); mask = wxT("*") + std_ext; ChangeFileNameExt(FullFileName,std_ext); FullFileName = EDA_FileSelector(_("GenCAD file:"), wxEmptyString, /* Chemin par defaut */ FullFileName, /* nom fichier par defaut */ std_ext, /* extension par defaut */ mask, /* Masque d'affichage */ this, wxOPEN, FALSE ); if ( FullFileName == wxEmptyString ) return; if ( (file = wxFopen(FullFileName, wxT("wt") )) == NULL ) { msg = _("Unable to create ") + FullFileName; DisplayError(this, msg); return; } /* Mise a jour des infos PCB: */ m_Pcb->ComputeBoundaryBox(); offsetX = m_Auxiliary_Axe_Position.x; offsetY = m_Auxiliary_Axe_Position.y; wxClientDC dc(DrawPanel); DrawPanel->PrepareGraphicContext(&dc); Compile_Ratsnest( &dc, TRUE ); /* Mise des modules vus en miroir en position "normale" (necessaire pour decrire les formes sous GenCAD, qui sont decrites en vue normale, orientation 0)) */ MODULE * module; for(module = m_Pcb->m_Modules; module != NULL; module = module->Next()) { module->flag = 0; if ( module->m_Layer == CUIVRE_N ) { Change_Side_Module(module, NULL); module->flag = 1; } } // Creation de l'entete: CreateHeaderInfoData(file, this); CreateBoardSection(file, m_Pcb); /* Creation liste des TRACKS (section $TRACK) id liste des outils de tracage de pistes */ CreateTracksInfoData(file, m_Pcb); /* Creation de la liste des formes utilisees (formes des composants principalement */ CreatePadsShapesSection(file, m_Pcb); // doit etre appele avant CreateShapesSection() CreateShapesSection( file, m_Pcb); /* Creation de la liste des equipotentielles: */ CreateSignalsSection(file, m_Pcb); CreateDevicesSection(file, m_Pcb); CreateComponentsSection(file, m_Pcb); CreateRoutesSection(file, m_Pcb); fclose(file); /* Remise en place des modules vus en miroir */ for(module = m_Pcb->m_Modules; module != NULL; module = module->Next()) { if ( module->flag ) { Change_Side_Module(module, NULL); module->flag = 0; } } } /**************************************************************************/ static int Pad_list_Sort_by_Shapes(const void * refptr, const void * objptr) /**************************************************************************/ /* Routine de tri de la liste des pads par type, puis pa taille */ { const D_PAD * padref, *padcmp; int diff; padref = *((D_PAD**) refptr); padcmp = *((D_PAD**) objptr); if( (diff = padref->m_PadShape - padcmp->m_PadShape) ) return diff; if( (diff = padref->m_Size.x - padcmp->m_Size.x) ) return diff; if( (diff = padref->m_Size.y - padcmp->m_Size.y) ) return diff; if( (diff = padref->m_Offset.x - padcmp->m_Offset.x) ) return diff; if( (diff = padref->m_Offset.y - padcmp->m_Offset.y) ) return diff; if( (diff = padref->m_DeltaSize.x - padcmp->m_DeltaSize.x) ) return diff; if( (diff = padref->m_DeltaSize.y - padcmp->m_DeltaSize.y) ) return diff; return 0; } /*****************************************************/ void CreatePadsShapesSection(FILE * file, BOARD * pcb) /*****************************************************/ /* Cree la liste des formes des pads ( 1 forme par pad ) initialise le membre .m_logical_connexion de la struct pad, la valeur 1 ..n pour les formes de pad PAD1 a PADn */ { D_PAD * pad, **padlist, **pad_list_base; char * pad_type; int memsize, ii, dx, dy; D_PAD * old_pad = NULL; int pad_name_number; fputs("$PADS\n", file); // Generation de la liste des pads tries par forme et dimensions: memsize = (pcb->m_NbPads + 1) * sizeof(D_PAD*); pad_list_base = (D_PAD**) MyZMalloc(memsize); memcpy(pad_list_base, pcb->m_Pads, memsize); qsort(pad_list_base, pcb->m_NbPads, sizeof(D_PAD*), Pad_list_Sort_by_Shapes); pad_name_number = 0; for( padlist = pad_list_base, ii = 0; ii < pcb->m_NbPads; padlist++, ii++) { pad = *padlist; pad->m_logical_connexion = pad_name_number; if ( old_pad && (old_pad->m_PadShape == pad->m_PadShape) && (old_pad->m_Size.x == pad->m_Size.x) && (old_pad->m_Size.y == pad->m_Size.y) && (old_pad->m_Offset.x == pad->m_Offset.x) && (old_pad->m_Offset.y == pad->m_Offset.y) && (old_pad->m_DeltaSize.x == pad->m_DeltaSize.x) && (old_pad->m_DeltaSize.y == pad->m_DeltaSize.y) ) continue; // Forme deja generee old_pad = pad; pad_name_number ++; pad->m_logical_connexion = pad_name_number; fprintf(file, "PAD PAD%d", pad->m_logical_connexion); dx = pad->m_Size.x / 2; dy = pad->m_Size.y / 2; switch( pad->m_PadShape ) { default: case CIRCLE: pad_type = "ROUND"; fprintf(file, " %s %d\n", pad_type, pad->m_Drill); fprintf(file, "CIRCLE %d %d %d\n", pad->m_Offset.x, - pad->m_Offset.y, pad->m_Size.x/2); break; case RECT: pad_type = "RECTANGULAR"; fprintf(file, " %s %d\n", pad_type, pad->m_Drill); fprintf(file, "RECTANGLE %d %d %d %d\n", -dx + pad->m_Offset.x, - dy - pad->m_Offset.y, dx + pad->m_Offset.x, - pad->m_Offset.y + dy ); break; case OVALE: /* description du contour par 2 linges et 2 arcs */ { pad_type = "FINGER"; fprintf(file, " %s %d\n", pad_type, pad->m_Drill); int dr = dx - dy; if ( dr >= 0 ) // ovale horizontal { int rayon = dy; fprintf(file, "LINE %d %d %d %d\n", -dr + pad->m_Offset.x, - pad->m_Offset.y - rayon, dr + pad->m_Offset.x, - pad->m_Offset.y - rayon ); fprintf(file, "ARC %d %d %d %d %d %d\n", dr + pad->m_Offset.x, - pad->m_Offset.y - rayon, dr + pad->m_Offset.x, - pad->m_Offset.y + rayon, dr + pad->m_Offset.x, - pad->m_Offset.y); fprintf(file, "LINE %d %d %d %d\n", dr + pad->m_Offset.x, - pad->m_Offset.y + rayon, -dr + pad->m_Offset.x, - pad->m_Offset.y + rayon ); fprintf(file, "ARC %d %d %d %d %d %d\n", -dr + pad->m_Offset.x, - pad->m_Offset.y + rayon, -dr + pad->m_Offset.x, - pad->m_Offset.y - rayon, -dr + pad->m_Offset.x, - pad->m_Offset.y); } else // ovale vertical { dr = -dr; int rayon = dx; fprintf(file, "LINE %d %d %d %d\n", -rayon + pad->m_Offset.x, - pad->m_Offset.y - dr, -rayon + pad->m_Offset.x, - pad->m_Offset.y + dr ); fprintf(file, "ARC %d %d %d %d %d %d\n", -rayon + pad->m_Offset.x, - pad->m_Offset.y + dr, rayon + pad->m_Offset.x, - pad->m_Offset.y + dr, pad->m_Offset.x, - pad->m_Offset.y + dr); fprintf(file, "LINE %d %d %d %d\n", rayon + pad->m_Offset.x, - pad->m_Offset.y + dr, rayon + pad->m_Offset.x, - pad->m_Offset.y - dr ); fprintf(file, "ARC %d %d %d %d %d %d\n", rayon + pad->m_Offset.x, - pad->m_Offset.y - dr, - rayon + pad->m_Offset.x, - pad->m_Offset.y - dr, pad->m_Offset.x, - pad->m_Offset.y - dr); } break; } case TRAPEZE: pad_type = "POLYGON"; break; } } fputs("$ENDPADS\n\n", file); MyFree(pad_list_base); } /**************************************************/ void CreateShapesSection(FILE * file, BOARD * pcb) /**************************************************/ /* Creation de la liste des formes des composants. Comme la forme de base (module de librairie peut etre modifiee, une forme est creee par composant La forme est donnee normalisee, c'est a dire orientation 0, position 0 non miroir Il y aura donc des formes indentiques redondantes Syntaxe: $SHAPES SHAPE <shape_name> shape_descr (line, arc ..) PIN <pin_name> <pad_name> <x_y_ref> <layer> <rot> <mirror> SHAPE <shape_name> .. $ENDSHAPES */ { MODULE * module; D_PAD * pad; char * layer; int orient; wxString pinname; char * mirror = "0"; fputs("$SHAPES\n", file); for(module = pcb->m_Modules; module != NULL; module = (MODULE *) module->Pnext) { ModuleWriteShape( file, module ); for( pad = module->m_Pads; pad != NULL; pad = (D_PAD*) pad->Pnext) { layer = "ALL"; if ( (pad->m_Masque_Layer & ALL_CU_LAYERS) == CUIVRE_LAYER ) { if ( module->m_Layer == CMP_N ) layer = "BOTTOM"; else layer = "TOP"; } else if ( (pad->m_Masque_Layer & ALL_CU_LAYERS) == CMP_LAYER ) { if ( module->m_Layer == CMP_N ) layer = "TOP"; else layer = "BOTTOM"; } pad->ReturnStringPadName(pinname); if( pinname.IsEmpty() ) pinname = wxT("noname"); orient = pad->m_Orient - module->m_Orient; NORMALIZE_ANGLE_POS(orient); fprintf(file, "PIN %s PAD%d %d %d %s %d %s", CONV_TO_UTF8(pinname), pad->m_logical_connexion, pad->m_Pos0.x, - pad->m_Pos0.y, layer, orient/10, mirror ); if ( orient % 10 ) fprintf(file, " .%d", orient % 10 ); fprintf(file, "\n"); } } fputs("$ENDSHAPES\n\n", file); } /******************************************************/ void CreateComponentsSection(FILE * file, BOARD * pcb) /******************************************************/ /* Creation de la section $COMPONENTS (Placement des composants Composants cote CUIVRE: Les formes sont donnees avec l'option "FLIP", c.a.d.: - ils sont decrits en vue normale (comme s'ils etaient sur cote COMPOSANT) - leur orientation est donnรฉe comme s'ils etaient cote composant. */ { MODULE * module = pcb->m_Modules; TEXTE_MODULE * PtTexte; char * mirror; char * flip; int ii; fputs("$COMPONENTS\n", file); for(; module != NULL; module = (MODULE *) module->Pnext) { int orient = module->m_Orient; if (module->flag) { mirror = "MIRRORX"; // Miroir selon axe X flip = "FLIP"; // Description normale ( formes a afficher en miroir X) NEGATE_AND_NORMALIZE_ANGLE_POS(orient); } else { mirror ="0"; flip = "0"; } fprintf(file, "COMPONENT %s\n", CONV_TO_UTF8(module->m_Reference->m_Text)); fprintf(file, "DEVICE %s\n", CONV_TO_UTF8(module->m_Reference->m_Text)); fprintf(file, "PLACE %d %d\n", mapXto(module->m_Pos.x), mapYto(module->m_Pos.y)); fprintf(file, "LAYER %s\n", (module->flag)? "BOTTOM" : "TOP"); fprintf(file, "ROTATION %d", orient/10 ); if (orient%10 ) fprintf(file, ".%d", orient%10 ); fputs("\n",file); fprintf(file, "SHAPE %s %s %s\n", CONV_TO_UTF8(module->m_Reference->m_Text), mirror, flip); /* Generation des elements textes (ref et valeur seulement) */ PtTexte = module->m_Reference; for ( ii = 0; ii < 2; ii++ ) { int orient = PtTexte->m_Orient; wxString layer = GenCAD_Layer_Name[SILKSCREEN_N_CMP]; fprintf(file, "TEXT %d %d %d %d.%d %s %s \"%s\"", PtTexte->m_Pos0.x, - PtTexte->m_Pos0.y, PtTexte->m_Size.x, orient /10, orient %10, mirror, CONV_TO_UTF8(layer), CONV_TO_UTF8(PtTexte->m_Text) ); fprintf(file, " 0 0 %d %d\n", PtTexte->m_Size.x * PtTexte->m_Text.Len(), PtTexte->m_Size.y ); PtTexte = module->m_Value; } // commentaire: fprintf(file, "SHEET Part %s %s\n", CONV_TO_UTF8(module->m_Reference->m_Text), CONV_TO_UTF8(module->m_Value->m_Text)); } fputs("$ENDCOMPONENTS\n\n", file); } /***************************************************/ void CreateSignalsSection(FILE * file, BOARD * pcb) /***************************************************/ /* Creation de la liste des equipotentielles: $SIGNALS SIGNAL <equipot name> NODE <component name> <pin name> ... NODE <component name> <pin name> $ENDSIGNALS */ { wxString msg; EQUIPOT * equipot; D_PAD * pad; MODULE * module; int NbNoConn = 1; fputs("$SIGNALS\n", file); for( equipot = pcb->m_Equipots; equipot != NULL; equipot = (EQUIPOT *) equipot->Pnext ) { if ( equipot->m_Netname == wxEmptyString ) // dummy equipot (non connexion) { equipot->m_Netname << wxT("NoConnection") << NbNoConn++; } if ( equipot->m_NetCode <= 0 ) // dummy equipot (non connexion) continue; msg = wxT("\nSIGNAL ") + equipot->m_Netname; fputs( CONV_TO_UTF8(msg), file); fputs("\n", file); for ( module = pcb->m_Modules; module != NULL; module = (MODULE *) module->Pnext ) { for( pad = module->m_Pads; pad != NULL; pad = (D_PAD *) pad->Pnext ) { wxString padname; if ( pad->m_NetCode != equipot->m_NetCode ) continue; pad->ReturnStringPadName(padname); msg.Printf(wxT("NODE %s %.4s"), module->m_Reference->m_Text.GetData(), padname.GetData()); fputs( CONV_TO_UTF8(msg), file); fputs("\n", file); } } } fputs("$ENDSIGNALS\n\n", file); } /*************************************************************/ bool CreateHeaderInfoData(FILE * file, WinEDA_PcbFrame * frame) /*************************************************************/ /* Creation de la section $HEADER ... $ENDHEADER */ { wxString msg; PCB_SCREEN * screen = frame->GetScreen(); fputs("$HEADER\n", file); fputs("GENCAD 1.4\n", file); msg = wxT("USER ") + g_Main_Title + wxT(" ") + GetBuildVersion(); fputs(CONV_TO_UTF8(msg), file); fputs("\n", file); msg = wxT("DRAWING ") + screen->m_FileName; fputs(CONV_TO_UTF8(msg), file); fputs("\n", file); msg = wxT("REVISION ") + screen->m_Revision + wxT(" ") + screen->m_Date; fputs(CONV_TO_UTF8(msg), file); fputs("\n", file); msg.Printf(wxT("UNITS USER %d"), PCB_INTERNAL_UNIT); fputs(CONV_TO_UTF8(msg), file); fputs("\n", file); msg.Printf( wxT("ORIGIN %d %d"), mapXto(frame->m_Auxiliary_Axe_Position.x), mapYto(frame->m_Auxiliary_Axe_Position.y)) ; fputs(CONV_TO_UTF8(msg), file); fputs("\n", file); fputs("INTERTRACK 0\n", file); fputs("$ENDHEADER\n\n", file); return TRUE; } /**************************************************************************/ static int Track_list_Sort_by_Netcode(const void * refptr, const void * objptr) /**************************************************************************/ /* Routine de tri de la liste des piste par netcode, puis par largeur puis par layer */ { const TRACK * ref, *cmp; int diff; ref = *((TRACK**) refptr); cmp = *((TRACK**) objptr); if( (diff = ref->m_NetCode - cmp->m_NetCode) ) return diff; if( (diff = ref->m_Width - cmp->m_Width) ) return diff; if( (diff = ref->m_Layer - cmp->m_Layer) ) return diff; return 0; } /*************************************************/ void CreateRoutesSection(FILE * file, BOARD * pcb) /*************************************************/ /* Creation de la liste des pistes, vias et zones section: $ROUTE ... $ENROUTE Les segments de piste doivent etre regroupes par nets */ { TRACK * track, ** tracklist; int vianum = 1; int old_netcode, old_width, old_layer; int nbitems, ii; // Calcul du nombre de segments a ecrire nbitems = 0; for( track = pcb->m_Track; track != NULL; track = (TRACK*) track->Pnext ) nbitems++; for( track = pcb->m_Zone; track != NULL; track = (TRACK*) track->Pnext ) { if ( track->m_StructType == TYPEZONE ) nbitems++; } tracklist = (TRACK **) MyMalloc( (nbitems+1) * sizeof(TRACK *) ); nbitems = 0; for( track = pcb->m_Track; track != NULL; track = (TRACK*) track->Pnext ) tracklist[nbitems++] = track; for( track = pcb->m_Zone; track != NULL; track = (TRACK*) track->Pnext ) { if ( track->m_StructType == TYPEZONE ) tracklist[nbitems++] = track; } tracklist[nbitems] = NULL; qsort(tracklist, nbitems, sizeof(TRACK *), Track_list_Sort_by_Netcode); fputs("$ROUTES\n", file); old_netcode = -1; old_width = -1; old_layer = -1; for( ii = 0; ii < nbitems; ii++ ) { track = tracklist[ii]; if ( old_netcode != track->m_NetCode ) { old_netcode = track->m_NetCode; EQUIPOT * equipot = GetEquipot( pcb, track->m_NetCode); fprintf(file,"\nROUTE %s\n", (equipot && (equipot->m_Netname != wxEmptyString) ) ? equipot->m_Netname.GetData() : wxT("_noname_" )); } if ( old_width != track->m_Width ) { old_width = track->m_Width; fprintf(file,"TRACK TRACK%d\n", track->m_Width); } if ( (track->m_StructType == TYPETRACK) || (track->m_StructType == TYPEZONE) ) { if ( old_layer != track->m_Layer ) { old_layer = track->m_Layer; fprintf(file,"LAYER %s\n", GenCAD_Layer_Name[track->m_Layer & 0x1F].GetData()); } fprintf(file, "LINE %d %d %d %d\n", mapXto(track->m_Start.x), mapYto(track->m_Start.y), mapXto(track->m_End.x), mapYto(track->m_End.y) ); } if ( track->m_StructType == TYPEVIA ) { fprintf(file, "VIA viapad%d %d %d ALL %d via%d\n", track->m_Width, mapXto(track->m_Start.x), mapYto(track->m_Start.y), g_DesignSettings.m_ViaDrill, vianum++ ); } } fputs("$ENDROUTES\n\n", file); free(tracklist); } /***************************************************/ void CreateDevicesSection(FILE * file, BOARD * pcb) /***************************************************/ /* Creation de la section de description des proprietes des composants ( la forme des composants est dans la section shape ) */ { MODULE * module; D_PAD * pad; fputs("$DEVICES\n", file); for(module = pcb->m_Modules; module != NULL; module = (MODULE *) module->Pnext) { fprintf(file, "DEVICE %s\n", CONV_TO_UTF8(module->m_Reference->m_Text)); fprintf(file, "PART %s\n", CONV_TO_UTF8(module->m_LibRef)); fprintf(file, "TYPE %s\n", "UNKNOWN"); for( pad = module->m_Pads; pad != NULL; pad = (D_PAD*) pad->Pnext) { fprintf(file, "PINDESCR %.4s", pad->m_Padname); if ( pad->m_Netname == wxEmptyString ) fputs(" NoConn\n", file); else fprintf(file, " %.4s\n", pad->m_Padname); } fprintf(file, "ATTRIBUTE %s\n", CONV_TO_UTF8(module->m_Value->m_Text)); } fputs("$ENDDEVICES\n\n", file); } /*************************************************/ void CreateBoardSection(FILE * file, BOARD * pcb) /*************************************************/ /* Creation de la section $BOARD. On ne cree ici que le rectangle d'encadrement du Board */ { fputs("$BOARD\n", file); fprintf(file, "LINE %d %d %d %d\n", mapXto(pcb->m_BoundaryBox.m_Pos.x), mapYto(pcb->m_BoundaryBox.m_Pos.y), mapXto(pcb->m_BoundaryBox.GetRight()), mapYto(pcb->m_BoundaryBox.m_Pos.y) ); fprintf(file, "LINE %d %d %d %d\n", mapXto(pcb->m_BoundaryBox.GetRight()), mapYto(pcb->m_BoundaryBox.m_Pos.y), mapXto(pcb->m_BoundaryBox.GetRight()), mapYto(pcb->m_BoundaryBox.GetBottom()) ); fprintf(file, "LINE %d %d %d %d\n", mapXto(pcb->m_BoundaryBox.GetRight()), mapYto(pcb->m_BoundaryBox.GetBottom()), mapXto(pcb->m_BoundaryBox.m_Pos.x), mapYto(pcb->m_BoundaryBox.GetBottom()) ); fprintf(file, "LINE %d %d %d %d\n", mapXto(pcb->m_BoundaryBox.m_Pos.x), mapYto(pcb->m_BoundaryBox.GetBottom()), mapXto(pcb->m_BoundaryBox.m_Pos.x), mapYto(pcb->m_BoundaryBox.m_Pos.y) ); fputs("$ENDBOARD\n\n", file); } /****************************************************/ int * CreateTracksInfoData(FILE * file, BOARD * pcb) /****************************************************/ /* Creation de la section "$TRACKS" Cette section definit les largeurs de pistes utilsees format: $TRACK TRACK <name> <width> $ENDTRACK on attribut ici comme nom l'epaisseur des traits precede de "TRACK": ex pour une largeur de 120 : nom = "TRACK120". */ { TRACK * track; int * trackinfo, * ptinfo; /* recherche des epaisseurs utilisees pour les traces: */ trackinfo = (int*) adr_lowmem; *trackinfo = -1; for( track = pcb->m_Track; track != NULL; track = (TRACK*) track->Pnext ) { if ( *trackinfo != track->m_Width ) // recherche d'une epaisseur deja utilisee { ptinfo = (int*) adr_lowmem; while (*ptinfo >= 0 ) { if ( *ptinfo != track->m_Width ) ptinfo ++; else break; } trackinfo = ptinfo; if ( *ptinfo < 0 ) { *ptinfo = track->m_Width; ptinfo++; *ptinfo = -1; } } } for( track = pcb->m_Zone; track != NULL; track = (TRACK*) track->Pnext ) { if ( *trackinfo != track->m_Width ) // recherche d'une epaisseur deja utilisee { ptinfo = (int*) adr_lowmem; while (*ptinfo >= 0 ) { if ( *ptinfo != track->m_Width ) ptinfo ++; else break; } trackinfo = ptinfo; if ( *ptinfo < 0 ) { *ptinfo = track->m_Width; ptinfo++; *ptinfo = -1; } } } // Write data fputs("$TRACKS\n", file); for( trackinfo = (int*) adr_lowmem; * trackinfo >= 0; trackinfo++ ) { fprintf(file,"TRACK TRACK%d %d\n", * trackinfo, * trackinfo); } fputs("$ENDTRACKS\n\n", file); return (int*) adr_lowmem; } /***************************************************/ void ModuleWriteShape( FILE * file, MODULE * module ) /***************************************************/ /* Sauvegarde de la forme d'un MODULE (section SHAPE) La forme est donnee "normalisee" (Orient 0, vue normale ( non miroir) Syntaxe: SHAPE <shape_name> shape_descr (line, arc ..): LINE startX startY endX endY ARC startX startY endX endY centreX scentreY CIRCLE centreX scentreY radius */ { EDGE_MODULE * PtEdge; EDA_BaseStruct * PtStruct; int Yaxis_sign = -1; // Controle changement signe axe Y (selon module normal/miroir et conevtions d'axe) /* Generation du fichier module: */ fprintf(file, "\nSHAPE %s\n", CONV_TO_UTF8(module->m_Reference->m_Text)); /* Attributs du module */ if( module->m_Attributs != MOD_DEFAULT ) { fprintf(file,"ATTRIBUTE"); if( module->m_Attributs & MOD_CMS ) fprintf(file," SMD"); if( module->m_Attributs & MOD_VIRTUAL ) fprintf(file," VIRTUAL"); fprintf(file,"\n"); } /* Generation des elements Drawing modules */ PtStruct = module->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext) { switch(PtStruct->m_StructType ) { case TYPETEXTEMODULE: break; case TYPEEDGEMODULE: PtEdge = (EDGE_MODULE*) PtStruct; switch(PtEdge->m_Shape ) { case S_SEGMENT: fprintf(file,"LINE %d %d %d %d\n", PtEdge->m_Start0.x, Yaxis_sign * PtEdge->m_Start0.y, PtEdge->m_End0.x, Yaxis_sign * PtEdge->m_End0.y); break; case S_CIRCLE: { int rayon = (int)hypot( (double)(PtEdge->m_End0.x - PtEdge->m_Start0.x), (double)(PtEdge->m_End0.y - PtEdge->m_Start0.y) ); fprintf(file,"CIRCLE %d %d %d\n", PtEdge->m_Start0.x, Yaxis_sign * PtEdge->m_Start0.y, rayon); break; } case S_ARC: /* print ARC x,y start x,y end x,y centre */ { int arcendx, arcendy; arcendx = PtEdge->m_Start0.x; arcendy = PtEdge->m_Start0.y; RotatePoint(& arcendx, &arcendy, PtEdge->m_Angle); fprintf(file,"ARC %d %d %d %d %d %d\n", PtEdge->m_End0.x, Yaxis_sign * PtEdge->m_End0.y, arcendx, Yaxis_sign * arcendy, PtEdge->m_Start0.x, Yaxis_sign * PtEdge->m_Start0.y); break; } default: DisplayError(NULL, wxT("Type Edge Module inconnu")); break; } /* Fin switch type edge */ break; default: break; } /* Fin switch gestion des Items draw */ } }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26", "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 486 ], [ 489, 817 ] ], [ [ 487, 488 ] ] ]
8e62773c625d7abb5f054c5285ead93803a3c504
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/math/stoch/corr.hpp
bad3e79a98bfc26d062f79f4cfeb2b297fe005f9
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,262
hpp
#ifndef __STOCHASTIC_CORRELATION_PROCESS_QM_HPP__ #define __STOCHASTIC_CORRELATION_PROCESS_QM_HPP__ #include <qmlib/math/stoch/diffusion.hpp> QM_NAMESPACE2(math) class stochcorr: public diffusion<1u> { public: stochcorr(PARAMETER kappa, PARAMETER theta, PARAMETER var, PARAMETER v0); qm_real drift(const qm_real& x, qm_real t) const; qm_real sigma(const qm_real& x, qm_real t) const; qm_string code() const {return "Stochastic Correlation";} protected: iparameter* p_kappa; iparameter* p_theta; iparameter* p_var; iparameter* p_v0; }; inline stochcorr::stochcorr(PARAMETER kappa, PARAMETER theta, PARAMETER var, PARAMETER v0) { p_kappa = kappa.get(); p_theta = theta.get(); p_var = var.get(); p_v0 = v0.get(); QM_REQUIRE(p_kappa && p_theta && p_var && p_v0,"Parameters not properly defined"); this->add(kappa); this->add(theta); this->add(var); this->add(v0); } qm_real stochcorr::drift(const qm_real& x, qm_real t) const { return p_kappa->get_value()*(p_theta->get_value() - x); } qm_real stochcorr::sigma(const qm_real& x, qm_real t) const { return std::sqrt(p_var->get_value()*(1.0 - x*x)); } QM_NAMESPACE_END2 #endif // __STOCHASTIC_CORRELATION_PROCESS_QM_HPP__
[ [ [ 1, 52 ] ] ]
24ab497ecf3e1b76e8caa200cadc1e66935fe9d7
fb8ab028c5e7865229f7032052ef6419cce6d843
/patterndemo/src/StdAfx.cpp
724b764634143ca55a835b459843ecaca6757116
[]
no_license
alexunder/autumtao
d3fbca5b87fef96606501de8bfd600825b628e42
296db161b50c96efab48b05b5846e6f1ac90c38a
refs/heads/master
2016-09-05T09:43:36.361738
2011-03-25T16:13:51
2011-03-25T16:13:51
33,286,987
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
// stdafx.cpp : source file that includes just the standard includes // recogdemo.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "Xalexu@59d19903-2beb-cf48-5e42-6f21bef2d45e" ]
[ [ [ 1, 8 ] ] ]
1658864e5e247b398671f4fe694a52b0c014f13a
a705a17ff1b502ec269b9f5e3dc3f873bd2d3b9c
/include/object.hpp
01b03f2133521b01665446f07d617cb512074929
[]
no_license
cantidio/ChicolinusQuest
82431a36516d17271685716590fe7aaba18226a0
9b77adabed9325bba23c4d99a3815e7f47456a4d
refs/heads/master
2021-01-25T07:27:54.263356
2011-08-09T11:17:53
2011-08-09T11:17:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
hpp
#ifndef _OBJECT_ #define _OBJECT_ #include "point.hpp" #include "spritepack.hpp" #include "animationpack.hpp" #include "include.hpp" #include "collision_box.hpp" class BG; class Object { protected: Point mPosition; Point mMaxAcceleration; Point mMoveAcceleration; Point mCurrentAcceleration; Point mOffset; Point mFriction; Collision mCollision; BG* mBG; int mDirection; std::string mName; std::string mSpritesName; std::string mAnimationName; SpritePack *mSprites; AnimationPack mAnimation; unsigned int mTimeOn; unsigned int mAnimationOn; unsigned int mFrameOn; bool mAnimationIsOver; bool mNeedToDestroy; public: Object(const Point& pPosition, const std::string& pScript, BG* pBG); Object(const Object& pObject); ~Object(); bool colide(const Object& pObject); void draw(const Point& pPosition); virtual void logic(); bool needToDestroy() const; bool animationIsOver() const; void changeAnimation( const unsigned int& pAnimation, const bool pForce = false ); void operator = (const Object& pObject); inline Point getPosition() const { return mPosition; } }; #endif
[ [ [ 1, 50 ] ] ]
3d071f4b564d1f8012618af493dbc3fae0ac1ef8
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/CodeLite/entry.h
ed78b7ebc10d6de66a3f719e6d836760af5a6b10
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
7,788
h
#ifndef CODELITE_ENTRY_H #define CODELITE_ENTRY_H #include "db_record.h" #include <wx/treectrl.h> #include "readtags.h" #include <wx/string.h> #include <map> #include "smart_ptr.h" #ifdef WXMAKINGDLL_CODELITE # define WXDLLIMPEXP_CL WXEXPORT #elif defined(WXUSINGDLL_CODELITE) # define WXDLLIMPEXP_CL WXIMPORT #else /* not making nor using FNB as DLL */ # define WXDLLIMPEXP_CL #endif // /** * TagEntry is a persistent object which is capable of storing and loading itself from * various inputs: * - tagEntry (ctags structure) * - wxSQLite3ResultSet - from the database * * It contains all the knowledge of storing and retrieving itself from the database * * \ingroup CodeLite * \version 1.0 * first version * * \date 11-11-2006 * \author Eran */ class WXDLLIMPEXP_CL TagEntry : public DbRecord { wxString m_path; ///< Tag full path wxString m_file; ///< File this tag is found int m_lineNumber; ///< Line number wxString m_pattern; ///< A pattern that can be used to locate the tag in the file wxString m_kind; ///< Member, function, class, typedef etc. wxString m_parent; ///< Direct parent wxTreeItemId m_hti; ///< Handle to tree item, not persistent item wxString m_name; ///< Tag name (short name, excluding any scope names) std::map<wxString, wxString> m_extFields; ///< Additional extension fields long m_position; ///< Position in the document - optional field, not persistent item long m_id; long m_parentId; wxString m_scope; public: /** * Construct a TagEntry from tagEntry struct * \param entry Tag entry */ TagEntry(const tagEntry& entry); /** * Default constructor. */ TagEntry(); /** * Copy constructor. */ TagEntry(const TagEntry& rhs); /** * Construct a tag entry from db record. * \param rs Result set */ TagEntry(wxSQLite3ResultSet& rs); /** * \param rhs Source to copy from (right hand side) * \return this */ TagEntry& operator=(const TagEntry& rhs); /** * Compare two TagEntry objects. * \param rhs Right hand side * \return true if identical, false otherwise */ bool operator==(const TagEntry& rhs); /** * Destructor */ virtual ~TagEntry(); /** * Construct a TagEntry from tagEntry struct. * \param entry Tag entry */ void Create(const tagEntry& entry); /** * Construct a TagEntry from values. * \param fileName File name * \param name Tag name * \param lineNumber Tag line number * \param pattern Pattern * \param kind Tag kind (class, struct, etc) * \param extFields Map of extenstion fields (key:value) * \param project Project name */ void Create(const wxString &fileName, const wxString &name, int lineNumber, const wxString &pattern, const wxString &kind, std::map<wxString, wxString>& extFields); /** * Test if this entry has been initialised. * \return true if this tag entry has been initialised */ const bool IsOk() const { return GetKind() != _T("<unknown>"); } /** * Test of this tag is a container (class, union, struct or namespace */ const bool IsContainer() const; //------------------------------------------ // Operations //------------------------------------------ int GetId() const { return m_id; } void SetId(int id) { m_id = id;} int GetParentId() const { return m_parentId; } void SetParentId(int id) { m_parentId = id;} const wxString& GetName() const { return m_name;} void SetName(const wxString& name) { m_name = name; } const wxString& GetPath() const { return m_path;} void SetPath(const wxString& path) { m_path = path; } const wxString& GetFile() const { return m_file;} void SetFile(const wxString& file) { m_file = file;} int GetLine() const { return m_lineNumber;} void SetLine(int line) { m_lineNumber = line; } const wxString& GetPattern() const { return m_pattern; } void SetPattern(const wxString& pattern) { m_pattern = pattern; } wxString GetKind() const; void SetKind(const wxString& kind) { m_kind = kind; } const wxString& GetParent() const { return m_parent; } void SetParent(const wxString& parent) { m_parent = parent; } wxTreeItemId& GetTreeItemId() { return m_hti; } void SetTreeItemId(wxTreeItemId& hti) { m_hti = hti; } wxString GetAccess() const { return GetExtField(_T("access"));} void SetAccess(const wxString &access){m_extFields[wxT("access")] = access;} wxString GetSignature() const { return GetExtField(_T("signature")); } wxString GetInherits() const { return GetExtField(_T("inherits")); } wxString GetTyperef() const { return GetExtField(_T("typeref")); } int GetPosition() const { return m_position; } void SetPosition(int col) { m_position = col; } const wxString &GetScope() const {return m_scope;} void SetScope(const wxString &scope){m_scope = scope;} /** * \return Scope name of the tag. * If path is empty in db or contains just the project name, it will return the literal <global>. * For project tags, an empty string is returned. */ wxString GetScopeName() const; /** * Generate a Key for this tag based on its attributes * \return tag key */ wxString Key() const; /** * Generate a display name for this tag to be used by the symbol tree * \return tag display name */ wxString GetDisplayName() const; /** * Generate a full display name for this tag that includes: * full scope + name + signature * \return tag full display name */ wxString GetFullDisplayName() const; /** * Return the actual name as described in the 'typeref' field * \return real name or wxEmptyString */ wxString NameFromTyperef(); /** * Return the actual type as described in the 'typeref' field * \return real name or wxEmptyString */ wxString TypeFromTyperef() const; //------------------------------------------ // Extenstion fields //------------------------------------------ wxString GetExtField(const wxString& extField) const { std::map<wxString, wxString>::const_iterator iter = m_extFields.find(extField); if(iter == m_extFields.end()) return wxEmptyString; return iter->second; } //------------------------------------------ // Misc //------------------------------------------ void Print(); //------------------------------------------ // Database operations //------------------------------------------ /** * Save this record into db. * \param insertPreparedStmnt Prepared statement for insert operation * \return TagOk, TagExist, TagError */ virtual int Store(wxSQLite3Statement& insertPreparedStmnt); /** * Update this record into db. * \param insertPreparedStmnt Prepared statement for insert operation * \return TagOk, TagError */ virtual int Update(wxSQLite3Statement& updatePreparedStmnt); /** * Delete this record from db. * \param deletePreparedStmnt Prepared statement for delete operation * \return TagOk, TagError */ virtual int Delete(wxSQLite3Statement& deletePreparedStmnt); /** * \return delete preapred statement */ virtual wxString GetDeleteOneStatement(); /** * \return update preapred statement */ virtual wxString GetUpdateOneStatement(); /** * \return insert preapred statement */ virtual wxString GetInsertOneStatement(); private: /** * Update the path with full path (e.g. namespace::class) * \param path path to add */ void UpdatePath(wxString & path); bool TypedefFromPattern(const wxString &tagPattern, const wxString &typedefName, wxString &name); }; typedef SmartPtr<TagEntry> TagEntryPtr; #endif // CODELITE_ENTRY_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 275 ] ] ]
683e5548dc559816fc9e159e0c3a3d580af85a04
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine samples/01_Sample/source/sdcSylfurDCGame.h
b0269d695ddb51b9efbc5a13fa68e4cabe41c81f
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#ifndef __SYLFUR_DC_GAME_H_ #define __SYLFUR_DC_GAME_H_ #include "qvGame.h" namespace sdc { class SylfurDCGame: public qv::Game { public: SylfurDCGame(); virtual ~SylfurDCGame(); }; } #endif
[ [ [ 1, 20 ] ] ]
f748918bb6176723b3f1132a42ab4dc95ee94077
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/unordered/test/unordered/move_tests.cpp
237f5810012397ed88a8421d02f160cc38bdbed3
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,148
cpp
// Copyright 2008-2009 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or move at http://www.boost.org/LICENSE_1_0.txt) #include <boost/unordered_set.hpp> #include <boost/unordered_map.hpp> #include "../helpers/test.hpp" #include "../objects/test.hpp" #include "../helpers/random_values.hpp" #include "../helpers/tracker.hpp" #include "../helpers/equivalent.hpp" #include "../helpers/invariants.hpp" namespace move_tests { test::seed_t seed(98624); template<class T> T empty(T*) { return T(); } template<class T> T create(test::random_values<T> const& v, test::object_count& count) { T x(v.begin(), v.end()); count = test::global_object_count; return x; } template<class T> T create(test::random_values<T> const& v, test::object_count& count, BOOST_DEDUCED_TYPENAME T::hasher hf, BOOST_DEDUCED_TYPENAME T::key_equal eq, BOOST_DEDUCED_TYPENAME T::allocator_type al, float mlf) { T x(0, hf, eq, al); x.max_load_factor(mlf); x.insert(v.begin(), v.end()); count = test::global_object_count; return x; } template <class T> void move_construct_tests1(T* ptr, test::random_generator const& generator = test::default_generator) { BOOST_DEDUCED_TYPENAME T::hasher hf; BOOST_DEDUCED_TYPENAME T::key_equal eq; BOOST_DEDUCED_TYPENAME T::allocator_type al; { T y(empty(ptr)); BOOST_TEST(y.empty()); BOOST_TEST(test::equivalent(y.hash_function(), hf)); BOOST_TEST(test::equivalent(y.key_eq(), eq)); BOOST_TEST(test::equivalent(y.get_allocator(), al)); BOOST_TEST(y.max_load_factor() == 1.0); test::check_equivalent_keys(y); } { test::random_values<T> v(1000, generator); test::object_count count; T y(create(v, count)); BOOST_TEST(count == test::global_object_count); test::check_container(y, v); test::check_equivalent_keys(y); } } template <class T> void move_assign_tests1(T*, test::random_generator const& generator = test::default_generator) { { test::random_values<T> v(500, generator); test::object_count count; T y; y = create(v, count); BOOST_TEST(count == test::global_object_count); test::check_container(y, v); test::check_equivalent_keys(y); } } template <class T> void move_construct_tests2(T*, test::random_generator const& generator = test::default_generator) { BOOST_DEDUCED_TYPENAME T::hasher hf(1); BOOST_DEDUCED_TYPENAME T::key_equal eq(1); BOOST_DEDUCED_TYPENAME T::allocator_type al(1); BOOST_DEDUCED_TYPENAME T::allocator_type al2(2); test::object_count count; { test::random_values<T> v(500, generator); T y(create(v, count, hf, eq, al, 0.5)); BOOST_TEST(count == test::global_object_count); test::check_container(y, v); BOOST_TEST(test::equivalent(y.hash_function(), hf)); BOOST_TEST(test::equivalent(y.key_eq(), eq)); BOOST_TEST(test::equivalent(y.get_allocator(), al)); BOOST_TEST(y.max_load_factor() == 0.5); // Not necessarily required. test::check_equivalent_keys(y); } { // TODO: To do this correctly requires the fancy new allocator stuff. test::random_values<T> v(500, generator); T y(create(v, count, hf, eq, al, 2.0), al2); BOOST_TEST(count != test::global_object_count); test::check_container(y, v); BOOST_TEST(test::equivalent(y.hash_function(), hf)); BOOST_TEST(test::equivalent(y.key_eq(), eq)); BOOST_TEST(test::equivalent(y.get_allocator(), al2)); BOOST_TEST(y.max_load_factor() == 2.0); // Not necessarily required. test::check_equivalent_keys(y); } { test::random_values<T> v(25, generator); T y(create(v, count, hf, eq, al, 1.0), al); #if defined(BOOST_HAS_RVALUE_REFS) BOOST_TEST(count == test::global_object_count); #else BOOST_TEST(test::global_object_count.constructions - count.constructions <= (test::is_map<T>::value ? 50 : 25)); BOOST_TEST(count.instances == test::global_object_count.instances); #endif test::check_container(y, v); BOOST_TEST(test::equivalent(y.hash_function(), hf)); BOOST_TEST(test::equivalent(y.key_eq(), eq)); BOOST_TEST(test::equivalent(y.get_allocator(), al)); BOOST_TEST(y.max_load_factor() == 1.0); // Not necessarily required. test::check_equivalent_keys(y); } } boost::unordered_set<test::object, test::hash, test::equal_to, test::allocator<test::object> >* test_set; boost::unordered_multiset<test::object, test::hash, test::equal_to, test::allocator<test::object> >* test_multiset; boost::unordered_map<test::object, test::object, test::hash, test::equal_to, test::allocator<test::object> >* test_map; boost::unordered_multimap<test::object, test::object, test::hash, test::equal_to, test::allocator<test::object> >* test_multimap; using test::default_generator; using test::generate_collisions; UNORDERED_TEST(move_construct_tests1, ((test_set)(test_multiset)(test_map)(test_multimap)) ) UNORDERED_TEST(move_assign_tests1, ((test_set)(test_multiset)(test_map)(test_multimap)) ) UNORDERED_TEST(move_construct_tests2, ((test_set)(test_multiset)(test_map)(test_multimap)) ((default_generator)(generate_collisions)) ) } RUN_TESTS()
[ "metrix@Blended.(none)" ]
[ [ [ 1, 162 ] ] ]
46f1c5754f4df2990d799ff143b64a307aaf085f
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/face/popoface/CNPopupMenu.cpp
9abcdb8942f6f67434d20e5b4ece514493e4fec2
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,078
cpp
// GfxPopupMenu.cpp: implementation of the CNPopupMenu class. // // Modified a lot by Zhang Yong ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CNPopupMenu.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CNPopupMenu::CNPopupMenu() { crMenuText = GetSysColor(COLOR_MENUTEXT); crMenuTextSel = GetSysColor(COLOR_HIGHLIGHTTEXT); cr3dFace = GetSysColor(COLOR_3DFACE); crMenu = GetSysColor(COLOR_MENU); crHighlight = GetSysColor(COLOR_HIGHLIGHT); cr3dHilight = GetSysColor(COLOR_3DHILIGHT); cr3dShadow = GetSysColor(COLOR_3DSHADOW); crGrayText = GetSysColor(COLOR_GRAYTEXT); m_clrBtnFace = GetSysColor(COLOR_BTNFACE); m_clrBtnHilight = GetSysColor(COLOR_BTNHILIGHT); m_clrBtnShadow = GetSysColor(COLOR_BTNSHADOW); iSpawnItem = 0; pSpawnItem = NULL; iImageItem = 0; pImageItem = NULL; hMenuFont = NULL; /* COLORMAP cMap[3] = { { RGB(128,128,128), cr3dShadow }, { RGB(192,192,192), cr3dFace }, { RGB(255,255,255), cr3dHilight } }; CBitmap bmp; bmp.LoadMappedBitmap(IDB_MENUCHK, 0, cMap, 3); ilOther.Create(19, 19, ILC_COLOR4|ILC_MASK, 1, 0); ilOther.Add(&bmp, cr3dFace); bmp.DeleteObject(); */ NONCLIENTMETRICS ncm; memset(&ncm, 0, sizeof(ncm)); ncm.cbSize = sizeof(ncm); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID) &ncm, 0); hGuiFont = ::CreateFontIndirect(&ncm.lfMenuFont); // David 08/04/98 - start - bold font handling hMenuBoldFont = NULL; CreateBoldFont(); // David 08/04/98 - end - bold font handling ilList.Create(16, 16, ILC_MASK | ILC_COLOR8, 5, 15); szImage = CSize(16, 16); // @@ vertDrawn = FALSE; } CNPopupMenu::~CNPopupMenu() { if (iSpawnItem > 0) { for (int t = 0; t < iSpawnItem; t++) if (pSpawnItem[t]) delete pSpawnItem[t]; GlobalFree((HGLOBAL) pSpawnItem); } if (iImageItem > 0) { GlobalFree((HGLOBAL) pImageItem); } if (hMenuFont) ::DeleteObject((HGDIOBJ)hMenuFont); if (hMenuBoldFont) ::DeleteObject((HGDIOBJ)hMenuBoldFont); } void CNPopupMenu::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { // CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC); // CRect rcItem(lpDrawItemStruct->rcItem); // pDC->FillSolidRect(rcItem, RGB(255,0,0)); if (lpDrawItemStruct->CtlType == ODT_MENU) { UINT id = lpDrawItemStruct->itemID; UINT state = lpDrawItemStruct->itemState; bool bEnab = !(state & ODS_DISABLED); bool bSelect = (state & ODS_SELECTED) ? true : false; bool bChecked = (state & ODS_CHECKED) ? true : false; // David 08/04/98 - start - bold font handling bool bBold = (state & ODS_DEFAULT) ? true : false; // David 08/04/98 - end - bold font handling SpawnItem * pItem = (SpawnItem *) lpDrawItemStruct->itemData; if (pItem) { CDC * pDC = CDC::FromHandle(lpDrawItemStruct->hDC); CFont * pft; // David 08/04/98 - start - bold font handling if (!bBold) pft = CFont::FromHandle((HFONT) hMenuFont ? hMenuFont : hGuiFont); else pft = CFont::FromHandle((HFONT) hMenuBoldFont ? hMenuBoldFont : hGuiFont); // David 08/04/98 - end - bold font handling CFont * of = pDC->SelectObject(pft); CRect rc(lpDrawItemStruct->rcItem); // @@ if (bmVert.m_hObject) { BITMAP bm; bmVert.GetBitmap(&bm); if ((lpDrawItemStruct->itemAction & ODA_DRAWENTIRE) && !vertDrawn) { vertDrawn = TRUE; CDC dcMem; dcMem.CreateCompatibleDC(pDC); CBitmap *bmOld = dcMem.SelectObject(&bmVert); pDC->SelectClipRgn(NULL); CRect rcWhole; pDC->GetClipBox(rcWhole); pDC->BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcMem, 0, bm.bmHeight - rcWhole.Height(), SRCCOPY); } rc.left += bm.bmWidth; } CRect rcImage(rc), rcText(rc); rcImage.right = rcImage.left + rc.Height(); rcImage.bottom = rc.bottom; if (pItem->iCmd == -3) // is a separator { CPen pnDk(PS_SOLID,1,cr3dShadow); CPen pnLt(PS_SOLID,1,cr3dHilight); CPen * opn = pDC->SelectObject(&pnDk); pDC->MoveTo(rc.left + 2, rc.top + 2); pDC->LineTo(rc.right - 2, rc.top + 2); pDC->SelectObject(&pnLt); pDC->MoveTo(rc.left + 2, rc.top + 3); pDC->LineTo(rc.right - 2, rc.top + 3); pDC->SelectObject(opn); } /* else if (pItem->iCmd == -4) // is a title item { CString cs(pItem->cText), cs1; CRect rcBdr(rcText); if (bSelect && bEnab) { rcText.top ++; rcText.left += 2; } pDC->FillSolidRect(rcText, crMenu); pDC->DrawText(cs, rcText, DT_VCENTER|DT_CENTER|DT_SINGLELINE); if (bSelect && bEnab) pDC->Draw3dRect(rcBdr,cr3dShadow,cr3dHilight); }*/ else { rcText.left = rcImage.right + 1; int obk = pDC->SetBkMode(TRANSPARENT); COLORREF ocr; if (bSelect) { if (pItem->iImageIdx >= 0 || (state & ODS_CHECKED)) //pDC->FillSolidRect(rcText, crHighlight); pDC->Draw3dRect(rcText, cr3dShadow, cr3dHilight); // @@ else //pDC->FillSolidRect(rc, crHighlight); pDC->Draw3dRect(rc, cr3dShadow, cr3dHilight); // @@ //ocr = pDC->SetTextColor(crMenuTextSel); ocr = pDC->SetTextColor(crHighlight); // @@ } else { if (pItem->iImageIdx >= 0 || (state & ODS_CHECKED)) pDC->FillSolidRect(rcText, crMenu); else pDC->FillSolidRect(rc/*rcText*/, crMenu); ocr = pDC->SetTextColor(crMenuText); } if (pItem->iImageIdx >= 0) { int ay = (rcImage.Height() - szImage.cy) / 2; int ax = (rcImage.Width() - szImage.cx) / 2; if (bSelect && bEnab) pDC->Draw3dRect(rcImage,cr3dHilight,cr3dShadow); else { pDC->Draw3dRect(rcImage,crMenu,crMenu); } if (bEnab) { ilList.Draw(pDC, pItem->iImageIdx, CPoint(rcImage.left + ax, rcImage.top +ay), ILD_NORMAL); } else { HICON hIcon = ilList.ExtractIcon( pItem->iImageIdx ); pDC->DrawState( CPoint(rcImage.left + ax, rcImage.top + ay ), szImage, (HICON)hIcon, DST_ICON | DSS_DISABLED, (CBrush *)NULL ); DestroyIcon(hIcon); // @@ } } else { if (bChecked) { int ay = (rcImage.Height() - szImage.cy) / 2; int ax = (rcImage.Width() - szImage.cx) / 2; ilOther.Draw(pDC, 0, CPoint(rcImage.left + ax, rcImage.top + ay - 2), ILD_NORMAL); } } CString cs(pItem->cText), cs1; if (cs.Compare("dummy") == 0) pItem = pItem; CSize sz; sz = pDC->GetTextExtent(cs); int ay1 = (rcText.Height() - sz.cy) / 2; rcText.top += ay1; rcText.left += 2; rcText.right -= 15; int tf = cs.Find('\t'); if (tf >= 0) { cs1 = cs.Right(cs.GetLength() - tf - 1); cs = cs.Left(tf); if (!bEnab) { if (!bSelect) { CRect rcText1(rcText); rcText1.InflateRect(-1,-1); pDC->SetTextColor(cr3dHilight); pDC->DrawText(cs, rcText1, DT_VCENTER|DT_LEFT); pDC->DrawText(cs1, rcText1, DT_VCENTER|DT_RIGHT); pDC->SetTextColor(crGrayText); pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT); pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT); } else { pDC->SetTextColor(crMenu); pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT); pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT); } } else { pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT); pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT); } } else { if (!bEnab) { // if (!bSelect) // @@ { CRect rcText1(rcText); rcText1.InflateRect(-1,-1); pDC->SetTextColor(cr3dHilight); pDC->DrawText(cs, rcText1, DT_VCENTER|DT_LEFT|DT_EXPANDTABS); pDC->SetTextColor(crGrayText); pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS); } /* else { pDC->SetTextColor(crMenu); pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS); }*/ } else pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS); } pDC->SetTextColor(ocr); pDC->SetBkMode(obk); } pDC->SelectObject(of); } } } void CNPopupMenu::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct) { // lpMeasureItemStruct->itemWidth = 200; // lpMeasureItemStruct->itemHeight = 25; bool res = false; if (lpMeasureItemStruct->CtlType == ODT_MENU) { UINT id = lpMeasureItemStruct->itemID; SpawnItem * pItem = (SpawnItem *) lpMeasureItemStruct->itemData; if (pItem) { if (pItem->iCmd == -3) // is a separator { lpMeasureItemStruct->itemWidth = 10; lpMeasureItemStruct->itemHeight = 6; } else { CString cs(pItem->cText); if (!cs.IsEmpty()) { CClientDC dc(AfxGetMainWnd()); CFont * pft = CFont::FromHandle(hMenuFont ? hMenuFont : hGuiFont); CFont * of = dc.SelectObject(pft); CSize osz = dc.GetOutputTabbedTextExtent(cs,0,NULL); // @@ /*if (pItem->iCmd == -4) { CRect rci(0,0,0,0); dc.DrawText(cs, rci, DT_CALCRECT|DT_TOP|DT_VCENTER|DT_SINGLELINE); lpMeasureItemStruct->itemHeight = rci.Height(); lpMeasureItemStruct->itemWidth = rci.Width(); } else*/ { lpMeasureItemStruct->itemHeight = szImage.cy + 5; if (osz.cy > (int) lpMeasureItemStruct->itemHeight) lpMeasureItemStruct->itemHeight = (int) osz.cy; lpMeasureItemStruct->itemWidth = osz.cx + 2 + 15; lpMeasureItemStruct->itemWidth += lpMeasureItemStruct->itemHeight > (UINT) szImage.cx ? (UINT) lpMeasureItemStruct->itemHeight : (UINT) szImage.cx; } dc.SelectObject(of); } else { lpMeasureItemStruct->itemHeight = szImage.cy + 5; lpMeasureItemStruct->itemWidth = 100; } } if (bmVert.m_hObject) { BITMAP bm; bmVert.GetBitmap(&bm); lpMeasureItemStruct->itemWidth += bm.bmWidth; } } } } bool CNPopupMenu::CreateBoldFont() { if (hMenuBoldFont) ::DeleteObject((HGDIOBJ)hMenuBoldFont); LOGFONT lgFont; ::GetObject (hMenuFont ? hMenuFont : hGuiFont, sizeof (lgFont), &lgFont); lgFont.lfWeight = FW_BOLD; hMenuBoldFont = CreateFontIndirect (&lgFont); return !!hMenuBoldFont; } bool CNPopupMenu::AddToolBarResource(unsigned int resId) { // David 08/04/98 - start - put CMenuSpawn in DLL HINSTANCE hInst = AfxFindResourceHandle (MAKEINTRESOURCE(resId), RT_TOOLBAR); if (!hInst) return false; // David 08/04/98 - end - put CMenuSpawn in DLL HRSRC hRsrc = ::FindResource(/*AfxGetResourceHandle()*/hInst, MAKEINTRESOURCE(resId), RT_TOOLBAR); if (hRsrc == NULL) return false; HGLOBAL hGlb = ::LoadResource(/*AfxGetResourceHandle()*/hInst, hRsrc); if (hGlb == NULL) return false; ToolBarData* pTBData = (ToolBarData*) ::LockResource(hGlb); if (pTBData == NULL) return false; ASSERT(pTBData->wVersion == 1); CBitmap bmp; bmp.LoadBitmap(resId); int nBmpItems = ilList.Add(&bmp, RGB(192,192,192)); bmp.DeleteObject(); WORD* pItem = (WORD*)(pTBData+1); for(int i=0; i<pTBData->wItemCount; i++, pItem++) { if(*pItem != ID_SEPARATOR) AddImageItem(nBmpItems++, (WORD) *pItem); } // ** it seem that Windows doesn't free these resource (from Heitor Tome) ::UnlockResource(hGlb); ::FreeResource(hGlb); // ** return true; } bool CNPopupMenu::LoadToolBarResource(unsigned int resId) { //David 08/04/98 - start - put CMenuSpawn in DLL HINSTANCE hInst = AfxFindResourceHandle (MAKEINTRESOURCE(resId), RT_TOOLBAR); if (!hInst) return false; //David 08/04/98 - end - put CMenuSpawn in DLL HRSRC hRsrc = ::FindResource(/*AfxGetResourceHandle()*/hInst, MAKEINTRESOURCE(resId), RT_TOOLBAR); if (hRsrc == NULL) return false; HGLOBAL hGlb = ::LoadResource(/*AfxGetResourceHandle()*/hInst, hRsrc); if (hGlb == NULL) return false; ToolBarData* pTBData = (ToolBarData*) ::LockResource(hGlb); if (pTBData == NULL) return false; ASSERT(pTBData->wVersion == 1); szImage.cx = (int) pTBData->wWidth; szImage.cy = (int) pTBData->wHeight; if (ilList.Create(szImage.cx, szImage.cy, ILC_COLOR4|ILC_MASK, pTBData->wItemCount, 0) == false) return false; ilList.SetBkColor(cr3dFace); CBitmap bmp; bmp.LoadBitmap(resId); ilList.Add(&bmp, RGB(192,192,192)); bmp.DeleteObject(); WORD* pItem = (WORD*)(pTBData+1); int nBmpItems = 0; for(int i=0; i<pTBData->wItemCount; i++, pItem++) { if(*pItem != ID_SEPARATOR) AddImageItem(nBmpItems++, (WORD) *pItem); } // ** it seem that Windows doesn't free these resource (from Heitor Tome) ::UnlockResource(hGlb); ::FreeResource(hGlb); // ** return true; } void CNPopupMenu::AddImageItem(const int idx, WORD cmd) { if (iImageItem == 0) pImageItem = (ImageItem *) GlobalAlloc(GPTR, sizeof(ImageItem)); else pImageItem = (ImageItem *) GlobalReAlloc((HGLOBAL) pImageItem, sizeof(ImageItem) * (iImageItem + 1), GMEM_MOVEABLE|GMEM_ZEROINIT); ASSERT(pImageItem); pImageItem[iImageItem].iCmd = (int) cmd; pImageItem[iImageItem].iImageIdx = idx; iImageItem ++; } void CNPopupMenu::RemapMenu(CMenu * pMenu) { static int iRecurse = 0; iRecurse ++; ASSERT(pMenu); int nItem = pMenu->GetMenuItemCount(); while ((--nItem)>=0) { UINT itemId = pMenu->GetMenuItemID(nItem); if (itemId == (UINT) -1) { CMenu *pops = pMenu->GetSubMenu(nItem); if (pops) RemapMenu(pops); if (iRecurse > 0) { CString cs; pMenu->GetMenuString(nItem, cs, MF_BYPOSITION); if (cs != "") { SpawnItem * sp = AddSpawnItem(cs, (iRecurse == 1) ? -4 : -2); pMenu->ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW, (UINT) -1, (LPCTSTR)sp); } } } else { if (itemId != 0) { UINT oldState = pMenu->GetMenuState(nItem,MF_BYPOSITION); if (!(oldState&MF_OWNERDRAW) && !(oldState&MF_BITMAP)) { ASSERT(oldState != (UINT)-1); CString cs; pMenu->GetMenuString(nItem, cs, MF_BYPOSITION); SpawnItem * sp = AddSpawnItem(cs, itemId); pMenu->ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW|oldState, (LPARAM)itemId, (LPCTSTR)sp); } } else { UINT oldState = pMenu->GetMenuState(nItem,MF_BYPOSITION); if (!(oldState&MF_OWNERDRAW) && !(oldState&MF_BITMAP)) { ASSERT(oldState != (UINT)-1); SpawnItem * sp = AddSpawnItem("--", -3); pMenu->ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW|oldState, (LPARAM)itemId, (LPCTSTR)sp); } } } } iRecurse --; } CNPopupMenu::SpawnItem * CNPopupMenu::AddSpawnItem(const char * txt, const int cmd) { if (iSpawnItem == 0) pSpawnItem = (SpawnItem **) GlobalAlloc(GPTR, sizeof(SpawnItem)); else pSpawnItem = (SpawnItem **) GlobalReAlloc((HGLOBAL) pSpawnItem, sizeof(SpawnItem) * (iSpawnItem + 1), GMEM_MOVEABLE|GMEM_ZEROINIT); ASSERT(pSpawnItem); SpawnItem * p = new SpawnItem; ASSERT(p); pSpawnItem[iSpawnItem] = p; lstrcpy(p->cText, txt); p->iCmd = cmd; if (cmd >= 0) p->iImageIdx = FindImageItem(cmd); else p->iImageIdx = cmd; iSpawnItem ++; return p; } int CNPopupMenu::FindImageItem(const int cmd) { for (int t = 0; t < iImageItem; t++) if (pImageItem[t].iCmd == cmd) return pImageItem[t].iImageIdx; return -1; } void CNPopupMenu::EnableMenuItems(CMenu * pMenu, CWnd * pParent) { ASSERT(pMenu); ASSERT(pParent); int nItem = pMenu->GetMenuItemCount(); CCmdUI state; state.m_pMenu = pMenu; state.m_nIndex = nItem-1; state.m_nIndexMax = nItem; while ((--nItem)>=0) { UINT itemId = pMenu->GetMenuItemID(nItem); if (itemId == (UINT) -1) { CMenu *pops = pMenu->GetSubMenu(nItem); if (pops) EnableMenuItems(pops, pParent); } else { if (itemId != 0) { state.m_nID = itemId; pParent->OnCmdMsg(itemId, CN_UPDATE_COMMAND_UI, &state, NULL); state.DoUpdate(pParent, true); } } state.m_nIndex = nItem-1; } } void CNPopupMenu::modifyMenu(UINT itemId, UINT bitmap, BOOL byCmd) { int index; if (!imageHash.Lookup(bitmap, index)) { CBitmap bm; bm.LoadBitmap(bitmap); index = ilList.Add(&bm, RGB(192, 192, 192)); imageHash.SetAt(bitmap, index); } modifyMenuInternal(itemId, index, byCmd); } void CNPopupMenu::modifyMenu(UINT itemId, HICON icon) { int index; if (!bitmapHash.Lookup(icon, index)) { index = ilList.Add(icon); bitmapHash.SetAt(icon, index); } modifyMenuInternal(itemId, index, TRUE); } void CNPopupMenu::modifyMenuInternal(UINT itemId, int imageIndex, BOOL byCmd) { if (byCmd) { UINT oldState = GetMenuState(itemId,MF_BYCOMMAND); if (!(oldState&MF_OWNERDRAW) && !(oldState&MF_BITMAP)) { ASSERT(oldState != (UINT)-1); CString cs; GetMenuString(itemId, cs, MF_BYCOMMAND); SpawnItem * sp = AddSpawnItem(cs, itemId); sp->iImageIdx = imageIndex; ModifyMenu(itemId,MF_BYCOMMAND|MF_OWNERDRAW|oldState, (LPARAM)itemId, (LPCTSTR)sp); } } else { UINT nItem = itemId; itemId = GetMenuItemID(nItem); if (itemId == (UINT) -1) { CString cs; GetMenuString(nItem, cs, MF_BYPOSITION); if (cs != "") { SpawnItem * sp = AddSpawnItem(cs, -4); sp->iImageIdx = imageIndex; ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW, (UINT) -1, (LPCTSTR)sp); } } else { if (itemId != 0) { UINT oldState = GetMenuState(nItem,MF_BYPOSITION); if (!(oldState&MF_OWNERDRAW) && !(oldState&MF_BITMAP)) { ASSERT(oldState != (UINT)-1); CString cs; GetMenuString(nItem, cs, MF_BYPOSITION); SpawnItem * sp = AddSpawnItem(cs, itemId); sp->iImageIdx = imageIndex; ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW|oldState, (LPARAM)itemId, (LPCTSTR)sp); } } else { UINT oldState = GetMenuState(nItem,MF_BYPOSITION); if (!(oldState&MF_OWNERDRAW) && !(oldState&MF_BITMAP)) { ASSERT(oldState != (UINT)-1); SpawnItem * sp = AddSpawnItem("--", -3); ModifyMenu(nItem,MF_BYPOSITION|MF_OWNERDRAW|oldState, (LPARAM)itemId, (LPCTSTR)sp); } } } } } void CNPopupMenu::appendMenu(UINT id, UINT bitmap, LPCTSTR str) { AppendMenu(MF_BYCOMMAND, id, str); modifyMenu(id, bitmap); } void CNPopupMenu::appendMenu(UINT id, UINT bitmap, UINT strID) { CString str; str.LoadString(strID); appendMenu(id, bitmap, str); } void CNPopupMenu::setVertBitmap(UINT bitmap) { for (int i = GetMenuItemCount() - 1; i >= 0; i--) { if (GetMenuItemID(i) == 0) { SpawnItem * sp = AddSpawnItem("--", -3); ModifyMenu(i, MF_BYPOSITION | MF_OWNERDRAW | MF_SEPARATOR, 0, (LPCTSTR) sp); } } bmVert.LoadBitmap(bitmap); }
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 693 ] ] ]
057bb9a92ae704495535c8392a3459c97b27f46b
789bfae90cbb728db537b24eb9ab21c88bda2786
/source/GameLostNotVisibleWaitStateClass.h
499c1c38581ce492abca96367d50db0c55c10eec
[ "MIT" ]
permissive
Izhido/bitsweeper
b89db2c2050cbc82ea60d31d2f31b041a1e913a3
a37902c5b9ae9c25ee30694c2ba0974fd235090e
refs/heads/master
2021-01-23T11:49:21.723909
2011-12-24T22:43:30
2011-12-24T22:43:30
34,614,275
0
2
null
null
null
null
UTF-8
C++
false
false
460
h
#ifndef GAMELOSTNOTVISIBLEWAITSTATECLASS_H #define GAMELOSTNOTVISIBLEWAITSTATECLASS_H #include "StateClass.h" #define GAME_LOST_NOT_VISIBLE_WAIT_STATE 28 class GameLostNotVisibleWaitStateClass : public StateClass { public: GameLostNotVisibleWaitStateClass(); void Start(class CommonDataClass* CommonData); void Run(class CommonDataClass* CommonData); void Draw(CommonDataClass* CommonData); private: int Count; }; #endif
[ "[email protected]@66f87ebb-1a6f-337b-3a26-6cadc16acdcf" ]
[ [ [ 1, 25 ] ] ]
a31b42d2e53204f85698897991ec5ade503ef40d
102d8810abb4d1c8aecb454304ec564030bf2f64
/TP3/Tanque/Tanque/Tanque/SDLHelper.h
d6def9202155d44bc6fa9deddd6a835324e66d97
[]
no_license
jfacorro/tp-taller-prog-1-fiuba
2742d775b917cc6df28188ecc1f671d812017a0a
a1c95914c3be6b1de56d828ea9ff03e982560526
refs/heads/master
2016-09-14T04:32:49.047792
2008-07-15T20:17:27
2008-07-15T20:17:27
56,912,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,719
h
#include "SDL.h" #include "Common.h" #include "Exception.h" #include "StringHelper.h" #include "windows.h" #ifndef SDLHelper_h #define SDLHelper_h typedef struct _Color { Uint8 R; Uint8 G; Uint8 B; } Color; typedef struct _Resolution { int w; int h; } Resolution; class Texture { private: char * id; char * filePath; SDL_Surface * bitmap; public: Texture(){}; Texture(char * id, char * filePath); Texture::~Texture(); char * GetId() { return this->id; }; void SetId(char * id) { this->id = StringHelper::Substring(id, 0, strlen(id)); }; char * GetFilePath() { return this->filePath; }; void SetFilePath(char * filePath) { this->filePath = StringHelper::Substring(filePath, 0, strlen(filePath)); }; SDL_Surface * GetBitmap() { return this->bitmap; }; void SetBitmap(SDL_Surface * bitmap) { this->bitmap = bitmap; }; }; class Configuration { private: Resolution resolucion; Color colorFondoGraf; SDL_Surface * textura; Color colorLinea; Color colorFondo; bool isDefaultConfig; public: Configuration(); /// Accessors Resolution GetResolucion() { return this->resolucion; }; void SetResolucion(Resolution resolucion) { this->isDefaultConfig = false; this->resolucion = resolucion; }; Color GetColorFondoGraf() { return this->colorFondoGraf; }; void SetColorFondoGraf(Color colorFondoGraf) { this->isDefaultConfig = false; this->colorFondoGraf = colorFondoGraf; }; SDL_Surface * GetTextura() { return this->textura; }; void SetTextura(SDL_Surface * textura); Color GetColorLinea() { return this->colorLinea; }; void SetColorLinea(Color colorLinea) { this->isDefaultConfig = false; this->colorLinea = colorLinea; }; Color GetColorFondo() { return this->colorFondo; }; void SetColorFondo(Color colorFondo) { this->isDefaultConfig = false; this->colorFondo = colorFondo; }; bool GetIsDefaultConfig() { return this->isDefaultConfig; }; }; class SDLHelper { private: SDL_Surface * screen; Configuration configuration; void DrawPixel(SDL_Surface * screen, int x, int y, Uint8 R, Uint8 G, Uint8 B); void GetPixel(SDL_Surface * screen, int x, int y, Uint8* R, Uint8* G, Uint8* B); HANDLE mutex; public: SDLHelper(); ~SDLHelper() {}; void Initialize(); void InitializeVideo(Configuration config); bool VideoInitialized() { return this->screen != NULL; }; void Quit(); void DrawSquare ( int x , int y , int l , Color color , SDL_Surface* texture , char * nodeId ); void DrawCircle ( int x , int y , int r , Color color , SDL_Surface* texture , char * nodeId ); void DrawRectangle ( int x , int y , int b , int h , Color color , SDL_Surface* texture , char * nodeId ); void DrawSegment ( int x1 , int y1 , int x2 , int y2 , Color color , char * nodeId ); SDL_PixelFormat * GetPixelFormat() { return this->screen->format; }; void Refresh(); void WaitForKey(); bool GetKeyPress(SDL_keysym & key); Configuration GetConfiguration() { return this->configuration; }; static SDL_Surface * LoadImage(char * imgPath); static Color GetDefaultFrontColor() { Color color; color.R = 0; color.G = 0; color.B = 0; return color; }; static Color GetDefaultBackColor() { Color color; color.R = 255; color.G = 255; color.B = 255; return color; }; static Resolution ResolutionByWidth(int width); static SDL_Surface * SDLResizeBitmap(SDL_Surface * image, int new_w, int new_h, int filter = 7); static SDL_Surface * SDLRotateBitmap(SDL_Surface * image, double angle, int filter = 7); }; #endif
[ "juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb" ]
[ [ [ 1, 138 ] ] ]
dff8ed98611da8f5765760311e365c3b011540fa
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/MapRenderer/src/renderer/MapBuffer.cpp
6ffa97cb5d926814d1f606de2d639d619b7d4b63
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
cpp
// // File: MapBuffer.cpp // Created by: Alexander Oster - [email protected] // #include "renderer/MapBuffer.h" #include "Config.h" #include "Debug.h" #include "include.h" //#include "renderer/Camera.h" using namespace std; cMapbuffer * pMapbuffer = NULL; cMapbuffer::cMapbuffer() { } cMapbuffer::~cMapbuffer() { Clear(); } void cMapbuffer::Clear(void) { MapBuffer_t::iterator iter; for (iter = root.begin(); iter != root.end(); iter++) delete(*iter).second; root.clear(); cache.clear(); } cMapblock *cMapbuffer::Get(int x, int y) { if((x < 0) || (y < 0)) return NULL; MapBuffer_t::iterator iter; iter = root.find((Uint32) x << 16 | y); if(iter == root.end()) return NULL; else return (*iter).second; } void cMapbuffer::Add(cMapblock * block) { if(!block) { pDebug.Log("NULL block in Mapbuffer::Add(Mapblock *)", __FILE__, __LINE__, LEVEL_CRITICAL); return; } if ((nConfig::cache_block > 0) && (cache.size() >= nConfig::cache_block)) { cMapblock * nblock = cache[0]; root.erase(nblock->blockx << 16 | nblock->blocky); cache.erase(cache.begin()); delete nblock; } Uint16 x = block->blockx; Uint16 y = block->blocky; root.insert(make_pair((Uint32) x << 16 | y, block)); cache.push_back(block); } cMapblock *cMapbuffer::CreateBlock(int x, int y) { cMapblock *block; if ((x < 0) || (y < 0)) return NULL; if((block = Get(x, y))) /* check buffer for block */ return block; /* if it is not there, generate new */ block = new cMapblock(); block->Generate(x, y); Add(block); return block; } void cMapbuffer::FreeBuffer(int blockx, int blocky, int radius) { MapBuffer_t::iterator iter; for (iter = root.begin(); iter != root.end(); iter++) { if ((iter->second->blockx < blockx - radius) || (iter->second->blockx > blockx + radius) || (iter->second->blocky < blocky - radius) || (iter->second->blocky > blocky + radius)) { delete iter->second; root.erase(iter); return; } } }
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 116 ] ] ]
564e5c22e148ac5156dc99f1fdf411f1829d022c
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Utility/handle.hpp
78fa1a6931534275746abcd9dedf9622d53012d8
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
588
hpp
#ifndef __SLON_ENGINE_UTILITY_HANDLE_H__ #define __SLON_ENGINE_UTILITY_HANDLE_H__ namespace slon { /** Handle for object for fast comparison and access to implementation class. */ struct handle { handle(void* pObj_ = 0) : pObj(pObj_) {} bool operator == (const handle& rhs) const { return pObj == rhs.pObj; } bool operator != (const handle& rhs) const { return pObj != rhs.pObj; } bool operator < (const handle& rhs) const { return pObj < rhs.pObj; } void* pObj; }; } // namespace slon #endif // __SLON_ENGINE_UTILITY_HANDLE_H__
[ "devnull@localhost" ]
[ [ [ 1, 22 ] ] ]
5f212f75dbf2e3dc73094e67f8b03ea863fdc2b3
2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83
/BasicOgreFramework/PhysxSDK/Samples/SampleCommonCode/src/Timing.cpp
cdf19d12d603470b235c18bc412389f524ddbc44
[]
no_license
mgq812/simengines-g2-code
5908d397ef2186e1988b1d14fa8b73f4674f96ea
699cb29145742c1768857945dc59ef283810d511
refs/heads/master
2016-09-01T22:57:54.845817
2010-01-11T19:26:51
2010-01-11T19:26:51
32,267,377
0
0
null
null
null
null
UTF-8
C++
false
false
2,158
cpp
#include <stdio.h> #ifdef WIN32 # define NOMINMAX # include <windows.h> #endif #if defined(_XBOX) # include <xtl.h> #endif #include "Nx.h" #include "Timing.h" #if defined(__CELLOS_LV2__) #include <sys/sys_time.h> #include <sys/time_util.h> unsigned long timeGetTime() { static uint64_t ulScale=0; uint64_t ulTime; if (ulScale==0) { ulScale = sys_time_get_timebase_frequency() / 1000; } #ifdef __SNC__ ulTime=__builtin_mftb(); #else asm __volatile__ ("mftb %0" : "=r" (ulTime) : : "memory"); #endif return ulTime/ulScale; } #elif defined(LINUX) #include <sys/time.h> unsigned long timeGetTime() { timeval tim; gettimeofday(&tim, NULL); unsigned long ms = (tim.tv_sec*1000u)+(long)(tim.tv_usec/1000.0); return ms; } #elif defined(_XBOX) unsigned long timeGetTime() { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); unsigned long long ticksPerMillisecond = freq.QuadPart/1000; LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return (unsigned long)(counter.QuadPart/ticksPerMillisecond); } #endif float getCurrentTime() { unsigned int currentTime = timeGetTime(); return (float)(currentTime)*0.001f; } #if !defined(LINUX) float getElapsedTime() { static LARGE_INTEGER previousTime; static LARGE_INTEGER freq; static bool init = false; if(!init){ QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&previousTime); init=true; } LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); unsigned long long elapsedTime = currentTime.QuadPart - previousTime.QuadPart; previousTime = currentTime; return (float)(elapsedTime)/(freq.QuadPart); } #else float getElapsedTime() { static timeval previousTime; static bool init = false; if(!init){ gettimeofday(&previousTime, NULL); init=true; } timeval currentTime; gettimeofday(&currentTime, NULL); double elapsedTime = (currentTime.tv_sec+currentTime.tv_usec/1000000.0) - (previousTime.tv_sec+previousTime.tv_usec/1000000.0); previousTime = currentTime; return (float)elapsedTime; } #endif
[ "erucarno@789472dc-e1c3-11de-81d3-db62269da9c1" ]
[ [ [ 1, 104 ] ] ]
d30015833046b5167b99dd804f1cc297a7726517
03b001592deac331cc5f277f6365501f7b3871de
/UVa/wertyu.cpp
769b43fa6f534e195850b4f7a25145b61b852b38
[]
no_license
raphamontana/usp-raphael
1ba2cb88737ae1730dd6e8c62a5c56f3da4cfe25
5ffff4ae5c60b69c1d0535d4c79c1c7dfa6dbf25
refs/heads/master
2021-01-01T06:38:42.606950
2010-05-11T23:59:08
2010-05-11T23:59:08
32,346,740
0
0
null
null
null
null
ISO-8859-10
C++
false
false
1,682
cpp
/* ========================================================================= */ /* Raphael Montanari nลก USP: 5890010 */ /* WERTYU */ /* ========================================================================= */ #include <stdio.h> #include <string.h> #include <map> using namespace std; int main (void) { map <char, char> m; // 1ยฐ linha m['1'] = '`'; m['2'] = '1'; m['3'] = '2'; m['4'] = '3'; m['5'] = '4'; m['6'] = '5'; m['7'] = '6'; m['8'] = '7'; m['9'] = '8'; m['0'] = '9'; m['-'] = '0'; m['='] = '-'; // 2ยฐ linha m['W'] = 'Q'; m['E'] = 'W'; m['R'] = 'E'; m['T'] = 'R'; m['Y'] = 'T'; m['U'] = 'Y'; m['I'] = 'U'; m['O'] = 'I'; m['P'] = 'O'; m['['] = 'P'; m[']'] = '['; m['\\'] = ']'; // 3ยฐ linha m['S'] = 'A'; m['D'] = 'S'; m['F'] = 'D'; m['G'] = 'F'; m['H'] = 'G'; m['J'] = 'H'; m['K'] = 'J'; m['L'] = 'K'; m[';'] = 'L'; m['\''] = ';'; // 4ยฐ linha m['X'] = 'Z'; m['C'] = 'X'; m['V'] = 'C'; m['B'] = 'V'; m['N'] = 'B'; m['M'] = 'N'; m[','] = 'M'; m['.'] = ','; m['/'] = '.'; // casos especiais m[' '] = ' '; m['\n'] = '\n'; char linha [1024]; int i, j, tamanho; while (fgets (linha, 1024, stdin) != 0) { tamanho = strlen(linha); for (i = 0; i < tamanho; i++) printf ("%c", m[linha [i]]); } return 0; }
[ "[email protected]@ba5301f2-bfe1-11dd-871e-457e4afae058" ]
[ [ [ 1, 72 ] ] ]
77e1eb20f33545f8d7df786526afd3f832a444f0
b2c8fcf00f878362556f107b40d49825f38d7dfd
/main.cpp
8ca2cf127c4a873d0063ed9c4e15cc5ed6d926c9
[]
no_license
Gandi24/geronad
ba9716c169cd6ed5da315e9a0c6a266760ca9277
77ed9e706f106caadd90209f6a9570aaf18ec6d3
refs/heads/master
2020-05-17T14:45:42.674765
2011-04-23T18:44:23
2011-04-23T18:44:23
1,654,154
0
0
null
null
null
null
ISO-8859-2
C++
false
false
978
cpp
/* * main.cpp * * Created on: 23-04-2011 * Author: Gandi */ /* * Kilka sugestii co do tworzenia przez nas projektu. * * 1. Wszystkie commity komentujcie krรณtko i tresciwie. * * 2. Jesli zaczynacie tworzyc nowa klase lub funkcje, to pierwsze co powinno sie zrobic, * to dodanie komentarza na temat co ta klasa/metoda ma robic i co pobierac. * * 3. Unikajmy nazw tmp=1, a=cos, dupa1==dupa2. Mam nadzieje, ze rozumiecie o co mi chodzi ;) * * 4. Jak najwiecej rzeczy, ktore sie da, piszmy w klasach. Latwiej jest z pliku .h importowac * klase, stworzyc jej instancje i dzialac juz na jej metodach, zamiast tworzyc setke funkcji, * a potem sie w nich gubic. Bo bedziemy sie gubic przy tylu osobach, tego nie da sie ukryc. * * 5. Dzielmy pliki na mniejsze. Zamiast stworzyc plik o 1000 linijek, lepiej stworzyc 4 po 250 * (o ile sie da oczywiscie). * * 6. Z czym sie nie zgadzacie lub co widzicie inaczej - piszcie. * * */
[ [ [ 1, 28 ] ] ]
af968307aec41471efdb1645484a59634a833c4a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndPvp.h
90f13f9d21709d3209ca539f4fbaac63c6750012
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,273
h
#ifndef __WNDPVP__H #define __WNDPVP__H class CWndPvp : public CWndNeuz { public: // CWndPvpBase m_wndStateBase; CWndPvp(); ~CWndPvp(); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnDraw( C2DRender* p2DRender ); virtual void OnInitialUpdate(); virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ); virtual void OnSize( UINT nType, int cx, int cy ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual void OnLButtonDown( UINT nFlags, CPoint point ); }; class CWndPenaltyPK : public CWndNeuz { public: u_long m_uIdPlayer; CWndPenaltyPK(); ~CWndPenaltyPK(); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnDraw( C2DRender* p2DRender ); virtual void OnInitialUpdate(); virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ); virtual void OnSize( UINT nType, int cx, int cy ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual void OnLButtonDown( UINT nFlags, CPoint point ); }; #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 38 ] ] ]
af0ec355de324835193d952adf8394d53fe87b63
c79def23ba8a4ad23bb51068d303f3ead942ed2a
/include/SuperOutputXML.h
1576b72ee32b5ba8697d781d5b1bd79f0dab5253
[ "BSD-3-Clause" ]
permissive
programmingisgood/superprofiler
a519020250ed236331219dc5da7adf9c8cf8863c
1fa7d1785ca3c91457c6fb634ab027290a2fa8e6
refs/heads/master
2021-01-19T15:02:08.250385
2009-08-13T18:37:05
2009-08-13T18:37:05
32,189,128
0
0
null
null
null
null
UTF-8
C++
false
false
2,419
h
/** Copyright (c) 2009, Brian Cronin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #ifndef SUPEROUTPUTXML_H #define SUPEROUTPUTXML_H #include "SuperOutput.h" #include <fstream> namespace SuperProfiler { class SuperOutputXML : public SuperOutput { public: SuperOutputXML(const std::string & fileName); ~SuperOutputXML(); void OutputFunctionData(SuperFuncDataList & funcData, double totalRunTime); void OutputCallTree(SuperStackNode * stack); private: //No default construction! SuperOutputXML(); //No copies! SuperOutputXML(const SuperOutputXML &); const SuperOutputXML & operator=(const SuperOutputXML &); void OutputNode(SuperStackNode * outputNode, size_t currDepth, std::ofstream & outputFile); /** * Simply outputs tabs character to the stream. **/ void OutputTabs(size_t howMany, std::ofstream & outputFile); std::string ReplaceXMLSpecialCharacters(const std::string & search); std::ofstream outputFile; }; } #endif
[ "programmingisgood@1faae0e8-f407-11dd-984d-ab748d24aa7e" ]
[ [ [ 1, 60 ] ] ]
45d0435dd27dec028efef0090f346b494121a8c6
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/detail/other.hpp
19c2ff9d0275bd8a2e9b26564027a72eb180baae
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
3,168
hpp
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_OTHER_HPP_INCLUDED #define LUABIND_OTHER_HPP_INCLUDED // header derived from source code found in Boost.Python // Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #include <luabind/config.hpp> #include <boost/config.hpp> namespace luabind { template<class T> struct other { typedef T type; }; } #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION namespace luabind { namespace detail { template<typename T> class unwrap_other { public: typedef T type; }; template<typename T> class unwrap_other<other<T> > { public: typedef T type; }; } } // namespace luabind::detail # else // no partial specialization #include <boost/type.hpp> namespace luabind { namespace detail { typedef char ( &yes_other_t )[1]; typedef char ( &no_other_t )[2]; no_other_t is_other_test( ... ); template<typename T> yes_other_t is_other_test( type_< other<T> > ); template<bool wrapped> struct other_unwrapper { template <class T> struct apply { typedef T type; }; }; template<> struct other_unwrapper<true> { template <class T> struct apply { typedef typename T::type type; }; }; template<typename T> class is_other { public: BOOST_STATIC_CONSTANT( bool, value = ( sizeof( detail::is_other_test( type_<T>() ) ) == sizeof( detail::yes_other_t ) ) ); }; template <typename T> class unwrap_other : public detail::other_unwrapper < is_other<T>::value >::template apply<T> {}; } } // namespace luabind::detail #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #endif // LUABIND_OTHER_HPP_INCLUDED
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 125 ] ] ]
95b11d468d93af36642f5ccbb4901894bec6d77b
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleGui/TControl.cpp
f63b8a57b966f30bc3a060b083f92eed178d84b2
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
768
cpp
/* * TControl.cpp * TootleGui * * Created by Graham Reeves on 14/01/2010. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include "TControl.h" #include "TWindow.h" //------------------------------------------------------ // //------------------------------------------------------ TLGui::TControl::TControl(TRefRef ControlRef) : m_ControlRef ( ControlRef ), m_pParent ( NULL ) { } //------------------------------------------------------ // initialise - this is seperated from the constructor so we can use virtual functions //------------------------------------------------------ bool TLGui::TControl::Initialise(TWindow& Parent) { Parent.AddChild( *this ); m_pParent = &Parent; return true; }
[ [ [ 1, 33 ] ] ]
3a85296f8a92403ea9854216516121e5dc9dff04
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Targets/FMath/include/fvec.h
4f8b2f1027d29127905a888be8075d5e386c0739
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
3,551
h
#ifndef _FVEC_H_ #define _FVEC_H_ #include "fmath.h" namespace fmath { class fvec3 { public: fvec3( void ) { } fvec3( fixed x, fixed y, fixed z ) { m_vec[0] = x; m_vec[1] = y; m_vec[2] = z; } fvec3( const fixed* vec ) { m_vec[0] = vec[0]; m_vec[1] = vec[1]; m_vec[2] = vec[2]; } fvec3( const fmath::fvec3& vec ) { m_vec[0] = vec.m_vec[0]; m_vec[1] = vec.m_vec[1]; m_vec[2] = vec.m_vec[2]; } operator const fixed*( void ) const { return &m_vec[0]; } fmath::fixed& operator[]( int index ) { return m_vec[index]; } const fmath::fixed& operator[]( int index ) const { return m_vec[index]; } bool operator==( const fmath::fvec3& vec ) const { return (m_vec[0] == vec.m_vec[0]) && (m_vec[1] == vec.m_vec[1]) && (m_vec[2] == vec.m_vec[2]); } bool operator!=( const fmath::fvec3& vec ) const { return !(m_vec[0] == vec.m_vec[0]) && (m_vec[1] == vec.m_vec[1]) && (m_vec[2] == vec.m_vec[2]); } fmath::fvec3& operator=( const fmath::fvec3& vec ) { m_vec[0] = vec.m_vec[0]; m_vec[1] = vec.m_vec[1]; m_vec[2] = vec.m_vec[2]; return *this; } fmath::fvec3 operator+( const fmath::fvec3& vec ) const { return fmath::fvec3(m_vec[0] + vec.m_vec[0], m_vec[1] + vec.m_vec[1], m_vec[2] + vec.m_vec[2]); } fmath::fvec3 operator-( const fmath::fvec3& vec ) const { return fmath::fvec3(m_vec[0] - vec.m_vec[0], m_vec[1] - vec.m_vec[1], m_vec[2] - vec.m_vec[2]); } fmath::fvec3 operator*( const fmath::fixed& scalar ) const { return fmath::fvec3(fmath::multiply(m_vec[0], scalar), fmath::multiply(m_vec[1], scalar), fmath::multiply(m_vec[2], scalar)); } fmath::fvec3& operator+=( const fmath::fvec3& vec ) { m_vec[0] += vec.m_vec[0]; m_vec[1] += vec.m_vec[1]; m_vec[2] += vec.m_vec[2]; return *this; } fmath::fvec3& operator-=( const fmath::fvec3& vec ) { m_vec[0] -= vec.m_vec[0]; m_vec[1] -= vec.m_vec[1]; m_vec[2] -= vec.m_vec[2]; return *this; } fmath::fvec3& operator*=( const fmath::fixed& scalar ) { m_vec[0] = fmath::multiply(m_vec[0], scalar); m_vec[1] = fmath::multiply(m_vec[1], scalar); m_vec[2] = fmath::multiply(m_vec[2], scalar); return *this; } protected: fmath::fixed m_vec[3]; }; inline fmath::fixed fvec3dot( const fmath::fvec3& a, const fmath::fvec3& b ) { return (fmath::multiply(a[0], b[0]) + fmath::multiply(a[1], b[1]) + fmath::multiply(a[2], b[2])); } inline fmath::fvec3 fvec3cross( const fmath::fvec3& a, const fmath::fvec3& b ) { return fmath::fvec3(fmath::multiply(a[1], b[2]) - fmath::multiply(b[1], a[2]), fmath::multiply(a[2], b[0]) - fmath::multiply(b[2], a[0]), fmath::multiply(a[0], b[1]) - fmath::multiply(b[0], a[1])); } } #endif
[ [ [ 1, 166 ] ] ]
7e4de604a764d5c1c21d885bb2ba79eb382f21ca
98740362033fe20f921c8e3f55cb99bc7045597f
/library/cplusplushelper.cpp
de91d7f074c3cfa0975d3809459d495e59314476
[]
no_license
ee-444/ArduinoRoverLib
bf0d799d5601740f7ca5a4668d1017f730649099
edebdd8a0dd5d4e4de01a01f122e1350b73e7333
refs/heads/master
2021-01-22T14:33:36.311184
2011-04-04T07:06:35
2011-04-04T07:06:35
1,565,914
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
#include "cplusplushelper.h" #include <stdlib.h> void __cxa_pure_virtual(void) { } int __cxa_guard_acquire(__guard *g) { return !*(char *)(g); } void __cxa_guard_release (__guard *g) { *(char *)g = 1; } void __cxa_guard_abort (__guard *) { } void* operator new(size_t size) { return malloc(size); } void operator delete(void * ptr) { free(ptr); }
[ [ [ 1, 35 ] ] ]
17aef4f7537de7cf19ecc11a63281fa0c8b6ae3b
d64ed1f7018aac768ddbd04c5b465c860a6e75fa
/DisplayList.cpp
87c85be95928cf8b8dc3e92535b7d0a46a48ff8a
[]
no_license
roc2/archive-freepcb-codeproject
68aac46d19ac27f9b726ea7246cfc3a4190a0136
cbd96cd2dc81a86e1df57b86ce540cf7c120c282
refs/heads/master
2020-03-25T00:04:22.712387
2009-06-13T04:36:32
2009-06-13T04:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
65,333
cpp
// DisplayList.cpp : implementation of class CDisplayList // // this is a linked-list of display elements // each element is a primitive graphics object such as a line-segment, // circle, annulus, etc. // #include "stdafx.h" #include <math.h> #include "memdc.h" #include "dle_arc.h" #include "dle_centroid.h" #include "dle_circle.h" #include "dle_donut.h" #include "dle_hole.h" #include "dle_line.h" #include "dle_octagon.h" #include "dle_oval.h" #include "dle_rect.h" #include "dle_rect_rounded.h" #include "dle_square.h" #include "dle_x.h" // dimensions passed to DisplayList from the application are in PCBU (i.e. nm) // since the Win95/98 GDI uses 16-bit arithmetic, PCBU must be scaled to DU (i.e. mils) // //#define PCBU_PER_DU PCBU_PER_WU //#define MIL_PER_DU NM_PER_MIL/PCBU_PER_DU // conversion from mils to display units //#define DU_PER_MIL PCBU_PER_DU/NM_PER_MIL // conversion from display units to mils #define DL_MAX_LAYERS 32 #define HILITE_POINT_W 10 // size/2 of selection box for points (mils) // constructor // dl_element::dl_element() { } // constructor // CDisplayList::CDisplayList( int pcbu_per_wu ) { m_pcbu_per_wu = pcbu_per_wu; // create lists for all layers for( int layer=0; layer<MAX_LAYERS; layer++ ) { // default colors, these should be overwritten with actual colors m_rgb[layer].Set( layer*63, // R (layer/4)*127, // G (layer/8)*63 // B ); // default order m_layer_in_order[layer] = layer; // will be drawn from highest to lowest m_order_for_layer[layer] = layer; m_vis[layer] = 0; // Force the creation of "traces" job. // This is where the traces are added to in the non job specific version of Add() GetJob_traces(layer); } // miscellaneous m_ratline_w = 1; m_drag_flag = 0; m_drag_num_lines = 0; m_drag_line_pt = 0; m_drag_num_ratlines = 0; m_drag_ratline_start_pt = 0; m_drag_ratline_end_pt = 0; m_drag_ratline_width = 0; m_cross_hairs = 0; m_visual_grid_on = 0; m_visual_grid_spacing = 0; m_inflection_mode = IM_NONE; } // destructor // CDisplayList::~CDisplayList() { RemoveAll(); // Delete the "traces" jobs for( int layer=0; layer<MAX_LAYERS; layer++ ) { delete GetJob_traces(layer); } } // Remove element from list, return id // id CDisplayList::Remove( dl_element * element ) { if( !element ) { id no_id; return no_id; } if( element->magic != DL_MAGIC ) { ASSERT(0); id no_id; return no_id; } // remove links to this element element->DLinkList_remove(); // destroy element id el_id = element->id; delete( element ); return el_id; } void CDisplayList::RemoveAllFromLayer( int layer ) { CDLinkList *pLIST = &m_LIST_job[layer]; for (;;) { if( pLIST->next == pLIST ) break; delete static_cast<CDL_job*>(pLIST->next); } // Re-insert the "traces" job GetJob_traces(layer); } void CDisplayList::RemoveAll() { // traverse lists for all layers, removing all elements for( int layer=0; layer<MAX_LAYERS; layer++ ) { RemoveAllFromLayer( layer ); } if( m_drag_line_pt ) { free( m_drag_line_pt ); m_drag_line_pt = 0; } if( m_drag_ratline_start_pt ) { free( m_drag_ratline_start_pt ); m_drag_ratline_start_pt = 0; } if( m_drag_ratline_end_pt ) { free( m_drag_ratline_end_pt ); m_drag_ratline_end_pt = 0; } } // Set conversion parameters between world coords (used by elements in // display list) and window coords (pixels) // // enter with: // client_r = window client rectangle (pixels) // screen_r = window client rectangle in screen coords (pixels) // pane_org_x = starting x-coord of PCB drawing area in client rect (pixels) // pane_bottom_h = height of bottom pane (pixels) // pcb units per pixel = nm per pixel // org_x = x-coord of left edge of drawing area (pcb units) // org_y = y-coord of bottom edge of drawing area (pcb units) // // note that the actual scale factor is set by the arguments to // SetWindowExt and SetViewportExt, and may be slightly different for x and y // void CDisplayList::SetMapping( CRect *client_r, CRect *screen_r, int pane_org_x, int pane_bottom_h, double pcbu_per_pixel, int org_x, int org_y ) { m_client_r = client_r; // pixels m_screen_r = screen_r; // pixels m_pane_org_x = pane_org_x; // pixels m_bottom_pane_h = pane_bottom_h; // pixels m_pane_org_y = client_r->bottom - pane_bottom_h; // pixels m_scale = pcbu_per_pixel/m_pcbu_per_wu; // world units per pixel m_org_x = org_x/m_pcbu_per_wu; // world units m_org_y = org_y/m_pcbu_per_wu; // world units //now set extents double rw = m_client_r.Width(); // width of client area (pixels) double rh = m_client_r.Height(); // height of client area (pixels) double ext_x = rw*pcbu_per_pixel/m_pcbu_per_wu; // width in WU double ext_y = rh*pcbu_per_pixel/m_pcbu_per_wu; // height in WU int div = 1, mult = 1; if( m_pcbu_per_wu >=25400 ) { // this is necessary for Win95/98 (16-bit GDI) int ext_max = max( ext_x, ext_y ); if( ext_max > 30000 ) div = ext_max/15000; } else mult = m_pcbu_per_wu; if( ext_x*mult/div > INT_MAX ) ASSERT(0); if( ext_y*mult/div > INT_MAX ) ASSERT(0); w_ext_x = ext_x*mult/div; v_ext_x = rw*mult/div; w_ext_y = ext_y*mult/div; v_ext_y = -rh*mult/div; m_wu_per_pixel_x = (double)w_ext_x/v_ext_x; // actual ratios m_wu_per_pixel_y = (double)w_ext_y/v_ext_y; m_pcbu_per_pixel_x = m_wu_per_pixel_x * m_pcbu_per_wu; m_pcbu_per_pixel_y = m_wu_per_pixel_y * m_pcbu_per_wu; m_max_x = m_org_x + m_wu_per_pixel_x*(client_r->right-pane_org_x) + 2; // world units m_max_y = m_org_y - m_wu_per_pixel_y*client_r->bottom + 2; // world units } void CDisplayList::Scale_pcbu_to_wu(CRect &rect) { rect.top /= m_pcbu_per_wu; rect.bottom /= m_pcbu_per_wu; rect.left /= m_pcbu_per_wu; rect.right /= m_pcbu_per_wu; } // add graphics element used for selection // dl_element * CDisplayList::AddSelector( id id, void * ptr, int layer, int gtype, int visible, int w, int holew, int x, int y, int xf, int yf, int xo, int yo, int radius ) { // create new element dl_element * new_element = CreateDLE( id, ptr, layer, gtype, visible, w, holew, 0, x,y, xf,yf, xo,yo, radius, layer ); // Add to traces job in selection layer CDL_job *pDL_job = GetJob_traces(LAY_SELECTION); pDL_job->Add(new_element); return new_element; } dl_element * CDisplayList::CreateDLE( int gtype ) { // create new element and link into list dl_element * new_element; switch( gtype ) { case DL_LINE: new_element = new CDLE_LINE; break; case DL_CIRC: new_element = new CDLE_CIRC; break; case DL_DONUT: new_element = new CDLE_DONUT; break; case DL_SQUARE: new_element = new CDLE_SQUARE; break; case DL_RECT: new_element = new CDLE_RECT; break; case DL_RRECT: new_element = new CDLE_RRECT; break; case DL_OVAL: new_element = new CDLE_OVAL; break; case DL_OCTAGON: new_element = new CDLE_OCTAGON; break; case DL_HOLE: new_element = new CDLE_HOLE; break; case DL_HOLLOW_CIRC: new_element = new CDLE_HOLLOW_CIRC; break; case DL_HOLLOW_RECT: new_element = new CDLE_HOLLOW_RECT; break; case DL_HOLLOW_RRECT: new_element = new CDLE_HOLLOW_RRECT; break; case DL_HOLLOW_OVAL: new_element = new CDLE_HOLLOW_OVAL; break; case DL_HOLLOW_OCTAGON: new_element = new CDLE_HOLLOW_OCTAGON; break; case DL_RECT_X: new_element = new CDLE_RECT_X; break; case DL_ARC_CW: new_element = new CDLE_ARC_CW; break; case DL_ARC_CCW: new_element = new CDLE_ARC_CCW; break; case DL_CENTROID: new_element = new CDLE_CENTROID; break; case DL_X: new_element = new CDLE_X; break; default: new_element = new dl_element; break; } // now copy data from entry into element new_element->magic = DL_MAGIC; new_element->dlist = this; new_element->gtype = gtype; return new_element; } dl_element * CDisplayList::CreateDLE( id id, void * ptr, int layer, int gtype, int visible, int w, int holew, int clearancew, int x, int y, int xf, int yf, int xo, int yo, int radius, int orig_layer ) { // create new element dl_element * new_element = CreateDLE( gtype ); if( layer == LAY_RAT_LINE ) { new_element->w = m_ratline_w; } else { new_element->w = (w < 0) ? w : w / m_pcbu_per_wu; } // now copy data from entry into element new_element->id = id; new_element->ptr = ptr; new_element->visible = visible; new_element->holew = holew / m_pcbu_per_wu; new_element->clearancew = clearancew / m_pcbu_per_wu; new_element->i.x = x / m_pcbu_per_wu; new_element->i.y = y / m_pcbu_per_wu; new_element->f.x = xf / m_pcbu_per_wu; new_element->f.y = yf / m_pcbu_per_wu; new_element->org.x = xo / m_pcbu_per_wu; new_element->org.y = yo / m_pcbu_per_wu; new_element->radius = radius / m_pcbu_per_wu; new_element->sel_vert = 0; new_element->layer = layer; new_element->orig_layer = orig_layer; return new_element; } dl_element * CDisplayList::MorphDLE( dl_element *pFrom, int to_gtype ) { // create new element dl_element * new_element = CreateDLE( to_gtype ); new_element->id = pFrom->id; new_element->ptr = pFrom->ptr; new_element->visible = pFrom->visible; new_element->holew = pFrom->holew; new_element->clearancew = pFrom->clearancew; new_element->i = pFrom->i; new_element->f = pFrom->f; new_element->org = pFrom->org; new_element->radius = pFrom->radius; new_element->sel_vert = pFrom->sel_vert; new_element->layer = pFrom->layer; new_element->orig_layer = pFrom->orig_layer; // Move the element into the same list as pFrom pFrom->insert_after(new_element); pFrom->DLinkList_remove(); return new_element; } CDL_job_traces * CDisplayList::GetJob_traces( int layer ) { CDL_job_traces *pJob; CDLinkList *pElement = m_LIST_job[layer].next; if( pElement == &m_LIST_job[layer] ) { pJob = new CDL_job_traces(this); m_LIST_job[layer].insert_after(pJob); } else { pJob = static_cast< CDL_job_traces * >(pElement); } return pJob; } void CDisplayList::Add( CDL_job *pDL_job, int layer ) { m_LIST_job[layer].move_before(pDL_job); } // Add entry to end of list, returns pointer to element created. // // Entry is added to the given job. // // Dimensional units for input parameters are PCBU // dl_element * CDisplayList::Add( CDL_job *pDL_job, id id, void * ptr, int layer, int gtype, int visible, int w, int holew, int clearancew, int x, int y, int xf, int yf, int xo, int yo, int radius ) { // create new element dl_element * new_element = CreateDLE( id, ptr, layer, gtype, visible, w, holew, clearancew, x,y, xf,yf, xo,yo, radius, layer ); // Link into job pDL_job->Add(new_element); return new_element; } // Add entry to end of list, returns pointer to element created. // // Entry is added to the traces job. If that job doesn't exist, it will be created. // // Dimensional units for input parameters are PCBU // dl_element * CDisplayList::Add( id id, void * ptr, int layer, int gtype, int visible, int w, int holew, int clearancew, int x, int y, int xf, int yf, int xo, int yo, int radius, int orig_layer ) { // create new element dl_element * new_element = CreateDLE( id, ptr, layer, gtype, visible, w, holew, clearancew, x,y, xf,yf, xo,yo, radius, orig_layer ); // Link into traces job CDL_job *pDL_job = GetJob_traces(layer); pDL_job->Add(new_element); return new_element; } void CDisplayList::Add( dl_element * element ) { // Link into traces job CDL_job *pDL_job = GetJob_traces(element->layer); pDL_job->Add(element); } // set element parameters in PCBU // void CDisplayList::Set_visible( dl_element * el, int visible ) { if( el) el->visible = visible; } void CDisplayList::Set_sel_vert( dl_element * el, int sel_vert ) { if( el) el->sel_vert = sel_vert; } void CDisplayList::Set_w( dl_element * el, int w ) { if( el) el->w = w/m_pcbu_per_wu; } void CDisplayList::Set_clearance( dl_element * el, int clearance ) { if( el) el->clearancew = clearance/m_pcbu_per_wu; } void CDisplayList::Set_holew( dl_element * el, int holew ) { if( el) el->holew = holew/m_pcbu_per_wu; } void CDisplayList::Set_x_org( dl_element * el, int x_org ) { if( el) el->org.x = x_org/m_pcbu_per_wu; } void CDisplayList::Set_y_org( dl_element * el, int y_org ) { if( el) el->org.y = y_org/m_pcbu_per_wu; } void CDisplayList::Set_x( dl_element * el, int x ) { if( el) el->i.x = x/m_pcbu_per_wu; } void CDisplayList::Set_y( dl_element * el, int y ) { if( el) el->i.y = y/m_pcbu_per_wu; } void CDisplayList::Set_xf( dl_element * el, int xf ) { if( el) el->f.x = xf/m_pcbu_per_wu; } void CDisplayList::Set_yf( dl_element * el, int yf ) { if( el) el->f.y = yf/m_pcbu_per_wu; } void CDisplayList::Set_layer( dl_element * el, int layer ) { if( el) el->layer = layer; } void CDisplayList::Set_radius( dl_element * el, int radius ) { if( el) el->radius = radius/m_pcbu_per_wu; } void CDisplayList::Set_id( dl_element * el, id * id ) { if( el) el->id = *id; } void CDisplayList::Move( dl_element * el, int dx, int dy ) { el->i.x += dx; el->i.y += dy; el->org.x += dx; el->org.y += dy; el->f.x += dx; el->f.y += dy; } // get element parameters in PCBU // void * CDisplayList::Get_ptr( dl_element * el ) { return el->ptr; } int CDisplayList::Get_gtype( dl_element * el ) { return el->gtype; } int CDisplayList::Get_visible( dl_element * el ) { return el->visible; } int CDisplayList::Get_sel_vert( dl_element * el ) { return el->sel_vert; } int CDisplayList::Get_w( dl_element * el ) { return el->w*m_pcbu_per_wu; } int CDisplayList::Get_holew( dl_element * el ) { return el->holew*m_pcbu_per_wu; } int CDisplayList::Get_x_org( dl_element * el ) { return el->org.x*m_pcbu_per_wu; } int CDisplayList::Get_y_org( dl_element * el ) { return el->org.y*m_pcbu_per_wu; } int CDisplayList::Get_x( dl_element * el ) { return el->i.x*m_pcbu_per_wu; } int CDisplayList::Get_y( dl_element * el ) { return el->i.y*m_pcbu_per_wu; } int CDisplayList::Get_xf( dl_element * el ) { return el->f.x*m_pcbu_per_wu; } int CDisplayList::Get_yf( dl_element * el ) { return el->f.y*m_pcbu_per_wu; } int CDisplayList::Get_radius( dl_element * el ) { return el->radius*m_pcbu_per_wu; } int CDisplayList::Get_layer( dl_element * el ) { return el->layer; } id CDisplayList::Get_id( dl_element * el ) { return el->id; } void CDisplayList::Get_Endpoints(CPoint *cpi, CPoint *cpf) { cpi->x = m_drag_xi*m_pcbu_per_wu; cpi->y = m_drag_yi*m_pcbu_per_wu; cpf->x = m_drag_xf*m_pcbu_per_wu; cpf->y = m_drag_yf*m_pcbu_per_wu; } // Draw the display list using device DC or memory DC // void CDisplayList::Draw( CDC * dDC ) { CDC * pDC; if( memDC ) pDC = memDC; else pDC = dDC; pDC->SetBkColor( C_RGB::black ); // create pens and brushes CPen black_pen ( PS_SOLID, 1, C_RGB::white ); CPen white_pen ( PS_SOLID, 1, C_RGB::black ); CPen grid_pen ( PS_SOLID, 1, m_rgb[LAY_VISIBLE_GRID] ); CPen backgnd_pen( PS_SOLID, 1, m_rgb[LAY_BACKGND] ); CPen board_pen ( PS_SOLID, 1, m_rgb[LAY_BOARD_OUTLINE] ); CBrush black_brush( C_RGB::black ); CBrush backgnd_brush( m_rgb[LAY_BACKGND] ); CBrush * old_brush; CPen * old_pen; // paint it background color old_brush = pDC->SelectObject( &backgnd_brush ); old_pen = pDC->SelectObject( &black_pen ); CRect client_rect; client_rect.left = m_org_x; client_rect.right = m_max_x; client_rect.bottom = m_org_y; client_rect.top = m_max_y; pDC->Rectangle( &client_rect ); // visual grid if( m_visual_grid_on && (m_visual_grid_spacing/m_scale)>5 && m_vis[LAY_VISIBLE_GRID] ) { int startix = m_org_x/m_visual_grid_spacing; int startiy = m_org_y/m_visual_grid_spacing; double start_grid_x = startix*m_visual_grid_spacing; double start_grid_y = startiy*m_visual_grid_spacing; for( double ix=start_grid_x; ix<m_max_x; ix+=m_visual_grid_spacing ) { for( double iy=start_grid_y; iy<m_max_y; iy+=m_visual_grid_spacing ) { pDC->SetPixel( ix, iy, m_rgb[LAY_VISIBLE_GRID] ); } } } // now traverse the lists, starting with the layer in the last element // of the m_order[] array CDrawInfo di; di.DC_Master = pDC; CMemDC dcMemory(pDC); for( int order=(MAX_LAYERS-1); order>=0; order-- ) { int layer = m_layer_in_order[order]; if( !m_vis[layer] || layer == LAY_SELECTION ) { continue; } if( layer > LAY_BOARD_OUTLINE ) { // Use transparent DC in dcMemory di.DC = &dcMemory; dcMemory.mono(); di.layer_color[0] = C_RGB::mono_off; di.layer_color[1] = C_RGB::mono_on; } else { // Draw directly on main DC (di.DC_Master) for speed di.DC = di.DC_Master; di.layer_color[0] = m_rgb[LAY_BACKGND]; di.layer_color[1] = m_rgb[layer]; } // Run drawing jobs for this layer CDLinkList *pElement; for( pElement = m_LIST_job[layer].next; pElement != &m_LIST_job[layer]; pElement = pElement->next ) { CDL_job *pJob = static_cast<CDL_job*>(pElement); pJob->Draw(di); } if( di.DC != di.DC_Master ) { // di.DC is a monochrome mask // DC_Master &= ~mask // 0 = transparent (AND with ~RGB(0,0,0) -> no effect, D AND 1 = D) // 1 = solid (AND with ~RGB(255,255,255) -> clear the masked area to RGB(0,0,0) di.DC_Master->SetTextColor(RGB(0,0,0)); di.DC_Master->SetBkColor(RGB(255,255,255)); di.DC_Master->BitBlt(m_org_x, m_org_y, m_max_x-m_org_x, m_max_y-m_org_y, di.DC, m_org_x, m_org_y, 0x00220326); // DC_Master |= mask // 0 = transparent (OR with RBG(0,0,0) -> no effect D OR 0 = D) // 1 = solid (OR the masked area with layer color -> 0 OR C = C) di.DC_Master->SetBkColor( m_rgb[layer] ); di.DC_Master->BitBlt(m_org_x, m_org_y, m_max_x-m_org_x, m_max_y-m_org_y, di.DC, m_org_x, m_org_y, SRCPAINT); } } dcMemory.DeleteDC(); // origin CRect r; r.top = 25*NM_PER_MIL/m_pcbu_per_wu; r.left = -25*NM_PER_MIL/m_pcbu_per_wu; r.right = 25*NM_PER_MIL/m_pcbu_per_wu; r.bottom = -25*NM_PER_MIL/m_pcbu_per_wu; pDC->SelectObject( &grid_pen ); pDC->SelectObject( GetStockObject( HOLLOW_BRUSH ) ); pDC->MoveTo( -100*NM_PER_MIL/m_pcbu_per_wu, 0 ); pDC->LineTo( -25*NM_PER_MIL/m_pcbu_per_wu, 0 ); pDC->MoveTo( 100*NM_PER_MIL/m_pcbu_per_wu, 0 ); pDC->LineTo( 25*NM_PER_MIL/m_pcbu_per_wu, 0 ); pDC->MoveTo( 0, -100*NM_PER_MIL/m_pcbu_per_wu ); pDC->LineTo( 0, -25*NM_PER_MIL/m_pcbu_per_wu ); pDC->MoveTo( 0, 100*NM_PER_MIL/m_pcbu_per_wu ); pDC->LineTo( 0, 25*NM_PER_MIL/m_pcbu_per_wu ); pDC->Ellipse( r ); pDC->SelectObject( old_pen ); pDC->SelectObject( old_brush ); // if dragging, draw drag lines or shape int old_ROP2 = pDC->GetROP2(); pDC->SetROP2( R2_XORPEN ); if( m_drag_num_lines ) { // draw line array CPen drag_pen( PS_SOLID, 1, m_rgb[m_drag_layer] ); CPen * old_pen = pDC->SelectObject( &drag_pen ); for( int il=0; il<m_drag_num_lines; il++ ) { pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); } pDC->SelectObject( old_pen ); } if( m_drag_num_ratlines ) { // draw ratline array CPen drag_pen( PS_SOLID, m_drag_ratline_width, m_rgb[m_drag_layer] ); CPen * old_pen = pDC->SelectObject( &drag_pen ); for( int il=0; il<m_drag_num_ratlines; il++ ) { pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); } pDC->SelectObject( old_pen ); } if( m_drag_flag ) { // 4. Redraw the three segments: if(m_drag_shape == DS_SEGMENT) { pDC->MoveTo( m_drag_xb, m_drag_yb ); // draw first segment CPen pen0( PS_SOLID, m_drag_w0, m_rgb[m_drag_layer_0] ); CPen * old_pen = pDC->SelectObject( &pen0 ); pDC->LineTo( m_drag_xi, m_drag_yi ); // draw second segment CPen pen1( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); pDC->SelectObject( &pen1 ); pDC->LineTo( m_drag_xf, m_drag_yf ); // draw third segment if(m_drag_style2 != DSS_NONE) { CPen pen2( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); pDC->SelectObject( &pen2 ); pDC->LineTo( m_drag_xe, m_drag_ye ); } pDC->SelectObject( old_pen ); } // draw drag shape, if used if( m_drag_shape == DS_LINE_VERTEX || m_drag_shape == DS_LINE ) { CPen pen_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); // draw dragged shape pDC->SelectObject( &pen_w ); if( m_drag_style1 == DSS_STRAIGHT ) { if( m_inflection_mode == IM_NONE ) { pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); } else { CPoint pi( m_drag_xi, m_drag_yi ); CPoint pf( m_drag_x, m_drag_y ); CPoint p = GetInflectionPoint( pi, pf, m_inflection_mode ); pDC->MoveTo( m_drag_xi, m_drag_yi ); if( p != pi ) pDC->LineTo( p.x, p.y ); pDC->LineTo( m_drag_x, m_drag_y ); } m_last_inflection_mode = m_inflection_mode; } else if( m_drag_style1 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else if( m_drag_style1 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else ASSERT(0); if( m_drag_shape == DS_LINE_VERTEX ) { CPen pen( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); pDC->SelectObject( &pen ); if( m_drag_style2 == DSS_STRAIGHT ) pDC->LineTo( m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_x, m_drag_y, m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_x, m_drag_y, m_drag_xf, m_drag_yf ); else ASSERT(0); pDC->SelectObject( old_pen ); } pDC->SelectObject( old_pen ); // see if leading via needs to be drawn if( m_drag_via_drawn ) { // draw or undraw via int thick = (m_drag_via_w - m_drag_via_holew)/2; int w = m_drag_via_w - thick; int holew = m_drag_via_holew; // CPen pen( PS_SOLID, thick, m_rgb[LAY_PAD_THRU] ); CPen pen( PS_SOLID, thick, m_rgb[m_drag_layer_1] ); CPen * old_pen = pDC->SelectObject( &pen ); CBrush black_brush( C_RGB::black ); CBrush * old_brush = pDC->SelectObject( &black_brush ); pDC->Ellipse( m_drag_xi - w/2, m_drag_yi - w/2, m_drag_xi + w/2, m_drag_yi + w/2 ); pDC->SelectObject( old_brush ); pDC->SelectObject( old_pen ); } } else if( m_drag_shape == DS_ARC_STRAIGHT || m_drag_shape == DS_ARC_CW || m_drag_shape == DS_ARC_CCW ) { CPen pen_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); // redraw dragged shape pDC->SelectObject( &pen_w ); if( m_drag_shape == DS_ARC_STRAIGHT ) DrawArc( pDC, DL_LINE, m_drag_x, m_drag_y, m_drag_xi, m_drag_yi ); else if( m_drag_shape == DS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else if( m_drag_shape == DS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); pDC->SelectObject( old_pen ); m_last_drag_shape = m_drag_shape; } } // if cross hairs, draw them if( m_cross_hairs ) { // draw cross-hairs COLORREF bk = pDC->SetBkColor( C_RGB::black ); CPen pen( PS_DOT, 0, C_RGB::grey ); pDC->SelectObject( &pen ); int x = m_cross_bottom.x; int y = m_cross_left.y; m_cross_left.x = m_org_x; m_cross_right.x = m_max_x; m_cross_bottom.y = m_org_y; m_cross_top.y = m_max_y; if( x-m_org_x > y-m_org_y ) { // bottom-left cursor line intersects m_org_y m_cross_botleft.x = x - (y - m_org_y); m_cross_botleft.y = m_org_y; } else { // bottom-left cursor line intersects m_org_x m_cross_botleft.x = m_org_x; m_cross_botleft.y = y - (x - m_org_x); } if( m_max_x-x > y-m_org_y ) { // bottom-right cursor line intersects m_org_y m_cross_botright.x = x + (y - m_org_y); m_cross_botright.y = m_org_y; } else { // bottom-right cursor line intersects m_max_x m_cross_botright.x = m_max_x; m_cross_botright.y = y - (m_max_x - x); } if( x-m_org_x > m_max_y-y ) { // top-left cursor line intersects m_max_y m_cross_topleft.x = x - (m_max_y - y); m_cross_topleft.y = m_max_y; } else { // top-left cursor line intersects m_org_x m_cross_topleft.x = m_org_x; m_cross_topleft.y = y + (x - m_org_x); } if( m_max_x-x > m_max_y-y ) { // top-right cursor line intersects m_max_y m_cross_topright.x = x + (m_max_y - y); m_cross_topright.y = m_max_y; } else { // top-right cursor line intersects m_max_x m_cross_topright.x = m_max_x; m_cross_topright.y = y + (m_max_x - x); } pDC->MoveTo( m_cross_left ); pDC->LineTo( m_cross_right ); pDC->MoveTo( m_cross_bottom ); pDC->LineTo( m_cross_top ); if( m_cross_hairs == 2 ) { pDC->MoveTo( m_cross_topleft ); pDC->LineTo( m_cross_botright ); pDC->MoveTo( m_cross_botleft ); pDC->LineTo( m_cross_topright ); } pDC->SelectObject( old_pen ); pDC->SetBkColor( bk ); } pDC->SetROP2( old_ROP2 ); // restore original objects pDC->SelectObject( old_pen ); pDC->SelectObject( old_brush ); // double-buffer to screen if( memDC ) { dDC->BitBlt( m_org_x, m_org_y, m_max_x-m_org_x, m_max_y-m_org_y, pDC, m_org_x, m_org_y, SRCCOPY ); } } // set the display color for a layer // void CDisplayList::SetLayerRGB( int layer, C_RGB color ) { m_rgb[layer] = color; } void CDisplayList::SetLayerVisible( int layer, BOOL vis ) { m_vis[layer] = vis; } // test x,y for a hit on an item in the selection layer // creates arrays with layer and id of each hit item // assigns priority based on layer and id // then returns pointer to item with highest priority // If exclude_id != NULL, excludes item with // id == exclude_id and ptr == exclude_ptr // If include_id != NULL, only include items that match include_id[] // where n_include_ids is size of array, and // where 0's in include_id[] fields are treated as wildcards // // Returns: Index into hit_info[] if hit, -1 if no hit int CDisplayList::TestSelect( int x, int y, CDL_job::HitInfo hit_info[], int max_hits, int &num_hits, id * exclude_id, void * exclude_ptr, id * include_id, int n_include_ids ) { int best_hit = -1; // Get the traces job (last in job list) if( m_vis[LAY_SELECTION] ) { CDL_job_traces *pJob = GetJob_traces(LAY_SELECTION); CPoint point(x/m_pcbu_per_wu, y/m_pcbu_per_wu); num_hits = pJob->TestForHit(point, hit_info, max_hits-1); // now return highest priority hit if( num_hits == 0 ) { goto no_hit; } else { // Mark the end of the hit array with invalid layer. // assign priority to each hit, track maximum, exclude exclude_id item int best_hit_priority = 0; for( int i=0; i<num_hits; i++ ) { BOOL excluded_hit = FALSE; BOOL included_hit = TRUE; if( exclude_id ) { if( hit_info[i].ID == *exclude_id && hit_info[i].ptr == exclude_ptr ) excluded_hit = TRUE; } if( include_id ) { included_hit = FALSE; for( int inc=0; inc<n_include_ids; inc++ ) { id * inc_id = &include_id[inc]; if( inc_id->type == hit_info[i].ID.type && ( inc_id->st == 0 || inc_id->st == hit_info[i].ID.st ) && ( inc_id->i == 0 || inc_id->i == hit_info[i].ID.i ) && ( inc_id->sst == 0 || inc_id->sst == hit_info[i].ID.sst ) && ( inc_id->ii == 0 || inc_id->ii == hit_info[i].ID.ii ) ) { included_hit = TRUE; break; } } } if( !excluded_hit && included_hit ) { // OK, valid hit, now assign priority // start with reversed layer drawing order * 10 // i.e. last drawn = highest priority int priority = (MAX_LAYERS - m_order_for_layer[hit_info[i].layer])*10; // bump priority for small items which may be overlapped by larger items on same layer if( hit_info[i].ID.type == ID_PART && hit_info[i].ID.st == ID_SEL_REF_TXT ) priority++; else if( hit_info[i].ID.type == ID_PART && hit_info[i].ID.st == ID_SEL_VALUE_TXT ) priority++; else if( hit_info[i].ID.type == ID_BOARD && hit_info[i].ID.st == ID_BOARD_OUTLINE && hit_info[i].ID.sst == ID_SEL_CORNER ) priority++; else if( hit_info[i].ID.type == ID_NET && hit_info[i].ID.st == ID_AREA && hit_info[i].ID.sst == ID_SEL_CORNER ) priority++; else if( hit_info[i].ID.type == ID_NET && hit_info[i].ID.st == ID_CONNECT && hit_info[i].ID.sst == ID_SEL_VERTEX ) priority++; hit_info[i].priority = priority; if( priority >= best_hit_priority ) { best_hit_priority = priority; best_hit = i; } } else { // Not valid hit, set priority < zero hit_info[i].priority = -1; } } } } no_hit: return best_hit; } // Start dragging arrays of drag lines and ratlines // Assumes that arrays have already been set up using MakeLineArray, etc. // If no arrays, just drags point // int CDisplayList::StartDraggingArray( CDC * pDC, int xx, int yy, int vert, int layer, int crosshair ) { // convert to display units int x = xx/m_pcbu_per_wu; int y = yy/m_pcbu_per_wu; // cancel dragging non-array shape m_drag_flag = 0; m_drag_shape = 0; // set up for dragging array m_drag_x = x; // "grab point" m_drag_y = y; m_drag_vert = vert; // set axis for flipping item to opposite side of PCB m_drag_layer = layer; m_drag_angle = 0; m_drag_side = 0; SetUpCrosshairs( crosshair, x, y ); // done return 0; } // Start dragging rectangle // int CDisplayList::StartDraggingRectangle( CDC * pDC, int x, int y, int xi, int yi, int xf, int yf, int vert, int layer ) { // create drag lines CPoint p1(xi,yi); CPoint p2(xf,yi); CPoint p3(xf,yf); CPoint p4(xi,yf); MakeDragLineArray( 4 ); AddDragLine( p1, p2 ); AddDragLine( p2, p3 ); AddDragLine( p3, p4 ); AddDragLine( p4, p1 ); StartDraggingArray( pDC, x, y, vert, layer ); // done return 0; } // Start dragging line // int CDisplayList::StartDraggingRatLine( CDC * pDC, int x, int y, int xi, int yi, int layer, int w, int crosshair ) { // create drag line CPoint p1(xi,yi); CPoint p2(x,y); MakeDragRatlineArray( 1, 1 ); AddDragRatline( p1, p2 ); StartDraggingArray( pDC, xi, yi, 0, layer, crosshair ); // done return 0; } // set style of arc being dragged, using CPolyLine styles // void CDisplayList::SetDragArcStyle( int style ) { if( style == CPolyLine::STRAIGHT ) m_drag_shape = DS_ARC_STRAIGHT; else if( style == CPolyLine::ARC_CW ) m_drag_shape = DS_ARC_CW; else if( style == CPolyLine::ARC_CCW ) m_drag_shape = DS_ARC_CCW; } // Start dragging arc endpoint, using style from CPolyLine // Use the layer color and width w // int CDisplayList::StartDraggingArc( CDC * pDC, int style, int xx, int yy, int xi, int yi, int layer, int w, int crosshair ) { int x = xx/m_pcbu_per_wu; int y = yy/m_pcbu_per_wu; // set up for dragging m_drag_flag = 1; if( style == CPolyLine::STRAIGHT ) m_drag_shape = DS_ARC_STRAIGHT; else if( style == CPolyLine::ARC_CW ) m_drag_shape = DS_ARC_CW; else if( style == CPolyLine::ARC_CCW ) m_drag_shape = DS_ARC_CCW; m_drag_x = x; // position of endpoint (at cursor) m_drag_y = y; m_drag_xi = xi/m_pcbu_per_wu; // start point m_drag_yi = yi/m_pcbu_per_wu; m_drag_side = 0; m_drag_layer_1 = layer; m_drag_w1 = w/m_pcbu_per_wu; // set up cross hairs SetUpCrosshairs( crosshair, x, y ); //Redraw // Draw( pDC ); // done return 0; } // Start dragging the selected line endpoint // Use the layer1 color and width w // int CDisplayList::StartDraggingLine( CDC * pDC, int x, int y, int xi, int yi, int layer1, int w, int layer_no_via, int via_w, int via_holew, int crosshair, int style, int inflection_mode ) { // set up for dragging m_drag_flag = 1; m_drag_shape = DS_LINE; m_drag_x = x/m_pcbu_per_wu; // position of endpoint (at cursor) m_drag_y = y/m_pcbu_per_wu; m_drag_xi = xi/m_pcbu_per_wu; // initial vertex m_drag_yi = yi/m_pcbu_per_wu; m_drag_side = 0; m_drag_layer_1 = layer1; m_drag_w1 = w/m_pcbu_per_wu; m_drag_style1 = style; m_drag_layer_no_via = layer_no_via; m_drag_via_w = via_w/m_pcbu_per_wu; m_drag_via_holew = via_holew/m_pcbu_per_wu; m_drag_via_drawn = 0; m_inflection_mode = inflection_mode; m_last_inflection_mode = IM_NONE; // set up cross hairs SetUpCrosshairs( crosshair, x, y ); //Redraw // Draw( pDC ); // done return 0; } // Start dragging line vertex (i.e. vertex between 2 line segments) // Use the layer1 color and width w1 for the first segment from (xi,yi) to the vertex, // Use the layer2 color and width w2 for the second segment from the vertex to (xf,yf) // While dragging, insert via at start point of first segment if layer1 != layer_no_via // using via parameters via_w and via_holew // Note that layer1 may be changed while dragging by ChangeRouting Layer() // If dir = 1, swap start and end points // int CDisplayList::StartDraggingLineVertex( CDC * pDC, int x, int y, int xi, int yi, int xf, int yf, int layer1, int layer2, int w1, int w2, int style1, int style2, int layer_no_via, int via_w, int via_holew, int dir, int crosshair ) { // set up for dragging m_drag_flag = 1; m_drag_shape = DS_LINE_VERTEX; m_drag_x = x/m_pcbu_per_wu; // position of central vertex (at cursor) m_drag_y = y/m_pcbu_per_wu; if( dir == 0 ) { // routing forward m_drag_xi = xi/m_pcbu_per_wu; // initial vertex m_drag_yi = yi/m_pcbu_per_wu; m_drag_xf = xf/m_pcbu_per_wu; // final vertex m_drag_yf = yf/m_pcbu_per_wu; } else { // routing backward m_drag_xi = xf/m_pcbu_per_wu; // initial vertex m_drag_yi = yf/m_pcbu_per_wu; m_drag_xf = xi/m_pcbu_per_wu; // final vertex m_drag_yf = yi/m_pcbu_per_wu; } m_drag_side = 0; m_drag_layer_1 = layer1; m_drag_layer_2 = layer2; m_drag_w1 = w1/m_pcbu_per_wu; m_drag_w2 = w2/m_pcbu_per_wu; m_drag_style1 = style1; m_drag_style2 = style2; m_drag_layer_no_via = layer_no_via; m_drag_via_w = via_w/m_pcbu_per_wu; m_drag_via_holew = via_holew/m_pcbu_per_wu; m_drag_via_drawn = 0; // set up cross hairs SetUpCrosshairs( crosshair, x, y ); //Redraw Draw( pDC ); // done return 0; } // Start dragging line segment (i.e. line segment between 2 vertices) // Use the layer0 color and width w0 for the "before" segment from (xb,yb) to (xi, yi), // Use the layer1 color and width w1 for the moving segment from (xi,yi) to (xf, yf), // Use the layer2 color and width w2 for the ending segment from (xf, yf) to (xe,ye) // While dragging, insert via at (xi, yi) if layer1 != layer_no_via1, insert via // at (xf, yf) if layer2 != layer_no_via. // using via parameters via_w and via_holew // Note that layer1 may be changed while dragging by ChangeRouting Layer() // If dir = 1, swap start and end points // int CDisplayList::StartDraggingLineSegment( CDC * pDC, int x, int y, int xb, int yb, int xi, int yi, int xf, int yf, int xe, int ye, int layer0, int layer1, int layer2, int w0, int w1, int w2, int style0, int style1, int style2, int layer_no_via, int via_w, int via_holew, int crosshair ) { // set up for dragging m_drag_flag = 1; m_drag_shape = DS_SEGMENT; m_drag_x = x/m_pcbu_per_wu; // position of reference point (at cursor) m_drag_y = y/m_pcbu_per_wu; m_drag_xb = xb/m_pcbu_per_wu; // vertex before m_drag_yb = yb/m_pcbu_per_wu; m_drag_xi = xi/m_pcbu_per_wu; // initial vertex m_drag_yi = yi/m_pcbu_per_wu; m_drag_xf = xf/m_pcbu_per_wu; // final vertex m_drag_yf = yf/m_pcbu_per_wu; m_drag_xe = xe/m_pcbu_per_wu; // End vertex m_drag_ye = ye/m_pcbu_per_wu; m_drag_side = 0; m_drag_layer_0 = layer0; m_drag_layer_1 = layer1; m_drag_layer_2 = layer2; m_drag_w0 = w0/m_pcbu_per_wu; m_drag_w1 = w1/m_pcbu_per_wu; m_drag_w2 = w2/m_pcbu_per_wu; m_drag_style0 = style0; m_drag_style1 = style1; m_drag_style2 = style2; m_drag_layer_no_via = layer_no_via; m_drag_via_w = via_w/m_pcbu_per_wu; m_drag_via_holew = via_holew/m_pcbu_per_wu; m_drag_via_drawn = 0; // set up cross hairs SetUpCrosshairs( crosshair, x, y ); //Redraw Draw( pDC ); // done return 0; } // Drag graphics with cursor // void CDisplayList::Drag( CDC * pDC, int x, int y ) { // convert from PCB to display coords int xx = x/m_pcbu_per_wu; int yy = y/m_pcbu_per_wu; // set XOR pen mode for dragging int old_ROP2 = pDC->SetROP2( R2_XORPEN ); //**** there are three dragging modes, which may be used simultaneously ****// // drag array of lines, used to make complex graphics like a part if( m_drag_num_lines ) { CPen drag_pen( PS_SOLID, 1, m_rgb[m_drag_layer] ); CPen * old_pen = pDC->SelectObject( &drag_pen ); for( int il=0; il<m_drag_num_lines; il++ ) { // undraw pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); // redraw pDC->MoveTo( xx+m_drag_line_pt[2*il].x, yy+m_drag_line_pt[2*il].y ); pDC->LineTo( xx+m_drag_line_pt[2*il+1].x, yy+m_drag_line_pt[2*il+1].y ); } pDC->SelectObject( old_pen ); } // drag array of rubberband lines, used for ratlines to dragged part if( m_drag_num_ratlines ) { CPen drag_pen( PS_SOLID, m_drag_ratline_width, m_rgb[m_drag_layer] ); CPen * old_pen = pDC->SelectObject( &drag_pen ); for( int il=0; il<m_drag_num_ratlines; il++ ) { // undraw pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); // draw pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( xx+m_drag_ratline_end_pt[il].x, yy+m_drag_ratline_end_pt[il].y ); } pDC->SelectObject( old_pen ); } // draw special shapes, used for polyline sides and trace segments if( m_drag_flag && ( m_drag_shape == DS_LINE_VERTEX || m_drag_shape == DS_LINE ) ) { // drag rubberband trace segment, or vertex between two rubberband segments // used for routing traces CPen pen_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); // undraw first segment CPen * old_pen = pDC->SelectObject( &pen_w ); { if( m_drag_style1 == DSS_STRAIGHT ) { if( m_last_inflection_mode == IM_NONE ) { pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); } else { CPoint pi( m_drag_xi, m_drag_yi ); CPoint pf( m_drag_x, m_drag_y ); CPoint p = GetInflectionPoint( pi, pf, m_last_inflection_mode ); pDC->MoveTo( m_drag_xi, m_drag_yi ); if( p != pi ) pDC->LineTo( p.x, p.y ); pDC->LineTo( m_drag_x, m_drag_y ); } } else if( m_drag_style1 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else if( m_drag_style1 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else ASSERT(0); if( m_drag_shape == DS_LINE_VERTEX ) { // undraw second segment CPen pen( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); CPen * old_pen = pDC->SelectObject( &pen ); if( m_drag_style2 == DSS_STRAIGHT ) pDC->LineTo( m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_x, m_drag_y, m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_x, m_drag_y, m_drag_xf, m_drag_yf ); else ASSERT(0); pDC->SelectObject( old_pen ); } // draw first segment if( m_drag_style1 == DSS_STRAIGHT ) { if( m_inflection_mode == IM_NONE ) { pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( xx, yy ); } else { CPoint pi( m_drag_xi, m_drag_yi ); CPoint pf( xx, yy ); CPoint p = GetInflectionPoint( pi, pf, m_inflection_mode ); pDC->MoveTo( m_drag_xi, m_drag_yi ); if( p != pi ) pDC->LineTo( p.x, p.y ); pDC->LineTo( xx, yy ); } m_last_inflection_mode = m_inflection_mode; } else if( m_drag_style1 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, xx, yy ); else if( m_drag_style1 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, xx, yy ); else ASSERT(0); if( m_drag_shape == DS_LINE_VERTEX ) { // draw second segment CPen pen( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); CPen * old_pen = pDC->SelectObject( &pen ); if( m_drag_style2 == DSS_STRAIGHT ) pDC->LineTo( m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, xx, yy, m_drag_xf, m_drag_yf ); else if( m_drag_style2 == DSS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, xx, yy, m_drag_xf, m_drag_yf ); else ASSERT(0); pDC->SelectObject( old_pen ); } // see if leading via needs to be changed if( ( (m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && !m_drag_via_drawn ) || (!(m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && m_drag_via_drawn ) ) { // draw or undraw via int thick = (m_drag_via_w - m_drag_via_holew)/2; int w = m_drag_via_w - thick; int holew = m_drag_via_holew; // CPen pen( PS_SOLID, thick, m_rgb[LAY_PAD_THRU] ); CPen pen( PS_SOLID, thick, m_rgb[m_drag_layer_1] ); CPen * old_pen = pDC->SelectObject( &pen ); { CBrush black_brush( C_RGB::black ); CBrush * old_brush = pDC->SelectObject( &black_brush ); pDC->Ellipse( m_drag_xi - w/2, m_drag_yi - w/2, m_drag_xi + w/2, m_drag_yi + w/2 ); pDC->SelectObject( old_brush ); } pDC->SelectObject( old_pen ); m_drag_via_drawn = 1 - m_drag_via_drawn; } } pDC->SelectObject( old_pen ); } // move a trace segment else if( m_drag_flag && m_drag_shape == DS_SEGMENT ) { { ASSERT(m_drag_style0 == DSS_STRAIGHT); pDC->MoveTo( m_drag_xb, m_drag_yb ); // undraw first segment CPen pen0( PS_SOLID, m_drag_w0, m_rgb[m_drag_layer_0] ); CPen * old_pen = pDC->SelectObject( &pen0 ); pDC->LineTo( m_drag_xi, m_drag_yi ); // undraw second segment ASSERT(m_drag_style1 == DSS_STRAIGHT); CPen pen1( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); pDC->SelectObject( &pen1 ); pDC->LineTo( m_drag_xf, m_drag_yf ); // undraw third segment if(m_drag_style2 == DSS_STRAIGHT) // Could also be DSS_NONE (this segment only) { CPen pen2( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); pDC->SelectObject( &pen2 ); pDC->LineTo( m_drag_xe, m_drag_ye ); } pDC->SelectObject( old_pen ); } // Adjust the two vertices, (xi, yi) and (xf, yf) based on the movement of xx and yy // relative to m_drag_x and m_drag_y: // 1. Move the endpoints of (xi, yi), (xf, yf) of the line by the mouse movement. This // is just temporary, since the final ending position is determined by the intercept // points with the leading and trailing segments: int new_xi = m_drag_xi + xx - m_drag_x; // Check sign here. int new_yi = m_drag_yi + yy - m_drag_y; int new_xf = m_drag_xf + xx - m_drag_x; int new_yf = m_drag_yf + yy - m_drag_y; int old_xb_dir = sign(m_drag_xi - m_drag_xb); int old_yb_dir = sign(m_drag_yi - m_drag_yb); int old_xi_dir = sign(m_drag_xf - m_drag_xi); int old_yi_dir = sign(m_drag_yf - m_drag_yi); int old_xe_dir = sign(m_drag_xe - m_drag_xf); int old_ye_dir = sign(m_drag_ye - m_drag_yf); // 2. Find the intercept between the extended segment in motion and the leading segment. double d_new_xi; double d_new_yi; FindLineIntersection(m_drag_xb, m_drag_yb, m_drag_xi, m_drag_yi, new_xi, new_yi, new_xf, new_yf, &d_new_xi, &d_new_yi); int i_drag_xi = floor(d_new_xi + .5); int i_drag_yi = floor(d_new_yi + .5); // 3. Find the intercept between the extended segment in motion and the trailing segment: int i_drag_xf, i_drag_yf; if(m_drag_style2 == DSS_STRAIGHT) { double d_new_xf; double d_new_yf; FindLineIntersection(new_xi, new_yi, new_xf, new_yf, m_drag_xf, m_drag_yf, m_drag_xe, m_drag_ye, &d_new_xf, &d_new_yf); i_drag_xf = floor(d_new_xf + .5); i_drag_yf = floor(d_new_yf + .5); } else { i_drag_xf = new_xf; i_drag_yf = new_yf; } // If we drag too far, the line segment can reverse itself causing a little triangle to form. // That's a bad thing. if(sign(i_drag_xf - i_drag_xi) == old_xi_dir && sign(i_drag_yf - i_drag_yi) == old_yi_dir && sign(i_drag_xi - m_drag_xb) == old_xb_dir && sign(i_drag_yi - m_drag_yb) == old_yb_dir && sign(m_drag_xe - i_drag_xf) == old_xe_dir && sign(m_drag_ye - i_drag_yf) == old_ye_dir ) { m_drag_xi = i_drag_xi; m_drag_yi = i_drag_yi; m_drag_xf = i_drag_xf; m_drag_yf = i_drag_yf; } else { xx = m_drag_x; yy = m_drag_y; } // 4. Redraw the three segments: { pDC->MoveTo( m_drag_xb, m_drag_yb ); // draw first segment CPen pen0( PS_SOLID, m_drag_w0, m_rgb[m_drag_layer_0] ); CPen * old_pen = pDC->SelectObject( &pen0 ); pDC->LineTo( m_drag_xi, m_drag_yi ); // draw second segment CPen pen1( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); pDC->SelectObject( &pen1 ); pDC->LineTo( m_drag_xf, m_drag_yf ); if(m_drag_style2 == DSS_STRAIGHT) { // draw third segment CPen pen2( PS_SOLID, m_drag_w2, m_rgb[m_drag_layer_2] ); pDC->SelectObject( &pen2 ); pDC->LineTo( m_drag_xe, m_drag_ye ); } pDC->SelectObject( old_pen ); } } else if( m_drag_flag && (m_drag_shape == DS_ARC_STRAIGHT || m_drag_shape == DS_ARC_CW || m_drag_shape == DS_ARC_CCW) ) { CPen pen_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); // undraw old arc CPen * old_pen = pDC->SelectObject( &pen_w ); { if( m_last_drag_shape == DS_ARC_STRAIGHT ) DrawArc( pDC, DL_LINE, m_drag_x, m_drag_y, m_drag_xi, m_drag_yi ); else if( m_last_drag_shape == DS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); else if( m_last_drag_shape == DS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, m_drag_x, m_drag_y ); // draw new arc if( m_drag_shape == DS_ARC_STRAIGHT ) DrawArc( pDC, DL_LINE, xx, yy, m_drag_xi, m_drag_yi ); else if( m_drag_shape == DS_ARC_CW ) DrawArc( pDC, DL_ARC_CW, m_drag_xi, m_drag_yi, xx, yy ); else if( m_drag_shape == DS_ARC_CCW ) DrawArc( pDC, DL_ARC_CCW, m_drag_xi, m_drag_yi, xx, yy ); m_last_drag_shape = m_drag_shape; // used only for polylines } pDC->SelectObject( old_pen ); } // remember shape data m_drag_x = xx; m_drag_y = yy; // now undraw and redraw cross-hairs, if necessary if( m_cross_hairs ) { int x = xx; int y = yy; COLORREF bk = pDC->SetBkColor( C_RGB::black ); CPen cross_pen( PS_DOT, 0, C_RGB::grey ); CPen * old_pen = pDC->SelectObject( &cross_pen ); { pDC->MoveTo( m_cross_left ); pDC->LineTo( m_cross_right ); pDC->MoveTo( m_cross_bottom ); pDC->LineTo( m_cross_top ); if( m_cross_hairs == 2 ) { pDC->MoveTo( m_cross_topleft ); pDC->LineTo( m_cross_botright ); pDC->MoveTo( m_cross_botleft ); pDC->LineTo( m_cross_topright ); } m_cross_left.x = m_org_x; m_cross_left.y = y; m_cross_right.x = m_max_x; m_cross_right.y = y; m_cross_bottom.x = x; m_cross_bottom.y = m_org_y; m_cross_top.x = x; m_cross_top.y = m_max_y; if( x-m_org_x > y-m_org_y ) { // bottom-left cursor line intersects m_org_y m_cross_botleft.x = x - (y - m_org_y); m_cross_botleft.y = m_org_y; } else { // bottom-left cursor line intersects m_org_x m_cross_botleft.x = m_org_x; m_cross_botleft.y = y - (x - m_org_x); } if( m_max_x-x > y-m_org_y ) { // bottom-right cursor line intersects m_org_y m_cross_botright.x = x + (y - m_org_y); m_cross_botright.y = m_org_y; } else { // bottom-right cursor line intersects m_max_x m_cross_botright.x = m_max_x; m_cross_botright.y = y - (m_max_x - x); } if( x-m_org_x > m_max_y-y ) { // top-left cursor line intersects m_max_y m_cross_topleft.x = x - (m_max_y - y); m_cross_topleft.y = m_max_y; } else { // top-left cursor line intersects m_org_x m_cross_topleft.x = m_org_x; m_cross_topleft.y = y + (x - m_org_x); } if( m_max_x-x > m_max_y-y ) { // top-right cursor line intersects m_max_y m_cross_topright.x = x + (m_max_y - y); m_cross_topright.y = m_max_y; } else { // top-right cursor line intersects m_max_x m_cross_topright.x = m_max_x; m_cross_topright.y = y + (m_max_x - x); } pDC->MoveTo( m_cross_left ); pDC->LineTo( m_cross_right ); pDC->MoveTo( m_cross_bottom ); pDC->LineTo( m_cross_top ); if( m_cross_hairs == 2 ) { pDC->MoveTo( m_cross_topleft ); pDC->LineTo( m_cross_botright ); pDC->MoveTo( m_cross_botleft ); pDC->LineTo( m_cross_topright ); } } pDC->SelectObject( old_pen ); pDC->SetBkColor( bk ); } // restore drawing mode pDC->SetROP2( old_ROP2 ); return; } // Stop dragging // int CDisplayList::StopDragging() { m_drag_flag = 0; m_drag_num_lines = 0; m_drag_num_ratlines = 0; m_cross_hairs = 0; m_last_drag_shape = DS_NONE; return 0; } // Change the drag layer and/or width for DS_LINE_VERTEX // if ww = 0, don't change width // void CDisplayList::ChangeRoutingLayer( CDC * pDC, int layer1, int layer2, int ww ) { int w = ww; if( !w ) w = m_drag_w1*m_pcbu_per_wu; int old_ROP2 = pDC->GetROP2(); pDC->SetROP2( R2_XORPEN ); if( m_drag_shape == DS_LINE_VERTEX ) { CPen pen_old( PS_SOLID, 1, m_rgb[m_drag_layer_2] ); CPen pen_old_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); CPen pen( PS_SOLID, 1, m_rgb[layer2] ); CPen pen_w( PS_SOLID, w/m_pcbu_per_wu, m_rgb[layer1] ); // undraw segments CPen * old_pen = pDC->SelectObject( &pen_old_w ); pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); pDC->SelectObject( &pen_old ); pDC->LineTo( m_drag_xf, m_drag_yf ); // redraw segments pDC->SelectObject( &pen_w ); pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); pDC->SelectObject( &pen ); pDC->LineTo( m_drag_xf, m_drag_yf ); // update variables m_drag_layer_1 = layer1; m_drag_layer_2 = layer2; m_drag_w1 = w/m_pcbu_per_wu; // see if leading via needs to be changed if( ( (m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && !m_drag_via_drawn ) || (!(m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && m_drag_via_drawn ) ) { // draw or undraw via int thick = (m_drag_via_w - m_drag_via_holew)/2; int w = m_drag_via_w - thick; int holew = m_drag_via_holew; // CPen pen( PS_SOLID, thick, m_rgb[LAY_PAD_THRU] ); CPen pen( PS_SOLID, thick, m_rgb[m_drag_layer_1] ); CPen * old_pen = pDC->SelectObject( &pen ); CBrush black_brush( C_RGB::black ); CBrush * old_brush = pDC->SelectObject( &black_brush ); pDC->Ellipse( m_drag_xi - w/2, m_drag_yi - w/2, m_drag_xi + w/2, m_drag_yi + w/2 ); pDC->SelectObject( old_brush ); pDC->SelectObject( old_pen ); m_drag_via_drawn = 1 - m_drag_via_drawn; } } else if( m_drag_shape == DS_LINE ) { CPen pen_old_w( PS_SOLID, m_drag_w1, m_rgb[m_drag_layer_1] ); CPen pen( PS_SOLID, 1, m_rgb[layer2] ); CPen pen_w( PS_SOLID, w/m_pcbu_per_wu, m_rgb[layer1] ); // undraw segments CPen * old_pen = pDC->SelectObject( &pen_old_w ); pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); // redraw segments pDC->SelectObject( &pen_w ); pDC->MoveTo( m_drag_xi, m_drag_yi ); pDC->LineTo( m_drag_x, m_drag_y ); // update variables m_drag_layer_1 = layer1; m_drag_w1 = w/m_pcbu_per_wu; // see if leading via needs to be changed if( ( (m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && !m_drag_via_drawn ) || (!(m_drag_layer_no_via != 0 && m_drag_layer_1 != m_drag_layer_no_via) && m_drag_via_drawn ) ) { // draw or undraw via int thick = (m_drag_via_w - m_drag_via_holew)/2; int w = m_drag_via_w - thick; int holew = m_drag_via_holew; // CPen pen( PS_SOLID, thick, m_rgb[LAY_PAD_THRU] ); CPen pen( PS_SOLID, thick, m_rgb[m_drag_layer_1] ); CPen * old_pen = pDC->SelectObject( &pen ); CBrush black_brush( C_RGB::black ); CBrush * old_brush = pDC->SelectObject( &black_brush ); pDC->Ellipse( m_drag_xi - w/2, m_drag_yi - w/2, m_drag_xi + w/2, m_drag_yi + w/2 ); pDC->SelectObject( old_brush ); pDC->SelectObject( old_pen ); m_drag_via_drawn = 1 - m_drag_via_drawn; } pDC->SelectObject( old_pen ); } // restore drawing mode pDC->SetROP2( old_ROP2 ); return; } // change angle by adding 90 degrees clockwise // void CDisplayList::IncrementDragAngle( CDC * pDC ) { m_drag_angle = (m_drag_angle + 90) % 360; CPoint zero(0,0); CPen drag_pen( PS_SOLID, 1, m_rgb[m_drag_layer] ); CPen *old_pen = pDC->SelectObject( &drag_pen ); int old_ROP2 = pDC->GetROP2(); pDC->SetROP2( R2_XORPEN ); // erase lines for( int il=0; il<m_drag_num_lines; il++ ) { pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); } for( int il=0; il<m_drag_num_ratlines; il++ ) { pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); } // rotate points, redraw lines for( int il=0; il<m_drag_num_lines; il++ ) { RotatePoint( &m_drag_line_pt[2*il], 90, zero ); RotatePoint( &m_drag_line_pt[2*il+1], 90, zero ); pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); } for( int il=0; il<m_drag_num_ratlines; il++ ) { RotatePoint( &m_drag_ratline_end_pt[il], 90, zero ); pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); } pDC->SelectObject( old_pen ); pDC->SetROP2( old_ROP2 ); m_drag_vert = 1 - m_drag_vert; } // flip to opposite side of board // void CDisplayList::FlipDragSide( CDC * pDC ) { m_drag_side = 1 - m_drag_side; CPen drag_pen( PS_SOLID, 1, m_rgb[m_drag_layer] ); CPen *old_pen = pDC->SelectObject( &drag_pen ); int old_ROP2 = pDC->GetROP2(); pDC->SetROP2( R2_XORPEN ); // erase lines for( int il=0; il<m_drag_num_lines; il++ ) { pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); } for( int il=0; il<m_drag_num_ratlines; il++ ) { pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); } // modify drag lines for( int il=0; il<m_drag_num_lines; il++ ) { if( m_drag_vert == 0 ) { m_drag_line_pt[2*il].x = -m_drag_line_pt[2*il].x; m_drag_line_pt[2*il+1].x = -m_drag_line_pt[2*il+1].x; } else { m_drag_line_pt[2*il].y = -m_drag_line_pt[2*il].y; m_drag_line_pt[2*il+1].y = -m_drag_line_pt[2*il+1].y; } } for( int il=0; il<m_drag_num_ratlines; il++ ) { if( m_drag_vert == 0 ) { m_drag_ratline_end_pt[il].x = -m_drag_ratline_end_pt[il].x; } else { m_drag_ratline_end_pt[il].y = -m_drag_ratline_end_pt[il].y; } } // redraw lines for( int il=0; il<m_drag_num_lines; il++ ) { pDC->MoveTo( m_drag_x+m_drag_line_pt[2*il].x, m_drag_y+m_drag_line_pt[2*il].y ); pDC->LineTo( m_drag_x+m_drag_line_pt[2*il+1].x, m_drag_y+m_drag_line_pt[2*il+1].y ); } for( int il=0; il<m_drag_num_ratlines; il++ ) { pDC->MoveTo( m_drag_ratline_start_pt[il].x, m_drag_ratline_start_pt[il].y ); pDC->LineTo( m_drag_x+m_drag_ratline_end_pt[il].x, m_drag_y+m_drag_ratline_end_pt[il].y ); } pDC->SelectObject( old_pen ); pDC->SetROP2( old_ROP2 ); // if part was vertical, rotate 180 degrees if( m_drag_vert ) { IncrementDragAngle( pDC ); IncrementDragAngle( pDC ); } } // get any changes in side which occurred while dragging // int CDisplayList::GetDragSide() { return m_drag_side; } // get any changes in angle which occurred while dragging // int CDisplayList::GetDragAngle() { return m_drag_angle; } int CDisplayList::MakeDragLineArray( int num_lines ) { if( m_drag_line_pt ) free( m_drag_line_pt ); m_drag_line_pt = (CPoint*)calloc( 2*num_lines, sizeof(CPoint) ); if( !m_drag_line_pt ) return 1; m_drag_max_lines = num_lines; m_drag_num_lines = 0; return 0; } int CDisplayList::MakeDragRatlineArray( int num_ratlines, int width ) { if( m_drag_ratline_start_pt ) free(m_drag_ratline_start_pt ); m_drag_ratline_start_pt = (CPoint*)calloc( num_ratlines, sizeof(CPoint) ); if( !m_drag_ratline_start_pt ) return 1; if( m_drag_ratline_end_pt ) free(m_drag_ratline_end_pt ); m_drag_ratline_end_pt = (CPoint*)calloc( num_ratlines, sizeof(CPoint) ); if( !m_drag_ratline_end_pt ) return 1; m_drag_ratline_width = width; m_drag_max_ratlines = num_ratlines; m_drag_num_ratlines = 0; return 0; } int CDisplayList::AddDragLine( CPoint pi, CPoint pf ) { if( m_drag_num_lines >= m_drag_max_lines ) return 1; m_drag_line_pt[2*m_drag_num_lines].x = pi.x/m_pcbu_per_wu; m_drag_line_pt[2*m_drag_num_lines].y = pi.y/m_pcbu_per_wu; m_drag_line_pt[2*m_drag_num_lines+1].x = pf.x/m_pcbu_per_wu; m_drag_line_pt[2*m_drag_num_lines+1].y = pf.y/m_pcbu_per_wu; m_drag_num_lines++; return 0; } int CDisplayList::AddDragRatline( CPoint pi, CPoint pf ) { if( m_drag_num_ratlines == m_drag_max_ratlines ) return 1; m_drag_ratline_start_pt[m_drag_num_ratlines].x = pi.x/m_pcbu_per_wu; m_drag_ratline_start_pt[m_drag_num_ratlines].y = pi.y/m_pcbu_per_wu; m_drag_ratline_end_pt[m_drag_num_ratlines].x = pf.x/m_pcbu_per_wu; m_drag_ratline_end_pt[m_drag_num_ratlines].y = pf.y/m_pcbu_per_wu; m_drag_num_ratlines++; return 0; } // add element to highlight layer (if the orig_layer is visible) // int CDisplayList::HighLight( int gtype, int x, int y, int xf, int yf, int w, int orig_layer ) { id h_id; Add( h_id, NULL, LAY_HILITE, gtype, 1, w, 0, 0, x, y, xf, yf, x, y, 0, orig_layer ); return 0; } int CDisplayList::CancelHighLight() { RemoveAllFromLayer( LAY_HILITE ); return 0; } // Set the device context and memory context to world coords // void CDisplayList::SetDCToWorldCoords( CDC * pDC, CDC * mDC, int pcbu_org_x, int pcbu_org_y ) { memDC = NULL; if( pDC ) { // set window scale (WU per pixel) and origin (WU) pDC->SetMapMode( MM_ANISOTROPIC ); pDC->SetWindowExt( w_ext_x, w_ext_y ); pDC->SetWindowOrg( pcbu_org_x/m_pcbu_per_wu, pcbu_org_y/m_pcbu_per_wu ); // set viewport to client rect with origin in lower left // leave room for m_left_pane to the left of the PCB drawing area pDC->SetViewportExt( v_ext_x, v_ext_y ); pDC->SetViewportOrg( m_pane_org_x, m_pane_org_y ); } if( mDC->m_hDC ) { // set window scale (units per pixel) and origin (units) mDC->SetMapMode( MM_ANISOTROPIC ); mDC->SetWindowExt( w_ext_x, w_ext_y ); mDC->SetWindowOrg( pcbu_org_x/m_pcbu_per_wu, pcbu_org_y/m_pcbu_per_wu ); // set viewport to client rect with origin in lower left // leave room for m_left_pane to the left of the PCB drawing area mDC->SetViewportExt( v_ext_x, v_ext_y ); mDC->SetViewportOrg( m_pane_org_x, m_pane_org_y ); // update pointer memDC = mDC; } } void CDisplayList::SetVisibleGrid( BOOL on, double grid ) { m_visual_grid_on = on; m_visual_grid_spacing = grid/m_pcbu_per_wu; } void CDisplayList::SetUpCrosshairs( int type, int x, int y ) { // set up cross hairs m_cross_hairs = type; m_cross_left.x = m_org_x; m_cross_left.y = y; m_cross_right.x = m_max_x; m_cross_right.y = y; m_cross_bottom.x = x; m_cross_bottom.y = m_org_y; m_cross_top.x = x; m_cross_top.y = m_max_y; if( x-m_org_x > y-m_org_y ) { // bottom-left cursor line intersects m_org_y m_cross_botleft.x = x - (y - m_org_y); m_cross_botleft.y = m_org_y; } else { // bottom-left cursor line intersects m_org_x m_cross_botleft.x = m_org_x; m_cross_botleft.y = y - (x - m_org_x); } if( m_max_x-x > y-m_org_y ) { // bottom-right cursor line intersects m_org_y m_cross_botright.x = x + (y - m_org_y); m_cross_botright.y = m_org_y; } else { // bottom-right cursor line intersects m_max_x m_cross_botright.x = m_max_x; m_cross_botright.y = y - (m_max_x - x); } if( x-m_org_x > m_max_y-y ) { // top-left cursor line intersects m_max_y m_cross_topleft.x = x - (m_max_y - y); m_cross_topleft.y = m_max_y; } else { // top-left cursor line intersects m_org_x m_cross_topleft.x = m_org_x; m_cross_topleft.y = y - (x - m_org_x); } if( m_max_x-x > m_max_y-y ) { // top-right cursor line intersects m_max_y m_cross_topright.x = x + (m_max_y - y); m_cross_topright.y = m_max_y; } else { // top-right cursor line intersects m_max_x m_cross_topright.x = m_max_x; m_cross_topright.y = y + (m_max_x - x); } } // Convert point in window coords to PCB units (i.e. nanometers) // CPoint CDisplayList::WindowToPCB( CPoint point ) { CPoint p; double test = ((point.x-m_pane_org_x)*m_wu_per_pixel_x + m_org_x)*m_pcbu_per_wu; p.x = test; test = ((point.y-m_pane_org_y)*m_wu_per_pixel_y + m_org_y)*m_pcbu_per_wu; p.y = test; return p; } // Convert point in screen coords to PCB units // CPoint CDisplayList::ScreenToPCB( CPoint point ) { CPoint p; p.x = point.x - m_screen_r.left; p.y = point.y - m_screen_r.top; p = WindowToPCB( p ); return p; } // Convert point in PCB units to screen coords // CPoint CDisplayList::PCBToScreen( CPoint point ) { CPoint p; p.x = (point.x - m_org_x*m_pcbu_per_wu)/m_pcbu_per_pixel_x+m_pane_org_x+m_screen_r.left; p.y = (point.y - m_org_y*m_pcbu_per_wu)/m_pcbu_per_pixel_y-m_bottom_pane_h+m_screen_r.bottom; return p; } void CDisplayList::UpdateRatlineWidth( int width ) { m_ratline_w = width / m_pcbu_per_wu; GetJob_traces( LAY_RAT_LINE )->UpdateLineWidths(m_ratline_w, LAY_RAT_LINE); GetJob_traces( LAY_SELECTION )->UpdateLineWidths(m_ratline_w, LAY_RAT_LINE); }
[ "freepcb@9bfb2a70-7351-0410-8a08-c5b0c01ed314", "jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314" ]
[ [ [ 1, 6 ], [ 8, 9 ], [ 25, 25 ], [ 27, 32 ], [ 41, 50 ], [ 57, 59 ], [ 65, 66 ], [ 68, 85 ], [ 118, 121 ], [ 132, 133 ], [ 135, 170 ], [ 172, 173 ], [ 175, 200 ], [ 202, 211 ], [ 213, 217 ], [ 228, 233 ], [ 245, 246 ], [ 249, 250 ], [ 278, 279 ], [ 281, 281 ], [ 319, 319 ], [ 321, 323 ], [ 377, 377 ], [ 395, 395 ], [ 434, 434 ], [ 436, 436 ], [ 438, 439 ], [ 441, 441 ], [ 443, 444 ], [ 451, 451 ], [ 453, 454 ], [ 456, 456 ], [ 458, 459 ], [ 461, 461 ], [ 464, 464 ], [ 466, 466 ], [ 468, 469 ], [ 471, 471 ], [ 473, 474 ], [ 476, 476 ], [ 478, 479 ], [ 481, 481 ], [ 483, 484 ], [ 486, 486 ], [ 488, 489 ], [ 491, 491 ], [ 493, 494 ], [ 496, 496 ], [ 498, 499 ], [ 501, 501 ], [ 503, 504 ], [ 507, 508 ], [ 515, 525 ], [ 532, 533 ], [ 535, 535 ], [ 538, 552 ], [ 554, 555 ], [ 564, 564 ], [ 567, 569 ], [ 571, 588 ], [ 590, 593 ], [ 596, 596 ], [ 602, 604 ], [ 606, 607 ], [ 610, 610 ], [ 615, 615 ], [ 660, 662 ], [ 665, 684 ], [ 686, 691 ], [ 693, 700 ], [ 702, 704 ], [ 706, 713 ], [ 715, 722 ], [ 724, 727 ], [ 729, 734 ], [ 736, 743 ], [ 746, 774 ], [ 777, 796 ], [ 799, 799 ], [ 801, 809 ], [ 812, 819 ], [ 821, 828 ], [ 831, 909 ], [ 911, 915 ], [ 917, 917 ], [ 919, 929 ], [ 932, 935 ], [ 942, 942 ], [ 949, 949 ], [ 951, 951 ], [ 956, 956 ], [ 958, 958 ], [ 960, 960 ], [ 966, 966 ], [ 1020, 1022 ], [ 1026, 1027 ], [ 1029, 1050 ], [ 1052, 1055 ], [ 1057, 1057 ], [ 1059, 1065 ], [ 1070, 1071 ], [ 1073, 1077 ], [ 1079, 1079 ], [ 1081, 1084 ], [ 1087, 1088 ], [ 1090, 1108 ], [ 1110, 1182 ], [ 1184, 1244 ], [ 1246, 1250 ], [ 1253, 1298 ], [ 1300, 1301 ], [ 1303, 1305 ], [ 1307, 1314 ], [ 1316, 1331 ], [ 1333, 1350 ], [ 1352, 1377 ], [ 1379, 1382 ], [ 1385, 1397 ], [ 1399, 1425 ], [ 1428, 1447 ], [ 1450, 1451 ], [ 1453, 1458 ], [ 1460, 1471 ], [ 1473, 1477 ], [ 1479, 1484 ], [ 1486, 1537 ], [ 1539, 1560 ], [ 1562, 1565 ], [ 1567, 1572 ], [ 1574, 1582 ], [ 1584, 1608 ], [ 1610, 1614 ], [ 1617, 1708 ], [ 1710, 1731 ], [ 1733, 1734 ], [ 1739, 1745 ], [ 1747, 1751 ], [ 1754, 1766 ], [ 1769, 1769 ], [ 1771, 1779 ], [ 1783, 1787 ], [ 1789, 1792 ], [ 1794, 1805 ], [ 1808, 1808 ], [ 1810, 1818 ], [ 1820, 1833 ], [ 1835, 1838 ], [ 1840, 1850 ], [ 1852, 1877 ], [ 1879, 2022 ], [ 2024, 2034 ], [ 2036, 2061 ], [ 2063, 2141 ], [ 2143, 2143 ], [ 2145, 2166 ], [ 2168, 2171 ], [ 2175, 2175 ] ], [ [ 7, 7 ], [ 10, 24 ], [ 26, 26 ], [ 33, 40 ], [ 51, 56 ], [ 60, 64 ], [ 67, 67 ], [ 86, 117 ], [ 122, 131 ], [ 134, 134 ], [ 171, 171 ], [ 174, 174 ], [ 201, 201 ], [ 212, 212 ], [ 218, 227 ], [ 234, 244 ], [ 247, 248 ], [ 251, 277 ], [ 280, 280 ], [ 282, 318 ], [ 320, 320 ], [ 324, 376 ], [ 378, 394 ], [ 396, 433 ], [ 435, 435 ], [ 437, 437 ], [ 440, 440 ], [ 442, 442 ], [ 445, 450 ], [ 452, 452 ], [ 455, 455 ], [ 457, 457 ], [ 460, 460 ], [ 462, 463 ], [ 465, 465 ], [ 467, 467 ], [ 470, 470 ], [ 472, 472 ], [ 475, 475 ], [ 477, 477 ], [ 480, 480 ], [ 482, 482 ], [ 485, 485 ], [ 487, 487 ], [ 490, 490 ], [ 492, 492 ], [ 495, 495 ], [ 497, 497 ], [ 500, 500 ], [ 502, 502 ], [ 505, 506 ], [ 509, 514 ], [ 526, 531 ], [ 534, 534 ], [ 536, 537 ], [ 553, 553 ], [ 556, 563 ], [ 565, 566 ], [ 570, 570 ], [ 589, 589 ], [ 594, 595 ], [ 597, 601 ], [ 605, 605 ], [ 608, 609 ], [ 611, 614 ], [ 616, 659 ], [ 663, 664 ], [ 685, 685 ], [ 692, 692 ], [ 701, 701 ], [ 705, 705 ], [ 714, 714 ], [ 723, 723 ], [ 728, 728 ], [ 735, 735 ], [ 744, 745 ], [ 775, 776 ], [ 797, 798 ], [ 800, 800 ], [ 810, 811 ], [ 820, 820 ], [ 829, 830 ], [ 910, 910 ], [ 916, 916 ], [ 918, 918 ], [ 930, 931 ], [ 936, 941 ], [ 943, 948 ], [ 950, 950 ], [ 952, 955 ], [ 957, 957 ], [ 959, 959 ], [ 961, 965 ], [ 967, 1019 ], [ 1023, 1025 ], [ 1028, 1028 ], [ 1051, 1051 ], [ 1056, 1056 ], [ 1058, 1058 ], [ 1066, 1069 ], [ 1072, 1072 ], [ 1078, 1078 ], [ 1080, 1080 ], [ 1085, 1086 ], [ 1089, 1089 ], [ 1109, 1109 ], [ 1183, 1183 ], [ 1245, 1245 ], [ 1251, 1252 ], [ 1299, 1299 ], [ 1302, 1302 ], [ 1306, 1306 ], [ 1315, 1315 ], [ 1332, 1332 ], [ 1351, 1351 ], [ 1378, 1378 ], [ 1383, 1384 ], [ 1398, 1398 ], [ 1426, 1427 ], [ 1448, 1449 ], [ 1452, 1452 ], [ 1459, 1459 ], [ 1472, 1472 ], [ 1478, 1478 ], [ 1485, 1485 ], [ 1538, 1538 ], [ 1561, 1561 ], [ 1566, 1566 ], [ 1573, 1573 ], [ 1583, 1583 ], [ 1609, 1609 ], [ 1615, 1616 ], [ 1709, 1709 ], [ 1732, 1732 ], [ 1735, 1738 ], [ 1746, 1746 ], [ 1752, 1753 ], [ 1767, 1768 ], [ 1770, 1770 ], [ 1780, 1782 ], [ 1788, 1788 ], [ 1793, 1793 ], [ 1806, 1807 ], [ 1809, 1809 ], [ 1819, 1819 ], [ 1834, 1834 ], [ 1839, 1839 ], [ 1851, 1851 ], [ 1878, 1878 ], [ 2023, 2023 ], [ 2035, 2035 ], [ 2062, 2062 ], [ 2142, 2142 ], [ 2144, 2144 ], [ 2167, 2167 ], [ 2172, 2174 ], [ 2176, 2178 ] ] ]
f5f855b48dc2683ebe423295ead0a0321ab14ff0
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/CitySimpleAddForm.h
e600d48c97473ee10a28a7fd930662f20bd52c06
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,320
h
//--------------------------------------------------------------------------- #ifndef CitySimpleAddFormH #define CitySimpleAddFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "CitySimpleProcessForm.h" #include "VStringStorage.h" #include <ExtCtrls.hpp> #include "RxGrdCpt.h" #include "VCustomKeyComboBox.h" #include "VMemoKeyComboBox.h" enum TourCitySimpleAddStringsTypes { TourCitySimpleAddCityFieldExistErrorMessageStr = TourCitySimpleProcessCityStringsCount, TourCitySimpleAddCityFieldExistExceptionMessageStr }; //--------------------------------------------------------------------------- class TTourCitySimpleAddForm : public TTourCitySimpleProcessForm { __published: // IDE-managed Components void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose); private: // User declarations public: // User declarations __fastcall TTourCitySimpleAddForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTourCitySimpleAddForm *TourCitySimpleAddForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 35 ] ] ]
ea92d7ae6f01746d571aa2f31da5a5c4dad140c3
6131815bf1b62accfc529c2bc9db21194c7ba545
/FrameworkApp/Server.cpp
c1b329175f2112630e0ecea8de04c50a5f09ec62
[]
no_license
dconefourseven/honoursproject
b2ee664ccfc880c008f29d89aad03d9458480fc8
f26b967fda8eb6937f574fd6f3eb76c8fecf072a
refs/heads/master
2021-05-29T07:14:35.261586
2011-05-15T18:27:49
2011-05-15T18:27:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,108
cpp
#include "Server.h" #include <cassert> extern bool QuitApplication; Server::Server() { mutexHandle = NULL; sa_size = sizeof(sockaddr); HasConnection = false; hostIP = new char[20]; m_DInput = new DirectInput(); } Server::~Server() { } bool Server::InitialiseNetworking() { printf("Server Program\n"); printf("By Henry S Fortuna\n\n"); printf("Modified and extended by David Clarke\n"); mutexHandle = CreateMutex(NULL, false, NULL); PrintQueue.LoadThread(&mutexHandle, &SendQ, &ReceiveQ, &SendQUDP, &ReceiveQUDP); PrintQueue.begin(); printf("Beginning Network Application\n"); if(!StartWinSock2()) return false; GetHostIPAddress(); printf("Host IP: %s\n",hostIP); m_Sockets[0].LoadSocket(); m_Sockets[0].LoadAddress(SERVERPORT, hostIP); printf("The IP address is: "); printf("%d.", (int)m_Sockets[0].GetAddress().sin_addr.S_un.S_un_b.s_b1); printf("%d.", (int)m_Sockets[0].GetAddress().sin_addr.S_un.S_un_b.s_b2); printf("%d.", (int)m_Sockets[0].GetAddress().sin_addr.S_un.S_un_b.s_b3); printf("%d\n", (int)m_Sockets[0].GetAddress().sin_addr.S_un.S_un_b.s_b4); printf("My PORT address is: "); printf("%d\n", (int)m_Sockets[0].GetPortNumber()); // Bind the listening socket if (!m_Sockets[0].BindSocketToAddress()) { WSACleanup (); return false; } // Set s[0] to listen for connections if (!m_Sockets[0].MakeListeningSocket()) { WSACleanup (); return false; } m_UDPSocket.LoadSocket(); m_UDPSocket.LoadAddress(1500, m_Sockets[0].GetAddress().sin_addr); UDPRemoteAddress.sin_family = AF_INET; UDPRemoteAddress.sin_port = htons (1501); UDPRemoteAddress.sin_addr.s_addr = m_Sockets[0].GetAddress().sin_addr.s_addr; if(!m_UDPSocket.BindSocketToAddress()) { WSACleanup(); return false; } if(!m_UDPSocket.MakeSocketNonBlocking()) { WSACleanup(); return false; } // Create some file descriptor sets FD_ZERO(&Master); // Clear the sets FD_ZERO(&fd_tmp); FD_ZERO(&fd_except); FD_SET(m_Sockets[0].GetSocket(), &Master); // Put listening socket in set FD_SET(m_Sockets[0].GetSocket(), &fd_except); // Put listening socket in set FD_SET(m_UDPSocket.GetSocket(), &Master); timeout.tv_sec=0; // or until some activity timeout.tv_usec=015000; connectionCount = 0; // Keep track of number of connections UDPSocketRW.LoadThread(m_UDPSocket.GetSocket(), 0, mutexHandle, &SendQUDP, &ReceiveQUDP, m_UDPSocket.GetAddress(), UDPRemoteAddress); UDPSocketRW.begin(); printf("Listening for a connections...\n"); printf("Number of current connection = %d\n\n", connectionCount); m_BroadcastSocket.LoadSocket(); m_BroadcastSocket.LoadBroadcast(2500); m_BroadcastListener.LoadSocket(); m_BroadcastListener.LoadAddress(2501); if(!m_BroadcastSocket.MakeSocketBroadcasting()) { WSACleanup(); return false; } if(!m_BroadcastListener.BindSocketToAddress()) { printf("cannot bind port number %d \n", 2501); WSACleanup(); return false; } FD_SET(m_BroadcastListener.GetSocket(), &Master); return true; } void Server::UpdateNetworking() { if(QuitApplication) PostQuitMessage(0); WaitForSingleObject(mutexHandle, INFINITE); UDPSocketRW.threadProc(); // Get working copy of sets fd_tmp = Master; fd_except = Master; // Look for socket activity select(0, &fd_tmp, NULL, &fd_except, &timeout); sprintf_s(broadcastPacket.IPAddress, sizeof(broadcastPacket.IPAddress), hostIP); sendto(m_BroadcastSocket.GetSocket(), (char*)&broadcastPacket, sizeof(broadcastPacket), 0, (struct sockaddr*)&m_BroadcastSocket.GetAddress(), sizeof(sockaddr_in)); if(FD_ISSET(m_BroadcastListener.GetSocket(), &fd_tmp)) { int sa_in_size = sizeof(sockaddr_in); recvfrom(m_BroadcastListener.GetSocket(), (char*)&broadcastPacket, sizeof(broadcastPacket), 0, (struct sockaddr*)m_BroadcastListener.GetAddressPointer(), &sa_in_size); if(UDPRemoteAddress.sin_addr.s_addr != m_BroadcastListener.GetAddress().sin_addr.s_addr) { UDPRemoteAddress.sin_addr = m_BroadcastListener.GetAddress().sin_addr; UDPSocketRW.ReloadRemoteAddress(UDPRemoteAddress); printf("The IP address of UDP YOU is: "); printf("%d.", (int)UDPRemoteAddress.sin_addr.S_un.S_un_b.s_b1); printf("%d.", (int)UDPRemoteAddress.sin_addr.S_un.S_un_b.s_b2); printf("%d.", (int)UDPRemoteAddress.sin_addr.S_un.S_un_b.s_b3); printf("%d\n", (int)UDPRemoteAddress.sin_addr.S_un.S_un_b.s_b4); } } // Has there been a socket exception? if(FD_ISSET(m_Sockets[0].GetSocket(), &fd_except)) { //deal with it //cout << "exception on listening socket" << endl; printf("exception on listening socket\n"); system("pause"); CleanUp(); exit(0); } // Process any connection attempts if(FD_ISSET(m_Sockets[0].GetSocket(), &fd_tmp)) { int Sock_Num, Accepted; Accepted = 0; // find a free socket for client for(int j=1; j<NUMCONN; j++) { if(m_Sockets[j].GetSocket() == 0) { Sock_Num = j; m_Sockets[Sock_Num].SetSocket(accept (m_Sockets[0].GetSocket(),&you,&sa_size)); if (m_Sockets[Sock_Num].GetSocket()==INVALID_SOCKET) { printf("Error: Unable to accept connection!\n"); system("pause"); CleanUp(); exit(0); } printf("Accepted Client on socket %d\n", j); Accepted = 1; break; } } if (Accepted) { printf("Client has connected!\n"); sprintf_s (testPacket.Buffer, sizeof(testPacket),"%c",MSG_CONNECTED); //A printf ("The Following has been sent -> %c\n", testPacket.Buffer[0]); send (m_Sockets[Sock_Num].GetSocket(),(char *)&testPacket,sizeof(MyPacket_t),0); FD_SET(m_Sockets[Sock_Num].GetSocket(), &Master); SocketRW[Sock_Num].LoadThread(m_Sockets[Sock_Num].GetSocket(), Sock_Num, &mutexHandle, &SendQ, &ReceiveQ, Master, &connectionCount ); SocketRW[Sock_Num].begin(); HasConnection = true; connectionCount++; } else { printf("Can't accept any more connections\n"); SOCKET s_tmp = accept (m_Sockets[Sock_Num].GetSocket(),&you,&sa_size); closesocket (s_tmp); } } fd_tmp = Master; for(int i = 1; i < NUMCONN; i++) { if(FD_ISSET(m_Sockets[i].GetSocket(), &fd_tmp)) { bool flag = SocketRW[i].GetConnectionClosed(); //Ensure the sockets are zero if they aren't assigned to threads if(flag) { FD_CLR(m_Sockets[i].GetSocket(), &Master); m_Sockets[i].CloseSocket(); // close the connection m_Sockets[i].SetSocket(0); // reset to 0 for reuse connectionCount--; SocketRW[i].endRW(); SocketRW[i] = NULL; HasConnection = false; } } } ReleaseMutex(mutexHandle); } void Server::CleanUp() { // cleanup and exit for(int i=0;i<NUMCONN;i++) { SocketRW[i].endRW(); if(m_Sockets[i].GetSocket()) m_Sockets[i].CloseSocket(); } CloseHandle(mutexHandle); PrintQueue.end(); UDPSocketRW.end(); m_UDPSocket.CloseSocket(); WSACleanup (); printf("Quitting\n"); //Sleep(5000); } bool Server::StartWinSock2() { // Startup Winsock WSADATA w; int error = WSAStartup (0x0202,&w); if (error) { printf("Error: You need WinSock 2.2!\n"); return false; } if (w.wVersion!=0x0202) { printf("Error: Wrong WinSock version!\n"); WSACleanup (); return false; } return true; } void Server::GetHostIPAddress() { //get local machine IP on uni network char* hostname = new char[80]; gethostname(hostname, 80); hostent* hostInfo = gethostbyname(hostname); int infoSize = sizeof(hostInfo->h_addr_list) - 1; int i = 0; struct in_addr addr; if (hostInfo->h_addrtype == AF_INET) { while (hostInfo->h_addr_list[i] != 0) { addr.s_addr = *(u_long *) hostInfo->h_addr_list[i++]; sprintf_s(hostIP, 20, "%s", inet_ntoa(addr)); if(hostIP[0] == '1' && hostIP[0] == '9' && hostIP[0] == '2') { hostInfo->h_addr_list[i] = 0; //leave the loop } } } }
[ "davidclarke1990@fa56ba20-0011-6cdf-49b4-5b20436119f6" ]
[ [ [ 1, 324 ] ] ]
20f912cc205095c4281ce3dd0fd43cce65245cae
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Audio/OAL/OAL_AudioObject.cpp
50317d5725c5df4144946b3e231e945e045b0d38
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
2,891
cpp
#include "OAL_AudioObject.hpp" #include "OAL_AudioDriver.hpp" #include "../../Math/Math.hpp" #include "../Utility/OggVorbisUtil.hpp" #include <alc.h> using namespace Spiral; using namespace Spiral::Audio; OalAudioObject::OalAudioObject( ALuint sourceHandle, ALuint bufferHandle, ALuint dataHandle, OalAudioDriver* driver ): m_sourceHandle( sourceHandle ),m_bufferHandle( bufferHandle ),m_dataHandle(dataHandle),m_audioDriver( driver ) { } void OalAudioObject::DoPlay( bool looping ) { if( IsValidBuffer() ) { ALint loop = AL_FALSE; ALint state; if( looping == true ) { loop = AL_TRUE; } alGetSourcei( m_sourceHandle, AL_SOURCE_STATE, &state ); alSourcei( m_sourceHandle, AL_LOOPING, loop ); if( state != AL_PLAYING ) { alSourcePlay( m_sourceHandle ); } } } void OalAudioObject::DoStop() { if( IsValidBuffer() ) { alSourceStop( m_sourceHandle ); } } bool OalAudioObject::IsValidBuffer() const { return bool( m_bufferHandle != 0 && alIsBuffer( m_bufferHandle ) == AL_TRUE ); } OalAudioObject::~OalAudioObject() { Stop(); alDeleteBuffers( 1, &m_bufferHandle ); alDeleteSources( 1, &m_sourceHandle ); } void OalAudioObject::DoPause() { if( IsValidBuffer() ) { alSourcePause( m_sourceHandle ); } } void OalAudioObject::DoSetPosition( const Math::Vector3f& position ) { alSource3f( m_sourceHandle, AL_POSITION, position[0], position[1], position[2] ); } const Math::Vector3f OalAudioObject::DoGetPosition() const { ALfloat position[3]; alGetSourcefv( m_sourceHandle, AL_POSITION, position ); return Math::Vector3f( position[0], position[1], position[2] ); } Cloneable* OalAudioObject::DoClone() const { ALuint srcHandle,bufferHandle = 0; alGenSources( 1, &srcHandle ); if( IsValidBuffer() ) { alGenBuffers( 1, &bufferHandle ); CloneBufferToHandle( bufferHandle ); } OalAudioObject* cloneObject = new OalAudioObject( srcHandle, bufferHandle, m_dataHandle, m_audioDriver ); return cloneObject; } void OalAudioObject::CloneBufferToHandle( ALuint toHandle )const { ALint channels, size, bits, freq; ALenum format; alGetBufferi( m_bufferHandle, AL_CHANNELS, &channels ); alGetBufferi( m_bufferHandle, AL_SIZE, &size ); alGetBufferi( m_bufferHandle, AL_BITS, &bits ); alGetBufferi( m_bufferHandle, AL_FREQUENCY, &freq ); if( bits == 16 ) { format = channels > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; }else if( bits == 8 ) { format = channels > 1 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; } const boost::int8_t* srcData = m_audioDriver->GetBufferData( m_dataHandle ); if( srcData != NULL ) { alBufferData( toHandle, format, srcData, size, freq ); } } void OalAudioObject::DoSetVolume( SpReal vol ) { alSourcef( m_sourceHandle, AL_GAIN, vol ); AudioUtil::ReportALErrors(); }
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 126 ] ] ]
8a2f4afa6bcec34a8c2f119b8d700bdcff7fa14e
814e67bf5d1c2f2e233b3ec1ee07faaaa65a9951
/compiladormarvel/ArvoreIntermediaria.cpp
65c3ebfcc1b391b7ec8d728760c066a24e5caf6b
[]
no_license
lsalamon/compiladormarvel
686a5814e363fee41163d8a447d6753ebe84d220
55ea7a3f3cb76ec738e792e608ab01a9f48e5f8b
refs/heads/master
2021-01-10T08:17:50.321427
2009-03-20T14:06:43
2009-03-20T14:06:43
50,113,476
0
0
null
null
null
null
UTF-8
C++
false
false
5,501
cpp
#include <stdlib.h> #include <stdio.h> #include <typeinfo> #include "ArvoreIntermediaria.h" //ExpList ExpList::ExpList(Exp *prim, ExpList *prox){ this->prim = prim; this->prox = prox; }; void ExpList::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList::~ExpList(){}; //StmList StmList::StmList(Stm *prim, StmList *prox){ this->prim = prim; this->prox = prox; }; void StmList::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; StmList::~StmList(){}; // CONST CONST::CONST(int value){ this->value = value; }; void CONST::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * CONST::kids(){ return NULL; }; Exp * CONST::build(ExpList * kids){ return new CONST(this->value); }; CONST::~CONST(){}; //CONSTF CONSTF::CONSTF(float value){ this->value = value; }; void CONSTF::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * CONSTF::kids(){ return NULL; }; Exp * CONSTF::build(ExpList * kids){ return new CONSTF(this->value); }; CONSTF::~CONSTF(){}; //NAME NAME::NAME(Label *l){ this->l = l; }; void NAME::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * NAME::kids(){ return NULL; }; Exp * NAME::build(ExpList * kids){ return new NAME(this->l); }; NAME::~NAME(){}; //TEMP TEMP::TEMP(Temp *t){ this->t = t; }; void TEMP::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * TEMP::kids(){ return NULL; }; Exp * TEMP::build(ExpList * kids){ return new TEMP(this->t); }; TEMP::~TEMP(){}; //BINOP BINOP::BINOP(int binOP, Exp *left, Exp *right){ this->binOP = binOP; this->left = left; this->right = right; }; void BINOP::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * BINOP::kids(){ return new ExpList(this->left, new ExpList(this->right,NULL)); }; Exp * BINOP::build(ExpList * kids){ return new BINOP(this->binOP, kids->prim, kids->prox->prim); }; BINOP::~BINOP() {}; //MEM MEM::MEM(Exp *e){ this->e = e; } void MEM::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * MEM::kids(){ return new ExpList(this->e, NULL); }; Exp * MEM::build(ExpList * kids){ return new MEM(kids->prim); }; MEM::~MEM(){}; //CALL CALL::CALL(Exp *func, ExpList *args){ this->func = func; this->args = args; }; void CALL::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * CALL::kids(){ return new ExpList(this->func, this->args); }; Exp * CALL::build(ExpList * kids){ return new CALL(kids->prim, kids->prox); }; CALL::~CALL(){}; //ESEQ ESEQ::ESEQ(Stm *s, Exp *e){ this->s = s; this->e = e; }; void ESEQ::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * ESEQ::kids(){ return NULL; } Exp * ESEQ::build(ExpList * kids){ return NULL; }; ESEQ::~ESEQ(){}; //MOVE MOVE::MOVE(Exp *dst, Exp *src){ this->dst = dst; this->src = src; }; void MOVE::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList *MOVE::kids() { if (typeid(* this->dst).name() == typeid(MEM).name()) return new ExpList(this->dst, new ExpList(this->src, NULL)); else return new ExpList(this->src, NULL); } Stm *MOVE::build(ExpList *kids){ if (typeid(* this->dst).name() == typeid(MEM).name()) return new MOVE(new MEM(kids->prim), kids->prox->prim); else return new MOVE(this->dst , kids->prim); }; MOVE::~MOVE(){}; //EXP EXP::EXP(Exp *e){ this->e = e; }; void EXP::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList *EXP::kids() { return new ExpList(this->e , NULL); } Stm *EXP::build(ExpList *kids){ return new EXP(kids->prim); }; EXP::~EXP(){}; //JUMP JUMP::JUMP(Exp *e){ this->e = e; this->targets = NULL; }; JUMP::JUMP(Exp *e, LabelList *targets){ this->e = e; this->targets = targets; }; void JUMP::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList *JUMP::kids() { return new ExpList(this->e, NULL); } Stm *JUMP::build(ExpList *kids){ return new JUMP(kids->prim, this->targets); }; JUMP::~JUMP(){}; //CJUMP CJUMP::CJUMP(int relOp, Exp *left, Exp *right, Label *ifTrue, Label *ifFalse){ this->relOp = relOp; this->left = left; this->right = right; this->ifTrue = ifTrue; this->ifFalse = ifFalse; }; void CJUMP::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList * CJUMP::kids(){ return new ExpList(this->left , new ExpList(this->right,NULL)); }; Stm * CJUMP::build(ExpList *kids){ return new CJUMP(this->relOp , kids->prim, kids->prox->prim, this->ifTrue, this->ifFalse); }; CJUMP::~CJUMP(){}; //SEQ SEQ::SEQ(Stm *left, Stm *right){ this->left = left; this->right = right; }; void SEQ::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList *SEQ::kids(){ return NULL; }; Stm * SEQ::build(ExpList *kids){ return NULL; }; SEQ::~SEQ(){}; //LABEL LABEL::LABEL(Label *l){ this->l = l; }; void LABEL::accept(VisitorArvoreIntermediaria *v){ v->visit(this); }; ExpList *LABEL::kids(){ return NULL; }; Stm *LABEL::build(ExpList *kids){ return new LABEL(this->l); }; LABEL::~LABEL(){};
[ "gildo.leonel@df256a42-0e3e-0410-b2fe-0dffcef58804", "cslopes@df256a42-0e3e-0410-b2fe-0dffcef58804" ]
[ [ [ 1, 2 ], [ 4, 27 ], [ 29, 106 ], [ 108, 167 ], [ 183, 190 ], [ 196, 210 ], [ 219, 230 ], [ 240, 248 ], [ 250, 252 ], [ 254, 264 ], [ 266, 267 ], [ 269, 271 ] ], [ [ 3, 3 ], [ 28, 28 ], [ 107, 107 ], [ 168, 182 ], [ 191, 195 ], [ 211, 218 ], [ 231, 239 ], [ 249, 249 ], [ 253, 253 ], [ 265, 265 ], [ 268, 268 ] ] ]
3eb27810e3515e7b5a35868f8972feea1c03ef2b
5c165fbf269ec78254dee24696588355ebb05297
/Phoenix/PhoenixConsole.cpp
1608dba9cc6b5ad1c766611c7fc0b37c0f92d179
[]
no_license
kumorikarasu/Phoenix-Engine
dce69af719f3a1a38363aa6330b1d0bb4cdc991d
87bcfef06f4f57eb44a1c57a67e7ed76795667ec
refs/heads/master
2021-01-10T07:57:06.020395
2011-06-20T13:21:06
2011-06-20T13:21:06
55,923,401
0
0
null
null
null
null
UTF-8
C++
false
false
3,066
cpp
#include "PhoenixGlobal.h" #include "PhoenixConsole.h" #include "PhoenixUtil.h" #include "PhoenixRenderer.h" namespace PhoenixCore{ Console* Console::console = new Console(); Console* Console::Instance(){ if (console == NULL) console = new Console(); return console; } Console::Console() { m_btoggle=false; m_logfile = fopen("console_log.txt","a+"); fprintf(m_logfile,"\n\nBuildVer: %d TimeStamp:%d\n",0,time(NULL)); fclose(m_logfile); } Console::~Console() { } void Console::Draw(IRenderer * GDI) { if (this->m_btoggle){ GDI->DrawRectangle(Vertex2(0,0,Color(0.5f,0.5f,0.5f,0.5f)), Vertex2(GDI->getWidth(),0,Color(0.5f,0.5f,0.5f,0.5f)), Vertex2(GDI->getWidth(),200,Color(0.5f,0.5f,0.5f,0.5f)), Vertex2(0,200,Color(0.5f,0.5f,0.5f,0.5f))); if (m_lConsole.size() > 0){ std::list<sMessageLine>::reverse_iterator iter = m_lConsole.rbegin(); for (int i = 8; i>0; i--){ if (iter->m_type == C_WARNING){ GDI->DrawTextW(Vertex2(10, 2 + i*22,Color(1.0f,1.0f,0.0f)), iter->m_text); }else if (iter->m_type == C_ERROR){ GDI->DrawTextW(Vertex2(10, 2 + i*22,Color(1.0f,0.0f,0.0f)), iter->m_text); }else GDI->DrawTextW(Vertex2(10, 2 + i*22,Color(1.0f,1.0f,1.0f)), iter->m_text); ++iter; if (iter == m_lConsole.rend()) break; } } } } //outputs a line to ONLY the file log void Console::Log(const TCHAR* fmt, int _type, ...) { sMessageLine line; va_list va; va_start(va,_type); vswprintf(line.m_text,fmt,va); //print the line _tcscat(line.m_text,_T("\n")); console->m_logfile = fopen("console_log.txt","a+"); fwprintf(console->m_logfile,line.m_text); fclose(console->m_logfile); va_end(va); line.m_type = _type; } //Outputs a line to both the screen console and the file console void Console::Line(const TCHAR* fmt, int _type, ...) { sMessageLine line; va_list va; va_start(va,_type); vswprintf(line.m_text,fmt,va); line.m_type = _type; console->m_lConsole.push_back(line); //print the line _tcscat(line.m_text,_T("\n")); console->m_logfile = fopen("console_log.txt","a+"); fwprintf(console->m_logfile,line.m_text); fclose(console->m_logfile); va_end(va); /* va_list va; va_start(va, fmt); DWORD size = MultiByteToWideChar(CP_ACP,0,fmt,-1,NULL,0); wchar_t* sBuff = NULL; wchar_t* fm; fm = new wchar_t[size]; MultiByteToWideChar(CP_ACP,0,fmt,-1,fm,size); vswprintf(sBuff,fm, va); PString tBuff = reinterpret_cast < const wchar_t* > (sBuff); delete sBuff,fm; va_end(va); line.m_text = tBuff; line.m_type = _type; m_lConsole.push_back(line); */ } void Console::Input(bool key[]){ } }
[ [ [ 1, 132 ] ] ]
f18e0e92c118be179813bcc762dd7168f041de50
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/MyGUIEngine/src/MyGUI_ProgressFactory.cpp
6c76fe415508821446338aea2f52b7eeb55a06c8
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,508
cpp
/*! @file @author Albert Semenov @date 01/2008 @module */ #include "MyGUI_ProgressFactory.h" #include "MyGUI_Progress.h" #include "MyGUI_SkinManager.h" #include "MyGUI_WidgetManager.h" namespace MyGUI { namespace factory { ProgressFactory::ProgressFactory() { // ั€ะตะณะตัั‚ั€ะธั€ัƒะตะผ ัะตะฑั MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.registerFactory(this); // ั€ะตะณะตัั‚ั€ะธั€ัƒะตะผ ะฒัะต ะฟะฐั€ัะตั€ั‹ manager.registerDelegate("Progress_Range") = newDelegate(this, &ProgressFactory::Progress_Range); manager.registerDelegate("Progress_Position") = newDelegate(this, &ProgressFactory::Progress_Position); manager.registerDelegate("Progress_AutoTrack") = newDelegate(this, &ProgressFactory::Progress_AutoTrack); } ProgressFactory::~ProgressFactory() { // ัƒะดะฐะปัะตะผ ัะตะฑั MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.unregisterFactory(this); // ัƒะดะฐะปัะตะผ ะฒัะต ะฟะฐั€ัะตั€ั‹ manager.unregisterDelegate("Progress_Range"); manager.unregisterDelegate("Progress_Position"); manager.unregisterDelegate("Progress_AutoTrack"); } const Ogre::String& ProgressFactory::getType() { return Progress::_getType(); } WidgetPtr ProgressFactory::createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, const Ogre::String& _name) { return new Progress(_coord, _align, SkinManager::getInstance().getSkin(_skin), _parent, _name); } // ะผะตั‚ะพะดั‹ ะดะปั ะฟะฐั€ัะธะฝะณะฐ void ProgressFactory::Progress_Range(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value) { MYGUI_RETURN_IS_FALSE_TYPE(ProgressPtr, _widget, _key); static_cast<ProgressPtr>(_widget)->setProgressRange(utility::parseSizeT(_value)); } void ProgressFactory::Progress_Position(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value) { MYGUI_RETURN_IS_FALSE_TYPE(ProgressPtr, _widget, _key); static_cast<ProgressPtr>(_widget)->setProgressPosition(utility::parseSizeT(_value)); } void ProgressFactory::Progress_AutoTrack(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value) { MYGUI_RETURN_IS_FALSE_TYPE(ProgressPtr, _widget, _key); static_cast<ProgressPtr>(_widget)->setProgressAutoTrack(utility::parseBool(_value)); } } // namespace factory } // namespace MyGUI
[ [ [ 1, 71 ] ] ]
6c72f4010aba2c31330370e48377dda4209d66a3
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvmesh/import/MeshImportOBJ.cpp
bf4779918778d16830d5efb7f88a4e7c47221c51
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
3,407
cpp
// This code is in the public domain -- [email protected] #include <nvcore/StrLib.h> #include <nvcore/Tokenizer.h> #include <nvmath/Vector.h> #include "MeshImportOBJ.h" using namespace nv; /// Import an OBJ mesh. bool MeshImportOBJ::import(Stream * stream) { Tokenizer parser(stream); parser.setDelimiters("/"); m_builder.reset(); int positionCount = 0; int normalCount = 0; int texCoordCount = 0; try { float x, y, z; while (parser.nextLine()) { if (parser.token() == "v") { x = y = z = 0.0f; if (parser.nextToken()) x = parser.token().toFloat(); if (parser.nextToken()) y = parser.token().toFloat(); if (parser.nextToken()) z = parser.token().toFloat(); m_builder.addPosition(Vector3(x, y, z)); positionCount++; } else if (parser.token() == "vn") { x = y = z = 0.0f; if (parser.nextToken()) x = parser.token().toFloat(); if (parser.nextToken()) y = parser.token().toFloat(); if (parser.nextToken()) z = parser.token().toFloat(); m_builder.addNormal(Vector3(x, y, z)); normalCount++; } else if (parser.token() == "vt") { x = y = z = 0.0f; if (parser.nextToken()) x = parser.token().toFloat(); if (parser.nextToken()) y = parser.token().toFloat(); m_builder.addTexCoord(Vector2(x, y)); texCoordCount++; } else if (parser.token() == "f") { m_builder.beginPolygon(); bool tokenAvailable = false; while(tokenAvailable || parser.nextToken()) { int v = 0; int t = 0; int n = 0; v = parser.token().toInt(); tokenAvailable = parser.nextToken(); if (tokenAvailable && parser.token() == "/") { tokenAvailable = parser.nextToken(); if (tokenAvailable && parser.token() != "/") { t = parser.token().toInt(); tokenAvailable = parser.nextToken(); } if (tokenAvailable && parser.token() == "/") { tokenAvailable = parser.nextToken(); n = parser.token().toInt(); tokenAvailable = false; } } if(v < 0) v = positionCount - v; else if (v == 0) v = NIL; else v = v - 1; if(t < 0) t = positionCount - t; else if (t == 0) t = NIL; else t = t - 1; if(n < 0) n = positionCount - n; else if (n == 0) n = NIL; else n = n - 1; m_builder.addVertex(v, n, t); } m_builder.endPolygon(); } else if (parser.token() == "g") { // @@ Ignore groups. } else if (parser.token() == "s") { if (parser.nextToken()) { // @@ I'm not sure that a number is provided. uint group = parser.token().toUnsignedInt(); m_builder.beginGroup(group); } } else if (parser.token() == "usemtl") { // if (parser.nextToken()) { // m_builder.beginMaterial(parser.token().toString()); // } } } } catch(TokenizerException) { m_builder.reset(); return false; } m_builder.optimize(); m_builder.done(); return true; } // This doesn't work on MSVC! class MeshImportFactoryOBJ : public MeshImportFactory { public: virtual const char * extension() const { return ".obj"; } virtual MeshImport * createImporter() const { return new MeshImportOBJ(); } }; NV_REGISTER_MESH_IMPORT_FACTORY(MeshImportFactoryOBJ);
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 136 ] ] ]
4de5234ed816a15041a05d5aa8e4ed2d89808c71
6b75de27b75015e5622bfcedbee0bf65e1c6755d
/Queue_tree/SeqQueue.h
0dd73b62556123c03b24bf0a188c0cb54a524636
[]
no_license
xhbang/data_structure
6e4ac9170715c0e45b78f8a1b66c838f4031a638
df2ff9994c2d7969788f53d90291608ac5b1ef2b
refs/heads/master
2020-04-04T02:07:18.620014
2011-12-05T09:39:34
2011-12-05T09:39:34
2,393,408
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
h
#include <iostream> using namespace std; #ifndef SEQ_QUEUE_H #define SEQ_QUEUE_H template <typename T> class SeqQueue{ private: T *data; int front; int rear; int size; public: SeqQueue(int defaultSize=100):size(defaultSize),front(0),rear(0){ data =new T[defaultSize]; } ~SeqQueue(){ delete [ ]data; //never forget the "[ ]" front=rear=size=0; //ไนŸ่ฎธๆ˜ฏๅคšไฝ™็š„ } int En_Queue(T item); //่ฟ”ๅ›ž1ๆˆๅŠŸ T De_Queue(); //ไผšๅˆ ๅŽป T Front_Queue(); //ๅช่ฏป int Is_Empty(); }; template <typename T> int SeqQueue<T>::En_Queue(T item){ if(((rear+1)%size)!=front){ data[rear]=item; rear=(rear+1)%size; return 1; } else return 0; } template <typename T> T SeqQueue<T>::De_Queue(){ if(front!=rear){ T x=data[front]; front=(front+1)%size; return x; } else return 0; } template <typename T> T SeqQueue<T>::Front_Queue(){ if(front!=rear){ T x=data[front]; return x; } else return 0; } template <typename T> int SeqQueue<T>::Is_Empty(){ return rear==front; } //test /* int main(){ SeqQueue<int> q; for(int i=0;i<5;i++) q.En_Queue(i); int num; while(!q.Is_Empty()){ num=q.De_Queue(); cout<<num<<"\t"; } return 0; } */ #endif
[ [ [ 1, 79 ] ] ]
83cdc54a4cbae4fc9f773610953acc15c17d3eea
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/input/DIKeyboard.cpp
e354db37b2669389184e73bed6bcb1e2f721fe8e
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,752
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "DIKeyboard.h" using namespace dingus; int gDik2Ascii [][2] = { { DIK_ESCAPE, 0x27 }, { DIK_SPACE, ' ' }, { DIK_0, '0' }, { DIK_1, '1' }, { DIK_2, '2' }, { DIK_3, '3' }, { DIK_4, '4' }, { DIK_5, '5' }, { DIK_6, '6' }, { DIK_7, '7' }, { DIK_8, '8' }, { DIK_9, '9' }, { DIK_Q, 'Q' }, { DIK_W, 'W' }, { DIK_E, 'E' }, { DIK_R, 'R' }, { DIK_T, 'T' }, { DIK_Y, 'Y' }, { DIK_U, 'U' }, { DIK_I, 'I' }, { DIK_O, 'O' }, { DIK_P, 'P' }, { DIK_A, 'A' }, { DIK_S, 'S' }, { DIK_D, 'D' }, { DIK_F, 'F' }, { DIK_G, 'G' }, { DIK_H, 'H' }, { DIK_J, 'J' }, { DIK_K, 'K' }, { DIK_L, 'L' }, { DIK_Z, 'Z' }, { DIK_X, 'X' }, { DIK_C, 'C' }, { DIK_V, 'V' }, { DIK_B, 'B' }, { DIK_N, 'N' }, { DIK_M, 'M' } }; int gDikCount = sizeof(gDik2Ascii) / sizeof(gDik2Ascii[0]); CDIKeyboard::CDIKeyboard( HWND hwnd, IDirectInput8& di8 ) : mDIKeyboard( NULL ) { HRESULT hRes; DWORD dwCoopFlags; dwCoopFlags = DISCL_NONEXCLUSIVE | DISCL_FOREGROUND; // Obtain an interface to the system keyboard device. hRes = di8.CreateDevice( GUID_SysKeyboard, &mDIKeyboard, NULL ); assert( SUCCEEDED( hRes ) ); assert( mDIKeyboard ); // hr the data format to "keyboard format" - a predefined data format // // A data format specifies which controls on a device we // are interested in, and how they should be reported. // // This tells DirectInput that we will be passing an array // of 256 bytes to IDirectInputDevice::GetDeviceState. hRes = mDIKeyboard->SetDataFormat( &c_dfDIKeyboard ); assert( SUCCEEDED( hRes ) ); // Set the cooperativity level to let DirectInput know how // this device should interact with the system and with other // DirectInput applications. hRes = mDIKeyboard->SetCooperativeLevel( hwnd, dwCoopFlags ); assert( SUCCEEDED( hRes ) ); int q; for( q = 0; q < ASCII_BY_DIK_TABLE_SIZE; q++ ) { mAsciiByDik[ q ] = 0; } for( q = 0; q < gDikCount; q++ ) { int index = ::gDik2Ascii[q][0]; assert( index > 0 && index < ASCII_BY_DIK_TABLE_SIZE ); mAsciiByDik[ index ] = ::gDik2Ascii[q][1]; } memset( mOldDiks, 0x00, sizeof( mOldDiks ) ); /* // IMPORTANT STEP TO USE BUFFERED DEVICE DATA! // // DirectInput uses unbuffered I/O (buffer size = 0) by default. // If you want to read buffered data, you need to set a nonzero // buffer size. // // Set the buffer size to DINPUT_BUFFERSIZE (defined above) elements. // // The buffer size is a DWORD property associated with the device. DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = SAMPLE_BUFFER_SIZE; // Arbitary buffer size if( FAILED( hRes = mDIKeyboard->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) ) assert( SUCCEEDED( hRes ) ); */ // Acquire the newly created device mDIKeyboard->Acquire(); } int CDIKeyboard::dik2ascii( int dik ) { if( dik >= 0 && dik < ASCII_BY_DIK_TABLE_SIZE ) return mAsciiByDik[ dik ]; else return 0; } CInputEvents CDIKeyboard::poll() { HRESULT hr; BYTE diks[256]; // DirectInput keyboard state buffer int i; CInputEvents events; // Get the input's device state, and put the state in diks ZeroMemory( &diks, sizeof(diks) ); if( FAILED( hr = mDIKeyboard->GetDeviceState( sizeof(diks), &diks ) ) ) { // DirectInput may be telling us that the input stream has been // interrupted. We aren't tracking any state between polls, so // we don't have any special reset that needs to be done. // We just re-acquire and try again. // If input is lost then acquire and keep trying mDIKeyboard->Acquire(); while( hr == DIERR_INPUTLOST ) hr = mDIKeyboard->Acquire(); // hr may be DIERR_OTHERAPPHASPRIO or other errors. This // may occur when the app is minimized or in the process of // switching, so just try again later return events; } for( i = 0; i < 256; i++ ) { if( diks[i] == mOldDiks[i] && !(diks[i]&0x80) ) continue; int keyCode = dik2ascii(i); CKeyEvent::eMode mode; if( diks[i] == mOldDiks[i] ) mode = CKeyEvent::KEY_DOWN; else mode = (diks[i]&0x80) ? (CKeyEvent::KEY_PRESSED) : (CKeyEvent::KEY_RELEASED); events.addEvent( new CKeyEvent(mode,keyCode,i) ); mOldDiks[i] = diks[i]; } return events; }
[ [ [ 1, 180 ] ] ]
76d6e68587de0bf6c4be6d8b00e4fdb60ee3d816
2112057af069a78e75adfd244a3f5b224fbab321
/branches/ref1/src-root/include/common/misc/boost_assign_wrapper.h
cb8cbd6dfc2f6ae68ee8d640d94cb2ca0906b001
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,112
h
/** * @file common/misc/boost_assign_wrapper.h * Turns off vc7.1 warning 4512 for boost/assign.hpp */ /* Copyright (C) 2005-2006 ireon.org developers council * $Id$ * 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4512) #endif #include "boost/assign.hpp" using namespace boost::assign; #ifdef _MSC_VER #pragma warning(pop) #endif
[ [ [ 1, 35 ] ] ]
bbdfa902d91fed70d81aa5e710b873f589ad4673
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/checked.h
8f1e80db0501ee2375b1c0fcb03f33170d89f83f
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,090
h
// Copyright 2006 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #include "core.h" #include <stdexcept> namespace vtk_utf8 { // Exceptions that may be thrown from the library functions. class invalid_code_point : public vtkstd::exception { uint32_t cp; public: invalid_code_point(uint32_t _cp) : cp(_cp) {} virtual const char* what() const throw() { return "Invalid code point"; } uint32_t code_point() const {return cp;} }; class invalid_utf8 : public vtkstd::exception { uint8_t u8; public: invalid_utf8 (uint8_t u) : u8(u) {} virtual const char* what() const throw() { return "Invalid UTF-8"; } uint8_t utf8_octet() const {return u8;} }; class invalid_utf16 : public vtkstd::exception { uint16_t u16; public: invalid_utf16 (uint16_t u) : u16(u) {} virtual const char* what() const throw() { return "Invalid UTF-16"; } uint16_t utf16_word() const {return u16;} }; class not_enough_room : public vtkstd::exception { public: virtual const char* what() const throw() { return "Not enough space"; } }; /// The library API - functions intended to be called by the users template <typename octet_iterator, typename output_iterator> output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) { while (start != end) { octet_iterator sequence_start = start; internal::utf_error err_code = internal::validate_next(start, end); switch (err_code) { case internal::OK : for (octet_iterator it = sequence_start; it != start; ++it) *out++ = *it; break; case internal::NOT_ENOUGH_ROOM: throw not_enough_room(); case internal::INVALID_LEAD: append (replacement, out); ++start; break; case internal::INCOMPLETE_SEQUENCE: case internal::OVERLONG_SEQUENCE: case internal::INVALID_CODE_POINT: append (replacement, out); ++start; // just one replacement mark for the sequence while (internal::is_trail(*start) && start != end) ++start; break; } } return out; } template <typename octet_iterator, typename output_iterator> inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) { static const uint32_t replacement_marker = internal::mask16(0xfffd); return replace_invalid(start, end, out, replacement_marker); } template <typename octet_iterator> octet_iterator append(uint32_t cp, octet_iterator result) { if (!internal::is_code_point_valid(cp)) throw invalid_code_point(cp); if (cp < 0x80) // one octet *(result++) = static_cast<uint8_t>(cp); else if (cp < 0x800) { // two octets *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else if (cp < 0x10000) { // three octets *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else if (cp <= internal::CODE_POINT_MAX) { // four octets *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); *(result++) = static_cast<uint8_t>(((cp >> 12)& 0x3f) | 0x80); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else throw invalid_code_point(cp); return result; } template <typename octet_iterator> uint32_t next(octet_iterator& it, octet_iterator end) { uint32_t cp = 0; internal::utf_error err_code = internal::validate_next(it, end, &cp); switch (err_code) { case internal::OK : break; case internal::NOT_ENOUGH_ROOM : throw not_enough_room(); case internal::INVALID_LEAD : case internal::INCOMPLETE_SEQUENCE : case internal::OVERLONG_SEQUENCE : throw invalid_utf8(*it); case internal::INVALID_CODE_POINT : throw invalid_code_point(cp); } return cp; } template <typename octet_iterator> uint32_t peek_next(octet_iterator it, octet_iterator end) { return next(it, end); } template <typename octet_iterator> uint32_t prior(octet_iterator& it, octet_iterator start) { octet_iterator end = it; while (internal::is_trail(*(--it))) if (it < start) throw invalid_utf8(*it); // error - no lead byte in the sequence octet_iterator temp = it; return next(temp, end); } /// Deprecated in versions that include "prior" template <typename octet_iterator> uint32_t previous(octet_iterator& it, octet_iterator pass_start) { octet_iterator end = it; while (internal::is_trail(*(--it))) if (it == pass_start) throw invalid_utf8(*it); // error - no lead byte in the sequence octet_iterator temp = it; return next(temp, end); } template <typename octet_iterator, typename distance_type> void advance (octet_iterator& it, distance_type n, octet_iterator end) { for (distance_type i = 0; i < n; ++i) next(it, end); } template <typename octet_iterator> typename vtkstd::string::difference_type distance (octet_iterator first, octet_iterator last) { typename vtkstd::string::difference_type dist; for (dist = 0; first < last; ++dist) next(first, last); return dist; } template <typename u16bit_iterator, typename octet_iterator> octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { uint32_t cp = internal::mask16(*start++); // Take care of surrogate pairs first if (internal::is_surrogate(cp)) { if (start != end) { uint32_t trail_surrogate = internal::mask16(*start++); if (trail_surrogate >= internal::TRAIL_SURROGATE_MIN && trail_surrogate <= internal::TRAIL_SURROGATE_MAX) cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; else throw invalid_utf16(static_cast<uint16_t>(trail_surrogate)); } else throw invalid_utf16(static_cast<uint16_t>(*start)); } result = append(cp, result); } return result; } template <typename u16bit_iterator, typename octet_iterator> u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start != end) { uint32_t cp = next(start, end); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET); *result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); } else *result++ = static_cast<uint16_t>(cp); } return result; } template <typename octet_iterator, typename u32bit_iterator> octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) result = append(*(start++), result); return result; } template <typename octet_iterator, typename u32bit_iterator> u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start < end) (*result++) = next(start, end); return result; } // The iterator class template <typename octet_iterator> class iterator : public vtkstd::iterator <vtkstd::bidirectional_iterator_tag, uint32_t> { octet_iterator it; octet_iterator range_start; octet_iterator range_end; public: iterator () {}; explicit iterator (const octet_iterator& octet_it, const octet_iterator& _range_start, const octet_iterator& _range_end) : it(octet_it), range_start(_range_start), range_end(_range_end) { if (it < range_start || it > range_end) throw vtkstd::out_of_range("Invalid utf-8 iterator position"); } // the default "big three" are OK octet_iterator base () const { return it; } uint32_t operator * () const { octet_iterator temp = it; return next(temp, range_end); } bool operator == (const iterator& rhs) const { if (range_start != rhs.range_start || range_end != rhs.range_end) throw vtkstd::logic_error("Comparing utf-8 iterators defined with different ranges"); return (it == rhs.it); } bool operator != (const iterator& rhs) const { return !(operator == (rhs)); } iterator& operator ++ () { next(it, range_end); return *this; } iterator operator ++ (int) { iterator temp = *this; next(it, range_end); return temp; } iterator& operator -- () { prior(it, range_start); return *this; } iterator operator -- (int) { iterator temp = *this; prior(it, range_start); return temp; } }; // class iterator } // namespace vtk_utf8 #endif //header guard
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 318 ] ] ]
5411c68a08788fdc648de9668e9e063b9ba01698
6c8c4728e608a4badd88de181910a294be56953a
/CommunicationModule/TelepathyIM/ChatSession.h
ea13ae43d48eee3cce1b78daebc15f03fca317c9
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,204
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_Communication_TelepathyIM_ChatSession_h #define incl_Communication_TelepathyIM_ChatSession_h #include <string> #include <QStringList> #include <TelepathyQt4/TextChannel> #include <TelepathyQt4/Connection> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/PendingChannel> #include <TelepathyQt4/ReceivedMessage> //#include <Foundation.h> //#include "interface.h" //#include "ContactGroup.h" //#include "ChatMessage.h" #include "ChatSessionInterface.h" #include "ChatSessionParticipant.h" #include "ModuleLoggingFunctions.h" #include "CommunicationModuleFwd.h" namespace TelepathyIM { /** * Text message based communication session with one or more participants. * This can represents irc channel or jabber conversation. * * This uses Telepathy text channel to communicate with IM server. */ class ChatSession : public Communication::ChatSessionInterface { Q_OBJECT MODULE_LOGGING_FUNCTIONS static const std::string NameStatic() { return "CommunicationModule"; } // for logging functionality public: //! Used by TelepathyIM::Connection class //! when user initiates a new chat sessionj ChatSession(Contact& self_contact, Contact& contact, Tp::ConnectionPtr tp_connection); //! Used by TelepathyIM:Connection class //! When a chat session is initiated by IM server ChatSession(Contact& self_contact, Tp::TextChannelPtr tp_text_channel); //! Used by TelepathyIM:Connection class //! When user open chat room session ChatSession(const QString &room_id, Tp::ConnectionPtr tp_connection); virtual ~ChatSession(); //! Send a text message to chat session //! @param text The message virtual void SendChatMessage(const QString &text); //! @return State of the session virtual Communication::ChatSessionInterface::State GetState() const; //! Closes the chat session. No more messages can be send or received. //! Causes Closed signals to be emitted. virtual void Close(); //! @return all known participants of the chat session virtual Communication::ChatSessionParticipantVector GetParticipants() const; //! @return the message history of this chat sessions virtual Communication::ChatMessageVector GetMessageHistory(); virtual Tp::TextChannelPtr GetTpTextChannel() {return tp_text_channel_;} protected: virtual void HandlePendingMessage(); virtual ChatSessionParticipant* GetParticipant(Tp::ContactPtr contact); virtual ChatSessionParticipant* GetParticipant(uint sender_id); State state_; Tp::TextChannelPtr tp_text_channel_; Tp::Connection* tp_conneciton_; QStringList send_buffer_; ChatMessageVector message_history_; ChatSessionParticipantVector participants_; ChatSessionParticipant self_participant_; protected slots: //! This method is called ONLY when session is established by client //! and it's NOT called when the session is established by server virtual void OnTextChannelCreated(Tp::PendingOperation* op); virtual void OnIncomingTextChannelReady(Tp::PendingOperation* op); virtual void OnOutgoingTextChannelReady(Tp::PendingOperation* op); virtual void OnMessageSendAck(Tp::PendingOperation* op); virtual void OnChannelInvalidated(Tp::DBusProxy *, const QString &, const QString &); virtual void OnMessageReceived(const Tp::ReceivedMessage &message); virtual void OnTextChannelClosed(Tp::PendingOperation* op); virtual void OnChannelPendingMessageRemoved(const Tp::ReceivedMessage &message); signals: void Ready(ChatSession* session); }; // typedef std::vector<ChatSession*> ChatSessionVector; } // end of namespace: TelepathyIM #endif // incl_Communication_TelepathyIM_ChatSession_h
[ "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 2 ], [ 26, 54 ], [ 56, 94 ], [ 96, 97 ], [ 99, 99 ] ], [ [ 3, 5 ], [ 7, 13 ], [ 19, 19 ], [ 22, 25 ], [ 95, 95 ], [ 100, 102 ] ], [ [ 6, 6 ], [ 14, 18 ], [ 20, 21 ], [ 55, 55 ], [ 98, 98 ] ] ]
fb29bfa283ccb114f97fdebf925893ee77dab0b2
2e65def61753098295cc8fda3684ddc6dc62b099
/Slider.h
8c0f6d0fd84e64bbb0270f7ca1c34aaa3817c4fd
[]
no_license
JohnnyXiaoYang/wickedwidgets
3bafd6dab9fa75028a80c0a158b8563e15f4c6c6
523b3875647dcd2015de4db8979e28460a126db2
refs/heads/master
2021-05-26T19:20:59.052458
2010-10-23T12:30:09
2010-10-23T12:30:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,654
h
// Slider.h : Declaration of the CSlider #ifndef __Slider_H_ #define __Slider_H_ #include "resource.h" // main symbols #include <atlctl.h> #include "WickedWidgetsCP.h" ///////////////////////////////////////////////////////////////////////////// // CSlider class ATL_NO_VTABLE CSlider : public CComObjectRootEx<CComSingleThreadModel>, public IDispatchImpl<ISlider, &IID_ISlider, &LIBID_WICKEDWIDGETSLib>, public CComControl<CSlider>, public IPersistStreamInitImpl<CSlider>, public IOleControlImpl<CSlider>, public IOleObjectImpl<CSlider>, public IOleInPlaceActiveObjectImpl<CSlider>, public IViewObjectExImpl<CSlider>, public IOleInPlaceObjectWindowlessImpl<CSlider>, public IConnectionPointContainerImpl<CSlider>, public IPersistStorageImpl<CSlider>, public ISpecifyPropertyPagesImpl<CSlider>, public IQuickActivateImpl<CSlider>, public IDataObjectImpl<CSlider>, public IProvideClassInfo2Impl<&CLSID_Slider, &DIID__ISliderEvents, &LIBID_WICKEDWIDGETSLib>, public IPropertyNotifySinkCP<CSlider>, public CComCoClass<CSlider, &CLSID_Slider>, public CProxy_ISliderEvents< CSlider > { public: typedef struct tagPathValue { long nValuePathWidth; long nOffsetLeft; long nOffsetRight; float nStepWidth; long nCurrentValue; long nStepCount; void Initialize(long nPathWidth, long nBallWidth, long nStepCount) { nOffsetLeft = nBallWidth / 2; nOffsetRight = nBallWidth / 2; nValuePathWidth = nPathWidth - (nOffsetRight + nOffsetLeft); nStepWidth = (float)nValuePathWidth / (float)nStepCount; this->nStepCount = nStepCount; }; bool HitTest(POINT pt, long nValue) { float nValueLeft = (float)GetValueLeft(nValue); float nValueRight = (float)nValueLeft + nStepWidth; if ((float)pt.x >= nValueLeft && (float)pt.x <= nValueRight) return true; return false; }; long GetValueLeft(long nValue) { return (long)(nValue * nStepWidth); } long ValueFromPoint(POINT pt) { float nValue = ((float)pt.x / (float)nValuePathWidth) * (float)nStepCount; if (nValue > nStepCount) nValue = (float)nStepCount; if (nValue < 0) nValue = 0; return ((long)nValue); } } PathValue; CSlider() { m_bWindowOnly = TRUE; m_orientation = Horizontal; } HRESULT FinalConstruct( ) { m_sliderBall.hDC = NULL; m_sliderBall.hDCPressed = NULL; m_sliderPath.hDC = NULL; m_sliderPath.hDCPressed = NULL; m_hdcMem = NULL; m_sliderPath.rc.left = 0; m_sliderPath.rc.right = 0; m_sliderPath.rc.top = 0; m_sliderPath.rc.bottom = 0; m_sliderBall.rc.left = 0; m_sliderBall.rc.right = 0; m_sliderBall.rc.top = 0; m_sliderBall.rc.bottom = 0; m_nSliderWidth = 0; m_nSliderHeight = 0; m_nMax = 100; m_nMin = 0; // m_nValue = 0; m_bPressed = FALSE; bEnabled = VARIANT_TRUE; return S_OK; } void FinalRelease() { CleanGDIObjects(); } DECLARE_REGISTRY_RESOURCEID(IDR_SLIDER) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CSlider) COM_INTERFACE_ENTRY(ISlider) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IViewObjectEx) COM_INTERFACE_ENTRY(IViewObject2) COM_INTERFACE_ENTRY(IViewObject) COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceObject) COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceActiveObject) COM_INTERFACE_ENTRY(IOleControl) COM_INTERFACE_ENTRY(IOleObject) COM_INTERFACE_ENTRY(IPersistStreamInit) COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit) COM_INTERFACE_ENTRY(IConnectionPointContainer) COM_INTERFACE_ENTRY(ISpecifyPropertyPages) COM_INTERFACE_ENTRY(IQuickActivate) COM_INTERFACE_ENTRY(IPersistStorage) COM_INTERFACE_ENTRY(IDataObject) COM_INTERFACE_ENTRY(IProvideClassInfo) COM_INTERFACE_ENTRY(IProvideClassInfo2) COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer) END_COM_MAP() BEGIN_PROP_MAP(CSlider) PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4) PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4) PROP_ENTRY("SliderMax", DISPID_SLIDERMAX, CLSID_NULL) PROP_ENTRY("SliderMin", DISPID_SLIDERMIN, CLSID_NULL) PROP_ENTRY("SliderValue", DISPID_SLIDERVALUE, CLSID_NULL) PROP_ENTRY("SliderEnabled", DISPID_SLIDERENABLED, CLSID_NULL) PROP_ENTRY("SliderPathPicture", DISPID_PATHPICTURE, CLSID_NULL) PROP_ENTRY("SliderBallPicture", DISPID_BALLPICTURE, CLSID_NULL) PROP_ENTRY("SliderBallPicturePressed", DISPID_BALLPICTUREPRESSED, CLSID_NULL) // Example entries // PROP_ENTRY("Property Description", dispid, clsid) // PROP_PAGE(CLSID_StockColorPage) END_PROP_MAP() BEGIN_CONNECTION_POINT_MAP(CSlider) CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink) CONNECTION_POINT_ENTRY(DIID__ISliderEvents) END_CONNECTION_POINT_MAP() BEGIN_MSG_MAP(CSlider) CHAIN_MSG_MAP(CComControl<CSlider>) DEFAULT_REFLECTION_HANDLER() MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUP) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd) END_MSG_MAP() // Handler prototypes: // LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); // LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); // LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); // IViewObjectEx DECLARE_VIEW_STATUS(VIEWSTATUS_SOLIDBKGND | VIEWSTATUS_OPAQUE) // ISlider public: void CenterPathAndBall(); void CreatePressedBall(); STDMETHOD(get_TransparentColor)(/*[out, retval]*/ OLE_COLOR *pVal); STDMETHOD(put_TransparentColor)(/*[in]*/ OLE_COLOR newVal); STDMETHOD(get_BallPicturePressed)(/*[out, retval]*/ IPictureDisp* *pVal); STDMETHOD(put_BallPicturePressed)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(putref_BallPicturePressed)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(get_BallPicture)(/*[out, retval]*/ IPictureDisp* *pVal); STDMETHOD(put_BallPicture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(putref_BallPicture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(get_PathPicture)(/*[out, retval]*/ IPictureDisp* *pVal); STDMETHOD(put_PathPicture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(putref_PathPicture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(get_Enabled)(/*[out, retval]*/ VARIANT_BOOL *pVal); STDMETHOD(put_Enabled)(/*[in]*/ VARIANT_BOOL newVal); STDMETHOD(get_Value)(/*[out, retval]*/ long *pVal); STDMETHOD(put_Value)(/*[in]*/ long newVal); STDMETHOD(get_Min)(/*[out, retval]*/ long *pVal); STDMETHOD(put_Min)(/*[in]*/ long newVal); STDMETHOD(get_Max)(/*[out, retval]*/ long *pVal); STDMETHOD(put_Max)(/*[in]*/ long newVal); STDMETHOD(InPlaceActivate)( LONG iVerb, const RECT* prcPosRect = NULL ) { HRESULT hr = CComControl<CSlider>::InPlaceActivate( iVerb, prcPosRect ); return hr; } protected: LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { if (m_sliderBall.hDC == NULL) CreateBall(); if (m_sliderBall.hDCPressed == NULL) CreatePressedBall(); if (m_sliderPath.hDC == NULL) CreatePath(); m_value.Initialize(m_nSliderWidth, m_sliderBall.rc.right - m_sliderBall.rc.left, m_nMax - m_nMin); put_Value(m_value.nCurrentValue); return 0; } LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { m_bPressed = TRUE; HWND hwndAx; m_spInPlaceSite->GetWindow(&hwndAx); SetCapture(); DWORD xPos = LOWORD(lParam); // horizontal position of cursor DWORD yPos = HIWORD(lParam); // vertical position of cursor long nBallWidth = m_sliderBall.rc.right - m_sliderBall.rc.left; long nBallHeight = m_sliderBall.rc.bottom - m_sliderBall.rc.top; if (m_orientation == Horizontal) { m_sliderBall.nOffsetTag = xPos - m_sliderBall.rc.left; if (m_sliderBall.nOffsetTag > nBallWidth || m_sliderBall.nOffsetTag < 0) { m_sliderBall.nOffsetTag = nBallWidth / 2; } } else { m_sliderBall.nOffsetTag = m_sliderBall.rc.bottom - yPos; if (m_sliderBall.nOffsetTag > nBallHeight || m_sliderBall.nOffsetTag < 0) { m_sliderBall.nOffsetTag = nBallHeight / 2; } } CalculateBallPosition(-1, -1); return 0; } LRESULT OnLButtonUP(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { m_bPressed = FALSE; ReleaseCapture(); RedrawWindow(NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); Fire_Click(); return 0; } LRESULT OnMouseMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { if (m_bPressed) CalculateBallPosition(-1, -1); return 0; } HRESULT OnDraw(ATL_DRAWINFO& di) { RECT& rc = *(RECT*)di.prcBounds; if (m_sliderPath.picture != NULL && m_hdcMem) { FillRect(m_hdcMem, &rc, (HBRUSH) (COLOR_BTNFACE+1)); if (m_sliderPath.hDC) { BitBlt(m_hdcMem, m_sliderPath.rc.left, m_sliderPath.rc.top, m_sliderPath.rc.right - m_sliderPath.rc.left, m_sliderPath.rc.bottom - m_sliderPath.rc.top, m_sliderPath.hDC, 0, 0, SRCCOPY); } HDC hDCBall = m_bPressed ? m_sliderBall.hDCPressed : m_sliderBall.hDC; if (!hDCBall && m_bPressed && m_sliderBall.hDC) hDCBall = m_sliderBall.hDC; if (hDCBall) { BitBlt(m_hdcMem, m_sliderBall.rc.left, m_sliderBall.rc.top, m_sliderBall.rc.right - m_sliderBall.rc.left, m_sliderBall.rc.bottom - m_sliderBall.rc.top, hDCBall, 0, 0, SRCCOPY); } // Copy memdc to window dc BitBlt(di.hdcDraw, 0, 0, m_nSliderWidth, m_nSliderHeight, m_hdcMem, 0, 0, SRCCOPY); } else { FillRect(di.hdcDraw, &rc, (HBRUSH) (COLOR_3DSHADOW+1)); } return S_OK; } LRESULT OnEraseBkgnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { /* HDC hdc =(HDC)wParam; if (hdc && m_sliderPath.hDC) { BitBlt(hdc, m_sliderPath.rc.left, m_sliderPath.rc.top, m_sliderPath.rc.right - m_sliderPath.rc.left, m_sliderPath.rc.bottom - m_sliderPath.rc.top, m_sliderPath.hDC, 0, 0, SRCCOPY); } */ //bHandled = TRUE; return 0; } private: void CreatePath(); void CreateBall(); void CalculateBallPosition(int iManualX, int iManualY); void CleanGDIObjects(); private: struct SliderElement { HDC hDC; RECT rc; HDC hDCPressed; long nOffsetTag; CComPtr<IPictureDisp> pictureDisp; CComPtr<IPicture> picture; CComPtr<IPictureDisp> pictureDispPressed; CComPtr<IPicture> picturePressed; }; VARIANT_BOOL bEnabled; long m_nMax; long m_nMin; // long m_nValue; long m_nSliderWidth; long m_nSliderHeight; HDC m_hdcMem; BOOL m_bPressed; SliderElement m_sliderPath; SliderElement m_sliderBall; enumSliderOrientation m_orientation; OLE_COLOR m_clrTransparent; tagPathValue m_value; }; #endif //__Slider_H_
[ [ [ 1, 420 ] ] ]
fba3a302e1c41a51f5a33fc65af5ccd855368456
3699ee70db05a390ce86e64e09e779263510df6f
/branches/World Server/playerfunctions.cpp
ab32c5c3aed752d95fcd072f37ee3dbc51988c06
[]
no_license
trebor57/osprosedev
4fbe6616382ccd98e45c8c24034832850054a4fc
71852cac55df1dbe6e5d6f4264a2a2e6fd3bb506
refs/heads/master
2021-01-13T01:50:47.003277
2008-05-14T17:48:29
2008-05-14T17:48:29
32,129,756
0
0
null
null
null
null
UTF-8
C++
false
false
16,554
cpp
/* Rose Online Server Emulator Copyright (C) 2006,2007 OSRose Team http://www.osrose.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. depeloped with Main erose/hrose source server + some change from the original eich source */ #include "player.h" #include "worldserver.h" // Returns the amount of exp that is needed for the next level UINT CPlayer::GetLevelEXP( ) { if (Stats->Level <= 15) return (unsigned int)( ( Stats->Level + 10 ) * ( Stats->Level + 5 ) * ( Stats->Level + 3 ) * 0.7 ); else if (Stats->Level <= 50) return (unsigned int)( ( Stats->Level - 5 ) * ( Stats->Level + 2 ) * ( Stats->Level + 2 ) * 2.2 ); else if (Stats->Level <= 100) return (unsigned int)( ( Stats->Level - 38 ) * ( Stats->Level - 5 ) * ( Stats->Level + 2 ) * 9 ); else if (Stats->Level <= 139) return (unsigned int)( ( Stats->Level + 220 ) * ( Stats->Level + 34 ) * ( Stats->Level + 27 ) ); else return (unsigned int)( ( Stats->Level - 126 ) * ( Stats->Level - 15 ) * ( Stats->Level + 7 ) * 41 ); } // check if player can level up bool CPlayer::CheckPlayerLevelUP( ) { if (CharInfo->Exp >= GetLevelEXP()) { CharInfo->Exp -= GetLevelEXP(); Stats->Level++; Stats->HP = GetMaxHP( ); Stats->MP = GetMaxMP( ); CharInfo->StatPoints += int((Stats->Level*0.8)+10); //if(Stats->Level>=10) CharInfo->SkillPoints +=((Stats->Level+2)/2); BEGINPACKET( pak, 0x79e ); ADDWORD( pak, clientid ); ADDWORD( pak, Stats->Level ); ADDDWORD( pak, CharInfo->Exp ); ADDWORD( pak, CharInfo->StatPoints ); ADDWORD( pak, CharInfo->SkillPoints ); client->SendPacket( &pak ); RESETPACKET( pak, 0x79e ); ADDWORD( pak, clientid ); GServer->SendToVisible( &pak, this ); SetStats( ); //SendLevelUPtoChar(this); return true; } return false; } // Send a PM to client with user information bool CPlayer::GetPlayerInfo( ) { char text[50]; sprintf(text,"Attack: %i | Critical: %i",Stats->Attack_Power, Stats->Critical ); BEGINPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"Defense: %i | Magic Defense: %i",Stats->Defense, Stats->Magic_Defense); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"Accury: %i | Dodge: %i",Stats->Accury,Stats->Dodge ); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"aspeed: %i | mspeed: %i",Stats->Attack_Speed,Stats->Move_Speed ); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"HP: %i/%i , MP: %i/%i",Stats->HP,Stats->MaxHP,Stats->MP,Stats->MaxMP); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"Position[%i]: (%.0f,%.0f)",Position->Map,Position->current.x,Position->current.y); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"ClientID: %u | CharID: %u", clientid, CharInfo->charid ); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"inGame: %i | Logged: %i", Session->inGame, Session->isLoggedIn ); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); sprintf(text,"ClanName[%u]: %s | ClanGrade: %i | ClanRank: %i", Clan->clanid, Clan->clanname, Clan->grade, Clan->clanrank ); RESETPACKET( pak, 0x0784 ); ADDSTRING( pak, "[GM]PlayerInfo" ); ADDBYTE( pak, 0 ); ADDSTRING( pak, text ); ADDBYTE( pak, 0 ); client->SendPacket(&pak); return true; } // clearn player lists bool CPlayer::CleanPlayerVector( ) { CMap* map = GServer->MapList.Index[Position->Map]; VisiblePlayers.clear(); VisibleMonsters.clear(); VisibleDrops.clear(); VisibleNPCs.clear(); return true; } // update visibility list bool CPlayer::VisiblityList( ) { if(!this->Session->inGame) return true; std::vector<CPlayer*> newVisiblePlayers; std::vector<CDrop*> newVisibleDrops; std::vector<unsigned int> newVisibleMonsters; std::vector<CNPC*> newVisibleNPCs; // Clients CMap* map = GServer->MapList.Index[Position->Map]; for(UINT i=0;i<map->PlayerList.size();i++) { CPlayer* otherclient = map->PlayerList.at(i); if ( this==otherclient || !otherclient->Session->inGame) { continue; } float distance = GServer->distance( this->Position->current, otherclient->Position->current ); if ( GServer->IsVisible( this, otherclient ) ) { if ( distance < MAXVISUALRANGE && !otherclient->isInvisibleMode ) { newVisiblePlayers.push_back( otherclient ); } else { ClearObject( otherclient->clientid ); } } else { if ( distance < MINVISUALRANGE && !otherclient->isInvisibleMode ) { newVisiblePlayers.push_back( otherclient ); otherclient->SpawnToPlayer(this, otherclient); } } } // Monsters for(UINT i=0;i<map->MonsterList.size();i++) { CMonster* thismon = map->MonsterList.at( i ); float distance = GServer->distance ( this->Position->current, thismon->Position->current ); if ( GServer->IsVisible( this, thismon ) ) { if (distance < MAXVISUALRANGE ) { newVisibleMonsters.push_back( thismon->clientid); } else { ClearObject( thismon->clientid ); } } else { if ( distance< MINVISUALRANGE ) { newVisibleMonsters.push_back( thismon->clientid); thismon->SpawnMonster(this, thismon ); } } } // Drops for(unsigned i=0; i<map->DropsList.size(); i++) { CDrop* thisdrop = map->DropsList.at(i); float distance = GServer->distance( this->Position->current, thisdrop->pos ); if ( GServer->IsVisible( this, thisdrop ) ) { if ( distance< MAXVISUALRANGE ) { newVisibleDrops.push_back( thisdrop ); } else { this->ClearObject( thisdrop->clientid ); } } else { if ( distance < MINVISUALRANGE ) { newVisibleDrops.push_back( thisdrop ); GServer->pakSpawnDrop( this, thisdrop ); } } } // Npcs for(unsigned i=0; i<map->NPCList.size(); i++) { CNPC* thisnpc = map->NPCList.at(i); float distance = GServer->distance( this->Position->current, thisnpc->pos ); if ( GServer->IsVisible( this, thisnpc ) ) { if ( distance < MAXVISUALRANGE ) { newVisibleNPCs.push_back( thisnpc ); } else { this->ClearObject( thisnpc->clientid ); } } else { if ( distance < MINVISUALRANGE ) { newVisibleNPCs.push_back( thisnpc ); GServer->pakSpawnNPC( this, thisnpc ); } } } VisiblePlayers.clear(); VisibleDrops.clear(); VisibleMonsters.clear(); VisibleNPCs.clear(); VisiblePlayers = newVisiblePlayers; VisibleDrops = newVisibleDrops; VisibleMonsters = newVisibleMonsters; VisibleNPCs = newVisibleNPCs; return true; } // Returns a free slot in the inventory (0xffff if is full) UINT CPlayer::GetNewItemSlot( CItem thisitem ) { UINT tabsize = 30; UINT itemtab = 0; switch(thisitem.itemtype) { case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9://equip itemtab=0; break; case 10://consumibles itemtab=1; break; case 11:case 12://etc itemtab=2; break; case 14://pat itemtab=3; break; default: Log(MSG_WARNING,"unknown itemtype %i", thisitem.itemtype); return 0xffff; break; } //Log(MSG_WARNING,"itemtype %i", thisitem.itemtype); for(int i=0;i<30;i++) { UINT slot=12; slot += (tabsize*itemtab)+i; switch(itemtab) { case 0:case 3://equip and pat { if(items[slot].itemnum==0 && items[slot].count<1) return slot; } break; case 1:case 2://consumible and etc { if((items[slot].itemnum == thisitem.itemnum && items[slot].count<999) ||(items[slot].itemnum==0 && items[slot].count<1)) return slot; } break; } } return 0xffff; } // Returns a free slot in the storage (0xffff if is full) UINT CPlayer::GetNewStorageItemSlot( CItem thisitem ) { for(UINT i=0;i<160;i++) { if(storageitems[i].itemtype == 0) return i; } return 0xffff; } // Erase a object from the user bool CPlayer::ClearObject( unsigned int otherclientid ) { BEGINPACKET( pak, 0x794 ); ADDWORD( pak, otherclientid ); client->SendPacket( &pak ); return true; } // Clean the player values void CPlayer::RestartPlayerVal( ) { ClearBattle( Battle ); Shop->open = false; Trade->trade_target = 0; Trade->trade_status = 0; } // HP/MP Regeneration Function bool CPlayer::Regeneration() { if (Stats->MaxHP==Stats->HP && Stats->MaxMP== Stats->MP) { lastRegenTime=0; return true; } //LMA REGEN bool is_first_regen=false; if (lastRegenTime==0) { is_first_regen=true; } clock_t etime = clock() - lastRegenTime; if( etime >= 8 * CLOCKS_PER_SEC && Stats->HP > 0 ) { unsigned int hpamount = GetHPRegenAmount( ); unsigned int mpamount = GetMPRegenAmount( ); Stats->HP += hpamount; Stats->MP += mpamount; if( Stats->HP > Stats->MaxHP) Stats->HP = Stats->MaxHP; if( Stats->MP > Stats->MaxMP ) Stats->MP = Stats->MaxMP; if (Stats->MaxHP==Stats->HP && Stats->MaxMP== Stats->MP) lastRegenTime=0; else lastRegenTime = clock(); } return true; } // Heal Player when use Food/Pots bool CPlayer::PlayerHeal() { clock_t transtime = clock() - UsedItem->lastRegTime; if( UsedItem->usevalue!=0 && transtime >= 0.3*CLOCKS_PER_SEC ) { if( UsedItem->used < UsedItem->usevalue && Stats->HP > 0 ) { int value = UsedItem->userate; if((UsedItem->usevalue - UsedItem->used) < value) { value = UsedItem->usevalue - UsedItem->used; } // geo edit for instant heal // 3 jan 07 //if(UsedItem->usetype==16 || UsedItem->usetype==17) // value = UsedItem->usevalue; // end geo edit switch( UsedItem->usetype ) { case 16: // HP Stats->HP += value; if(Stats->HP > Stats->MaxHP) Stats->HP = Stats->MaxHP; break; case 17: // MP Stats->MP += value; if(Stats->MP > Stats->MaxMP) Stats->MP = Stats->MaxMP; break; } UsedItem->used += value; UsedItem->lastRegTime = clock(); } else { BEGINPACKET( pak,0x7b7 ); ADDWORD ( pak, clientid ); ADDDWORD ( pak, GServer->BuildBuffs( this ) ); switch( UsedItem->usetype ) { case 16: // HP ADDWORD( pak, Stats->HP ); break; case 17: // MP ADDWORD( pak, Stats->MP ); break; } GServer->SendToVisible( &pak, this ); UsedItem->used = 0; UsedItem->usevalue = 0; UsedItem->userate = 0; UsedItem->usetype = 0; } } return true; } void CPlayer::ReduceABC( ) { unsigned int weapontype = 0; weapontype = GServer->EquipList[WEAPON].Index[items[7].itemnum]->type; switch(weapontype) { case 231: items[132].count--; if(items[132].count<=0) { ClearBattle( Battle ); ClearItem( items[132] ); } break; case 232: items[133].count--; if(items[133].count<=0) { ClearBattle( Battle ); ClearItem( items[133] ); } break; case 233: items[134].count--; if(items[134].count<=0) { ClearBattle( Battle ); ClearItem( items[134] ); } break; case 271: items[132].count--; if(items[132].count<=0) { ClearBattle( Battle ); ClearItem( items[135] ); } break; } } // return party pointer CParty* CPlayer::GetParty( ) { return Party->party; } // return intelligence unsigned int CPlayer::GetInt( ) { return Attr->Int; } // add item [return item slot [0xffff if couldn't add it]] unsigned int CPlayer::AddItem( CItem item ) { unsigned int newslot=0; newslot = GetNewItemSlot( item ); if(newslot!=0xffff) { if(items[newslot].count>0) { unsigned int ntcount = item.count; unsigned int utcount = items[newslot].count; if(ntcount+utcount>999) { item.count = ntcount+utcount - 999; items[newslot].count = 999; unsigned int otherslot = GetNewItemSlot( item ); if(otherslot!=0xffff) { if(items[otherslot].count!=0) items[otherslot].count += item.count; else items[otherslot] = item; return newslot*1000+otherslot; } else { items[newslot].count = utcount; return 0xffff; //not inventory space } } else items[newslot].count = ntcount+utcount; } else items[newslot] = item; } return newslot; } void CPlayer::UpdateInventory( unsigned int slot1, unsigned int slot2 ) { if(slot1==0xffff && slot2==0xffff) return; BEGINPACKET( pak, 0x718 ); if(slot2!=0xffff && slot2!=0xffff) {ADDBYTE( pak, 2 );} else {ADDBYTE( pak, 1 );} if(slot1!=0xffff) { ADDBYTE ( pak, slot1); ADDWORD ( pak, GServer->BuildItemHead( items[slot1] ) ); ADDDWORD ( pak, GServer->BuildItemData( items[slot1] ) ); } if(slot2!=0xffff) { ADDBYTE ( pak, slot2 ); ADDWORD ( pak, GServer->BuildItemHead( items[slot2] ) ); ADDDWORD ( pak, GServer->BuildItemData( items[slot2] ) ); } client->SendPacket( &pak ); }
[ "remichael@004419b5-314d-0410-88ab-2927961a341b" ]
[ [ [ 1, 556 ] ] ]
15c8d82177f08c202323ad6cbadeed263b84b0f8
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/core/src/GameAreaListener.cpp
3d23bbc6c6f98a9d72e46b551994fae85e0fede0
[ "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,636
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 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 "GameAreaListener.h" #include "GameEventManager.h" #include "CoreSubsystem.h" #include "Exception.h" namespace rl { GameAreaListener::~GameAreaListener() { GameEventManager::getSingleton().removeAreaListener( this ); } bool GameAreaListener::eventRaised( GameAreaEvent* anEvent ) { try { switch( anEvent->getReason() ) { case GameAreaEvent::AREA_ENTERED: this->areaEntered( anEvent ); break; case GameAreaEvent::AREA_LEFT: this->areaLeft( anEvent ); break; } } catch( ScriptInvocationFailedException& sife ) { Logger::getSingleton().log(Logger::CORE, Ogre::LML_CRITICAL, sife.toString() ); } // consumed or not ;) return false; } }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 55 ] ] ]
e0874a88cf7a87b42c1f6d7bbddd48babc208913
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEApplications/SE_OpenGL_Application/SEOpenGLApplicationPCH.cpp
4844d2ebebe12112a0d9d7bec46bd37d95da5cd8
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
970
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEOpenGLApplicationPCH.h"
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 21 ] ] ]
0d471b633c51da6fa2657a08e6690fc5ae0edbb1
bfe8eca44c0fca696a0031a98037f19a9938dd26
/detect_fullscreen/detect_fullscreen/detect_fullscreenDlg.cpp
8c8e9bc679bae8bf60d160793b81788a94bf33b7
[]
no_license
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
9,410
cpp
// detect_fullscreenDlg.cpp : implementation file // #include "stdafx.h" #include "detect_fullscreen.h" #include "detect_fullscreenDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // Cdetect_fullscreenDlg dialog Cdetect_fullscreenDlg::Cdetect_fullscreenDlg(CWnd* pParent /*=NULL*/) : CDialog(Cdetect_fullscreenDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void Cdetect_fullscreenDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(Cdetect_fullscreenDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP END_MESSAGE_MAP() // Cdetect_fullscreenDlg message handlers BOOL Cdetect_fullscreenDlg::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 RegisterAccessBar(m_hWnd, TRUE); return TRUE; // return TRUE unless you set the focus to a control } void Cdetect_fullscreenDlg::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 Cdetect_fullscreenDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags // the minimized window. HCURSOR Cdetect_fullscreenDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } LRESULT Cdetect_fullscreenDlg::WindowProc(UINT msg, WPARAM wp, LPARAM lp) { if (MSG_APPBAR_MSGID == msg) { switch((UINT)wp) { case ABN_FULLSCREENAPP: { if (TRUE == (BOOL)lp) { TRACE(TEXT("full\n")); //KAppBarMsg::m_bFullScreen = TRUE; } else { TRACE(TEXT("not full\n")); //KAppBarMsg::m_bFullScreen = FALSE; } } break; default: break; } } return CDialog::WindowProc(msg, wp, lp); } // RegisterAccessBar - registers or unregisters an appbar. // Returns TRUE if successful, or FALSE otherwise. // hwndAccessBar - handle to the appbar // fRegister - register and unregister flag // // Global variables // g_uSide - screen edge (defaults to ABE_TOP) // g_fAppRegistered - flag indicating whether the bar is registered BOOL Cdetect_fullscreenDlg::RegisterAccessBar(HWND hwndAccessBar, BOOL fRegister) { APPBARDATA abd; // Specify the structure size and handle to the appbar. abd.cbSize = sizeof(APPBARDATA); abd.hWnd = hwndAccessBar; if (fRegister) { // Provide an identifier for notification messages. abd.uCallbackMessage = MSG_APPBAR_MSGID; // Register the appbar. if (!SHAppBarMessage(ABM_NEW, &abd)) return FALSE; g_uSide = ABE_TOP; // default edge g_fAppRegistered = TRUE; } else { // Unregister the appbar. SHAppBarMessage(ABM_REMOVE, &abd); g_fAppRegistered = FALSE; } return TRUE; } // AppBarQuerySetPos - sets the size and position of an appbar. // uEdge - screen edge to which the appbar is to be anchored // lprc - current bounding rectangle of the appbar // pabd - address of the APPBARDATA structure with the hWnd and // cbSize members filled void PASCAL Cdetect_fullscreenDlg::AppBarQuerySetPos(UINT uEdge, LPRECT lprc, PAPPBARDATA pabd) { //int iHeight = 0; //int iWidth = 0; //pabd->rc = *lprc; //pabd->uEdge = uEdge; //// Copy the screen coordinates of the appbar's bounding //// rectangle into the APPBARDATA structure. //if ((uEdge == ABE_LEFT) || // (uEdge == ABE_RIGHT)) { // iWidth = pabd->rc.right - pabd->rc.left; // pabd->rc.top = 0; // pabd->rc.bottom = GetSystemMetrics(SM_CYSCREEN); //} else { // iHeight = pabd->rc.bottom - pabd->rc.top; // pabd->rc.left = 0; // pabd->rc.right = GetSystemMetrics(SM_CXSCREEN); //} //// Query the system for an approved size and position. //SHAppBarMessage(ABM_QUERYPOS, pabd); //// Adjust the rectangle, depending on the edge to which the //// appbar is anchored. //switch (uEdge) { // case ABE_LEFT: // pabd->rc.right = pabd->rc.left + iWidth; // break; // case ABE_RIGHT: // pabd->rc.left = pabd->rc.right - iWidth; // break; // case ABE_TOP: // pabd->rc.bottom = pabd->rc.top + iHeight; // break; // case ABE_BOTTOM: // pabd->rc.top = pabd->rc.bottom - iHeight; // break; //} //// Pass the final bounding rectangle to the system. //SHAppBarMessage(ABM_SETPOS, pabd); //// Move and size the appbar so that it conforms to the //// bounding rectangle passed to the system. //MoveWindow(pabd->hWnd, pabd->rc.left, pabd->rc.top, // pabd->rc.right - pabd->rc.left, // pabd->rc.bottom - pabd->rc.top, TRUE); } // AppBarCallback - processes notification messages sent by the system. // hwndAccessBar - handle to the appbar // uNotifyMsg - identifier of the notification message // lParam - message parameter void Cdetect_fullscreenDlg::AppBarCallback(HWND hwndAccessBar, UINT uNotifyMsg, LPARAM lParam) { //APPBARDATA abd; //UINT uState; //abd.cbSize = sizeof(abd); //abd.hWnd = hwndAccessBar; //switch (uNotifyMsg) { // case ABN_STATECHANGE: // // Check to see if the taskbar's always-on-top state has // // changed and, if it has, change the appbar's state // // accordingly. // uState = SHAppBarMessage(ABM_GETSTATE, &abd); // SetWindowPos(hwndAccessBar, // (ABS_ALWAYSONTOP & uState) ? HWND_TOPMOST : HWND_BOTTOM, // 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); // break; // case ABN_FULLSCREENAPP: // // A full-screen application has started, or the last full- // // screen application has closed. Set the appbar's // // z-order appropriately. // if (lParam) { // SetWindowPos(hwndAccessBar, // (ABS_ALWAYSONTOP & uState) ? HWND_TOPMOST : HWND_BOTTOM, // 0, 0, 0, 0, // SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); // } // else { // uState = SHAppBarMessage(ABM_GETSTATE, &abd); // if (uState & ABS_ALWAYSONTOP) // SetWindowPos(hwndAccessBar, HWND_TOPMOST, // 0, 0, 0, 0, // SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); // } // case ABN_POSCHANGED: // // The taskbar or another appbar has changed its // // size or position. // AppBarPosChanged(&abd); // break; //} } // AppBarPosChanged - adjusts the appbar's size and position. // pabd - address of an APPBARDATA structure that contains information // used to adjust the size and position void PASCAL Cdetect_fullscreenDlg::AppBarPosChanged(PAPPBARDATA pabd) { //RECT rc; //RECT rcWindow; //int iHeight; //int iWidth; //rc.top = 0; //rc.left = 0; //rc.right = GetSystemMetrics(SM_CXSCREEN); //rc.bottom = GetSystemMetrics(SM_CYSCREEN); //GetWindowRect(pabd->hWnd, &rcWindow); //iHeight = rcWindow.bottom - rcWindow.top; //iWidth = rcWindow.right - rcWindow.left; //switch (g_uSide) { // case ABE_TOP: // rc.bottom = rc.top + iHeight; // break; // case ABE_BOTTOM: // rc.top = rc.bottom - iHeight; // break; // case ABE_LEFT: // rc.right = rc.left + iWidth; // break; // case ABE_RIGHT: // rc.left = rc.right - iWidth; // break; //} //AppBarQuerySetPos(g_uSide, &rc, pabd); }
[ "[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 393 ] ] ]
2005c99f008b86fe3b5e6ad37f8ba9e07c3edfd9
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/XMonitor/debug/moc_TitleBar.cpp
63f4f5fbf0c25c6f937e2920f98b8644059aa0df
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
2,098
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'TitleBar.h' ** ** Created: Fri Apr 1 12:39:01 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/TitleBar.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'TitleBar.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.0. 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_TitleBar[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_TitleBar[] = { "TitleBar\0" }; const QMetaObject TitleBar::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_TitleBar, qt_meta_data_TitleBar, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &TitleBar::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *TitleBar::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *TitleBar::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_TitleBar)) return static_cast<void*>(const_cast< TitleBar*>(this)); return QWidget::qt_metacast(_clname); } int TitleBar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 69 ] ] ]
903d1a9101783ee76940ee7e68606c8b2c788c52
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/base.hpp
ca108628a56b32a44d49966bfafab75790840874
[]
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
858
hpp
#ifndef BOOST_MPL_BASE_HPP_INCLUDED #define BOOST_MPL_BASE_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/base.hpp,v $ // $Date: 2006/04/17 23:48:05 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(T) > struct base { typedef typename T::base type; BOOST_MPL_AUX_LAMBDA_SUPPORT(1,base,(T)) }; BOOST_MPL_AUX_NA_SPEC(1, base) }} #endif // BOOST_MPL_BASE_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 35 ] ] ]
ebd0507b07088e0981ac35654a1e1b5249147a38
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/test/ntestcmdprotocpp/ntestcmdprotocpp.h
e395b74300620f1f6390496f77320c5b083a6600
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,532
h
#include "kernel/nroot.h" #include "kernel/ncmdprotocpp.h" /** Macro used to simplify testing */ #define NCMDPROTONATIVECPP_DECLARE_TEST(TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM,TestCode) \ NCMDPROTONATIVECPP_DECLARE(0,,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) \ { \ n_printf( #MemberName ": ret=(" #TR ") - " #NUMINPARAM "in=" #INPARAM " - " #NUMOUTPARAM "out=" #OUTPARAM " "); \ TestCode; \ } class nTestCmdProtoCPP : public nRoot { public: nTestCmdProtoCPP(); virtual ~nTestCmdProtoCPP(); NCMDPROTOCPP_DECLARE_BEGIN(nTestCmdProtoCPP); // 0 parameters nothing returned NCMDPROTOCPP_DECLARE_TEST(void,Test0VV, 0, (), 0, (), (0) ); // 0 parameters with return type NCMDPROTOCPP_DECLARE_TEST(int, Test0IV, 0, (), 0, (), return (0) ); NCMDPROTOCPP_DECLARE_TEST(bool, Test0BV, 0, (), 0, (), return (false) ); NCMDPROTOCPP_DECLARE_TEST(float, Test0FV, 0, (), 0, (), return (0.0f) ); NCMDPROTOCPP_DECLARE_TEST(char *, Test0SV, 0, (), 0, (), return ("test") ); NCMDPROTOCPP_DECLARE_TEST(void *, Test0OV, 0, (), 0, (), return (this) ); NCMDPROTOCPP_DECLARE_TEST(nRoot *, Test0OV1, 0, (), 0, (), return (this) ); // 0 parameters with return type, const version NCMDPROTOCPP_DECLARE_TEST(const int, Test0CIV, 0, (), 0, (), return (0) ); NCMDPROTOCPP_DECLARE_TEST(const bool,Test0CBV, 0, (), 0, (), return (false) ); NCMDPROTOCPP_DECLARE_TEST(const float, Test0CFV, 0, (), 0, (), return (0.0) ); NCMDPROTOCPP_DECLARE_TEST(const char *, Test0CSV, 0, (), 0, (), return ("test") ); NCMDPROTOCPP_DECLARE_TEST(const void *, Test0COV, 0, (), 0, (), return (this) ); NCMDPROTOCPP_DECLARE_TEST(const nRoot *,Test0COV1, 0, (), 0, (), return (this) ); // 1 parameter with no return type NCMDPROTOCPP_DECLARE_TEST(void, Test1VI,1,(int &), 0, (), (n_printf("%d\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VB,1,(bool &), 0, (), (n_printf("%d\n", (int) inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VF,1,(float &), 0, (), (n_printf("%f\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VS,1,(char * &), 0, (), (n_printf("%s\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VO,1,(void * &), 0, (), (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() )) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VO2,1,(nRoot * &), 0, (), (n_printf("0x%x %s\n", inarg1, inarg1->GetName())) ); // 1 inargeter with no return type, const version NCMDPROTOCPP_DECLARE_TEST(void, Test1VCI,1,(const int), 0, (), (n_printf("%d\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCB,1,(const bool), 0, (), (n_printf("%d\n", (int) inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCF,1,(const float), 0, (), (n_printf("%f\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCS,1,(const char *), 0, (), (n_printf("%s\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCO,1,(const void *), 0, (), (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() )) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCO2,1,(nRoot *), 0, (), (n_printf("0x%x %s\n", inarg1, inarg1->GetName())) ); // 1 inargeter with return type NCMDPROTOCPP_DECLARE_TEST(int, Test1II,1,(int), 0, (), return (n_printf("%d\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(bool, Test1BB,1,(bool), 0, (), return (n_printf("%d\n", (int) inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(float, Test1FF,1,(float), 0, (), return (n_printf("%f\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(char *, Test1SS,1,(char *), 0, (), return (n_printf("%s\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(void *, Test1OO,1,(void *), 0, (), return (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() ), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(nRoot *, Test1OO2,1,(nRoot *), 0, (), return (n_printf("0x%x %s\n", inarg1, inarg1->GetName()), inarg1) ); // 1 inargeter with constant return type NCMDPROTOCPP_DECLARE_TEST(const int, Test1CII,1,(int), 0, (), return (n_printf("%d\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const bool, Test1CBB,1,(bool), 0, (), return (n_printf("%d\n", (int) inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const float, Test1CFF,1,(float), 0, (), return (n_printf("%f\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const char *, Test1CSS,1,(char *), 0, (), return (n_printf("%s\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const void *, Test1COO,1,(void *), 0, (), return (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() ), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const nRoot *, Test1COO2,1,(nRoot *), 0, (), return (n_printf("0x%x %s\n", inarg1, inarg1->GetName()), inarg1) ); // 1 inargeter with return type NCMDPROTOCPP_DECLARE_TEST(int, Test1ICI,1,(const int), 0, (), return (n_printf("%d\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(bool, Test1BCB,1,(const bool), 0, (), return (n_printf("%d\n", (int) inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(float, Test1FCF,1,(const float), 0, (), return (n_printf("%f\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(char *, Test1SCS,1,(const char *), 0, (), return (n_printf("%s\n", inarg1), (char *) inarg1) ); NCMDPROTOCPP_DECLARE_TEST(void *, Test1OCO,1,(const void *), 0, (), return (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() ), (void *) inarg1) ); NCMDPROTOCPP_DECLARE_TEST(nRoot *, Test1OCO2,1,(const nRoot *), 0, (), return (n_printf("0x%x %s\n", inarg1, inarg1->GetName()), (nRoot *) inarg1) ); // 1 constant inargeter with return type NCMDPROTOCPP_DECLARE_TEST(const int, Test1CICI,1,(int), 0, (), return (n_printf("%d\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const bool, Test1CBCB,1,(bool), 0, (), return (n_printf("%d\n", (int) inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const float, Test1CFCF,1,(float), 0, (), return (n_printf("%f\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const char *, Test1CSCS,1,(char *), 0, (), return (n_printf("%s\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const void *, Test1COCO,1,(void *), 0, (), return (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() ), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(const nRoot *, Test1COCO2,1,(nRoot *), 0, (), return (n_printf("0x%x %s\n", inarg1, inarg1->GetName()), inarg1) ); // several inargeters NCMDPROTOCPP_DECLARE_TEST(int, Test6IIBFSOO, 6,(int,bool,float,char *,void *,nRoot *), 0, (), return (n_printf("%d %d %f %s 0x%x %s 0x%x %s\n", inarg1, (int) inarg2, inarg3, inarg4, inarg5, ((nRoot *) inarg5)->GetName(), inarg6, inarg6->GetName()), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(int, Test6ICICBCFCSCOCO, 6,(const int,const bool,const float,const char *,const void *,const nRoot *), 0, (), return (n_printf("%d %d %f %s 0x%x %s 0x%x %s\n", inarg1, (int) inarg2, inarg3, inarg4, inarg5, ((nRoot *) inarg5)->GetName(), inarg6, inarg6->GetName()), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(void, Test6VIBFSOO, 6,(int,bool,float,char *,void *,nRoot *), 0, (), return (n_printf("%d %d %f %s 0x%x %s 0x%x %s\n", inarg1, (int) inarg2, inarg3, inarg4, inarg5, ((nRoot *) inarg5)->GetName(), inarg6, inarg6->GetName()) ) ); NCMDPROTOCPP_DECLARE_TEST(void, Test6VCICBCFCSCOCO, 6,(const int,const bool,const float,const char *,const void *,const nRoot *), 0, (), return (n_printf("%d %d %f %s 0x%x %s 0x%x %s\n", inarg1, (int) inarg2, inarg3, inarg4, inarg5, ((nRoot *) inarg5)->GetName(), inarg6, inarg6->GetName()) ) ); /// test with new type vector3 and vector3 * NCMDPROTOCPP_DECLARE_TEST(vector3, Test0V3V, 0, (), 0, (), return ( vector3(10.0f,20.0f,30.0f) ) ); NCMDPROTOCPP_DECLARE_TEST(const vector3, Test0CV3V, 0, (), 0, (), return ( vector3(10.0f,20.0f,30.0f) ) ); NCMDPROTOCPP_DECLARE_TEST(vector3 *, Test0V3PV, 0, (), 0, (), return ( n_new(vector3(10.0f,20.0f,30.0f)) ) ); NCMDPROTOCPP_DECLARE_TEST(const vector3 *, Test0CV3PV, 0, (), 0, (), return ( n_new(vector3(10.0f,20.0f,30.0f)) ) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VV3,1,(vector3), 0, (), (n_printf("%f %f %f\n", inarg1.x, inarg1.y, inarg1.z)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCV3,1,(const vector3), 0, (), (n_printf("%f %f %f\n", inarg1.x, inarg1.y, inarg1.z)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VV3P,1,(vector3 *), 0, (), (n_printf("%f %f %f\n", inarg1->x, inarg1->y, inarg1->z)) ); NCMDPROTOCPP_DECLARE_TEST(void, Test1VCV3P,1,(const vector3 *), 0, (), (n_printf("%f %f %f\n", inarg1->x, inarg1->y, inarg1->z)) ); /// test output inargeters NCMDPROTOCPP_DECLARE_TEST(void, OutTest1V3, 0, (), 1, (vector3 *), ( outarg1->x = 1.f, outarg1->y = 2.f, outarg1->z = 3.f ) ); NCMDPROTOCPP_DECLARE_TEST(int, OutTest1IV3, 0, (), 1, (vector3 *), return ( outarg1->x = 1.f, outarg1->y = 2.f, outarg1->z = 3.f, 25 ) ); // 1 inargeter with no return type with input references NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VI,1,(int &), 0, (), (n_printf("%d\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VB,1,(bool &), 0, (), (n_printf("%d\n", (int) inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VF,1,(float &), 0, (), (n_printf("%f\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VS,1,(char * &), 0, (), (n_printf("%s\n", inarg1)) ); NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VO,1,(void * &), 0, (), (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() )) ); NCMDPROTOCPP_DECLARE_TEST(void, RefTest1VO2,1,(nRoot * &), 0, (), (n_printf("0x%x %s\n", inarg1, inarg1->GetName())) ); // 1 inargeter with return type with input references & return references NCMDPROTOCPP_DECLARE_TEST(int &, RefTest1II,1,(int &), 0, (), return (n_printf("%d\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(bool &, RefTest1BB,1,(bool &), 0, (), return (n_printf("%d\n", (int) inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(float &, RefTest1FF,1,(float &), 0, (), return (n_printf("%f\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(char * &, RefTest1SS,1,(char * &), 0, (), return (n_printf("%s\n", inarg1), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(void * &, RefTest1OO,1,(void * &), 0, (), return (n_printf("0x%x %s\n", inarg1, ((nRoot *) inarg1)->GetName() ), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(nRoot * &, RefTest1OO2,1,(nRoot * &), 0, (), return (n_printf("0x%x %s\n", inarg1, inarg1->GetName()), inarg1) ); NCMDPROTOCPP_DECLARE_TEST(int, InOutTest1IV3, 1, (vector3 *), 1, (vector3 *), return ( outarg1->x = inarg1->x, outarg1->y = inarg1->y, outarg1->z = inarg1->z, 22 ) ); NCMDPROTOCPP_DECLARE_END(nTestCmdProtoCPP) };
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 162 ] ] ]
44eee2602948c75b282e19e1d49c7d2ba193f494
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/UIProcess/WebPageProxy.cpp
9d21c17a644f4593b41974ed523dc554b895a60b
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,499
cpp
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebPageProxy.h" #include "DrawingAreaProxy.h" #include "MessageID.h" #include "PageClient.h" #include "WebBackForwardList.h" #include "WebBackForwardListItem.h" #include "WebContext.h" #include "WebContextUserMessageCoders.h" #include "WebCoreArgumentCoders.h" #include "WebData.h" #include "WebEditCommandProxy.h" #include "WebEvent.h" #include "WebFormSubmissionListenerProxy.h" #include "WebFramePolicyListenerProxy.h" #include "WebPageMessageKinds.h" #include "WebPageNamespace.h" #include "WebPageProxyMessageKinds.h" #include "WebPreferences.h" #include "WebProcessManager.h" #include "WebProcessMessageKinds.h" #include "WebProcessProxy.h" #include "WebURLRequest.h" #include "WKContextPrivate.h" #include <stdio.h> #ifndef NDEBUG #include <wtf/RefCountedLeakCounter.h> #endif using namespace WebCore; namespace WebKit { #ifndef NDEBUG static WTF::RefCountedLeakCounter webPageProxyCounter("WebPageProxy"); #endif PassRefPtr<WebPageProxy> WebPageProxy::create(WebPageNamespace* pageNamespace, uint64_t pageID) { return adoptRef(new WebPageProxy(pageNamespace, pageID)); } WebPageProxy::WebPageProxy(WebPageNamespace* pageNamespace, uint64_t pageID) : m_pageClient(0) , m_pageNamespace(pageNamespace) , m_mainFrame(0) , m_estimatedProgress(0.0) , m_isInWindow(false) , m_backForwardList(WebBackForwardList::create(this)) , m_textZoomFactor(1) , m_pageZoomFactor(1) , m_valid(true) , m_closed(false) , m_pageID(pageID) { #ifndef NDEBUG webPageProxyCounter.increment(); #endif } WebPageProxy::~WebPageProxy() { #ifndef NDEBUG webPageProxyCounter.decrement(); #endif } WebProcessProxy* WebPageProxy::process() const { return m_pageNamespace->process(); } bool WebPageProxy::isValid() { return m_valid; } void WebPageProxy::setPageClient(PageClient* pageClient) { m_pageClient = pageClient; } void WebPageProxy::setDrawingArea(PassOwnPtr<DrawingAreaProxy> drawingArea) { if (drawingArea == m_drawingArea) return; m_drawingArea = drawingArea; } void WebPageProxy::initializeLoaderClient(const WKPageLoaderClient* loadClient) { m_loaderClient.initialize(loadClient); } void WebPageProxy::initializePolicyClient(const WKPagePolicyClient* policyClient) { m_policyClient.initialize(policyClient); } void WebPageProxy::initializeFormClient(const WKPageFormClient* formClient) { m_formClient.initialize(formClient); } void WebPageProxy::initializeUIClient(const WKPageUIClient* client) { m_uiClient.initialize(client); } void WebPageProxy::revive() { m_valid = true; m_pageNamespace->reviveIfNecessary(); m_pageNamespace->process()->addExistingWebPage(this, m_pageID); processDidRevive(); } void WebPageProxy::initializeWebPage(const IntSize& size, PassOwnPtr<DrawingAreaProxy> drawingArea) { if (!isValid()) { puts("initializeWebPage called with a dead WebProcess"); revive(); return; } m_drawingArea = drawingArea; process()->send(WebProcessMessage::Create, m_pageID, CoreIPC::In(size, pageNamespace()->context()->preferences()->store(), *(m_drawingArea.get()))); } void WebPageProxy::reinitializeWebPage(const WebCore::IntSize& size) { if (!isValid()) return; ASSERT(m_drawingArea); process()->send(WebProcessMessage::Create, m_pageID, CoreIPC::In(size, pageNamespace()->context()->preferences()->store(), *(m_drawingArea.get()))); } void WebPageProxy::close() { if (!isValid()) return; m_closed = true; process()->disconnectFramesFromPage(this); m_mainFrame = 0; m_pageTitle = String(); m_toolTip = String(); Vector<RefPtr<ScriptReturnValueCallback> > scriptReturnValueCallbacks; copyValuesToVector(m_scriptReturnValueCallbacks, scriptReturnValueCallbacks); for (size_t i = 0, size = scriptReturnValueCallbacks.size(); i < size; ++i) scriptReturnValueCallbacks[i]->invalidate(); m_scriptReturnValueCallbacks.clear(); Vector<RefPtr<RenderTreeExternalRepresentationCallback> > renderTreeExternalRepresentationCallbacks; copyValuesToVector(m_renderTreeExternalRepresentationCallbacks, renderTreeExternalRepresentationCallbacks); for (size_t i = 0, size = renderTreeExternalRepresentationCallbacks.size(); i < size; ++i) renderTreeExternalRepresentationCallbacks[i]->invalidate(); m_renderTreeExternalRepresentationCallbacks.clear(); Vector<RefPtr<FrameSourceCallback> > frameSourceCallbacks; copyValuesToVector(m_frameSourceCallbacks, frameSourceCallbacks); m_frameSourceCallbacks.clear(); for (size_t i = 0, size = frameSourceCallbacks.size(); i < size; ++i) frameSourceCallbacks[i]->invalidate(); Vector<WebEditCommandProxy*> editCommandVector; copyToVector(m_editCommandSet, editCommandVector); m_editCommandSet.clear(); for (size_t i = 0, size = editCommandVector.size(); i < size; ++i) editCommandVector[i]->invalidate(); m_estimatedProgress = 0.0; m_loaderClient.initialize(0); m_policyClient.initialize(0); m_uiClient.initialize(0); m_drawingArea.clear(); process()->send(WebPageMessage::Close, m_pageID, CoreIPC::In()); process()->removeWebPage(m_pageID); } bool WebPageProxy::tryClose() { if (!isValid()) return true; process()->send(WebPageMessage::TryClose, m_pageID, CoreIPC::In()); return false; } void WebPageProxy::loadURL(const String& url) { if (!isValid()) { puts("loadURL called with a dead WebProcess"); revive(); } process()->send(WebPageMessage::LoadURL, m_pageID, CoreIPC::In(url)); } void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest) { if (!isValid()) { puts("loadURLRequest called with a dead WebProcess"); revive(); } process()->send(WebPageMessage::LoadURLRequest, m_pageID, CoreIPC::In(urlRequest->resourceRequest())); } void WebPageProxy::stopLoading() { if (!isValid()) return; process()->send(WebPageMessage::StopLoading, m_pageID, CoreIPC::In()); } void WebPageProxy::reload(bool reloadFromOrigin) { if (!isValid()) return; process()->send(WebPageMessage::Reload, m_pageID, CoreIPC::In(reloadFromOrigin)); } void WebPageProxy::goForward() { if (!isValid()) return; if (!canGoForward()) return; process()->send(WebPageMessage::GoForward, m_pageID, CoreIPC::In(m_backForwardList->forwardItem()->itemID())); } bool WebPageProxy::canGoForward() const { return m_backForwardList->forwardItem(); } void WebPageProxy::goBack() { if (!isValid()) return; if (!canGoBack()) return; process()->send(WebPageMessage::GoBack, m_pageID, CoreIPC::In(m_backForwardList->backItem()->itemID())); } bool WebPageProxy::canGoBack() const { return m_backForwardList->backItem(); } void WebPageProxy::goToBackForwardItem(WebBackForwardListItem* item) { if (!isValid()) return; process()->send(WebPageMessage::GoToBackForwardItem, m_pageID, CoreIPC::In(item->itemID())); } void WebPageProxy::didChangeBackForwardList() { m_loaderClient.didChangeBackForwardList(this); } void WebPageProxy::setFocused(bool isFocused) { if (!isValid()) return; process()->send(WebPageMessage::SetFocused, m_pageID, CoreIPC::In(isFocused)); } void WebPageProxy::setActive(bool active) { if (!isValid()) return; process()->send(WebPageMessage::SetActive, m_pageID, CoreIPC::In(active)); } void WebPageProxy::setIsInWindow(bool isInWindow) { if (m_isInWindow == isInWindow) return; m_isInWindow = isInWindow; if (!isValid()) return; process()->send(WebPageMessage::SetIsInWindow, m_pageID, CoreIPC::In(isInWindow)); } void WebPageProxy::mouseEvent(const WebMouseEvent& event) { if (!isValid()) return; // NOTE: This does not start the responsiveness timer because mouse move should not indicate interaction. if (event.type() != WebEvent::MouseMove) process()->responsivenessTimer()->start(); process()->send(WebPageMessage::MouseEvent, m_pageID, CoreIPC::In(event)); } void WebPageProxy::wheelEvent(const WebWheelEvent& event) { if (!isValid()) return; process()->responsivenessTimer()->start(); process()->send(WebPageMessage::WheelEvent, m_pageID, CoreIPC::In(event)); } void WebPageProxy::keyEvent(const WebKeyboardEvent& event) { if (!isValid()) return; process()->responsivenessTimer()->start(); process()->send(WebPageMessage::KeyEvent, m_pageID, CoreIPC::In(event)); } #if ENABLE(TOUCH_EVENTS) void WebPageProxy::touchEvent(const WebTouchEvent& event) { if (!isValid()) return; process()->send(WebPageMessage::TouchEvent, m_pageID, CoreIPC::In(event)); } #endif void WebPageProxy::receivedPolicyDecision(WebCore::PolicyAction action, WebFrameProxy* frame, uint64_t listenerID) { if (!isValid()) return; process()->send(WebPageMessage::DidReceivePolicyDecision, m_pageID, CoreIPC::In(frame->frameID(), listenerID, (uint32_t)action)); } void WebPageProxy::setCustomUserAgent(const String& userAgent) { if (!isValid()) return; process()->send(WebPageMessage::SetCustomUserAgent, m_pageID, CoreIPC::In(userAgent)); } void WebPageProxy::terminateProcess() { if (!isValid()) return; process()->terminate(); } PassRefPtr<WebData> WebPageProxy::sessionState() const { // FIXME: Return session state data for saving Page state. return 0; } void WebPageProxy::restoreFromSessionState(WebData*) { // FIXME: Restore the Page from the passed in session state data. } void WebPageProxy::setTextZoomFactor(double zoomFactor) { if (!isValid()) return; if (m_textZoomFactor == zoomFactor) return; m_textZoomFactor = zoomFactor; process()->send(WebPageMessage::SetTextZoomFactor, m_pageID, CoreIPC::In(m_textZoomFactor)); } void WebPageProxy::setPageZoomFactor(double zoomFactor) { if (!isValid()) return; if (m_pageZoomFactor == zoomFactor) return; m_pageZoomFactor = zoomFactor; process()->send(WebPageMessage::SetPageZoomFactor, m_pageID, CoreIPC::In(m_pageZoomFactor)); } void WebPageProxy::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor) { if (!isValid()) return; if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor) return; m_pageZoomFactor = pageZoomFactor; m_textZoomFactor = textZoomFactor; process()->send(WebPageMessage::SetPageAndTextZoomFactors, m_pageID, CoreIPC::In(m_pageZoomFactor, m_textZoomFactor)); } void WebPageProxy::runJavaScriptInMainFrame(const String& script, PassRefPtr<ScriptReturnValueCallback> prpCallback) { RefPtr<ScriptReturnValueCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_scriptReturnValueCallbacks.set(callbackID, callback.get()); process()->send(WebPageMessage::RunJavaScriptInMainFrame, m_pageID, CoreIPC::In(script, callbackID)); } void WebPageProxy::getRenderTreeExternalRepresentation(PassRefPtr<RenderTreeExternalRepresentationCallback> prpCallback) { RefPtr<RenderTreeExternalRepresentationCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_renderTreeExternalRepresentationCallbacks.set(callbackID, callback.get()); process()->send(WebPageMessage::GetRenderTreeExternalRepresentation, m_pageID, callbackID); } void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, PassRefPtr<FrameSourceCallback> prpCallback) { RefPtr<FrameSourceCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_frameSourceCallbacks.set(callbackID, callback.get()); process()->send(WebPageMessage::GetSourceForFrame, m_pageID, CoreIPC::In(frame->frameID(), callbackID)); } void WebPageProxy::preferencesDidChange() { if (!isValid()) return; // FIXME: It probably makes more sense to send individual preference changes. // However, WebKitTestRunner depends on getting a preference change notification even if nothing changed in UI process, so that overrides get removed. process()->send(WebPageMessage::PreferencesDidChange, m_pageID, CoreIPC::In(pageNamespace()->context()->preferences()->store())); } void WebPageProxy::getStatistics(WKContextStatistics* statistics) { statistics->numberOfWKFrames += process()->frameCountInPage(this); } void WebPageProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments) { if (messageID.is<CoreIPC::MessageClassDrawingAreaProxy>()) { m_drawingArea->didReceiveMessage(connection, messageID, arguments); return; } switch (messageID.get<WebPageProxyMessage::Kind>()) { case WebPageProxyMessage::DidCreateMainFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didCreateMainFrame(frameID); break; } case WebPageProxyMessage::DidCreateSubFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didCreateSubFrame(frameID); break; } case WebPageProxyMessage::DidStartProvisionalLoadForFrame: { uint64_t frameID; String url; if (!arguments->decode(CoreIPC::Out(frameID, url))) return; didStartProvisionalLoadForFrame(process()->webFrame(frameID), url); break; } case WebPageProxyMessage::DidReceiveServerRedirectForProvisionalLoadForFrame: { uint64_t frameID; String url; if (!arguments->decode(CoreIPC::Out(frameID, url))) return; didReceiveServerRedirectForProvisionalLoadForFrame(process()->webFrame(frameID), url); break; } case WebPageProxyMessage::DidFailProvisionalLoadForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFailProvisionalLoadForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidCommitLoadForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didCommitLoadForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidFinishDocumentLoadForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFinishDocumentLoadForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidFinishLoadForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFinishLoadForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidFailLoadForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFailLoadForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidReceiveTitleForFrame: { uint64_t frameID; String title; if (!arguments->decode(CoreIPC::Out(frameID, title))) return; didReceiveTitleForFrame(process()->webFrame(frameID), title); break; } case WebPageProxyMessage::DidFirstLayoutForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFirstLayoutForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidFirstVisuallyNonEmptyLayoutForFrame: { uint64_t frameID; if (!arguments->decode(frameID)) return; didFirstVisuallyNonEmptyLayoutForFrame(process()->webFrame(frameID)); break; } case WebPageProxyMessage::DidStartProgress: didStartProgress(); break; case WebPageProxyMessage::DidChangeProgress: { double value; if (!arguments->decode(value)) return; didChangeProgress(value); break; } case WebPageProxyMessage::DidFinishProgress: didFinishProgress(); break; case WebPageProxyMessage::DidReceiveEvent: { uint32_t type; if (!arguments->decode(type)) return; didReceiveEvent((WebEvent::Type)type); break; } case WebPageProxyMessage::TakeFocus: { // FIXME: Use enum here. bool direction; if (!arguments->decode(direction)) return; takeFocus(direction); break; } case WebPageProxyMessage::DecidePolicyForNavigationAction: { uint64_t frameID; uint32_t navigationType; uint32_t modifiers; String url; uint64_t listenerID; if (!arguments->decode(CoreIPC::Out(frameID, navigationType, modifiers, url, listenerID))) return; decidePolicyForNavigationAction(process()->webFrame(frameID), static_cast<NavigationType>(navigationType), static_cast<WebEvent::Modifiers>(modifiers), url, listenerID); break; } case WebPageProxyMessage::DecidePolicyForNewWindowAction: { uint64_t frameID; uint32_t navigationType; uint32_t modifiers; String url; uint64_t listenerID; if (!arguments->decode(CoreIPC::Out(frameID, navigationType, modifiers, url, listenerID))) return; decidePolicyForNewWindowAction(process()->webFrame(frameID), static_cast<NavigationType>(navigationType), static_cast<WebEvent::Modifiers>(modifiers), url, listenerID); break; } case WebPageProxyMessage::DecidePolicyForMIMEType: { uint64_t frameID; String MIMEType; String url; uint64_t listenerID; if (!arguments->decode(CoreIPC::Out(frameID, MIMEType, url, listenerID))) return; decidePolicyForMIMEType(process()->webFrame(frameID), MIMEType, url, listenerID); break; } case WebPageProxyMessage::WillSubmitForm: { uint64_t frameID; uint64_t sourceFrameID; Vector<std::pair<String, String> > textFieldValues; uint64_t listenerID; RefPtr<APIObject> userData; WebContextUserMessageDecoder messageDecoder(userData, pageNamespace()->context()); if (!arguments->decode(CoreIPC::Out(frameID, sourceFrameID, textFieldValues, listenerID, messageDecoder))) return; willSubmitForm(process()->webFrame(frameID), process()->webFrame(sourceFrameID), textFieldValues, userData.get(), listenerID); break; } case WebPageProxyMessage::DidRunJavaScriptInMainFrame: { String resultString; uint64_t callbackID; if (!arguments->decode(CoreIPC::Out(resultString, callbackID))) return; didRunJavaScriptInMainFrame(resultString, callbackID); break; } case WebPageProxyMessage::DidGetRenderTreeExternalRepresentation: { String resultString; uint64_t callbackID; if (!arguments->decode(CoreIPC::Out(resultString, callbackID))) return; didGetRenderTreeExternalRepresentation(resultString, callbackID); break; } case WebPageProxyMessage::DidGetSourceForFrame: { String resultString; uint64_t callbackID; if (!arguments->decode(CoreIPC::Out(resultString, callbackID))) return; didGetSourceForFrame(resultString, callbackID); break; } case WebPageProxyMessage::SetToolTip: { String toolTip; if (!arguments->decode(toolTip)) return; setToolTip(toolTip); break; } case WebPageProxyMessage::SetCursor: { #if USE(LAZY_NATIVE_CURSOR) Cursor cursor; if (!arguments->decode(cursor)) return; setCursor(cursor); #endif break; } case WebPageProxyMessage::ShowPage: { showPage(); break; } case WebPageProxyMessage::ClosePage: { closePage(); break; } case WebPageProxyMessage::BackForwardAddItem: { uint64_t itemID; if (!arguments->decode(CoreIPC::Out(itemID))) return; addItemToBackForwardList(process()->webBackForwardItem(itemID)); break; } case WebPageProxyMessage::BackForwardGoToItem: { uint64_t itemID; if (!arguments->decode(CoreIPC::Out(itemID))) return; goToItemInBackForwardList(process()->webBackForwardItem(itemID)); break; } case WebPageProxyMessage::ContentsSizeChanged: { IntSize size; uint64_t frameID; if (!arguments->decode(CoreIPC::Out(frameID, size))) return; contentsSizeChanged(process()->webFrame(frameID), size); break; } case WebPageProxyMessage::SetStatusText: { String text; if (!arguments->decode(CoreIPC::Out(text))) return; setStatusText(text); break; } case WebPageProxyMessage::RegisterEditCommandForUndo: { uint64_t commandID; uint32_t editAction; if (!arguments->decode(CoreIPC::Out(commandID, editAction))) return; registerEditCommandForUndo(commandID, static_cast<EditAction>(editAction)); break; } case WebPageProxyMessage::ClearAllEditCommands: clearAllEditCommands(); break; default: ASSERT_NOT_REACHED(); break; } } void WebPageProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, CoreIPC::ArgumentEncoder* reply) { if (messageID.is<CoreIPC::MessageClassDrawingAreaProxy>()) { m_drawingArea->didReceiveSyncMessage(connection, messageID, arguments, reply); return; } switch (messageID.get<WebPageProxyMessage::Kind>()) { case WebPageProxyMessage::CreateNewPage: { RefPtr<WebPageProxy> newPage = createNewPage(); if (newPage) { // FIXME: Pass the real size. reply->encode(CoreIPC::In(newPage->pageID(), IntSize(100, 100), newPage->pageNamespace()->context()->preferences()->store(), *(newPage->drawingArea()))); } else { reply->encode(CoreIPC::In(static_cast<uint64_t>(0), IntSize(), WebPreferencesStore(), DrawingAreaBase::DrawingAreaInfo())); } break; } case WebPageProxyMessage::RunJavaScriptAlert: { uint64_t frameID; String message; if (!arguments->decode(CoreIPC::Out(frameID, message))) return; runJavaScriptAlert(process()->webFrame(frameID), message); break; } case WebPageProxyMessage::RunJavaScriptConfirm: { // FIXME: We should probably encode something in the case that the arguments do not decode correctly. uint64_t frameID; String message; if (!arguments->decode(CoreIPC::Out(frameID, message))) return; bool result = runJavaScriptConfirm(process()->webFrame(frameID), message); reply->encode(CoreIPC::In(result)); break; } case WebPageProxyMessage::RunJavaScriptPrompt: { // FIXME: We should probably encode something in the case that the arguments do not decode correctly. uint64_t frameID; String message; String defaultValue; if (!arguments->decode(CoreIPC::Out(frameID, message, defaultValue))) return; String result = runJavaScriptPrompt(process()->webFrame(frameID), message, defaultValue); reply->encode(CoreIPC::In(result)); break; } case WebPageProxyMessage::BackForwardBackItem: { WebBackForwardListItem* backItem = m_backForwardList->backItem(); uint64_t backItemID = backItem ? backItem->itemID() : 0; reply->encode(CoreIPC::In(backItemID)); break; } case WebPageProxyMessage::BackForwardCurrentItem: { WebBackForwardListItem* currentItem = m_backForwardList->currentItem(); uint64_t currentItemID = currentItem ? currentItem->itemID() : 0; reply->encode(CoreIPC::In(currentItemID)); break; } case WebPageProxyMessage::BackForwardForwardItem: { WebBackForwardListItem* forwardItem = m_backForwardList->forwardItem(); uint64_t forwardItemID = forwardItem ? forwardItem->itemID() : 0; reply->encode(CoreIPC::In(forwardItemID)); break; } case WebPageProxyMessage::BackForwardItemAtIndex: { int itemIndex; if (!arguments->decode(CoreIPC::Out(itemIndex))) return; WebBackForwardListItem* item = m_backForwardList->itemAtIndex(itemIndex); uint64_t itemID = item ? item->itemID() : 0; reply->encode(CoreIPC::In(itemID)); break; } case WebPageProxyMessage::BackForwardBackListCount: { int backListCount = m_backForwardList->backListCount(); reply->encode(CoreIPC::In(backListCount)); break; } case WebPageProxyMessage::BackForwardForwardListCount: { int forwardListCount = m_backForwardList->forwardListCount(); reply->encode(CoreIPC::In(forwardListCount)); break; } #if USE(ACCELERATED_COMPOSITING) case WebPageProxyMessage::DidChangeAcceleratedCompositing: { bool compositing; if (!arguments->decode(CoreIPC::Out(compositing))) return; didChangeAcceleratedCompositing(compositing); reply->encode(*(drawingArea())); break; } #endif // USE(ACCELERATED_COMPOSITING) default: ASSERT_NOT_REACHED(); break; } } void WebPageProxy::didCreateMainFrame(uint64_t frameID) { ASSERT(!m_mainFrame); m_mainFrame = WebFrameProxy::create(this, frameID); process()->frameCreated(frameID, m_mainFrame.get()); } void WebPageProxy::didCreateSubFrame(uint64_t frameID) { ASSERT(m_mainFrame); process()->frameCreated(frameID, WebFrameProxy::create(this, frameID).get()); } void WebPageProxy::didStartProgress() { m_estimatedProgress = 0.0; m_loaderClient.didStartProgress(this); } void WebPageProxy::didChangeProgress(double value) { m_estimatedProgress = value; m_loaderClient.didChangeProgress(this); } void WebPageProxy::didFinishProgress() { m_estimatedProgress = 1.0; m_loaderClient.didFinishProgress(this); } void WebPageProxy::didStartProvisionalLoadForFrame(WebFrameProxy* frame, const String& url) { frame->didStartProvisionalLoad(url); m_loaderClient.didStartProvisionalLoadForFrame(this, frame); } void WebPageProxy::didReceiveServerRedirectForProvisionalLoadForFrame(WebFrameProxy* frame, const String& url) { frame->didReceiveServerRedirectForProvisionalLoad(url); m_loaderClient.didReceiveServerRedirectForProvisionalLoadForFrame(this, frame); } void WebPageProxy::didFailProvisionalLoadForFrame(WebFrameProxy* frame) { m_loaderClient.didFailProvisionalLoadWithErrorForFrame(this, frame); } void WebPageProxy::didCommitLoadForFrame(WebFrameProxy* frame) { frame->didCommitLoad(); m_loaderClient.didCommitLoadForFrame(this, frame); } void WebPageProxy::didFinishDocumentLoadForFrame(WebFrameProxy* frame) { m_loaderClient.didFinishDocumentLoadForFrame(this, frame); } void WebPageProxy::didFinishLoadForFrame(WebFrameProxy* frame) { frame->didFinishLoad(); m_loaderClient.didFinishLoadForFrame(this, frame); } void WebPageProxy::didFailLoadForFrame(WebFrameProxy* frame) { m_loaderClient.didFailLoadWithErrorForFrame(this, frame); } void WebPageProxy::didReceiveTitleForFrame(WebFrameProxy* frame, const String& title) { frame->didReceiveTitle(title); // Cache the title for the main frame in the page. if (frame == m_mainFrame) m_pageTitle = title; m_loaderClient.didReceiveTitleForFrame(this, title.impl(), frame); } void WebPageProxy::didFirstLayoutForFrame(WebFrameProxy* frame) { m_loaderClient.didFirstLayoutForFrame(this, frame); } void WebPageProxy::didFirstVisuallyNonEmptyLayoutForFrame(WebFrameProxy* frame) { m_loaderClient.didFirstVisuallyNonEmptyLayoutForFrame(this, frame); } // PolicyClient void WebPageProxy::decidePolicyForNavigationAction(WebFrameProxy* frame, NavigationType navigationType, WebEvent::Modifiers modifiers, const String& url, uint64_t listenerID) { RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); if (!m_policyClient.decidePolicyForNavigationAction(this, navigationType, modifiers, url, frame, listener.get())) listener->use(); } void WebPageProxy::decidePolicyForNewWindowAction(WebFrameProxy* frame, NavigationType navigationType, WebEvent::Modifiers modifiers, const String& url, uint64_t listenerID) { RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); if (!m_policyClient.decidePolicyForNewWindowAction(this, navigationType, modifiers, url, frame, listener.get())) listener->use(); } void WebPageProxy::decidePolicyForMIMEType(WebFrameProxy* frame, const String& MIMEType, const String& url, uint64_t listenerID) { RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); if (!m_policyClient.decidePolicyForMIMEType(this, MIMEType, url, frame, listener.get())) listener->use(); } // FormClient void WebPageProxy::willSubmitForm(WebFrameProxy* frame, WebFrameProxy* sourceFrame, Vector<std::pair<String, String> >& textFieldValues, APIObject* userData, uint64_t listenerID) { RefPtr<WebFormSubmissionListenerProxy> listener = frame->setUpFormSubmissionListenerProxy(listenerID); if (!m_formClient.willSubmitForm(this, frame, sourceFrame, textFieldValues, userData, listener.get())) listener->continueSubmission(); } // UIClient PassRefPtr<WebPageProxy> WebPageProxy::createNewPage() { return m_uiClient.createNewPage(this); } void WebPageProxy::showPage() { m_uiClient.showPage(this); } void WebPageProxy::closePage() { m_uiClient.close(this); } void WebPageProxy::runJavaScriptAlert(WebFrameProxy* frame, const String& message) { m_uiClient.runJavaScriptAlert(this, message, frame); } bool WebPageProxy::runJavaScriptConfirm(WebFrameProxy* frame, const String& message) { return m_uiClient.runJavaScriptConfirm(this, message, frame); } String WebPageProxy::runJavaScriptPrompt(WebFrameProxy* frame, const String& message, const String& defaultValue) { return m_uiClient.runJavaScriptPrompt(this, message, defaultValue, frame); } void WebPageProxy::setStatusText(const String& text) { m_uiClient.setStatusText(this, text); } void WebPageProxy::contentsSizeChanged(WebFrameProxy* frame, const WebCore::IntSize& size) { m_uiClient.contentsSizeChanged(this, size, frame); } // BackForwardList void WebPageProxy::addItemToBackForwardList(WebBackForwardListItem* item) { m_backForwardList->addItem(item); } void WebPageProxy::goToItemInBackForwardList(WebBackForwardListItem* item) { m_backForwardList->goToItem(item); } // Undo management void WebPageProxy::registerEditCommandForUndo(uint64_t commandID, EditAction editAction) { registerEditCommandForUndo(WebEditCommandProxy::create(commandID, editAction, this)); } void WebPageProxy::clearAllEditCommands() { m_pageClient->clearAllEditCommands(); } void WebPageProxy::registerEditCommandForUndo(PassRefPtr<WebEditCommandProxy> commandProxy) { m_pageClient->registerEditCommand(commandProxy, PageClient::Undo); } void WebPageProxy::registerEditCommandForRedo(PassRefPtr<WebEditCommandProxy> commandProxy) { m_pageClient->registerEditCommand(commandProxy, PageClient::Redo); } void WebPageProxy::addEditCommand(WebEditCommandProxy* command) { m_editCommandSet.add(command); } void WebPageProxy::removeEditCommand(WebEditCommandProxy* command) { m_editCommandSet.remove(command); if (!isValid()) return; process()->send(WebPageMessage::DidRemoveEditCommand, m_pageID, command->commandID()); } // Other void WebPageProxy::takeFocus(bool direction) { m_pageClient->takeFocus(direction); } void WebPageProxy::setToolTip(const String& toolTip) { String oldToolTip = m_toolTip; m_toolTip = toolTip; m_pageClient->toolTipChanged(oldToolTip, m_toolTip); } void WebPageProxy::setCursor(const WebCore::Cursor& cursor) { m_pageClient->setCursor(cursor); } void WebPageProxy::didReceiveEvent(WebEvent::Type type) { switch (type) { case WebEvent::MouseMove: break; case WebEvent::MouseDown: case WebEvent::MouseUp: case WebEvent::Wheel: case WebEvent::KeyDown: case WebEvent::KeyUp: case WebEvent::RawKeyDown: case WebEvent::Char: process()->responsivenessTimer()->stop(); break; } } void WebPageProxy::didRunJavaScriptInMainFrame(const String& resultString, uint64_t callbackID) { RefPtr<ScriptReturnValueCallback> callback = m_scriptReturnValueCallbacks.take(callbackID); if (!callback) { // FIXME: Log error or assert. return; } callback->performCallbackWithReturnValue(resultString.impl()); } void WebPageProxy::didGetRenderTreeExternalRepresentation(const String& resultString, uint64_t callbackID) { RefPtr<RenderTreeExternalRepresentationCallback> callback = m_renderTreeExternalRepresentationCallbacks.take(callbackID); if (!callback) { // FIXME: Log error or assert. return; } callback->performCallbackWithReturnValue(resultString.impl()); } void WebPageProxy::didGetSourceForFrame(const String& resultString, uint64_t callbackID) { RefPtr<FrameSourceCallback> callback = m_frameSourceCallbacks.take(callbackID); if (!callback) { // FIXME: Log error or assert. return; } callback->performCallbackWithReturnValue(resultString.impl()); } #if USE(ACCELERATED_COMPOSITING) void WebPageProxy::didChangeAcceleratedCompositing(bool compositing) { if (compositing) didEnterAcceleratedCompositing(); else didLeaveAcceleratedCompositing(); } #endif void WebPageProxy::processDidBecomeUnresponsive() { m_loaderClient.didBecomeUnresponsive(this); } void WebPageProxy::processDidBecomeResponsive() { m_loaderClient.didBecomeResponsive(this); } void WebPageProxy::processDidExit() { ASSERT(m_pageClient); m_valid = false; if (m_mainFrame) m_urlAtProcessExit = m_mainFrame->url(); m_mainFrame = 0; m_pageTitle = String(); m_toolTip = String(); Vector<RefPtr<ScriptReturnValueCallback> > scriptReturnValueCallbacks; copyValuesToVector(m_scriptReturnValueCallbacks, scriptReturnValueCallbacks); for (size_t i = 0, size = scriptReturnValueCallbacks.size(); i < size; ++i) scriptReturnValueCallbacks[i]->invalidate(); m_scriptReturnValueCallbacks.clear(); Vector<RefPtr<RenderTreeExternalRepresentationCallback> > renderTreeExternalRepresentationCallbacks; copyValuesToVector(m_renderTreeExternalRepresentationCallbacks, renderTreeExternalRepresentationCallbacks); for (size_t i = 0, size = renderTreeExternalRepresentationCallbacks.size(); i < size; ++i) renderTreeExternalRepresentationCallbacks[i]->invalidate(); m_renderTreeExternalRepresentationCallbacks.clear(); Vector<RefPtr<FrameSourceCallback> > frameSourceCallbacks; copyValuesToVector(m_frameSourceCallbacks, frameSourceCallbacks); m_frameSourceCallbacks.clear(); for (size_t i = 0, size = frameSourceCallbacks.size(); i < size; ++i) frameSourceCallbacks[i]->invalidate(); Vector<WebEditCommandProxy*> editCommandVector; copyToVector(m_editCommandSet, editCommandVector); m_editCommandSet.clear(); for (size_t i = 0, size = editCommandVector.size(); i < size; ++i) editCommandVector[i]->invalidate(); m_pageClient->clearAllEditCommands(); m_estimatedProgress = 0.0; m_pageClient->processDidExit(); m_loaderClient.processDidExit(this); } void WebPageProxy::processDidRevive() { ASSERT(m_pageClient); m_pageClient->processDidRevive(); } #if USE(ACCELERATED_COMPOSITING) void WebPageProxy::didEnterAcceleratedCompositing() { m_pageClient->pageDidEnterAcceleratedCompositing(); } void WebPageProxy::didLeaveAcceleratedCompositing() { m_pageClient->pageDidLeaveAcceleratedCompositing(); } #endif // USE(ACCELERATED_COMPOSITING) } // namespace WebKit
[ [ [ 1, 1222 ] ] ]
e5f00d166161e0082edadae07b7c5625eabd7450
1e01b697191a910a872e95ddfce27a91cebc57dd
/BNFReadCChar.h
9c4f7e077271298b34fb3c6b959ed8675d3c1524
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
2,045
h
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2004 Cรšdric Lemaire This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifndef _BNFReadCChar_h_ #define _BNFReadCChar_h_ #include "GrfBlock.h" namespace CodeWorker { class DtaBNFScript; class BNFClause; class ExprScriptVariable; class BNFReadCChar : public GrfCommand { private: DtaBNFScript* _pBNFScript; ExprScriptVariable* _pVariableToAssign; bool _bConcatVariable; std::vector<std::string> _listOfConstants; int _iClauseReturnType; bool _bContinue; bool _bNoCase; public: BNFReadCChar(DtaBNFScript* pBNFScript, GrfBlock* pParent, bool bContinue, bool bNoCase); virtual ~BNFReadCChar(); virtual void accept(DtaVisitor& visitor, DtaVisitorEnvironment& env); virtual bool isABNFCommand() const; void setVariableToAssign(ExprScriptVariable* pVariableToAssign, bool bConcat, BNFClause& theClause); inline void setConstantsToMatch(const std::vector<std::string>& listOfConstants) { _listOfConstants = listOfConstants; } virtual std::string toString() const; void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const; protected: virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility); }; } #endif
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 62 ] ] ]
0bbf5e94595a2dca82c88dd2dc3b35bf736a00c3
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/test_contained_class.cpp
074e0c3118ea1df6d0080db077dd9e4e6b1f810e
[]
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
1,661
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_contained_class.cpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // 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) // should pass compilation and execution #include <fstream> #include <cstdio> // remove #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::remove; } #endif #include <boost/serialization/nvp.hpp> #include "test_tools.hpp" #include "B.hpp" /////////////////////////////////////////////////////// // Contained class class C { private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int /* file_version */){ ar & BOOST_SERIALIZATION_NVP(b); } B b; public: bool operator==(const C &rhs) const { return b == rhs.b; } }; int test_main( int /* argc */, char* /* argv */[] ) { const char * testfile = boost::archive::tmpnam(NULL); BOOST_REQUIRE(NULL != testfile); C c, c1; { test_ostream os(testfile, TEST_STREAM_FLAGS); test_oarchive oa(os); oa << boost::serialization::make_nvp("c", c); } { test_istream is(testfile, TEST_STREAM_FLAGS); test_iarchive ia(is); ia >> boost::serialization::make_nvp("c", c1); } BOOST_CHECK(c == c1); std::remove(testfile); return boost::exit_success; } // EOF
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 66 ] ] ]
824d9e35219d129ed4961ba751707848f0369527
30e4267e1a7fe172118bf26252aa2eb92b97a460
/tools/MakePluginPerl/MFCExtTempl/Cx_Example.cpp
332350b02a8bc6220cd70f5e4dbe3d97baeb71b6
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
UTF-8
C++
false
false
217
cpp
#include "StdAfx.h" #include "Cx_Example.h" Cx_Example::Cx_Example() { } Cx_Example::~Cx_Example() { } void Cx_Example::Foo() { AfxMessageBox(L"Cx_Example::Foo"); } void Cx_Example::Foo2() { }
[ "thinkye@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 19 ] ] ]
62250a18a7f88ebad4c1c25e767fddee9e36074a
29e87c19d99b77d379b2f9760f5e7afb3b3790fa
/src/qt-client/QToggleHeaderAction.cpp
dafac33a0e065eedf26a84335af0bb0b6e3b06d5
[]
no_license
wilcobrouwer/dmplayer
c0c63d9b641a0f76e426ed30c3a83089166d0000
9f767a15e25016f6ada4eff6a1cdd881ad922915
refs/heads/master
2021-05-30T17:23:21.889844
2011-03-29T08:51:52
2011-03-29T08:51:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
#include "QToggleHeaderAction.moc" #include <QTreeWidget> QToggleHeaderAction::QToggleHeaderAction(QTreeView* widget, const QString& name_, int pos_) : view(widget) , pos(pos_) , QAction(name_, widget) { QObject::connect(this, SIGNAL(triggered(bool)), this, SLOT(execute(bool))); this->setCheckable(true); } void QToggleHeaderAction::execute(bool checked) { if (checked) view->showColumn(pos); else view->hideColumn(pos); //this->toggle(); }
[ "simon.sasburg@e69229e2-1541-0410-bedc-87cb2d1b0d4b" ]
[ [ [ 1, 21 ] ] ]
20c998687f9e19ac6255889cf9fc5465ccbd5fde
25f1d3e7bbb6f445174e75fed29a1028546d3562
/2DTransView.h
c48b54d934e6e1e2359cbcf56f46f714df2e2731
[]
no_license
psgsgpsg/windr2-project
288694c5d4bb8f28e67c392a2b15220d4b02f9af
4f4f92734860cba028399bda6ab4ea7d46f63ca1
refs/heads/master
2021-01-22T23:26:48.972710
2010-06-16T08:31:34
2010-06-16T08:31:34
39,536,718
0
0
null
null
null
null
UTF-8
C++
false
false
4,243
h
๏ปฟ// 2DTransView.h : CMy2DTransView ํด๋ž˜์Šค์˜ ์ธํ„ฐํŽ˜์ด์Šค // #pragma once // ํ‘œ์ค€ STL vector ์ปจํ…Œ์ด๋„ˆ์™€, DisplayList ํด๋ž˜์Šค #include <vector> #include "DisplayList.h" class CMy2DTransView : public CView { protected: // serialization์—์„œ๋งŒ ๋งŒ๋“ค์–ด์ง‘๋‹ˆ๋‹ค. CMy2DTransView(); DECLARE_DYNCREATE(CMy2DTransView) // ํŠน์„ฑ์ž…๋‹ˆ๋‹ค. // ์ง์ ‘ ์ถ”๊ฐ€ํ•œ ๋ฉค๋ฒ„ ๋ณ€์ˆ˜ ๋ฆฌ์ŠคํŠธ public: CMy2DTransDoc* GetDocument() const; double Scale, delScale; // ์Šค์ผ€์ผ ๋ฐ ์Šค์ผ€์ผ ์ฆ๋ถ„ ๋ณ€์ˆ˜ int DirSize; // ํ˜•์ƒ ๋ณ€๊ฒฝ์‹œ ์‚ฌ์šฉ๋˜๋Š” ๋ณ€์ˆ˜ vector<DisplayList> DList, tempList; // ์  ๋ฐ์ดํ„ฐ ์ €์žฅ์„ ์œ„ํ•œ ๊ตฌ์กฐ์ฒด๋ฅผ ์„ ์–ธํ•จ //CBrush jbrBack; // ๋ฐ”ํƒ• ๋ฐฐ๊ฒฝ ์น ํ•˜๊ธฐ์šฉ ๋ธŒ๋Ÿฌ์‹œ CRect rcClient; // ํด๋ผ์ด์–ธํŠธ ์˜์—ญ ์ €์žฅ์šฉ ๊ตฌ์กฐ์ฒด //COLORREF crBack; // ๋ฐฐ๊ฒฝ ์ƒ‰์„ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ ๊ตฌ์กฐ์ฒด CPoint anchor, curPoint; // Mouse location points CString status; // ์ƒํƒœ ํ‘œ์‹œ์ค„์šฉ CString ๊ฐ์ฒด int cen_x, cen_y; // ๋ทฐ ์˜์—ญ์˜ ์ค‘์‹ฌ์  ์ขŒํ‘œ double MaxX, MaxY, MinX, MinY; // ๋ฐ์ดํ„ฐ๋กœ๋ถ€ํ„ฐ ์ตœ๋Œ€ ์ตœ์†Œ๊ฐ’์„ ์ฝ์–ด๋“ค์ž„ int nElements; // ์ „์ฒด ๋„ํ˜•์˜ ๊ฐฏ์ˆ˜ double wsx, wsy, CenX, CenY; double moveSize, scaleSize; // UI๋กœ๋ถ€ํ„ฐ์˜ ์ž…๋ ฅ ๋ณ€์ˆ˜ ์ €์žฅ์šฉ double originX, originY; // ๋ฐ์ดํ„ฐ์˜ ์›์ ์ด View์ƒ์˜ ์ขŒํ‘œ๋กœ ๋ณ€ํ™˜๋œ ์ขŒํ‘œ double moveX, moveY; // ๋งˆ์šฐ์Šค๋กœ ๋“œ๋ž˜๊ทธ์‹œ ์ด๋™ํ•œ ์ด ๋ณ€๋Ÿ‰์„ ์ €์žฅํ•˜๋Š” ๋ฐ์ดํ„ฐ int WIDTH, HEIGHT; // View ์˜์—ญ์˜ ํญ๊ณผ ๋†’์ด๋ฅผ ์ €์ •ํ•˜๋Š” ๋ณ€์ˆ˜ double rotCenterX, rotCenterY; // ํšŒ์ „ ์ค‘์‹ฌ ์ขŒํ‘œ์  (๋ฐ์ดํ„ฐ ์ขŒํ‘œ) double rotCenterX_view, rotCenterY_view; // ํšŒ์ „ ์ค‘์‹ฌ ์ขŒํ‘œ์  (view์— ๋งคํ•‘๋œ ์ขŒํ‘œ) double rotAngle; // ํšŒ์ „ ๊ฐ๋„ ์ €์žฅ ๋ณ€์ˆ˜ double totalRot; // ์ „์ฒด ํšŒ์ „ ๊ฐ๋„ ์ €์žฅ ๋ณ€์ˆ˜ // ํ”Œ๋ž˜๊ทธ ๊ด€๋ จ bool isScaleRatioCustomized; // ๋งˆ์šฐ์Šค ํœ ์„ ํ†ตํ•ด ์Šค์ผ€์ผ์ด ๋ณ€๊ฒฝ๋˜์—ˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ์ €์žฅ // ์ง์ ‘ ์ถ”๊ฐ€ํ•œ ๋ฉค๋ฒ„ ํ•จ์ˆ˜ ๋ฆฌ์ŠคํŠธ bool FileRead(CString); // ํŒŒ์ผ parsing์„ ์œ„ํ•œ ์ฒ˜๋ฆฌ void DrawLines(); // ์„ ์„ ๊ทธ๋ฆฌ๋Š” ํ•จ์ˆ˜ void DrawAxes(); // ์ขŒํ‘œ์ถ•์„ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค. // ์žฌ์ •์˜์ž…๋‹ˆ๋‹ค. public: virtual void OnDraw(CDC* pDC); // ์ด ๋ทฐ๋ฅผ ๊ทธ๋ฆฌ๊ธฐ ์œ„ํ•ด ์žฌ์ •์˜๋˜์—ˆ์Šต๋‹ˆ๋‹ค. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); void AddToRecentFileList(LPCTSTR lpszPathName); // ํŒŒ์ผ์„ MRU ๋ชฉ๋ก์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. CMainFrame* GetMainFrm(); // ์ฃผ ์œˆ๋„์šฐ ์ฃผ์†Œ์ฐฝ์˜ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. static size_t round( double d ); // ๋ฐ˜์˜ฌ๋ฆผ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. // ๊ตฌํ˜„์ž…๋‹ˆ๋‹ค. public: virtual ~CMy2DTransView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // ์ƒ์„ฑ๋œ ๋ฉ”์‹œ์ง€ ๋งต ํ•จ์ˆ˜ protected: afx_msg void OnFilePrintPreview(); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); public: afx_msg void OnFileOpen(); // ํŒŒ์ผ์„ ์—ด๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜ ์ฒ˜๋ฆฌ afx_msg void OnFileNew(); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnDirUp(); afx_msg void OnDirDown(); afx_msg void OnDirLeft(); afx_msg void OnDirLup(); afx_msg void OnDirLdown(); afx_msg void OnDirRdown(); afx_msg void OnDirRight(); afx_msg void OnDirRup(); afx_msg void OnRotateLeft(); afx_msg void OnRotateRight(); afx_msg void OnScaleMagnify(); afx_msg void recalcScale(); // ์Šค์ผ€์ผ์„ ์›๋ž˜๋Œ€๋กœ ์„ค์ •ํ•˜๊ณ , ๋‹ค์‹œ ๊ทธ๋ฆฌ๋Š” ํ•จ์ˆ˜ afx_msg void OnScaleShrink(); DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // 2DTransView.cpp์˜ ๋””๋ฒ„๊ทธ ๋ฒ„์ „ inline CMy2DTransDoc* CMy2DTransView::GetDocument() const { return reinterpret_cast<CMy2DTransDoc*>(m_pDocument); } #endif
[ "happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35", "Happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35" ]
[ [ [ 1, 4 ], [ 8, 15 ], [ 17, 18 ], [ 24, 24 ], [ 45, 45 ], [ 47, 53 ], [ 57, 70 ], [ 76, 85 ], [ 92, 98 ] ], [ [ 5, 7 ], [ 16, 16 ], [ 19, 23 ], [ 25, 44 ], [ 46, 46 ], [ 54, 56 ], [ 71, 75 ], [ 86, 91 ] ] ]
252b47310e53a293c3963b70c36d6317a79ce809
e53e3f6fac0340ae0435c8e60d15d763704ef7ec
/WDL/filewrite.h
6f06f9c371ebe3013d769caca64856e5dde557d2
[]
no_license
b-vesco/vfx-wdl
906a69f647938b60387d8966f232a03ce5b87e5f
ee644f752e2174be2fefe43275aec2979f0baaec
refs/heads/master
2020-05-30T21:37:06.356326
2011-01-04T08:54:45
2011-01-04T08:54:45
848,136
2
0
null
null
null
null
UTF-8
C++
false
false
17,147
h
/* WDL - filewrite.h Copyright (C) 2005 and later Cockos Incorporated 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. This file provides the WDL_FileWrite object, which can be used to create/write files. On windows systems it supports writing synchronously, asynchronously, and asynchronously without buffering. On windows systems it supports files larger than 4gb. On non-windows systems it acts as a wrapper for fopen()/etc. */ #ifndef _WDL_FILEWRITE_H_ #define _WDL_FILEWRITE_H_ #include "ptrlist.h" #if defined(_WIN32) && !defined(WDL_NO_WIN32_FILEWRITE) #ifndef WDL_WIN32_NATIVE_WRITE #define WDL_WIN32_NATIVE_WRITE #endif #else #ifdef WDL_WIN32_NATIVE_WRITE #undef WDL_WIN32_NATIVE_WRITE #endif #if !defined(WDL_NO_POSIX_FILEWRITE) #include <sys/fcntl.h> #include <sys/file.h> #include <sys/errno.h> #define WDL_POSIX_NATIVE_WRITE #endif #endif #ifdef _MSC_VER #define WDL_FILEWRITE_POSTYPE __int64 #else #define WDL_FILEWRITE_POSTYPE long long #endif //#define WIN32_ASYNC_NOBUF_WRITE // this doesnt seem to give much perf increase (writethrough with buffering is fine, since ultimately writes get deferred anyway) class WDL_FileWrite { #ifdef WDL_WIN32_NATIVE_WRITE class WDL_FileWrite__WriteEnt { public: WDL_FileWrite__WriteEnt(int sz) { m_last_writepos=0; m_bufused=0; m_bufsz=sz; m_bufptr = (char *)__buf.Resize(sz+4095); int a=((int)(INT_PTR)m_bufptr)&4095; if (a) m_bufptr += 4096-a; memset(&m_ol,0,sizeof(m_ol)); m_ol.hEvent=CreateEvent(NULL,TRUE,TRUE,NULL); } ~WDL_FileWrite__WriteEnt() { CloseHandle(m_ol.hEvent); } WDL_FILEWRITE_POSTYPE m_last_writepos; int m_bufused,m_bufsz; OVERLAPPED m_ol; char *m_bufptr; WDL_TypedBuf<char> __buf; }; #endif #if defined(_WIN32) && !defined(WDL_NO_SUPPORT_UTF8) BOOL HasUTF8(const char *_str) { const unsigned char *str = (const unsigned char *)_str; if (!str) return FALSE; while (*str) { unsigned char c = *str; if (c >= 0xC2) { if (c <= 0xDF && str[1] >=0x80 && str[1] <= 0xBF) return TRUE; else if (c <= 0xEF && str[1] >=0x80 && str[1] <= 0xBF && str[2] >=0x80 && str[2] <= 0xBF) return TRUE; else if (c <= 0xF4 && str[1] >=0x80 && str[1] <= 0xBF && str[2] >=0x80 && str[2] <= 0xBF) return TRUE; } str++; } return FALSE; } #endif public: WDL_FileWrite(const char *filename, int allow_async=1, int bufsize=8192, int minbufs=16, int maxbufs=16, bool wantAppendTo=false, bool noFileLocking=false) // async==2 is unbuffered { m_file_position=0; m_file_max_position=0; if(!filename) { #ifdef WDL_WIN32_NATIVE_WRITE m_fh = INVALID_HANDLE_VALUE; m_async = 0; #elif defined(WDL_POSIX_NATIVE_WRITE) m_filedes_locked=false; m_filedes=-1; m_bufspace_used=0; #else m_fp = NULL; #endif return; } #ifdef WDL_WIN32_NATIVE_WRITE bool isNT = (GetVersion()<0x80000000); m_async = allow_async && isNT; #ifdef WIN32_ASYNC_NOBUF_WRITE bufsize = (bufsize+4095)&~4095; if (bufsize<4096) bufsize=4096; #endif int rwflag = GENERIC_WRITE; int createFlag= wantAppendTo?OPEN_ALWAYS:CREATE_ALWAYS; int shareFlag = noFileLocking ? (FILE_SHARE_READ|FILE_SHARE_WRITE) : FILE_SHARE_READ; int flag = FILE_ATTRIBUTE_NORMAL; if (m_async) { rwflag |= GENERIC_READ; #ifdef WIN32_ASYNC_NOBUF_WRITE flag |= FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH; #else flag |= FILE_FLAG_OVERLAPPED|(allow_async>1 ? FILE_FLAG_WRITE_THROUGH: 0); #endif } { #ifndef WDL_NO_SUPPORT_UTF8 m_fh=INVALID_HANDLE_VALUE; if (isNT && HasUTF8(filename)) { int szreq=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,filename,-1,NULL,0); if (szreq > 1000) { WDL_TypedBuf<WCHAR> wfilename; wfilename.Resize(szreq+10); if (MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,filename,-1,wfilename.Get(),wfilename.GetSize())) m_fh = CreateFileW(wfilename.Get(),rwflag,shareFlag,NULL,createFlag,flag,NULL); } else { WCHAR wfilename[1024]; if (MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,filename,-1,wfilename,1024)) m_fh = CreateFileW(wfilename,rwflag,shareFlag,NULL,createFlag,flag,NULL); } } if (m_fh == INVALID_HANDLE_VALUE) #endif m_fh = CreateFileA(filename,rwflag,shareFlag,NULL,createFlag,flag,NULL); } if (m_async && m_fh != INVALID_HANDLE_VALUE) { m_async_bufsize=bufsize; m_async_maxbufs=maxbufs; m_async_minbufs=minbufs; int x; for (x = 0; x < m_async_minbufs; x ++) { WDL_FileWrite__WriteEnt *t=new WDL_FileWrite__WriteEnt(m_async_bufsize); m_empties.Add(t); } } if (m_fh != INVALID_HANDLE_VALUE && wantAppendTo) SetPosition(GetSize()); #elif defined(WDL_POSIX_NATIVE_WRITE) m_bufspace_used=0; m_filedes_locked=false; m_filedes=open(filename,O_WRONLY|O_CREAT,0644); if (m_filedes>=0) { if (!noFileLocking) { int preverr; if ((preverr=flock(m_filedes,LOCK_EX|LOCK_NB))<0 && errno == EWOULDBLOCK) // try to get exclusive, at least for a moment { // FAILED exclusive locking close(m_filedes); m_filedes=-1; } else { if (flock(m_filedes,LOCK_SH|LOCK_NB)>=0 || // return to shared lock preverr>=0) m_filedes_locked=true; } } if (m_filedes>=0) { if (!wantAppendTo) ftruncate(m_filedes,0); else { struct stat st; if (!fstat(m_filedes,&st)) SetPosition(st.st_size); } } #ifdef __APPLE__ if (m_filedes >= 0 && allow_async>1) fcntl(m_filedes,F_NOCACHE,1); #endif } if (minbufs * bufsize >= 16384) m_bufspace.Resize((minbufs*bufsize+4095)&~4095); #else m_fp=fopen(filename,wantAppendTo ? "a+b" : "wb"); if (wantAppendTo && m_fp) fseek(m_fp,0,SEEK_END); #endif } ~WDL_FileWrite() { #ifdef WDL_WIN32_NATIVE_WRITE // todo, async close stuff? if (m_fh != INVALID_HANDLE_VALUE && m_async) { SyncOutput(true); } m_empties.Empty(true); m_pending.Empty(true); if (m_fh != INVALID_HANDLE_VALUE) CloseHandle(m_fh); m_fh=INVALID_HANDLE_VALUE; #elif defined(WDL_POSIX_NATIVE_WRITE) if (m_filedes >= 0) { if (m_bufspace.GetSize() > 0 && m_bufspace_used>0) { int v=pwrite(m_filedes,m_bufspace.Get(),m_bufspace_used,m_file_position); if (v>0) m_file_position+=v; if (m_file_position > m_file_max_position) m_file_max_position=m_file_position; m_bufspace_used=0; } if (m_filedes_locked) flock(m_filedes,LOCK_UN); close(m_filedes); } m_filedes=-1; #else if (m_fp) fclose(m_fp); m_fp=0; #endif } bool IsOpen() { #ifdef WDL_WIN32_NATIVE_WRITE return (m_fh != INVALID_HANDLE_VALUE); #elif defined(WDL_POSIX_NATIVE_WRITE) return m_filedes >= 0; #else return m_fp != NULL; #endif } int Write(const void *buf, int len) { #ifdef WDL_WIN32_NATIVE_WRITE if (m_fh == INVALID_HANDLE_VALUE) return 0; if (m_async) { char *pbuf=(char *)buf; while (len > 0) { if (!m_empties.GetSize()) { WDL_FileWrite__WriteEnt *ent=m_pending.Get(0); DWORD s=0; if (ent) { bool wasabort=false; if (GetOverlappedResult(m_fh,&ent->m_ol,&s,FALSE)|| (wasabort=(GetLastError()==ERROR_OPERATION_ABORTED))) { m_pending.Delete(0); if (wasabort) { if (!RunAsyncWrite(ent,false)) m_empties.Add(ent); } else { m_empties.Add(ent); ent->m_bufused=0; } } } } WDL_FileWrite__WriteEnt *ent=m_empties.Get(0); if (!ent) { if (m_pending.GetSize()>=m_async_maxbufs) { SyncOutput(false); } if (!(ent=m_empties.Get(0))) m_empties.Add(ent = new WDL_FileWrite__WriteEnt(m_async_bufsize)); // new buffer } int ml=ent->m_bufsz-ent->m_bufused; if (ml>len) ml=len; memcpy(ent->m_bufptr+ent->m_bufused,pbuf,ml); ent->m_bufused+=ml; len-=ml; pbuf+=ml; if (ent->m_bufused >= ent->m_bufsz) { if (RunAsyncWrite(ent,true)) m_empties.Delete(0); // if queued remove from list } } return pbuf - (char *)buf; } else { DWORD dw=0; WriteFile(m_fh,buf,len,&dw,NULL); m_file_position+=dw; if (m_file_position>m_file_max_position) m_file_max_position=m_file_position; return dw; } #elif defined(WDL_POSIX_NATIVE_WRITE) if (m_bufspace.GetSize()>0) { char *rdptr = (char *)buf; int rdlen = len; while (rdlen>0) { int amt = m_bufspace.GetSize() - m_bufspace_used; if (amt>0) { if (amt>rdlen) amt=rdlen; memcpy((char *)m_bufspace.Get()+m_bufspace_used,rdptr,amt); m_bufspace_used += amt; rdptr+=amt; rdlen -= amt; if (m_file_position+m_bufspace_used > m_file_max_position) m_file_max_position=m_file_position + m_bufspace_used; } if (m_bufspace_used >= m_bufspace.GetSize()) { int v=pwrite(m_filedes,m_bufspace.Get(),m_bufspace_used,m_file_position); if (v>0) m_file_position+=v; m_bufspace_used=0; } } return len; } else { int v=pwrite(m_filedes,buf,len,m_file_position); if (v>0) m_file_position+=v; if (m_file_position > m_file_max_position) m_file_max_position=m_file_position; return v; } #else return fwrite(buf,1,len,m_fp); #endif } WDL_FILEWRITE_POSTYPE GetSize() { #ifdef WDL_WIN32_NATIVE_WRITE if (m_fh == INVALID_HANDLE_VALUE) return 0; DWORD h=0; DWORD l=GetFileSize(m_fh,&h); WDL_FILEWRITE_POSTYPE tmp=(((WDL_FILEWRITE_POSTYPE)h)<<32)|l; WDL_FILEWRITE_POSTYPE tmp2=GetPosition(); if (tmp<m_file_max_position) return m_file_max_position; if (tmp<tmp2) return tmp2; return tmp; #elif defined(WDL_POSIX_NATIVE_WRITE) if (m_filedes < 0) return -1; return m_file_max_position; #else if (!m_fp) return -1; int opos=ftell(m_fp); fseek(m_fp,0,SEEK_END); int a=ftell(m_fp); fseek(m_fp,opos,SEEK_SET); return a; #endif } WDL_FILEWRITE_POSTYPE GetPosition() { #ifdef WDL_WIN32_NATIVE_WRITE if (m_fh == INVALID_HANDLE_VALUE) return -1; WDL_FILEWRITE_POSTYPE pos=m_file_position; if (m_async) { WDL_FileWrite__WriteEnt *ent=m_empties.Get(0); if (ent) pos+=ent->m_bufused; } return pos; #elif defined(WDL_POSIX_NATIVE_WRITE) if (m_filedes < 0) return -1; return m_file_position + m_bufspace_used; #else if (!m_fp) return -1; return ftell(m_fp); #endif } #ifdef WDL_WIN32_NATIVE_WRITE bool RunAsyncWrite(WDL_FileWrite__WriteEnt *ent, bool updatePosition) // returns true if ent is added to pending { if (ent && ent->m_bufused>0) { if (updatePosition) { ent->m_last_writepos = m_file_position; m_file_position += ent->m_bufused; if (m_file_position>m_file_max_position) m_file_max_position=m_file_position; } #ifdef WIN32_ASYNC_NOBUF_WRITE if (ent->m_bufused&4095) { int offs=(ent->m_bufused&4095); char tmp[4096]; memset(tmp,0,4096); *(WDL_FILEWRITE_POSTYPE *)&ent->m_ol.Offset = ent->m_last_writepos + ent->m_bufused - offs; ResetEvent(ent->m_ol.hEvent); DWORD dw=0; if (!ReadFile(m_fh,tmp,4096,&dw,&ent->m_ol)) { if (GetLastError() == ERROR_IO_PENDING) WaitForSingleObject(ent->m_ol.hEvent,INFINITE); } memcpy(ent->m_bufptr+ent->m_bufused,tmp+offs,4096-offs); ent->m_bufused += 4096-offs; } #endif DWORD d=0; *(WDL_FILEWRITE_POSTYPE *)&ent->m_ol.Offset = ent->m_last_writepos; ResetEvent(ent->m_ol.hEvent); if (!WriteFile(m_fh,ent->m_bufptr,ent->m_bufused,&d,&ent->m_ol)) { if (GetLastError()==ERROR_IO_PENDING) { m_pending.Add(ent); return true; } } ent->m_bufused=0; } return false; } void SyncOutput(bool syncall) { if (syncall) { if (RunAsyncWrite(m_empties.Get(0),true)) m_empties.Delete(0); } for (;;) { WDL_FileWrite__WriteEnt *ent=m_pending.Get(0); if (!ent) break; DWORD s=0; m_pending.Delete(0); if (!GetOverlappedResult(m_fh,&ent->m_ol,&s,TRUE) && GetLastError()==ERROR_OPERATION_ABORTED) { // rewrite this one if (!RunAsyncWrite(ent,false)) m_empties.Add(ent); } else { m_empties.Add(ent); ent->m_bufused=0; if (!syncall) break; } } } #endif bool SetPosition(WDL_FILEWRITE_POSTYPE pos) // returns 0 on success { #ifdef WDL_WIN32_NATIVE_WRITE if (m_fh == INVALID_HANDLE_VALUE) return true; if (m_async) { SyncOutput(true); m_file_position=pos; if (m_file_position>m_file_max_position) m_file_max_position=m_file_position; #ifdef WIN32_ASYNC_NOBUF_WRITE if (m_file_position&4095) { WDL_FileWrite__WriteEnt *ent=m_empties.Get(0); if (ent) { int psz=(int) (m_file_position&4095); m_file_position -= psz; *(WDL_FILEWRITE_POSTYPE *)&ent->m_ol.Offset = m_file_position; ResetEvent(ent->m_ol.hEvent); DWORD dwo=0; if (!ReadFile(m_fh,ent->m_bufptr,4096,&dwo,&ent->m_ol)) { if (GetLastError() == ERROR_IO_PENDING) WaitForSingleObject(ent->m_ol.hEvent,INFINITE); } ent->m_bufused=(int)psz; } } #endif return false; } m_file_position=pos; if (m_file_position>m_file_max_position) m_file_max_position=m_file_position; LONG high=(LONG) (m_file_position>>32); return SetFilePointer(m_fh,(LONG)(m_file_position&0xFFFFFFFFi64),&high,FILE_BEGIN)==0xFFFFFFFF && GetLastError() != NO_ERROR; #elif defined(WDL_POSIX_NATIVE_WRITE) if (m_filedes < 0) return true; if (m_bufspace.GetSize() > 0 && m_bufspace_used>0) { int v=pwrite(m_filedes,m_bufspace.Get(),m_bufspace_used,m_file_position); if (v>0) m_file_position+=v; if (m_file_position > m_file_max_position) m_file_max_position=m_file_position; m_bufspace_used=0; } m_file_position = pos; // seek! if (m_file_position>m_file_max_position) m_file_max_position=m_file_position; return false; #else if (!m_fp) return true; return !!fseek(m_fp,pos,SEEK_SET); #endif } WDL_FILEWRITE_POSTYPE m_file_position, m_file_max_position; #ifdef WDL_WIN32_NATIVE_WRITE HANDLE GetHandle() { return m_fh; } HANDLE m_fh; bool m_async; int m_async_bufsize, m_async_minbufs, m_async_maxbufs; WDL_PtrList<WDL_FileWrite__WriteEnt> m_empties; WDL_PtrList<WDL_FileWrite__WriteEnt> m_pending; #elif defined(WDL_POSIX_NATIVE_WRITE) int GetHandle() { return m_filedes; } WDL_HeapBuf m_bufspace; int m_bufspace_used; int m_filedes; bool m_filedes_locked; #else int GetHandle() { return fileno(m_fp); } FILE *m_fp; #endif } WDL_FIXALIGN; #endif
[ [ [ 1, 639 ] ] ]
0b9e14ea5c76987e646b2582228d174f5b0f434f
826479e30cfe9f7b9a1b7262211423d8208ffb68
/RayTracer/CImplicit.h
116893739533de3c5af546bdd179c702b96e0255
[]
no_license
whztt07/real-time-raytracer
5d1961c545e4703a3811fd7eabdff96017030abd
f54a75aed811b8ab6a509c70f879739896428fff
refs/heads/master
2021-01-17T05:33:13.305151
2008-12-19T20:17:30
2008-12-19T20:17:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,108
h
// Author : Jean-Rene Bedard ([email protected]) #pragma once #include "CObjectRT.h" class CImplicit : public CObjectRT { public: CImplicit(); virtual ~CImplicit(); int refinementSteps; float tStep; CVector centre; float radius; float inline fieldEquation(CVector *v); virtual void frameCalc(CCamera *c); virtual float inline IntersectGeneral(CRay *r); virtual float inline intersectFixed(CRay *r); virtual inline bool intersects(CRay *r); virtual inline bool intersects(CPlaneIntersection *p); virtual CVector inline Normal(CVector *poi); private: float rSquared, invRadius, cTerm; CVector origin; }; float inline CImplicit::fieldEquation(CVector *v) { const CVector nv = *v * 0.1f; const float a = (2.0f * nv.x * nv.x + nv.z * nv.z + nv.y * nv.y - 1.0f); const float zCube = nv.y * nv.y * nv.y; return a * a * a - 0.1f * nv.x * nv.x * zCube - nv.z * nv.z * zCube; /*CVector nv = *v * 1.0f; float x = nv.x, y = nv.y, z = nv.z; float d = (x * y * z) * 0.05f; return d * d - 10.0f;*/ } // this is currently done with less precision than the primary CRay intersection float inline CImplicit::IntersectGeneral(CRay *r) { float b = r->d.x * (r->o.x - centre.x) + r->d.y * (r->o.y - centre.y) + r->d.z * (r->o.z - centre.z); float c = (r->o.x - centre.x) * (r->o.x - centre.x) + (r->o.y - centre.y) * (r->o.y - centre.y) + (r->o.z - centre.z) * (r->o.z - centre.z) - rSquared; const float d = b * b - c; if (d < 0.0f) return -1.0f; const float sqrtd = sqrtf(d); float t1 = -b - sqrtd, t2 = -b + sqrtd; if (t2 < 0.0f) return -1.0f; if (t1 < 0.0f) t1 = 0.0f; float t = t1; float f = fieldEquation(&(r->o + r->d * t)); bool intersected = false; // iterate through volume looking for intersections while (t < t2) { t += tStep; if (f * fieldEquation(&(r->o + r->d * t)) < 0.0f) { intersected = true; break; } } if (!intersected) return -1.0f; float start = t - tStep, end = t; for (int i = 0; i < refinementSteps; i++) // do 1/4 number of refinement steps { float midpoint = (start + end) * 0.5f; CVector middle = r->o + r->d * midpoint; if (f * fieldEquation(&middle) < 0.0f) end = midpoint; else start = midpoint; } return (start + end) * 0.5f - 0.08f; } float inline CImplicit::intersectFixed(CRay *r) { float b = r->d * origin; float d = b * b - cTerm; if (d < 0.0f) return -1.0f; float sqrtd = sqrtf(d); float t1 = -b - sqrtd, t2 = -b + sqrtd; //if (t2 < 0.0f) return -1.0f; //if (t1 < 0.0f) t1 = 0.01f; float t = t1; float f = fieldEquation(&(r->o + r->d * t)); bool intersected = false; // iterate through volume looking for intersections while (t < t2) { t += tStep; if (f * fieldEquation(&(r->o + r->d * t)) < 0.0f) { intersected = true; break; } } if (!intersected) return -1.0f; float start = t - tStep, end = t; for (int i = 0; i < refinementSteps; i++) { float midpoint = (start + end) * 0.5f; CVector middle = r->o + r->d * midpoint; if (f * fieldEquation(&middle) < 0.0f) end = midpoint; else start = midpoint; } return (start + end) * 0.5f - 0.08f; } bool inline CImplicit::intersects(CRay *r) { float b = r->d.x * (r->o.x - centre.x) + r->d.y * (r->o.y - centre.y) + r->d.z * (r->o.z - centre.z); float c = (r->o.x - centre.x) * (r->o.x - centre.x) + (r->o.y - centre.y) * (r->o.y - centre.y) + (r->o.z - centre.z) * (r->o.z - centre.z) - rSquared; float d = b * b - c; if (d < 0.0f) return false; return true; } bool inline CImplicit::intersects(CPlaneIntersection *p) { if (fabsf(p->n * centre - p->d) > radius) return false; return true; } CVector inline CImplicit::Normal(CVector *poi) { CVector v = *poi; float e0 = fieldEquation(poi); float e1x = fieldEquation(&(v + CVector(0.01f,0.0f,0.0f))); float e1y = fieldEquation(&(v + CVector(0.0f,0.01f,0.0f))); float e1z = fieldEquation(&(v + CVector(0.0f,0.0f,0.01f))); CVector g = CVector(e1x - e0,e1y - e0,e1z - e0) * 100.0f; return g | 1.0f; }
[ [ [ 1, 160 ] ] ]