content
stringlengths 10
4.9M
|
---|
// TabStrip.cpp: Superclasses SysTabControl32.
#include "stdafx.h"
#include "TabStrip.h"
#include "ClassFactory.h"
#pragma comment(lib, "comctl32.lib")
// initialize complex constants
FONTDESC TabStrip::Properties::FontProperty::defaultFont = {
sizeof(FONTDESC),
OLESTR("MS Sans Serif"),
120000,
FW_NORMAL,
ANSI_CHARSET,
FALSE,
FALSE,
FALSE
};
TabStrip::TabStrip()
{
pSimpleFrameSite = NULL;
properties.font.InitializePropertyWatcher(this, DISPID_TABSTRIPCTL_FONT);
properties.mouseIcon.InitializePropertyWatcher(this, DISPID_TABSTRIPCTL_MOUSEICON);
// always create a window, even if the container supports windowless controls
m_bWindowOnly = TRUE;
// initialize
tabUnderMouse = -1;
pToolTipBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (MAX_PATH + 1) * sizeof(WCHAR));
// Microsoft couldn't make it more difficult to detect whether we should use themes or not...
flags.usingThemes = FALSE;
if(CTheme::IsThemingSupported() && RunTimeHelper::IsCommCtrl6()) {
HMODULE hThemeDLL = LoadLibrary(TEXT("uxtheme.dll"));
if(hThemeDLL) {
typedef BOOL WINAPI IsAppThemedFn();
IsAppThemedFn* pfnIsAppThemed = static_cast<IsAppThemedFn*>(GetProcAddress(hThemeDLL, "IsAppThemed"));
if(pfnIsAppThemed()) {
flags.usingThemes = TRUE;
}
FreeLibrary(hThemeDLL);
}
}
if(RunTimeHelper::IsVista()) {
CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pWICImagingFactory));
ATLASSUME(pWICImagingFactory);
}
}
TabStrip::~TabStrip()
{
if(pToolTipBuffer) {
HeapFree(GetProcessHeap(), 0, pToolTipBuffer);
}
}
//////////////////////////////////////////////////////////////////////
// implementation of ISupportsErrorInfo
STDMETHODIMP TabStrip::InterfaceSupportsErrorInfo(REFIID interfaceToCheck)
{
if(InlineIsEqualGUID(IID_ITabStrip, interfaceToCheck)) {
return S_OK;
}
return S_FALSE;
}
// implementation of ISupportsErrorInfo
//////////////////////////////////////////////////////////////////////
STDMETHODIMP TabStrip::GetSizeMax(ULARGE_INTEGER* pSize)
{
ATLASSERT_POINTER(pSize, ULARGE_INTEGER);
if(!pSize) {
return E_POINTER;
}
pSize->LowPart = 0;
pSize->HighPart = 0;
pSize->QuadPart = sizeof(LONG/*signature*/) + sizeof(LONG/*version*/) + sizeof(DWORD/*atlVersion*/) + sizeof(m_sizeExtent);
// we've 21 VT_I4 properties...
pSize->QuadPart += 21 * (sizeof(VARTYPE) + sizeof(LONG));
// ...and 16 VT_BOOL properties...
pSize->QuadPart += 16 * (sizeof(VARTYPE) + sizeof(VARIANT_BOOL));
// ...and 2 VT_DISPATCH properties
pSize->QuadPart += 2 * (sizeof(VARTYPE) + sizeof(CLSID));
// we've to query each object for its size
CComPtr<IPersistStreamInit> pStreamInit = NULL;
if(properties.font.pFontDisp) {
if(FAILED(properties.font.pFontDisp->QueryInterface(IID_IPersistStream, reinterpret_cast<LPVOID*>(&pStreamInit)))) {
properties.font.pFontDisp->QueryInterface(IID_IPersistStreamInit, reinterpret_cast<LPVOID*>(&pStreamInit));
}
}
if(pStreamInit) {
ULARGE_INTEGER tmp = {0};
pStreamInit->GetSizeMax(&tmp);
pSize->QuadPart += tmp.QuadPart;
}
pStreamInit = NULL;
if(properties.mouseIcon.pPictureDisp) {
if(FAILED(properties.mouseIcon.pPictureDisp->QueryInterface(IID_IPersistStream, reinterpret_cast<LPVOID*>(&pStreamInit)))) {
properties.mouseIcon.pPictureDisp->QueryInterface(IID_IPersistStreamInit, reinterpret_cast<LPVOID*>(&pStreamInit));
}
}
if(pStreamInit) {
ULARGE_INTEGER tmp = {0};
pStreamInit->GetSizeMax(&tmp);
pSize->QuadPart += tmp.QuadPart;
}
return S_OK;
}
STDMETHODIMP TabStrip::Load(LPSTREAM pStream)
{
ATLASSUME(pStream);
if(!pStream) {
return E_POINTER;
}
HRESULT hr = S_OK;
LONG signature = 0;
LONG version = 0;
if(FAILED(hr = pStream->Read(&signature, sizeof(signature), NULL))) {
return hr;
}
if(signature != 0x0A0A0A0A/*4x AppID*/) {
// might be a legacy stream, that starts with the ATL version
if(signature == 0x0700 || signature == 0x0710 || signature == 0x0800 || signature == 0x0900) {
version = 0x0099;
} else {
return E_FAIL;
}
}
//LONG version = 0;
if(version != 0x0099) {
if(FAILED(hr = pStream->Read(&version, sizeof(version), NULL))) {
return hr;
}
if(version > 0x0102) {
return E_FAIL;
}
}
DWORD atlVersion;
if(version == 0x0099) {
atlVersion = 0x0900;
} else {
if(FAILED(hr = pStream->Read(&atlVersion, sizeof(atlVersion), NULL))) {
return hr;
}
}
if(atlVersion > _ATL_VER) {
return E_FAIL;
}
if(version != 0x0100) {
if(FAILED(hr = pStream->Read(&m_sizeExtent, sizeof(m_sizeExtent), NULL))) {
return hr;
}
}
typedef HRESULT ReadVariantFromStreamFn(__in LPSTREAM pStream, VARTYPE expectedVarType, __inout LPVARIANT pVariant);
ReadVariantFromStreamFn* pfnReadVariantFromStream = NULL;
if(version == 0x0100) {
pfnReadVariantFromStream = ReadVariantFromStream_Legacy;
} else {
pfnReadVariantFromStream = ReadVariantFromStream;
}
VARIANT propertyValue;
VariantInit(&propertyValue);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL allowDragDrop = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
AppearanceConstants appearance = static_cast<AppearanceConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
BorderStyleConstants borderStyle = static_cast<BorderStyleConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL closeableTabs = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
DisabledEventsConstants disabledEvents = static_cast<DisabledEventsConstants>(propertyValue.lVal);
/*if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL dontRedraw = propertyValue.boolVal;*/
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
LONG dragActivateTime = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
LONG dragScrollTimeBase = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL enabled = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_XSIZE_PIXELS fixedTabWidth = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL focusOnButtonDown = propertyValue.boolVal;
VARTYPE vt;
if(FAILED(hr = pStream->Read(&vt, sizeof(VARTYPE), NULL)) || (vt != VT_DISPATCH)) {
return hr;
}
CComPtr<IFontDisp> pFont = NULL;
if(FAILED(hr = OleLoadFromStream(pStream, IID_IDispatch, reinterpret_cast<LPVOID*>(&pFont)))) {
if(hr != REGDB_E_CLASSNOTREG) {
return S_OK;
}
}
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_XSIZE_PIXELS horizontalPadding = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL hotTracking = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
LONG hoverTime = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_COLOR insertMarkColor = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_XSIZE_PIXELS minTabWidth = propertyValue.lVal;
if(FAILED(hr = pStream->Read(&vt, sizeof(VARTYPE), NULL)) || (vt != VT_DISPATCH)) {
return hr;
}
CComPtr<IPictureDisp> pMouseIcon = NULL;
if(FAILED(hr = OleLoadFromStream(pStream, IID_IDispatch, reinterpret_cast<LPVOID*>(&pMouseIcon)))) {
if(hr != REGDB_E_CLASSNOTREG) {
return S_OK;
}
}
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
MousePointerConstants mousePointer = static_cast<MousePointerConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL multiRow = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL multiSelect = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL ownerDrawn = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL processContextMenuKeys = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL raggedTabRows = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
RegisterForOLEDragDropConstants registerForOLEDragDrop = static_cast<RegisterForOLEDragDropConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
RightToLeftConstants rightToLeft = static_cast<RightToLeftConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL scrollToOpposite = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL showButtonSeparators = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL showToolTips = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
StyleConstants style = static_cast<StyleConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL supportOLEDragImages = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
TabBoundingBoxDefinitionConstants tabBoundingBoxDefinition = static_cast<TabBoundingBoxDefinitionConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
TabCaptionAlignmentConstants tabCaptionAlignment = static_cast<TabCaptionAlignmentConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_YSIZE_PIXELS tabHeight = propertyValue.lVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
TabPlacementConstants tabPlacement = static_cast<TabPlacementConstants>(propertyValue.lVal);
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL useFixedTabWidth = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_BOOL, &propertyValue))) {
return hr;
}
VARIANT_BOOL useSystemFont = propertyValue.boolVal;
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
OLE_YSIZE_PIXELS verticalPadding = propertyValue.lVal;
CloseableTabsModeConstants closeableTabsMode = ctmDisplayOnAllTabs;
OLEDragImageStyleConstants oleDragImageStyle = odistClassic;
if(version >= 0x0101) {
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
oleDragImageStyle = static_cast<OLEDragImageStyleConstants>(propertyValue.lVal);
if(version >= 0x0102) {
if(FAILED(hr = pfnReadVariantFromStream(pStream, VT_I4, &propertyValue))) {
return hr;
}
closeableTabsMode = static_cast<CloseableTabsModeConstants>(propertyValue.lVal);
}
}
hr = put_AllowDragDrop(allowDragDrop);
if(FAILED(hr)) {
return hr;
}
hr = put_Appearance(appearance);
if(FAILED(hr)) {
return hr;
}
hr = put_BorderStyle(borderStyle);
if(FAILED(hr)) {
return hr;
}
hr = put_CloseableTabs(closeableTabs);
if(FAILED(hr)) {
return hr;
}
hr = put_CloseableTabsMode(closeableTabsMode);
if(FAILED(hr)) {
return hr;
}
hr = put_DisabledEvents(disabledEvents);
if(FAILED(hr)) {
return hr;
}
/*hr = put_DontRedraw(dontRedraw);
if(FAILED(hr)) {
return hr;
}*/
hr = put_DragActivateTime(dragActivateTime);
if(FAILED(hr)) {
return hr;
}
hr = put_DragScrollTimeBase(dragScrollTimeBase);
if(FAILED(hr)) {
return hr;
}
hr = put_Enabled(enabled);
if(FAILED(hr)) {
return hr;
}
hr = put_FixedTabWidth(fixedTabWidth);
if(FAILED(hr)) {
return hr;
}
hr = put_FocusOnButtonDown(focusOnButtonDown);
if(FAILED(hr)) {
return hr;
}
hr = put_Font(pFont);
if(FAILED(hr)) {
return hr;
}
hr = put_HorizontalPadding(horizontalPadding);
if(FAILED(hr)) {
return hr;
}
hr = put_HotTracking(hotTracking);
if(FAILED(hr)) {
return hr;
}
hr = put_HoverTime(hoverTime);
if(FAILED(hr)) {
return hr;
}
hr = put_InsertMarkColor(insertMarkColor);
if(FAILED(hr)) {
return hr;
}
hr = put_MinTabWidth(minTabWidth);
if(FAILED(hr)) {
return hr;
}
hr = put_MouseIcon(pMouseIcon);
if(FAILED(hr)) {
return hr;
}
hr = put_MousePointer(mousePointer);
if(FAILED(hr)) {
return hr;
}
hr = put_MultiRow(multiRow);
if(FAILED(hr)) {
return hr;
}
hr = put_MultiSelect(multiSelect);
if(FAILED(hr)) {
return hr;
}
hr = put_OLEDragImageStyle(oleDragImageStyle);
if(FAILED(hr)) {
return hr;
}
hr = put_OwnerDrawn(ownerDrawn);
if(FAILED(hr)) {
return hr;
}
hr = put_ProcessContextMenuKeys(processContextMenuKeys);
if(FAILED(hr)) {
return hr;
}
hr = put_RaggedTabRows(raggedTabRows);
if(FAILED(hr)) {
return hr;
}
hr = put_RegisterForOLEDragDrop(registerForOLEDragDrop);
if(FAILED(hr)) {
return hr;
}
hr = put_RightToLeft(rightToLeft);
if(FAILED(hr)) {
return hr;
}
hr = put_ScrollToOpposite(scrollToOpposite);
if(FAILED(hr)) {
return hr;
}
hr = put_ShowButtonSeparators(showButtonSeparators);
if(FAILED(hr)) {
return hr;
}
hr = put_ShowToolTips(showToolTips);
if(FAILED(hr)) {
return hr;
}
hr = put_Style(style);
if(FAILED(hr)) {
return hr;
}
hr = put_SupportOLEDragImages(supportOLEDragImages);
if(FAILED(hr)) {
return hr;
}
hr = put_TabBoundingBoxDefinition(tabBoundingBoxDefinition);
if(FAILED(hr)) {
return hr;
}
hr = put_TabCaptionAlignment(tabCaptionAlignment);
if(FAILED(hr)) {
return hr;
}
hr = put_TabHeight(tabHeight);
if(FAILED(hr)) {
return hr;
}
hr = put_TabPlacement(tabPlacement);
if(FAILED(hr)) {
return hr;
}
hr = put_UseFixedTabWidth(useFixedTabWidth);
if(FAILED(hr)) {
return hr;
}
hr = put_UseSystemFont(useSystemFont);
if(FAILED(hr)) {
return hr;
}
hr = put_VerticalPadding(verticalPadding);
if(FAILED(hr)) {
return hr;
}
SetDirty(FALSE);
return S_OK;
}
STDMETHODIMP TabStrip::Save(LPSTREAM pStream, BOOL clearDirtyFlag)
{
ATLASSUME(pStream);
if(!pStream) {
return E_POINTER;
}
HRESULT hr = S_OK;
LONG signature = 0x0A0A0A0A/*4x AppID*/;
if(FAILED(hr = pStream->Write(&signature, sizeof(signature), NULL))) {
return hr;
}
LONG version = 0x0102;
if(FAILED(hr = pStream->Write(&version, sizeof(version), NULL))) {
return hr;
}
DWORD atlVersion = _ATL_VER;
if(FAILED(hr = pStream->Write(&atlVersion, sizeof(atlVersion), NULL))) {
return hr;
}
if(FAILED(hr = pStream->Write(&m_sizeExtent, sizeof(m_sizeExtent), NULL))) {
return hr;
}
VARIANT propertyValue;
VariantInit(&propertyValue);
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.allowDragDrop);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.appearance;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.borderStyle;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.closeableTabs);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.disabledEvents;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
/*propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.dontRedraw);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;*/
propertyValue.lVal = properties.dragActivateTime;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.dragScrollTimeBase;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.enabled);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.fixedTabWidth;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.focusOnButtonDown);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
CComPtr<IPersistStream> pPersistStream = NULL;
if(properties.font.pFontDisp) {
if(FAILED(hr = properties.font.pFontDisp->QueryInterface(IID_IPersistStream, reinterpret_cast<LPVOID*>(&pPersistStream)))) {
return hr;
}
}
// store some marker
VARTYPE vt = VT_DISPATCH;
if(FAILED(hr = pStream->Write(&vt, sizeof(VARTYPE), NULL))) {
return hr;
}
if(pPersistStream) {
if(FAILED(hr = OleSaveToStream(pPersistStream, pStream))) {
return hr;
}
} else {
if(FAILED(hr = WriteClassStm(pStream, CLSID_NULL))) {
return hr;
}
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.horizontalPadding;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.hotTracking);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.hoverTime;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.insertMarkColor;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.minTabWidth;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
pPersistStream = NULL;
if(properties.mouseIcon.pPictureDisp) {
if(FAILED(hr = properties.mouseIcon.pPictureDisp->QueryInterface(IID_IPersistStream, reinterpret_cast<LPVOID*>(&pPersistStream)))) {
return hr;
}
}
// store some marker
vt = VT_DISPATCH;
if(FAILED(hr = pStream->Write(&vt, sizeof(VARTYPE), NULL))) {
return hr;
}
if(pPersistStream) {
if(FAILED(hr = OleSaveToStream(pPersistStream, pStream))) {
return hr;
}
} else {
if(FAILED(hr = WriteClassStm(pStream, CLSID_NULL))) {
return hr;
}
}
propertyValue.lVal = properties.mousePointer;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.multiRow);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.multiSelect);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.ownerDrawn);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.processContextMenuKeys);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.raggedTabRows);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.registerForOLEDragDrop;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.rightToLeft;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.scrollToOpposite);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.showButtonSeparators);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.showToolTips);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.style;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.supportOLEDragImages);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.tabBoundingBoxDefinition;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.tabCaptionAlignment;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.tabHeight;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.lVal = properties.tabPlacement;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_BOOL;
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.useFixedTabWidth);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.boolVal = BOOL2VARIANTBOOL(properties.useSystemFont);
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
propertyValue.vt = VT_I4;
propertyValue.lVal = properties.verticalPadding;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
// version 0x0101 starts here
propertyValue.lVal = properties.oleDragImageStyle;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
// version 0x0102 starts here
propertyValue.lVal = properties.closeableTabsMode;
if(FAILED(hr = WriteVariantToStream(pStream, &propertyValue))) {
return hr;
}
if(clearDirtyFlag) {
SetDirty(FALSE);
}
return S_OK;
}
HWND TabStrip::Create(HWND hWndParent, ATL::_U_RECT rect/* = NULL*/, LPCTSTR szWindowName/* = NULL*/, DWORD dwStyle/* = 0*/, DWORD dwExStyle/* = 0*/, ATL::_U_MENUorID MenuOrID/* = 0U*/, LPVOID lpCreateParam/* = NULL*/)
{
INITCOMMONCONTROLSEX data = {0};
data.dwSize = sizeof(data);
data.dwICC = ICC_TAB_CLASSES;
InitCommonControlsEx(&data);
dwStyle = GetStyleBits();
dwExStyle = GetExStyleBits();
return CComControl<TabStrip>::Create(hWndParent, rect, szWindowName, dwStyle, dwExStyle, MenuOrID, lpCreateParam);
}
HRESULT TabStrip::OnDraw(ATL_DRAWINFO& drawInfo)
{
if(IsInDesignMode()) {
CAtlString text = TEXT("TabStrip ");
CComBSTR buffer;
get_Version(&buffer);
text += buffer;
SetTextAlign(drawInfo.hdcDraw, TA_CENTER | TA_BASELINE);
TextOut(drawInfo.hdcDraw, drawInfo.prcBounds->left + (drawInfo.prcBounds->right - drawInfo.prcBounds->left) / 2, drawInfo.prcBounds->top + (drawInfo.prcBounds->bottom - drawInfo.prcBounds->top) / 2, text, text.GetLength());
}
return S_OK;
}
void TabStrip::OnFinalMessage(HWND /*hWnd*/)
{
if(dragDropStatus.pDropTargetHelper) {
dragDropStatus.pDropTargetHelper->Release();
dragDropStatus.pDropTargetHelper = NULL;
}
Release();
}
STDMETHODIMP TabStrip::IOleObject_SetClientSite(LPOLECLIENTSITE pClientSite)
{
pSimpleFrameSite = NULL;
if(pClientSite) {
pClientSite->QueryInterface(IID_ISimpleFrameSite, reinterpret_cast<LPVOID*>(&pSimpleFrameSite));
}
HRESULT hr = CComControl<TabStrip>::IOleObject_SetClientSite(pClientSite);
/* Check whether the container has an ambient font. If it does, clone it; otherwise create our own
font object when we hook up a client site. */
if(!properties.font.pFontDisp) {
FONTDESC defaultFont = properties.font.GetDefaultFont();
CComPtr<IFontDisp> pFont;
if(FAILED(GetAmbientFontDisp(&pFont))) {
// use the default font
OleCreateFontIndirect(&defaultFont, IID_IFontDisp, reinterpret_cast<LPVOID*>(&pFont));
}
put_Font(pFont);
}
return hr;
}
STDMETHODIMP TabStrip::OnDocWindowActivate(BOOL /*fActivate*/)
{
return S_OK;
}
BOOL TabStrip::PreTranslateAccelerator(LPMSG pMessage, HRESULT& hReturnValue)
{
if((pMessage->message >= WM_KEYFIRST) && (pMessage->message <= WM_KEYLAST)) {
LRESULT dialogCode = SendMessage(pMessage->hwnd, WM_GETDLGCODE, 0, 0);
if(dialogCode & DLGC_WANTTAB) {
if(pMessage->wParam == VK_TAB) {
hReturnValue = S_FALSE;
return TRUE;
}
}
switch(pMessage->wParam) {
case VK_LEFT:
case VK_RIGHT:
case VK_UP:
case VK_DOWN:
case VK_HOME:
case VK_END:
case VK_NEXT:
case VK_PRIOR:
if(dialogCode & DLGC_WANTARROWS) {
if(!(GetKeyState(VK_MENU) & 0x8000)) {
SendMessage(pMessage->hwnd, pMessage->message, pMessage->wParam, pMessage->lParam);
hReturnValue = S_OK;
return TRUE;
}
}
break;
case VK_TAB:
if(pMessage->message == WM_KEYDOWN) {
if(GetAsyncKeyState(VK_CONTROL) & 0x8000) {
int activeTab = SendMessage(TCM_GETCURSEL, 0, 0);
activeTab += (GetAsyncKeyState(VK_SHIFT) & 0x8000 ? -1 : 1);
int tabCount = SendMessage(TCM_GETITEMCOUNT, 0, 0);
if(activeTab < 0) {
activeTab = tabCount - 1;
} else if(activeTab >= tabCount) {
activeTab = 0;
}
SendMessage(TCM_SETCURSEL, activeTab, 0);
hReturnValue = S_OK;
return TRUE;
}
}
break;
}
}
return CComControl<TabStrip>::PreTranslateAccelerator(pMessage, hReturnValue);
}
HIMAGELIST TabStrip::CreateLegacyDragImage(int tabIndex, LPPOINT pUpperLeftPoint, LPRECT pBoundingRectangle)
{
/********************************************************************************************************
* Known problems: *
* - We use hardcoded margins. *
********************************************************************************************************/
// retrieve tab details
BOOL tabIsActive = (tabIndex == SendMessage(TCM_GETCURSEL, 0, 0));
// retrieve window details
BOOL layoutRTL = ((GetExStyle() & WS_EX_LAYOUTRTL) == WS_EX_LAYOUTRTL);
// create the DCs we'll draw into
HDC hCompatibleDC = GetDC();
CDC memoryDC;
memoryDC.CreateCompatibleDC(hCompatibleDC);
CDC maskMemoryDC;
maskMemoryDC.CreateCompatibleDC(hCompatibleDC);
// calculate the bounding rectangle
CRect tabBoundingRect;
SendMessage(TCM_GETITEMRECT, tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRect));
if(tabIsActive) {
tabBoundingRect.InflateRect(2, 2);
} else {
tabBoundingRect.InflateRect(-1, 0);
}
if(pBoundingRectangle) {
*pBoundingRectangle = tabBoundingRect;
}
// calculate drag image size and upper-left corner
SIZE dragImageSize = {0};
if(pUpperLeftPoint) {
pUpperLeftPoint->x = tabBoundingRect.left;
pUpperLeftPoint->y = tabBoundingRect.top;
}
dragImageSize.cx = tabBoundingRect.Width();
dragImageSize.cy = tabBoundingRect.Height();
// offset RECTs
SIZE offset = {0};
offset.cx = tabBoundingRect.left;
offset.cy = tabBoundingRect.top;
tabBoundingRect.OffsetRect(-offset.cx, -offset.cy);
// setup the DCs we'll draw into
memoryDC.SetBkColor(GetSysColor(COLOR_WINDOW));
memoryDC.SetTextColor(GetSysColor(COLOR_WINDOWTEXT));
memoryDC.SetBkMode(TRANSPARENT);
// create drag image bitmap
/* NOTE: We prefer creating 32bpp drag images, because this improves performance of
TabStripTabContainer::CreateDragImage(). */
BOOL doAlphaChannelProcessing = RunTimeHelper::IsCommCtrl6();
BITMAPINFO bitmapInfo = {0};
if(doAlphaChannelProcessing) {
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = dragImageSize.cx;
bitmapInfo.bmiHeader.biHeight = -dragImageSize.cy;
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
}
CBitmap dragImage;
LPRGBQUAD pDragImageBits = NULL;
if(doAlphaChannelProcessing) {
dragImage.CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, reinterpret_cast<LPVOID*>(&pDragImageBits), NULL, 0);
} else {
dragImage.CreateCompatibleBitmap(hCompatibleDC, dragImageSize.cx, dragImageSize.cy);
}
HBITMAP hPreviousBitmap = memoryDC.SelectBitmap(dragImage);
CBitmap dragImageMask;
dragImageMask.CreateBitmap(dragImageSize.cx, dragImageSize.cy, 1, 1, NULL);
HBITMAP hPreviousBitmapMask = maskMemoryDC.SelectBitmap(dragImageMask);
// initialize the bitmap
RECT rc = tabBoundingRect;
if(doAlphaChannelProcessing && pDragImageBits) {
// we need a transparent background
LPRGBQUAD pPixel = pDragImageBits;
for(int y = 0; y < dragImageSize.cy; ++y) {
for(int x = 0; x < dragImageSize.cx; ++x, ++pPixel) {
pPixel->rgbRed = 0xFF;
pPixel->rgbGreen = 0xFF;
pPixel->rgbBlue = 0xFF;
pPixel->rgbReserved = 0x00;
}
}
} else {
memoryDC.FillRect(&rc, static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
}
maskMemoryDC.FillRect(&rc, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
// draw the tab
memoryDC.SetViewportOrg(-offset.cx, -offset.cy);
SendMessage(WM_PRINTCLIENT, reinterpret_cast<WPARAM>(static_cast<HDC>(memoryDC)));
memoryDC.SetViewportOrg(0, 0);
if(doAlphaChannelProcessing && pDragImageBits) {
// correct the alpha channel
LPRGBQUAD pPixel = pDragImageBits;
POINT pt;
for(pt.y = 0; pt.y < dragImageSize.cy; ++pt.y) {
for(pt.x = 0; pt.x < dragImageSize.cx; ++pt.x, ++pPixel) {
if(layoutRTL) {
// we're working on raw data, so we've to handle WS_EX_LAYOUTRTL ourselves
POINT pt2 = pt;
pt2.x = dragImageSize.cx - pt.x - 1;
if(maskMemoryDC.GetPixel(pt2.x, pt2.y) == 0x00000000) {
if(pPixel->rgbReserved == 0x00) {
pPixel->rgbReserved = 0xFF;
}
}
} else {
// layout is left to right
if(maskMemoryDC.GetPixel(pt.x, pt.y) == 0x00000000) {
if(pPixel->rgbReserved == 0x00) {
pPixel->rgbReserved = 0xFF;
}
}
}
}
}
}
memoryDC.SelectBitmap(hPreviousBitmap);
maskMemoryDC.SelectBitmap(hPreviousBitmapMask);
// create the imagelist
HIMAGELIST hDragImageList = ImageList_Create(dragImageSize.cx, dragImageSize.cy, (RunTimeHelper::IsCommCtrl6() ? ILC_COLOR32 : ILC_COLOR24) | ILC_MASK, 1, 0);
ImageList_SetBkColor(hDragImageList, CLR_NONE);
ImageList_Add(hDragImageList, dragImage, dragImageMask);
ReleaseDC(hCompatibleDC);
return hDragImageList;
}
BOOL TabStrip::CreateLegacyOLEDragImage(ITabStripTabContainer* pTabs, LPSHDRAGIMAGE pDragImage)
{
ATLASSUME(pTabs);
ATLASSERT_POINTER(pDragImage, SHDRAGIMAGE);
BOOL succeeded = FALSE;
// use a normal legacy drag image as base
OLE_HANDLE h = NULL;
OLE_XPOS_PIXELS xUpperLeft = 0;
OLE_YPOS_PIXELS yUpperLeft = 0;
pTabs->CreateDragImage(&xUpperLeft, &yUpperLeft, &h);
if(h) {
HIMAGELIST hImageList = static_cast<HIMAGELIST>(LongToHandle(h));
// retrieve the drag image's size
int bitmapHeight;
int bitmapWidth;
ImageList_GetIconSize(hImageList, &bitmapWidth, &bitmapHeight);
pDragImage->sizeDragImage.cx = bitmapWidth;
pDragImage->sizeDragImage.cy = bitmapHeight;
CDC memoryDC;
memoryDC.CreateCompatibleDC();
pDragImage->hbmpDragImage = NULL;
if(RunTimeHelper::IsCommCtrl6()) {
// handle alpha channel
IImageList* pImgLst = NULL;
HMODULE hMod = LoadLibrary(TEXT("comctl32.dll"));
if(hMod) {
typedef HRESULT WINAPI HIMAGELIST_QueryInterfaceFn(HIMAGELIST, REFIID, LPVOID*);
HIMAGELIST_QueryInterfaceFn* pfnHIMAGELIST_QueryInterface = reinterpret_cast<HIMAGELIST_QueryInterfaceFn*>(GetProcAddress(hMod, "HIMAGELIST_QueryInterface"));
if(pfnHIMAGELIST_QueryInterface) {
pfnHIMAGELIST_QueryInterface(hImageList, IID_IImageList, reinterpret_cast<LPVOID*>(&pImgLst));
}
FreeLibrary(hMod);
}
if(!pImgLst) {
pImgLst = reinterpret_cast<IImageList*>(hImageList);
pImgLst->AddRef();
}
ATLASSUME(pImgLst);
DWORD imageFlags = 0;
pImgLst->GetItemFlags(0, &imageFlags);
if(imageFlags & ILIF_ALPHA) {
// the drag image makes use of the alpha channel
IMAGEINFO imageInfo = {0};
ImageList_GetImageInfo(hImageList, 0, &imageInfo);
// fetch raw data
BITMAPINFO bitmapInfo = {0};
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = pDragImage->sizeDragImage.cx;
bitmapInfo.bmiHeader.biHeight = -pDragImage->sizeDragImage.cy;
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
LPRGBQUAD pSourceBits = static_cast<LPRGBQUAD>(HeapAlloc(GetProcessHeap(), 0, pDragImage->sizeDragImage.cx * pDragImage->sizeDragImage.cy * sizeof(RGBQUAD)));
GetDIBits(memoryDC, imageInfo.hbmImage, 0, pDragImage->sizeDragImage.cy, pSourceBits, &bitmapInfo, DIB_RGB_COLORS);
// create target bitmap
LPRGBQUAD pDragImageBits = NULL;
pDragImage->hbmpDragImage = CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, reinterpret_cast<LPVOID*>(&pDragImageBits), NULL, 0);
ATLASSERT(pDragImageBits);
pDragImage->crColorKey = 0xFFFFFFFF;
if(pDragImageBits) {
// transfer raw data
CopyMemory(pDragImageBits, pSourceBits, pDragImage->sizeDragImage.cx * pDragImage->sizeDragImage.cy * 4);
}
// clean up
HeapFree(GetProcessHeap(), 0, pSourceBits);
DeleteObject(imageInfo.hbmImage);
DeleteObject(imageInfo.hbmMask);
}
pImgLst->Release();
}
if(!pDragImage->hbmpDragImage) {
// fallback mode
memoryDC.SetBkMode(TRANSPARENT);
// create target bitmap
HDC hCompatibleDC = ::GetDC(HWND_DESKTOP);
pDragImage->hbmpDragImage = CreateCompatibleBitmap(hCompatibleDC, bitmapWidth, bitmapHeight);
::ReleaseDC(HWND_DESKTOP, hCompatibleDC);
HBITMAP hPreviousBitmap = memoryDC.SelectBitmap(pDragImage->hbmpDragImage);
// draw target bitmap
pDragImage->crColorKey = RGB(0xF4, 0x00, 0x00);
CBrush backroundBrush;
backroundBrush.CreateSolidBrush(pDragImage->crColorKey);
memoryDC.FillRect(CRect(0, 0, bitmapWidth, bitmapHeight), backroundBrush);
ImageList_Draw(hImageList, 0, memoryDC, 0, 0, ILD_NORMAL);
// clean up
memoryDC.SelectBitmap(hPreviousBitmap);
}
ImageList_Destroy(hImageList);
if(pDragImage->hbmpDragImage) {
// retrieve the offset
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
if(GetExStyle() & WS_EX_LAYOUTRTL) {
pDragImage->ptOffset.x = xUpperLeft + pDragImage->sizeDragImage.cx - mousePosition.x;
} else {
pDragImage->ptOffset.x = mousePosition.x - xUpperLeft;
}
pDragImage->ptOffset.y = mousePosition.y - yUpperLeft;
succeeded = TRUE;
}
}
return succeeded;
}
BOOL TabStrip::CreateVistaOLEDragImage(ITabStripTabContainer* pTabs, LPSHDRAGIMAGE pDragImage)
{
ATLASSUME(pTabs);
ATLASSERT_POINTER(pDragImage, SHDRAGIMAGE);
BOOL succeeded = FALSE;
CTheme themingEngine;
themingEngine.OpenThemeData(NULL, VSCLASS_DRAGDROP);
if(themingEngine.IsThemeNull()) {
// FIXME: What should we do here?
ATLASSERT(FALSE && "Current theme does not define the \"DragDrop\" class.");
} else {
// retrieve the drag image's size
CDC memoryDC;
memoryDC.CreateCompatibleDC();
themingEngine.GetThemePartSize(memoryDC, DD_IMAGEBG, 1, NULL, TS_TRUE, &pDragImage->sizeDragImage);
MARGINS margins = {0};
themingEngine.GetThemeMargins(memoryDC, DD_IMAGEBG, 1, TMT_CONTENTMARGINS, NULL, &margins);
pDragImage->sizeDragImage.cx -= margins.cxLeftWidth + margins.cxRightWidth;
pDragImage->sizeDragImage.cy -= margins.cyTopHeight + margins.cyBottomHeight;
}
ATLASSERT(pDragImage->sizeDragImage.cx > 0);
ATLASSERT(pDragImage->sizeDragImage.cy > 0);
// create target bitmap
BITMAPINFO bitmapInfo = {0};
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = pDragImage->sizeDragImage.cx;
bitmapInfo.bmiHeader.biHeight = -pDragImage->sizeDragImage.cy;
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
LPRGBQUAD pDragImageBits = NULL;
pDragImage->hbmpDragImage = CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, reinterpret_cast<LPVOID*>(&pDragImageBits), NULL, 0);
HIMAGELIST hSourceImageList = (cachedSettings.hHighResImageList ? cachedSettings.hHighResImageList : cachedSettings.hImageList);
if(!hSourceImageList) {
// report success, although we've an empty drag image
return TRUE;
}
IImageList2* pImgLst = NULL;
HMODULE hMod = LoadLibrary(TEXT("comctl32.dll"));
if(hMod) {
typedef HRESULT WINAPI HIMAGELIST_QueryInterfaceFn(HIMAGELIST, REFIID, LPVOID*);
HIMAGELIST_QueryInterfaceFn* pfnHIMAGELIST_QueryInterface = reinterpret_cast<HIMAGELIST_QueryInterfaceFn*>(GetProcAddress(hMod, "HIMAGELIST_QueryInterface"));
if(pfnHIMAGELIST_QueryInterface) {
pfnHIMAGELIST_QueryInterface(hSourceImageList, IID_IImageList2, reinterpret_cast<LPVOID*>(&pImgLst));
}
FreeLibrary(hMod);
}
if(!pImgLst) {
IImageList* p = reinterpret_cast<IImageList*>(hSourceImageList);
p->QueryInterface(IID_IImageList2, reinterpret_cast<LPVOID*>(&pImgLst));
}
ATLASSUME(pImgLst);
if(pImgLst) {
LONG numberOfTabs = 0;
pTabs->Count(&numberOfTabs);
ATLASSERT(numberOfTabs > 0);
// don't display more than 5 (10) thumbnails
numberOfTabs = min(numberOfTabs, (hSourceImageList == cachedSettings.hHighResImageList ? 5 : 10));
CComPtr<IUnknown> pUnknownEnum = NULL;
pTabs->get__NewEnum(&pUnknownEnum);
CComQIPtr<IEnumVARIANT> pEnum = pUnknownEnum;
ATLASSUME(pEnum);
if(pEnum) {
int cx = 0;
int cy = 0;
pImgLst->GetIconSize(&cx, &cy);
SIZE thumbnailSize;
thumbnailSize.cy = pDragImage->sizeDragImage.cy - 3 * (numberOfTabs - 1);
if(thumbnailSize.cy < 8) {
// don't get smaller than 8x8 thumbnails
numberOfTabs = (pDragImage->sizeDragImage.cy - 8) / 3 + 1;
thumbnailSize.cy = pDragImage->sizeDragImage.cy - 3 * (numberOfTabs - 1);
}
thumbnailSize.cx = thumbnailSize.cy;
int thumbnailBufferSize = thumbnailSize.cx * thumbnailSize.cy * sizeof(RGBQUAD);
LPRGBQUAD pThumbnailBits = static_cast<LPRGBQUAD>(HeapAlloc(GetProcessHeap(), 0, thumbnailBufferSize));
ATLASSERT(pThumbnailBits);
if(pThumbnailBits) {
// iterate over the dragged tabs
VARIANT v;
int i = 0;
CComPtr<ITabStripTab> pTab = NULL;
while(pEnum->Next(1, &v, NULL) == S_OK) {
if(v.vt == VT_DISPATCH) {
v.pdispVal->QueryInterface(IID_ITabStripTab, reinterpret_cast<LPVOID*>(&pTab));
ATLASSUME(pTab);
if(pTab) {
// get the tab's icon
LONG icon = 0;
pTab->get_IconIndex(&icon);
pImgLst->ForceImagePresent(icon, ILFIP_ALWAYS);
HICON hIcon = NULL;
pImgLst->GetIcon(icon, ILD_TRANSPARENT, &hIcon);
ATLASSERT(hIcon);
if(hIcon) {
// finally create the thumbnail
ZeroMemory(pThumbnailBits, thumbnailBufferSize);
HRESULT hr = CreateThumbnail(hIcon, thumbnailSize, pThumbnailBits, TRUE);
DestroyIcon(hIcon);
if(FAILED(hr)) {
pTab = NULL;
VariantClear(&v);
break;
}
// add the thumbail to the drag image keeping the alpha channel intact
if(i == 0) {
LPRGBQUAD pDragImagePixel = pDragImageBits;
LPRGBQUAD pThumbnailPixel = pThumbnailBits;
for(int scanline = 0; scanline < thumbnailSize.cy; ++scanline, pDragImagePixel += pDragImage->sizeDragImage.cx, pThumbnailPixel += thumbnailSize.cx) {
CopyMemory(pDragImagePixel, pThumbnailPixel, thumbnailSize.cx * sizeof(RGBQUAD));
}
} else {
LPRGBQUAD pDragImagePixel = pDragImageBits;
LPRGBQUAD pThumbnailPixel = pThumbnailBits;
pDragImagePixel += 3 * i * pDragImage->sizeDragImage.cx;
for(int scanline = 0; scanline < thumbnailSize.cy; ++scanline, pDragImagePixel += pDragImage->sizeDragImage.cx) {
LPRGBQUAD p = pDragImagePixel + 2 * i;
for(int x = 0; x < thumbnailSize.cx; ++x, ++p, ++pThumbnailPixel) {
// merge the pixels
p->rgbRed = pThumbnailPixel->rgbRed * pThumbnailPixel->rgbReserved / 0xFF + (0xFF - pThumbnailPixel->rgbReserved) * p->rgbRed / 0xFF;
p->rgbGreen = pThumbnailPixel->rgbGreen * pThumbnailPixel->rgbReserved / 0xFF + (0xFF - pThumbnailPixel->rgbReserved) * p->rgbGreen / 0xFF;
p->rgbBlue = pThumbnailPixel->rgbBlue * pThumbnailPixel->rgbReserved / 0xFF + (0xFF - pThumbnailPixel->rgbReserved) * p->rgbBlue / 0xFF;
p->rgbReserved = pThumbnailPixel->rgbReserved + (0xFF - pThumbnailPixel->rgbReserved) * p->rgbReserved / 0xFF;
}
}
}
}
++i;
pTab = NULL;
if(i == numberOfTabs) {
VariantClear(&v);
break;
}
}
}
VariantClear(&v);
}
HeapFree(GetProcessHeap(), 0, pThumbnailBits);
succeeded = TRUE;
}
}
pImgLst->Release();
}
return succeeded;
}
//////////////////////////////////////////////////////////////////////
// implementation of IDropTarget
STDMETHODIMP TabStrip::DragEnter(IDataObject* pDataObject, DWORD keyState, POINTL mousePosition, DWORD* pEffect)
{
// NOTE: pDataObject can be NULL
if(properties.supportOLEDragImages && !dragDropStatus.pDropTargetHelper) {
CoCreateInstance(CLSID_DragDropHelper, NULL, CLSCTX_ALL, IID_PPV_ARGS(&dragDropStatus.pDropTargetHelper));
}
DROPDESCRIPTION oldDropDescription;
ZeroMemory(&oldDropDescription, sizeof(DROPDESCRIPTION));
IDataObject_GetDropDescription(pDataObject, oldDropDescription);
POINT buffer = {mousePosition.x, mousePosition.y};
Raise_OLEDragEnter(pDataObject, pEffect, keyState, mousePosition);
if(dragDropStatus.pDropTargetHelper) {
dragDropStatus.pDropTargetHelper->DragEnter(*this, pDataObject, &buffer, *pEffect);
if(dragDropStatus.useItemCountLabelHack) {
dragDropStatus.pDropTargetHelper->DragLeave();
dragDropStatus.pDropTargetHelper->DragEnter(*this, pDataObject, &buffer, *pEffect);
dragDropStatus.useItemCountLabelHack = FALSE;
}
}
DROPDESCRIPTION newDropDescription;
ZeroMemory(&newDropDescription, sizeof(DROPDESCRIPTION));
if(SUCCEEDED(IDataObject_GetDropDescription(pDataObject, newDropDescription)) && memcmp(&oldDropDescription, &newDropDescription, sizeof(DROPDESCRIPTION))) {
InvalidateDragWindow(pDataObject);
}
return S_OK;
}
STDMETHODIMP TabStrip::DragLeave(void)
{
Raise_OLEDragLeave();
if(dragDropStatus.pDropTargetHelper) {
dragDropStatus.pDropTargetHelper->DragLeave();
dragDropStatus.pDropTargetHelper->Release();
dragDropStatus.pDropTargetHelper = NULL;
}
return S_OK;
}
STDMETHODIMP TabStrip::DragOver(DWORD keyState, POINTL mousePosition, DWORD* pEffect)
{
// NOTE: pDataObject can be NULL
CComQIPtr<IDataObject> pDataObject = dragDropStatus.pActiveDataObject;
DROPDESCRIPTION oldDropDescription;
ZeroMemory(&oldDropDescription, sizeof(DROPDESCRIPTION));
IDataObject_GetDropDescription(pDataObject, oldDropDescription);
POINT buffer = {mousePosition.x, mousePosition.y};
Raise_OLEDragMouseMove(pEffect, keyState, mousePosition);
if(dragDropStatus.pDropTargetHelper) {
dragDropStatus.pDropTargetHelper->DragOver(&buffer, *pEffect);
}
DROPDESCRIPTION newDropDescription;
ZeroMemory(&newDropDescription, sizeof(DROPDESCRIPTION));
if(SUCCEEDED(IDataObject_GetDropDescription(pDataObject, newDropDescription)) && (newDropDescription.type > DROPIMAGE_NONE || memcmp(&oldDropDescription, &newDropDescription, sizeof(DROPDESCRIPTION)))) {
InvalidateDragWindow(pDataObject);
}
return S_OK;
}
STDMETHODIMP TabStrip::Drop(IDataObject* pDataObject, DWORD keyState, POINTL mousePosition, DWORD* pEffect)
{
// NOTE: pDataObject can be NULL
POINT buffer = {mousePosition.x, mousePosition.y};
dragDropStatus.drop_pDataObject = pDataObject;
dragDropStatus.drop_mousePosition = buffer;
dragDropStatus.drop_effect = *pEffect;
Raise_OLEDragDrop(pDataObject, pEffect, keyState, mousePosition);
if(dragDropStatus.pDropTargetHelper) {
dragDropStatus.pDropTargetHelper->Drop(pDataObject, &buffer, *pEffect);
dragDropStatus.pDropTargetHelper->Release();
dragDropStatus.pDropTargetHelper = NULL;
}
dragDropStatus.drop_pDataObject = NULL;
return S_OK;
}
// implementation of IDropTarget
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of IDropSource
STDMETHODIMP TabStrip::GiveFeedback(DWORD effect)
{
VARIANT_BOOL useDefaultCursors = VARIANT_TRUE;
//if(flags.usingThemes && RunTimeHelper::IsVista()) {
ATLASSUME(dragDropStatus.pSourceDataObject);
BOOL isShowingLayered = FALSE;
FORMATETC format = {0};
format.cfFormat = static_cast<CLIPFORMAT>(RegisterClipboardFormat(TEXT("IsShowingLayered")));
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
STGMEDIUM medium = {0};
if(SUCCEEDED(dragDropStatus.pSourceDataObject->GetData(&format, &medium))) {
if(medium.hGlobal) {
isShowingLayered = *static_cast<LPBOOL>(GlobalLock(medium.hGlobal));
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
BOOL useDropDescriptionHack = FALSE;
format.cfFormat = static_cast<CLIPFORMAT>(RegisterClipboardFormat(TEXT("UsingDefaultDragImage")));
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
if(SUCCEEDED(dragDropStatus.pSourceDataObject->GetData(&format, &medium))) {
if(medium.hGlobal) {
useDropDescriptionHack = *static_cast<LPBOOL>(GlobalLock(medium.hGlobal));
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
if(isShowingLayered && properties.oleDragImageStyle != odistClassic) {
SetCursor(static_cast<HCURSOR>(LoadImage(NULL, MAKEINTRESOURCE(OCR_NORMAL), IMAGE_CURSOR, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED)));
useDefaultCursors = VARIANT_FALSE;
}
if(useDropDescriptionHack) {
// this will make drop descriptions work
format.cfFormat = static_cast<CLIPFORMAT>(RegisterClipboardFormat(TEXT("DragWindow")));
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
if(SUCCEEDED(dragDropStatus.pSourceDataObject->GetData(&format, &medium))) {
if(medium.hGlobal) {
// WM_USER + 1 (with wParam = 0 and lParam = 0) hides the drag image
#define WM_SETDROPEFFECT WM_USER + 2 // (wParam = DCID_*, lParam = 0)
#define DDWM_UPDATEWINDOW WM_USER + 3 // (wParam = 0, lParam = 0)
typedef enum DROPEFFECTS
{
DCID_NULL = 0,
DCID_NO = 1,
DCID_MOVE = 2,
DCID_COPY = 3,
DCID_LINK = 4,
DCID_MAX = 5
} DROPEFFECTS;
HWND hWndDragWindow = *static_cast<HWND*>(GlobalLock(medium.hGlobal));
GlobalUnlock(medium.hGlobal);
DROPEFFECTS dropEffect = DCID_NULL;
switch(effect) {
case DROPEFFECT_NONE:
dropEffect = DCID_NO;
break;
case DROPEFFECT_COPY:
dropEffect = DCID_COPY;
break;
case DROPEFFECT_MOVE:
dropEffect = DCID_MOVE;
break;
case DROPEFFECT_LINK:
dropEffect = DCID_LINK;
break;
}
if(::IsWindow(hWndDragWindow)) {
::PostMessage(hWndDragWindow, WM_SETDROPEFFECT, dropEffect, 0);
}
}
ReleaseStgMedium(&medium);
}
}
//}
Raise_OLEGiveFeedback(effect, &useDefaultCursors);
return (useDefaultCursors == VARIANT_FALSE ? S_OK : DRAGDROP_S_USEDEFAULTCURSORS);
}
STDMETHODIMP TabStrip::QueryContinueDrag(BOOL pressedEscape, DWORD keyState)
{
HRESULT actionToContinueWith = S_OK;
if(pressedEscape) {
actionToContinueWith = DRAGDROP_S_CANCEL;
} else if(!(keyState & dragDropStatus.draggingMouseButton)) {
actionToContinueWith = DRAGDROP_S_DROP;
}
Raise_OLEQueryContinueDrag(pressedEscape, keyState, &actionToContinueWith);
return actionToContinueWith;
}
// implementation of IDropSource
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of IDropSourceNotify
STDMETHODIMP TabStrip::DragEnterTarget(HWND hWndTarget)
{
Raise_OLEDragEnterPotentialTarget(HandleToLong(hWndTarget));
return S_OK;
}
STDMETHODIMP TabStrip::DragLeaveTarget(void)
{
Raise_OLEDragLeavePotentialTarget();
return S_OK;
}
// implementation of IDropSourceNotify
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of ICategorizeProperties
STDMETHODIMP TabStrip::GetCategoryName(PROPCAT category, LCID /*languageID*/, BSTR* pName)
{
switch(category) {
case PROPCAT_Colors:
*pName = GetResString(IDPC_COLORS).Detach();
return S_OK;
break;
case PROPCAT_DragDrop:
*pName = GetResString(IDPC_DRAGDROP).Detach();
return S_OK;
break;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::MapPropertyToCategory(DISPID property, PROPCAT* pCategory)
{
if(!pCategory) {
return E_POINTER;
}
switch(property) {
case DISPID_TABSTRIPCTL_APPEARANCE:
case DISPID_TABSTRIPCTL_BORDERSTYLE:
case DISPID_TABSTRIPCTL_CLOSEABLETABS:
case DISPID_TABSTRIPCTL_CLOSEABLETABSMODE:
case DISPID_TABSTRIPCTL_DISPLAYAREAHEIGHT:
case DISPID_TABSTRIPCTL_DISPLAYAREALEFT:
case DISPID_TABSTRIPCTL_DISPLAYAREATOP:
case DISPID_TABSTRIPCTL_DISPLAYAREAWIDTH:
case DISPID_TABSTRIPCTL_FIXEDTABWIDTH:
case DISPID_TABSTRIPCTL_HORIZONTALPADDING:
case DISPID_TABSTRIPCTL_MINTABWIDTH:
case DISPID_TABSTRIPCTL_MOUSEICON:
case DISPID_TABSTRIPCTL_MOUSEPOINTER:
case DISPID_TABSTRIPCTL_SHOWBUTTONSEPARATORS:
case DISPID_TABSTRIPCTL_STYLE:
case DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT:
case DISPID_TABSTRIPCTL_TABHEIGHT:
case DISPID_TABSTRIPCTL_TABPLACEMENT:
case DISPID_TABSTRIPCTL_USEFIXEDTABWIDTH:
case DISPID_TABSTRIPCTL_VERTICALPADDING:
*pCategory = PROPCAT_Appearance;
return S_OK;
break;
case DISPID_TABSTRIPCTL_ACTIVETAB:
case DISPID_TABSTRIPCTL_CARETTAB:
case DISPID_TABSTRIPCTL_DISABLEDEVENTS:
//case DISPID_TABSTRIPCTL_DONTREDRAW:
case DISPID_TABSTRIPCTL_FOCUSONBUTTONDOWN:
case DISPID_TABSTRIPCTL_HOTTRACKING:
case DISPID_TABSTRIPCTL_HOVERTIME:
case DISPID_TABSTRIPCTL_MULTIROW:
case DISPID_TABSTRIPCTL_MULTISELECT:
case DISPID_TABSTRIPCTL_OWNERDRAWN:
case DISPID_TABSTRIPCTL_PROCESSCONTEXTMENUKEYS:
case DISPID_TABSTRIPCTL_RAGGEDTABROWS:
//case DISPID_TABSTRIPCTL_REFLECTCONTEXTMENUMESSAGES:
case DISPID_TABSTRIPCTL_RIGHTTOLEFT:
case DISPID_TABSTRIPCTL_SCROLLTOOPPOSITE:
case DISPID_TABSTRIPCTL_SHOWTOOLTIPS:
case DISPID_TABSTRIPCTL_TABBOUNDINGBOXDEFINITION:
*pCategory = PROPCAT_Behavior;
return S_OK;
break;
case DISPID_TABSTRIPCTL_INSERTMARKCOLOR:
*pCategory = PROPCAT_Colors;
return S_OK;
break;
case DISPID_TABSTRIPCTL_APPID:
case DISPID_TABSTRIPCTL_APPNAME:
case DISPID_TABSTRIPCTL_APPSHORTNAME:
case DISPID_TABSTRIPCTL_BUILD:
case DISPID_TABSTRIPCTL_CHARSET:
case DISPID_TABSTRIPCTL_HDRAGIMAGELIST:
case DISPID_TABSTRIPCTL_HHIGHRESIMAGELIST:
case DISPID_TABSTRIPCTL_HIMAGELIST:
case DISPID_TABSTRIPCTL_HWND:
case DISPID_TABSTRIPCTL_HWNDARROWBUTTONS:
case DISPID_TABSTRIPCTL_HWNDTOOLTIP:
case DISPID_TABSTRIPCTL_ISRELEASE:
case DISPID_TABSTRIPCTL_PROGRAMMER:
case DISPID_TABSTRIPCTL_TESTER:
case DISPID_TABSTRIPCTL_VERSION:
*pCategory = PROPCAT_Data;
return S_OK;
break;
case DISPID_TABSTRIPCTL_ALLOWDRAGDROP:
case DISPID_TABSTRIPCTL_DRAGACTIVATETIME:
case DISPID_TABSTRIPCTL_DRAGGEDTABS:
case DISPID_TABSTRIPCTL_DRAGSCROLLTIMEBASE:
case DISPID_TABSTRIPCTL_DROPHILITEDTAB:
case DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE:
case DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP:
case DISPID_TABSTRIPCTL_SHOWDRAGIMAGE:
case DISPID_TABSTRIPCTL_SUPPORTOLEDRAGIMAGES:
*pCategory = PROPCAT_DragDrop;
return S_OK;
break;
case DISPID_TABSTRIPCTL_FONT:
case DISPID_TABSTRIPCTL_USESYSTEMFONT:
*pCategory = PROPCAT_Font;
return S_OK;
break;
case DISPID_TABSTRIPCTL_TABS:
*pCategory = PROPCAT_List;
return S_OK;
break;
case DISPID_TABSTRIPCTL_ENABLED:
*pCategory = PROPCAT_Misc;
return S_OK;
break;
}
return E_FAIL;
}
// implementation of ICategorizeProperties
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of ICreditsProvider
CAtlString TabStrip::GetAuthors(void)
{
CComBSTR buffer;
get_Programmer(&buffer);
return CAtlString(buffer);
}
CAtlString TabStrip::GetHomepage(void)
{
return TEXT("https://www.TimoSoft-Software.de");
}
CAtlString TabStrip::GetPaypalLink(void)
{
return TEXT("https://www.paypal.com/xclick/business=TKunze71216%40gmx.de&item_name=TabStrip&no_shipping=1&tax=0¤cy_code=EUR");
}
CAtlString TabStrip::GetSpecialThanks(void)
{
return TEXT("<NAME>, Wine Headquarters");
}
CAtlString TabStrip::GetThanks(void)
{
CAtlString ret = TEXT("Google, various newsgroups and mailing lists, many websites,\n");
ret += TEXT("Heaven Shall Burn, Arch Enemy, Machine Head, Trivium, Deadlock, Draconian, Soulfly, Delain, Lacuna Coil, Ensiferum, Epica, Nightwish, Guns N' Roses and many other musicians");
return ret;
}
CAtlString TabStrip::GetVersion(void)
{
CAtlString ret = TEXT("Version ");
CComBSTR buffer;
get_Version(&buffer);
ret += buffer;
ret += TEXT(" (");
get_CharSet(&buffer);
ret += buffer;
ret += TEXT(")\nCompilation timestamp: ");
ret += TEXT(STRTIMESTAMP);
ret += TEXT("\n");
VARIANT_BOOL b;
get_IsRelease(&b);
if(b == VARIANT_FALSE) {
ret += TEXT("This version is for debugging only.");
}
return ret;
}
// implementation of ICreditsProvider
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of IPerPropertyBrowsing
STDMETHODIMP TabStrip::GetDisplayString(DISPID property, BSTR* pDescription)
{
if(!pDescription) {
return E_POINTER;
}
CComBSTR description;
HRESULT hr = S_OK;
switch(property) {
case DISPID_TABSTRIPCTL_APPEARANCE:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.appearance), description);
break;
case DISPID_TABSTRIPCTL_BORDERSTYLE:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.borderStyle), description);
break;
case DISPID_TABSTRIPCTL_CLOSEABLETABSMODE:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.closeableTabsMode), description);
break;
case DISPID_TABSTRIPCTL_MOUSEPOINTER:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.mousePointer), description);
break;
case DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.oleDragImageStyle), description);
break;
case DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.registerForOLEDragDrop), description);
break;
case DISPID_TABSTRIPCTL_RIGHTTOLEFT:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.rightToLeft), description);
break;
case DISPID_TABSTRIPCTL_STYLE:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.style), description);
break;
case DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.tabCaptionAlignment), description);
break;
case DISPID_TABSTRIPCTL_TABPLACEMENT:
hr = GetDisplayStringForSetting(property, static_cast<DWORD>(properties.tabPlacement), description);
break;
default:
return IPerPropertyBrowsingImpl<TabStrip>::GetDisplayString(property, pDescription);
break;
}
if(SUCCEEDED(hr)) {
*pDescription = description.Detach();
}
return *pDescription ? S_OK : E_OUTOFMEMORY;
}
STDMETHODIMP TabStrip::GetPredefinedStrings(DISPID property, CALPOLESTR* pDescriptions, CADWORD* pCookies)
{
if(!pDescriptions || !pCookies) {
return E_POINTER;
}
int c = 0;
switch(property) {
case DISPID_TABSTRIPCTL_BORDERSTYLE:
case DISPID_TABSTRIPCTL_CLOSEABLETABSMODE:
case DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE:
c = 2;
break;
case DISPID_TABSTRIPCTL_APPEARANCE:
case DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP:
case DISPID_TABSTRIPCTL_STYLE:
case DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT:
c = 3;
break;
case DISPID_TABSTRIPCTL_RIGHTTOLEFT:
case DISPID_TABSTRIPCTL_TABPLACEMENT:
c = 4;
break;
case DISPID_TABSTRIPCTL_MOUSEPOINTER:
c = 30;
break;
default:
return IPerPropertyBrowsingImpl<TabStrip>::GetPredefinedStrings(property, pDescriptions, pCookies);
break;
}
pDescriptions->cElems = c;
pCookies->cElems = c;
pDescriptions->pElems = static_cast<LPOLESTR*>(CoTaskMemAlloc(pDescriptions->cElems * sizeof(LPOLESTR)));
pCookies->pElems = static_cast<LPDWORD>(CoTaskMemAlloc(pCookies->cElems * sizeof(DWORD)));
for(UINT iDescription = 0; iDescription < pDescriptions->cElems; ++iDescription) {
UINT propertyValue = iDescription;
if(property == DISPID_TABSTRIPCTL_CLOSEABLETABSMODE) {
propertyValue++;
} else if((property == DISPID_TABSTRIPCTL_MOUSEPOINTER) && (iDescription == pDescriptions->cElems - 1)) {
propertyValue = mpCustom;
}
CComBSTR description;
HRESULT hr = GetDisplayStringForSetting(property, propertyValue, description);
if(SUCCEEDED(hr)) {
size_t bufferSize = SysStringLen(description) + 1;
pDescriptions->pElems[iDescription] = static_cast<LPOLESTR>(CoTaskMemAlloc(bufferSize * sizeof(WCHAR)));
ATLVERIFY(SUCCEEDED(StringCchCopyW(pDescriptions->pElems[iDescription], bufferSize, description)));
// simply use the property value as cookie
pCookies->pElems[iDescription] = propertyValue;
} else {
return DISP_E_BADINDEX;
}
}
return S_OK;
}
STDMETHODIMP TabStrip::GetPredefinedValue(DISPID property, DWORD cookie, VARIANT* pPropertyValue)
{
switch(property) {
case DISPID_TABSTRIPCTL_APPEARANCE:
case DISPID_TABSTRIPCTL_BORDERSTYLE:
case DISPID_TABSTRIPCTL_CLOSEABLETABSMODE:
case DISPID_TABSTRIPCTL_MOUSEPOINTER:
case DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE:
case DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP:
case DISPID_TABSTRIPCTL_RIGHTTOLEFT:
case DISPID_TABSTRIPCTL_STYLE:
case DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT:
case DISPID_TABSTRIPCTL_TABPLACEMENT:
VariantInit(pPropertyValue);
pPropertyValue->vt = VT_I4;
// we used the property value itself as cookie
pPropertyValue->lVal = cookie;
break;
default:
return IPerPropertyBrowsingImpl<TabStrip>::GetPredefinedValue(property, cookie, pPropertyValue);
break;
}
return S_OK;
}
STDMETHODIMP TabStrip::MapPropertyToPage(DISPID property, CLSID* pPropertyPage)
{
return IPerPropertyBrowsingImpl<TabStrip>::MapPropertyToPage(property, pPropertyPage);
}
// implementation of IPerPropertyBrowsing
//////////////////////////////////////////////////////////////////////
HRESULT TabStrip::GetDisplayStringForSetting(DISPID property, DWORD cookie, CComBSTR& description)
{
switch(property) {
case DISPID_TABSTRIPCTL_APPEARANCE:
switch(cookie) {
case a2D:
description = GetResStringWithNumber(IDP_APPEARANCE2D, a2D);
break;
case a3D:
description = GetResStringWithNumber(IDP_APPEARANCE3D, a3D);
break;
case a3DLight:
description = GetResStringWithNumber(IDP_APPEARANCE3DLIGHT, a3DLight);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_BORDERSTYLE:
switch(cookie) {
case bsNone:
description = GetResStringWithNumber(IDP_BORDERSTYLENONE, bsNone);
break;
case bsFixedSingle:
description = GetResStringWithNumber(IDP_BORDERSTYLEFIXEDSINGLE, bsFixedSingle);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_CLOSEABLETABSMODE:
switch(cookie) {
case ctmDisplayOnAllTabs:
description = GetResStringWithNumber(IDP_CLOSEABLETABSMODEDISPLAYONALLTABS, ctmDisplayOnAllTabs);
break;
case ctmDisplayOnActiveTab:
description = GetResStringWithNumber(IDP_CLOSEABLETABSMODEDISPLAYONACTIVETAB, ctmDisplayOnActiveTab);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_MOUSEPOINTER:
switch(cookie) {
case mpDefault:
description = GetResStringWithNumber(IDP_MOUSEPOINTERDEFAULT, mpDefault);
break;
case mpArrow:
description = GetResStringWithNumber(IDP_MOUSEPOINTERARROW, mpArrow);
break;
case mpCross:
description = GetResStringWithNumber(IDP_MOUSEPOINTERCROSS, mpCross);
break;
case mpIBeam:
description = GetResStringWithNumber(IDP_MOUSEPOINTERIBEAM, mpIBeam);
break;
case mpIcon:
description = GetResStringWithNumber(IDP_MOUSEPOINTERICON, mpIcon);
break;
case mpSize:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZE, mpSize);
break;
case mpSizeNESW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZENESW, mpSizeNESW);
break;
case mpSizeNS:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZENS, mpSizeNS);
break;
case mpSizeNWSE:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZENWSE, mpSizeNWSE);
break;
case mpSizeEW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZEEW, mpSizeEW);
break;
case mpUpArrow:
description = GetResStringWithNumber(IDP_MOUSEPOINTERUPARROW, mpUpArrow);
break;
case mpHourglass:
description = GetResStringWithNumber(IDP_MOUSEPOINTERHOURGLASS, mpHourglass);
break;
case mpNoDrop:
description = GetResStringWithNumber(IDP_MOUSEPOINTERNODROP, mpNoDrop);
break;
case mpArrowHourglass:
description = GetResStringWithNumber(IDP_MOUSEPOINTERARROWHOURGLASS, mpArrowHourglass);
break;
case mpArrowQuestion:
description = GetResStringWithNumber(IDP_MOUSEPOINTERARROWQUESTION, mpArrowQuestion);
break;
case mpSizeAll:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSIZEALL, mpSizeAll);
break;
case mpHand:
description = GetResStringWithNumber(IDP_MOUSEPOINTERHAND, mpHand);
break;
case mpInsertMedia:
description = GetResStringWithNumber(IDP_MOUSEPOINTERINSERTMEDIA, mpInsertMedia);
break;
case mpScrollAll:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLALL, mpScrollAll);
break;
case mpScrollN:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLN, mpScrollN);
break;
case mpScrollNE:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLNE, mpScrollNE);
break;
case mpScrollE:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLE, mpScrollE);
break;
case mpScrollSE:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLSE, mpScrollSE);
break;
case mpScrollS:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLS, mpScrollS);
break;
case mpScrollSW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLSW, mpScrollSW);
break;
case mpScrollW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLW, mpScrollW);
break;
case mpScrollNW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLNW, mpScrollNW);
break;
case mpScrollNS:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLNS, mpScrollNS);
break;
case mpScrollEW:
description = GetResStringWithNumber(IDP_MOUSEPOINTERSCROLLEW, mpScrollEW);
break;
case mpCustom:
description = GetResStringWithNumber(IDP_MOUSEPOINTERCUSTOM, mpCustom);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE:
switch(cookie) {
case odistClassic:
description = GetResStringWithNumber(IDP_OLEDRAGIMAGESTYLECLASSIC, odistClassic);
break;
case odistAeroIfAvailable:
description = GetResStringWithNumber(IDP_OLEDRAGIMAGESTYLEAERO, odistAeroIfAvailable);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP:
switch(cookie) {
case rfoddNoDragDrop:
description = GetResStringWithNumber(IDP_REGISTERFOROLEDRAGDROPNONE, rfoddNoDragDrop);
break;
case rfoddNativeDragDrop:
description = GetResStringWithNumber(IDP_REGISTERFOROLEDRAGDROPNATIVE, rfoddNativeDragDrop);
break;
case rfoddAdvancedDragDrop:
description = GetResStringWithNumber(IDP_REGISTERFOROLEDRAGDROPADVANCED, rfoddAdvancedDragDrop);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_RIGHTTOLEFT:
switch(cookie) {
case 0:
description = GetResStringWithNumber(IDP_RIGHTTOLEFTNONE, 0);
break;
case rtlText:
description = GetResStringWithNumber(IDP_RIGHTTOLEFTTEXT, rtlText);
break;
case rtlLayout:
description = GetResStringWithNumber(IDP_RIGHTTOLEFTLAYOUT, rtlLayout);
break;
case rtlText | rtlLayout:
description = GetResStringWithNumber(IDP_RIGHTTOLEFTTEXTLAYOUT, rtlText | rtlLayout);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_STYLE:
switch(cookie) {
case sTabs:
description = GetResStringWithNumber(IDP_STYLETABS, sTabs);
break;
case sButtons:
description = GetResStringWithNumber(IDP_STYLEBUTTONS, sButtons);
break;
case sFlatButtons:
description = GetResStringWithNumber(IDP_STYLEFLATBUTTONS, sFlatButtons);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT:
switch(cookie) {
case tcaNormal:
description = GetResStringWithNumber(IDP_TABCAPTIONALIGNMENTNORMAL, tcaNormal);
break;
case tcaForceIconLeft:
description = GetResStringWithNumber(IDP_TABCAPTIONALIGNMENTFORCEICONLEFT, tcaForceIconLeft);
break;
case tcaForceCaptionLeft:
description = GetResStringWithNumber(IDP_TABCAPTIONALIGNMENTFORCECAPTIONLEFT, tcaForceCaptionLeft);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
case DISPID_TABSTRIPCTL_TABPLACEMENT:
switch(cookie) {
case tpTop:
description = GetResStringWithNumber(IDP_TABPLACEMENTTOP, tpTop);
break;
case tpBottom:
description = GetResStringWithNumber(IDP_TABPLACEMENTBOTTOM, tpBottom);
break;
case tpLeft:
description = GetResStringWithNumber(IDP_TABPLACEMENTLEFT, tpLeft);
break;
case tpRight:
description = GetResStringWithNumber(IDP_TABPLACEMENTRIGHT, tpRight);
break;
default:
return DISP_E_BADINDEX;
break;
}
break;
default:
return DISP_E_BADINDEX;
break;
}
return S_OK;
}
//////////////////////////////////////////////////////////////////////
// implementation of ISpecifyPropertyPages
STDMETHODIMP TabStrip::GetPages(CAUUID* pPropertyPages)
{
if(!pPropertyPages) {
return E_POINTER;
}
pPropertyPages->cElems = 4;
pPropertyPages->pElems = static_cast<LPGUID>(CoTaskMemAlloc(sizeof(GUID) * pPropertyPages->cElems));
if(pPropertyPages->pElems) {
pPropertyPages->pElems[0] = CLSID_CommonProperties;
pPropertyPages->pElems[1] = CLSID_StockColorPage;
pPropertyPages->pElems[2] = CLSID_StockFontPage;
pPropertyPages->pElems[3] = CLSID_StockPicturePage;
return S_OK;
}
return E_OUTOFMEMORY;
}
// implementation of ISpecifyPropertyPages
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of IOleObject
STDMETHODIMP TabStrip::DoVerb(LONG verbID, LPMSG pMessage, IOleClientSite* pActiveSite, LONG reserved, HWND hWndParent, LPCRECT pBoundingRectangle)
{
switch(verbID) {
case 1: // About...
return DoVerbAbout(hWndParent);
break;
default:
return IOleObjectImpl<TabStrip>::DoVerb(verbID, pMessage, pActiveSite, reserved, hWndParent, pBoundingRectangle);
break;
}
}
STDMETHODIMP TabStrip::EnumVerbs(IEnumOLEVERB** ppEnumerator)
{
static OLEVERB oleVerbs[3] = {
{OLEIVERB_UIACTIVATE, L"&Edit", 0, OLEVERBATTRIB_NEVERDIRTIES | OLEVERBATTRIB_ONCONTAINERMENU},
{OLEIVERB_PROPERTIES, L"&Properties...", 0, OLEVERBATTRIB_ONCONTAINERMENU},
{1, L"&About...", 0, OLEVERBATTRIB_NEVERDIRTIES | OLEVERBATTRIB_ONCONTAINERMENU},
};
return EnumOLEVERB::CreateInstance(oleVerbs, 3, ppEnumerator);
}
// implementation of IOleObject
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// implementation of IOleControl
STDMETHODIMP TabStrip::GetControlInfo(LPCONTROLINFO pControlInfo)
{
ATLASSERT_POINTER(pControlInfo, CONTROLINFO);
if(!pControlInfo) {
return E_POINTER;
}
// our control can have an accelerator
pControlInfo->cb = sizeof(CONTROLINFO);
pControlInfo->hAccel = properties.hAcceleratorTable;
pControlInfo->cAccel = static_cast<USHORT>(properties.hAcceleratorTable ? CopyAcceleratorTable(properties.hAcceleratorTable, NULL, 0) : 0);
pControlInfo->dwFlags = 0;
return S_OK;
}
STDMETHODIMP TabStrip::OnMnemonic(LPMSG pMessage)
{
if(GetStyle() & WS_DISABLED) {
return S_OK;
}
ATLASSERT(pMessage->message == WM_SYSKEYDOWN);
SHORT pressedKeyCode = static_cast<SHORT>(pMessage->wParam);
int tabToSelect = -1;
TCITEM tab = {0};
tab.mask = TCIF_TEXT;
tab.cchTextMax = MAX_TABTEXTLENGTH;
tab.pszText = static_cast<LPTSTR>(HeapAlloc(GetProcessHeap(), 0, (tab.cchTextMax + 1) * sizeof(TCHAR)));
if(tab.pszText) {
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
if(tab.pszText) {
for(int i = lstrlen(tab.pszText) - 1; i > 0; --i) {
if((tab.pszText[i - 1] == TEXT('&')) && (tab.pszText[i] != TEXT('&'))) {
// TODO: Does this work with MFC?
if((VkKeyScan(tab.pszText[i]) == pressedKeyCode) || (VkKeyScan(static_cast<TCHAR>(tolower(tab.pszText[i]))) == pressedKeyCode)) {
tabToSelect = tabIndex;
break;
}
}
}
}
}
HeapFree(GetProcessHeap(), 0, tab.pszText);
}
if(tabToSelect != -1) {
if(tabToSelect != SendMessage(TCM_GETCURSEL, 0, 0)) {
SendMessage(TCM_SETCURSEL, tabToSelect, 0);
}
}
return S_OK;
}
// implementation of IOleControl
//////////////////////////////////////////////////////////////////////
HRESULT TabStrip::DoVerbAbout(HWND hWndParent)
{
HRESULT hr = S_OK;
//hr = OnPreVerbAbout();
if(SUCCEEDED(hr)) {
AboutDlg dlg;
dlg.SetOwner(this);
dlg.DoModal(hWndParent);
hr = S_OK;
//hr = OnPostVerbAbout();
}
return hr;
}
HRESULT TabStrip::OnPropertyObjectChanged(DISPID propertyObject, DISPID /*objectProperty*/)
{
switch(propertyObject) {
case DISPID_TABSTRIPCTL_FONT:
if(!properties.useSystemFont) {
ApplyFont();
}
break;
}
return S_OK;
}
HRESULT TabStrip::OnPropertyObjectRequestEdit(DISPID /*propertyObject*/, DISPID /*objectProperty*/)
{
return S_OK;
}
STDMETHODIMP TabStrip::get_ActiveTab(ITabStripTab** ppActiveTab)
{
ATLASSERT_POINTER(ppActiveTab, ITabStripTab*);
if(!ppActiveTab) {
return E_POINTER;
}
if(IsWindow()) {
int activeTab = SendMessage(TCM_GETCURSEL, 0, 0);
ClassFactory::InitTabStripTab(activeTab, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppActiveTab));
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::putref_ActiveTab(ITabStripTab* pNewActiveTab)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_ACTIVETAB);
HRESULT hr = E_FAIL;
int newActiveTab = -1;
if(pNewActiveTab) {
LONG l = -1;
pNewActiveTab->get_Index(&l);
newActiveTab = l;
}
if(IsWindow()) {
SendMessage(TCM_SETCURSEL, newActiveTab, 0);
hr = S_OK;
}
FireOnChanged(DISPID_TABSTRIPCTL_ACTIVETAB);
return hr;
}
STDMETHODIMP TabStrip::get_AllowDragDrop(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.allowDragDrop = ((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_DETECTDRAGDROP) == TCS_EX_DETECTDRAGDROP);
}
*pValue = BOOL2VARIANTBOOL(properties.allowDragDrop);
return S_OK;
}
STDMETHODIMP TabStrip::put_AllowDragDrop(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_ALLOWDRAGDROP);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.allowDragDrop != b) {
/* We set the style before adjusting properties.allowDragDrop because we need the old value of
properties.allowDragDrop in OnSetExtendedStyle. */
if(IsWindow()) {
SendMessage(TCM_SETEXTENDEDSTYLE, TCS_EX_DETECTDRAGDROP, (b ? TCS_EX_DETECTDRAGDROP : 0));
}
properties.allowDragDrop = b;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_ALLOWDRAGDROP);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Appearance(AppearanceConstants* pValue)
{
ATLASSERT_POINTER(pValue, AppearanceConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
if(GetExStyle() & WS_EX_CLIENTEDGE) {
properties.appearance = a3D;
} else if(GetExStyle() & WS_EX_STATICEDGE) {
properties.appearance = a3DLight;
} else {
properties.appearance = a2D;
}
}
*pValue = properties.appearance;
return S_OK;
}
STDMETHODIMP TabStrip::put_Appearance(AppearanceConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_APPEARANCE);
if(properties.appearance != newValue) {
properties.appearance = newValue;
SetDirty(TRUE);
if(IsWindow()) {
switch(properties.appearance) {
case a2D:
ModifyStyleEx(WS_EX_CLIENTEDGE | WS_EX_STATICEDGE, 0, SWP_DRAWFRAME | SWP_FRAMECHANGED);
break;
case a3D:
ModifyStyleEx(WS_EX_STATICEDGE, WS_EX_CLIENTEDGE, SWP_DRAWFRAME | SWP_FRAMECHANGED);
break;
case a3DLight:
ModifyStyleEx(WS_EX_CLIENTEDGE, WS_EX_STATICEDGE, SWP_DRAWFRAME | SWP_FRAMECHANGED);
break;
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_APPEARANCE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_AppID(SHORT* pValue)
{
ATLASSERT_POINTER(pValue, SHORT);
if(!pValue) {
return E_POINTER;
}
*pValue = 10;
return S_OK;
}
STDMETHODIMP TabStrip::get_AppName(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
*pValue = SysAllocString(L"TabStrip");
return S_OK;
}
STDMETHODIMP TabStrip::get_AppShortName(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
*pValue = SysAllocString(L"TabStripCtl");
return S_OK;
}
STDMETHODIMP TabStrip::get_BorderStyle(BorderStyleConstants* pValue)
{
ATLASSERT_POINTER(pValue, BorderStyleConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.borderStyle = ((GetStyle() & WS_BORDER) == WS_BORDER ? bsFixedSingle : bsNone);
}
*pValue = properties.borderStyle;
return S_OK;
}
STDMETHODIMP TabStrip::put_BorderStyle(BorderStyleConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_BORDERSTYLE);
if(properties.borderStyle != newValue) {
properties.borderStyle = newValue;
SetDirty(TRUE);
if(IsWindow()) {
switch(properties.borderStyle) {
case bsNone:
ModifyStyle(WS_BORDER, 0, SWP_DRAWFRAME | SWP_FRAMECHANGED);
break;
case bsFixedSingle:
ModifyStyle(0, WS_BORDER, SWP_DRAWFRAME | SWP_FRAMECHANGED);
break;
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_BORDERSTYLE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Build(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
*pValue = VERSION_BUILD;
return S_OK;
}
STDMETHODIMP TabStrip::get_CaretTab(ITabStripTab** ppCaretTab)
{
ATLASSERT_POINTER(ppCaretTab, ITabStripTab*);
if(!ppCaretTab) {
return E_POINTER;
}
if(IsWindow()) {
int caretTab = SendMessage(TCM_GETCURFOCUS, 0, 0);
ClassFactory::InitTabStripTab(caretTab, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppCaretTab));
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::putref_CaretTab(ITabStripTab* pNewCaretTab)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_CARETTAB);
HRESULT hr = E_FAIL;
int newCaretTab = -1;
if(pNewCaretTab) {
LONG l = -1;
pNewCaretTab->get_Index(&l);
newCaretTab = l;
}
if(IsWindow()) {
SendMessage(TCM_SETCURFOCUS, newCaretTab, 0);
hr = S_OK;
}
FireOnChanged(DISPID_TABSTRIPCTL_CARETTAB);
return hr;
}
STDMETHODIMP TabStrip::get_CharSet(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
#ifdef UNICODE
*pValue = SysAllocString(L"Unicode");
#else
*pValue = SysAllocString(L"ANSI");
#endif
return S_OK;
}
STDMETHODIMP TabStrip::get_CloseableTabs(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
*pValue = BOOL2VARIANTBOOL(properties.closeableTabs);
return S_OK;
}
STDMETHODIMP TabStrip::put_CloseableTabs(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_CLOSEABLETABS);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.closeableTabs != b) {
properties.closeableTabs = b;
SetDirty(TRUE);
if(properties.closeableTabs) {
mouseStatus.overCloseButton = -1;
mouseStatus.overCloseButtonOnMouseDown = -1;
}
FireViewChange();
FireOnChanged(DISPID_TABSTRIPCTL_CLOSEABLETABS);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_CloseableTabsMode(CloseableTabsModeConstants* pValue)
{
ATLASSERT_POINTER(pValue, CloseableTabsModeConstants);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.closeableTabsMode;
return S_OK;
}
STDMETHODIMP TabStrip::put_CloseableTabsMode(CloseableTabsModeConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_CLOSEABLETABSMODE);
if(properties.closeableTabsMode != newValue) {
properties.closeableTabsMode = newValue;
SetDirty(TRUE);
if(properties.closeableTabs) {
mouseStatus.overCloseButton = -1;
mouseStatus.overCloseButtonOnMouseDown = -1;
}
FireViewChange();
FireOnChanged(DISPID_TABSTRIPCTL_CLOSEABLETABSMODE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DisabledEvents(DisabledEventsConstants* pValue)
{
ATLASSERT_POINTER(pValue, DisabledEventsConstants);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.disabledEvents;
return S_OK;
}
STDMETHODIMP TabStrip::put_DisabledEvents(DisabledEventsConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_DISABLEDEVENTS);
if(properties.disabledEvents != newValue) {
if((properties.disabledEvents & deMouseEvents) != (newValue & deMouseEvents)) {
if(IsWindow()) {
if(!properties.closeableTabs && ((newValue & deMouseEvents) == deMouseEvents)) {
// nothing to do
} else {
TRACKMOUSEEVENT trackingOptions = {0};
trackingOptions.cbSize = sizeof(trackingOptions);
trackingOptions.hwndTrack = *this;
trackingOptions.dwFlags = TME_HOVER | TME_LEAVE | TME_CANCEL;
TrackMouseEvent(&trackingOptions);
tabUnderMouse = -1;
}
}
}
properties.disabledEvents = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_DISABLEDEVENTS);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DisplayAreaHeight(OLE_YSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
CRect rc;
GetWindowRect(&rc);
ScreenToClient(&rc);
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&rc));
*pValue = rc.Height();
} else {
*pValue = 0;
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DisplayAreaLeft(OLE_XPOS_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_XPOS_PIXELS);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
RECT rc = {0};
GetWindowRect(&rc);
ScreenToClient(&rc);
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&rc));
*pValue = rc.left;
} else {
*pValue = 0;
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DisplayAreaTop(OLE_YPOS_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
RECT rc = {0};
GetWindowRect(&rc);
ScreenToClient(&rc);
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&rc));
*pValue = rc.top;
} else {
*pValue = 0;
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DisplayAreaWidth(OLE_XSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_XSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
CRect rc;
GetWindowRect(&rc);
ScreenToClient(&rc);
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&rc));
*pValue = rc.Width();
} else {
*pValue = 0;
}
return S_OK;
}
//
//STDMETHODIMP TabStrip::get_DontRedraw(VARIANT_BOOL* pValue)
//{
// ATLASSERT_POINTER(pValue, VARIANT_BOOL);
// if(!pValue) {
// return E_POINTER;
// }
//
// *pValue = BOOL2VARIANTBOOL(properties.dontRedraw);
// return S_OK;
//}
//
//STDMETHODIMP TabStrip::put_DontRedraw(VARIANT_BOOL newValue)
//{
// PUTPROPPROLOG(DISPID_TABSTRIPCTL_DONTREDRAW);
//
// UINT b = VARIANTBOOL2BOOL(newValue);
// if(properties.dontRedraw != b) {
// properties.dontRedraw = b;
// SetDirty(TRUE);
// if(IsWindow()) {
// SetRedraw(!b);
// }
// FireOnChanged(DISPID_TABSTRIPCTL_DONTREDRAW);
// }
// return S_OK;
//}
STDMETHODIMP TabStrip::get_DragActivateTime(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.dragActivateTime;
return S_OK;
}
STDMETHODIMP TabStrip::put_DragActivateTime(LONG newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_DRAGACTIVATETIME);
if((newValue < -1) || (newValue > 60000)) {
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
if(properties.dragActivateTime != newValue) {
properties.dragActivateTime = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_DRAGACTIVATETIME);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DraggedTabs(ITabStripTabContainer** ppTabs)
{
ATLASSERT_POINTER(ppTabs, ITabStripTabContainer*);
if(!ppTabs) {
return E_POINTER;
}
*ppTabs = NULL;
if(dragDropStatus.pDraggedTabs) {
return dragDropStatus.pDraggedTabs->Clone(ppTabs);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DragScrollTimeBase(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.dragScrollTimeBase;
return S_OK;
}
STDMETHODIMP TabStrip::put_DragScrollTimeBase(LONG newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_DRAGSCROLLTIMEBASE);
if((newValue < -1) || (newValue > 60000)) {
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
if(properties.dragScrollTimeBase != newValue) {
properties.dragScrollTimeBase = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_DRAGSCROLLTIMEBASE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_DropHilitedTab(ITabStripTab** ppDropHilitedTab)
{
ATLASSERT_POINTER(ppDropHilitedTab, ITabStripTab*);
if(!ppDropHilitedTab) {
return E_POINTER;
}
ClassFactory::InitTabStripTab(cachedSettings.dropHilitedTab, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppDropHilitedTab));
return S_OK;
}
STDMETHODIMP TabStrip::putref_DropHilitedTab(ITabStripTab* pNewDropHilitedTab)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_DROPHILITEDTAB);
HRESULT hr = E_FAIL;
int newDropHilitedTab = -1;
if(pNewDropHilitedTab) {
LONG l = -1;
pNewDropHilitedTab->get_Index(&l);
newDropHilitedTab = l;
}
if(cachedSettings.dropHilitedTab == newDropHilitedTab) {
return S_OK;
}
if(IsWindow()) {
dragDropStatus.HideDragImage(TRUE);
if(newDropHilitedTab == -1) {
if(SendMessage(TCM_HIGHLIGHTITEM, cachedSettings.dropHilitedTab, MAKELPARAM(FALSE, 0))) {
hr = S_OK;
}
} else {
if(SendMessage(TCM_HIGHLIGHTITEM, newDropHilitedTab, MAKELPARAM(TRUE, 0))) {
hr = S_OK;
}
}
dragDropStatus.ShowDragImage(TRUE);
}
FireOnChanged(DISPID_TABSTRIPCTL_DROPHILITEDTAB);
return hr;
}
STDMETHODIMP TabStrip::get_Enabled(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.enabled = !(GetStyle() & WS_DISABLED);
}
*pValue = BOOL2VARIANTBOOL(properties.enabled);
return S_OK;
}
STDMETHODIMP TabStrip::put_Enabled(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_ENABLED);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.enabled != b) {
properties.enabled = b;
SetDirty(TRUE);
if(IsWindow()) {
EnableWindow(properties.enabled);
FireViewChange();
}
if(!properties.enabled) {
IOleInPlaceObject_UIDeactivate();
}
FireOnChanged(DISPID_TABSTRIPCTL_ENABLED);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_FixedTabWidth(OLE_XSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.fixedTabWidth;
return S_OK;
}
STDMETHODIMP TabStrip::put_FixedTabWidth(OLE_XSIZE_PIXELS newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_FIXEDTABWIDTH);
if(newValue < 0) {
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
if(properties.fixedTabWidth != newValue) {
properties.fixedTabWidth = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETITEMSIZE, 0, MAKELPARAM(properties.fixedTabWidth, properties.tabHeight));
}
FireOnChanged(DISPID_TABSTRIPCTL_FIXEDTABWIDTH);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_FocusOnButtonDown(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.focusOnButtonDown = ((GetStyle() & TCS_FOCUSONBUTTONDOWN) == TCS_FOCUSONBUTTONDOWN);
}
*pValue = BOOL2VARIANTBOOL(properties.focusOnButtonDown);
return S_OK;
}
STDMETHODIMP TabStrip::put_FocusOnButtonDown(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_FOCUSONBUTTONDOWN);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.focusOnButtonDown != b) {
properties.focusOnButtonDown = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.focusOnButtonDown) {
ModifyStyle(0, TCS_FOCUSONBUTTONDOWN);
} else {
ModifyStyle(TCS_FOCUSONBUTTONDOWN, 0);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_FOCUSONBUTTONDOWN);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Font(IFontDisp** ppFont)
{
ATLASSERT_POINTER(ppFont, IFontDisp*);
if(!ppFont) {
return E_POINTER;
}
if(*ppFont) {
(*ppFont)->Release();
*ppFont = NULL;
}
if(properties.font.pFontDisp) {
properties.font.pFontDisp->QueryInterface(IID_IFontDisp, reinterpret_cast<LPVOID*>(ppFont));
}
return S_OK;
}
STDMETHODIMP TabStrip::put_Font(IFontDisp* pNewFont)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_FONT);
if(properties.font.pFontDisp != pNewFont) {
properties.font.StopWatching();
if(properties.font.pFontDisp) {
properties.font.pFontDisp->Release();
properties.font.pFontDisp = NULL;
}
if(pNewFont) {
CComQIPtr<IFont, &IID_IFont> pFont(pNewFont);
if(pFont) {
CComPtr<IFont> pClonedFont = NULL;
pFont->Clone(&pClonedFont);
if(pClonedFont) {
pClonedFont->QueryInterface(IID_IFontDisp, reinterpret_cast<LPVOID*>(&properties.font.pFontDisp));
}
}
}
properties.font.StartWatching();
}
if(!properties.useSystemFont) {
ApplyFont();
}
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_FONT);
return S_OK;
}
STDMETHODIMP TabStrip::putref_Font(IFontDisp* pNewFont)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_FONT);
if(properties.font.pFontDisp != pNewFont) {
properties.font.StopWatching();
if(properties.font.pFontDisp) {
properties.font.pFontDisp->Release();
properties.font.pFontDisp = NULL;
}
if(pNewFont) {
pNewFont->QueryInterface(IID_IFontDisp, reinterpret_cast<LPVOID*>(&properties.font.pFontDisp));
}
properties.font.StartWatching();
} else if(pNewFont) {
pNewFont->AddRef();
}
if(!properties.useSystemFont) {
ApplyFont();
}
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_FONT);
return S_OK;
}
STDMETHODIMP TabStrip::get_hDragImageList(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
if(dragDropStatus.IsDragging()) {
*pValue = HandleToLong(dragDropStatus.hDragImageList);
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::get_hHighResImageList(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
*pValue = HandleToLong(cachedSettings.hHighResImageList);
return S_OK;
}
STDMETHODIMP TabStrip::put_hHighResImageList(OLE_HANDLE newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HHIGHRESIMAGELIST);
if(cachedSettings.hHighResImageList != reinterpret_cast<HIMAGELIST>(LongToHandle(newValue))) {
cachedSettings.hHighResImageList = reinterpret_cast<HIMAGELIST>(LongToHandle(newValue));
FireOnChanged(DISPID_TABSTRIPCTL_HHIGHRESIMAGELIST);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_hImageList(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
*pValue = HandleToLong(cachedSettings.hImageList);
} else {
*pValue = NULL;
}
return S_OK;
}
STDMETHODIMP TabStrip::put_hImageList(OLE_HANDLE newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HIMAGELIST);
if(IsWindow()) {
SendMessage(TCM_SETIMAGELIST, 0, newValue);
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_HIMAGELIST);
return S_OK;
}
STDMETHODIMP TabStrip::get_HorizontalPadding(OLE_XSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_XSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.horizontalPadding;
return S_OK;
}
STDMETHODIMP TabStrip::put_HorizontalPadding(OLE_XSIZE_PIXELS newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HORIZONTALPADDING);
if(properties.horizontalPadding != newValue) {
properties.horizontalPadding = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETPADDING, 0, MAKELPARAM(properties.horizontalPadding, properties.verticalPadding));
// temporarily toggle the TCS_FIXEDWIDTH style, so that SysTabControl32 recalculates the tab metrics
if(GetStyle() & TCS_FIXEDWIDTH) {
ModifyStyle(TCS_FIXEDWIDTH, 0);
ModifyStyle(0, TCS_FIXEDWIDTH);
} else {
ModifyStyle(0, TCS_FIXEDWIDTH);
ModifyStyle(TCS_FIXEDWIDTH, 0);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_HORIZONTALPADDING);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_HotTracking(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.hotTracking = ((GetStyle() & TCS_HOTTRACK) == TCS_HOTTRACK);
}
*pValue = BOOL2VARIANTBOOL(properties.hotTracking);
return S_OK;
}
STDMETHODIMP TabStrip::put_HotTracking(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HOTTRACKING);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.hotTracking != b) {
properties.hotTracking = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.hotTracking) {
ModifyStyle(0, TCS_HOTTRACK);
} else {
ModifyStyle(TCS_HOTTRACK, 0);
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_HOTTRACKING);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_HoverTime(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.hoverTime;
return S_OK;
}
STDMETHODIMP TabStrip::put_HoverTime(LONG newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HOVERTIME);
if((newValue < 0) && (newValue != -1)) {
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
if(properties.hoverTime != newValue) {
properties.hoverTime = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_HOVERTIME);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_hWnd(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
*pValue = HandleToLong(static_cast<HWND>(*this));
return S_OK;
}
STDMETHODIMP TabStrip::get_hWndArrowButtons(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
*pValue = HandleToLong(static_cast<HWND>(GetDlgItem(1)));
}
return S_OK;
}
STDMETHODIMP TabStrip::get_hWndToolTip(OLE_HANDLE* pValue)
{
ATLASSERT_POINTER(pValue, OLE_HANDLE);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
*pValue = HandleToLong(reinterpret_cast<HWND>(SendMessage(TCM_GETTOOLTIPS, 0, 0)));
}
return S_OK;
}
STDMETHODIMP TabStrip::put_hWndToolTip(OLE_HANDLE newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_HWNDTOOLTIP);
if(IsWindow()) {
SendMessage(TCM_SETTOOLTIPS, reinterpret_cast<WPARAM>(LongToHandle(newValue)), 0);
}
FireOnChanged(DISPID_TABSTRIPCTL_HWNDTOOLTIP);
return S_OK;
}
STDMETHODIMP TabStrip::get_InsertMarkColor(OLE_COLOR* pValue)
{
ATLASSERT_POINTER(pValue, OLE_COLOR);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
COLORREF color = static_cast<COLORREF>(SendMessage(TCM_GETINSERTMARKCOLOR, 0, 0));
if(color == CLR_NONE) {
properties.insertMarkColor = 0;
} else if(color != OLECOLOR2COLORREF(properties.insertMarkColor)) {
properties.insertMarkColor = color;
}
}
*pValue = properties.insertMarkColor;
return S_OK;
}
STDMETHODIMP TabStrip::put_InsertMarkColor(OLE_COLOR newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_INSERTMARKCOLOR);
if(properties.insertMarkColor != newValue) {
properties.insertMarkColor = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETINSERTMARKCOLOR, 0, OLECOLOR2COLORREF(properties.insertMarkColor));
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_INSERTMARKCOLOR);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_IsRelease(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
#ifdef NDEBUG
*pValue = VARIANT_TRUE;
#else
*pValue = VARIANT_FALSE;
#endif
return S_OK;
}
STDMETHODIMP TabStrip::get_MinTabWidth(OLE_XSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.minTabWidth;
return S_OK;
}
STDMETHODIMP TabStrip::put_MinTabWidth(OLE_XSIZE_PIXELS newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MINTABWIDTH);
if((newValue < 0) && (newValue != -1)) {
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
if(properties.minTabWidth != newValue) {
properties.minTabWidth = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETMINTABWIDTH, 0, properties.minTabWidth);
}
FireOnChanged(DISPID_TABSTRIPCTL_MINTABWIDTH);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_MouseIcon(IPictureDisp** ppMouseIcon)
{
ATLASSERT_POINTER(ppMouseIcon, IPictureDisp*);
if(!ppMouseIcon) {
return E_POINTER;
}
if(*ppMouseIcon) {
(*ppMouseIcon)->Release();
*ppMouseIcon = NULL;
}
if(properties.mouseIcon.pPictureDisp) {
properties.mouseIcon.pPictureDisp->QueryInterface(IID_IPictureDisp, reinterpret_cast<LPVOID*>(ppMouseIcon));
}
return S_OK;
}
STDMETHODIMP TabStrip::put_MouseIcon(IPictureDisp* pNewMouseIcon)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MOUSEICON);
if(properties.mouseIcon.pPictureDisp != pNewMouseIcon) {
properties.mouseIcon.StopWatching();
if(properties.mouseIcon.pPictureDisp) {
properties.mouseIcon.pPictureDisp->Release();
properties.mouseIcon.pPictureDisp = NULL;
}
if(pNewMouseIcon) {
// clone the picture by storing it into a stream
CComQIPtr<IPersistStream, &IID_IPersistStream> pPersistStream(pNewMouseIcon);
if(pPersistStream) {
ULARGE_INTEGER pictureSize = {0};
pPersistStream->GetSizeMax(&pictureSize);
HGLOBAL hGlobalMem = GlobalAlloc(GHND, pictureSize.LowPart);
if(hGlobalMem) {
CComPtr<IStream> pStream = NULL;
CreateStreamOnHGlobal(hGlobalMem, TRUE, &pStream);
if(pStream) {
if(SUCCEEDED(pPersistStream->Save(pStream, FALSE))) {
LARGE_INTEGER startPosition = {0};
pStream->Seek(startPosition, STREAM_SEEK_SET, NULL);
OleLoadPicture(pStream, startPosition.LowPart, FALSE, IID_IPictureDisp, reinterpret_cast<LPVOID*>(&properties.mouseIcon.pPictureDisp));
}
pStream.Release();
}
GlobalFree(hGlobalMem);
}
}
}
properties.mouseIcon.StartWatching();
}
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_MOUSEICON);
return S_OK;
}
STDMETHODIMP TabStrip::putref_MouseIcon(IPictureDisp* pNewMouseIcon)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MOUSEICON);
if(properties.mouseIcon.pPictureDisp != pNewMouseIcon) {
properties.mouseIcon.StopWatching();
if(properties.mouseIcon.pPictureDisp) {
properties.mouseIcon.pPictureDisp->Release();
properties.mouseIcon.pPictureDisp = NULL;
}
if(pNewMouseIcon) {
pNewMouseIcon->QueryInterface(IID_IPictureDisp, reinterpret_cast<LPVOID*>(&properties.mouseIcon.pPictureDisp));
}
properties.mouseIcon.StartWatching();
} else if(pNewMouseIcon) {
pNewMouseIcon->AddRef();
}
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_MOUSEICON);
return S_OK;
}
STDMETHODIMP TabStrip::get_MousePointer(MousePointerConstants* pValue)
{
ATLASSERT_POINTER(pValue, MousePointerConstants);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.mousePointer;
return S_OK;
}
STDMETHODIMP TabStrip::put_MousePointer(MousePointerConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MOUSEPOINTER);
if(properties.mousePointer != newValue) {
properties.mousePointer = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_MOUSEPOINTER);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_MultiRow(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.multiRow = ((GetStyle() & TCS_MULTILINE) == TCS_MULTILINE);
}
*pValue = BOOL2VARIANTBOOL(properties.multiRow);
return S_OK;
}
STDMETHODIMP TabStrip::put_MultiRow(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MULTIROW);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.multiRow != b) {
properties.multiRow = b;
SetDirty(TRUE);
if(!properties.multiRow) {
// single line and tpLeft/tpRight are incompatible
TabPlacementConstants tabPlacement = static_cast<TabPlacementConstants>(0);
get_TabPlacement(&tabPlacement);
switch(tabPlacement) {
case tpLeft:
case tpRight:
put_TabPlacement(tpTop);
break;
}
// single line and scroll to opposite are incompatible
put_ScrollToOpposite(VARIANT_FALSE);
}
if(IsWindow()) {
if(properties.multiRow) {
ModifyStyle(TCS_SINGLELINE, TCS_MULTILINE);
} else {
ModifyStyle(TCS_MULTILINE, TCS_SINGLELINE);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_MULTIROW);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_MultiSelect(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.multiSelect = ((GetStyle() & TCS_MULTISELECT) == TCS_MULTISELECT);
}
*pValue = BOOL2VARIANTBOOL(properties.multiSelect);
return S_OK;
}
STDMETHODIMP TabStrip::put_MultiSelect(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_MULTISELECT);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.multiSelect != b) {
properties.multiSelect = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.multiSelect) {
ModifyStyle(0, TCS_MULTISELECT);
} else {
ModifyStyle(TCS_MULTISELECT, 0);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_MULTISELECT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_OLEDragImageStyle(OLEDragImageStyleConstants* pValue)
{
ATLASSERT_POINTER(pValue, OLEDragImageStyleConstants);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.oleDragImageStyle;
return S_OK;
}
STDMETHODIMP TabStrip::put_OLEDragImageStyle(OLEDragImageStyleConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE);
if(properties.oleDragImageStyle != newValue) {
properties.oleDragImageStyle = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_OLEDRAGIMAGESTYLE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_OwnerDrawn(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.ownerDrawn = ((GetStyle() & TCS_OWNERDRAWFIXED) == TCS_OWNERDRAWFIXED);
}
*pValue = BOOL2VARIANTBOOL(properties.ownerDrawn);
return S_OK;
}
STDMETHODIMP TabStrip::put_OwnerDrawn(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_OWNERDRAWN);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.ownerDrawn != b) {
properties.ownerDrawn = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.ownerDrawn) {
ModifyStyle(0, TCS_OWNERDRAWFIXED);
} else {
ModifyStyle(TCS_OWNERDRAWFIXED, 0);
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_OWNERDRAWN);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_ProcessContextMenuKeys(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
*pValue = BOOL2VARIANTBOOL(properties.processContextMenuKeys);
return S_OK;
}
STDMETHODIMP TabStrip::put_ProcessContextMenuKeys(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_PROCESSCONTEXTMENUKEYS);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.processContextMenuKeys != b) {
properties.processContextMenuKeys = b;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_PROCESSCONTEXTMENUKEYS);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Programmer(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
*pValue = SysAllocString(L"Timo \"TimoSoft\" Kunze");
return S_OK;
}
STDMETHODIMP TabStrip::get_RaggedTabRows(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.raggedTabRows = ((GetStyle() & TCS_RAGGEDRIGHT) == TCS_RAGGEDRIGHT);
}
*pValue = BOOL2VARIANTBOOL(properties.raggedTabRows);
return S_OK;
}
STDMETHODIMP TabStrip::put_RaggedTabRows(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_RAGGEDTABROWS);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.raggedTabRows != b) {
properties.raggedTabRows = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.raggedTabRows) {
ModifyStyle(0, TCS_RAGGEDRIGHT);
} else {
ModifyStyle(TCS_RAGGEDRIGHT, 0);
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_RAGGEDTABROWS);
}
return S_OK;
}
/*STDMETHODIMP TabStrip::get_ReflectContextMenuMessages(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
*pValue = BOOL2VARIANTBOOL(properties.reflectContextMenuMessages);
return S_OK;
}
STDMETHODIMP TabStrip::put_ReflectContextMenuMessages(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_REFLECTCONTEXTMENUMESSAGES);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.reflectContextMenuMessages != b) {
properties.reflectContextMenuMessages = b;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_REFLECTCONTEXTMENUMESSAGES);
}
return S_OK;
}*/
STDMETHODIMP TabStrip::get_RegisterForOLEDragDrop(RegisterForOLEDragDropConstants* pValue)
{
ATLASSERT_POINTER(pValue, RegisterForOLEDragDropConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
if((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_REGISTERDROP) == TCS_EX_REGISTERDROP) {
properties.registerForOLEDragDrop = rfoddNativeDragDrop;
}
}
*pValue = properties.registerForOLEDragDrop;
return S_OK;
}
STDMETHODIMP TabStrip::put_RegisterForOLEDragDrop(RegisterForOLEDragDropConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP);
if(properties.registerForOLEDragDrop != newValue) {
properties.registerForOLEDragDrop = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETEXTENDEDSTYLE, TCS_EX_REGISTERDROP, 0);
RevokeDragDrop(*this);
switch(properties.registerForOLEDragDrop) {
case rfoddNativeDragDrop:
SendMessage(TCM_SETEXTENDEDSTYLE, TCS_EX_REGISTERDROP, TCS_EX_REGISTERDROP);
break;
case rfoddAdvancedDragDrop: {
ATLVERIFY(RegisterDragDrop(*this, static_cast<IDropTarget*>(this)) == S_OK);
break;
}
}
}
FireOnChanged(DISPID_TABSTRIPCTL_REGISTERFOROLEDRAGDROP);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_RightToLeft(RightToLeftConstants* pValue)
{
ATLASSERT_POINTER(pValue, RightToLeftConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.rightToLeft = static_cast<RightToLeftConstants>(0);
DWORD style = GetExStyle();
if(style & WS_EX_LAYOUTRTL) {
properties.rightToLeft = static_cast<RightToLeftConstants>(static_cast<long>(properties.rightToLeft) | rtlLayout);
}
if(style & WS_EX_RTLREADING) {
properties.rightToLeft = static_cast<RightToLeftConstants>(static_cast<long>(properties.rightToLeft) | rtlText);
}
}
*pValue = properties.rightToLeft;
return S_OK;
}
STDMETHODIMP TabStrip::put_RightToLeft(RightToLeftConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_RIGHTTOLEFT);
if(properties.rightToLeft != newValue) {
BOOL changingLayout = ((properties.rightToLeft & rtlLayout) != (newValue & rtlLayout));
properties.rightToLeft = newValue;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.rightToLeft & rtlLayout) {
if(properties.rightToLeft & rtlText) {
ModifyStyleEx(WS_EX_LTRREADING, WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT | WS_EX_RTLREADING);
} else {
ModifyStyleEx(WS_EX_RTLREADING, WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT | WS_EX_LTRREADING);
}
} else {
if(properties.rightToLeft & rtlText) {
ModifyStyleEx(WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT | WS_EX_LTRREADING, WS_EX_RTLREADING);
} else {
ModifyStyleEx(WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT | WS_EX_RTLREADING, WS_EX_LTRREADING);
}
}
if(changingLayout) {
// this will force an update of the up-down control's position
CRect clientRectangle;
GetClientRect(&clientRectangle);
SendMessage(WM_SIZE, SIZE_RESTORED, MAKELPARAM(clientRectangle.Width(), clientRectangle.Height()));
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_RIGHTTOLEFT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_ScrollToOpposite(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.scrollToOpposite = ((GetStyle() & TCS_SCROLLOPPOSITE) == TCS_SCROLLOPPOSITE);
}
*pValue = BOOL2VARIANTBOOL(properties.scrollToOpposite);
return S_OK;
}
STDMETHODIMP TabStrip::put_ScrollToOpposite(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_SCROLLTOOPPOSITE);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.scrollToOpposite != b) {
if(IsWindow()) {
if(IsInDesignMode()) {
//RecreateControlWindow();
MessageBox(TEXT("The control window won't apply this setting until the Form it is placed on is closed and reloaded."), TEXT("TabStrip - ScrollToOpposite"), MB_ICONINFORMATION);
} else {
// Set not supported at runtime - raise VB runtime error 382
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 382);
}
}
properties.scrollToOpposite = b;
SetDirty(TRUE);
if(properties.scrollToOpposite) {
// single line and scroll to opposite are incompatible
put_MultiRow(VARIANT_TRUE);
// buttons and scroll to opposite are incompatible
put_Style(sTabs);
}
FireOnChanged(DISPID_TABSTRIPCTL_SCROLLTOOPPOSITE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_ShowButtonSeparators(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.showButtonSeparators = ((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_FLATSEPARATORS) == TCS_EX_FLATSEPARATORS);
}
*pValue = BOOL2VARIANTBOOL(properties.showButtonSeparators);
return S_OK;
}
STDMETHODIMP TabStrip::put_ShowButtonSeparators(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_SHOWBUTTONSEPARATORS);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.showButtonSeparators != b) {
properties.showButtonSeparators = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.showButtonSeparators) {
SendMessage(TCM_SETEXTENDEDSTYLE, TCS_EX_FLATSEPARATORS, TCS_EX_FLATSEPARATORS);
} else {
SendMessage(TCM_SETEXTENDEDSTYLE, TCS_EX_FLATSEPARATORS, 0);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_SHOWBUTTONSEPARATORS);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_ShowDragImage(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!dragDropStatus.IsDragging()) {
return E_FAIL;
}
*pValue = BOOL2VARIANTBOOL(dragDropStatus.IsDragImageVisible());
return S_OK;
}
STDMETHODIMP TabStrip::put_ShowDragImage(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_SHOWDRAGIMAGE);
if(!dragDropStatus.hDragImageList && !dragDropStatus.pDropTargetHelper) {
return E_FAIL;
}
if(newValue == VARIANT_FALSE) {
dragDropStatus.HideDragImage(FALSE);
} else {
dragDropStatus.ShowDragImage(FALSE);
}
FireOnChanged(DISPID_TABSTRIPCTL_SHOWDRAGIMAGE);
return S_OK;
}
STDMETHODIMP TabStrip::get_ShowToolTips(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.showToolTips = ((GetStyle() & TCS_TOOLTIPS) == TCS_TOOLTIPS);
}
*pValue = BOOL2VARIANTBOOL(properties.showToolTips);
return S_OK;
}
STDMETHODIMP TabStrip::put_ShowToolTips(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_SHOWTOOLTIPS);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.showToolTips != b) {
if(IsWindow()) {
if(IsInDesignMode()) {
//RecreateControlWindow();
} else {
// Set not supported at runtime - raise VB runtime error 382
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 382);
}
}
properties.showToolTips = b;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_SHOWTOOLTIPS);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Style(StyleConstants* pValue)
{
ATLASSERT_POINTER(pValue, StyleConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
DWORD style = GetStyle();
if(style & TCS_FLATBUTTONS) {
properties.style = sFlatButtons;
} else if(style & TCS_BUTTONS) {
properties.style = sButtons;
} else {
properties.style = sTabs;
}
}
*pValue = properties.style;
return S_OK;
}
STDMETHODIMP TabStrip::put_Style(StyleConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_STYLE);
if(properties.style != newValue) {
properties.style = newValue;
SetDirty(TRUE);
switch(properties.style) {
case sButtons:
case sFlatButtons:
// buttons and scroll to opposite are incompatible
put_ScrollToOpposite(VARIANT_FALSE);
break;
}
if(IsWindow()) {
switch(properties.style) {
case sTabs:
ModifyStyle(TCS_BUTTONS | TCS_FLATBUTTONS, TCS_TABS);
break;
case sButtons:
ModifyStyle(TCS_FLATBUTTONS | TCS_TABS, TCS_BUTTONS);
break;
case sFlatButtons:
ModifyStyle(TCS_TABS, TCS_BUTTONS | TCS_FLATBUTTONS);
break;
}
}
FireOnChanged(DISPID_TABSTRIPCTL_STYLE);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_SupportOLEDragImages(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
*pValue = BOOL2VARIANTBOOL(properties.supportOLEDragImages);
return S_OK;
}
STDMETHODIMP TabStrip::put_SupportOLEDragImages(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_SUPPORTOLEDRAGIMAGES);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.supportOLEDragImages != b) {
properties.supportOLEDragImages = b;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_SUPPORTOLEDRAGIMAGES);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_TabBoundingBoxDefinition(TabBoundingBoxDefinitionConstants* pValue)
{
ATLASSERT_POINTER(pValue, TabBoundingBoxDefinitionConstants);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.tabBoundingBoxDefinition;
return S_OK;
}
STDMETHODIMP TabStrip::put_TabBoundingBoxDefinition(TabBoundingBoxDefinitionConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_TABBOUNDINGBOXDEFINITION);
if(properties.tabBoundingBoxDefinition != newValue) {
properties.tabBoundingBoxDefinition = newValue;
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_TABBOUNDINGBOXDEFINITION);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_TabCaptionAlignment(TabCaptionAlignmentConstants* pValue)
{
ATLASSERT_POINTER(pValue, TabCaptionAlignmentConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
DWORD style = GetStyle();
if(style & TCS_FORCELABELLEFT) {
properties.tabCaptionAlignment = tcaForceCaptionLeft;
} else if(style & TCS_FORCEICONLEFT) {
properties.tabCaptionAlignment = tcaForceIconLeft;
} else {
properties.tabCaptionAlignment = tcaNormal;
}
}
*pValue = properties.tabCaptionAlignment;
return S_OK;
}
STDMETHODIMP TabStrip::put_TabCaptionAlignment(TabCaptionAlignmentConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT);
if(properties.tabCaptionAlignment != newValue) {
properties.tabCaptionAlignment = newValue;
SetDirty(TRUE);
if(IsWindow()) {
switch(properties.tabCaptionAlignment) {
case tcaNormal:
ModifyStyle(TCS_FORCEICONLEFT | TCS_FORCELABELLEFT, 0);
break;
case tcaForceIconLeft:
ModifyStyle(TCS_FORCELABELLEFT, TCS_FORCEICONLEFT);
break;
case tcaForceCaptionLeft:
ModifyStyle(TCS_FORCEICONLEFT, TCS_FORCELABELLEFT);
break;
}
}
FireOnChanged(DISPID_TABSTRIPCTL_TABCAPTIONALIGNMENT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_TabHeight(OLE_YSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.tabHeight;
return S_OK;
}
STDMETHODIMP TabStrip::put_TabHeight(OLE_YSIZE_PIXELS newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_TABHEIGHT);
if(properties.tabHeight != newValue) {
properties.tabHeight = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETITEMSIZE, 0, MAKELPARAM(properties.fixedTabWidth, properties.tabHeight));
}
FireOnChanged(DISPID_TABSTRIPCTL_TABHEIGHT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_TabPlacement(TabPlacementConstants* pValue)
{
ATLASSERT_POINTER(pValue, TabPlacementConstants);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
DWORD style = GetStyle();
if(style & TCS_VERTICAL) {
if(style & TCS_RIGHT) {
properties.tabPlacement = tpRight;
} else {
properties.tabPlacement = tpLeft;
}
} else {
if(style & TCS_BOTTOM) {
properties.tabPlacement = tpBottom;
} else {
properties.tabPlacement = tpTop;
}
}
}
*pValue = properties.tabPlacement;
return S_OK;
}
STDMETHODIMP TabStrip::put_TabPlacement(TabPlacementConstants newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_TABPLACEMENT);
if(properties.tabPlacement != newValue) {
if(IsWindow()) {
switch(newValue) {
case tpTop:
if(GetStyle() & TCS_VERTICAL) {
if(IsInDesignMode()) {
//RecreateControlWindow();
MessageBox(TEXT("The control window won't apply this setting until the Form it is placed on is closed and reloaded."), TEXT("TabStrip - TabPlacement"), MB_ICONINFORMATION);
} else {
// Set not supported at runtime - raise VB runtime error 382
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 382);
}
} else {
ModifyStyle(TCS_BOTTOM | TCS_RIGHT | TCS_VERTICAL, 0);
}
break;
case tpBottom:
if(GetStyle() & TCS_VERTICAL) {
if(IsInDesignMode()) {
//RecreateControlWindow();
MessageBox(TEXT("The control window won't apply this setting until the Form it is placed on is closed and reloaded."), TEXT("TabStrip - TabPlacement"), MB_ICONINFORMATION);
} else {
// Set not supported at runtime - raise VB runtime error 382
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 382);
}
} else {
ModifyStyle(TCS_RIGHT | TCS_VERTICAL, TCS_BOTTOM);
}
break;
case tpLeft:
case tpRight:
if(IsInDesignMode()) {
//RecreateControlWindow();
MessageBox(TEXT("The control window won't apply this setting until the Form it is placed on is closed and reloaded."), TEXT("TabStrip - TabPlacement"), MB_ICONINFORMATION);
} else {
// Set not supported at runtime - raise VB runtime error 382
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 382);
}
break;
}
}
properties.tabPlacement = newValue;
SetDirty(TRUE);
switch(properties.tabPlacement) {
case tpLeft:
case tpRight:
// single line and tpLeft/tpRight are incompatible
put_MultiRow(VARIANT_TRUE);
break;
}
FireOnChanged(DISPID_TABSTRIPCTL_TABPLACEMENT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Tabs(ITabStripTabs** ppTabs)
{
ATLASSERT_POINTER(ppTabs, ITabStripTabs*);
if(!ppTabs) {
return E_POINTER;
}
ClassFactory::InitTabStripTabs(this, IID_ITabStripTabs, reinterpret_cast<LPUNKNOWN*>(ppTabs));
return S_OK;
}
STDMETHODIMP TabStrip::get_Tester(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
*pValue = SysAllocString(L"Timo \"TimoSoft\" Kunze");
return S_OK;
}
STDMETHODIMP TabStrip::get_UseFixedTabWidth(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
if(!IsInDesignMode() && IsWindow()) {
properties.useFixedTabWidth = ((GetStyle() & TCS_FIXEDWIDTH) == TCS_FIXEDWIDTH);
}
*pValue = BOOL2VARIANTBOOL(properties.useFixedTabWidth);
return S_OK;
}
STDMETHODIMP TabStrip::put_UseFixedTabWidth(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_USEFIXEDTABWIDTH);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.useFixedTabWidth != b) {
properties.useFixedTabWidth = b;
SetDirty(TRUE);
if(IsWindow()) {
if(properties.useFixedTabWidth) {
ModifyStyle(0, TCS_FIXEDWIDTH);
} else {
ModifyStyle(TCS_FIXEDWIDTH, 0);
}
FireViewChange();
}
FireOnChanged(DISPID_TABSTRIPCTL_USEFIXEDTABWIDTH);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_UseSystemFont(VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
*pValue = BOOL2VARIANTBOOL(properties.useSystemFont);
return S_OK;
}
STDMETHODIMP TabStrip::put_UseSystemFont(VARIANT_BOOL newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_USESYSTEMFONT);
UINT b = VARIANTBOOL2BOOL(newValue);
if(properties.useSystemFont != b) {
properties.useSystemFont = b;
SetDirty(TRUE);
if(IsWindow()) {
ApplyFont();
}
FireOnChanged(DISPID_TABSTRIPCTL_USESYSTEMFONT);
}
return S_OK;
}
STDMETHODIMP TabStrip::get_Version(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
TCHAR pBuffer[50];
ATLVERIFY(SUCCEEDED(StringCbPrintf(pBuffer, 50 * sizeof(TCHAR), TEXT("%i.%i.%i.%i"), VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION1, VERSION_BUILD)));
*pValue = CComBSTR(pBuffer);
return S_OK;
}
STDMETHODIMP TabStrip::get_VerticalPadding(OLE_YSIZE_PIXELS* pValue)
{
ATLASSERT_POINTER(pValue, OLE_YSIZE_PIXELS);
if(!pValue) {
return E_POINTER;
}
*pValue = properties.verticalPadding;
return S_OK;
}
STDMETHODIMP TabStrip::put_VerticalPadding(OLE_YSIZE_PIXELS newValue)
{
PUTPROPPROLOG(DISPID_TABSTRIPCTL_VERTICALPADDING);
if(properties.verticalPadding != newValue) {
properties.verticalPadding = newValue;
SetDirty(TRUE);
if(IsWindow()) {
SendMessage(TCM_SETPADDING, 0, MAKELPARAM(properties.horizontalPadding, properties.verticalPadding));
// temporarily toggle the TCS_FIXEDWIDTH style, so that SysTabControl32 recalculates the tab metrics
if(GetStyle() & TCS_FIXEDWIDTH) {
ModifyStyle(TCS_FIXEDWIDTH, 0);
ModifyStyle(0, TCS_FIXEDWIDTH);
} else {
ModifyStyle(0, TCS_FIXEDWIDTH);
ModifyStyle(TCS_FIXEDWIDTH, 0);
}
}
FireOnChanged(DISPID_TABSTRIPCTL_VERTICALPADDING);
}
return S_OK;
}
STDMETHODIMP TabStrip::About(void)
{
AboutDlg dlg;
dlg.SetOwner(this);
dlg.DoModal();
return S_OK;
}
STDMETHODIMP TabStrip::BeginDrag(ITabStripTabContainer* pDraggedTabs, OLE_HANDLE hDragImageList/* = NULL*/, OLE_XPOS_PIXELS* pXHotSpot/* = NULL*/, OLE_YPOS_PIXELS* pYHotSpot/* = NULL*/)
{
ATLASSUME(pDraggedTabs);
if(!pDraggedTabs) {
return E_POINTER;
}
int xHotSpot = 0;
if(pXHotSpot) {
xHotSpot = *pXHotSpot;
}
int yHotSpot = 0;
if(pYHotSpot) {
yHotSpot = *pYHotSpot;
}
HRESULT hr = dragDropStatus.BeginDrag(*this, pDraggedTabs, static_cast<HIMAGELIST>(LongToHandle(hDragImageList)), &xHotSpot, &yHotSpot);
SetCapture();
if(pXHotSpot) {
*pXHotSpot = xHotSpot;
}
if(pYHotSpot) {
*pYHotSpot = yHotSpot;
}
if(dragDropStatus.hDragImageList) {
ImageList_BeginDrag(dragDropStatus.hDragImageList, 0, xHotSpot, yHotSpot);
dragDropStatus.dragImageIsHidden = 0;
ImageList_DragEnter(0, 0, 0);
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ImageList_DragMove(mousePosition.x, mousePosition.y);
}
return hr;
}
STDMETHODIMP TabStrip::CalculateDisplayArea(RECTANGLE* pWindowRectangle, RECTANGLE* pDisplayArea)
{
ATLASSERT_POINTER(pWindowRectangle, RECTANGLE);
if(!pWindowRectangle) {
return E_POINTER;
}
ATLASSERT_POINTER(pDisplayArea, RECTANGLE);
if(!pDisplayArea) {
return E_POINTER;
}
if(IsWindow()) {
RECT rc = {pWindowRectangle->Left, pWindowRectangle->Top, pWindowRectangle->Right, pWindowRectangle->Bottom};
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&rc));
pDisplayArea->Left = rc.left;
pDisplayArea->Top = rc.top;
pDisplayArea->Right = rc.right;
pDisplayArea->Bottom = rc.bottom;
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::CalculateWindowRectangle(RECTANGLE* pDisplayArea, RECTANGLE* pWindowRectangle)
{
ATLASSERT_POINTER(pDisplayArea, RECTANGLE);
if(!pDisplayArea) {
return E_POINTER;
}
ATLASSERT_POINTER(pWindowRectangle, RECTANGLE);
if(!pWindowRectangle) {
return E_POINTER;
}
if(IsWindow()) {
RECT rc = {pDisplayArea->Left, pDisplayArea->Top, pDisplayArea->Right, pDisplayArea->Bottom};
SendMessage(TCM_ADJUSTRECT, TRUE, reinterpret_cast<LPARAM>(&rc));
pWindowRectangle->Left = rc.left;
pWindowRectangle->Top = rc.top;
pWindowRectangle->Right = rc.right;
pWindowRectangle->Bottom = rc.bottom;
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::CountTabRows(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
if(IsWindow()) {
*pValue = SendMessage(TCM_GETROWCOUNT, 0, 0);
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::CreateTabContainer(VARIANT tabs/* = _variant_t(DISP_E_PARAMNOTFOUND, VT_ERROR)*/, ITabStripTabContainer** ppContainer/* = NULL*/)
{
ATLASSERT_POINTER(ppContainer, ITabStripTabContainer*);
if(!ppContainer) {
return E_POINTER;
}
*ppContainer = NULL;
CComObject<TabStripTabContainer>* pTSTabContainerObj = NULL;
CComObject<TabStripTabContainer>::CreateInstance(&pTSTabContainerObj);
pTSTabContainerObj->AddRef();
// clone all settings
pTSTabContainerObj->SetOwner(this);
pTSTabContainerObj->QueryInterface(__uuidof(ITabStripTabContainer), reinterpret_cast<LPVOID*>(ppContainer));
pTSTabContainerObj->Release();
if(*ppContainer) {
(*ppContainer)->Add(tabs);
RegisterTabContainer(static_cast<ITabContainer*>(pTSTabContainerObj));
}
return S_OK;
}
STDMETHODIMP TabStrip::EndDrag(VARIANT_BOOL abort)
{
if(!dragDropStatus.IsDragging()) {
return E_FAIL;
}
KillTimer(timers.ID_DRAGSCROLL);
KillTimer(timers.ID_DRAGACTIVATE);
ReleaseCapture();
if(dragDropStatus.hDragImageList) {
dragDropStatus.HideDragImage(TRUE);
ImageList_EndDrag();
}
HRESULT hr = S_OK;
if(abort) {
hr = Raise_AbortedDrag();
} else {
hr = Raise_Drop();
}
dragDropStatus.EndDrag();
Invalidate();
return hr;
}
STDMETHODIMP TabStrip::FinishOLEDragDrop(void)
{
if(dragDropStatus.pDropTargetHelper && dragDropStatus.drop_pDataObject) {
dragDropStatus.pDropTargetHelper->Drop(dragDropStatus.drop_pDataObject, &dragDropStatus.drop_mousePosition, dragDropStatus.drop_effect);
dragDropStatus.pDropTargetHelper->Release();
dragDropStatus.pDropTargetHelper = NULL;
return S_OK;
}
// Can't perform requested operation - raise VB runtime error 17
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 17);
}
STDMETHODIMP TabStrip::GetClosestInsertMarkPosition(OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, InsertMarkPositionConstants* pRelativePosition, ITabStripTab** ppTSTab)
{
ATLASSERT_POINTER(pRelativePosition, InsertMarkPositionConstants);
if(!pRelativePosition) {
return E_POINTER;
}
ATLASSERT_POINTER(ppTSTab, ITabStripTab*);
if(!ppTSTab) {
return E_POINTER;
}
BOOL vertical = ((GetStyle() & TCS_VERTICAL) == TCS_VERTICAL);
int proposedTabIndex = -1;
InsertMarkPositionConstants proposedRelativePosition = impNowhere;
POINT pt = {x, y};
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
int previousCenter = -100000;
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
CRect tabBoundingRectangle;
SendMessage(TCM_GETITEMRECT, tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle));
if(vertical) {
BOOL isFirstInRow = !((tabBoundingRectangle.left <= previousCenter) && (previousCenter <= tabBoundingRectangle.right));
previousCenter = tabBoundingRectangle.CenterPoint().x;
if((pt.x >= tabBoundingRectangle.left) && (pt.x <= tabBoundingRectangle.right)) {
if(isFirstInRow && (pt.y < tabBoundingRectangle.top)) {
proposedTabIndex = tabIndex;
proposedRelativePosition = impBefore;
} else if(pt.y >= tabBoundingRectangle.top) {
proposedTabIndex = tabIndex;
if(pt.y < tabBoundingRectangle.CenterPoint().y) {
proposedRelativePosition = impBefore;
} else {
proposedRelativePosition = impAfter;
}
}
}
} else {
BOOL isFirstInRow = !((tabBoundingRectangle.top <= previousCenter) && (previousCenter <= tabBoundingRectangle.bottom));
previousCenter = tabBoundingRectangle.CenterPoint().y;
if((pt.y >= tabBoundingRectangle.top) && (pt.y <= tabBoundingRectangle.bottom)) {
if(isFirstInRow && (pt.x < tabBoundingRectangle.left)) {
proposedTabIndex = tabIndex;
proposedRelativePosition = impBefore;
} else if(pt.x >= tabBoundingRectangle.left) {
proposedTabIndex = tabIndex;
if(pt.x < tabBoundingRectangle.CenterPoint().x) {
proposedRelativePosition = impBefore;
} else {
proposedRelativePosition = impAfter;
}
}
}
}
}
if(proposedTabIndex == -1) {
*ppTSTab = NULL;
*pRelativePosition = impNowhere;
} else {
*pRelativePosition = proposedRelativePosition;
ClassFactory::InitTabStripTab(proposedTabIndex, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppTSTab), FALSE);
}
return S_OK;
}
STDMETHODIMP TabStrip::GetInsertMarkPosition(InsertMarkPositionConstants* pRelativePosition, ITabStripTab** ppTSTab)
{
ATLASSERT_POINTER(pRelativePosition, InsertMarkPositionConstants);
if(!pRelativePosition) {
return E_POINTER;
}
ATLASSERT_POINTER(ppTSTab, ITabStripTab*);
if(!ppTSTab) {
return E_POINTER;
}
if(insertMark.tabIndex != -1) {
if(insertMark.afterTab) {
*pRelativePosition = impAfter;
} else {
*pRelativePosition = impBefore;
}
ClassFactory::InitTabStripTab(insertMark.tabIndex, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppTSTab));
} else {
*ppTSTab = NULL;
*pRelativePosition = impNowhere;
}
return S_OK;
}
STDMETHODIMP TabStrip::HitTest(OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, HitTestConstants* pHitTestDetails, ITabStripTab** ppHitTab)
{
ATLASSERT_POINTER(ppHitTab, ITabStripTab*);
if(!ppHitTab) {
return E_POINTER;
}
if(IsWindow()) {
UINT hitTestFlags = static_cast<UINT>(*pHitTestDetails);
int tabIndex = HitTest(x, y, &hitTestFlags, TRUE);
if(pHitTestDetails) {
*pHitTestDetails = static_cast<HitTestConstants>(hitTestFlags);
}
ClassFactory::InitTabStripTab(tabIndex, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(ppHitTab));
return S_OK;
}
return E_FAIL;
}
STDMETHODIMP TabStrip::LoadSettingsFromFile(BSTR file, VARIANT_BOOL* pSucceeded)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
*pSucceeded = VARIANT_FALSE;
// open the file
COLE2T converter(file);
LPTSTR pFilePath = converter;
CComPtr<IStream> pStream = NULL;
HRESULT hr = SHCreateStreamOnFile(pFilePath, STGM_READ | STGM_SHARE_DENY_WRITE, &pStream);
if(SUCCEEDED(hr) && pStream) {
// read settings
if(Load(pStream) == S_OK) {
*pSucceeded = VARIANT_TRUE;
}
}
return S_OK;
}
STDMETHODIMP TabStrip::OLEDrag(LONG* pDataObject/* = NULL*/, OLEDropEffectConstants supportedEffects/* = odeCopyOrMove*/, OLE_HANDLE hWndToAskForDragImage/* = -1*/, ITabStripTabContainer* pDraggedTabs/* = NULL*/, LONG itemCountToDisplay/* = -1*/, OLEDropEffectConstants* pPerformedEffects/* = NULL*/)
{
if(supportedEffects == odeNone) {
// don't waste time
return S_OK;
}
if(hWndToAskForDragImage == -1) {
ATLASSUME(pDraggedTabs);
if(!pDraggedTabs) {
return E_INVALIDARG;
}
}
ATLASSERT_POINTER(pDataObject, LONG);
LONG dummy = NULL;
if(!pDataObject) {
pDataObject = &dummy;
}
ATLASSERT_POINTER(pPerformedEffects, OLEDropEffectConstants);
OLEDropEffectConstants performedEffect = odeNone;
if(!pPerformedEffects) {
pPerformedEffects = &performedEffect;
}
HWND hWnd = NULL;
if(hWndToAskForDragImage == -1) {
hWnd = *this;
} else {
hWnd = static_cast<HWND>(LongToHandle(hWndToAskForDragImage));
}
CComPtr<IOLEDataObject> pOLEDataObject = NULL;
CComPtr<IDataObject> pDataObjectToUse = NULL;
if(*pDataObject) {
pDataObjectToUse = *reinterpret_cast<LPDATAOBJECT*>(pDataObject);
CComObject<TargetOLEDataObject>* pOLEDataObjectObj = NULL;
CComObject<TargetOLEDataObject>::CreateInstance(&pOLEDataObjectObj);
pOLEDataObjectObj->AddRef();
pOLEDataObjectObj->Attach(pDataObjectToUse);
pOLEDataObjectObj->QueryInterface(IID_IOLEDataObject, reinterpret_cast<LPVOID*>(&pOLEDataObject));
pOLEDataObjectObj->Release();
} else {
CComObject<SourceOLEDataObject>* pOLEDataObjectObj = NULL;
CComObject<SourceOLEDataObject>::CreateInstance(&pOLEDataObjectObj);
pOLEDataObjectObj->AddRef();
pOLEDataObjectObj->SetOwner(this);
if(itemCountToDisplay == -1) {
if(pDraggedTabs) {
if(flags.usingThemes && RunTimeHelper::IsVista()) {
pDraggedTabs->Count(&pOLEDataObjectObj->properties.numberOfItemsToDisplay);
}
}
} else if(itemCountToDisplay >= 0) {
if(flags.usingThemes && RunTimeHelper::IsVista()) {
pOLEDataObjectObj->properties.numberOfItemsToDisplay = itemCountToDisplay;
}
}
pOLEDataObjectObj->QueryInterface(IID_IOLEDataObject, reinterpret_cast<LPVOID*>(&pOLEDataObject));
pOLEDataObjectObj->QueryInterface(IID_IDataObject, reinterpret_cast<LPVOID*>(&pDataObjectToUse));
pOLEDataObjectObj->Release();
}
ATLASSUME(pDataObjectToUse);
pDataObjectToUse->QueryInterface(IID_IDataObject, reinterpret_cast<LPVOID*>(&dragDropStatus.pSourceDataObject));
CComQIPtr<IDropSource, &IID_IDropSource> pDragSource(this);
if(pDraggedTabs) {
pDraggedTabs->Clone(&dragDropStatus.pDraggedTabs);
}
POINT mousePosition = {0};
GetCursorPos(&mousePosition);
ScreenToClient(&mousePosition);
if(properties.supportOLEDragImages) {
IDragSourceHelper* pDragSourceHelper = NULL;
CoCreateInstance(CLSID_DragDropHelper, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pDragSourceHelper));
if(pDragSourceHelper) {
if(flags.usingThemes && RunTimeHelper::IsVista()) {
IDragSourceHelper2* pDragSourceHelper2 = NULL;
pDragSourceHelper->QueryInterface(IID_IDragSourceHelper2, reinterpret_cast<LPVOID*>(&pDragSourceHelper2));
if(pDragSourceHelper2) {
pDragSourceHelper2->SetFlags(DSH_ALLOWDROPDESCRIPTIONTEXT);
// this was the only place we actually use IDragSourceHelper2
pDragSourceHelper->Release();
pDragSourceHelper = static_cast<IDragSourceHelper*>(pDragSourceHelper2);
}
}
HRESULT hr = pDragSourceHelper->InitializeFromWindow(hWnd, &mousePosition, pDataObjectToUse);
if(FAILED(hr)) {
/* This happens if full window dragging is deactivated. Actually, InitializeFromWindow() contains a
fallback mechanism for this case. This mechanism retrieves the passed window's class name and
builds the drag image using TVM_CREATEDRAGIMAGE if it's SysTreeView32, LVM_CREATEDRAGIMAGE if
it's SysListView32 and so on. Our class name is TabStrip[U|A], so we're doomed.
So how can we have drag images anyway? Well, we use a very ugly hack: We temporarily activate
full window dragging. */
BOOL fullWindowDragging;
SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &fullWindowDragging, 0);
if(!fullWindowDragging) {
SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0);
pDragSourceHelper->InitializeFromWindow(hWnd, &mousePosition, pDataObjectToUse);
SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, FALSE, NULL, 0);
}
}
if(pDragSourceHelper) {
pDragSourceHelper->Release();
}
}
}
if(IsLeftMouseButtonDown()) {
dragDropStatus.draggingMouseButton = MK_LBUTTON;
} else if(IsRightMouseButtonDown()) {
dragDropStatus.draggingMouseButton = MK_RBUTTON;
}
if(flags.usingThemes && properties.oleDragImageStyle == odistAeroIfAvailable && RunTimeHelper::IsVista()) {
dragDropStatus.useItemCountLabelHack = TRUE;
}
if(pOLEDataObject) {
Raise_OLEStartDrag(pOLEDataObject);
}
HRESULT hr = DoDragDrop(pDataObjectToUse, pDragSource, supportedEffects, reinterpret_cast<LPDWORD>(pPerformedEffects));
KillTimer(timers.ID_DRAGSCROLL);
KillTimer(timers.ID_DRAGACTIVATE);
if((hr == DRAGDROP_S_DROP) && pOLEDataObject) {
Raise_OLECompleteDrag(pOLEDataObject, *pPerformedEffects);
}
dragDropStatus.Reset();
return S_OK;
}
STDMETHODIMP TabStrip::Refresh(void)
{
if(IsWindow()) {
dragDropStatus.HideDragImage(TRUE);
Invalidate();
UpdateWindow();
dragDropStatus.ShowDragImage(TRUE);
}
return S_OK;
}
STDMETHODIMP TabStrip::SaveSettingsToFile(BSTR file, VARIANT_BOOL* pSucceeded)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
*pSucceeded = VARIANT_FALSE;
// create the file
COLE2T converter(file);
LPTSTR pFilePath = converter;
CComPtr<IStream> pStream = NULL;
HRESULT hr = SHCreateStreamOnFile(pFilePath, STGM_CREATE | STGM_WRITE | STGM_SHARE_DENY_WRITE, &pStream);
if(SUCCEEDED(hr) && pStream) {
// write settings
if(Save(pStream, FALSE) == S_OK) {
if(FAILED(pStream->Commit(STGC_DEFAULT))) {
return S_OK;
}
*pSucceeded = VARIANT_TRUE;
}
}
return S_OK;
}
STDMETHODIMP TabStrip::SetInsertMarkPosition(InsertMarkPositionConstants relativePosition, ITabStripTab* pTSTab)
{
int tabIndex = -1;
if(pTSTab) {
LONG l = NULL;
pTSTab->get_Index(&l);
tabIndex = l;
}
HRESULT hr = E_FAIL;
if(IsWindow()) {
dragDropStatus.HideDragImage(TRUE);
switch(relativePosition) {
case impNowhere:
if(SendMessage(TCM_SETINSERTMARK, FALSE, -1)) {
hr = S_OK;
}
break;
case impBefore:
if(SendMessage(TCM_SETINSERTMARK, FALSE, tabIndex)) {
hr = S_OK;
}
break;
case impAfter:
if(SendMessage(TCM_SETINSERTMARK, TRUE, tabIndex)) {
hr = S_OK;
}
break;
case impDontChange:
hr = S_OK;
break;
}
dragDropStatus.ShowDragImage(TRUE);
}
return hr;
}
LRESULT TabStrip::OnChar(UINT /*message*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deKeyboardEvents)) {
SHORT keyAscii = static_cast<SHORT>(wParam);
if(SUCCEEDED(Raise_KeyPress(&keyAscii))) {
// the client may have changed the key code (actually it can be changed to 0 only)
wParam = keyAscii;
if(wParam == 0) {
wasHandled = TRUE;
}
}
}
return 0;
}
LRESULT TabStrip::OnContextMenu(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
if(reinterpret_cast<HWND>(wParam) == *this) {
POINT mousePosition = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
if((mousePosition.x != -1) && (mousePosition.y != -1)) {
ScreenToClient(&mousePosition);
}
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
Raise_ContextMenu(button, shift, mousePosition.x, mousePosition.y);
return 0;
/*} else if(properties.reflectContextMenuMessages) {
return ::SendMessage(reinterpret_cast<HWND>(wParam), OCM__BASE + message, wParam, lParam);*/
}
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnCreate(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(*this) {
// this will keep the object alive if the client destroys the control window in an event handler
AddRef();
/* SysTabControl32 already sent a WM_NOTIFYFORMAT/NF_QUERY message to the parent window, but
unfortunately our reflection object did not yet know where to reflect this message to. So we ask
SysTabControl32 to send the message again. */
SendMessage(WM_NOTIFYFORMAT, reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent), NF_REQUERY);
Raise_RecreatedControlWindow(HandleToLong(static_cast<HWND>(*this)));
}
return lr;
}
LRESULT TabStrip::OnDestroy(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& wasHandled)
{
Raise_DestroyedControlWindow(HandleToLong(static_cast<HWND>(*this)));
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnHScroll(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& wasHandled)
{
if(properties.closeableTabs) {
// redraw around the arrow buttons
CWindow arrowButtons = GetDlgItem(1);
CRect rc;
arrowButtons.GetWindowRect(&rc);
rc.InflateRect(5, 5);
ScreenToClient(&rc);
InvalidateRect(&rc);
}
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnKeyDown(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(!(properties.disabledEvents & deKeyboardEvents)) {
SHORT keyCode = static_cast<SHORT>(wParam);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
if(SUCCEEDED(Raise_KeyDown(&keyCode, shift))) {
// the client may have changed the key code
wParam = keyCode;
if(wParam == 0) {
return 0;
}
}
}
return DefWindowProc(message, wParam, lParam);
}
LRESULT TabStrip::OnKeyUp(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(!(properties.disabledEvents & deKeyboardEvents)) {
SHORT keyCode = static_cast<SHORT>(wParam);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
if(SUCCEEDED(Raise_KeyUp(&keyCode, shift))) {
// the client may have changed the key code
wParam = keyCode;
if(wParam == 0) {
return 0;
}
}
}
return DefWindowProc(message, wParam, lParam);
}
LRESULT TabStrip::OnLButtonDblClk(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
// SysTabControl32 sends NM_CLICK on each WM_LBUTTONUP
mouseStatus.ignoreNM_CLICK = TRUE;
if(!(properties.disabledEvents & deClickEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 1/*MouseButtonConstants.vbLeftButton*/;
Raise_DblClick(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnLButtonDown(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
UINT hitTestDetails = 0;
POINT mousePosition = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
mouseStatus.overCloseButton = tabIndex;
mouseStatus.overCloseButtonOnMouseDown = tabIndex;
} else {
// signal the HitTest method that we didn't hit a close button - will be reset to -1 on Click event
mouseStatus.overCloseButtonOnMouseDown = -2;
}
}
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 1/*MouseButtonConstants.vbLeftButton*/;
Raise_MouseDown(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(!mouseStatus.enteredControl) {
mouseStatus.EnterControl();
}
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(flags.silentSelectionChanges == 0) {
if(!(properties.disabledEvents & deTabSelectionChanged)) {
if(GetAsyncKeyState(VK_CONTROL) & 0x8000) {
DWORD style = GetStyle();
if(((style & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) && ((style & TCS_MULTISELECT) == TCS_MULTISELECT)) {
UINT dummy = 0;
int tabIndex = HitTest(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), &dummy);
if(tabIndex != -1) {
Raise_TabSelectionChanged(tabIndex);
}
}
}
}
}
if(properties.allowDragDrop) {
UINT dummy = 0;
int tabIndex = HitTest(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), &dummy);
if(tabIndex != -1) {
dragDropStatus.candidate.tabIndex = tabIndex;
dragDropStatus.candidate.button = MK_LBUTTON;
dragDropStatus.candidate.position.x = GET_X_LPARAM(lParam);
dragDropStatus.candidate.position.y = GET_Y_LPARAM(lParam);
/* NOTE: We should call SetCapture() here, but this won't work, because SysTabControl32 already
captures the mouse in buttons mode. */
}
}
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
UINT hitTestDetails = 0;
POINT mousePosition = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
mouseStatus.overCloseButton = tabIndex;
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(tabIndex, tabIndex == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
}
return lr;
}
LRESULT TabStrip::OnLButtonUp(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(properties.allowDragDrop) {
dragDropStatus.candidate.tabIndex = -1;
}
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 1/*MouseButtonConstants.vbLeftButton*/;
Raise_MouseUp(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
UINT hitTestDetails = 0;
POINT mousePosition = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
mouseStatus.overCloseButton = tabIndex;
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(tabIndex, tabIndex == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
}
return 0;
}
LRESULT TabStrip::OnMButtonDblClk(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deClickEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 4/*MouseButtonConstants.vbMiddleButton*/;
Raise_MDblClick(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnMButtonDown(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 4/*MouseButtonConstants.vbMiddleButton*/;
Raise_MouseDown(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(!mouseStatus.enteredControl) {
mouseStatus.EnterControl();
}
return 0;
}
LRESULT TabStrip::OnMButtonUp(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 4/*MouseButtonConstants.vbMiddleButton*/;
Raise_MouseUp(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnMouseActivate(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
/* Hide the message from CComControl, so that the control doesn't receive the focus if the user activates
another tab. */
return DefWindowProc(message, wParam, lParam);
}
LRESULT TabStrip::OnMouseHover(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
Raise_MouseHover(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnMouseLeave(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& wasHandled)
{
wasHandled = FALSE;
/* NOTE: We check for mouseStatus.enteredControl because SysTabControl32 sends a WM_MOUSELEAVE after
each WM_MOUSEWHEEL message if it has the focus. */
if(!(properties.disabledEvents & deMouseEvents) && mouseStatus.enteredControl) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
Raise_MouseLeave(button, shift, mouseStatus.lastPosition.x, mouseStatus.lastPosition.y);
}
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
mouseStatus.overCloseButton = -1;
}
}
return 0;
}
LRESULT TabStrip::OnMouseMove(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
Raise_MouseMove(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(!mouseStatus.enteredControl) {
mouseStatus.EnterControl();
}
if(properties.allowDragDrop) {
if(dragDropStatus.candidate.tabIndex != -1) {
// calculate the rectangle, that the mouse cursor must leave to start dragging
int clickRectWidth = GetSystemMetrics(SM_CXDRAG);
if(clickRectWidth < 4) {
clickRectWidth = 4;
}
int clickRectHeight = GetSystemMetrics(SM_CYDRAG);
if(clickRectHeight < 4) {
clickRectHeight = 4;
}
CRect rc(dragDropStatus.candidate.position.x - clickRectWidth, dragDropStatus.candidate.position.y - clickRectHeight, dragDropStatus.candidate.position.x + clickRectWidth, dragDropStatus.candidate.position.y + clickRectHeight);
if(!rc.PtInRect(CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)))) {
NMTCBEGINDRAG details = {0};
details.hdr.idFrom = GetDlgCtrlID();
details.hdr.hwndFrom = *this;
details.iItem = dragDropStatus.candidate.tabIndex;
details.ptDrag = dragDropStatus.candidate.position;
switch(dragDropStatus.candidate.button) {
case MK_LBUTTON:
details.hdr.code = TCN_BEGINDRAG;
GetParent().SendMessage(WM_NOTIFY, details.hdr.idFrom, reinterpret_cast<LPARAM>(&details));
break;
case MK_RBUTTON:
details.hdr.code = TCN_BEGINRDRAG;
GetParent().SendMessage(WM_NOTIFY, details.hdr.idFrom, reinterpret_cast<LPARAM>(&details));
break;
}
dragDropStatus.candidate.tabIndex = -1;
}
}
}
if(dragDropStatus.IsDragging()) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
Raise_DragMouseMove(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(properties.closeableTabs) {
UINT hitTestDetails = 0;
POINT mousePosition = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
if(mouseStatus.overCloseButton == -1) {
mouseStatus.overCloseButton = tabIndex;
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(tabIndex, tabIndex == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
mouseStatus.overCloseButton = -1;
}
}
return 0;
}
LRESULT TabStrip::OnNCHitTest(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*wasHandled*/)
{
return HTCLIENT;
}
LRESULT TabStrip::OnPaint(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(wParam && (!RunTimeHelper::IsCommCtrl6() || !flags.usingThemes || (RunTimeHelper::IsCommCtrl6() && (GetStyle() & TCS_OWNERDRAWFIXED) == TCS_OWNERDRAWFIXED))) {
// Without this code, we get a black background as soon as our WindowlessLabel control is one of the contained controls.
RECT clientRectangle = {0};
GetClientRect(&clientRectangle);
FillRect(reinterpret_cast<HDC>(wParam), &clientRectangle, GetSysColorBrush(COLOR_3DFACE));
}
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(message == WM_PAINT) {
HDC hDC = GetDC();
DrawCloseButtonsAndInsertionMarks(hDC);
ReleaseDC(hDC);
} else {
DrawCloseButtonsAndInsertionMarks(reinterpret_cast<HDC>(wParam));
}
return lr;
}
LRESULT TabStrip::OnRButtonDblClk(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
// SysTabControl32 sends NM_RCLICK on each WM_RBUTTONUP
mouseStatus.ignoreNM_RCLICK = TRUE;
if(!(properties.disabledEvents & deClickEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 2/*MouseButtonConstants.vbRightButton*/;
Raise_RDblClick(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnRButtonDown(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 2/*MouseButtonConstants.vbRightButton*/;
Raise_MouseDown(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(!mouseStatus.enteredControl) {
mouseStatus.EnterControl();
}
if(!(properties.disabledEvents & deTabSelectionChanged)) {
if(!(GetAsyncKeyState(VK_CONTROL) & 0x8000)) {
DWORD style = GetStyle();
if(((style & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) && ((style & TCS_MULTISELECT) == TCS_MULTISELECT)) {
UINT dummy = 0;
int tabIndex = HitTest(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), &dummy);
if(tabIndex != -1) {
// HACK: TCM_GETCURSEL returns -1 after the active tab was changed using the right mouse button
SendMessage(TCM_SETCURSEL, tabIndex, 0);
}
}
}
}
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(flags.silentSelectionChanges == 0) {
if(!(properties.disabledEvents & deTabSelectionChanged)) {
if(GetAsyncKeyState(VK_CONTROL) & 0x8000) {
DWORD style = GetStyle();
if(((style & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) && ((style & TCS_MULTISELECT) == TCS_MULTISELECT)) {
UINT dummy = 0;
int tabIndex = HitTest(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), &dummy);
if(tabIndex != -1) {
Raise_TabSelectionChanged(tabIndex);
}
}
}
}
}
if(properties.allowDragDrop) {
UINT dummy = 0;
int tabIndex = HitTest(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), &dummy);
if(tabIndex != -1) {
dragDropStatus.candidate.tabIndex = tabIndex;
dragDropStatus.candidate.button = MK_RBUTTON;
dragDropStatus.candidate.position.x = GET_X_LPARAM(lParam);
dragDropStatus.candidate.position.y = GET_Y_LPARAM(lParam);
/* NOTE: We should call SetCapture() here, but this won't work, because SysTabControl32 already
captures the mouse in buttons mode. */
}
}
return lr;
}
LRESULT TabStrip::OnRButtonUp(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(properties.allowDragDrop) {
dragDropStatus.candidate.tabIndex = -1;
}
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(wParam, button, shift);
button = 2/*MouseButtonConstants.vbRightButton*/;
Raise_MouseUp(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnSetCursor(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& wasHandled)
{
HCURSOR hCursor = NULL;
BOOL setCursor = FALSE;
// Are we really over the control?
CRect clientArea;
GetClientRect(&clientArea);
ClientToScreen(&clientArea);
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
if(clientArea.PtInRect(mousePosition)) {
// maybe the control is overlapped by a foreign window
if(WindowFromPoint(mousePosition) == *this) {
setCursor = TRUE;
}
}
if(setCursor) {
if(properties.mousePointer == mpCustom) {
if(properties.mouseIcon.pPictureDisp) {
CComQIPtr<IPicture, &IID_IPicture> pPicture(properties.mouseIcon.pPictureDisp);
if(pPicture) {
OLE_HANDLE h = NULL;
pPicture->get_Handle(&h);
hCursor = static_cast<HCURSOR>(LongToHandle(h));
}
}
} else {
hCursor = MousePointerConst2hCursor(properties.mousePointer);
}
if(hCursor) {
SetCursor(hCursor);
return TRUE;
}
}
wasHandled = FALSE;
return FALSE;
}
LRESULT TabStrip::OnSetFont(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_FONT) == S_FALSE) {
return 0;
}
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(!properties.font.dontGetFontObject) {
// this message wasn't sent by ourselves, so we have to get the new font.pFontDisp object
if(!properties.font.owningFontResource) {
properties.font.currentFont.Detach();
}
properties.font.currentFont.Attach(reinterpret_cast<HFONT>(wParam));
properties.font.owningFontResource = FALSE;
properties.useSystemFont = FALSE;
properties.font.StopWatching();
if(properties.font.pFontDisp) {
properties.font.pFontDisp->Release();
properties.font.pFontDisp = NULL;
}
if(!properties.font.currentFont.IsNull()) {
LOGFONT logFont = {0};
int bytes = properties.font.currentFont.GetLogFont(&logFont);
if(bytes) {
FONTDESC font = {0};
CT2OLE converter(logFont.lfFaceName);
HDC hDC = GetDC();
if(hDC) {
LONG fontHeight = logFont.lfHeight;
if(fontHeight < 0) {
fontHeight = -fontHeight;
}
int pixelsPerInch = GetDeviceCaps(hDC, LOGPIXELSY);
ReleaseDC(hDC);
font.cySize.Lo = fontHeight * 720000 / pixelsPerInch;
font.cySize.Hi = 0;
font.lpstrName = converter;
font.sWeight = static_cast<SHORT>(logFont.lfWeight);
font.sCharset = logFont.lfCharSet;
font.fItalic = logFont.lfItalic;
font.fUnderline = logFont.lfUnderline;
font.fStrikethrough = logFont.lfStrikeOut;
}
font.cbSizeofstruct = sizeof(FONTDESC);
OleCreateFontIndirect(&font, IID_IFontDisp, reinterpret_cast<LPVOID*>(&properties.font.pFontDisp));
}
}
properties.font.StartWatching();
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_FONT);
}
return lr;
}
//
//LRESULT TabStrip::OnSetRedraw(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
//{
// if(lParam == 71216) {
// // the message was sent by ourselves
// lParam = 0;
// if(wParam) {
// // We're gonna activate redrawing - does the client allow this?
// if(properties.dontRedraw) {
// // no, so eat this message
// return 0;
// }
// }
// } else {
// // TODO: Should we really do this?
// properties.dontRedraw = !wParam;
// }
//
// return DefWindowProc(message, wParam, lParam);
//}
LRESULT TabStrip::OnSettingChange(UINT /*message*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& wasHandled)
{
if(wParam == SPI_SETNONCLIENTMETRICS) {
if(properties.useSystemFont) {
ApplyFont();
//Invalidate();
}
}
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnThemeChanged(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& wasHandled)
{
// Microsoft couldn't make it more difficult to detect whether we should use themes or not...
flags.usingThemes = FALSE;
if(CTheme::IsThemingSupported() && RunTimeHelper::IsCommCtrl6()) {
HMODULE hThemeDLL = LoadLibrary(TEXT("uxtheme.dll"));
if(hThemeDLL) {
typedef BOOL WINAPI IsAppThemedFn();
IsAppThemedFn* pfnIsAppThemed = static_cast<IsAppThemedFn*>(GetProcAddress(hThemeDLL, "IsAppThemed"));
if(pfnIsAppThemed()) {
flags.usingThemes = TRUE;
}
FreeLibrary(hThemeDLL);
}
}
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnTimer(UINT /*message*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& wasHandled)
{
switch(wParam) {
//case timers.ID_REDRAW:
// if(IsWindowVisible()) {
// KillTimer(timers.ID_REDRAW);
// SetRedraw(!properties.dontRedraw);
// } else {
// // wait... (this fixes visibility problems if another control displays a nag screen)
// }
// break;
case timers.ID_DRAGSCROLL:
AutoScroll();
break;
case timers.ID_DRAGACTIVATE:
KillTimer(timers.ID_DRAGACTIVATE);
if((dragDropStatus.lastDropTarget != -1) && (dragDropStatus.lastDropTarget != SendMessage(TCM_GETCURSEL, 0, 0))) {
SendMessage(TCM_SETCURSEL, dragDropStatus.lastDropTarget, 0);
}
break;
default:
wasHandled = FALSE;
break;
}
return 0;
}
LRESULT TabStrip::OnWindowPosChanged(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& wasHandled)
{
LPWINDOWPOS pDetails = reinterpret_cast<LPWINDOWPOS>(lParam);
CRect windowRectangle = m_rcPos;
/* Ugly hack: We depend on this message being sent without SWP_NOMOVE at least once, but this requirement
not always will be fulfilled. Fortunately pDetails seems to contain correct x and y values
even if SWP_NOMOVE is set.
*/
if(!(pDetails->flags & SWP_NOMOVE) || (windowRectangle.IsRectNull() && pDetails->x != 0 && pDetails->y != 0)) {
windowRectangle.MoveToXY(pDetails->x, pDetails->y);
}
if(!(pDetails->flags & SWP_NOSIZE)) {
windowRectangle.right = windowRectangle.left + pDetails->cx;
windowRectangle.bottom = windowRectangle.top + pDetails->cy;
}
if(!(pDetails->flags & SWP_NOMOVE) || !(pDetails->flags & SWP_NOSIZE)) {
ATLASSUME(m_spInPlaceSite);
if(m_spInPlaceSite && !windowRectangle.EqualRect(&m_rcPos)) {
m_spInPlaceSite->OnPosRectChange(&windowRectangle);
}
if(!(pDetails->flags & SWP_NOSIZE)) {
/* Problem: When the control is resized, m_rcPos already contains the new rectangle, even before the
* message is sent without SWP_NOSIZE. Therefore raise the event even if the rectangles are
* equal. Raising the event too often is better than raising it too few.
*/
Raise_ResizedControlWindow();
}
}
wasHandled = FALSE;
return 0;
}
LRESULT TabStrip::OnXButtonDblClk(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deClickEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(GET_KEYSTATE_WPARAM(wParam), button, shift);
switch(GET_XBUTTON_WPARAM(wParam)) {
case XBUTTON1:
button = embXButton1;
break;
case XBUTTON2:
button = embXButton2;
break;
}
Raise_XDblClick(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnXButtonDown(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(GET_KEYSTATE_WPARAM(wParam), button, shift);
switch(GET_XBUTTON_WPARAM(wParam)) {
case XBUTTON1:
button = embXButton1;
break;
case XBUTTON2:
button = embXButton2;
break;
}
Raise_MouseDown(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else if(!mouseStatus.enteredControl) {
mouseStatus.EnterControl();
}
return 0;
}
LRESULT TabStrip::OnXButtonUp(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& wasHandled)
{
wasHandled = FALSE;
if(!(properties.disabledEvents & deMouseEvents)) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(GET_KEYSTATE_WPARAM(wParam), button, shift);
switch(GET_XBUTTON_WPARAM(wParam)) {
case XBUTTON1:
button = embXButton1;
break;
case XBUTTON2:
button = embXButton2;
break;
}
Raise_MouseUp(button, shift, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
}
LRESULT TabStrip::OnReflectedDrawItem(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& wasHandled)
{
LPDRAWITEMSTRUCT pDetails = reinterpret_cast<LPDRAWITEMSTRUCT>(lParam);
ATLASSERT(pDetails->CtlType == ODT_TAB);
ATLASSERT(pDetails->itemAction == ODA_DRAWENTIRE);
ATLASSERT((pDetails->itemState & (ODS_GRAYED | ODS_DISABLED | ODS_CHECKED | ODS_FOCUS | ODS_DEFAULT | ODS_NOACCEL | ODS_NOFOCUSRECT | ODS_COMBOBOXEDIT | ODS_HOTLIGHT | ODS_INACTIVE)) == 0);
if(pDetails->hwndItem == *this) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(pDetails->itemID, this, FALSE);
Raise_OwnerDrawTab(pTSTab, static_cast<OwnerDrawTabStateConstants>(pDetails->itemState), HandleToLong(pDetails->hDC), reinterpret_cast<RECTANGLE*>(&pDetails->rcItem));
return TRUE;
}
wasHandled = FALSE;
return FALSE;
}
LRESULT TabStrip::OnReflectedNotifyFormat(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(lParam == NF_QUERY) {
#ifdef UNICODE
return NFR_UNICODE;
#else
return NFR_ANSI;
#endif
}
return 0;
}
LRESULT TabStrip::OnGetDragImage(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& wasHandled)
{
BOOL succeeded = FALSE;
BOOL useVistaDragImage = FALSE;
if(dragDropStatus.pDraggedTabs) {
if(flags.usingThemes && properties.oleDragImageStyle == odistAeroIfAvailable && RunTimeHelper::IsVista()) {
succeeded = CreateVistaOLEDragImage(dragDropStatus.pDraggedTabs, reinterpret_cast<LPSHDRAGIMAGE>(lParam));
useVistaDragImage = succeeded;
}
if(!succeeded) {
// use a legacy drag image as fallback
succeeded = CreateLegacyOLEDragImage(dragDropStatus.pDraggedTabs, reinterpret_cast<LPSHDRAGIMAGE>(lParam));
}
if(succeeded && RunTimeHelper::IsVista()) {
FORMATETC format = {0};
format.cfFormat = static_cast<CLIPFORMAT>(RegisterClipboardFormat(TEXT("UsingDefaultDragImage")));
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
medium.hGlobal = GlobalAlloc(GPTR, sizeof(BOOL));
if(medium.hGlobal) {
LPBOOL pUseVistaDragImage = static_cast<LPBOOL>(GlobalLock(medium.hGlobal));
*pUseVistaDragImage = useVistaDragImage;
GlobalUnlock(medium.hGlobal);
dragDropStatus.pSourceDataObject->SetData(&format, &medium, TRUE);
}
}
}
wasHandled = succeeded;
// TODO: Why do we have to return FALSE to have the set offset not ignored if a Vista drag image is used?
return succeeded && !useVistaDragImage;
}
LRESULT TabStrip::OnCreateDragImage(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
return reinterpret_cast<LRESULT>(CreateLegacyDragImage(lParam, reinterpret_cast<LPPOINT>(wParam), NULL));
}
LRESULT TabStrip::OnDeleteAllItems(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = FALSE;
VARIANT_BOOL cancel = VARIANT_FALSE;
if(!(properties.disabledEvents & deTabDeletionEvents)) {
if(flags.silentTabDeletions == 0) {
Raise_RemovingTab(NULL, &cancel);
}
}
if(cancel == VARIANT_FALSE) {
if(!(properties.disabledEvents & deMouseEvents)) {
if(tabUnderMouse != -1) {
// we're removing the tab below the mouse cursor
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabUnderMouse, this);
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
UINT hitTestDetails = 0;
HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
Raise_TabMouseLeave(pTSTab, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
tabUnderMouse = -1;
}
}
if((GetStyle() & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) {
Raise_CaretChanged(caretChangedStatus.previousCaretTab, -1);
}
Raise_ActiveTabChanged(activeTabChangedStatus.previousActiveTab, -1);
if(flags.silentTabDeletions == 0) {
if(!(properties.disabledEvents & deFreeTabData)) {
Raise_FreeTabData(NULL);
}
}
// finally pass the message to the tabstrip
lr = DefWindowProc(message, wParam, lParam);
if(lr) {
mouseStatus.overCloseButton = -1;
mouseStatus.overCloseButtonOnMouseDown = -1;
cachedSettings.dropHilitedTab = -1;
dragDropStatus.lastDropTarget = -1;
insertMark.tabIndex = -1;
RebuildAcceleratorTable();
if(flags.silentTabDeletions == 0) {
if(!(properties.disabledEvents & deTabDeletionEvents)) {
Raise_RemovedTab(NULL);
}
}
RemoveTabFromTabContainers(-1);
#ifdef USE_STL
tabIDs.clear();
tabParams.clear();
#else
tabIDs.RemoveAll();
tabParams.RemoveAll();
#endif
}
}
return lr;
}
LRESULT TabStrip::OnDeleteItem(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = FALSE;
VARIANT_BOOL cancel = VARIANT_FALSE;
CComPtr<ITabStripTab> pTabStripTabItf = NULL;
CComObject<TabStripTab>* pTabStripTabObj = NULL;
if(!(properties.disabledEvents & deTabDeletionEvents) && (flags.silentTabDeletions == 0)) {
CComObject<TabStripTab>::CreateInstance(&pTabStripTabObj);
pTabStripTabObj->AddRef();
pTabStripTabObj->SetOwner(this);
pTabStripTabObj->Attach(wParam);
pTabStripTabObj->QueryInterface(IID_ITabStripTab, reinterpret_cast<LPVOID*>(&pTabStripTabItf));
pTabStripTabObj->Release();
Raise_RemovingTab(pTabStripTabItf, &cancel);
}
if(cancel == VARIANT_FALSE) {
CComPtr<IVirtualTabStripTab> pVTabStripTabItf = NULL;
if(!(properties.disabledEvents & deTabDeletionEvents) && (flags.silentTabDeletions == 0)) {
CComObject<VirtualTabStripTab>* pVTabStripTabObj = NULL;
CComObject<VirtualTabStripTab>::CreateInstance(&pVTabStripTabObj);
pVTabStripTabObj->AddRef();
pVTabStripTabObj->SetOwner(this);
if(pTabStripTabObj) {
pTabStripTabObj->SaveState(pVTabStripTabObj);
}
pVTabStripTabObj->QueryInterface(IID_IVirtualTabStripTab, reinterpret_cast<LPVOID*>(&pVTabStripTabItf));
pVTabStripTabObj->Release();
}
if(!(properties.disabledEvents & deMouseEvents)) {
if(static_cast<int>(wParam) == tabUnderMouse) {
// we're removing the tab below the mouse cursor
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
UINT hitTestDetails = 0;
HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
Raise_TabMouseLeave(pTabStripTabItf, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
tabUnderMouse = -1;
}
}
if((GetStyle() & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) {
if(caretChangedStatus.previousCaretTab == static_cast<int>(wParam)) {
Raise_CaretChanged(caretChangedStatus.previousCaretTab, -1);
}
}
if(activeTabChangedStatus.previousActiveTab == static_cast<int>(wParam)) {
Raise_ActiveTabChanged(activeTabChangedStatus.previousActiveTab, -1);
}
if(flags.silentTabDeletions == 0) {
if(!(properties.disabledEvents & deFreeTabData)) {
if(pTabStripTabItf) {
Raise_FreeTabData(pTabStripTabItf);
} else {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(wParam, this, FALSE);
Raise_FreeTabData(pTSTab);
}
}
}
// finally pass the message to the tabstrip
LONG tabIDBeingRemoved = TabIndexToID(wParam);
lr = DefWindowProc(message, wParam, lParam);
if(lr) {
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
if(mouseStatus.overCloseButtonOnMouseDown == static_cast<int>(wParam)) {
mouseStatus.overCloseButtonOnMouseDown = -1;
}
UINT hitTestDetails = 0;
POINT mousePosition = {0};
GetCursorPos(&mousePosition);
ScreenToClient(&mousePosition);
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
mouseStatus.overCloseButton = tabIndex;
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
mouseStatus.overCloseButton = -1;
}
}
if(flags.silentTabDeletions == 0) {
if(cachedSettings.dropHilitedTab == static_cast<int>(wParam)) {
cachedSettings.dropHilitedTab = -1;
} else if(cachedSettings.dropHilitedTab > static_cast<int>(wParam)) {
--cachedSettings.dropHilitedTab;
}
if(dragDropStatus.lastDropTarget == static_cast<int>(wParam)) {
dragDropStatus.lastDropTarget = -1;
}
if(insertMark.tabIndex == static_cast<int>(wParam)) {
insertMark.tabIndex = -1;
} else if(insertMark.tabIndex > static_cast<int>(wParam)) {
--insertMark.tabIndex;
}
RemoveTabFromTabContainers(tabIDBeingRemoved);
#ifdef USE_STL
tabIDs.erase(tabIDs.begin() + static_cast<int>(wParam));
std::list<TabData>::iterator iter2 = tabParams.begin();
if(iter2 != tabParams.end()) {
std::advance(iter2, wParam);
if(iter2 != tabParams.end()) {
tabParams.erase(iter2);
}
}
#else
tabIDs.RemoveAt(static_cast<int>(wParam));
POSITION p = tabParams.FindIndex(wParam);
if(p) {
tabParams.RemoveAt(p);
}
#endif
}
RebuildAcceleratorTable();
if(flags.silentTabDeletions == 0) {
if(!(properties.disabledEvents & deTabDeletionEvents)) {
Raise_RemovedTab(pVTabStripTabItf);
}
}
}
if(!(properties.disabledEvents & deMouseEvents)) {
if(lr) {
// maybe we have a new tab below the mouse cursor now
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
UINT hitTestDetails = 0;
int newTabUnderMouse = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
if(newTabUnderMouse != tabUnderMouse) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
if(tabUnderMouse != -1) {
pTabStripTabItf = ClassFactory::InitTabStripTab(tabUnderMouse, this);
Raise_TabMouseLeave(pTabStripTabItf, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
}
tabUnderMouse = newTabUnderMouse;
if(tabUnderMouse != -1) {
pTabStripTabItf = ClassFactory::InitTabStripTab(tabUnderMouse, this);
Raise_TabMouseEnter(pTabStripTabItf, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
}
}
}
}
}
return lr;
}
LRESULT TabStrip::OnDeselectAll(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(properties.disabledEvents & deTabSelectionChanged) {
return DefWindowProc(message, wParam, lParam);
} else {
// store the selection states before processing the message
#ifdef USE_STL
std::vector<DWORD> selectionStatesBefore;
#else
CAtlArray<DWORD> selectionStatesBefore;
#endif
TCITEM tab = {0};
tab.dwStateMask = TCIS_BUTTONPRESSED;
tab.mask = TCIF_STATE;
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
if(flags.silentSelectionChanges == 0) {
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
#ifdef USE_STL
selectionStatesBefore.push_back(tab.dwState & TCIS_BUTTONPRESSED);
#else
selectionStatesBefore.Add(tab.dwState & TCIS_BUTTONPRESSED);
#endif
}
}
// let SysTabControl32 handle the message
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(flags.silentSelectionChanges == 0) {
// now retrieve the selection states again and raise the event if necessary
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
if((tab.dwState & TCIS_BUTTONPRESSED) != selectionStatesBefore[tabIndex]) {
Raise_TabSelectionChanged(tabIndex);
}
}
}
return lr;
}
}
LRESULT TabStrip::OnGetExtendedStyle(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(properties.allowDragDrop) {
lr |= TCS_EX_DETECTDRAGDROP;
}
return lr;
}
LRESULT TabStrip::OnGetInsertMark(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*wasHandled*/)
{
ATLASSERT(lParam);
if(lParam == 0) {
return FALSE;
}
LPTCINSERTMARK pDetails = reinterpret_cast<LPTCINSERTMARK>(lParam);
if(pDetails->size == sizeof(TCINSERTMARK)) {
pDetails->tabIndex = insertMark.tabIndex;
pDetails->afterTab = insertMark.afterTab;
return TRUE;
}
return FALSE;
}
LRESULT TabStrip::OnGetInsertMarkColor(UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*wasHandled*/)
{
return insertMark.color;
}
LRESULT TabStrip::OnGetItem(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
BOOL overwriteLParam = FALSE;
LPTCITEM pTabData = reinterpret_cast<LPTCITEM>(lParam);
#ifdef DEBUG
if(message == TCM_GETITEMA) {
ATLASSERT_POINTER(pTabData, TCITEMA);
} else {
ATLASSERT_POINTER(pTabData, TCITEMW);
}
#endif
if(!pTabData) {
return DefWindowProc(message, wParam, lParam);
}
if(pTabData->mask & TCIF_NOINTERCEPTION) {
// SysTabControl32 shouldn't see this flag
pTabData->mask &= ~TCIF_NOINTERCEPTION;
} else if(pTabData->mask == TCIF_PARAM) {
// just look up in the 'tabParams' list
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, wParam);
if(iter != tabParams.end()) {
pTabData->lParam = iter->lParam;
return TRUE;
}
}
#else
POSITION p = tabParams.FindIndex(wParam);
if(p) {
pTabData->lParam = tabParams.GetAt(p).lParam;
return TRUE;
}
#endif
// tab not found
return FALSE;
} else if(pTabData->mask & TCIF_PARAM) {
overwriteLParam = TRUE;
}
// forward the message
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(overwriteLParam) {
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, wParam);
if(iter != tabParams.end()) {
pTabData->lParam = iter->lParam;
}
}
#else
POSITION p = tabParams.FindIndex(wParam);
if(p) {
pTabData->lParam = tabParams.GetAt(p).lParam;
}
#endif
}
return lr;
}
LRESULT TabStrip::OnHighlightItem(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(lr) {
if(LOWORD(lParam)) {
// a tab got highlighted
if(static_cast<int>(wParam) != cachedSettings.dropHilitedTab) {
DefWindowProc(TCM_HIGHLIGHTITEM, cachedSettings.dropHilitedTab, MAKELPARAM(FALSE, 0));
cachedSettings.dropHilitedTab = static_cast<int>(wParam);
}
} else {
// a tab got un-highlighted
if(static_cast<int>(wParam) == cachedSettings.dropHilitedTab) {
cachedSettings.dropHilitedTab = -1;
}
}
}
return lr;
}
LRESULT TabStrip::OnInsertItem(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
int insertedTab = -1;
if(!(properties.disabledEvents & deTabInsertionEvents)) {
CComObject<VirtualTabStripTab>* pVTabStripTabObj = NULL;
CComPtr<IVirtualTabStripTab> pVTabStripTabItf = NULL;
VARIANT_BOOL cancel = VARIANT_FALSE;
if(flags.silentTabInsertions == 0) {
CComObject<VirtualTabStripTab>::CreateInstance(&pVTabStripTabObj);
pVTabStripTabObj->AddRef();
pVTabStripTabObj->SetOwner(this);
#ifdef UNICODE
BOOL mustConvert = (message == TCM_INSERTITEMA);
#else
BOOL mustConvert = (message == TCM_INSERTITEMW);
#endif
if(mustConvert) {
#ifdef UNICODE
LPTCITEMA pTabData = reinterpret_cast<LPTCITEMA>(lParam);
TCITEMW convertedTabData = {0};
CA2W converter(pTabData->pszText);
convertedTabData.pszText = converter;
#else
LPTCITEMW pTabData = reinterpret_cast<LPTCITEMW>(lParam);
TCITEMA convertedTabData = {0};
CW2A converter(pTabData->pszText);
convertedTabData.pszText = converter;
#endif
convertedTabData.cchTextMax = pTabData->cchTextMax;
convertedTabData.mask = pTabData->mask;
convertedTabData.dwState = pTabData->dwState;
convertedTabData.dwStateMask = pTabData->dwStateMask;
convertedTabData.iImage = pTabData->iImage;
convertedTabData.lParam = pTabData->lParam;
pVTabStripTabObj->LoadState(&convertedTabData, wParam);
} else {
pVTabStripTabObj->LoadState(reinterpret_cast<LPTCITEM>(lParam), wParam);
}
pVTabStripTabObj->QueryInterface(IID_IVirtualTabStripTab, reinterpret_cast<LPVOID*>(&pVTabStripTabItf));
pVTabStripTabObj->Release();
Raise_InsertingTab(pVTabStripTabItf, &cancel);
pVTabStripTabObj = NULL;
}
if(cancel == VARIANT_FALSE) {
// finally pass the message to the tabstrip
LPTCITEM pDetails = reinterpret_cast<LPTCITEM>(lParam);
TabData tabData = {0};
tabData.isCloseable = TRUE;
pDetails->mask &= ~TCIF_NOINTERCEPTION;
if(flags.silentTabInsertions == 0) {
tabData.lParam = pDetails->lParam;
pDetails->lParam = GetNewTabID();
pDetails->mask |= TCIF_PARAM;
}
insertedTab = DefWindowProc(message, wParam, lParam);
if(insertedTab != -1) {
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
mouseStatus.overCloseButtonOnMouseDown = -1;
UINT hitTestDetails = 0;
POINT mousePosition = {0};
GetCursorPos(&mousePosition);
ScreenToClient(&mousePosition);
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
mouseStatus.overCloseButton = tabIndex;
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
mouseStatus.overCloseButton = -1;
}
}
if(flags.silentTabInsertions == 0) {
/* NOTE: Activating silent insertions implies that the 'tabIDs' vector and the 'tabParams' list
have to be updated explicitly. */
#ifdef USE_STL
if(insertedTab >= static_cast<int>(tabIDs.size())) {
tabIDs.push_back(static_cast<LONG>(pDetails->lParam));
} else {
tabIDs.insert(tabIDs.begin() + insertedTab, static_cast<LONG>(pDetails->lParam));
}
std::list<TabData>::iterator iter2 = tabParams.begin();
if(iter2 != tabParams.end()) {
std::advance(iter2, insertedTab);
}
tabParams.insert(iter2, tabData);
#else
if(insertedTab >= static_cast<int>(tabIDs.GetCount())) {
tabIDs.Add(static_cast<LONG>(pDetails->lParam));
} else {
tabIDs.InsertAt(insertedTab, static_cast<LONG>(pDetails->lParam));
}
POSITION p = tabParams.FindIndex(insertedTab);
if(p) {
tabParams.InsertBefore(p, tabData);
} else {
tabParams.AddTail(tabData);
}
#endif
}
if(insertedTab <= cachedSettings.dropHilitedTab) {
++cachedSettings.dropHilitedTab;
}
if(insertedTab <= insertMark.tabIndex) {
++insertMark.tabIndex;
}
RebuildAcceleratorTable();
if(flags.silentTabInsertions == 0) {
CComPtr<ITabStripTab> pTabStripTabItf = ClassFactory::InitTabStripTab(insertedTab, this, FALSE);
Raise_InsertedTab(pTabStripTabItf);
}
}
}
} else {
// finally pass the message to the tabstrip
LPTCITEM pDetails = reinterpret_cast<LPTCITEM>(lParam);
TabData tabData = {0};
tabData.isCloseable = TRUE;
pDetails->mask &= ~TCIF_NOINTERCEPTION;
if(flags.silentTabInsertions == 0) {
tabData.lParam = pDetails->lParam;
pDetails->lParam = GetNewTabID();
pDetails->mask |= TCIF_PARAM;
}
insertedTab = DefWindowProc(message, wParam, lParam);
if(insertedTab != -1) {
if(!dragDropStatus.IsDragging() && properties.closeableTabs) {
mouseStatus.overCloseButtonOnMouseDown = -1;
UINT hitTestDetails = 0;
POINT mousePosition = {0};
GetCursorPos(&mousePosition);
ScreenToClient(&mousePosition);
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
mouseStatus.overCloseButton = tabIndex;
if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else if(mouseStatus.overCloseButton != -1) {
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, mouseStatus.overCloseButton == SendMessage(TCM_GETCURSEL, 0, 0), &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
mouseStatus.overCloseButton = -1;
}
}
if(flags.silentTabInsertions == 0) {
/* NOTE: Activating silent insertions implies that the 'tabIDs' vector and the 'tabParams' list
have to be updated explicitly. */
#ifdef USE_STL
if(insertedTab >= static_cast<int>(tabIDs.size())) {
tabIDs.push_back(static_cast<LONG>(pDetails->lParam));
} else {
tabIDs.insert(tabIDs.begin() + insertedTab, static_cast<LONG>(pDetails->lParam));
}
std::list<TabData>::iterator iter2 = tabParams.begin();
if(iter2 != tabParams.end()) {
std::advance(iter2, insertedTab);
}
tabParams.insert(iter2, tabData);
#else
if(insertedTab >= static_cast<int>(tabIDs.GetCount())) {
tabIDs.Add(static_cast<LONG>(pDetails->lParam));
} else {
tabIDs.InsertAt(insertedTab, static_cast<LONG>(pDetails->lParam));
}
POSITION p = tabParams.FindIndex(insertedTab);
if(p) {
tabParams.InsertBefore(p, tabData);
} else {
tabParams.AddTail(tabData);
}
#endif
}
if(insertedTab <= cachedSettings.dropHilitedTab) {
++cachedSettings.dropHilitedTab;
}
if(insertedTab <= insertMark.tabIndex) {
++insertMark.tabIndex;
}
RebuildAcceleratorTable();
}
}
if(!(properties.disabledEvents & deMouseEvents)) {
if(insertedTab != -1) {
// maybe we have a new tab below the mouse cursor now
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
UINT hitTestDetails = 0;
int newTabUnderMouse = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
if(newTabUnderMouse != tabUnderMouse) {
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
if(tabUnderMouse != -1) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabUnderMouse, this);
Raise_TabMouseLeave(pTSTab, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
}
tabUnderMouse = newTabUnderMouse;
if(tabUnderMouse != -1) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabUnderMouse, this);
Raise_TabMouseEnter(pTSTab, button, shift, mousePosition.x, mousePosition.y, hitTestDetails);
}
}
}
}
// HACK: we've somehow to initialize caretChangedStatus and activeTabChangedStatus
if((GetStyle() & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) {
int caretTab = SendMessage(TCM_GETCURFOCUS, 0, 0);
if(caretTab != caretChangedStatus.previousCaretTab) {
Raise_CaretChanged(caretChangedStatus.previousCaretTab, caretTab);
}
}
int activeTab = SendMessage(TCM_GETCURSEL, 0, 0);
if(activeTab != activeTabChangedStatus.previousActiveTab) {
Raise_ActiveTabChanged(activeTabChangedStatus.previousActiveTab, activeTab);
}
return insertedTab;
}
LRESULT TabStrip::OnSetCurFocus(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = DefWindowProc(message, wParam, lParam);
if((GetStyle() & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0) {
Raise_CaretChanged(caretChangedStatus.previousCaretTab, wParam);
}
return lr;
}
LRESULT TabStrip::OnSetCurSel(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
VARIANT_BOOL cancel = VARIANT_FALSE;
Raise_ActiveTabChanging(activeTabChangedStatus.previousActiveTab, &cancel);
if(cancel == VARIANT_FALSE) {
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(lr != -1) {
Raise_ActiveTabChanged(activeTabChangedStatus.previousActiveTab, wParam);
}
return lr;
}
return -1;
}
LRESULT TabStrip::OnSetExtendedStyle(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LRESULT lr = DefWindowProc(message, wParam & ~TCS_EX_DETECTDRAGDROP, lParam & ~TCS_EX_DETECTDRAGDROP);
if(properties.allowDragDrop) {
lr |= TCS_EX_DETECTDRAGDROP;
}
if((wParam == 0) || ((wParam & TCS_EX_DETECTDRAGDROP) == TCS_EX_DETECTDRAGDROP)) {
properties.allowDragDrop = ((lParam & TCS_EX_DETECTDRAGDROP) == TCS_EX_DETECTDRAGDROP);
}
return lr;
}
LRESULT TabStrip::OnSetImageList(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_HIMAGELIST) == S_FALSE) {
return 0;
}
/* We must store the new settings before the call to DefWindowProc, because we may need them to
handle the WM_PAINT message this message probably will cause. */
cachedSettings.hImageList = reinterpret_cast<HIMAGELIST>(lParam);
LRESULT lr = DefWindowProc(message, wParam, lParam);
// TODO: Isn't there a better way for correcting the values if an error occured?
cachedSettings.hImageList = reinterpret_cast<HIMAGELIST>(SendMessage(TCM_GETIMAGELIST, 0, 0));
FireOnChanged(DISPID_TABSTRIPCTL_HIMAGELIST);
return lr;
}
LRESULT TabStrip::OnSetInsertMark(UINT /*message*/, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
RECT oldInsertMarkRect = {0};
RECT newInsertMarkRect = {0};
if(insertMark.tabIndex != -1) {
// calculate the current insertion mark's rectangle
RECT tabBoundingRectangle = {0};
SendMessage(TCM_GETITEMRECT, insertMark.tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle));
if(GetStyle() & TCS_VERTICAL) {
if(insertMark.afterTab) {
oldInsertMarkRect.top = tabBoundingRectangle.bottom - 4;
oldInsertMarkRect.bottom = tabBoundingRectangle.bottom + 4;
} else {
oldInsertMarkRect.top = tabBoundingRectangle.top - 4;
oldInsertMarkRect.bottom = tabBoundingRectangle.top + 4;
}
oldInsertMarkRect.left = tabBoundingRectangle.left;
oldInsertMarkRect.right = tabBoundingRectangle.right;
} else {
if(insertMark.afterTab) {
oldInsertMarkRect.left = tabBoundingRectangle.right - 4;
oldInsertMarkRect.right = tabBoundingRectangle.right + 4;
} else {
oldInsertMarkRect.left = tabBoundingRectangle.left - 4;
oldInsertMarkRect.right = tabBoundingRectangle.left + 4;
}
oldInsertMarkRect.top = tabBoundingRectangle.top;
oldInsertMarkRect.bottom = tabBoundingRectangle.bottom;
}
}
insertMark.ProcessSetInsertMark(wParam, lParam);
if(insertMark.tabIndex != -1) {
// calculate the new insertion mark's rectangle
RECT tabBoundingRectangle = {0};
SendMessage(TCM_GETITEMRECT, insertMark.tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle));
if(GetStyle() & TCS_VERTICAL) {
if(insertMark.afterTab) {
newInsertMarkRect.top = tabBoundingRectangle.bottom - 4;
newInsertMarkRect.bottom = tabBoundingRectangle.bottom + 4;
} else {
newInsertMarkRect.top = tabBoundingRectangle.top - 4;
newInsertMarkRect.bottom = tabBoundingRectangle.top + 4;
}
newInsertMarkRect.left = tabBoundingRectangle.left;
newInsertMarkRect.right = tabBoundingRectangle.right;
} else {
if(insertMark.afterTab) {
newInsertMarkRect.left = tabBoundingRectangle.right - 4;
newInsertMarkRect.right = tabBoundingRectangle.right + 4;
} else {
newInsertMarkRect.left = tabBoundingRectangle.left - 4;
newInsertMarkRect.right = tabBoundingRectangle.left + 4;
}
newInsertMarkRect.top = tabBoundingRectangle.top;
newInsertMarkRect.bottom = tabBoundingRectangle.bottom;
}
}
// redraw
if(oldInsertMarkRect.right - oldInsertMarkRect.left > 0) {
InvalidateRect(&oldInsertMarkRect);
}
if(newInsertMarkRect.right - newInsertMarkRect.left > 0) {
InvalidateRect(&newInsertMarkRect);
}
// always succeed
return TRUE;
}
LRESULT TabStrip::OnSetInsertMarkColor(UINT /*message*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_INSERTMARKCOLOR) == S_FALSE) {
return 0;
}
COLORREF previousColor = insertMark.color;
insertMark.color = static_cast<COLORREF>(lParam);
// calculate insertion mark rectangle
RECT tabBoundingRectangle = {0};
SendMessage(TCM_GETITEMRECT, insertMark.tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle));
RECT insertMarkRect = {0};
if(GetStyle() & TCS_VERTICAL) {
if(insertMark.afterTab) {
insertMarkRect.top = tabBoundingRectangle.bottom - 4;
insertMarkRect.bottom = tabBoundingRectangle.bottom + 4;
} else {
insertMarkRect.top = tabBoundingRectangle.top - 4;
insertMarkRect.bottom = tabBoundingRectangle.top + 4;
}
insertMarkRect.left = tabBoundingRectangle.left;
insertMarkRect.right = tabBoundingRectangle.right;
} else {
if(insertMark.afterTab) {
insertMarkRect.left = tabBoundingRectangle.right - 4;
insertMarkRect.right = tabBoundingRectangle.right + 4;
} else {
insertMarkRect.left = tabBoundingRectangle.left - 4;
insertMarkRect.right = tabBoundingRectangle.left + 4;
}
insertMarkRect.top = tabBoundingRectangle.top;
insertMarkRect.bottom = tabBoundingRectangle.bottom;
}
// redraw this rectangle
InvalidateRect(&insertMarkRect);
SetDirty(TRUE);
FireOnChanged(DISPID_TABSTRIPCTL_INSERTMARKCOLOR);
return previousColor;
}
LRESULT TabStrip::OnSetItem(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
LPTCITEM pTabData = reinterpret_cast<LPTCITEM>(lParam);
#ifdef DEBUG
if(message == TCM_SETITEMA) {
ATLASSERT_POINTER(pTabData, TCITEMA);
} else {
ATLASSERT_POINTER(pTabData, TCITEMW);
}
#endif
if(!pTabData) {
return DefWindowProc(message, wParam, lParam);
}
if(pTabData->mask & TCIF_NOINTERCEPTION) {
// SysTabControl32 shouldn't see this flag
pTabData->mask &= ~TCIF_NOINTERCEPTION;
} else if(pTabData->mask == LVIF_PARAM) {
// simply update the 'tabParams' list
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, wParam);
if(iter != tabParams.end()) {
iter->lParam = pTabData->lParam;
return TRUE;
}
}
#else
POSITION p = tabParams.FindIndex(wParam);
if(p) {
tabParams.GetAt(p).lParam = pTabData->lParam;
return TRUE;
}
#endif
// tab not found
return FALSE;
} else if(pTabData->mask & TCIF_PARAM) {
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, wParam);
if(iter != tabParams.end()) {
iter->lParam = pTabData->lParam;
pTabData->mask &= ~TCIF_PARAM;
}
}
#else
POSITION p = tabParams.FindIndex(wParam);
if(p) {
tabParams.GetAt(p).lParam = pTabData->lParam;
pTabData->mask &= ~TCIF_PARAM;
}
#endif
}
if(properties.disabledEvents & deTabSelectionChanged) {
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(lr) {
if(pTabData->mask & TCIF_STATE) {
if(pTabData->dwStateMask & TCIS_HIGHLIGHTED) {
if(static_cast<int>(wParam) == cachedSettings.dropHilitedTab) {
if((pTabData->dwState & TCIS_HIGHLIGHTED) == 0) {
// TCIS_HIGHLIGHTED was removed
cachedSettings.dropHilitedTab = -1;
}
}
}
}
if(pTabData->mask & TCIF_TEXT) {
RebuildAcceleratorTable();
}
}
return lr;
} else {
// retrieve the current selection state
TCITEM tab = {0};
if(flags.silentSelectionChanges == 0) {
tab.dwStateMask = TCIS_BUTTONPRESSED;
tab.mask = TCIF_STATE;
SendMessage(TCM_GETITEM, wParam, reinterpret_cast<LPARAM>(&tab));
}
DWORD previousState = (tab.dwState & TCIS_BUTTONPRESSED);
// let SysTabControl32 handle the message
LRESULT lr = DefWindowProc(message, wParam, lParam);
if(lr) {
if(pTabData->mask & TCIF_STATE) {
if(pTabData->dwStateMask & TCIS_HIGHLIGHTED) {
if(static_cast<int>(wParam) == cachedSettings.dropHilitedTab) {
if((pTabData->dwState & TCIS_HIGHLIGHTED) == 0) {
// TCIS_HIGHLIGHTED was removed
cachedSettings.dropHilitedTab = -1;
}
}
}
}
if(pTabData->mask & TCIF_TEXT) {
RebuildAcceleratorTable();
}
}
if(flags.silentSelectionChanges == 0) {
// check for selection change
SendMessage(TCM_GETITEM, wParam, reinterpret_cast<LPARAM>(&tab));
if((tab.dwState & TCIS_BUTTONPRESSED) != previousState) {
Raise_TabSelectionChanged(wParam);
}
}
return lr;
}
}
LRESULT TabStrip::OnSetItemSize(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_FIXEDTABWIDTH) == S_FALSE || FireOnRequestEdit(DISPID_TABSTRIPCTL_TABHEIGHT) == S_FALSE) {
return 0;
}
properties.fixedTabWidth = GET_X_LPARAM(lParam);
properties.tabHeight = GET_Y_LPARAM(lParam);
LRESULT lr = DefWindowProc(message, wParam, lParam);
FireOnChanged(DISPID_TABSTRIPCTL_FIXEDTABWIDTH);
FireOnChanged(DISPID_TABSTRIPCTL_TABHEIGHT);
return lr;
}
LRESULT TabStrip::OnSetMinTabWidth(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_MINTABWIDTH) == S_FALSE) {
return 0;
}
properties.minTabWidth = lParam;
LRESULT lr = DefWindowProc(message, wParam, lParam);
FireOnChanged(DISPID_TABSTRIPCTL_MINTABWIDTH);
return lr;
}
LRESULT TabStrip::OnSetPadding(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/)
{
if(FireOnRequestEdit(DISPID_TABSTRIPCTL_HORIZONTALPADDING) == S_FALSE || FireOnRequestEdit(DISPID_TABSTRIPCTL_VERTICALPADDING) == S_FALSE) {
return 0;
}
properties.horizontalPadding = GET_X_LPARAM(lParam);
properties.verticalPadding = GET_Y_LPARAM(lParam);
LRESULT lr = DefWindowProc(message, wParam, lParam);
FireOnChanged(DISPID_TABSTRIPCTL_HORIZONTALPADDING);
FireOnChanged(DISPID_TABSTRIPCTL_VERTICALPADDING);
return lr;
}
LRESULT TabStrip::OnToolTipGetDispInfoNotificationA(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/)
{
LPNMTTDISPINFOA pDetails = reinterpret_cast<LPNMTTDISPINFOA>(pNotificationDetails);
ATLASSERT_POINTER(pDetails, NMTTDISPINFOA);
if(!pDetails || pDetails->hdr.hwndFrom != reinterpret_cast<HWND>(SendMessage(TCM_GETTOOLTIPS, 0, 0))) {
return 0;
}
ZeroMemory(pToolTipBuffer, MAX_PATH * sizeof(CHAR));
BSTR tooltip = NULL;
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(pDetails->hdr.idFrom, this);
Raise_TabGetInfoTipText(pTSTab, MAX_PATH, &tooltip);
if(lstrlenA(CW2A(tooltip)) > 0) {
lstrcpynA(reinterpret_cast<LPSTR>(pToolTipBuffer), CW2A(tooltip), MAX_PATH);
}
pDetails->lpszText = reinterpret_cast<LPSTR>(pToolTipBuffer);
return 0;
}
LRESULT TabStrip::OnToolTipGetDispInfoNotificationW(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/)
{
LPNMTTDISPINFOW pDetails = reinterpret_cast<LPNMTTDISPINFOW>(pNotificationDetails);
ATLASSERT_POINTER(pDetails, NMTTDISPINFOW);
if(!pDetails || pDetails->hdr.hwndFrom != reinterpret_cast<HWND>(SendMessage(TCM_GETTOOLTIPS, 0, 0))) {
return 0;
}
ZeroMemory(pToolTipBuffer, MAX_PATH * sizeof(WCHAR));
BSTR tooltip = NULL;
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(pDetails->hdr.idFrom, this);
Raise_TabGetInfoTipText(pTSTab, MAX_PATH, &tooltip);
//#ifdef UNICODE
if(lstrlenW(CW2CW(tooltip)) > 0) {
lstrcpynW(reinterpret_cast<LPWSTR>(pToolTipBuffer), CW2CW(tooltip), MAX_PATH);
}
//#else
//OSVERSIONINFO ovi = {sizeof(OSVERSIONINFO)};
//if(GetVersionEx(&ovi) && (ovi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)) {
// /* HACK: On Windows 9x strange things happen. Instead of the ANSI notification, the Unicode
// notification is sent. This isn't really a problem, but lstrcpynW() seems to be broken. */
// LPCWSTR pToolTip = CW2CW(tooltip);
// if(lstrlenW(pToolTip) > 0) {
// // as lstrcpynW() seems to be broken, copy the string manually
// LPWSTR tmp = reinterpret_cast<LPWSTR>(pToolTipBuffer);
// for(int i = 0; (*pToolTip != 0) && (i < MAX_PATH); ++i, ++pToolTip, ++tmp) {
// *tmp = *pToolTip;
// }
// *tmp = 0;
// }
//} else {
// if(lstrlenW(CW2CW(tooltip)) > 0) {
// lstrcpynW(reinterpret_cast<LPWSTR>(pToolTipBuffer), CW2CW(tooltip), MAX_PATH);
// }
//}
//#endif
pDetails->lpszText = reinterpret_cast<LPWSTR>(pToolTipBuffer);
return 0;
}
LRESULT TabStrip::OnClickNotification(int /*controlID*/, LPNMHDR /*pNotificationDetails*/, BOOL& /*wasHandled*/)
{
if(!(properties.disabledEvents & deClickEvents)) {
// SysTabControl32 sends NM_CLICK on each WM_LBUTTONUP
if(mouseStatus.ignoreNM_CLICK) {
mouseStatus.ignoreNM_CLICK = FALSE;
} else {
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
button |= 1/*MouseButtonConstants.vbLeftButton*/;
Raise_Click(button, shift, mousePosition.x, mousePosition.y);
}
}
if(properties.closeableTabs && properties.closeableTabsMode == ctmDisplayOnActiveTab && mouseStatus.overCloseButtonOnMouseDown == -2 && !dragDropStatus.IsDragging()) {
mouseStatus.overCloseButtonOnMouseDown = -1;
UINT hitTestDetails = 0;
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
int tabIndex = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
if(hitTestDetails & TCHT_CLOSEBUTTON) {
mouseStatus.overCloseButton = tabIndex;
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, TRUE, &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else {
mouseStatus.overCloseButtonOnMouseDown = -1;
}
return 0;
}
LRESULT TabStrip::OnRClickNotification(int /*controlID*/, LPNMHDR /*pNotificationDetails*/, BOOL& /*wasHandled*/)
{
if(!(properties.disabledEvents & deClickEvents)) {
// SysTabControl32 sends NM_RCLICK on each WM_RBUTTONUP
if(mouseStatus.ignoreNM_RCLICK) {
mouseStatus.ignoreNM_RCLICK = FALSE;
} else {
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
button |= 2/*MouseButtonConstants.vbRightButton*/;
Raise_RClick(button, shift, mousePosition.x, mousePosition.y);
}
}
return 0;
}
LRESULT TabStrip::OnBeginDragNotification(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/)
{
LPNMTCBEGINDRAG pDetails = reinterpret_cast<LPNMTCBEGINDRAG>(pNotificationDetails);
ATLASSERT_POINTER(pDetails, NMTCBEGINDRAG);
if(!pDetails) {
return 0;
}
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
button |= 1/*MouseButtonConstants.vbLeftButton*/;
POINT mousePosition = pDetails->ptDrag;
UINT hitTestDetails = 0;
HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(pDetails->iItem, this);
Raise_TabBeginDrag(pTSTab, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails));
return 0;
}
LRESULT TabStrip::OnBeginRDragNotification(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/)
{
LPNMTCBEGINDRAG pDetails = reinterpret_cast<LPNMTCBEGINDRAG>(pNotificationDetails);
ATLASSERT_POINTER(pDetails, NMTCBEGINDRAG);
if(!pDetails) {
return 0;
}
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
button |= 2/*MouseButtonConstants.vbRightButton*/;
POINT mousePosition = pDetails->ptDrag;
UINT hitTestDetails = 0;
HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(pDetails->iItem, this);
Raise_TabBeginRDrag(pTSTab, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails));
return 0;
}
LRESULT TabStrip::OnFocusChangeNotification(int /*controlID*/, LPNMHDR /*pNotificationDetails*/, BOOL& /*wasHandled*/)
{
int tabIndex = SendMessage(TCM_GETCURFOCUS, 0, 0);
Raise_CaretChanged(caretChangedStatus.previousCaretTab, tabIndex);
return 0;
}
LRESULT TabStrip::OnGetObjectNotification(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/)
{
LPNMOBJECTNOTIFY pDetails = reinterpret_cast<LPNMOBJECTNOTIFY>(pNotificationDetails);
ATLASSERT(*(pDetails->piid) == IID_IDropTarget);
pDetails->hResult = QueryInterface(*(pDetails->piid), &pDetails->pObject);
return 0;
}
LRESULT TabStrip::OnSelChangeNotification(int /*controlID*/, LPNMHDR /*pNotificationDetails*/, BOOL& /*wasHandled*/)
{
if(properties.closeableTabs) {
// redraw around the arrow buttons
CWindow arrowButtons = GetDlgItem(1);
CRect rc;
arrowButtons.GetWindowRect(&rc);
rc.InflateRect(5, 5);
ScreenToClient(&rc);
InvalidateRect(&rc);
}
int tabIndex = SendMessage(TCM_GETCURSEL, 0, 0);
Raise_ActiveTabChanged(activeTabChangedStatus.previousActiveTab, tabIndex);
return 0;
}
LRESULT TabStrip::OnSelChangingNotification(int /*controlID*/, LPNMHDR /*pNotificationDetails*/, BOOL& /*wasHandled*/)
{
activeTabChangedStatus.previousActiveTab = SendMessage(TCM_GETCURSEL, 0, 0);
VARIANT_BOOL cancel = VARIANT_FALSE;
Raise_ActiveTabChanging(activeTabChangedStatus.previousActiveTab, &cancel);
return (cancel != VARIANT_FALSE);
}
void TabStrip::ApplyFont(void)
{
properties.font.dontGetFontObject = TRUE;
if(IsWindow()) {
if(!properties.font.owningFontResource) {
properties.font.currentFont.Detach();
}
properties.font.currentFont.Attach(NULL);
if(properties.useSystemFont) {
// use the system font
properties.font.currentFont.Attach(static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT)));
properties.font.owningFontResource = FALSE;
// apply the font
SendMessage(WM_SETFONT, reinterpret_cast<WPARAM>(static_cast<HFONT>(properties.font.currentFont)), MAKELPARAM(TRUE, 0));
} else {
/* The whole font object or at least some of its attributes were changed. 'font.pFontDisp' is
still valid, so simply update our font. */
if(properties.font.pFontDisp) {
CComQIPtr<IFont, &IID_IFont> pFont(properties.font.pFontDisp);
if(pFont) {
HFONT hFont = NULL;
pFont->get_hFont(&hFont);
properties.font.currentFont.Attach(hFont);
properties.font.owningFontResource = FALSE;
SendMessage(WM_SETFONT, reinterpret_cast<WPARAM>(static_cast<HFONT>(properties.font.currentFont)), MAKELPARAM(TRUE, 0));
} else {
SendMessage(WM_SETFONT, NULL, MAKELPARAM(TRUE, 0));
}
} else {
SendMessage(WM_SETFONT, NULL, MAKELPARAM(TRUE, 0));
}
Invalidate();
}
}
properties.font.dontGetFontObject = FALSE;
FireViewChange();
}
inline HRESULT TabStrip::Raise_AbortedDrag(void)
{
//if(m_nFreezeEvents == 0) {
return Fire_AbortedDrag();
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_ActiveTabChanged(int previousActiveTab, int newActiveTab)
{
HWND hWndToShow = GetAssociatedWindow(newActiveTab);
if(hWndToShow && ::IsWindow(hWndToShow)) {
::ShowWindow(hWndToShow, SW_SHOW);
}
if(newActiveTab == previousActiveTab) {
return S_OK;
}
if(!(GetStyle() & (TCS_FLATBUTTONS | TCS_BUTTONS))) {
Raise_CaretChanged(previousActiveTab, newActiveTab);
}
activeTabChangedStatus.previousActiveTab = newActiveTab;
HRESULT hr = S_OK;
if(flags.silentActiveTabChanges == 0) {
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pPreviousActiveTab = ClassFactory::InitTabStripTab(previousActiveTab, this);
CComPtr<ITabStripTab> pNewActiveTab = ClassFactory::InitTabStripTab(newActiveTab, this);
hr = Fire_ActiveTabChanged(pPreviousActiveTab, pNewActiveTab);
//}
}
if(!(properties.disabledEvents & deTabSelectionChanged)) {
if(flags.silentSelectionChanges == 0) {
// now retrieve the selection states again and raise the TabSelectionChanged event if necessary
TCITEM tab = {0};
tab.dwStateMask = TCIS_BUTTONPRESSED;
tab.mask = TCIF_STATE;
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
#ifdef USE_STL
if(numberOfTabs == static_cast<int>(activeTabChangedStatus.selectionStatesBeforeChange.size())) {
#else
if(numberOfTabs == static_cast<int>(activeTabChangedStatus.selectionStatesBeforeChange.GetCount())) {
#endif
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
if(tabIndex != newActiveTab) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
if((tab.dwState & TCIS_BUTTONPRESSED) != activeTabChangedStatus.selectionStatesBeforeChange[tabIndex]) {
Raise_TabSelectionChanged(tabIndex);
}
}
}
}
}
#ifdef USE_STL
activeTabChangedStatus.selectionStatesBeforeChange.clear();
#else
activeTabChangedStatus.selectionStatesBeforeChange.RemoveAll();
#endif
if(flags.silentSelectionChanges == 0) {
if(newActiveTab != -1) {
Raise_TabSelectionChanged(newActiveTab);
}
}
}
return hr;
}
inline HRESULT TabStrip::Raise_ActiveTabChanging(int previousActiveTab, VARIANT_BOOL* pCancel)
{
HRESULT hr = S_OK;
if(flags.silentActiveTabChanges == 0) {
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pPreviousActiveTab = ClassFactory::InitTabStripTab(previousActiveTab, this);
hr = Fire_ActiveTabChanging(pPreviousActiveTab, pCancel);
//}
}
if(*pCancel == VARIANT_FALSE) {
HWND hWndToHide = GetAssociatedWindow(previousActiveTab);
if(hWndToHide && ::IsWindow(hWndToHide)) {
::ShowWindow(hWndToHide, SW_HIDE);
}
if(!(properties.disabledEvents & deTabSelectionChanged)) {
// store the selection states before the change
TCITEM tab = {0};
tab.dwStateMask = TCIS_BUTTONPRESSED;
tab.mask = TCIF_STATE;
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
#ifdef USE_STL
activeTabChangedStatus.selectionStatesBeforeChange.push_back(tab.dwState & TCIS_BUTTONPRESSED);
#else
activeTabChangedStatus.selectionStatesBeforeChange.Add(tab.dwState & TCIS_BUTTONPRESSED);
#endif
}
}
}
return hr;
}
inline HRESULT TabStrip::Raise_CaretChanged(int previousCaretTab, int newCaretTab)
{
if(newCaretTab == previousCaretTab) {
return S_OK;
}
caretChangedStatus.previousCaretTab = newCaretTab;
if(flags.silentCaretChanges == 0) {
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pPreviousCaretTab = ClassFactory::InitTabStripTab(previousCaretTab, this);
CComPtr<ITabStripTab> pNewCaretTab = ClassFactory::InitTabStripTab(newCaretTab, this);
return Fire_CaretChanged(pPreviousCaretTab, pNewCaretTab);
//}
}
return S_OK;
}
inline HRESULT TabStrip::Raise_Click(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
mouseStatus.lastClickedTab = HitTest(x, y, &hitTestDetails);
if(properties.closeableTabs && properties.closeableTabsMode == ctmDisplayOnActiveTab && mouseStatus.overCloseButtonOnMouseDown == -2 && !dragDropStatus.IsDragging()) {
mouseStatus.overCloseButtonOnMouseDown = -1;
UINT hitTestDetails2 = 0;
int tabIndex = HitTest(x, y, &hitTestDetails2, TRUE);
if(hitTestDetails2 & TCHT_CLOSEBUTTON) {
mouseStatus.overCloseButton = tabIndex;
RECT closeButtonRectangle = {0};
if(CalculateCloseButtonRectangle(mouseStatus.overCloseButton, TRUE, &closeButtonRectangle)) {
InvalidateRect(&closeButtonRectangle);
}
}
} else {
mouseStatus.overCloseButtonOnMouseDown = -1;
}
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(mouseStatus.lastClickedTab, this);
return Fire_Click(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_ContextMenu(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
//if(m_nFreezeEvents == 0) {
if((x == -1) && (y == -1)) {
// the event was caused by the keyboard
if(properties.processContextMenuKeys) {
// retrieve the focused tab and propose its rectangle's middle as the menu's position
int tabIndex = SendMessage(TCM_GETCURFOCUS, 0, 0);
if(tabIndex != -1) {
CRect tabRectangle;
if(SendMessage(TCM_GETITEMRECT, tabIndex, reinterpret_cast<LPARAM>(&tabRectangle))) {
CPoint centerPoint = tabRectangle.CenterPoint();
x = centerPoint.x;
y = centerPoint.y;
}
}
} else {
return S_OK;
}
}
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_ContextMenu(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_DblClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
if(tabIndex != mouseStatus.lastClickedTab) {
tabIndex = -1;
}
mouseStatus.lastClickedTab = -1;
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_DblClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_DestroyedControlWindow(LONG hWnd)
{
//KillTimer(timers.ID_REDRAW);
RemoveTabFromTabContainers(-1);
#ifdef USE_STL
tabIDs.clear();
tabParams.clear();
#else
tabIDs.RemoveAll();
tabParams.RemoveAll();
#endif
if(properties.registerForOLEDragDrop == rfoddAdvancedDragDrop) {
ATLVERIFY(RevokeDragDrop(*this) == S_OK);
}
//if(m_nFreezeEvents == 0) {
return Fire_DestroyedControlWindow(hWnd);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_DragMouseMove(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
if(dragDropStatus.hDragImageList) {
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ImageList_DragMove(mousePosition.x, mousePosition.y);
}
UINT hitTestDetails = 0;
int dropTarget = HitTest(x, y, &hitTestDetails, TRUE);
ITabStripTab* pDropTarget = NULL;
ClassFactory::InitTabStripTab(dropTarget, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(&pDropTarget));
VARIANT_BOOL autoActivateTab = VARIANT_TRUE;
if(dropTarget == -1) {
autoActivateTab = VARIANT_FALSE;
}
LONG autoScrollVelocity = 0;
BOOL handleAutoScroll = FALSE;
if(((GetStyle() & TCS_MULTILINE) == 0) && ((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_REGISTERDROP) == 0) && (properties.dragScrollTimeBase != 0)) {
handleAutoScroll = TRUE;
/* Use a 16 pixels wide border at both ends of the tab bar as the zone for auto-scrolling.
Are we within this zone? */
CPoint mousePos(x, y);
CRect noScrollZone(0, 0, 0, 0);
GetWindowRect(&noScrollZone);
ScreenToClient(&noScrollZone);
BOOL rightToLeft = ((GetExStyle() & WS_EX_LAYOUTRTL) == WS_EX_LAYOUTRTL);
if(rightToLeft) {
// noScrollZone is right to left, too, and PtInRect doesn't like that
LONG buffer = noScrollZone.left;
noScrollZone.left = noScrollZone.right;
noScrollZone.right = buffer;
}
BOOL isInScrollZone = noScrollZone.PtInRect(mousePos);
if(isInScrollZone) {
// we're within the window rectangle, so do further checks
if(GetStyle() & TCS_BOTTOM) {
noScrollZone.DeflateRect(properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH, 0);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y < noScrollZone.bottom - properties.tabHeight));
} else {
noScrollZone.DeflateRect(properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH, 0);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y > noScrollZone.top + properties.tabHeight));
}
}
if(rightToLeft) {
// mousePos is right to left, so make noScrollZone right to left again
LONG buffer = noScrollZone.left;
noScrollZone.left = noScrollZone.right;
noScrollZone.right = buffer;
}
if(isInScrollZone) {
// we're within the default scroll zone - propose a velocity
if(mousePos.x < noScrollZone.left) {
autoScrollVelocity = -1;
} else if(mousePos.x >= noScrollZone.right) {
autoScrollVelocity = 1;
}
}
}
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
hr = Fire_DragMouseMove(&pDropTarget, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails), &autoActivateTab, &autoScrollVelocity);
//}
if(pDropTarget) {
LONG l = -1;
pDropTarget->get_Index(&l);
dropTarget = l;
// we don't want to produce a mem-leak...
pDropTarget->Release();
} else {
dropTarget = -1;
}
if(autoActivateTab == VARIANT_FALSE) {
// cancel auto-activation
KillTimer(timers.ID_DRAGACTIVATE);
} else {
if(dropTarget != dragDropStatus.lastDropTarget) {
// cancel auto-activation of previous target
KillTimer(timers.ID_DRAGACTIVATE);
if(properties.dragActivateTime != 0) {
// start timered auto-activation of new target
SetTimer(timers.ID_DRAGACTIVATE, (properties.dragActivateTime == -1 ? GetDoubleClickTime() : properties.dragActivateTime));
}
}
}
dragDropStatus.lastDropTarget = dropTarget;
if(handleAutoScroll) {
dragDropStatus.autoScrolling.currentScrollVelocity = autoScrollVelocity;
LONG smallestInterval = abs(autoScrollVelocity);
if(smallestInterval) {
smallestInterval = (properties.dragScrollTimeBase == -1 ? GetDoubleClickTime() / 4 : properties.dragScrollTimeBase) / smallestInterval;
if(smallestInterval == 0) {
smallestInterval = 1;
}
}
if(smallestInterval != dragDropStatus.autoScrolling.currentTimerInterval) {
// reset the timer
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = smallestInterval;
if(smallestInterval != 0) {
SetTimer(timers.ID_DRAGSCROLL, smallestInterval);
}
}
if(smallestInterval) {
/* Scroll immediately to avoid the theoretical situation where the timer interval is changed
faster than the timer fires so the control never is scrolled. */
AutoScroll();
}
} else {
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = 0;
}
return hr;
}
inline HRESULT TabStrip::Raise_Drop(void)
{
//if(m_nFreezeEvents == 0) {
DWORD position = GetMessagePos();
POINT mousePosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
ScreenToClient(&mousePosition);
UINT hitTestDetails = 0;
int dropTarget = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
CComPtr<ITabStripTab> pDropTarget = ClassFactory::InitTabStripTab(dropTarget, this);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
return Fire_Drop(pDropTarget, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_FreeTabData(ITabStripTab* pTSTab)
{
//if(m_nFreezeEvents == 0) {
return Fire_FreeTabData(pTSTab);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_InsertedTab(ITabStripTab* pTSTab)
{
//if(m_nFreezeEvents == 0) {
return Fire_InsertedTab(pTSTab);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_InsertingTab(IVirtualTabStripTab* pTSTab, VARIANT_BOOL* pCancel)
{
//if(m_nFreezeEvents == 0) {
return Fire_InsertingTab(pTSTab, pCancel);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_KeyDown(SHORT* pKeyCode, SHORT shift)
{
//if(m_nFreezeEvents == 0) {
return Fire_KeyDown(pKeyCode, shift);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_KeyPress(SHORT* pKeyAscii)
{
//if(m_nFreezeEvents == 0) {
return Fire_KeyPress(pKeyAscii);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_KeyUp(SHORT* pKeyCode, SHORT shift)
{
//if(m_nFreezeEvents == 0) {
return Fire_KeyUp(pKeyCode, shift);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
mouseStatus.lastClickedTab = HitTest(x, y, &hitTestDetails);
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(mouseStatus.lastClickedTab, this);
return Fire_MClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MDblClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
if(tabIndex != mouseStatus.lastClickedTab) {
tabIndex = -1;
}
mouseStatus.lastClickedTab = -1;
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_MDblClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MouseDown(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
if(!mouseStatus.enteredControl) {
Raise_MouseEnter(button, shift, x, y);
}
if(!mouseStatus.hoveredControl) {
TRACKMOUSEEVENT trackingOptions = {0};
trackingOptions.cbSize = sizeof(trackingOptions);
trackingOptions.hwndTrack = *this;
trackingOptions.dwFlags = TME_HOVER | TME_CANCEL;
TrackMouseEvent(&trackingOptions);
Raise_MouseHover(button, shift, x, y);
}
mouseStatus.StoreClickCandidate(button);
//if(m_nFreezeEvents == 0) {
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_MouseDown(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MouseEnter(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
TRACKMOUSEEVENT trackingOptions = {0};
trackingOptions.cbSize = sizeof(trackingOptions);
trackingOptions.hwndTrack = *this;
trackingOptions.dwHoverTime = (properties.hoverTime == -1 ? HOVER_DEFAULT : properties.hoverTime);
trackingOptions.dwFlags = TME_HOVER | TME_LEAVE;
TrackMouseEvent(&trackingOptions);
mouseStatus.EnterControl();
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
tabUnderMouse = tabIndex;
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
Fire_MouseEnter(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
if(pTSTab) {
Raise_TabMouseEnter(pTSTab, button, shift, x, y, hitTestDetails);
}
return hr;
}
inline HRESULT TabStrip::Raise_MouseHover(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
if(!mouseStatus.hoveredControl) {
mouseStatus.HoverControl();
//if(m_nFreezeEvents == 0) {
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_MouseHover(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
}
return S_OK;
}
inline HRESULT TabStrip::Raise_MouseLeave(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabUnderMouse, this);
if(pTSTab) {
Raise_TabMouseLeave(pTSTab, button, shift, x, y, hitTestDetails);
}
tabUnderMouse = -1;
mouseStatus.LeaveControl();
//if(m_nFreezeEvents == 0) {
pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_MouseLeave(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MouseMove(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
if(!mouseStatus.enteredControl) {
Raise_MouseEnter(button, shift, x, y);
}
mouseStatus.lastPosition.x = x;
mouseStatus.lastPosition.y = y;
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
// Do we move over another tab than before?
if(tabIndex != tabUnderMouse) {
CComPtr<ITabStripTab> pPrevTSTab = ClassFactory::InitTabStripTab(tabUnderMouse, this);
if(pPrevTSTab) {
Raise_TabMouseLeave(pPrevTSTab, button, shift, x, y, hitTestDetails);
}
tabUnderMouse = tabIndex;
if(pTSTab) {
Raise_TabMouseEnter(pTSTab, button, shift, x, y, hitTestDetails);
}
}
//if(m_nFreezeEvents == 0) {
return Fire_MouseMove(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_MouseUp(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
if(mouseStatus.IsClickCandidate(button)) {
/* Watch for clicks.
Are we still within the control's client area? */
BOOL hasLeftControl = FALSE;
DWORD position = GetMessagePos();
POINT cursorPosition = {GET_X_LPARAM(position), GET_Y_LPARAM(position)};
RECT clientArea;
GetClientRect(&clientArea);
ClientToScreen(&clientArea);
if(PtInRect(&clientArea, cursorPosition)) {
// maybe the control is overlapped by a foreign window
if(WindowFromPoint(cursorPosition) != *this) {
hasLeftControl = TRUE;
}
} else {
hasLeftControl = TRUE;
}
if(!hasLeftControl) {
// we don't have left the control, so raise the click event
switch(button) {
case 1/*MouseButtonConstants.vbLeftButton*/:
/*if(!(properties.disabledEvents & deClickEvents)) {
Raise_Click(button, shift, x, y);
}*/
break;
case 2/*MouseButtonConstants.vbRightButton*/:
/*if(!(properties.disabledEvents & deClickEvents)) {
Raise_RClick(button, shift, x, y);
}*/
break;
case 4/*MouseButtonConstants.vbMiddleButton*/:
if(!(properties.disabledEvents & deClickEvents)) {
Raise_MClick(button, shift, x, y);
}
break;
case embXButton1:
case embXButton2:
if(!(properties.disabledEvents & deClickEvents)) {
Raise_XClick(button, shift, x, y);
}
break;
}
}
mouseStatus.RemoveClickCandidate(button);
}
//if(m_nFreezeEvents == 0) {
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_MouseUp(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLECompleteDrag(IOLEDataObject* pData, OLEDropEffectConstants performedEffect)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLECompleteDrag(pData, performedEffect);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLEDragDrop(IDataObject* pData, DWORD* pEffect, DWORD keyState, POINTL mousePosition)
{
// NOTE: pData can be NULL
KillTimer(timers.ID_DRAGSCROLL);
KillTimer(timers.ID_DRAGACTIVATE);
ScreenToClient(reinterpret_cast<LPPOINT>(&mousePosition));
SHORT button = 0;
SHORT shift = 0;
OLEKEYSTATE2BUTTONANDSHIFT(keyState, button, shift);
UINT hitTestDetails = 0;
int dropTarget = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails, TRUE);
CComPtr<ITabStripTab> pDropTarget = ClassFactory::InitTabStripTab(dropTarget, this);
if(pData) {
/* Actually we wouldn't need the next line, because the data object passed to this method should
always be the same as the data object that was passed to Raise_OLEDragEnter. */
dragDropStatus.pActiveDataObject = ClassFactory::InitOLEDataObject(pData);
} else {
dragDropStatus.pActiveDataObject = NULL;
}
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
if(dragDropStatus.pActiveDataObject) {
hr = Fire_OLEDragDrop(dragDropStatus.pActiveDataObject, reinterpret_cast<OLEDropEffectConstants*>(pEffect), pDropTarget, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails));
}
//}
dragDropStatus.pActiveDataObject = NULL;
dragDropStatus.OLEDragLeaveOrDrop();
Invalidate();
return hr;
}
inline HRESULT TabStrip::Raise_OLEDragEnter(IDataObject* pData, DWORD* pEffect, DWORD keyState, POINTL mousePosition)
{
// NOTE: pData can be NULL
ScreenToClient(reinterpret_cast<LPPOINT>(&mousePosition));
SHORT button = 0;
SHORT shift = 0;
OLEKEYSTATE2BUTTONANDSHIFT(keyState, button, shift);
dragDropStatus.OLEDragEnter();
UINT hitTestDetails = 0;
int dropTarget = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
ITabStripTab* pDropTarget = NULL;
ClassFactory::InitTabStripTab(dropTarget, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(&pDropTarget));
VARIANT_BOOL autoActivateTab = VARIANT_TRUE;
if(dropTarget == -1) {
autoActivateTab = VARIANT_FALSE;
}
LONG autoScrollVelocity = 0;
BOOL handleAutoScroll = FALSE;
if(((GetStyle() & TCS_MULTILINE) == 0) && ((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_REGISTERDROP) == 0) && (properties.dragScrollTimeBase != 0)) {
handleAutoScroll = TRUE;
/* Use a 16 pixels wide border at both ends of the tab bar as the zone for auto-scrolling.
Are we within this zone? */
CPoint mousePos(mousePosition.x, mousePosition.y);
CRect noScrollZone(0, 0, 0, 0);
GetWindowRect(&noScrollZone);
ScreenToClient(&noScrollZone);
BOOL isInScrollZone = noScrollZone.PtInRect(mousePos);
if(isInScrollZone) {
// we're within the window rectangle, so do further checks
if(GetStyle() & TCS_BOTTOM) {
noScrollZone.DeflateRect(0, properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y < noScrollZone.bottom - properties.tabHeight));
} else {
noScrollZone.DeflateRect(properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH, 0);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y > noScrollZone.top + properties.tabHeight));
}
}
if(isInScrollZone) {
// we're within the default scroll zone - propose a velocity
if(mousePos.x < noScrollZone.left) {
autoScrollVelocity = -1;
} else if(mousePos.x >= noScrollZone.right) {
autoScrollVelocity = 1;
}
}
}
if(pData) {
dragDropStatus.pActiveDataObject = ClassFactory::InitOLEDataObject(pData);
} else {
dragDropStatus.pActiveDataObject = NULL;
}
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
if(dragDropStatus.pActiveDataObject) {
hr = Fire_OLEDragEnter(dragDropStatus.pActiveDataObject, reinterpret_cast<OLEDropEffectConstants*>(pEffect), &pDropTarget, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails), &autoActivateTab, &autoScrollVelocity);
}
//}
if(pDropTarget) {
// we're using a raw pointer
pDropTarget->Release();
}
if(autoActivateTab == VARIANT_FALSE) {
// cancel auto-activation
KillTimer(timers.ID_DRAGACTIVATE);
} else {
if(dropTarget != dragDropStatus.lastDropTarget) {
// cancel auto-activation of previous target
KillTimer(timers.ID_DRAGACTIVATE);
if(properties.dragActivateTime != 0) {
// start timered auto-activation of new target
SetTimer(timers.ID_DRAGACTIVATE, (properties.dragActivateTime == -1 ? GetDoubleClickTime() : properties.dragActivateTime));
}
}
}
dragDropStatus.lastDropTarget = dropTarget;
if(handleAutoScroll) {
dragDropStatus.autoScrolling.currentScrollVelocity = autoScrollVelocity;
LONG smallestInterval = abs(autoScrollVelocity);
if(smallestInterval) {
smallestInterval = (properties.dragScrollTimeBase == -1 ? GetDoubleClickTime() / 4 : properties.dragScrollTimeBase) / smallestInterval;
if(smallestInterval == 0) {
smallestInterval = 1;
}
}
if(smallestInterval != dragDropStatus.autoScrolling.currentTimerInterval) {
// reset the timer
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = smallestInterval;
if(smallestInterval != 0) {
SetTimer(timers.ID_DRAGSCROLL, smallestInterval);
}
}
if(smallestInterval) {
/* Scroll immediately to avoid the theoretical situation where the timer interval is changed
faster than the timer fires so the control never is scrolled. */
AutoScroll();
}
} else {
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = 0;
}
return hr;
}
inline HRESULT TabStrip::Raise_OLEDragEnterPotentialTarget(LONG hWndPotentialTarget)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLEDragEnterPotentialTarget(hWndPotentialTarget);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLEDragLeave(void)
{
KillTimer(timers.ID_DRAGSCROLL);
KillTimer(timers.ID_DRAGACTIVATE);
SHORT button = 0;
SHORT shift = 0;
WPARAM2BUTTONANDSHIFT(-1, button, shift);
UINT hitTestDetails = 0;
int dropTarget = HitTest(dragDropStatus.lastMousePosition.x, dragDropStatus.lastMousePosition.y, &hitTestDetails);
CComPtr<ITabStripTab> pDropTarget = ClassFactory::InitTabStripTab(dropTarget, this);
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
if(dragDropStatus.pActiveDataObject) {
hr = Fire_OLEDragLeave(dragDropStatus.pActiveDataObject, pDropTarget, button, shift, dragDropStatus.lastMousePosition.x, dragDropStatus.lastMousePosition.y, static_cast<HitTestConstants>(hitTestDetails));
}
//}
dragDropStatus.pActiveDataObject = NULL;
dragDropStatus.OLEDragLeaveOrDrop();
Invalidate();
return hr;
}
inline HRESULT TabStrip::Raise_OLEDragLeavePotentialTarget(void)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLEDragLeavePotentialTarget();
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLEDragMouseMove(DWORD* pEffect, DWORD keyState, POINTL mousePosition)
{
ScreenToClient(reinterpret_cast<LPPOINT>(&mousePosition));
dragDropStatus.lastMousePosition = mousePosition;
SHORT button = 0;
SHORT shift = 0;
OLEKEYSTATE2BUTTONANDSHIFT(keyState, button, shift);
UINT hitTestDetails = 0;
int dropTarget = HitTest(mousePosition.x, mousePosition.y, &hitTestDetails);
ITabStripTab* pDropTarget = NULL;
ClassFactory::InitTabStripTab(dropTarget, this, IID_ITabStripTab, reinterpret_cast<LPUNKNOWN*>(&pDropTarget));
VARIANT_BOOL autoActivateTab = VARIANT_TRUE;
if(dropTarget == -1) {
autoActivateTab = VARIANT_FALSE;
}
LONG autoScrollVelocity = 0;
BOOL handleAutoScroll = FALSE;
if(((GetStyle() & TCS_MULTILINE) == 0) && ((SendMessage(TCM_GETEXTENDEDSTYLE, 0, 0) & TCS_EX_REGISTERDROP) == 0) && (properties.dragScrollTimeBase != 0)) {
handleAutoScroll = TRUE;
/* Use a 16 pixels wide border at both ends of the tab bar as the zone for auto-scrolling.
Are we within this zone? */
CPoint mousePos(mousePosition.x, mousePosition.y);
CRect noScrollZone(0, 0, 0, 0);
GetWindowRect(&noScrollZone);
ScreenToClient(&noScrollZone);
BOOL rightToLeft = ((GetExStyle() & WS_EX_LAYOUTRTL) == WS_EX_LAYOUTRTL);
if(rightToLeft) {
// noScrollZone is right to left, too, and PtInRect doesn't like that
LONG buffer = noScrollZone.left;
noScrollZone.left = noScrollZone.right;
noScrollZone.right = buffer;
}
BOOL isInScrollZone = noScrollZone.PtInRect(mousePos);
if(isInScrollZone) {
// we're within the window rectangle, so do further checks
if(GetStyle() & TCS_BOTTOM) {
noScrollZone.DeflateRect(properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH, 0);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y < noScrollZone.bottom - properties.tabHeight));
} else {
noScrollZone.DeflateRect(properties.DRAGSCROLLZONEWIDTH, 0, properties.DRAGSCROLLZONEWIDTH, 0);
isInScrollZone = !(noScrollZone.PtInRect(mousePos) || (mousePos.y > noScrollZone.top + properties.tabHeight));
}
}
if(rightToLeft) {
// mousePos is right to left, so make noScrollZone right to left again
LONG buffer = noScrollZone.left;
noScrollZone.left = noScrollZone.right;
noScrollZone.right = buffer;
}
if(isInScrollZone) {
// we're within the default scroll zone - propose a velocity
if(mousePos.x < noScrollZone.left) {
autoScrollVelocity = -1;
} else if(mousePos.x >= noScrollZone.right) {
autoScrollVelocity = 1;
}
}
}
HRESULT hr = S_OK;
//if(m_nFreezeEvents == 0) {
if(dragDropStatus.pActiveDataObject) {
hr = Fire_OLEDragMouseMove(dragDropStatus.pActiveDataObject, reinterpret_cast<OLEDropEffectConstants*>(pEffect), &pDropTarget, button, shift, mousePosition.x, mousePosition.y, static_cast<HitTestConstants>(hitTestDetails), &autoActivateTab, &autoScrollVelocity);
}
//}
if(pDropTarget) {
// we're using a raw pointer
pDropTarget->Release();
}
if(autoActivateTab == VARIANT_FALSE) {
// cancel auto-activation
KillTimer(timers.ID_DRAGACTIVATE);
} else {
if(dropTarget != dragDropStatus.lastDropTarget) {
// cancel auto-activation of previous target
KillTimer(timers.ID_DRAGACTIVATE);
if(properties.dragActivateTime != 0) {
// start timered auto-activation of new target
SetTimer(timers.ID_DRAGACTIVATE, (properties.dragActivateTime == -1 ? GetDoubleClickTime() : properties.dragActivateTime));
}
}
}
dragDropStatus.lastDropTarget = dropTarget;
if(handleAutoScroll) {
dragDropStatus.autoScrolling.currentScrollVelocity = autoScrollVelocity;
LONG smallestInterval = abs(autoScrollVelocity);
if(smallestInterval) {
smallestInterval = (properties.dragScrollTimeBase == -1 ? GetDoubleClickTime() / 4 : properties.dragScrollTimeBase) / smallestInterval;
if(smallestInterval == 0) {
smallestInterval = 1;
}
}
if(smallestInterval != dragDropStatus.autoScrolling.currentTimerInterval) {
// reset the timer
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = smallestInterval;
if(smallestInterval != 0) {
SetTimer(timers.ID_DRAGSCROLL, smallestInterval);
}
}
if(smallestInterval) {
/* Scroll immediately to avoid the theoretical situation where the timer interval is changed
faster than the timer fires so the control never is scrolled. */
AutoScroll();
}
} else {
KillTimer(timers.ID_DRAGSCROLL);
dragDropStatus.autoScrolling.currentTimerInterval = 0;
}
return hr;
}
inline HRESULT TabStrip::Raise_OLEGiveFeedback(DWORD effect, VARIANT_BOOL* pUseDefaultCursors)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLEGiveFeedback(static_cast<OLEDropEffectConstants>(effect), pUseDefaultCursors);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLEQueryContinueDrag(BOOL pressedEscape, DWORD keyState, HRESULT* pActionToContinueWith)
{
//if(m_nFreezeEvents == 0) {
SHORT button = 0;
SHORT shift = 0;
OLEKEYSTATE2BUTTONANDSHIFT(keyState, button, shift);
return Fire_OLEQueryContinueDrag(BOOL2VARIANTBOOL(pressedEscape), button, shift, reinterpret_cast<OLEActionToContinueWithConstants*>(pActionToContinueWith));
//}
//return S_OK;
}
/* We can't make this one inline, because it's called from SourceOLEDataObject only, so the compiler
would try to integrate it into SourceOLEDataObject, which of course won't work. */
HRESULT TabStrip::Raise_OLEReceivedNewData(IOLEDataObject* pData, LONG formatID, LONG index, LONG dataOrViewAspect)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLEReceivedNewData(pData, formatID, index, dataOrViewAspect);
//}
//return S_OK;
}
/* We can't make this one inline, because it's called from SourceOLEDataObject only, so the compiler
would try to integrate it into SourceOLEDataObject, which of course won't work. */
HRESULT TabStrip::Raise_OLESetData(IOLEDataObject* pData, LONG formatID, LONG index, LONG dataOrViewAspect)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLESetData(pData, formatID, index, dataOrViewAspect);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OLEStartDrag(IOLEDataObject* pData)
{
//if(m_nFreezeEvents == 0) {
return Fire_OLEStartDrag(pData);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_OwnerDrawTab(ITabStripTab* pTSTab, OwnerDrawTabStateConstants tabState, LONG hDC, RECTANGLE* pDrawingRectangle)
{
//if(m_nFreezeEvents == 0) {
return Fire_OwnerDrawTab(pTSTab, tabState, hDC, pDrawingRectangle);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_RClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
mouseStatus.lastClickedTab = HitTest(x, y, &hitTestDetails);
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(mouseStatus.lastClickedTab, this);
return Fire_RClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_RDblClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
if(tabIndex != mouseStatus.lastClickedTab) {
tabIndex = -1;
}
mouseStatus.lastClickedTab = -1;
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_RDblClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_RecreatedControlWindow(LONG hWnd)
{
// configure the control
SendConfigurationMessages();
if(properties.registerForOLEDragDrop == rfoddAdvancedDragDrop) {
ATLVERIFY(RegisterDragDrop(*this, static_cast<IDropTarget*>(this)) == S_OK);
}
/*if(properties.dontRedraw) {
SetTimer(timers.ID_REDRAW, timers.INT_REDRAW);
}*/
//if(m_nFreezeEvents == 0) {
return Fire_RecreatedControlWindow(hWnd);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_RemovedTab(IVirtualTabStripTab* pTSTab)
{
//if(m_nFreezeEvents == 0) {
return Fire_RemovedTab(pTSTab);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_RemovingTab(ITabStripTab* pTSTab, VARIANT_BOOL* pCancel)
{
//if(m_nFreezeEvents == 0) {
return Fire_RemovingTab(pTSTab, pCancel);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_ResizedControlWindow(void)
{
//if(m_nFreezeEvents == 0) {
return Fire_ResizedControlWindow();
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_TabBeginDrag(ITabStripTab* pTSTab, SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, UINT hitTestDetails)
{
//if(m_nFreezeEvents == 0) {
return Fire_TabBeginDrag(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_TabBeginRDrag(ITabStripTab* pTSTab, SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, UINT hitTestDetails)
{
//if(m_nFreezeEvents == 0) {
return Fire_TabBeginRDrag(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_TabGetInfoTipText(ITabStripTab* pTSTab, LONG maxInfoTipLength, BSTR* pInfoTipText)
{
//if(m_nFreezeEvents == 0) {
return Fire_TabGetInfoTipText(pTSTab, maxInfoTipLength, pInfoTipText);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_TabMouseEnter(ITabStripTab* pTSTab, SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, UINT hitTestDetails)
{
if(/*(m_nFreezeEvents == 0) && */mouseStatus.enteredControl) {
return Fire_TabMouseEnter(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
}
return S_OK;
}
inline HRESULT TabStrip::Raise_TabMouseLeave(ITabStripTab* pTSTab, SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, UINT hitTestDetails)
{
if(/*(m_nFreezeEvents == 0) && */mouseStatus.enteredControl) {
return Fire_TabMouseLeave(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
}
return S_OK;
}
inline HRESULT TabStrip::Raise_TabSelectionChanged(int tabIndex)
{
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_TabSelectionChanged(pTSTab);
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_XClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
mouseStatus.lastClickedTab = HitTest(x, y, &hitTestDetails);
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(mouseStatus.lastClickedTab, this);
return Fire_XClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
inline HRESULT TabStrip::Raise_XDblClick(SHORT button, SHORT shift, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y)
{
UINT hitTestDetails = 0;
int tabIndex = HitTest(x, y, &hitTestDetails);
if(tabIndex != mouseStatus.lastClickedTab) {
tabIndex = -1;
}
mouseStatus.lastClickedTab = -1;
//if(m_nFreezeEvents == 0) {
CComPtr<ITabStripTab> pTSTab = ClassFactory::InitTabStripTab(tabIndex, this);
return Fire_XDblClick(pTSTab, button, shift, x, y, static_cast<HitTestConstants>(hitTestDetails));
//}
//return S_OK;
}
void TabStrip::EnterSilentTabInsertionSection(void)
{
++flags.silentTabInsertions;
}
void TabStrip::LeaveSilentTabInsertionSection(void)
{
--flags.silentTabInsertions;
}
void TabStrip::EnterSilentTabDeletionSection(void)
{
++flags.silentTabDeletions;
}
void TabStrip::LeaveSilentTabDeletionSection(void)
{
--flags.silentTabDeletions;
}
void TabStrip::EnterSilentActiveTabChangeSection(void)
{
++flags.silentActiveTabChanges;
}
void TabStrip::LeaveSilentActiveTabChangeSection(void)
{
--flags.silentActiveTabChanges;
}
void TabStrip::EnterSilentCaretChangeSection(void)
{
++flags.silentCaretChanges;
}
void TabStrip::LeaveSilentCaretChangeSection(void)
{
--flags.silentCaretChanges;
}
void TabStrip::EnterSilentSelectionChangesSection(void)
{
++flags.silentSelectionChanges;
}
void TabStrip::LeaveSilentSelectionChangesSection(void)
{
--flags.silentSelectionChanges;
}
void TabStrip::RecreateControlWindow(void)
{
// This method shouldn't be used, because it will destroy all contained controls.
ATLASSERT(FALSE);
/*if(m_bInPlaceActive) {
BOOL isUIActive = m_bUIActive;
InPlaceDeactivate();
ATLASSERT(m_hWnd == NULL);
InPlaceActivate((isUIActive ? OLEIVERB_UIACTIVATE : OLEIVERB_INPLACEACTIVATE));
}*/
}
DWORD TabStrip::GetExStyleBits(void)
{
DWORD extendedStyle = WS_EX_LEFT | WS_EX_LTRREADING;
switch(properties.appearance) {
case a3D:
extendedStyle |= WS_EX_CLIENTEDGE;
break;
case a3DLight:
extendedStyle |= WS_EX_STATICEDGE;
break;
}
if(properties.rightToLeft & rtlLayout) {
extendedStyle |= WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
}
if(properties.rightToLeft & rtlText) {
extendedStyle |= WS_EX_RTLREADING;
}
return extendedStyle;
}
DWORD TabStrip::GetStyleBits(void)
{
DWORD style = WS_CHILDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
switch(properties.borderStyle) {
case bsFixedSingle:
style |= WS_BORDER;
break;
}
if(!properties.enabled) {
style |= WS_DISABLED;
}
if(properties.focusOnButtonDown) {
style |= TCS_FOCUSONBUTTONDOWN;
}
if(properties.hotTracking) {
style |= TCS_HOTTRACK;
}
if(properties.multiRow) {
style |= TCS_MULTILINE;
}
if(properties.multiSelect) {
style |= TCS_MULTISELECT;
}
if(properties.ownerDrawn) {
style |= TCS_OWNERDRAWFIXED;
}
if(properties.raggedTabRows) {
style |= TCS_RAGGEDRIGHT;
}
if(properties.scrollToOpposite) {
style |= TCS_SCROLLOPPOSITE;
}
if(properties.showToolTips) {
style |= TCS_TOOLTIPS;
}
switch(properties.style) {
case sButtons:
style |= TCS_BUTTONS;
break;
case sFlatButtons:
style |= TCS_BUTTONS | TCS_FLATBUTTONS;
break;
}
switch(properties.tabCaptionAlignment) {
case tcaForceIconLeft:
style |= TCS_FORCEICONLEFT;
break;
case tcaForceCaptionLeft:
style |= TCS_FORCELABELLEFT;
break;
}
switch(properties.tabPlacement) {
case tpBottom:
style |= TCS_BOTTOM;
break;
case tpLeft:
style |= TCS_VERTICAL;
break;
case tpRight:
style |= TCS_VERTICAL | TCS_RIGHT;
break;
}
if(properties.useFixedTabWidth) {
style |= TCS_FIXEDWIDTH;
}
return style;
}
void TabStrip::SendConfigurationMessages(void)
{
DWORD extendedStyle = 0;
if(properties.allowDragDrop) {
extendedStyle |= TCS_EX_DETECTDRAGDROP;
}
if(properties.registerForOLEDragDrop == rfoddNativeDragDrop) {
extendedStyle |= TCS_EX_REGISTERDROP;
}
if(properties.showButtonSeparators) {
extendedStyle |= TCS_EX_FLATSEPARATORS;
}
SendMessage(TCM_SETEXTENDEDSTYLE, 0, extendedStyle);
SendMessage(TCM_SETINSERTMARKCOLOR, 0, OLECOLOR2COLORREF(properties.insertMarkColor));
SendMessage(TCM_SETITEMSIZE, 0, MAKELPARAM(properties.fixedTabWidth, properties.tabHeight));
SendMessage(TCM_SETMINTABWIDTH, 0, properties.minTabWidth);
SendMessage(TCM_SETPADDING, 0, MAKELPARAM(properties.horizontalPadding, properties.verticalPadding));
ApplyFont();
if(IsInDesignMode()) {
// insert some dummy tabs
TCITEM tab = {0};
tab.mask = TCIF_TEXT;
tab.pszText = TEXT("Dummy Tab 1");
SendMessage(TCM_INSERTITEM, 0, reinterpret_cast<LPARAM>(&tab));
tab.pszText = TEXT("Dummy Tab 2");
SendMessage(TCM_INSERTITEM, 1, reinterpret_cast<LPARAM>(&tab));
tab.pszText = TEXT("Dummy Tab 3");
SendMessage(TCM_INSERTITEM, 2, reinterpret_cast<LPARAM>(&tab));
tab.pszText = TEXT("Dummy Tab 4");
SendMessage(TCM_INSERTITEM, 3, reinterpret_cast<LPARAM>(&tab));
tab.pszText = TEXT("Dummy Tab 5");
SendMessage(TCM_INSERTITEM, 4, reinterpret_cast<LPARAM>(&tab));
}
}
HCURSOR TabStrip::MousePointerConst2hCursor(MousePointerConstants mousePointer)
{
WORD flag = 0;
switch(mousePointer) {
case mpArrow:
flag = OCR_NORMAL;
break;
case mpCross:
flag = OCR_CROSS;
break;
case mpIBeam:
flag = OCR_IBEAM;
break;
case mpIcon:
flag = OCR_ICOCUR;
break;
case mpSize:
flag = OCR_SIZEALL; // OCR_SIZE is obsolete
break;
case mpSizeNESW:
flag = OCR_SIZENESW;
break;
case mpSizeNS:
flag = OCR_SIZENS;
break;
case mpSizeNWSE:
flag = OCR_SIZENWSE;
break;
case mpSizeEW:
flag = OCR_SIZEWE;
break;
case mpUpArrow:
flag = OCR_UP;
break;
case mpHourglass:
flag = OCR_WAIT;
break;
case mpNoDrop:
flag = OCR_NO;
break;
case mpArrowHourglass:
flag = OCR_APPSTARTING;
break;
case mpArrowQuestion:
flag = 32651;
break;
case mpSizeAll:
flag = OCR_SIZEALL;
break;
case mpHand:
flag = OCR_HAND;
break;
case mpInsertMedia:
flag = 32663;
break;
case mpScrollAll:
flag = 32654;
break;
case mpScrollN:
flag = 32655;
break;
case mpScrollNE:
flag = 32660;
break;
case mpScrollE:
flag = 32658;
break;
case mpScrollSE:
flag = 32662;
break;
case mpScrollS:
flag = 32656;
break;
case mpScrollSW:
flag = 32661;
break;
case mpScrollW:
flag = 32657;
break;
case mpScrollNW:
flag = 32659;
break;
case mpScrollNS:
flag = 32652;
break;
case mpScrollEW:
flag = 32653;
break;
default:
return NULL;
}
return static_cast<HCURSOR>(LoadImage(0, MAKEINTRESOURCE(flag), IMAGE_CURSOR, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED));
}
int TabStrip::IDToTabIndex(LONG ID)
{
#ifdef USE_STL
std::vector<LONG>::iterator iter = std::find(tabIDs.begin(), tabIDs.end(), ID);
if(iter != tabIDs.end()) {
return std::distance(tabIDs.begin(), iter);
}
#else
for(size_t i = 0; i < tabIDs.GetCount(); ++i) {
if(tabIDs[i] == ID) {
return i;
}
}
#endif
return -1;
}
LONG TabStrip::TabIndexToID(int tabIndex)
{
ATLASSERT(IsWindow());
TCITEM tab = {0};
tab.mask = TCIF_PARAM | TCIF_NOINTERCEPTION;
if(SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab))) {
return tab.lParam;
}
return -1;
}
LONG TabStrip::GetNewTabID(void)
{
static LONG lastID = 0;
return ++lastID;
}
void TabStrip::RegisterTabContainer(ITabContainer* pContainer)
{
ATLASSUME(pContainer);
#ifdef _DEBUG
#ifdef USE_STL
std::unordered_map<DWORD, ITabContainer*>::iterator iter = tabContainers.find(pContainer->GetID());
ATLASSERT(iter == tabContainers.end());
#else
CAtlMap<DWORD, ITabContainer*>::CPair* pEntry = tabContainers.Lookup(pContainer->GetID());
ATLASSERT(!pEntry);
#endif
#endif
tabContainers[pContainer->GetID()] = pContainer;
}
void TabStrip::DeregisterTabContainer(DWORD containerID)
{
#ifdef USE_STL
std::unordered_map<DWORD, ITabContainer*>::iterator iter = tabContainers.find(containerID);
ATLASSERT(iter != tabContainers.end());
if(iter != tabContainers.end()) {
tabContainers.erase(iter);
}
#else
tabContainers.RemoveKey(containerID);
#endif
}
void TabStrip::RemoveTabFromTabContainers(LONG tabID)
{
#ifdef USE_STL
for(std::unordered_map<DWORD, ITabContainer*>::const_iterator iter = tabContainers.begin(); iter != tabContainers.end(); ++iter) {
iter->second->RemovedTab(tabID);
}
#else
POSITION p = tabContainers.GetStartPosition();
while(p) {
tabContainers.GetValueAt(p)->RemovedTab(tabID);
tabContainers.GetNextValue(p);
}
#endif
}
int TabStrip::HitTest(LONG x, LONG y, UINT* pFlags, BOOL ignoreBoundingBoxDefinition/* = FALSE*/)
{
ATLASSERT(IsWindow());
UINT hitTestFlags = 0;
if(pFlags) {
hitTestFlags = *pFlags;
}
TCHITTESTINFO hitTestInfo = {{x, y}, hitTestFlags };
int tabIndex = SendMessage(TCM_HITTEST, 0, reinterpret_cast<LPARAM>(&hitTestInfo));
if(tabIndex == -1) {
// Are we outside the tab headers?
CRect windowRectangle;
GetWindowRect(&windowRectangle);
ScreenToClient(&windowRectangle);
if(windowRectangle.PtInRect(hitTestInfo.pt)) {
// Are we inside the client area?
CRect clientRectangle(&windowRectangle);
SendMessage(TCM_ADJUSTRECT, FALSE, reinterpret_cast<LPARAM>(&clientRectangle));
if(clientRectangle.PtInRect(hitTestInfo.pt)) {
// bingo
hitTestInfo.flags |= TCHT_CLIENTAREA;
} else {
// we're probably in the blank area next to a tab
}
} else {
if(x < windowRectangle.left) {
hitTestInfo.flags |= TCHT_TOLEFT;
} else if(x > windowRectangle.right) {
hitTestInfo.flags |= TCHT_TORIGHT;
}
if(y < windowRectangle.top) {
hitTestInfo.flags |= TCHT_ABOVE;
} else if(y > windowRectangle.bottom) {
hitTestInfo.flags |= TCHT_BELOW;
}
}
} else if(properties.closeableTabs) {
/* When the Click event is raised, the clicked tab already is the new caret tab. So if the tab didn't
* have a close button during MouseDown, we shouldn't return TCHT_CLOSEBUTTON until after the Click
* event. Otherwise the tab will close on activation if the close buttons materializes below the mouse
* cursor.
*/
if(properties.closeableTabsMode != ctmDisplayOnActiveTab || mouseStatus.overCloseButtonOnMouseDown >= -1) {
CRect buttonRectangle;
if(CalculateCloseButtonRectangle(tabIndex, tabIndex == SendMessage(TCM_GETCURSEL, 0, 0), &buttonRectangle)) {
if(buttonRectangle.PtInRect(hitTestInfo.pt)) {
hitTestInfo.flags = TCHT_CLOSEBUTTON;
}
}
}
}
hitTestFlags = hitTestInfo.flags;
if(pFlags) {
*pFlags = hitTestFlags;
}
if(!ignoreBoundingBoxDefinition && ((properties.tabBoundingBoxDefinition & hitTestFlags) != hitTestFlags)) {
tabIndex = -1;
}
return tabIndex;
}
BOOL TabStrip::IsInDesignMode(void)
{
BOOL b = TRUE;
GetAmbientUserMode(b);
return !b;
}
void TabStrip::MoveTabIndex(int oldTabIndex, int newTabIndex)
{
LONG tabID = tabIDs[oldTabIndex];
#ifdef USE_STL
tabIDs.erase(tabIDs.begin() + oldTabIndex);
if(newTabIndex >= static_cast<int>(tabIDs.size())) {
tabIDs.push_back(tabID);
} else {
tabIDs.insert(tabIDs.begin() + newTabIndex, tabID);
}
std::list<TabData>::iterator iter2 = tabParams.begin();
if(iter2 != tabParams.end()) {
std::advance(iter2, oldTabIndex);
TabData tmp = *iter2;
tabParams.erase(iter2);
iter2 = tabParams.begin();
if(iter2 != tabParams.end()) {
std::advance(iter2, newTabIndex);
tabParams.insert(iter2, tmp);
}
}
#else
tabIDs.RemoveAt(oldTabIndex);
if(newTabIndex >= static_cast<int>(tabIDs.GetCount())) {
tabIDs.Add(tabID);
} else {
tabIDs.InsertAt(newTabIndex, tabID);
}
POSITION pOldEntry = tabParams.FindIndex(oldTabIndex);
if(pOldEntry) {
TabData tmp = tabParams.GetAt(pOldEntry);
tabParams.RemoveAt(pOldEntry);
POSITION pNewEntry = tabParams.FindIndex(newTabIndex);
if(pNewEntry) {
tabParams.InsertBefore(pNewEntry, tmp);
} else {
tabParams.AddTail(tmp);
}
}
#endif
}
HWND TabStrip::GetAssociatedWindow(int tabIndex)
{
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, tabIndex);
if(iter != tabParams.end()) {
return iter->hAssociatedWindow;
}
}
#else
POSITION p = tabParams.FindIndex(tabIndex);
if(p) {
return tabParams.GetAt(p).hAssociatedWindow;
}
#endif
return NULL;
}
void TabStrip::SetAssociatedWindow(int tabIndex, HWND hAssociatedWindow)
{
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, tabIndex);
if(iter != tabParams.end()) {
iter->hAssociatedWindow = hAssociatedWindow;
}
}
#else
POSITION p = tabParams.FindIndex(tabIndex);
if(p) {
tabParams.GetAt(p).hAssociatedWindow = hAssociatedWindow;
}
#endif
ATLASSERT(GetAssociatedWindow(tabIndex) == hAssociatedWindow);
}
BOOL TabStrip::IsCloseableTab(int tabIndex)
{
if(properties.closeableTabs) {
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, tabIndex);
if(iter != tabParams.end()) {
return iter->isCloseable;
}
}
#else
POSITION p = tabParams.FindIndex(tabIndex);
if(p) {
return tabParams.GetAt(p).isCloseable;
}
#endif
}
return FALSE;
}
HRESULT TabStrip::SetCloseableTab(int tabIndex, BOOL isCloseable)
{
if(properties.closeableTabs) {
#ifdef USE_STL
std::list<TabData>::iterator iter = tabParams.begin();
if(iter != tabParams.end()) {
std::advance(iter, tabIndex);
if(iter != tabParams.end()) {
iter->isCloseable = isCloseable;
return S_OK;
}
}
#else
POSITION p = tabParams.FindIndex(tabIndex);
if(p) {
tabParams.GetAt(p).isCloseable = isCloseable;
return S_OK;
}
#endif
}
return E_INVALIDARG;
}
void TabStrip::AutoScroll(void)
{
CUpDownCtrl upDownControl = GetDlgItem(1);
if(!upDownControl.IsWindow()) {
return;
}
LONG realScrollTimeBase = properties.dragScrollTimeBase;
if(realScrollTimeBase == -1) {
realScrollTimeBase = GetDoubleClickTime() / 4;
}
if(dragDropStatus.autoScrolling.currentScrollVelocity < 0) {
// Have we been waiting long enough since the last scroll to the left?
if((GetTickCount() - dragDropStatus.autoScrolling.lastScroll_Left) >= static_cast<ULONG>(realScrollTimeBase / abs(dragDropStatus.autoScrolling.currentScrollVelocity))) {
int lowerBound = 0;
int upperBound = 0;
upDownControl.GetRange32(lowerBound, upperBound);
int currentPosition = upDownControl.GetPos32();
if(currentPosition > lowerBound) {
// scroll left
dragDropStatus.autoScrolling.lastScroll_Left = GetTickCount();
dragDropStatus.HideDragImage(TRUE);
SendMessage(WM_HSCROLL, MAKEWPARAM(SB_THUMBPOSITION, --currentPosition), 0);
dragDropStatus.ShowDragImage(TRUE);
}
}
} else if(dragDropStatus.autoScrolling.currentScrollVelocity > 0) {
// Have we been waiting long enough since the last scroll to the right?
if((GetTickCount() - dragDropStatus.autoScrolling.lastScroll_Right) >= static_cast<ULONG>(realScrollTimeBase / abs(dragDropStatus.autoScrolling.currentScrollVelocity))) {
int lowerBound = 0;
int upperBound = 0;
upDownControl.GetRange32(lowerBound, upperBound);
int currentPosition = upDownControl.GetPos32();
if(currentPosition < upperBound) {
// scroll right
dragDropStatus.autoScrolling.lastScroll_Right = GetTickCount();
dragDropStatus.HideDragImage(TRUE);
SendMessage(WM_HSCROLL, MAKEWPARAM(SB_THUMBPOSITION, ++currentPosition), 0);
dragDropStatus.ShowDragImage(TRUE);
}
}
}
}
void TabStrip::RebuildAcceleratorTable(void)
{
if(properties.hAcceleratorTable) {
DestroyAcceleratorTable(properties.hAcceleratorTable);
properties.hAcceleratorTable = NULL;
}
// create a new accelerator table
TCITEM tab = {0};
tab.mask = TCIF_TEXT;
tab.cchTextMax = MAX_TABTEXTLENGTH;
tab.pszText = static_cast<LPTSTR>(HeapAlloc(GetProcessHeap(), 0, (tab.cchTextMax + 1) * sizeof(TCHAR)));
if(tab.pszText) {
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
TCHAR* pAcceleratorChars = static_cast<TCHAR*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, numberOfTabs * sizeof(TCHAR)));
if(pAcceleratorChars) {
int numberOfTabsWithAccelerator = 0;
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
SendMessage(TCM_GETITEM, tabIndex, reinterpret_cast<LPARAM>(&tab));
pAcceleratorChars[tabIndex] = TEXT('\0');
if(tab.pszText) {
for(int i = lstrlen(tab.pszText) - 1; i > 0; --i) {
if((tab.pszText[i - 1] == TEXT('&')) && (tab.pszText[i] != TEXT('&'))) {
++numberOfTabsWithAccelerator;
pAcceleratorChars[tabIndex] = tab.pszText[i];
break;
}
}
}
}
if(numberOfTabsWithAccelerator) {
LPACCEL pAccelerators = static_cast<LPACCEL>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (numberOfTabsWithAccelerator * 4) * sizeof(ACCEL)));
if(pAccelerators) {
int i = 0;
for(int tabIndex = 0; tabIndex < numberOfTabs; ++tabIndex) {
if(pAcceleratorChars[tabIndex] != TEXT('\0')) {
pAccelerators[i * 4].cmd = static_cast<WORD>(tabIndex);
pAccelerators[i * 4].fVirt = FALT;
pAccelerators[i * 4].key = static_cast<WORD>(tolower(pAcceleratorChars[tabIndex]));
pAccelerators[i * 4 + 1].cmd = static_cast<WORD>(tabIndex);
pAccelerators[i * 4 + 1].fVirt = 0;
pAccelerators[i * 4 + 1].key = static_cast<WORD>(tolower(pAcceleratorChars[tabIndex]));
pAccelerators[i * 4 + 2].cmd = static_cast<WORD>(tabIndex);
pAccelerators[i * 4 + 2].fVirt = FVIRTKEY | FALT;
pAccelerators[i * 4 + 2].key = LOBYTE(VkKeyScan(pAcceleratorChars[tabIndex]));
pAccelerators[i * 4 + 3].cmd = static_cast<WORD>(tabIndex);
pAccelerators[i * 4 + 3].fVirt = FVIRTKEY | FALT | FSHIFT;
pAccelerators[i * 4 + 3].key = LOBYTE(VkKeyScan(pAcceleratorChars[tabIndex]));
++i;
}
}
properties.hAcceleratorTable = CreateAcceleratorTable(pAccelerators, numberOfTabsWithAccelerator * 4);
HeapFree(GetProcessHeap(), 0, pAccelerators);
}
}
HeapFree(GetProcessHeap(), 0, pAcceleratorChars);
}
HeapFree(GetProcessHeap(), 0, tab.pszText);
}
// report the new accelerator table to the container
CComQIPtr<IOleControlSite, &IID_IOleControlSite> pSite(m_spClientSite);
if(pSite) {
pSite->OnControlInfoChanged();
}
}
BOOL TabStrip::CalculateCloseButtonRectangle(int tabIndex, BOOL tabIsActive, LPRECT pButtonRectangle)
{
if(!pButtonRectangle) {
return FALSE;
}
if(properties.closeableTabsMode == ctmDisplayOnActiveTab && !tabIsActive) {
return FALSE;
}
if(!IsCloseableTab(tabIndex)) {
return FALSE;
}
CRect tabBoundingRectangle;
if(SendMessage(TCM_GETITEMRECT, tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle))) {
*pButtonRectangle = tabBoundingRectangle;
DWORD style = GetStyle();
BOOL buttons = ((style & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0);
if(style & TCS_VERTICAL) {
pButtonRectangle->bottom -= 3;
pButtonRectangle->top = pButtonRectangle->bottom - 13;
if(style & TCS_RIGHT) {
if(tabIsActive) {
pButtonRectangle->right -= (buttons ? 3 : 2);
} else {
pButtonRectangle->right -= 3;
}
pButtonRectangle->left = pButtonRectangle->right - 13;
} else {
if(tabIsActive) {
pButtonRectangle->left += (buttons ? 2 : 1);
} else {
pButtonRectangle->left += 2;
}
pButtonRectangle->right = pButtonRectangle->left + 13;
}
} else {
pButtonRectangle->right -= 3;
pButtonRectangle->left = pButtonRectangle->right - 14;
if(style & TCS_BOTTOM) {
if(tabIsActive) {
pButtonRectangle->top += (buttons ? 2 : 3);
} else {
pButtonRectangle->top += 2;
}
pButtonRectangle->bottom = pButtonRectangle->top + 14;
} else {
if(tabIsActive) {
pButtonRectangle->top += 2;
} else {
pButtonRectangle->top += (buttons ? 2 : 3);
}
pButtonRectangle->bottom = pButtonRectangle->top + 14;
}
}
return TRUE;
}
return FALSE;
}
void TabStrip::DrawCloseButtonsAndInsertionMarks(HDC hTargetDC)
{
CDCHandle targetDC = hTargetDC;
if(properties.closeableTabs) {
CTheme themingEngine;
if(flags.usingThemes) {
themingEngine.OpenThemeData(*this, VSCLASS_WINDOW);
}
DWORD style = GetStyle();
BOOL enabled = ((style & WS_DISABLED) == 0);
BOOL buttons = ((style & (TCS_FLATBUTTONS | TCS_BUTTONS)) != 0);
POINT mousePosition;
GetCursorPos(&mousePosition);
ScreenToClient(&mousePosition);
int numberOfTabs = SendMessage(TCM_GETITEMCOUNT, 0, 0);
int activeTab = SendMessage(TCM_GETCURSEL, 0, 0);
for(int tabIndex = (properties.closeableTabsMode == ctmDisplayOnActiveTab ? activeTab : 0); tabIndex < (properties.closeableTabsMode == ctmDisplayOnActiveTab ? activeTab + 1 : numberOfTabs); ++tabIndex) {
RECT buttonRectangle = {0};
if(CalculateCloseButtonRectangle(tabIndex, tabIndex == activeTab, &buttonRectangle)) {
if(buttons || themingEngine.IsThemeNull()) {
if(mouseStatus.overCloseButton == tabIndex) {
if(IsLeftMouseButtonDown()) {
// pushed
targetDC.DrawFrameControl(&buttonRectangle, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT | (enabled ? 0 : DFCS_INACTIVE) | DFCS_PUSHED);
} else {
// hot
targetDC.DrawFrameControl(&buttonRectangle, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT | (enabled ? 0 : DFCS_INACTIVE) | DFCS_HOT);
}
} else {
// normal
targetDC.DrawFrameControl(&buttonRectangle, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT | (enabled ? 0 : DFCS_INACTIVE));
}
} else {
if(mouseStatus.overCloseButton == tabIndex) {
if(IsLeftMouseButtonDown()) {
// pushed
themingEngine.DrawThemeBackground(targetDC, WP_SMALLCLOSEBUTTON, (enabled ? CBS_PUSHED : CBS_DISABLED), &buttonRectangle, NULL);
} else {
// hot
themingEngine.DrawThemeBackground(targetDC, WP_SMALLCLOSEBUTTON, (enabled ? CBS_HOT : CBS_DISABLED), &buttonRectangle, NULL);
}
} else {
// normal
themingEngine.DrawThemeBackground(targetDC, WP_SMALLCLOSEBUTTON, (enabled ? CBS_NORMAL : CBS_DISABLED), &buttonRectangle, NULL);
}
}
}
}
}
if(insertMark.tabIndex != -1) {
CPen pen;
pen.CreatePen(PS_SOLID, 1, insertMark.color);
HPEN hPreviousPen = targetDC.SelectPen(pen);
RECT tabBoundingRectangle = {0};
SendMessage(TCM_GETITEMRECT, insertMark.tabIndex, reinterpret_cast<LPARAM>(&tabBoundingRectangle));
RECT insertMarkRect = {0};
if(GetStyle() & TCS_VERTICAL) {
if(insertMark.afterTab) {
insertMarkRect.top = tabBoundingRectangle.bottom - 3;
insertMarkRect.bottom = tabBoundingRectangle.bottom + 3;
} else {
insertMarkRect.top = tabBoundingRectangle.top - 3;
insertMarkRect.bottom = tabBoundingRectangle.top + 3;
}
insertMarkRect.left = tabBoundingRectangle.left + 1;
insertMarkRect.right = tabBoundingRectangle.right - 1;
// draw the main line
targetDC.MoveTo(insertMarkRect.left, insertMarkRect.top + 2);
targetDC.LineTo(insertMarkRect.right, insertMarkRect.top + 2);
targetDC.MoveTo(insertMarkRect.left, insertMarkRect.top + 3);
targetDC.LineTo(insertMarkRect.right, insertMarkRect.top + 3);
// draw the ends
targetDC.MoveTo(insertMarkRect.left, insertMarkRect.top);
targetDC.LineTo(insertMarkRect.left, insertMarkRect.bottom);
targetDC.MoveTo(insertMarkRect.left + 1, insertMarkRect.top + 1);
targetDC.LineTo(insertMarkRect.left + 1, insertMarkRect.bottom - 1);
targetDC.MoveTo(insertMarkRect.right - 1, insertMarkRect.top + 1);
targetDC.LineTo(insertMarkRect.right - 1, insertMarkRect.bottom - 1);
targetDC.MoveTo(insertMarkRect.right, insertMarkRect.top);
targetDC.LineTo(insertMarkRect.right, insertMarkRect.bottom);
} else {
if(insertMark.afterTab) {
insertMarkRect.left = tabBoundingRectangle.right - 3;
insertMarkRect.right = tabBoundingRectangle.right + 3;
} else {
insertMarkRect.left = tabBoundingRectangle.left - 3;
insertMarkRect.right = tabBoundingRectangle.left + 3;
}
insertMarkRect.top = tabBoundingRectangle.top + 1;
insertMarkRect.bottom = tabBoundingRectangle.bottom - 1;
// draw the main line
targetDC.MoveTo(insertMarkRect.left + 2, insertMarkRect.top);
targetDC.LineTo(insertMarkRect.left + 2, insertMarkRect.bottom);
targetDC.MoveTo(insertMarkRect.left + 3, insertMarkRect.top);
targetDC.LineTo(insertMarkRect.left + 3, insertMarkRect.bottom);
// draw the ends
targetDC.MoveTo(insertMarkRect.left, insertMarkRect.top);
targetDC.LineTo(insertMarkRect.right, insertMarkRect.top);
targetDC.MoveTo(insertMarkRect.left + 1, insertMarkRect.top + 1);
targetDC.LineTo(insertMarkRect.right - 1, insertMarkRect.top + 1);
targetDC.MoveTo(insertMarkRect.left + 1, insertMarkRect.bottom - 1);
targetDC.LineTo(insertMarkRect.right - 1, insertMarkRect.bottom - 1);
targetDC.MoveTo(insertMarkRect.left, insertMarkRect.bottom);
targetDC.LineTo(insertMarkRect.right, insertMarkRect.bottom);
}
targetDC.SelectPen(hPreviousPen);
}
}
BOOL TabStrip::IsLeftMouseButtonDown(void)
{
if(GetSystemMetrics(SM_SWAPBUTTON)) {
return (GetAsyncKeyState(VK_RBUTTON) & 0x8000);
} else {
return (GetAsyncKeyState(VK_LBUTTON) & 0x8000);
}
}
BOOL TabStrip::IsRightMouseButtonDown(void)
{
if(GetSystemMetrics(SM_SWAPBUTTON)) {
return (GetAsyncKeyState(VK_LBUTTON) & 0x8000);
} else {
return (GetAsyncKeyState(VK_RBUTTON) & 0x8000);
}
}
HRESULT TabStrip::CreateThumbnail(HICON hIcon, SIZE& size, LPRGBQUAD pBits, BOOL doAlphaChannelPostProcessing)
{
if(!hIcon || !pBits || !pWICImagingFactory) {
return E_FAIL;
}
ICONINFO iconInfo;
GetIconInfo(hIcon, &iconInfo);
ATLASSERT(iconInfo.hbmColor);
BITMAP bitmapInfo = {0};
if(iconInfo.hbmColor) {
GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bitmapInfo);
} else if(iconInfo.hbmMask) {
GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bitmapInfo);
}
bitmapInfo.bmHeight = abs(bitmapInfo.bmHeight);
BOOL needsFrame = ((bitmapInfo.bmWidth < size.cx) || (bitmapInfo.bmHeight < size.cy));
if(iconInfo.hbmColor) {
DeleteObject(iconInfo.hbmColor);
}
if(iconInfo.hbmMask) {
DeleteObject(iconInfo.hbmMask);
}
HRESULT hr = E_FAIL;
CComPtr<IWICBitmapScaler> pWICBitmapScaler = NULL;
if(!needsFrame) {
hr = pWICImagingFactory->CreateBitmapScaler(&pWICBitmapScaler);
ATLASSERT(SUCCEEDED(hr));
ATLASSUME(pWICBitmapScaler);
}
if(needsFrame || SUCCEEDED(hr)) {
CComPtr<IWICBitmap> pWICBitmapSource = NULL;
hr = pWICImagingFactory->CreateBitmapFromHICON(hIcon, &pWICBitmapSource);
ATLASSERT(SUCCEEDED(hr));
ATLASSUME(pWICBitmapSource);
if(SUCCEEDED(hr)) {
if(!needsFrame) {
hr = pWICBitmapScaler->Initialize(pWICBitmapSource, size.cx, size.cy, WICBitmapInterpolationModeFant);
}
if(SUCCEEDED(hr)) {
WICRect rc = {0};
if(needsFrame) {
rc.Height = bitmapInfo.bmHeight;
rc.Width = bitmapInfo.bmWidth;
UINT stride = rc.Width * sizeof(RGBQUAD);
LPRGBQUAD pIconBits = static_cast<LPRGBQUAD>(HeapAlloc(GetProcessHeap(), 0, rc.Width * rc.Height * sizeof(RGBQUAD)));
hr = pWICBitmapSource->CopyPixels(&rc, stride, rc.Height * stride, reinterpret_cast<LPBYTE>(pIconBits));
ATLASSERT(SUCCEEDED(hr));
if(SUCCEEDED(hr)) {
// center the icon
int xIconStart = (size.cx - bitmapInfo.bmWidth) / 2;
int yIconStart = (size.cy - bitmapInfo.bmHeight) / 2;
LPRGBQUAD pIconPixel = pIconBits;
LPRGBQUAD pPixel = pBits;
pPixel += yIconStart * size.cx;
for(int y = yIconStart; y < yIconStart + bitmapInfo.bmHeight; ++y, pPixel += size.cx, pIconPixel += bitmapInfo.bmWidth) {
CopyMemory(pPixel + xIconStart, pIconPixel, bitmapInfo.bmWidth * sizeof(RGBQUAD));
}
HeapFree(GetProcessHeap(), 0, pIconBits);
rc.Height = size.cy;
rc.Width = size.cx;
// TODO: now draw a frame around it
}
} else {
rc.Height = size.cy;
rc.Width = size.cx;
UINT stride = rc.Width * sizeof(RGBQUAD);
hr = pWICBitmapScaler->CopyPixels(&rc, stride, rc.Height * stride, reinterpret_cast<LPBYTE>(pBits));
ATLASSERT(SUCCEEDED(hr));
if(SUCCEEDED(hr) && doAlphaChannelPostProcessing) {
for(int i = 0; i < rc.Width * rc.Height; ++i, ++pBits) {
if(pBits->rgbReserved == 0x00) {
ZeroMemory(pBits, sizeof(RGBQUAD));
}
}
}
}
} else {
ATLASSERT(FALSE && "Bitmap scaler failed");
}
}
}
return hr;
} |
<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
test_models.py
~~~~~~~~
newsmeme tests
:copyright: (c) 2010 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from flaskext.sqlalchemy import get_debug_queries
from flaskext.principal import Identity, AnonymousIdentity
from newsmeme import signals
from newsmeme.models import User, Post, Comment, Tag, post_tags
from newsmeme.extensions import db
from tests import TestCase
class TestTags(TestCase):
def test_empty_tag_cloud(self):
tags = Tag.query.cloud()
assert tags == []
def test_tag_cloud_with_posts(self):
user = User(username="tester",
email="<EMAIL>",
password="<PASSWORD>")
db.session.add(user)
db.session.commit()
for i in xrange(20):
post = Post(author=user,
title="test",
tags = "Music, comedy, IT crowd")
db.session.add(post)
db.session.commit()
for i in xrange(10):
post = Post(author=user,
title="test",
tags = "Twitter, YouTube, funny")
db.session.add(post)
db.session.commit()
post = Post(author=user,
title="test",
tags="Beer, parties, kegs")
db.session.add(post)
db.session.commit()
assert Tag.query.count() == 9
tags = Tag.query.cloud()
for tag in tags:
if tag.name in ("it crowd", "music", "comedy"):
assert tag.size == 10
elif tag.name in ("twitter", "youtube", "funny"):
assert tag.size == 5
elif tag.name in ("beer", "parties", "kegs"):
assert tag.size == 1
class TestUser(TestCase):
def test_gravatar(self):
user = User()
assert user.gravatar == ''
user = User(email="<EMAIL>")
assert user.gravatar == "f40aca99b2ca1491dbf6ec55597c4397"
def test_gravatar_url(self):
user = User()
assert user.gravatar_url(80) == ''
user = User(email="<EMAIL>")
assert user.gravatar_url(80) == \
"http://www.gravatar.com/avatar/f40aca99b2ca1491dbf6ec55597c4397.jpg?s=80"
def test_following(self):
user = User()
assert user.following == set()
user.following = set([1])
assert user.following == set([1])
def test_get_following(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
db.session.commit()
user.following = set([user2.id])
assert user.get_following().count() == 1
assert user.get_following().first().id == user2.id
assert user.is_following(user2)
def test_follow(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
assert user2.get_followers().count() == 0
db.session.commit()
user.follow(user2)
db.session.commit()
assert user.get_following().count() == 1
assert user.get_following().first().id == user2.id
assert user2.get_followers().count() == 1
assert user2.get_followers().first().id == user.id
def test_unfollow(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
assert user2.get_followers().count() == 0
db.session.commit()
user.follow(user2)
db.session.commit()
assert user.get_following().count() == 1
assert user.get_following().first().id == user2.id
assert user2.get_followers().count() == 1
assert user2.get_followers().first().id == user.id
user.unfollow(user2)
db.session.commit()
assert user.get_following().count() == 0
assert user2.get_followers().count() == 0
def test_can_receive_mail(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
db.session.commit()
id1 = Identity(user.id)
id2 = Identity(user2.id)
id1.provides.update(user.provides)
id2.provides.update(user2.provides)
assert not user.permissions.send_message.allows(id2)
assert not user2.permissions.send_message.allows(id1)
user.follow(user2)
db.session.commit()
del user.permissions
del user2.permissions
assert not user.permissions.send_message.allows(id2)
assert not user2.permissions.send_message.allows(id1)
user2.follow(user)
user.receive_email = True
del user.permissions
del user2.permissions
assert user.permissions.send_message.allows(id2)
assert not user2.permissions.send_message.allows(id1)
user2.receive_email = True
del user.permissions
del user2.permissions
assert user.permissions.send_message.allows(id2)
assert user2.permissions.send_message.allows(id1)
user.unfollow(user2)
del user.permissions
del user2.permissions
assert not user.permissions.send_message.allows(id2)
assert not user2.permissions.send_message.allows(id1)
def test_is_friend(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
user.follow(user2)
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
def test_is_friend(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_following().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
user.follow(user2)
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
user2.follow(user)
assert user.is_friend(user2)
assert user2.is_friend(user)
def test_get_friends(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_friends().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
assert user2.get_friends().count() == 0
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
assert user.get_friends().count() == 0
assert user2.get_friends().count() == 0
user.follow(user2)
db.session.commit()
assert not user.is_friend(user2)
assert not user2.is_friend(user)
assert user.get_friends().count() == 0
assert user2.get_friends().count() == 0
user2.follow(user)
assert user.is_friend(user2)
assert user2.is_friend(user)
assert user.get_friends().count() == 1
assert user2.get_friends().count() == 1
assert user.get_friends().first().id == user2.id
assert user2.get_friends().first().id == user.id
def test_followers(self):
user = User()
assert user.followers == set()
user.followers = set([1])
assert user.followers == set([1])
def test_get_followers(self):
user = User(username="tester",
email="<EMAIL>")
db.session.add(user)
assert user.get_followers().count() == 0
user2 = User(username="tester2",
email="<EMAIL>")
db.session.add(user2)
db.session.commit()
user.followers = set([user2.id])
assert user.get_followers().count() == 1
assert user.get_followers().first().id == user2.id
def test_check_password_if_password_none(self):
user = User()
assert not user.check_password("test")
def test_check_openid_if_password_none(self):
user = User()
assert not user.check_openid("test")
def test_check_password(self):
user = User(password="<PASSWORD>")
assert user.password != "<PASSWORD>"
assert not user.check_password("<PASSWORD>!")
assert user.check_password("<PASSWORD>")
def test_check_openid(self):
user = User(openid="google")
assert user.openid != "google"
assert not user.check_openid("test")
assert user.check_openid("google")
def test_authenticate_no_user(self):
user, is_auth = User.query.authenticate("<EMAIL>",
"test")
assert (user, is_auth) == (None, False)
def test_authenticate_bad_password(self):
user = User(username=u"tester",
email="<EMAIL>",
password="<PASSWORD>!")
db.session.add(user)
db.session.commit()
auth_user, is_auth = \
User.query.authenticate("<EMAIL>",
"test")
assert auth_user.id == user.id
assert not is_auth
def test_authenticate_good_username(self):
user = User(username=u"tester",
email="<EMAIL>",
password="<PASSWORD>!")
db.session.add(user)
db.session.commit()
auth_user, is_auth = \
User.query.authenticate("tester",
"test!")
assert auth_user.id == user.id
assert is_auth
def test_authenticate_good_email(self):
user = User(username=u"tester",
email="<EMAIL>",
password="<PASSWORD>!")
db.session.add(user)
db.session.commit()
auth_user, is_auth = \
User.query.authenticate("<EMAIL>",
"test!")
assert auth_user.id == user.id
assert is_auth
class TestPost(TestCase):
def setUp(self):
super(TestPost, self).setUp()
self.user = User(username="tester",
email="<EMAIL>",
password="<PASSWORD>")
db.session.add(self.user)
self.post = Post(title="testing",
link="http://reddit.com",
author=self.user)
db.session.add(self.post)
db.session.commit()
def test_url(self):
assert self.post.url == "/post/1/s/testing/"
def test_permanlink(self):
assert self.post.permalink == "http://localhost/post/1/s/testing/"
def test_popular(self):
assert Post.query.popular().count() == 1
self.post.score = 0
db.session.commit()
assert Post.query.popular().count() == 0
def test_deadpooled(self):
assert Post.query.deadpooled().count() == 0
self.post.score = 0
db.session.commit()
assert Post.query.deadpooled().count() == 1
def test_jsonify(self):
d = self.post.json
assert d['title'] == self.post.title
json = list(Post.query.jsonify())
assert json[0]['title'] == self.post.title
def test_tags(self):
assert self.post.taglist == []
self.post.tags = "Music, comedy, IT crowd"
db.session.commit()
assert self.post.taglist == ["Music", "comedy", "IT crowd"]
assert self.post.linked_taglist == [
("Music", "/tags/music/"),
("comedy", "/tags/comedy/"),
("IT crowd", "/tags/it-crowd/"),
]
assert Tag.query.count() == 3
for tag in Tag.query.all():
assert tag.num_posts == 1
assert tag.posts[0].id == self.post.id
post = Post(title="testing again",
link="http://reddit.com/r/programming",
author=self.user,
tags="comedy, it Crowd, Ubuntu")
db.session.add(post)
db.session.commit()
assert post.taglist == ["comedy", "it Crowd", "Ubuntu"]
assert Tag.query.count() == 4
for tag in Tag.query.all():
if tag.name.lower() in ("comedy", "it crowd"):
assert tag.num_posts == 2
assert tag.posts.count() == 2
else:
assert tag.num_posts == 1
assert tag.posts.count() == 1
def test_restricted(self):
db.session.delete(self.post)
user = User(username="testing", email="<EMAIL>")
db.session.add(user)
user2 = User(username="tester2", email="<EMAIL>")
db.session.add(user2)
db.session.commit()
admin = User(username="admin",
email="<EMAIL>",
role=User.MODERATOR)
assert user.id
post = Post(title="test",
author=user,
access=Post.PRIVATE)
db.session.add(post)
db.session.commit()
posts = Post.query.restricted(user)
assert Post.query.restricted(user).count() == 1
assert Post.query.restricted(admin).count() == 1
assert Post.query.restricted(None).count() == 0
assert Post.query.restricted(user2).count() == 0
post.access = Post.PUBLIC
db.session.commit()
posts = Post.query.restricted(user)
assert Post.query.restricted(user).count() == 1
assert Post.query.restricted(admin).count() == 1
assert Post.query.restricted(None).count() == 1
assert Post.query.restricted(user2).count() == 1
post.access = Post.FRIENDS
db.session.commit()
assert Post.query.restricted(user).count() == 1
assert Post.query.restricted(admin).count() == 1
assert Post.query.restricted(None).count() == 0
assert Post.query.restricted(user2).count() == 0
user2.follow(user)
user.follow(user2)
db.session.commit()
assert Post.query.restricted(user2).count() == 1
def test_can_access(self):
user = User(username="testing", email="<EMAIL>")
db.session.add(user)
user2 = User(username="tester2", email="<EMAIL>")
db.session.add(user2)
db.session.commit()
admin = User(username="admin",
email="<EMAIL>",
role=User.MODERATOR)
post = Post(title="test",
author_id=user.id,
access=Post.PRIVATE)
assert post.can_access(user)
assert post.can_access(admin)
assert not post.can_access(user2)
assert not post.can_access(None)
post.access = Post.PUBLIC
assert post.can_access(user)
assert post.can_access(admin)
assert post.can_access(user2)
assert post.can_access(None)
post.access = Post.FRIENDS
assert post.can_access(user)
assert post.can_access(admin)
assert not post.can_access(user2)
assert not post.can_access(None)
user.follow(user2)
user2.follow(user)
assert post.can_access(user2)
def test_edit_tags(self):
self.post.tags = "Music, comedy, IT crowd"
db.session.commit()
assert self.post.taglist == ["Music", "comedy", "IT crowd"]
assert self.post.linked_taglist == [
("Music", "/tags/music/"),
("comedy", "/tags/comedy/"),
("IT crowd", "/tags/it-crowd/"),
]
def _count_post_tags():
s = db.select([db.func.count(post_tags)])
return db.engine.execute(s).scalar()
assert _count_post_tags() == 3
self.post.tags = "music, iPhone, books"
db.session.commit()
for t in Tag.query.all():
if t.name in ("music", "iphone", "books"):
assert t.num_posts == 1
if t.name in ("comedy", "it crowd"):
assert t.num_posts == 0
assert _count_post_tags() == 3
self.post.tags = ""
assert _count_post_tags() == 0
def test_update_num_comments(self):
comment = Comment(post=self.post,
author=self.user,
comment="test")
db.session.add(comment)
db.session.commit()
signals.comment_added.send(self.post)
post = Post.query.get(self.post.id)
assert post.num_comments == 1
db.session.delete(comment)
db.session.commit()
signals.comment_deleted.send(post)
post = Post.query.get(post.id)
assert post.num_comments == 0
def test_votes(self):
assert self.post.votes == set([])
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
self.post.vote(user)
assert user.id in self.post.votes
post = Post.query.get(self.post.id)
assert user.id in post.votes
def test_can_vote(self):
assert not self.post.permissions.vote.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert not self.post.permissions.vote.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
identity.provides.update(user.provides)
assert self.post.permissions.vote.allows(identity)
votes = self.post.votes
votes.add(user.id)
self.post.votes = votes
del self.post.permissions
assert not self.post.permissions.vote.allows(identity)
def test_can_edit(self):
assert not self.post.permissions.edit.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert self.post.permissions.edit.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
assert not self.post.permissions.edit.allows(identity)
user.role = User.MODERATOR
identity.provides.update(user.provides)
assert self.post.permissions.edit.allows(identity)
user.role = User.ADMIN
del user.provides
identity.provides.update(user.provides)
assert self.post.permissions.edit.allows(identity)
def test_can_delete(self):
assert not self.post.permissions.delete.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert self.post.permissions.delete.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
assert not self.post.permissions.delete.allows(identity)
user.role = User.MODERATOR
identity.provides.update(user.provides)
assert self.post.permissions.delete.allows(identity)
user.role = User.ADMIN
del user.provides
identity.provides.update(user.provides)
assert self.post.permissions.delete.allows(identity)
def test_search(self):
posts = Post.query.search("testing")
assert posts.count() == 1
posts = Post.query.search("reddit")
assert posts.count() == 1
posts = Post.query.search("digg")
assert posts.count() == 0
posts = Post.query.search("testing reddit")
assert posts.count() == 1
posts = Post.query.search("testing digg")
assert posts.count() == 0
posts = Post.query.search("tester")
assert posts.count() == 1
def test_get_comments(self):
parent = Comment(comment="parent comment",
author=self.user,
post=self.post)
child1 = Comment(parent=parent,
post=self.post,
author=self.user,
comment="child1")
child2 = Comment(parent=parent,
post=self.post,
author=self.user,
comment="child2")
child3 = Comment(parent=child1,
post=self.post,
author=self.user,
comment="child3")
db.session.add_all([parent, child1, child2, child3])
db.session.commit()
num_queries = len(get_debug_queries())
comments = self.post.comments
assert len(get_debug_queries()) == num_queries + 1
assert comments[0].id == parent.id
assert comments[0].depth == 0
comments = comments[0].comments
assert comments[0].id == child1.id
assert comments[1].id == child2.id
assert comments[0].depth == 1
comments = comments[0].comments
assert comments[0].id == child3.id
assert comments[0].depth == 2
class TestComment(TestCase):
def setUp(self):
super(TestComment, self).setUp()
self.user = User(username="tester",
email="<EMAIL>",
password="<PASSWORD>")
db.session.add(self.user)
self.post = Post(title="testing",
link="http://reddit.com",
author=self.user)
db.session.add(self.post)
self.comment = Comment(post=self.post,
author=self.user,
comment="a comment")
db.session.add(self.comment)
db.session.commit()
def test_restricted(self):
db.session.delete(self.post)
db.session.delete(self.comment)
user = User(username="testing", email="<EMAIL>")
db.session.add(user)
user2 = User(username="tester2", email="<EMAIL>")
db.session.add(user2)
db.session.commit()
admin = User(username="admin",
email="<EMAIL>",
role=User.MODERATOR)
post = Post(title="test",
author=user,
access=Post.PRIVATE)
db.session.add(post)
db.session.commit()
comment = Comment(author=user,
post=post,
comment="test")
db.session.add(comment)
db.session.commit()
assert Comment.query.restricted(user).count() == 1
assert Comment.query.restricted(admin).count() == 1
assert Comment.query.restricted(None).count() == 0
assert Comment.query.restricted(user2).count() == 0
post.access = Post.PUBLIC
db.session.commit()
posts = Post.query.restricted(user)
assert Comment.query.restricted(user).count() == 1
assert Comment.query.restricted(admin).count() == 1
assert Comment.query.restricted(None).count() == 1
assert Comment.query.restricted(user2).count() == 1
post.access = Post.FRIENDS
db.session.commit()
assert Comment.query.restricted(user).count() == 1
assert Comment.query.restricted(admin).count() == 1
assert Comment.query.restricted(None).count() == 0
assert Comment.query.restricted(user2).count() == 0
user2.follow(user)
user.follow(user2)
db.session.commit()
assert Comment.query.restricted(user2).count() == 1
def test_can_edit(self):
assert not self.comment.permissions.edit.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert self.comment.permissions.edit.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
assert not self.comment.permissions.edit.allows(identity)
user.role = User.MODERATOR
identity.provides.update(user.provides)
assert self.comment.permissions.edit.allows(identity)
user.role = User.ADMIN
del user.provides
identity.provides.update(user.provides)
assert self.comment.permissions.edit.allows(identity)
def test_can_delete(self):
assert not self.comment.permissions.delete.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert self.comment.permissions.delete.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
assert not self.comment.permissions.delete.allows(identity)
user.role = User.MODERATOR
identity.provides.update(user.provides)
assert self.comment.permissions.delete.allows(identity)
user.role = User.ADMIN
del user.provides
identity.provides.update(user.provides)
assert self.comment.permissions.delete.allows(identity)
def test_votes(self):
comment = Comment()
user = User(username="test",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
assert comment.votes == set([])
comment.vote(user)
assert user.id in comment.votes
def test_can_vote(self):
assert not self.comment.permissions.vote.allows(AnonymousIdentity())
identity = Identity(self.user.id)
identity.provides.update(self.user.provides)
assert not self.comment.permissions.vote.allows(identity)
user = User(username="tester2",
email="<EMAIL>")
db.session.add(user)
db.session.commit()
identity = Identity(user.id)
identity.provides.update(user.provides)
assert self.comment.permissions.vote.allows(identity)
votes = self.comment.votes
votes.add(user.id)
self.comment.votes = votes
del self.comment.permissions
assert not self.comment.permissions.vote.allows(identity)
def test_url(self):
assert self.comment.url == "/post/1/s/testing/#comment-1"
def test_permanlink(self):
assert self.comment.permalink == \
"http://localhost/post/1/s/testing/#comment-1"
|
<filename>src/OOMPI/Status.cc
// -*- c++ -*-
//
// Copyright (c) 2002-2003 Indiana University. All rights reserved.
// Copyright (c) 1996, 1997, 1998, 2000 University of Notre Dame.
// All rights reserved.
//
// This file is part of the OOMPI software package. For license
// information, see the LICENSE file in the top level directory of the
// OOMPI source distribution.
//
// $Id$
//
// OOMPI Class library
// Status class
//
#include <mpi.h>
#include "Status.h"
#include "Constants.h"
#include "Comm_world.h"
//
// ======================================================================
//
// OOMPI_Status
//
// ======================================================================
//
//
// MPI Constructor/ Default Constructor
//
OOMPI_Status::OOMPI_Status()
{
}
OOMPI_Status::OOMPI_Status(MPI_Status a)
: mpi_status(a)
{
}
OOMPI_Status::OOMPI_Status(const OOMPI_Status &a)
: mpi_status(a.mpi_status)
{}
OOMPI_Status &
OOMPI_Status::operator=(const OOMPI_Status &a)
{
if (this != &a) {
mpi_status = a.mpi_status;
}
return *this;
}
OOMPI_Status &
OOMPI_Status::operator=(const MPI_Status &a)
{
mpi_status = a;
return *this;
}
OOMPI_Status::~OOMPI_Status(void) {}
//
// Member functions
//
// Get count of a datatype
int
OOMPI_Status::Get_count(OOMPI_Datatype datatype)
{
int count;
MPI_Datatype type = datatype.Get_mpi();
MPI_Get_count(&mpi_status, type, &count);
return count;
}
//
// Get the element of that datatype
//
int
OOMPI_Status::Get_elements(OOMPI_Datatype datatype)
{
int elements(0);
MPI_Datatype type = datatype.Get_mpi();
MPI_Get_elements(&mpi_status, type, &elements);
return elements;
}
//
// Get source
//
int
OOMPI_Status::Get_source(void) { return mpi_status.MPI_SOURCE; }
//
// Get tag
//
int
OOMPI_Status::Get_tag(void) { return mpi_status.MPI_TAG; }
//
// Get error
//
int
OOMPI_Status::Get_error(void) { return mpi_status.MPI_ERROR; }
//
// Test to see if a status has been cancelled
//
bool
OOMPI_Status::Test_cancelled(void)
{
int flag;
MPI_Test_cancelled(&mpi_status, &flag);
return (bool) flag;
}
//
// ======================================================================
//
// OOMPI_Status_array
//
// ======================================================================
//
//
// Constructors//Destructors
//
OOMPI_Status_array::OOMPI_Status_array(int num)
: size(num), max_size(num)
{
if (size < 1)
size = 1;
status_array = new OOMPI_Status [size];
if (!status_array)
OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
mpi_status_array = new MPI_Status [size];
if (!mpi_status_array)
OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
mpi_status_up_to_date = false;
}
OOMPI_Status_array::OOMPI_Status_array(MPI_Status a[], int num)
: size(0), max_size(0)
{
Set_mpi(a, num);
}
OOMPI_Status_array::OOMPI_Status_array(const OOMPI_Status_array &a)
//: size(a.size), max_size(a.max_size)
: size(0), max_size(0)
{
#if 0
int i;
if (size < 1) size = 1;
status_array = new OOMPI_Status [size];
if (!status_array)
OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
for (i = 0; i < size; i++)
status_array[i] = a.status_array[i];
#else
OOMPI_Status_array &src = (OOMPI_Status_array &) a;
MPI_Status *raw_data=src.Get_mpi();
Set_mpi(raw_data, src.Get_size());
#endif
}
OOMPI_Status_array &
OOMPI_Status_array::operator=(const OOMPI_Status_array &a)
{
if (this != &a) {
if (size != a.size)
Set_size(a.size);
for (int i = 0; i < size; i++) {
status_array[i] = a.status_array[i];
mpi_status_array[i] = a.mpi_status_array[i];
}
mpi_status_up_to_date = a.mpi_status_up_to_date;
}
return *this;
}
OOMPI_Status_array::~OOMPI_Status_array(void)
{
if (status_array)
delete[] status_array;
if (mpi_status_array)
delete[] mpi_status_array;
}
//
// Operators
//
OOMPI_Status &
OOMPI_Status_array::operator[](int i)
{
if (i < 0 || i >= size) {
MPI_Status mpi_temp;
mpi_temp.MPI_SOURCE = OOMPI_UNDEFINED;
mpi_temp.MPI_TAG = OOMPI_UNDEFINED;
static OOMPI_Status *temp =0;
if (temp)
*temp = mpi_temp;
else {
temp = new OOMPI_Status(mpi_temp);
if (!temp)
OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
}
//static OOMPI_Status *temp = NULL;
//if (temp == NULL) {
// temp = new OOMPI_Status(mpi_temp);
// if (!temp)
// OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
// }
// else
// *temp = mpi_temp;
return *temp;
}
return status_array[i];
}
MPI_Status *
OOMPI_Status_array::Get_mpi(void)
{
if( !mpi_status_up_to_date ) {
for (int i=0; i<size; i++) {
mpi_status_array[i] = status_array[i].Get_mpi();
}
mpi_status_up_to_date = true;
}
return mpi_status_array;
}
void
OOMPI_Status_array::Set_mpi(MPI_Status a[], int num)
{
int i;
Set_size(num);
for (i = 0; i < size; i++) {
status_array[i] = a[i];
mpi_status_array[i] = a[i];
}
mpi_status_up_to_date = true;
}
bool
OOMPI_Status_array::Set_size(int newsize)
{
if (newsize == size)
return true;
if (newsize < 1)
newsize = 1;
if (max_size < newsize) {
OOMPI_Status *new_status_array = new OOMPI_Status [newsize];
if (!new_status_array) {
OOMPI_ERROR.Handler(&OOMPI_COMM_WORLD, OOMPI_ERR_OTHER);
return false;
}
for (int i = 0; i < size; i++)
new_status_array[i] = status_array[i];
if (size > 0) {
delete[] status_array;
delete[] mpi_status_array;
}
max_size = newsize;
size = newsize;
status_array = new_status_array;
mpi_status_array = new MPI_Status [size];
mpi_status_up_to_date = false;
return true;
}
else {
size = newsize;
return true;
}
}
|
<reponame>solosTec/cyng
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 <NAME>
*
*/
#include <cyng/table/key.hpp>
namespace cyng
{
namespace store
{
// key::key()
// : pk_()
// , generation_(0)
// {}
}
namespace traits
{
// #if defined(CYNG_LEGACY_MODE_ON)
// const char type_tag<cyng::store::key>::name[] = "key";
// #endif
} // traits
}
|
def map_to_max_num_orders_exchange_filter(
self,
json: BinanceMaxNumOrdersExchangeFilterJson
) -> BinanceMaxNumOrdersExchangeFilterModel:
res = BinanceMaxNumOrdersExchangeFilterModel(
filter_type=json["filterType"],
max_num_orders=json["maxNumOrders"])
return res |
use core::marker::PhantomData;
use rustyl4api::syscall::{syscall, MsgInfo, SyscallOp};
mod cap_slot;
mod capref;
pub mod cnode;
pub mod endpoint;
pub mod identify;
pub mod interrupt;
pub mod monitor;
pub mod ram;
pub mod reply;
pub mod tcb;
pub mod untyped;
pub mod vtable;
pub use cap_slot::*;
pub use capref::*;
pub use cnode::{CNodeCap, CNodeObj, CNODE_DEPTH};
pub use endpoint::{EndpointObj, EpCap};
pub use interrupt::{InterruptCap, InterruptObj};
pub use monitor::{MonitorCap, MonitorObj};
pub use ram::{RamCap, RamObj};
pub use reply::{ReplyCap, ReplyObj};
pub use rustyl4api::objects::ObjType;
pub use tcb::{TcbCap, TcbObj, TCB_OBJ_BIT_SZ, TCB_OBJ_SZ};
pub use untyped::{UntypedCap, UntypedObj};
pub use vtable::{VTableCap, VTableObj};
#[derive(Debug)]
pub struct Capability<T: KernelObject> {
pub slot: CapSlot,
pub obj_type: PhantomData<T>,
}
impl<T: KernelObject> Capability<T> {
pub const fn new(slot: CapSlot) -> Self {
Self {
slot: slot,
obj_type: PhantomData,
}
}
fn slot(&self) -> usize {
self.slot.slot()
}
pub fn into_slot(self) -> CapSlot {
/* Get inner slot without runinng destructor */
let slot = self.slot();
core::mem::forget(self);
CapSlot::new(slot)
}
fn delete(&self) {
let info = MsgInfo::new(SyscallOp::CNodeDelete, 0);
let mut args = [self.slot(), 0, 0, 0, 0, 0];
syscall(info, &mut args).map(|_| ()).unwrap();
}
}
impl<T: KernelObject> core::ops::Drop for Capability<T> {
fn drop(&mut self) {
if self.slot() == 0 {
return;
}
self.delete();
}
}
pub trait KernelObject {
fn obj_type() -> ObjType;
}
|
/**
* The type Test util.
*/
public class TestUtil {
/**
* The constant S3_ROOT.
*/
public static final URI S3_ROOT = URI.create("https://s3-us-west-2.amazonaws.com/simiacryptus/");
private static final Logger logger = LoggerFactory.getLogger(TestUtil.class);
/**
* Gets stack info.
*
* @return the stack info
*/
public static Map<String, List<String>> getStackInfo() {
return Thread.getAllStackTraces().entrySet().stream().collect(Collectors.toMap(entry -> {
Thread key = entry.getKey();
RefUtil.freeRef(entry);
return RefString.format("%s@%d", key.getName(), key.getId());
}, entry -> {
StackTraceElement[] value = entry.getValue();
RefUtil.freeRef(entry);
return Arrays.stream(value).map(StackTraceElement::toString).collect(Collectors.toList());
}));
}
/**
* Compare plot canvas.
*
* @param title the title
* @param trials the trials
* @return the plot canvas
*/
@Nullable
public static PlotPanel compare(final String title, @Nonnull final ProblemRun... trials) {
try {
final DoubleSummaryStatistics xStatistics = RefArrays.stream(trials)
.flatMapToDouble(x -> x.history.stream().mapToDouble(step -> step.iteration)).filter(Double::isFinite)
.summaryStatistics();
final DoubleSummaryStatistics yStatistics = RefArrays.stream(trials)
.flatMapToDouble(
x -> x.history.stream().filter(y -> y.fitness > 0).mapToDouble(step -> Math.log10(step.fitness)))
.filter(Double::isFinite).summaryStatistics();
if (xStatistics.getCount() == 0) {
logger.info("No Data");
return null;
}
@Nonnull final double[] lowerBound = {xStatistics.getMin(),
yStatistics.getCount() < 2 ? 0 : yStatistics.getMin()};
@Nonnull final double[] upperBound = {xStatistics.getMax(),
yStatistics.getCount() < 2 ? 1 : yStatistics.getMax()};
Canvas canvas = new Canvas(new double[]{0, 0}, new double[]{1, 1e-5}, true);
PlotPanel plotPanel = new PlotPanel(canvas);
canvas.setTitle(title);
canvas.setAxisLabels("x", "y");
plotPanel.setSize(600, 400);
canvas.setAxisLabels("Iteration", "log10(Fitness)");
final RefList<ProblemRun> filtered = RefArrays.stream(trials).filter(x -> !x.history.isEmpty())
.collect(RefCollectors.toList());
if (filtered.isEmpty()) {
logger.info("No Data");
filtered.freeRef();
return null;
}
DoubleSummaryStatistics valueStatistics = filtered.stream().flatMap(x -> x.history.stream())
.mapToDouble(x -> x.fitness).filter(x -> x > 0).summaryStatistics();
logger.info(RefString.format("Plotting range=%s, %s; valueStats=%s", RefArrays.toString(lowerBound),
RefArrays.toString(upperBound), valueStatistics));
filtered.forEach(trial -> {
final double[][] pts = trial.history.stream()
.map(step -> new double[]{step.iteration, Math.log10(Math.max(step.fitness, valueStatistics.getMin()))})
.filter(x -> RefArrays.stream(x).allMatch(Double::isFinite)).toArray(double[][]::new);
if (pts.length > 1) {
logger.info(RefString.format("Plotting %s points for %s", pts.length, trial.name));
canvas.add(trial.plot(pts));
} else {
logger.info(RefString.format("Only %s points for %s", pts.length, trial.name));
}
});
filtered.freeRef();
return plotPanel;
} catch (@Nonnull final Exception e) {
e.printStackTrace(System.out);
return null;
}
}
/**
* Compare time plot canvas.
*
* @param title the title
* @param trials the trials
* @return the plot canvas
*/
@Nullable
public static PlotPanel compareTime(final String title, @Nonnull final ProblemRun... trials) {
try {
final DoubleSummaryStatistics[] xStatistics = RefArrays.stream(trials)
.map(x -> x.history.stream().mapToDouble(step -> step.epochTime).filter(Double::isFinite).summaryStatistics())
.toArray(DoubleSummaryStatistics[]::new);
final double totalTime = RefArrays.stream(xStatistics).mapToDouble(x -> x.getMax() - x.getMin()).max()
.getAsDouble();
final DoubleSummaryStatistics yStatistics = RefArrays.stream(trials)
.flatMapToDouble(
x -> x.history.stream().filter(y -> y.fitness > 0).mapToDouble(step -> Math.log10(step.fitness)))
.filter(Double::isFinite).summaryStatistics();
if (yStatistics.getCount() == 0) {
logger.info("No Data");
return null;
}
@Nonnull final double[] lowerBound = {0, yStatistics.getMin()};
@Nonnull final double[] upperBound = {totalTime / 1000.0, yStatistics.getCount() == 1 ? 0 : yStatistics.getMax()};
Canvas canvas = new Canvas(lowerBound, upperBound);
PlotPanel plotPanel = new PlotPanel(canvas);
canvas.setTitle(title);
canvas.setAxisLabels("x", "y");
canvas.setAxisLabels("Time", "log10(Fitness)");
plotPanel.setSize(600, 400);
final RefList<ProblemRun> filtered = RefArrays.stream(trials).filter(x -> !x.history.isEmpty())
.collect(RefCollectors.toList());
if (filtered.isEmpty()) {
logger.info("No Data");
filtered.freeRef();
return null;
}
DoubleSummaryStatistics valueStatistics = filtered.stream().flatMap(x -> x.history.stream())
.mapToDouble(x -> x.fitness).filter(x -> x > 0).summaryStatistics();
logger.info(RefString.format("Plotting range=%s, %s; valueStats=%s", RefArrays.toString(lowerBound),
RefArrays.toString(upperBound), valueStatistics));
for (int t = 0; t < filtered.size(); t++) {
final ProblemRun trial = filtered.get(t);
final DoubleSummaryStatistics trialStats = xStatistics[t];
final double[][] pts = trial.history.stream().map(step -> {
return new double[]{(step.epochTime - trialStats.getMin()) / 1000.0,
Math.log10(Math.max(step.fitness, valueStatistics.getMin()))};
}).filter(x -> RefArrays.stream(x).allMatch(Double::isFinite)).toArray(double[][]::new);
if (pts.length > 1) {
logger.info(RefString.format("Plotting %s points for %s", pts.length, trial.name));
canvas.add(trial.plot(pts));
} else {
logger.info(RefString.format("Only %s points for %s", pts.length, trial.name));
}
}
filtered.freeRef();
return plotPanel;
} catch (@Nonnull final Exception e) {
e.printStackTrace(System.out);
return null;
}
}
/**
* Extract performance.
*
* @param log the log
* @param network the network
*/
public static void extractPerformance(@Nonnull final NotebookOutput log, @Nonnull final DAGNetwork network) {
log.p("Per-key Performance Metrics:");
log.run(RefUtil.wrapInterface(() -> {
@Nonnull final RefMap<CharSequence, MonitoringWrapperLayer> metrics = new RefHashMap<>();
network.visitNodes(RefUtil.wrapInterface(node -> {
Layer nodeLayer = node.getLayer();
if (nodeLayer instanceof MonitoringWrapperLayer) {
@Nullable final MonitoringWrapperLayer layer = (MonitoringWrapperLayer) nodeLayer.addRef();
Layer inner = layer.getInner();
assert inner != null;
String str = inner.toString();
str += " class=" + inner.getClass().getName();
inner.freeRef();
RefUtil.freeRef(metrics.put(str, layer.addRef()));
layer.freeRef();
}
assert nodeLayer != null;
nodeLayer.freeRef();
node.freeRef();
}, metrics.addRef()));
RefSet<Map.Entry<CharSequence, MonitoringWrapperLayer>> temp_13_0018 = metrics.entrySet();
TestUtil.logger.info("Performance: \n\t" + RefUtil.orElse(temp_13_0018.stream()
.sorted(RefComparator.comparingDouble(new ToDoubleFunction<Map.Entry<CharSequence, MonitoringWrapperLayer>>() {
@Override
@RefIgnore
public double applyAsDouble(Map.Entry<CharSequence, MonitoringWrapperLayer> x) {
MonitoringWrapperLayer temp_13_0019 = x.getValue();
double temp_13_0002 = -temp_13_0019.getForwardPerformance().getMean();
temp_13_0019.freeRef();
RefUtil.freeRef(x);
return temp_13_0002;
}
})).map(e -> {
MonitoringWrapperLayer temp_13_0020 = e.getValue();
@Nonnull final PercentileStatistics performanceF = temp_13_0020.getForwardPerformance();
temp_13_0020.freeRef();
MonitoringWrapperLayer temp_13_0021 = e.getValue();
@Nonnull final PercentileStatistics performanceB = temp_13_0021.getBackwardPerformance();
temp_13_0021.freeRef();
String temp_13_0003 = RefString.format("%.6fs +- %.6fs (%d) <- %s", performanceF.getMean(),
performanceF.getStdDev(), performanceF.getCount(), e.getKey())
+ (performanceB.getCount() == 0 ? ""
: RefString.format("%n\tBack: %.6fs +- %.6fs (%s)", performanceB.getMean(), performanceB.getStdDev(),
performanceB.getCount()));
RefUtil.freeRef(e);
return temp_13_0003;
}).reduce((a, b) -> a + "\n\t" + b), "-"));
temp_13_0018.freeRef();
metrics.freeRef();
}, network.addRef()));
removeInstrumentation(network);
}
/**
* Remove instrumentation.
*
* @param network the network
*/
public static void removeInstrumentation(@Nonnull final DAGNetwork network) {
network.visitNodes(node -> {
Layer nodeLayer = node.getLayer();
if (nodeLayer instanceof MonitoringWrapperLayer) {
MonitoringWrapperLayer temp_13_0022 = node.<MonitoringWrapperLayer>getLayer();
Layer layer = temp_13_0022.getInner();
temp_13_0022.freeRef();
node.setLayer(layer == null ? null : layer.addRef());
if (null != layer)
layer.freeRef();
}
if (null != nodeLayer)
nodeLayer.freeRef();
node.freeRef();
});
network.freeRef();
}
/**
* Sample performance ref map.
*
* @param network the network
* @return the ref map
*/
@Nonnull
public static RefMap<CharSequence, Object> samplePerformance(@Nonnull final DAGNetwork network) {
@Nonnull final RefMap<CharSequence, Object> metrics = new RefHashMap<>();
network.visitLayers(RefUtil.wrapInterface(layer -> {
if (layer instanceof MonitoringWrapperLayer) {
MonitoringWrapperLayer monitoringWrapperLayer = (MonitoringWrapperLayer) layer;
Layer inner = monitoringWrapperLayer.getInner();
assert inner != null;
String str = inner.toString();
str += " class=" + inner.getClass().getName();
inner.freeRef();
RefHashMap<CharSequence, Object> row = new RefHashMap<>();
RefUtil.freeRef(row.put("fwd", monitoringWrapperLayer.getForwardPerformance().getMetrics()));
RefUtil.freeRef(row.put("rev", monitoringWrapperLayer.getBackwardPerformance().getMetrics()));
monitoringWrapperLayer.freeRef();
RefUtil.freeRef(metrics.put(str, row));
} else if (null != layer) layer.freeRef();
}, metrics.addRef()));
network.freeRef();
return metrics;
}
/**
* Gets monitor.
*
* @param history the history
* @return the monitor
*/
@Nonnull
public static TrainingMonitor getMonitor(@Nonnull final List<StepRecord> history) {
return getMonitor(history, null);
}
/**
* Gets monitor.
*
* @param history the history
* @param network the network
* @return the monitor
*/
@Nonnull
public static TrainingMonitor getMonitor(@Nonnull final List<StepRecord> history, @Nullable final Layer network) {
if (null != network)
network.freeRef();
return new TrainingMonitor() {
@Override
public void clear() {
super.clear();
}
@Override
public void log(final String msg) {
logger.info(msg);
super.log(msg);
}
@Override
public void onStepComplete(@Nonnull final Step currentPoint) {
assert currentPoint.point != null;
history.add(new StepRecord(currentPoint.point.getMean(), currentPoint.time, currentPoint.iteration));
super.onStepComplete(currentPoint);
}
};
}
/**
* Instrument performance.
*
* @param network the network
*/
public static void instrumentPerformance(@Nonnull final DAGNetwork network) {
network.visitNodes(node -> {
Layer layer = node.getLayer();
if (layer instanceof MonitoringWrapperLayer) {
((MonitoringWrapperLayer) layer).shouldRecordSignalMetrics(false);
RefUtil.freeRef(((MonitoringWrapperLayer) layer).addRef());
} else {
MonitoringWrapperLayer temp_13_0015 = new MonitoringWrapperLayer(layer == null ? null : layer.addRef());
temp_13_0015.shouldRecordSignalMetrics(false);
@Nonnull
MonitoringWrapperLayer monitoringWrapperLayer = temp_13_0015.addRef();
temp_13_0015.freeRef();
node.setLayer(monitoringWrapperLayer);
}
if (null != layer)
layer.freeRef();
node.freeRef();
});
network.freeRef();
}
/**
* Plot j panel.
*
* @param history the history
* @return the j panel
*/
@Nullable
public static JPanel plot(@Nonnull final List<StepRecord> history) {
try {
final DoubleSummaryStatistics valueStats = history.stream().mapToDouble(x -> x.fitness).summaryStatistics();
double min = valueStats.getMin();
if (0 < min) {
double[][] data = history.stream()
.map(step -> new double[]{step.iteration, Math.log10(Math.max(min, step.fitness))})
.filter(x -> Arrays.stream(x).allMatch(Double::isFinite)).toArray(double[][]::new);
if (Arrays.stream(data).mapToInt(x -> x.length).sum() == 0)
return null;
Canvas canvas = new Canvas(new double[]{0, 0}, new double[]{1, 1e-5}, true);
PlotPanel plotPanel = new PlotPanel(canvas);
canvas.add(ScatterPlot.of(data));
canvas.setTitle("Convergence Plot");
canvas.setAxisLabels("Iteration", "log10(Fitness)");
plotPanel.setSize(600, 400);
return plotPanel;
} else {
double[][] data = history.stream().map(step -> new double[]{step.iteration, step.fitness})
.filter(x -> Arrays.stream(x).allMatch(Double::isFinite)).toArray(double[][]::new);
if (Arrays.stream(data).mapToInt(x -> x.length).sum() == 0)
return null;
Canvas canvas = new Canvas(new double[]{0, 0}, new double[]{1, 1e-5}, true);
PlotPanel plotPanel = new PlotPanel(canvas);
plotPanel.setSize(600, 400);
canvas.add(ScatterPlot.of(data));
canvas.setTitle("Convergence Plot");
canvas.setAxisLabels("Iteration", "Fitness");
return plotPanel;
}
} catch (@Nonnull final Exception e) {
logger.warn("Error plotting", e);
return null;
}
}
/**
* Plot time plot canvas.
*
* @param history the history
* @return the plot canvas
*/
@Nullable
public static PlotPanel plotTime(@Nonnull final List<StepRecord> history) {
try {
final LongSummaryStatistics timeStats = history.stream().mapToLong(x -> x.epochTime).summaryStatistics();
final DoubleSummaryStatistics valueStats = history.stream().mapToDouble(x -> x.fitness).filter(x -> x > 0)
.summaryStatistics();
Canvas canvas = new Canvas(new double[]{0, 0}, new double[]{1, 1e-5}, true);
PlotPanel plotPanel = new PlotPanel(canvas);
canvas.add(ScatterPlot.of(history.stream()
.map(step -> new double[]{(step.epochTime - timeStats.getMin()) / 1000.0,
Math.log10(Math.max(valueStats.getMin(), step.fitness))})
.filter(x -> Arrays.stream(x).allMatch(Double::isFinite)).toArray(double[][]::new)));
canvas.setTitle("Convergence Plot");
canvas.setAxisLabels("Time", "log10(Fitness)");
plotPanel.setSize(600, 400);
return plotPanel;
} catch (@Nonnull final Exception e) {
e.printStackTrace(System.out);
return null;
}
}
/**
* Shuffle ref int stream.
*
* @param stream the stream
* @return the ref int stream
*/
@Nonnull
public static RefIntStream shuffle(@Nonnull RefIntStream stream) {
// http://primes.utm.edu/lists/small/10000.txt
long coprimeA = 41387;
long coprimeB = 9967;
long ringSize = coprimeA * coprimeB - 1;
@Nonnull
IntToLongFunction fn = x -> x * coprimeA * coprimeA % ringSize;
@Nonnull
LongToIntFunction inv = x -> (int) (x * coprimeB * coprimeB % ringSize);
@Nonnull
IntUnaryOperator conditions = x -> {
assert x < ringSize;
assert x >= 0;
return x;
};
return stream.map(conditions).mapToLong(fn).sorted().mapToInt(inv);
}
/**
* Or else supplier.
*
* @param <T> the type parameter
* @param suppliers the suppliers
* @return the supplier
*/
@Nonnull
public static <T> Supplier<T> orElse(@Nonnull Supplier<T>... suppliers) {
return () -> {
for (@Nonnull
Supplier<T> supplier : suppliers) {
T t = supplier.get();
if (null != t)
return t;
}
return null;
};
}
/**
* Animated gif char sequence.
*
* @param log the log
* @param images the images
* @return the char sequence
*/
@Nonnull
public static CharSequence animatedGif(@Nonnull final NotebookOutput log, @Nonnull final BufferedImage... images) {
return animatedGif(log, 15000, images);
}
/**
* Build map ref map.
*
* @param <K> the type parameter
* @param <V> the type parameter
* @param configure the configure
* @return the ref map
*/
@Nonnull
public static <K, V> RefMap<K, V> buildMap(@Nonnull RefConsumer<RefMap<K, V>> configure) {
RefMap<K, V> map = new RefHashMap<>();
configure.accept(map.addRef());
return map;
}
/**
* Geometric stream supplier.
*
* @param start the start
* @param end the end
* @param steps the steps
* @return the supplier
*/
@Nonnull
public static Supplier<RefDoubleStream> geometricStream(final double start, final double end, final int steps) {
double step = Math.pow(end / start, 1.0 / (steps - 1));
return () -> RefDoubleStream.iterate(start, x -> x * step).limit(steps);
}
/**
* Shuffle ref list.
*
* @param <T> the type parameter
* @param list the list
* @return the ref list
*/
@Nonnull
public static <T> RefList<T> shuffle(@Nullable final RefList<T> list) {
RefArrayList<T> copy = new RefArrayList<>(list);
RefCollections.shuffle(copy.addRef());
return copy;
}
/**
* Add global handlers.
*
* @param httpd the httpd
*/
public static void addGlobalHandlers(@Nullable final FileHTTPD httpd) {
if (null != httpd) {
httpd.addGET("threads.json", "text/json", out -> {
try {
JsonUtil.getMapper().writer().writeValue(out, getStackInfo());
//JsonUtil.MAPPER.writer().writeValue(out, new HashMap<>());
out.close();
} catch (IOException e) {
throw Util.throwException(e);
}
});
}
}
/**
* Sum tensor.
*
* @param tensorStream the tensor stream
* @return the tensor
*/
@Nonnull
public static Tensor sum(@Nonnull RefCollection<Tensor> tensorStream) {
Tensor temp_13_0012 = RefUtil.get(tensorStream.stream().reduce((a, b) -> {
return Tensor.add(a, b);
}));
tensorStream.freeRef();
return temp_13_0012;
}
/**
* Sum tensor.
*
* @param tensorStream the tensor stream
* @return the tensor
*/
@Nonnull
public static Tensor sum(@Nonnull RefStream<Tensor> tensorStream) {
return RefUtil.get(tensorStream.reduce((a, b) -> {
return Tensor.add(a, b);
}));
}
/**
* Avg tensor.
*
* @param values the values
* @return the tensor
*/
@Nonnull
public static Tensor avg(@Nonnull RefCollection<? extends Tensor> values) {
Tensor temp_13_0027 = sum(values.stream().map(x -> {
return x;
}));
temp_13_0027.scaleInPlace(1.0 / values.size());
Tensor temp_13_0013 = temp_13_0027.addRef();
temp_13_0027.freeRef();
values.freeRef();
return temp_13_0013;
}
/**
* Render char sequence.
*
* @param log the log
* @param tensor the tensor
* @param normalize the normalize
* @return the char sequence
*/
@Nonnull
public static CharSequence render(@Nonnull final NotebookOutput log, @Nonnull final Tensor tensor,
final boolean normalize) {
return RefUtil.get(ImageUtil.renderToImages(tensor, normalize).map(image -> {
return log.png(image, "");
}).reduce((a, b) -> a + b));
}
/**
* Animated gif char sequence.
*
* @param log the log
* @param loopTimeMs the loop time ms
* @param images the images
* @return the char sequence
*/
@Nonnull
public static CharSequence animatedGif(@Nonnull final NotebookOutput log, final int loopTimeMs,
@Nonnull final BufferedImage... images) {
try {
@Nonnull
String filename = UUID.randomUUID().toString() + ".gif";
@Nonnull
File file = new File(log.getResourceDir(), filename);
GifSequenceWriter.write(file, loopTimeMs / images.length, true, images);
return RefString.format("<img src=\"etc/%s\" />", filename);
} catch (IOException e) {
throw Util.throwException(e);
}
}
} |
1 of 15 View Caption
Tribune staff photos The First Presidency of The Church of Jesus Christ of Latter-day Saints and members of the Quorum of the Twel Scott Sommerdorf | The Salt Lake Tribune Elder Dallin H. Oaks delivers his talk "Opposition in All Things" at the a Chris Detrick | The Salt Lake Tribune Elder David A. Bednar, Quorum of the Twelve Apostles, speaks during the afternoon session Scott Sommerdorf | The Salt Lake Tribune Dale G. Renlund gives his first speech as a member of The Quorum of the Twelve at the Scott Sommerdorf | The Salt Lake Tribune Ronald A. Rasband gives his first speech as a member of The Quorum of the Twelve at th Scott Sommerdorf | The Salt Lake Tribune Elder Jeffrey R. Holland delivers his talk "Tomorrow the Lord Will Do Wonders A Elder D. Todd Christofferson ï LDS Quorum of the Twelve Apostles Scott Sommerdorf | The Salt Lake Tribune President Russell M. Nelson speaks at the 186th Semiannual General Conference of the Chris Detrick | The Salt Lake Tribune Quentin L. Cook, Quorum of the Twelve Apostles, speaks during morning session of the 185th Elder THomas S. Monson - Member of the Twelve Apostles - Received - April 5, 1969 Chris Detrick | The Salt Lake Tribune Robert D. Hales, Quorum of the Twelve Apostles, speaks during the afternoon session of the Elder THomas S. Monson - Member of the Twelve Apostles - Tribune File PHoto - Received - June 29, 1968 Chris Detrick | The Salt Lake Tribune Elder Neil L. Andersen, Quorum of the Twelve Apostles, speaks during the morning session o Scott Sommerdorf | The Salt Lake Tribune Gary E. Stevenson gives his first speech as a member of The Quorum of the Twelve at th Leah Hogsten | The Salt Lake Tribune l-r First Counselor Henry B. Eyring, President Thomas S. Monson and Second Counselor Dieter |
def authenticate(self, provider_name, request):
config = self.openid_config(provider_name)
auth_code = request.args['code']
token_response = self.token_request(config, auth_code)
access_token = token_response['access_token']
try:
claims = verify_id_token(token_response['id_token'], config)
except KeyNotFound:
config = self.refresh_keys(provider_name)
claims = verify_id_token(token_response['id_token'], config)
claims.update(self.userinfo(config, access_token))
return claims |
<reponame>AHAOAHA/encapsutils
package encapsutils
import (
"sync"
)
// Stack stack interface.
type Stack interface {
Push(v interface{}) bool
Top() interface{}
Pop() interface{}
Size() int
Empty() bool
}
type stack struct {
mtx *sync.RWMutex
bus []interface{}
}
// NewStack create new stack.
func NewStack() Stack {
return &stack{
mtx: &sync.RWMutex{},
bus: make([]interface{}, 0),
}
}
func (s *stack) Push(v interface{}) bool {
s.mtx.Lock()
defer s.mtx.Unlock()
s.bus = append(s.bus, v)
return true
}
func (s *stack) Pop() interface{} {
s.mtx.Lock()
defer s.mtx.Unlock()
if len(s.bus) > 0 {
rv := s.bus[len(s.bus)-1]
s.bus = s.bus[:len(s.bus)-1]
return rv
}
return nil
}
func (s *stack) Top() interface{} {
s.mtx.RLock()
defer s.mtx.RUnlock()
if len(s.bus) > 0 {
return s.bus[len(s.bus)-1]
}
return nil
}
func (s *stack) Size() int {
s.mtx.RLock()
defer s.mtx.RUnlock()
return len(s.bus)
}
func (s *stack) Empty() bool {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.Size() == 0
}
|
Extraction of three bioactive diterpenoids from Andrographis paniculata: effect of the extraction techniques on extract composition and quantification of three andrographolides using high-performance liquid chromatography.
Andrographis paniculata (Burm.f.) wall.ex Nees (Acanthaceae) or Kalmegh is an important medicinal plant finding uses in many Ayurvedic formulations. Diterpenoid compounds andrographolides (APs) are the main bioactive phytochemicals present in leaves and herbage of A. paniculata. The efficiency of supercritical fluid extraction (SFE) using carbon dioxide was compared with the solid-liquid extraction techniques such as solvent extraction, ultrasound-assisted solvent extraction and microwave-assisted solvent extraction with methanol, water and methanol-water as solvents. Also a rapid and validated reverse-phase high-performance liquid chromatography-diode array detection method was developed for the simultaneous determination of the three biologically active compounds, AP, neoandrographolide and andrograpanin, in the extracts of A. paniculata. Under the best SFE conditions tested for diterpenoids, which involved extraction at 60°C and 100 bar, the extractive efficiencies were 132 and 22 µg/g for AP and neoandrographolide, respectively. The modifier percentage significantly affected the extraction efficiency. |
<reponame>wksw/go-chassis<filename>core/router/weightpool/weightpool_test.go
package weightpool_test
import (
"testing"
"github.com/go-chassis/go-chassis/v2/core/config"
wp "github.com/go-chassis/go-chassis/v2/core/router/weightpool"
"github.com/stretchr/testify/assert"
)
var (
tagsOff100 = []*config.RouteTag{
{Weight: 25, Tags: map[string]string{"version": "A"}},
{Weight: 30, Tags: map[string]string{"version": "B"}},
{Weight: 40, Tags: map[string]string{"version": "C"}},
}
tags50 = []*config.RouteTag{
{Weight: 50, Tags: map[string]string{"version": "A"}},
{Weight: 50, Tags: map[string]string{"version": "B"}},
}
)
func TestPoolPickOne(t *testing.T) {
p, ok := wp.GetPool().Get("test")
if !ok {
p = wp.NewPool(tagsOff100...)
wp.GetPool().Set("test", p)
}
var a, b, c, d int
for i := 0; i < 100; i++ {
t := p.PickOne()
switch t.Tags["version"] {
case "A":
a++
case "B":
b++
case "C":
c++
case "latest":
d++
}
}
assert.Equal(t, a, 25)
assert.Equal(t, b, 30)
assert.Equal(t, c, 40)
assert.Equal(t, d, 5)
wp.GetPool().Reset("test")
}
func BenchmarkPickOne(b *testing.B) {
p := wp.NewPool(tagsOff100...)
b.ResetTimer()
for i := 0; i < b.N; i++ {
p.PickOne()
}
b.ReportAllocs()
}
func BenchmarkPickOneParallel(b *testing.B) {
p := wp.NewPool(tags50...)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
p.PickOne()
}
})
b.ReportAllocs()
}
|
"""Backwards compatibility alias for :mod:`gevent.resolver.thread`.
.. deprecated:: 1.3
Use :mod:`gevent.resolver.thread`
"""
import warnings
warnings.warn(
"gevent.resolver_thread is deprecated and will be removed in 1.5. "
"Use gevent.resolver.thread instead.",
DeprecationWarning,
stacklevel=2
)
del warnings
from gevent.resolver.thread import * # pylint:disable=wildcard-import,unused-wildcard-import
import gevent.resolver.thread as _thread
__all__ = _thread.__all__
del _thread
|
/**
* This Fragment follows the dumb/passive view pattern. Its sole responsibility is to render the UI.
* <p>
* https://martinfowler.com/eaaDev/PassiveScreen.html
* <p>
* https://medium.com/@rohitsingh14101992/lets-keep-activity-dumb-using-livedata-53468ed0dc1f
*/
public class TrackingTabFragment extends Fragment {
@BindView(R.id.tracking_status_bar)
TrackingStatusBar trackingStatusBar;
@Inject
TrackingViewModelFactory trackingViewModelFactory;
@Inject
TodayScheduleViewModel.Factory todayScheduleViewModelFactory;
@Inject
StudyBurstViewModel.Factory studyBurstViewModelFactory;
@Inject
SurveyViewModel.Factory surveyViewModelFactory;
private TrackingViewModel trackingViewModel;
private TodayScheduleViewModel todayScheduleViewModel;
private SurveyViewModel surveyViewModel;
private StudyBurstViewModel studyBurstViewModel;
private Unbinder unbinder;
public static TrackingTabFragment newInstance() {
return new TrackingTabFragment();
}
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tracking_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
// Move the status bar down by the window insets.
OnApplyWindowInsetsListener listener = SystemWindowHelper.getOnApplyWindowInsetsListener(Direction.TOP);
ViewCompat.setOnApplyWindowInsetsListener(this.trackingStatusBar, listener);
this.trackingStatusBar.setOnClickListener((View v) -> {
startActivity(new Intent(getActivity(), StudyBurstActivity.class));
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ViewCompat.requestApplyInsets(view);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
trackingViewModel = ViewModelProviders.of(this, trackingViewModelFactory.create())
.get(TrackingViewModel.class);
todayScheduleViewModel = ViewModelProviders.of(this, todayScheduleViewModelFactory)
.get(TodayScheduleViewModel.class);
todayScheduleViewModel.liveData().observe(this, todayHistoryItems -> {
// TODO: mdephillips 9/4/18 mimic what iOS does with the history items, see TodayViewController
});
studyBurstViewModel = ViewModelProviders.of(this, studyBurstViewModelFactory)
.get(StudyBurstViewModel.class);
studyBurstViewModel.liveData().observe(this, this::setupActionBar);
surveyViewModel = ViewModelProviders.of(this, surveyViewModelFactory)
.get(SurveyViewModel.class);
surveyViewModel.liveData().observe(this, scheduledActivityEntities -> {
// TODO: mdephillips 9/4/18 mimic what iOS does with these
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
/**
* Sets up the action bar according to the current state of the study burst
*
* @param item
* most recent item from the StudyBurstViewModel
*/
private void setupActionBar(@Nullable StudyBurstItem item) {
if (item == null) {
return;
}
if (!item.getHasStudyBurst() || item.getDayCount() == null) {
trackingStatusBar.setVisibility(View.GONE);
return;
}
trackingStatusBar.setVisibility(View.VISIBLE);
trackingStatusBar.setDayCount(item.getDayCount());
trackingStatusBar.setMax(100);
trackingStatusBar.setProgress(Math.round(100 * item.getProgress()));
if (getContext() == null) {
return;
}
TodayActionBarItem actionBarItem = item.getActionBarItem(getContext());
if (actionBarItem != null) {
trackingStatusBar.setTitle(actionBarItem.getTitle());
trackingStatusBar.setText(actionBarItem.getDetail());
} else {
trackingStatusBar.setTitle(null);
trackingStatusBar.setText(null);
}
}
} |
# Copyright (c) 2016-2017 <NAME>
# Licensed under Apache License v2.0
load(
"@bazel_toolbox//labels:labels.bzl",
"executable_label",
)
load(
":internal.bzl",
"web_internal_generate_variables",
)
generate_variables = rule(
attrs = {
"config": attr.label(
mandatory = True,
allow_single_file = True,
),
"out_js": attr.output(),
"out_css": attr.output(),
"out_scss": attr.output(),
"_generate_variables_script": executable_label(Label("//generate:generate_variables")),
},
output_to_genfiles = True,
implementation = web_internal_generate_variables,
)
|
def load(self, entities: List['DXFEntity']) -> None:
def load_block_record(
block_entities: Sequence['DXFEntity']) -> 'BlockRecord':
block = cast('Block', block_entities[0])
endblk = cast('EndBlk', block_entities[-1])
try:
block_record = cast(
'BlockRecord',
block_records.get(block.dxf.name)
)
except DXFTableEntryError:
block_record = cast(
'BlockRecord',
block_records.new(block.dxf.name, dxfattribs={'scale': 0})
)
block_record.set_block(block, endblk)
for entity in block_entities[1:-1]:
block_record.add_entity(entity)
return block_record
def link_entities() -> Iterable['DXFEntity']:
linked = entity_linker()
for entity in entities:
if not linked(entity):
yield entity
block_records = self.block_records
section_head: 'DXFTagStorage' = cast('DXFTagStorage', entities[0])
if section_head.dxftype() != 'SECTION' or \
section_head.base_class[1] != (2, 'BLOCKS'):
raise DXFStructureError(
"Critical structure error in BLOCKS section."
)
del entities[0]
block_entities = []
for entity in link_entities():
block_entities.append(entity)
if entity.dxftype() == 'ENDBLK':
block_record = load_block_record(block_entities)
self.add(block_record)
block_entities = [] |
/// Read the config file from the config path specified in `path`.
/// If the config file is read & parsed properly, it should return
/// a `Config`.
pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> {
let mut content = String::new();
// Check whether there are tons of configs in the path
if path.as_ref().is_dir() {
// Read every config files and put them into a string, if it is
for entry in fs::read_dir(path)? {
let entry = entry?;
let mut config = File::open(entry.path())?;
config.read_to_string(&mut content)?;
}
} else {
// Read the config file into a string, if it isn't
let mut config = File::open(path)?;
config.read_to_string(&mut content)?;
}
// Try to parse the string, and convert it into a `Config`.
let config = content.parse::<toml::Value>()?;
let config = config.try_into::<Self>()?;
Ok(config)
} |
import * as express from 'express';
import { Server } from "colyseus";
import { createServer } from "http";
import FreeForAll from './rooms/FreeForAll';
const port = 2560
const app = express();
app.use(express.json());
const gameServer = new Server({
server: createServer(app),
express: app,
});
gameServer.define("ffa", FreeForAll);
gameServer.listen(port); |
<filename>PrivateFrameworks/Catalyst/_CATProxyWaitToken.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class NSObject<OS_dispatch_group>;
__attribute__((visibility("hidden")))
@interface _CATProxyWaitToken : NSObject
{
// Error parsing type: AB, name: mFinished
NSObject<OS_dispatch_group> *mGroup;
BOOL _isExclusive;
id _resourceProxy;
}
@property(readonly, nonatomic) id resourceProxy; // @synthesize resourceProxy=_resourceProxy;
@property(readonly, nonatomic) BOOL isExclusive; // @synthesize isExclusive=_isExclusive;
- (void).cxx_destruct;
- (void)invalidate;
- (void)cancel;
- (void)notifyWithResourceProxy:(id)arg1;
- (void)dealloc;
- (id)initWithExclusive:(BOOL)arg1 group:(id)arg2;
@end
|
<filename>src/types/request.rs
use serde::{Deserialize, Serialize};
use serde_json::value::Value;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Request {
#[serde(rename = "requestId", default = "default_uuid_string")]
pub request_id: String,
pub action: String,
pub controller: String,
pub index: Option<String>,
pub collection: Option<String>,
pub jwt: Option<String>,
pub body: Option<Value>,
}
fn default_uuid_string() -> String {
Uuid::new_v4().to_string()
}
#[macro_export]
macro_rules! request {
($($json:tt)+) => {
$crate::forge_request_from_json!($($json)+)
}
}
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! forge_request_from_json {
($($json:tt)+) => {{
let json = serde_json::json!($($json)+);
serde_json::from_value::<$crate::types::Request>(json)
}}
}
#[cfg(test)]
mod test {
use super::*;
use serde_json::from_value;
use std::error::Error;
use uuid::Uuid;
type BoxResult = Result<(), Box<dyn Error>>;
#[test]
fn from_json_macro() -> BoxResult {
let request: Request = request!({
"action": "fakeAction",
"controller": "fakeController",
"jwt": "fakeToken",
"body": {
"query": {
"term": 42
}
}
})?;
assert_eq!("fakeAction", &request.action);
assert_eq!("fakeController", &request.controller);
assert_eq!(
42,
from_value::<i32>(request.body.unwrap()["query"]["term"].clone())?
);
assert!(Uuid::parse_str(&request.request_id).is_ok());
assert_eq!("fakeToken", &request.jwt.unwrap());
Ok(())
}
#[test]
fn with_empty_body() -> BoxResult {
let request: Request = request!({
"action": "fakeAction",
"controller": "fakeController",
})?;
assert_eq!("fakeAction", &request.action);
assert_eq!("fakeController", &request.controller);
Ok(())
}
}
|
/**
* Default implementation of {@link ServerInfoMessage}.
* Wraps the Protocol Buffer implementation
*/
class ServerInfoMessageImpl implements ServerInfoMessage {
private static final Logger logger = LoggerFactory.getLogger(ServerInfoMessageImpl.class);
private final NetData.ServerInfoMessage info;
ServerInfoMessageImpl(NetData.ServerInfoMessage pbInfo) {
this.info = pbInfo;
}
@Override
public String getGameName() {
return info.getGameName();
}
@Override
public String getMOTD() {
return info.getMOTD();
}
@Override
public List<WorldInfo> getWorldInfoList() {
List<WorldInfo> result = Lists.newArrayList();
for (NetData.WorldInfo pbWorldInfo : info.getWorldInfoList()) {
WorldInfo worldInfo = new WorldInfo();
worldInfo.setTime(pbWorldInfo.getTime());
worldInfo.setTitle(pbWorldInfo.getTitle());
result.add(worldInfo);
}
return result;
}
@Override
public List<String> getRegisterBlockFamilyList() {
return Collections.unmodifiableList(info.getRegisterBlockFamilyList());
}
@Override
public long getTime() {
return info.getTime();
}
@Override
public float getReflectionHeight() {
return info.getReflectionHeight();
}
@Override
public int getOnlinePlayersAmount() {
return info.getOnlinePlayersAmount();
}
@Override
public List<NameVersion> getModuleList() {
List<NameVersion> result = Lists.newArrayList();
for (NetData.ModuleInfo moduleInfo : info.getModuleList()) {
if (!moduleInfo.hasModuleId() || !moduleInfo.hasModuleVersion()) {
logger.error("Received incomplete module info");
} else {
Name id = new Name(moduleInfo.getModuleId());
Version version = new Version(moduleInfo.getModuleVersion());
result.add(new NameVersion(id, version));
}
}
return result;
}
@Override
public Map<Integer, String> getBlockIds() {
Map<Integer, String> result = Maps.newHashMap();
for (int i = 0; i < info.getBlockIdCount(); ++i) {
result.put(info.getBlockId(i), info.getBlockName(i));
}
return result;
}
} |
package desc
import "testing"
func TestDesc(t *testing.T){
st := []struct{
name string
nums []int
exp bool
}{
{"nil slice",nil, true},
{"single element",[]int{1},true},
{"descring",[]int{4,2,1},false},
{"can change",[]int{4,2,3},true},
{"3423",[]int{3,4,2,3},false},
}
for _,c := range st{
t.Run(c.name, func(t *testing.T){
ret := descWithoutMidification(c.nums)
if ret != c.exp {
t.Fatalf("expected %t but got %t, with input %v",
c.exp, ret, c.nums)
}
})
}
} |
// noopValidator is a no-op that only decodes the message, but does not check its contents.
func (s *Service) noopValidator(_ context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
m, err := s.decodePubsubMessage(msg)
if err != nil {
log.WithError(err).Debug("Could not decode message")
return pubsub.ValidationReject
}
msg.ValidatorData = m
return pubsub.ValidationAccept
} |
<reponame>retrodaredevil/allwpilib<filename>wpiutil/src/main/native/include/wpi/leb128.h
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2015-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#ifndef WPIUTIL_WPI_LEB128_H_
#define WPIUTIL_WPI_LEB128_H_
#include <cstddef>
#include "wpi/SmallVector.h"
namespace wpi {
class raw_istream;
/**
* Get size of unsigned LEB128 data
* @val: value
*
* Determine the number of bytes required to encode an unsigned LEB128 datum.
* The algorithm is taken from Appendix C of the DWARF 3 spec. For information
* on the encodings refer to section "7.6 - Variable Length Data". Return
* the number of bytes required.
*/
uint64_t SizeUleb128(uint64_t val);
/**
* Write unsigned LEB128 data
* @addr: the address where the ULEB128 data is to be stored
* @val: value to be stored
*
* Encode an unsigned LEB128 encoded datum. The algorithm is taken
* from Appendix C of the DWARF 3 spec. For information on the
* encodings refer to section "7.6 - Variable Length Data". Return
* the number of bytes written.
*/
uint64_t WriteUleb128(SmallVectorImpl<char>& dest, uint64_t val);
/**
* Read unsigned LEB128 data
* @addr: the address where the ULEB128 data is stored
* @ret: address to store the result
*
* Decode an unsigned LEB128 encoded datum. The algorithm is taken
* from Appendix C of the DWARF 3 spec. For information on the
* encodings refer to section "7.6 - Variable Length Data". Return
* the number of bytes read.
*/
uint64_t ReadUleb128(const char* addr, uint64_t* ret);
/**
* Read unsigned LEB128 data from a stream
* @is: the input stream where the ULEB128 data is to be read from
* @ret: address to store the result
*
* Decode an unsigned LEB128 encoded datum. The algorithm is taken
* from Appendix C of the DWARF 3 spec. For information on the
* encodings refer to section "7.6 - Variable Length Data". Return
* false on stream error, true on success.
*/
bool ReadUleb128(raw_istream& is, uint64_t* ret);
} // namespace wpi
#endif // WPIUTIL_WPI_LEB128_H_
|
“It’s like someone dropped ice water on the head of America,” Julie Gaines, the owner of Fishs Eddy, a home goods store in Manhattan, said of Mr. Trump’s increased odds. “Everyone sobered up. This could happen.”
Photo Linda Donohue, left, and Cathi Anderson shopping at Zabar’s on the Upper West Side of Manhattan on Wednesday. “We have to have more faith in the American public,” said Ms. Donohue, a longtime New Yorker now living in Seattle. Credit Demetrius Freeman for The New York Times
The creeping dread has accelerated in recent days, reaching critical levels even by Democratic standards.
Mrs. Clinton became sick. Several polls tightened to the margin of panic, with Mr. Trump overtaking her in surveys in Ohio and Florida. And even as Democrats hoped on Friday that Mr. Trump’s latest gambit — seeking to distance himself from his long history of “birtherism” — would backfire, there is a fear that no scandal can sink him.
A cartoon in The New Yorker captured it best: A woman sits in her psychiatrist’s office, perspiring in distress. The doctor scribbles on a pad. “I’m giving you something for Hillary’s pneumonia,” the caption reads.
Supporters of Mrs. Clinton have greeted the moment with varying degrees of alarm, according to interviews with dozens of them across the country.
They read warily about the health of her lungs and her swing-state field operations. They reassure one another by reminding themselves of President Obama’s two winning campaigns, which encountered similar fits of concern after Labor Day.
Advertisement Continue reading the main story
But even some zealous Clinton defenders have grown frustrated with their candidate, marveling at the prospect of her snatching defeat from the jaws of victory, for which some say they would never forgive her. The campaign’s decision last week not to acknowledge Mrs. Clinton’s pneumonia until two days after a diagnosis, once video surfaced of her stumbling out of a Sept. 11 memorial service on Sunday, has especially rankled.
“They kept it from us,” said Sonia Ascher, 74, a former campaign volunteer, sitting with her husband and son at a coffee shop in Portsmouth, N.H. “It was just another thing again, another mistake, which she really can’t afford right now.”
The gloom seems to be spreading. Maurice Doucet, 55, a software engineer from Portland, Ore., wondered aloud on Wednesday how the race had gotten this close, lamenting Mrs. Clinton’s use of a private email server as secretary of state.
Photo Guillermo Vidal and a friend’s dog, Dipsy, in Washington Square Park in Manhattan. Credit Demetrius Freeman for The New York Times
“The rational side of my brain goes, ‘There’s no way people are actually going to switch sides,’” he said of voters’ movement toward Mr. Trump. “But the emotional side,” he added, his voice trailing off moments later.
Today’s Headlines Wake up each morning to the day’s top news, analysis and opinion delivered to your inbox. Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. Sign Up Receive occasional updates and special offers for The New York Times's products and services. recaptcha status Recaptcha requires verification I'm not a robot reCAPTCHA Privacy - Terms Thank you for subscribing to Today’s Headlines . An error has occurred. Please try again later. You are already subscribed to this email. View all New York Times newsletters. See Sample
Manage Email Preferences
Not you?
Privacy Policy
In Washington Square Park in Manhattan, among smitten college students and acoustic guitars, Guillermo Vidal, 75, grimaced at the thought of a Trump presidency. His friend’s bichon frisé-poodle mix, Dipsy, sat on the bench beside him, looking fretful.
Mr. Vidal was asked what was troubling Dipsy.
“She’s a Democrat,” Mr. Vidal said dryly.
Then there are those who traffic in angst professionally, who are straining to consider even the chance of a Trump election.
“The possibility of that is too horrifying to broach,” Larry David, the “Seinfeld” co-creator and “Curb Your Enthusiasm” star, wrote in an email. “It’s like contemplating your own death.”
Surely Mr. David had done that, too?
“I can’t go there,” he said.
In liberal enclaves, some modest contingency planning has begun. Threats of relocation are a bipartisan ritual every four years, expanding the audience for Canadian home listings. But this time, voters seem to be taking their research a bit more seriously.
Ramona Gant, 28, a graduate student in Chicago, said she had just renewed her passport with the election in mind.
Advertisement Continue reading the main story
Ms. Donohue’s friend at Zabar’s, Ms. Anderson, also of Seattle, mused that Vancouver was not too far up the road.
Mike Brennan, 67, from Ventura County, Calif., is keeping an eye on the stock market.
“If it looks like it’s going to be close,” said Mr. Brennan, a Republican supporting Mrs. Clinton, “I’ll pull my money out.”
Photo Sonia Ascher, with her husband, John Greenwood, in Portsmouth, N.H. She criticized the Clinton campaign’s decision not to acknowledge Mrs. Clinton’s pneumonia until two days after a diagnosis. Credit Cheryl Senter for The New York Times
For many Americans, Mr. Trump’s momentum has registered as a more visceral threat, heightening concerns that had festered since his candidacy began. Ahtziry Barrera, 18, a college freshman from Orlando, Fla., arrived in the United States more than a decade ago from Mexico. Under an Obama administration policy known as DACA, which Mrs. Clinton has vowed to protect, Ms. Barrera has been allowed to stay in the country because she entered as a child.
“A lot of people were not taking him seriously. ‘Oh, he’s not going to win.’ But it happened,” she said of Mr. Trump’s success in the Republican primary race. “It is a big stress on me, knowing that Nov. 8 is the day I’ll know whether my future is going to be secure or not.”
Some optimists have preached calm, reminding one another of Mrs. Clinton’s organizational advantages and holding out hope that she can best Mr. Trump decisively on a debate stage.
While allowing that Mrs. Clinton has not run a perfect race, many of her admirers have cast blame elsewhere, singling out the news media, the Republicans who nominated Mr. Trump and, of course, the man himself.
Gloria Steinem, the feminist leader and a Clinton supporter, said in an email that she had sensed a growing worry in recent weeks, fearing that Mr. Trump’s candidacy was becoming “legitimized by ‘media evenhandedness’” that had made his assorted scandals seem more banal.
“There are things any campaign could do better, but in this case, I fear it’s like blaming the victim instead of the bully — dissociating in the hope that we won’t be bullied, too,” she wrote. “It’s like saying, ‘If only she hadn’t been walking in that neighborhood. …’”
Advertisement Continue reading the main story
Others hold tight to an abiding belief, perhaps against their better judgment, that everything will work out.
“I still believe in humanity,” said Nadia Johnson, 22, a Brooklyn resident lunching at a Whole Foods this week.
She quickly added a request: Ask her again in November. |
/*
* Copyright (C) 2019 Kaleidos Open Source SL
*
* This file is part of PATIO.
* PATIO 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.
*
* PATIO 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 PATIO. If not, see <https://www.gnu.org/licenses/>
*/
package patio.security.services;
import static io.github.benas.randombeans.api.EnhancedRandom.random;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.verify;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import patio.infrastructure.email.domain.Email;
import patio.infrastructure.email.services.EmailService;
import patio.infrastructure.email.services.internal.EmailComposerService;
import patio.infrastructure.email.services.internal.templates.URLResolverService;
import patio.security.services.internal.Auth0CryptoService;
import patio.security.services.internal.DefaultResetPasswordService;
import patio.user.domain.User;
import patio.user.repositories.UserRepository;
/**
* Tests {@link DefaultResetPasswordService}
*
* @since 0.1.0
*/
public class ResetPasswordServiceTests {
@Test
void testResetPasswordRequest() {
// given: a user
var user =
User.builder()
.with(u -> u.setOtp(""))
.with(u -> u.setOtpCreationDateTime(null))
.with(u -> u.setName("Peter"))
.build();
// and: a new randomly-generated One-time Password (OTP)
var randomOTP = "$2a$10$ccXSNGubl.ja9eV2Dfrxmhd9t";
var auth0CryptoService = Mockito.mock(Auth0CryptoService.class);
Mockito.when(auth0CryptoService.hash(any())).thenReturn(randomOTP);
// given: mocked repositories and services
var userRepository = Mockito.mock(UserRepository.class);
Mockito.when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.of(user));
// and: other mocked services
var emailComposerService = Mockito.mock(EmailComposerService.class);
var emailService = Mockito.mock(EmailService.class);
var urlResolverService = Mockito.mock(URLResolverService.class);
// when: invoking service resetPasswordRequest()
var defaultResetPasswordService =
new DefaultResetPasswordService(
"/user/{0}/reset?otp={1}",
userRepository,
auth0CryptoService,
emailComposerService,
emailService,
urlResolverService);
defaultResetPasswordService.resetPasswordRequest(user.getEmail());
// then: we should have set an OTP for the user
assertThat("The user's otp is now defined", user.getOtp(), is(randomOTP));
assertThat(
"The user's otpCreationDate is defined",
user.getOtpCreationDateTime().toString(),
is(not("")));
// and: user changes are persisted
verify(userRepository, atLeast(1)).save(any(User.class));
// and: an password resetting email is generated
verify(emailComposerService, atLeast(1)).composeEmail(any(), any(), any(), any());
Mockito.when(emailComposerService.composeEmail(any(), any(), any(), any()))
.thenReturn(random(Email.class));
// and: the email finally gets send
verify(emailService, atLeast(1)).send(any());
}
}
|
Contrubution of Snacks to Total Nutrient Intake by Normal and Overweight Puerto Rican Children at Three Different School Levels
Snacking is a common practice and depending upon content, can either contribute to or counteract the widespread incidence of our nation's obesity epidemic. The objective of this study is to determine the contribution of snacks to total daily nutrients in a population of normal and overweight children at 3 different school levels, both during week days and weekend days. To this effect, we have performed multiple 24 hr dietary recall interviews with normal weight (N) and overweight (O) (BMI at the 85th percentile) children in Elementary (E) n = 101, Intermediate (I) n = 116 and High (H) n = 105 schools of metropolitan San Juan, collecting information from week days and from weekend days. E students reported highest rate of snacking, followed by I students with H students having the lowest rate. Weekend snacking was less frequent with E and I children but about the same in H children. Results from macronutrient content show that snacks accounted for 23% of calories for E children, 34% of calories for I children and 28% of calories for H children with O children having slightly higher %'s than N children. Patterns of snacks on weekends closely resembled those of weekdays. Overall, these data provide information that could be used to determine if the content of snacks in our population weighs for or against the overall obesity problem. Financial support: National Research Initiative of the USDA Cooperative State Research Education and Extension Service, Grant number 2003–35200‐13590. |
// block.cpp -- implementation of parser/compiler for blocks
// Author: <NAME>
// Date 10/12/2016 -- framework established
// BNF
// <block> ::= { <block element> [ ; ] }
// <block element> ::= <declaration> | <statement>
#include "block.h"
// start sets
#define START_PUNCS SET32_EMPTY
#define START_KEYS ( to_set32_4( KEY_DO, KEY_IF, KEY_SELECT, KEY_CATCH ) \
| to_set32_3( KEY_RAISE, KEY_WHILE, KEY_FOR ) \
)
#define START_LEXS to_set32( IDENT )
// follow sets
#define FOLLOW_PUNCS SET32_EMPTY
#define FOLLOW_KEYS to_set32_4( KEY_END, KEY_ELSE, KEY_CASE, KEY_UNTIL )
#define FOLLOW_LEXS to_set32( ENDFILE )
// internal sets
Block * Block::compile( Environment * e ) {
Block * newBlock = new Block();
lex_wantinset( START_PUNCS, START_KEYS, START_LEXS, ER_WANT_BLOCK );
while (lex_isinset( START_PUNCS, START_KEYS, START_LEXS )) {
if ( (get_lex_this().type == IDENT)
&& lex_ispunc( get_lex_next(), PT_COLON ) ) {
// all declarations begin with ident:
e = Declaration::compile( e );
} else {
// if not a declaration must be a statement
Statement * s = Statement::compile( e );
}
if (lex_ispunc( get_lex_this(), PT_SEMI )) lex_advance();
}
lex_wantinset( FOLLOW_PUNCS, FOLLOW_KEYS, FOLLOW_LEXS, ER_WANT_ENDBLOK);
newBlock->attr = e;
return newBlock;
}
|
// PutMACIPAcl puts MAC IP access list config to the ETCD
func (ctl *VppAgentCtlImpl) PutMACIPAcl() error {
accessList := &acl.ACL{
Name: "aclmac1",
Rules: []*acl.ACL_Rule{
{
Action: acl.ACL_Rule_PERMIT,
MacipRule: &acl.ACL_Rule_MacIpRule{
SourceAddress: "192.168.0.1",
SourceAddressPrefix: uint32(16),
SourceMacAddress: "11:44:0A:B8:4A:35",
SourceMacAddressMask: "ff:ff:ff:ff:00:00",
},
},
},
Interfaces: &acl.ACL_Interfaces{
Ingress: []string{"tap1", "tap2"},
Egress: []string{"tap1", "tap2"},
},
}
ctl.Log.Infof("Access list put: %v", accessList)
return ctl.broker.Put(acl.Key(accessList.Name), accessList)
} |
/*
* Copyright 2018 coldrye.eu, <NAME>
*
* 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.
*/
package eu.coldrye.junit.env;
import eu.coldrye.junit.env.Fixtures.EnvProvider1;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.mockito.Mockito;
@TestInstance(Lifecycle.PER_CLASS)
public class AbstractEnvProviderTest {
private EnvProvider sut;
private Store storeMock;
@BeforeAll
public void setUp() {
sut = new EnvProvider1();
storeMock = Mockito.mock(Store.class);
}
@AfterAll
public void tearDown() {
sut = null;
storeMock = null;
}
@Test
public void setStore() {
sut.setStore(storeMock);
}
@Test
public void getStore() {
Assertions.assertEquals(storeMock, sut.getStore());
}
}
|
#include<stdio.h>
#include<string.h>
int main()
{ FILE *fin=fopen("input.txt","r");
FILE *fout=fopen("output.txt","w");
char s[10001];
int i,n,m;
fscanf(fin,"%d%d",&n,&m);
if(n==m)
{
for(i=0;i<n+m;i+=2)
{
s[i]='B';
s[i+1]='G';
}
fprintf(fout,"%s\n",s);
}
else if(n>m)
{
for(i=0;i<n-m;i++)
{
s[i]='B';
}
for(i=n-m;i<n+m;i+=2)
{
s[i]='G';
s[i+1]='B';
}
fprintf(fout,"%s\n",s);
}
else
{
for(i=0;i<m-n;i++)
{
s[i]='G';
}
for(i=m-n;i<n+m;i+=2)
{
s[i]='B';
s[i+1]='G';
}
fprintf(fout,"%s\n",s);
}
return 0;
}
|
/**
* Tests processor created outside the Spring context.
*/
@Test
public void testProcessor() {
Processor processor = new Processor();
logger.debug("Running processor from outside the Spring context.");
processor.process();
} |
/**
* Created by tomoya.
* Copyright (c) 2018, All Rights Reserved.
* https://yiiu.co
*/
public class BaseAdminController extends BaseApiController {
@Autowired
private AdminUserService adminUserService;
// 可以将传递到controller里的参数中Date类型的从String转成Date类型的对象
// 这货没有想象中的好用,还不如我手动控制String转Date了
// @InitBinder
// public void initBinder(ServletRequestDataBinder binder) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
// }
protected AdminUser getAdminUser() {
Subject subject = SecurityUtils.getSubject();
String principal = (String) subject.getPrincipal();
return adminUserService.selectByUsername(principal);
}
} |
n,m = map(int,input().split())
x = list(map(int,input().split()))
y = list(map(int,input().split()))
MOD = 10**9 + 7
ans = 0
temp1 = 0
temp2 = 0
for i in range(n):
temp1 += i*x[i] -(n-(i+1))*x[i]
temp1 %= MOD
for i in range(m):
temp2 += i*y[i] -(m-(i+1))*y[i]
temp2 %= MOD
ans = temp1*temp2
ans %= MOD
print(ans) |
n = input()
a = map(int, raw_input().split())
k = 10 ** 10
for i in range(n):
l = i
r = n - 1 - i
t = a[i] / max(l, r)
if t < k: k = t
print k
|
<gh_stars>1-10
/*
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*/
package com.google.cloud.managed.test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;
public class GcjTestRunner implements Runnable {
private final JUnitCore unit;
private final ByteArrayOutputStream resultBytes;
private final PrintStream resultStream;
private final List<Class<?>> classes;
public GcjTestRunner(List<Class<?>> classes) {
this.unit = new JUnitCore();
this.resultBytes = new ByteArrayOutputStream();
this.resultStream = new PrintStream(this.resultBytes);
this.unit.addListener(new TextListener(this.resultStream));
this.classes = new ArrayList<>(classes);
}
@Override
public void run() {
synchronized (resultStream) {
resultBytes.reset();
}
for (Class<?> clazz : classes) {
resultStream.append("\n").append("Running ").append(clazz.getName());
ClassLoader classLoader = clazz.getClassLoader();
resultStream.append(" (loaded by ").append(classLoader.getClass().getName()).append(")\n\n");
unit.run(clazz);
}
resultStream.append("ALL TESTS COMPLETED");
}
public String getOutput() {
//works because PrintStream is thread safe synchronizing on "this".
synchronized (resultStream) {
try {
return resultBytes.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
}
|
<filename>.history/classes/Round_20171106170947.py
class Round():
def __init__(self):
print("ANOTHA FAK UUUU")
|
def create_profile(sender, instance, created, **kwargs):
if created:
avt_default = 'avt/avatar-%s.png' % str(random.randint(1, 8))
Profile.objects.create(owner=instance, display_name=instance.username, avatar=avt_default) |
def create(self, document: Union[dict, AbstractMongoDocument]) -> str:
if getattr(document, "to_json", None) is not None:
document = document.to_json()
if isinstance(document, dict):
if "dataModelVersion" not in document and self.data_model_version is not None:
document["dataModelVersion"] = self.data_model_version
return str(self.collection.insert_one(document).inserted_id)
raise ValueError("Provided document needs to be a dict or provide a to_json() method") |
/* When the animation of the ReadyScreen is finished, move the top panel so that the user can click what's on the bottom panel, instead of the
* top one
*/
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == tmrPlay)
{
if (ReadyScreen.levelCounter >= 9)
{
start = true;
ReadyScreen.tmrReady.stop();
ReadyScreen.levelCounter = 0;
topPanel.setBounds(-436, 0, 436, 647);
}
repaint();
}
} |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Entities
*/
import { GuidString, Id64String } from "@bentley/bentleyjs-core";
import { XYProps } from "@bentley/geometry-core";
import { CodeProps } from "./Code";
import { RelatedElementProps } from "./ElementProps";
import { EntityProps, EntityQueryParams } from "./EntityProps";
/** Properties that define a [Model]($docs/bis/intro/model-fundamentals)
* @public
*/
export interface ModelProps extends EntityProps {
modeledElement: RelatedElementProps;
name?: string;
parentModel?: Id64String; // NB! Must always match the model of the modeledElement!
isPrivate?: boolean;
isTemplate?: boolean;
jsonProperties?: any;
}
/** Properties that specify what model should be loaded.
* @public
*/
export interface ModelLoadProps {
id?: Id64String;
code?: CodeProps;
}
/** Parameters for performing a query on [Model]($backend) classes.
* @public
*/
export interface ModelQueryParams extends EntityQueryParams {
wantTemplate?: boolean;
wantPrivate?: boolean;
}
/** Properties that describe a [GeometricModel]($backend)
* @public
*/
export interface GeometricModelProps extends ModelProps {
/** A unique identifier that is updated each time a change affecting the appearance of a geometric element within this model
* is committed to the iModel. In other words, between versions of the iModel, if this value is the same you can
* assume the appearance of all of the geometry in the model is the same (Note: other properties of elements may have changed.)
* If undefined, the state of the geometry is unknown.
*/
geometryGuid?: GuidString;
}
/** Properties that define a [GeometricModel2d]($backend)
* @public
*/
export interface GeometricModel2dProps extends GeometricModelProps {
/** The actual coordinates of (0,0) in modeling coordinates. An offset applied to all modeling coordinates. */
globalOrigin?: XYProps;
}
/** Properties that define a [GeometricModel3d]($backend)
* @public
*/
export interface GeometricModel3dProps extends GeometricModelProps {
/** If true, then the elements in this GeometricModel3d are not in real-world coordinates and will not be in the spatial index. */
isNotSpatiallyLocated?: boolean;
/** If true, then the elements in this GeometricModel3d are expected to be in an XY plane. */
isPlanProjection?: boolean;
}
|
/**
* Tests the ChangeCollectingPrefs.
*
* Each area that the ChangeCollectingPrefs collects changes for is tested
* separately here; there are no tests for combinations (yet)
*
* @author matt
*
*/
public final class TestChangeCollectingPrefs {
/**
*
*/
@Test
public void noTabHidingCausesNoChanges() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test(expected = IllegalStateException.class)
public void tabHidingWithoutPriorReadThrows() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
mockPrefs.setTabHidden(EasyMock.eq("SQL"));
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial
// setting - but don't do that here...
// don't do ccp.isTabHidden("SQL");
// Now change it
ccp.setTabHidden("SQL");
// b o o m
}
/**
*
*/
@Test
public void tabHidingAfterPriorReadCausesChanges() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.FALSE);
mockPrefs.setTabHidden(EasyMock.eq("SQL"));
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it
ccp.setTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void tabRepeatedTogglingFromClearedAfterPriorReadCausesNoChanges() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.FALSE);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it twice - no change should be made to the underlying prefs
ccp.setTabHidden("SQL");
ccp.clearTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void tabRepeatedTogglingFromHiddenAfterPriorReadCausesNoChanges() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.TRUE);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it twice - no change should be made to the underlying prefs
ccp.clearTabHidden("SQL");
ccp.setTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void clearingHiddenTabAfterPriorReadCausesChanges() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.TRUE);
mockPrefs.clearTabHidden(EasyMock.eq("SQL"));
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it
ccp.clearTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void clearingAlreadyClearedTabAfterPriorReadCausesNoChange() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.FALSE);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it
ccp.clearTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void hidingAlreadyHiddenTabAfterPriorReadCausesNoChange() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.TRUE);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now change it
ccp.setTabHidden("SQL");
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test
public void makingNoChangeToAlreadyHiddenTabAfterPriorReadCausesNoChange() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.expect(mockPrefs.isTabHidden("SQL")).andReturn(Boolean.TRUE);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
// The data has to be read through ccp first to create its initial setting
ccp.isTabHidden("SQL");
// Now don't make any changes
ccp.commit();
EasyMock.verify(mockPrefs);
}
/**
*
*/
@Test(expected = UnsupportedOperationException.class)
public void changingPrefsOptionThatsNotUsedByToolsOptionsThrows() {
final MiniMiserPrefs mockPrefs = EasyMock.createStrictMock(MiniMiserPrefs.class);
EasyMock.replay(mockPrefs);
final ChangeCollectingMiniMiserPrefs ccp = new ChangeCollectingMiniMiserPrefs(mockPrefs);
ccp.clearLastActiveFile(); // for example
}
} |
<filename>include/format.h
#ifndef FORMAT_H
#define FORMAT_H
#include <string>
namespace Format {
std::string ElapsedTime(long time);
std::string FormatTime(int i);
};
#endif
|
def kgtk_values(self,
validate: bool = False,
parse_fields: bool = False
)->typing.Iterator[typing.List[KgtkValue]]:
while True:
try:
yield self.to_kgtk_values(self.nextrow(), validate=validate, parse_fields=parse_fields)
except StopIteration:
return |
Role of propylamine transferases in hormone-induced stimulation of polyamine biosynthesis.
The effect of various hormones on the activities of the four enzymes engaged with the biosynthesis of the polyamines has been investigated in the rat. Human choriogonadotropin induced a dramatic, yet transient, stimulation of l-ornithine decarboxylase (EC 4.1.1.17) activity in rat ovary, with no or only marginal changes in the activities of S-adenosyl-l-methionine decarboxylase (EC 4.1.1.50), spermidine synthase (aminopropyltransferase; EC 2.5.1.16) or spermine synthase. A single injection of oestradiol into immature rats maximally induced uterine ornithine decarboxylase at 4h after the injection. This early stimulation of ornithine decarboxylase activity was accompanied by a distinct enhancement of adenosylmethionine decarboxylase activity and a decrease in the activities of spermidine synthase and spermine synthase. In the seminal vesicle of castrated rats, testosterone treatment elicited a striking and persistent stimulation of ornithine decarboxylase and adenosylmethionine decarboxylase activities. The activity of spermidine synthase likewise rapidly increased between the first and the second day after the commencement of the hormone treatment, whereas the activity of spermine synthase remained virtually unchanged during the whole period of observation. Testosterone-induced changes in polyamine formation in the ventral prostate were comparable with those found in the seminal vesicle, with the possible exception of a more pronounced stimulation of spermidine synthase activity. It thus appears that an enhancement in one or both of the propylamine transferase (aminopropyltransferase) activities in response to hormone administration is an indicator of hormone-dependent growth (uterus and the male accessory sexual glands), and is not necessarily associated with non-proliferative hormonal responses, such as gonadotropin-induced luteinization of the ovarian tissue. |
<gh_stars>0
# python3
# Copyright 2021 InstaDeep Ltd. All rights reserved.
#
# 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.
"""Example running MAD4PG on PZ environments."""
import functools
from datetime import datetime
from typing import Any
import launchpad as lp
import sonnet as snt
from absl import app, flags
from mava.systems.tf import mad4pg
from mava.utils import lp_utils
from mava.utils.environments import pettingzoo_utils
from mava.utils.loggers import logger_utils
from mava.wrappers.environment_loop_wrappers import MonitorParallelEnvironmentLoop
FLAGS = flags.FLAGS
flags.DEFINE_string(
"env_class",
"sisl",
"Pettingzoo environment class, e.g. atari (str).",
)
flags.DEFINE_string(
"env_name",
"multiwalker_v7",
"Pettingzoo environment name, e.g. pong (str).",
)
flags.DEFINE_string(
"mava_id",
str(datetime.now()),
"Experiment identifier that can be used to continue experiments.",
)
flags.DEFINE_string("base_dir", "~/mava", "Base dir to store experiments.")
def main(_: Any) -> None:
# Environment.
environment_factory = functools.partial(
pettingzoo_utils.make_environment,
env_name=FLAGS.env_name,
env_class=FLAGS.env_class,
remove_on_fall=False,
)
# Networks.
network_factory = lp_utils.partial_kwargs(mad4pg.make_default_networks)
# Checkpointer appends "Checkpoints" to checkpoint_dir.
checkpoint_dir = f"{FLAGS.base_dir}/{FLAGS.mava_id}"
# Log every [log_every] seconds.
log_every = 10
logger_factory = functools.partial(
logger_utils.make_logger,
directory=FLAGS.base_dir,
to_terminal=True,
to_tensorboard=True,
time_stamp=FLAGS.mava_id,
time_delta=log_every,
)
# Distributed program.
program = mad4pg.MAD4PG(
environment_factory=environment_factory,
network_factory=network_factory,
logger_factory=logger_factory,
num_executors=1,
policy_optimizer=snt.optimizers.Adam(learning_rate=1e-4),
critic_optimizer=snt.optimizers.Adam(learning_rate=1e-4),
checkpoint_subpath=checkpoint_dir,
max_gradient_norm=40.0,
eval_loop_fn=MonitorParallelEnvironmentLoop,
eval_loop_fn_kwargs={"path": checkpoint_dir, "record_every": 100},
).build()
# Ensure only trainer runs on gpu, while other processes run on cpu.
local_resources = lp_utils.to_device(
program_nodes=program.groups.keys(), nodes_on_gpu=["trainer"]
)
# Launch.
lp.launch(
program,
lp.LaunchType.LOCAL_MULTI_PROCESSING,
terminal="current_terminal",
local_resources=local_resources,
)
if __name__ == "__main__":
app.run(main)
|
<filename>day-13/src/main.rs
use std::{error::Error, path::PathBuf};
use advent_utils::{get_custom_config, Part, Solver};
use serde::Deserialize;
use day_13::{EmulatorMode, Solution};
#[derive(Debug, Deserialize)]
struct Config {
input_file: PathBuf,
part: Part,
mode: Option<EmulatorMode>,
}
fn main() -> Result<(), Box<dyn Error>> {
let config: Config = get_custom_config()?;
let solution = Solution::try_from_file_with_mode(config.input_file, config.mode)?;
println!("{}", solution.solve(config.part));
Ok(())
}
|
Linguistic Schoolscape as Public Communication: A Study of Announcements and Signages in De La Salle University – Dasmariñas
The study of linguistic landscape is considered in its infancy in socio-linguistic research (Monje, 2017). When we walk through an institution, it is common to encounter linguistic tokens in different locations. Announcements and signages are two of the most important things with regard to information dissemination in an institution. These things helped in aid to making students informed of everything that is important to know. These are as important as billboards and other big printed advertisements that we usually see in cities, factories etc. To make this effective, school signage should be integrated into the planning and design process, and should encompass brand reinforcement, way finding and regulatory, as well as specialty sign (David, 2011). These public signs are a type of a semiotic sign in that they too stand for other than themselves.
Introduction
The study of linguistic landscape is considered in its infancy in socio-linguistic research (Monje, 2017). When we walk through an institution, it is common to encounter linguistic tokens in different locations. Announcements and signages are two of the most important things with regard to information dissemination in an institution. These things helped in aid to making students informed of everything that is important to know. These are as important as billboards and other big printed advertisements that we usually see in cities, factories etc. To make this effective, school signage should be integrated into the planning and design process, and should encompass brand reinforcement, way finding and regulatory, as well as specialty sign (David, 2011). These public signs are a type of a semiotic sign in that they too stand for other than themselves.
Recent studies have shown that with the use of linguistic visual and spatial texts in the public, language awareness can be developed to the students and other learners engaged with the use of language. (Dagenais, 2009;Bolton, 2013;Dressler 2015).
Frequently, some experts have gone through research in order to know the effect of reading advertisements such as announcements, posters, signage, symbols and etc. to language learning. A considerable amount of research had been carried out but little research focused on its effect to linguistic competence; specifically, how the written announcements and signages affect the reading comprehension of students.
This study is related with the analysis of linguistic landscape. Landry and Bourhis (1997) define linguistic landscape as the visibility and salience of language on public and commercial signs in a given territory or region. To be more specific, the notion refers to: The language of public road signs, advertising billboards, street names, place names, commercial shop signs, and public signs on government buildings combines to form the linguistic landscape of a given territory, region, or urban agglomeration (p.25) In Hong Kong, a case study of shop signs and linguistic competence was made by Wolf (2012). The purpose of the study is to examine relations between the linguistic landscapes of two ethnically and socially diverse research areas and the linguistic competence of their inhabitants. It was shown that English is visibly present in most of the signage and other advertising materials of Hong Kong. More than that, employees of property agencies were in most cases fluent in English whilst workers at traditional shops such as butcheries and grocery stores were found to most likely lack conversational skills. As a whole, it was shown that in HK the preconditions for a high proficiency of English in a large majority of the population are given.
Moreover, another related study was conducted in Gaborone, Botswana by Akindele (2011) which aims to show that linguistic landscape can provide valuable insight into the linguistic situation of the place, including common patterns of language usage, official language policies, prevalent language attitudes, and the long-term consequences of language contact, among others. It was found out that the city is moving towards multilingualism in English, Setswana and Chinese. On the other hand, it is in high tendency that the English language was Linguistic landscape (LL) is the study of public signages in a distinct place. The study of linguistic landscape aims to promote a useful method to understand the evolution of an urban space. The language of public road signs, advertising billboards, street names, place names, commercial shop signs, and public signs on government building combines to form the linguistic landscape of a given territory, region or agglomeration (Landry & Bourhis, 1997). The present study intends to contribute to this development in educational institution. The aim of this study is to show and analyze the linguistic schoolscape of De La Salle University -Dasmariñas. This was done by analyzing the data collected from the school's public written signages such as announcements, posters, tarpaulins etc. Moreover, the researcher used quantitative approach to research to see if there is a significant difference on the language preferences of the seven (7) colleges of the institution.
Dastin Tabajunda
used as sign of prestige which also tells that the participants are proficient with the language.
To contextualize it, here in the Philippines, there have been studies aligned with LL conducted which determined the place and position of English in both rural and urban areas. Current studies focused on how English language functions in different spaces of the school whether it is in "top-down" or "bottom-up" (Astillero, 2018;Magno, 2017;Delos Reyes 2015).
A linguistic landscape study in Cebu City Higher Education offering communication programs (Magno, 2016) concluded that HEI's linguistic landscape represents current news and information in a formal tone and context as it caters to mature audience. Moreover, he also found out that choosing English language over other languages proves the remarkable influence of English as well as the prestige it currently carries in HEIs. Afar from that, bilingual and other multilingual signages are very minimal.
Similarly, Astillero (2016) used quantitative and qualitative to investigate languages in Irosin Secondary Schools. She found out that local languages in their province have very limited space in formal education especially in secondary level. Thus, the preferential use of English in the school LL, on one side, underscores the power, prestige of the language over the national and local languages and other, it may be contingent on the context where the dominant language is used (Astillero, 2011, p12).
Lastly, in the study presented by Reyes (2015), he concluded that the English language dominated the linguistic landscape of the two stations and very likely in many parts of the Philippines, evidently there is no "active competition" between English and Filipino in the linguistic landscape of the country. Hence, instead of being bilingual, it seems rather apt to call the LL as essentially "unilingual".
For the previous studies conducted about linguistic landscape, it may appear that the experts just focused on how the public signages shaped the acquisition and use of the English language and perhaps did not present if groups in a community have varieties of language preferences or just unified with the others. There were a few studies such that of Dagenais, Moore, Sabatier, Lamarre, and Armand (2009) which has proven that particularly educational sectors may benefit if children's identity is developed through contact and exposure with various linguistic landscape.
With the abovementioned study (Dagenais et al., 2009), consequently the purpose of this study is to identify the place of English in the linguistic schoolscape of DLSU-D. Moreover, this study will serve as a proof that the field of expertise or the department/college in an institution has a relation with the use of language such as monolingualism and bilingualism.
Statement of the problem
This study tried to answer the following questions: 1. What are the language preferences in the linguistic schoolscape of De La Salle University-Dasmariñas?
2. What are the common situational variables in the displays present in DLSUD?
3. What is the significant difference between college/s and language preferences on linguistic schoolscape?
Theoretical Framework
The theory that the researcher used in this study is the linguistic landscape theory. The concept of LL (linguistic landscape) was first drawn by Landry and Bourhis (1997) in their seminal work on ethnolinguistic vitality and signage in Canada as visibility of languages on objects that mark the public space in a given territory. Moreover, the researcher also took advantage of the method in schoolscape research focusing on categorization of establishment (based on Cenoz and Gorter 2006).
The notion of linguistic landscape as defined by Landry and Bourhis (1997) is the language of public road signs, advertising billboards, street names, places names, commercial shop signs and public signs on government buildings combines to form the linguistic landscape of a given territory, region, or urban agglomeration. According to Gorter (2006), the study on LL is concerned with 'the use of language in its written form in public sphere'.
Moreover, the researcher also used the proposed model of language planning and policy on linguistic landscape by Blommaert, Collins & Slembrouck (2005a). In here, it was seen that linguistic landscape is dependent on the space and environment, most significantly, to its physical aspect and semiotic aspect. Once it is already understood, it will take an impact on more effective communication. This simply means, that the languages posted in our environment, whatever setting it is, could shape the linguistic norms in a community.
Lastly, this study aims to support or reject the hypothesis that each college have equally utilized both monolingualism and bilingualism as their language preferences in linguistic schoolscape.
Research Design
The study utilized the descriptive, qualitative method and quantitative analysis of data research since it aims to present a study on the announcement and signages in English to DLSU-D. In this study, the researcher has used qualitative and quantitative research. Qualitative research is a situated activity that locates the observer in the real world (Denzin & Lincoln, 2005). In here, it studies things in their natural spaces, taking into account the current usage of language in different buildings where varieties of field of expertise are offered. Basically, qualitative researchers are interested in understanding the meaning people have constructed, that is how people makes sense of their world and the experiences they have in the world (Merriam, 2009). Quantitative research, on the other hand, are research methods dealing with numbers and anything that is measurable in a systematic way of investigation of phenomena and their relationships. It is used to answer questions on relationships within measurable variables with an intention to explain, predict and control phenomena (Leedy, 1993, p.87). The statistical data presented in this study was treated and interpreted quantitatively using the chi-square. The Chi-square test is intended to test how likely it is that an observed distribution is due to chance. It is also called a "goodness of fit" statistic, because it measures how well the observed distribution of data fits with the distribution that is expected if the variables are independent.
A Chi-square test is designed to analyze categorical data. That means that the data has been counted and divided into categories. It will not work with parametric or continuous data (such as height in inches). In this study, it was used to reject or support the null hypothesis.
Research Locale, Population and Sampling Technique
The venues that the researcher used for this study is De La Salle University -Dasmariñas. The said institution is one of the 17 La Salle schools which is considered as most competitive tertiary schools in the South and known as "Cavite's Premier University". In this school, the researcher looked for different colleges and departments were varieties of signages about announcements are posted such as at their bulletin boards, announcements posted on doors, and some other materials prepared by the administration of each college building. Moreover, there is a consideration on the diversity of the nationalities in the said institution as it affects the language preferences which is also a focus of this study. Table 1.1 presents the total population of foreign students in DLSUD for the 1 st and 2 nd semester including their nationalities which varies also and may give relevant effects to the linguistic schoolscape. This would also serve as a tool to determine the language preference of a school.
Data Gathering Procedure
The corpus of this study includes a complete inventory of the linguistic landscape of different departments in the institutions, based on the example of the study on the use of English in Keren Kayemet Street in Jerusalem, Israel (Rosenbaum et al., 1977). The analysis in LL study relies on photography and visual analysis in which the core data gathering method is to engage in photography that thoroughly document defined spaces in the institutions' buildings (Akindelle, 2011, p.5 Rosenbaum et al. (1977), the approach of the researcher involved taking digital pictures of all texts on each department building. For the statistical treatment of data, to prove that each college equally utilized both bilingualism and monolingualism as their language preferences in linguistic schoolscape, the researcher used the chi-square test.
Results
This chapter presents the results of the statistics of the signages and announcements with their common language preferences respectively and its relation to the research locale and population.
Producer of signs
Most of the signs examined were in bottom-up 221 (55%), which illustrates that majority of the signs examined were made by the faculty, students and parents combined Only 185 (45%) were made by the administrators and administrative staff. .1 gives us the idea as to which college belongs the higher numbers of signages made the teachers, students and parents as well as which college has a higher number of signages made by the administration and administrative staff. Majority, it is the teachers, students and parents turned to be the main makers of the signages in the place. The bottom-up signs are basically limited to the signages in trash-bins as well as some announcements regarding the upcoming graduation and some other policies that are in need to be followed even the school year has almost ending.
Field refers to what language is used to talk about; the tenor refers to the role relationships between the interactants; and mode indicates the role language is playing in the intersection (Magno, 2017). The field covers a wide range of texts and content in varied formats and styles, that provides announcements about contests, competitions, scholarships, forum, summit, conferences, preparations in case of calamities and emergencies, policies that must be followed, job-opportunities, recognition of exemplary students and faculty, program offerings and guidelines in which each college have set depending on the culture and norms they practice.
In terms of mode, the signages posted are purely written with creative designs and format followed.
• Statistical treatment of data
Using chi-square test
A Chi-square test is designed to analyze categorical data. That means that the data has been counted and divided into categories. It will not work with parametric or continuous data (such as height in inches). Table 5 shows the tabulated results to get the chisquare value. To get this, it is needed to obtain the expected frequency for each cell then construct a summary table in which, for each cell, you report the observed and expected frequencies, subtract the expected from the observed frequency, square this difference, divide by the expected frequency, and sum these quotients to obtain the chi-square value.
As indicated in
Step 5, to reject the null hypothesis at the 0.5 significance level with 1 degree of freedom, our calculated chi-square value would have to be larger than 12.59. Because we obtained a chi-square value of 26.55, we can reject the null hypothesis and accept the research hypothesis. Our results suggest that there is significant difference in each colleges' language preferences on linguistic schoolscape.
III. Discussion
The announcements and signages posted in the seven colleges of DLSUD were majorly in monolingual English. Only a few percentage were seen with bilingual language preference. This simply tells us that as an institution in an urban area, especially those located in Southern Tagalog Region near NCR, commonly uses both English and Filipino languages. The results will tell us that DLSUD is far from being multilingual in line with the community's language preference. Agreeably, English was also used as a sign of prestige as students, faculty and administrators preferred to use this for information dissemination. Administrative staff used bilingualism just for a very minimal chance (i.e. trash bins, SWC). Hence, it supports Reyes' claim that it seems rather apt to call the linguistic schoolscape as essentially "unilingual" or "monolingual". There was not any poster that showcases other dialects unlike with the study conducted by Astillero (2011) in a rural area in Sorsogon. In contrast with Reyes' (2015) claim that train stations in urban areas neglected the bilingual policy in the Philippines, the institution of this recent study was not in scope of that. The DepEd order Order No. 52, s. 1987 scopes all levels in the K-12 program which means, college or university level are not obliged to follow. Commission on Higher Education evenly supported this but not as critical as what presented in the former but it supports the norms in the linguistic schoolscape of the institution due to its independence. The policy just focused on the implementation of both English and Filipino languages in pedagogy which is not anymore, a scope of this study. Each college does not have equal or similar language preference. They may have diversity in their professional endeavors, language use, and cultural background but it does not reveal that it has an impact on their language preferences.
Announcements are the most important post identified due to its numbers posted in every college. In fact, most of the signages are addressed to and for the students. Based on the interview conducted, the posting processes takes long procedure before its approval. The results also show that English used to address the students straightforward and formal while Filipino is more informal and usually appeal to the emotions. Some other languages in the study like Latin, Japanese and Thai were just used to promote organizations, to post results of student-exchange and to tell historical background of the buildings and hallways. These results suggest that despite the promotion of bilingual and multilingual policy in education, the school stakeholders have clearly shown high preference to the English language.
These results are similar with the findings of Astiller (2011), Magno (2015) and Reyes (2015) stating that English dominated the linguistic landscape of the two stations and very likely in many parts of the Philippines, evidently there is no "active competition" between English and Filipino in the linguistic landscape of the country. Hence, instead of being bilingual, it seems rather apt to call the LL as essentially "unilingual".
The null hypothesis investigated in the study was to see if each college have equally utilized both bilingualism and monolingualism as their language preferences in linguistic schoolscape. As per the result, to reject the null hypothesis at the 0.5 significance level with 1 degree of freedom, our calculated chi-square value would have to be larger than 12.59. Because we obtained a chi-square value of 26.55, we can reject the null hypothesis and accept the research hypothesis. Our results suggest that there is significant difference in each colleges' language preferences on linguistic schoolscape.
IV. Conclusion and Recommendation
English dominated the linguistic schoolscape in DLSUD. Evidently, there is no competition between English and Filipino which has also been shown in previous studies. The situation is not only a mockery of the multilingual reality but also an aberration of the country's bilingual policy in a much broader sense (Reyes, 2015).
Though it may appear that the signages posted are "fairly" distributed for there are few spaces for bilingual languages in the linguistic schoolscape, still, the findings show that the general provision of the institution was called to use English as language of the majority, whether coming form the administration, administrative staff and other stakeholders. Moreover, each college have shown their language preferences independently without taking into account what languages were used in the bulletin boards of the other colleges.
It was also unfortunate to see some bulletin boards especially in CEAT without any content and just left alone plainly. The chance of disseminating information was not maximized and utilized. It may be better if all the administrative staff of each college will monitor how this bulletin boards were used.
Lastly, it was shown in the previous studies that considering the presence of bilingual and multilingual policy in education, still, English was mostly preferred. How can we protect the local languages which mirror the local identity of Filipinos if even the higher education institutions are not duly presenting it? |
<reponame>divljiboy/AndroidChattApp<gh_stars>0
package eu.execom.chatapplicationspring2017.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v7.app.AppCompatActivity;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import eu.execom.chatapplicationspring2017.eventbus.OttoBus;
/**
* Created by Home on 5/20/2017.
*/
@EActivity
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bus.register(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
bus.unregister(this);
}
@Bean
OttoBus bus;
}
|
ADVERTISEMENTS
Share with:
Online gambling industry is facing a big problem these days – players are losing their trust in online casinos because of the fear being scammed. When a player enters the digital gambling world he can not be sure that his odds are not rigged and that the outcome of the game is actually random. Everyone needs to know whether they are just having a bad day and bad luck or casino saw a big bet and decided to give a low card on purpose.
advertisement
Not so long time ago, three guys were faced with this problem and they decided to do something about it – gather a team and create the first decentralised Ethereum smart contract-based casino which offers a 0% house edge and solves the online gambling transparency question once and for all – Edgeless. Thanks to Ethereum smart contracts everything what is happening inside the casino will be easy accessed by anyone, so that all the paranoid people can be 100% sure that no one is trying to scam them.
The most important thing when it comes to fairness in any kind of online game is the randomness of numbers/outcomes. In order words – when you roll the dice – you don’t know whether the outcome is actually random (just like when you roll the dice in real life) or is it programmed to make you lose your bet. The list of casinos that got caught cheating in many ways, including rigging the outcome, is huge. This mechanism is pretty simple and that is why it is easily rigged. Online casino creates a random number using combination of casino’s number and client’s number. It blends 2 numbers and provides random outcome.
Idea behind that is: casino can rigg own number, but they would not be able to rigg client’s number and outcome will random, therefore casino would not able to cheat. But there is still three ways to do it:
Casino can easily influence client’s number assigning it on their own (that’s the case in most casinos, because an average player is not going to type and give random number before every gamble round – even if they have this option) Client enters number once and he is not changing it. Casino can identify it and use that information and adjust own number. Casino can delay own number and provided it to the ‘bender’ once visitor sent his. Then casino can adjust own number to client’s.
If the online casino which is based on smart contracts would try to rig the odds, it would be immediately spotted.
Moreover, 0% house edge can sound a bit crazy, but in reality even with 0% house edge, a player because of its imperfect play, gives around 0,83% to the casino – this was calculated by a former Nevada Gaming Control agent and professional card counter Bill Zender.
An average player does not play ‘the perfect game’ therefore, in the long run the casino takes a profit from his mistakes. An analogy can be taken from poker. A new player is playing against a Pro. Both have equal probability conditions – 50% vs. 50%. However, the Pro player makes better choices and the new player makes bad decisions, and in the long run, the Pro wins. 0% edge card games will be a primary marketing tool to attract players, but additionally, the casino will make profit from sports betting. In this area, the casino will earn 4% from all money wagered.
First there was online fiat money gambling houses, then we got Bitcoin casinos and now – the new era of casinos are about to begin. Decentralized, transparent and 0% edge casino is about to be launched.
Edgeless decided to raise an initial capital through Initial Coin Offering (ICO). Developers distribute a percentage of the initial coin supply among the early supporters and backers. Each one who will invest in Edgeless will be able to get his cut from 40% of profit which will be sent each month through smart contracts. According to Edgeless team, in 2018, the return of investment will be – 14.54%.
The money that is raised is usually spent on the future development of Edgeless casino and its games.
Their crowdfunding campaign will start on 16th of February 2017, 3:00 pm GMT and their goal is to raise 440 000 ETH by selling Edgeless tokens, the rate is 1 ETH = 1000 EDG. Then during next 6-8 months developed their first online game, 0% edge BlackJack, and set it live. In the future developments there is a plan to add more games to the package: 0% edge Video Poker, 0% edge Micro Limits Dice and Sports Betting. |
For performing couple Dannie and Sarah, it was an easy choice to find the perfect theatre to tie the knot in.
Over Thanksgiving weekend in 2014, Dannie and Sarah shared a quiet engagement. On a quiet Sunday night, the pair laid in bed, not looking forward to returning to work the next day. As they got comfortable into their pre-sleep snuggle, Sarah asked Dannie what her favourite part of their weekend together was. Dannie can’t remember what her answer was, but next asked Sarah what her favourite part was. Her response; “this part right here”, pulling a ring from under her pillow.
A few months later, Dannie also proposed. Another quiet affair, scooping up their recently adopted pooch and asking through the dog; “Hey Mum? Mama has a question for you. Will you marry her?”.
After enjoying the holidays together, they jumped into planning in February. Step one, venue hunting. They had a time frame in mind, one as close to Dannie’s mothers birthday as they could swing. The set three different appointments to see venues but, after looking at the first venue, they cancelled the other two. They had found something that was perfect.
Mayne Stage is a small theatre on the north side of Chicago with a restaurant in the front. Both Dannie and Sarah have a background in theatre, so it was a natural fit.
The couple are also amateur photographers so have plenty of opinions and ideas about what they wanted in a photographer and spent a lot of time looking up potential folk to work with. Once again, after meeting Johnny Knight, his experience in both weddings and theatre exceeded all their expectations.
Flowers were another detail the couple focused a lot of energy on. Sarah had scheduled a call with Flowers for Dreams. A local florist which donated a portion of their proceeds to a different charity every month. After seeing a preview of what they could create, Dannie and Sarah fell head over heels in love. An added bonus, the October charity benefited mental health, a cause dear to their hearts.
The rest of the details fell into place rather quickly. They asked their wedding party to be a part of the big day, went dress shopping and began DIY projects like their centre pieces and their guest book.
As wedding day dawned, rather than getting ready at a hotel or in a salon, the couple chose to host a brunch at their apartment and let everyone help each other get ready. They admit that while there was more planning and a bigger clean up ahead, it let everyone come together in a much more relaxed way and guaranteed everybody was fed before things started to get crazy. Dannie was set on having a salon experience so did sneak away from brunch for an hour and headed over to Goldplaited, a finishing salon in Lakeview
At the venue the couple split into separate dressing rooms to complete their wedding day preparation, getting Into their respective dresses.
They each had photographs in the upper and lower lobbies with their families, two dogs and bridal parties before the first look on the staircase. Sarah wore an A-line tulle dress with a chapel train, a sweetheart neckline and custom-made lace illusion necklace. Dannie chose a Vera Wang mermaid style tulle gown with ruched bodice and rosettes in the skirt.
Soon enough, it was time for the ceremony. The stage of the theatre was set up with a staircase coming off the double-wide aisle so the couple could walk down together with their Dads. Their celebrant was a long time friend of Dannie’s, and the ceremony included two monologues from ‘Loves Labours Lost’ and a children’s book titled ‘Love Monster’. Sarah’s sibling, Dima, played a piece on the viola.
At the end of the ceremony, Sarah smashed a glass I honour of her Jewish heritage, and the pair emerged into the bar for cocktail hour.
Dannie made an announcement, asking everyone to cheers, and the pair gave their guests a big kiss. Then, Dannie informed guests that it was the last freebie and from now on, kisses would cost money. The pair had chosen to donate this money to their favourite animal shelter, PAWS Chicago. Through the night they made special requests, trading donations for high-five kisses, arm wrestle kisses and even a dance off.
As the night came to a close, Dannie and Sarah called themselves a Lyft (Uber) and went home to their puppies and their own bed.
Exhausted and thrilled, they slept. Married at last.
Photography by Johnny Knight Photography (Chicago) |
#!/usr/bin/env python
# -*- mode: python; py-indent-offset: 4; py-continuation-offset: 4 -*-
"""
"""
import os
class EnvvarHelper(object):
"""
Envvar helper class. This can be used as a base class for specific environment
variables for set environments (i.e., Jenkins sets some standard envvars for its
jobs).
This class implements functions that are useful fetching or creating envvars.
"""
def __init__(self):
"""
Constructor.
"""
pass
def get_envvar_str(self, envvar_name, error_if_missing=False):
"""
Get the value of an environment variable if it exists and return
it as a string. If the envvar does not exist, return None.
Args:
envvar_name (str): The environment variable name.
error_if_missing (bool): If True then throw a KeyError if the envvar does not exist.
If False, we return None if the envvar is missing. Default: False
Returns:
The value of the envvar as a string if it exists.
If error_if_missing is false, we return `None` if the envvar is missing
or we throw a KeyError if it's missing.
Throws:
KeyError: If error_is_missing is True and the envvar does not exist.
"""
assert isinstance(envvar_name, str)
assert isinstance(error_if_missing, bool)
output = None
if envvar_name in os.environ:
output = str( os.environ[envvar_name] )
elif error_if_missing:
raise KeyError("ERROR: Missing required envvar '{}'".format(envvar_name))
return output
def get_or_create_if_missing(self, envvar_name, default_value=""):
"""
Attempt to retrieve an envvar but if it does not exist then set it with
a default value.
Args:
envvar_name (str) : The name of the envvar we're searching for.
default_value (str): The default value to set if the envvar doesn't exist.
Returns:
str value of the envvar that we either set or read.
"""
output = str(default_value)
try:
output = self.get_envvar_str(envvar_name, error_if_missing=True)
except KeyError:
os.environ[envvar_name] = str(default_value)
return output
|
// Helper Error for TypeScript situations where the programmer thinks they
// know better than TypeScript that some situation will never occur.
// The intention here is that the programmer does not expect a particular
// bit of code to happen, and so has not written careful error handling.
// If it does occur, at least there will be an error and we can figure out why.
// This is preferable to casting or disabling TypeScript altogether in order to
// avoid syntax errors.
// One common example is a regex, where if the regex matches then all of the
// (non-optional) regex groups will also be valid, but TypeScript doesn't know.
export class UnreachableCode extends Error {
constructor() {
super('This code shouldn\'t be reached');
}
}
|
import sys
A=raw_input()
B=raw_input()
G="GREATER"
L="LESS"
E="EQUAL"
if len(A) > len(B):
print G
sys.exit()
if len(A) < len(B):
print L
sys.exit()
for i in range(len(A)):
a = int(A[i])
b = int(B[i])
if a > b:
print G
sys.exit()
if a < b:
print L
sys.exit()
print E |
def act(self, state: Any, episode_num: int, env_id: int = 0):
outp = self.policy.act(state)
action_distr, value = outp["action_distribution"], outp["values"]
action = outp["action"]
self.last_values[env_id] = value.cpu().detach().numpy()
self.last_action_dist[env_id] = action_distr.cpu().detach().data.numpy()
return action |
<filename>include/ast/stmt/stmt.h
#ifndef STMT_H
#define STMT_H
#include "fwd.h"
class Stmt {
public:
class Visitor {
public:
virtual void VisitExprStmt(ExprStmt*) = 0;
virtual void VisitVarStmt(VarStmt*) = 0;
};
virtual void Accept(Stmt::Visitor*) = 0;
};
#endif /* STMT_H */
|
/**
* Created by hnakagawa on 14/09/09.
*/
@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class TaskExecutorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() {
}
@Test
public void run_shouldCallTasksRun() {
TaskExecutor<Integer, Integer> next = mock(TaskExecutor.class);
Promise<Integer, Integer> promise = mock(Promise.class);
when(promise.getState()).thenReturn(Promise.State.RUNNING);
when(promise.getTaskExecutor(2)).thenReturn((TaskExecutor)next);
Task<Integer, Integer> task = mock(Task.class);
TaskExecutor<Integer, Integer> executor = new TaskExecutor<Integer, Integer>(task, 1);
executor.setPromise(promise);
executor.run(0);
verify(task).run(0, next);
}
@Test
public void run_shouldCallPromisesYield() {
final Bundle bundle = new Bundle();
bundle.putString("a", "A");
Promise<Integer, Integer> promise = mock(Promise.class);
when(promise.getState()).thenReturn(Promise.State.RUNNING);
Task<Integer, Integer> nextTask = new Task<Integer, Integer>() {
@Override
public void run(Integer value, NextTask<Integer> next) {
next.yield(3, bundle);
}
};
TaskExecutor<Integer, Integer> nextExecutor = new TaskExecutor<Integer, Integer>(nextTask, 2);
nextExecutor.setPromise(promise);
when(promise.getTaskExecutor(2)).thenReturn((TaskExecutor)nextExecutor);
TaskExecutor<Integer, Integer> executor = new TaskExecutor<Integer, Integer>(nextTask, 1);
executor.setPromise(promise);
executor.run(0);
verify(promise).yield(3, bundle);
}
@Test
public void run_shouldCallPromisesFail() {
final Bundle bundle = new Bundle();
bundle.putString("a", "A");
final RuntimeException exp = new RuntimeException();
Promise<Integer, Integer> promise = mock(Promise.class);
when(promise.getState()).thenReturn(Promise.State.RUNNING);
Task<Integer, Integer> nextTask = new Task<Integer, Integer>() {
@Override
public void run(Integer value, NextTask<Integer> next) {
next.fail(bundle, exp);
}
};
TaskExecutor<Integer, Integer> nextExecutor = new TaskExecutor<Integer, Integer>(nextTask, 2);
nextExecutor.setPromise(promise);
when(promise.getTaskExecutor(2)).thenReturn((TaskExecutor)nextExecutor);
TaskExecutor<Integer, Integer> executor = new TaskExecutor<Integer, Integer>(nextTask, 1);
executor.setPromise(promise);
executor.run(0);
verify(promise).fail(bundle, exp);
}
@Test
public void run_shouldCallPromisesFailWithException() {
final RuntimeException exp = new RuntimeException();
Promise<Integer, Integer> promise = mock(Promise.class);
when(promise.getState()).thenReturn(Promise.State.RUNNING);
Task<Integer, Integer> nextTask = new Task<Integer, Integer>() {
@Override
public void run(Integer value, NextTask<Integer> next) {
throw exp;
}
};
TaskExecutor<Integer, Integer> nextExecutor = new TaskExecutor<Integer, Integer>(nextTask, 2);
nextExecutor.setPromise(promise);
when(promise.getTaskExecutor(2)).thenReturn((TaskExecutor)nextExecutor);
TaskExecutor<Integer, Integer> executor = new TaskExecutor<Integer, Integer>(nextTask, 1);
executor.setPromise(promise);
executor.run(0);
verify(promise).fail(null, exp);
}
} |
Effect of obesity and type 2 diabetes, and glucose ingestion on circulating spexin concentration in adolescents
Spexin is a novel peptide that has been reported to be down regulated in obese adults and children and in normoglycemic adults following glucose ingestion. Spexin may therefore have a role in metabolic regulation. The purpose of the current study was to determine the effect of obesity and type 2 diabetes (T2DM), and the effect of glucose ingestion on circulating spexin concentration in adolescents. Boys and girls (mean age 16 years old) classified as healthy normal weight (NW, n = 22), obese (Ob, n = 10), or obese with T2DM (n = 12) completed measurements of body composition, blood pressure, cardiorespiratory fitness, and blood concentrations of glucose, insulin, and lipids. The median fasting serum spexin concentration did not differ between groups (NW: 0.35; Ob: 0.38, T2DM: 0.34 ng/mL, respectively). In 10 NW participants who completed a standard oral glucose tolerance test, spexin concentration was unchanged at 30 and 120 minutes relative to the fasting baseline. Finally, spexin was not significantly correlated with any of the body composition, fitness, or blood biochemical measurements. These data do not support the proposed role of spexin as a metabolic regulator or biomarker of glucose control in adolescents. |
def cube_node_queue_fill(node: CubeNode, new_sounding: Sounding):
if node.n_queued == 0:
if Debug:
print('cube_node_queue_fill: queue is empty, adding depth and variance to queue')
node.queue = QueueList(new_sounding, None)
else:
insertion_index = None
for i in range(node.n_queued):
point = node.queue.get_item(i)
if new_sounding.depth > point.depth:
insertion_index = i + 1
else:
break
if insertion_index is not None:
if Debug:
print('cube_node_queue_fill: inserted, adding depth, variance to queue')
if insertion_index == 0:
node.queue = node.queue.prepend(new_sounding)
else:
node.queue.insert(new_sounding, insertion_index)
else:
if Debug:
print('cube_node_queue_fill: adding to beginning of queue, adding depth, variance to queue')
node.queue = node.queue.prepend(new_sounding)
node.n_queued = numbai64(node.n_queued + 1) |
Diminished Dose Minimally Invasive Radioguided Parathyroidectomy: A Case for Radioguidance
Minimally invasive radioguided parathyroidectomy (MIRP) has been established as an alternative to bilateral neck exploration (BNE) for primary hyperparathyroidism. We investigate whether a diminished dose of technetium-99m sestamibi gives similar results to the standard dose. One hundred one patients were offered MIRP or diminished-dose MIRP (ddMIRP). Patients received intravenous Tc-99m sestamibi at a dose of either 25 mCi 1.5 hours or 5 mCi 1 hour preoperatively. The procedure was terminated when the 20 per cent rule was satisfied. All tissue was confirmed to be parathyroid tissue by frozen section analysis. In addition, intraoperative parathyroid hormone levels were measured in a majority of patients. Patients who failed IOM underwent BNE. Frozen section analysis and intraoperative parathyroid hormone monitoring were also performed in the BNEs. Postoperatively, serum calcium levels were measured at 1 week and 6 months. Fifteen per cent of patients were male and 85 per cent were female. The median age was 63 years (range, 25–89 years). The first 58 patients had the standard dose of 25 mCi, whereas 43 patients had ddMIRP. Six patients (10%) failed intraoperative mapping in the MIRP group and were found to have single-gland disease. Five patients (12%) failed intraoperative mapping in the ddMIRP group. However, two patients were identified to have multigland disease making the true failure rate of intraoperative mapping 7 per cent (three patients). Median operative times for MIRP, ddMIRP, and BNE were 40 minutes, 46 minutes, and 105 minutes, respectively. The 20 per cent rule was satisfied in 96 per cent of patients undergoing MIRP and 98 per cent of patients undergoing ddMIRP. Frozen section analysis and intraoperative parathyroid hormone monitoring did not result in a change in management. Median follow up was 193 days and serum calcium levels at 6 months were normal. Diminished-dose MIRP is a feasible alternative to standard-dose MIRP without compromising surgical outcomes. |
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_UTILS_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_UTILS_H_
#include "tensorflow/core/common_runtime/gpu/gpu_id.h"
#include "tensorflow/core/common_runtime/gpu/gpu_id_manager.h"
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
#include "tensorflow/core/lib/gtl/int_type.h"
#include "tensorflow/core/platform/stream_executor.h"
namespace tensorflow {
namespace gpu = ::perftools::gputools;
// Utility methods for translation between Tensorflow GPU ids and CUDA GPU ids.
class GpuIdUtil {
public:
// Convenient methods for getting the associated executor given a TfGpuId or
// CudaGpuId.
static gpu::port::StatusOr<gpu::StreamExecutor*> ExecutorForCudaGpuId(
gpu::Platform* gpu_manager, CudaGpuId cuda_gpu_id) {
return gpu_manager->ExecutorForDevice(cuda_gpu_id.value());
}
static gpu::port::StatusOr<gpu::StreamExecutor*> ExecutorForCudaGpuId(
CudaGpuId cuda_gpu_id) {
return ExecutorForCudaGpuId(GPUMachineManager(), cuda_gpu_id);
}
static gpu::port::StatusOr<gpu::StreamExecutor*> ExecutorForTfGpuId(
TfGpuId tf_gpu_id) {
return ExecutorForCudaGpuId(GpuIdManager::TfToCudaGpuId(tf_gpu_id));
}
// Verify that the cuda_gpu_id associated with a TfGpuId is legitimate.
static void CheckValidTfGpuId(TfGpuId tf_gpu_id) {
const CudaGpuId cuda_gpu_id = GpuIdManager::TfToCudaGpuId(tf_gpu_id);
const int visible_device_count = GPUMachineManager()->VisibleDeviceCount();
CHECK_LT(cuda_gpu_id.value(), visible_device_count)
<< "cuda_gpu_id is outside discovered device range."
<< " TF GPU id: " << tf_gpu_id << " CUDA GPU id: " << cuda_gpu_id
<< " visible device count: " << visible_device_count;
}
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_UTILS_H_
|
#pragma once
// project header
#include "CreatePatch/HotPatcherSettingBase.h"
#include "HotPatcherLog.h"
#include "CreatePatch/HotPatcherContext.h"
#include "CreatePatch/TimeRecorder.h"
// engine header
#include "CoreMinimal.h"
#include "HotPatcherProxyBase.generated.h"
UCLASS()
class HOTPATCHEREDITOR_API UHotPatcherProxyBase : public UObject
{
public:
GENERATED_BODY()
FORCEINLINE virtual void SetProxySettings(FPatcherEntitySettingBase* InSetting)
{
Setting = InSetting;
}
virtual void Init(){};
virtual void Shutdown(){};
FORCEINLINE virtual bool DoExport(){return false;};
FORCEINLINE virtual FPatcherEntitySettingBase* GetSettingObject(){return Setting;};
public:
FExportPakProcess OnPaking;
FExportPakShowMsg OnShowMsg;
protected:
FPatcherEntitySettingBase* Setting;
};
|
/**
* Returns a <code>long</code> as a <code>byte</code> array of binary values.
*
* @param l the <code>long</code>
* @return a <code>byte</code> array
*/
public static byte[] asBytes(long l) {
long in = l;
byte[] out = new byte[64];
for (int j = 63; j > -1; j--) {
if ((in & 1) == 1) {
out[j] = '1';
}
else {
out[j] = '0';
}
in >>= 1;
}
return out;
} |
/**
* Checks if a person is vacant by checking against interviews from a person's list of interviews.
* If the person has interviews with overlapping time, return false.
*
* @param toSchedule interview to be scheduled for person.
*/
public boolean isVacantFor(Interview toSchedule) {
for (Interview interview : interviews) {
if (interview.hasOverLapWith(toSchedule)) {
return false;
}
}
return true;
} |
/**
* Flags in EKF_STATUS message
*/
public class ESTIMATOR_STATUS_FLAGS {
public static final int ESTIMATOR_ATTITUDE = 1; /* True if the attitude estimate is good | */
public static final int ESTIMATOR_VELOCITY_HORIZ = 2; /* True if the horizontal velocity estimate is good | */
public static final int ESTIMATOR_VELOCITY_VERT = 4; /* True if the vertical velocity estimate is good | */
public static final int ESTIMATOR_POS_HORIZ_REL = 8; /* True if the horizontal position (relative) estimate is good | */
public static final int ESTIMATOR_POS_HORIZ_ABS = 16; /* True if the horizontal position (absolute) estimate is good | */
public static final int ESTIMATOR_POS_VERT_ABS = 32; /* True if the vertical position (absolute) estimate is good | */
public static final int ESTIMATOR_POS_VERT_AGL = 64; /* True if the vertical position (above ground) estimate is good | */
public static final int ESTIMATOR_CONST_POS_MODE = 128; /* True if the EKF is in a constant position mode and is not using external measurements (eg GPS or optical flow) | */
public static final int ESTIMATOR_PRED_POS_HORIZ_REL = 256; /* True if the EKF has sufficient data to enter a mode that will provide a (relative) position estimate | */
public static final int ESTIMATOR_PRED_POS_HORIZ_ABS = 512; /* True if the EKF has sufficient data to enter a mode that will provide a (absolute) position estimate | */
public static final int ESTIMATOR_GPS_GLITCH = 1024; /* True if the EKF has detected a GPS glitch | */
public static final int ESTIMATOR_STATUS_FLAGS_ENUM_END = 1025; /* | */
} |
<filename>uebungen/0x0b/deepbutter.cpp
#include <condition_variable>
#include <iostream>
#include <thread>
std::mutex signal1;
std::mutex signal2;
void work_1();
void work_2();
// Mutex, lock, unlock, unique_lock
int main() {
// Starten Sie zwei Threads in main und lassen Sie sie sicher (!) in einen
// Wartezustand laufen.
signal1.lock();
signal2.lock();
std::thread thread1(work_1);
std::thread thread2(work_2);
// Signalisieren Sie aus main heraus dem ersten Thread, dass er weiterlaufen
// kann und warten auf das Ende der beiden Threads.
signal1.unlock();
thread1.join();
thread2.join();
// Die beiden Threads haben keine besonderen Aufgaben, es geht hier lediglich
// um eine wohldefinierte Reihenfolde der Abarbeitung. Verwenden Sie kein
// sleep, sondern lösen Sie das Problem durch die richtige Verwendung der
// Befehle.
};
void work_1() {
std::unique_lock<std::mutex> lock(signal1);
// Nach Erhalt des Signals im ersten Thread signalisieren dem zwieten Thread,
// dass er nun weiterlaufen kann.
signal2.unlock();
};
void work_2() { std::unique_lock<std::mutex> lock(signal2); }; |
import random
numbers=False
#αρχικά ελέγχω τις τιμές που δίνει ο χρ΄ηστης
while not numbers:
print ("δόστε τις διαστάσεις για τον ορθογώνιο πίνακα")
a=input("το πλάτος είναι :")
b=input("το ύψος είναι :")
try:
x=int(a)
y=int(b)
size=x*y
if x>=3 and y>0 and x != y:
numbers=True
#έλεγχος για τα 's' και 'o' για να είναι ίσα στο πλήθος
def chek(w,z):
r1=w.count("s")
r2=w.count("o")
for i in range(z):
if r1>r2:
w=w.replace("s","o",1)
r1=w.count("s")
r2=w.count("o")
elif r2>r1:
w=w.replace("o","s",1)
r1=w.count("s")
r2=w.count("o")
else:
r1=w.count("s")
r2=w.count("o")
k=w.split()
return k
total_score=[]
for f in range(10):
#δημιουργία του πίνακα
a=" "
for p in range(size):
grammata=["s","o"]
random.shuffle(grammata)
a=a+" "+grammata[0]+" "
l=chek(a,x)
score1=0
#οριζόντιος έλεγχος για sos
for i in range(y):
for j in range(x-2):
if l[j+(i*x)]=="s" and l[j+(i*x)+1]=="o" and l[j+(i*x)+2]=="s":
score1=score1+1
else:
score1=score1
#κάθετος έλεγχος για sos
for j in range(x*y-2*x):
if l[j]=="s" and l[j+x]=="o" and l[j+2*x]=="s":
score1=score1+1
else:
score1=score1
#διαγώνια προς τα δεξιά έλεγχος για sos
for i in range(y-2):
for j in range(x-2):
if l[j+(i*x)]=="s" and l[j+(i*x)+(x+1)]=="o" and l[j+(i*x)+2*(x+1)]=="s":
score1=score1+1
else:
score1=score1
#διαγώνια προς τα αριστερά έλεγχος για sos
for i in range(y-2):
for j in range(x-2):
if l[(i*x)+(x-1)-j]=="s" and l[(i*x)+2*(x-1)-j]=="o" and l[(i*x)+3*(x-1)-j]=="s":
score1=score1+1
else:
score1=score1
#αποθήκευση του score
total_score.append(score1)
#υπολογισμός και εκτύπωση το μέσου όρου απο τα score
t=sum(total_score)
l=len(total_score)
average=t/l
print("\nο μέσος όρος απο sos σε καθε γύρο είναι : ")
print(average)
elif x==y and x>=3 and y>0:
print("παρακαλώ δώστε πλάτος και ύψος ώστε να βγαίνει ο πίνακας ορθογώνιος\n")
elif x>=3:
print("παρακαλώ δώστε ύψος μεγαλύτερο απο το 0 !\n")
elif y>0:
print("παρακαλώ δώστε πλάτος μεγαλύτερο ή ισο του 3 !\n")
else:
print ("παρακαλώ δώστε πλάτος μεγαλύτερο ή ισο του 3 και ύψος μεγαλύτερο απο το 0 !!!\n")
except:
print ("παρακαλώ δώστε μόνο αριθμούς !!!\n")
|
/**
* This method discovers all translation tests within the <code>currentDirectory</code>, it travels down the
* directory structure looking for files that have a prefix of 'TranslationTest-'.
*/
private void discoverTests(final File currentDirectory)
{
try
{
final String[] files = currentDirectory.list();
if (files == null || files.length == 0)
{
if (logger.isDebugEnabled())
{
logger.debug("no files or directories found in directory '" + currentDirectory + '\'');
}
} else
{
for (String filename : files)
{
File file = new File(currentDirectory, filename);
if (StringUtils.trimToEmpty(file.getName()).startsWith(TEST_PREFIX))
{
final URL testUrl = file.toURI().toURL();
if (logger.isInfoEnabled())
{
logger.info("found translation test --> '" + testUrl + '\'');
}
TranslationTest test =
(TranslationTest) XmlObjectFactory.getInstance(TranslationTest.class).getObject(testUrl);
test.setUri(testUrl);
this.translationTests.put(
test.getTranslation(),
test);
} else if (file.isDirectory() && !IGNORED_DIRECTORIES.contains(file.getName()))
{
this.discoverTests(file);
}
}
}
}
catch (final Throwable throwable)
{
logger.error(throwable);
throw new TranslationTestDiscovererException(throwable);
}
} |
def move_data_to_calls(self, variant):
additional_call_info = {}
if self._should_copy_filter_to_calls():
additional_call_info[
bigquery_util.ColumnKeyConstants.FILTER] = variant.filters
if self._should_copy_quality_to_calls():
additional_call_info[
bigquery_util.ColumnKeyConstants.QUALITY] = variant.quality
for info_key, info_value in variant.info.items():
if self._should_move_info_key_to_calls(info_key):
additional_call_info[info_key] = info_value
for call in variant.calls:
call.info.update(additional_call_info) |
/**
* @author Samantha Whitt
* used for creating a wormhole on the screen
* example: show a wormhole at the left and/or right end of screen
*/
public class Wormhole {
private ImageView myWormhole;
/**
* constructor for wormhole that creates a new one
* example: Wormhole newWormhole = new Wormhole();
*/
public Wormhole(String side) {
Image wormhole_img = new Image(this.getClass().getClassLoader().getResourceAsStream(app.WORMHOLE_IMAGE));
myWormhole = new ImageView(wormhole_img);
if (side.equals("left")) {
myWormhole.setX(0);
myWormhole.setScaleX(-1);
} else if (side.equals("right")) {
myWormhole.setX(app.SCENE_WIDTH-getWidth());
}
myWormhole.setY(400);
}
/**
* used for adding to scene
* @return wormhole's ImageView
*/
public ImageView getImage() {
return myWormhole;
}
/**
* @return wormhole's ImageView width
*/
public double getWidth() {
return myWormhole.getBoundsInLocal().getWidth();
}
} |
n=int(input())
L=[1,1]+[0]*(n-1)
for k in range(2,n+1):
L[k]=L[k-1]+L[k-2]
nombre=[["o","O"][k+1 in L] for k in range(n)]
print("".join(nombre)) |
/**
* Parses yaml properties and turns them into regular Java properties. If the file does not
* exists, it returns null.
*
* @param file
* a yaml file
* @return a Java properties file reader
* @throws IOException
* @throws FileNotFoundException
*/
public static Properties build(final File file) throws FileNotFoundException, IOException
{
try (final Reader reader = Files.newBufferedReader(file.toPath()))
{
return build(reader);
}
} |
I got my package on Friday but finally got around to opening it this morning. There was a nice postcard from Tennessee with the sender writing on the back about the items she selected for me and why. Very thoughtful, and she mentions checking out my pinterest to see my interests which is a nice touch, and a reminder to me that I need to hang out there more. LOL
Inside my package is a cute makeup bag with some Essie Apricot Cuticle Oil, Physicians Formula Lip Gloss, 2 bottle of nail polish in various shades of purple (my favorite color) and Loreal Color Rich Lip Balm.
As a sweet bonus, there is a bag of chocolate..Godiva Chocolate. Because, like my gifter said..Its Chocolate.
You don't need another reason.
Thank you so much!! |
def check_restrictions(restrictions, element, keys, verbose):
params = OrderedDict(zip(keys, element))
valid = True
if callable(restrictions):
valid = restrictions(params)
else:
for restrict in restrictions:
try:
if not eval(replace_param_occurrences(restrict, params)):
valid = False
except ZeroDivisionError:
pass
if not valid and verbose:
print("skipping config", get_instance_string(params), "reason: config fails restriction")
return valid |
// SetPower sets the power to the speakers
func (h *Hub) SetPower(on bool) error {
current, err := h.Power()
if err != nil {
return err
}
if current == on {
return nil
}
onByte := 0x00
if on {
onByte = 0x01
}
msg := newControlMessage(append(cmdSetPower, byte(onByte)))
return h.connectAndSend(portControl, msg)
} |
Attitudes of German persons at risk for Huntington's disease toward predictive and prenatal testing.
Huntington's disease is an autosomal dominant neurodegenerative disorder characterized by involuntary movements, psychological deterioration and dementia. Indirect predictive testing by linkage analysis has been possible since 1983; direct predictive testing by detecting the instable CAG-repeat has been possible since 1993. Persons at risk were asked, by questionnaire, about their motivation and regarding attitude taking part in indirect and direct predictive and prenatal diagnostics. About half of the interrogated German persons at risk wish to undertake DNA analysis, whereas 32.7% do not want to take part in a direct predictive test. Motives for taking the test are the same as those mentioned in the literature (certainty of carrier status, decisions concerning marriage and further children, planning a career). Motives for not taking the test mostly involve psychological problems in coping with the test result. 45.7% wish to undergo a direct prenatal test (main cause: certainty of the gene status of the child), whereas 27% would not take this test (because of non-toleration of abortion). Only statistical trends could be seen between the intention to take the predictive or prenatal test and some social and demographic variables. The at-risk persons would not change their attitudes regarding indirect or direct predictive and prenatal DNA analysis; they seem to have a confirmed opinion about molecular genetics, mostly depending on familial and social background. |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#define ll long long
#define LiangJiaJun main
using namespace std;
long long A,B,n;
long long a[1000004];
int LiangJiaJun(){
scanf("%I64d%I64d%I64d",&A,&B,&n);
for(int i=0;i<=1000000;i++)a[i]=A+(i-1)*B;
for(int i=1;i<=n;i++){
long long l,t,m,p,z,y;
scanf("%I64d%I64d%I64d",&l,&t,&m);
if(a[(int)l]>t){
printf("-1\n");
continue;
}
p=l;z=l,y=t;long long ans=0;
while(z<=y){
long long mid=z+y>>1;
if(((2*A+(p+mid-2)*B)*(mid-p+1)<=2*m*t)&&(A+(mid-1)*B<=t))ans=mid,z=mid+1;
else y=mid-1;
}
printf("%I64d\n",ans);
}
return 0;
}
|
/**
* Created with IntelliJ IDEA.
* User: akashm
* Date: 6/10/13
* Time: 11:38 AM
* To change this template use File | Settings | File Templates.
*/
import java.util.*;
public class Main {
public static void main(String args[]) {
HashSet<Long> tprimes = new HashSet<Long>();
int max = (int) 1e6 + 10;
boolean[] isPrime = new boolean[max];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 0; i < max; i++)
if (isPrime[i]) {
tprimes.add(i * 1L * i);
for (int j = i + i; j < max; j += i)
isPrime[j] = false;
}
Scanner in = new Scanner(System.in);
for (int z = in.nextInt(); z > 0; z--)
System.out.println(tprimes.contains(in.nextLong()) ? "YES" : "NO");
}
}
|
/* Call im_convsub via arg vector.
*/
static int
convsub_vec( im_object *argv )
{
im_mask_object *mo = argv[2];
int xskip = *((int *) argv[3]);
int yskip = *((int *) argv[4]);
return( im_convsub( argv[0], argv[1], mo->mask, xskip, yskip ) );
} |
HENRICO COUNTY, Va. — Virginia made national headlines in 2008 when state lawmakers made it illegal for an adult to use his or her tongue while kissing a child. The so-called “French Kiss” law was signed by then Virginia Governor Tim Kaine.
Fast forward six years and it appears someone has been arrested — for the first time — for breaking that law.
Police arrested Erick Alezndro Hernandez Tellez, 21, of Henrico for sexual assaulting a 12-year-old “female acquaintance,” police said. Specifically Tellez was charged with violating Virginia Code 18.2-370.6, which states:
Any person 18 years of age or older who, with lascivious intent, kisses a child under the age of 13 on the mouth while knowingly and intentionally penetrating the mouth of such child with his tongue is guilty of a Class 1 misdemeanor.
Del. Riley Ingram (R – Chesterfield, Henrico, Prince George and Hopewell) sponsored the 2008 bill. He said he believed this was the first time anyone had been arrested for breaking the law he helped pass.
“The one about French kissing?” Del. Ingram replied when asked about it over the phone. “I don’t know of anyone whose been arrested for that.”
Requests were made with both the state and Henrico Police to confirm Del. Riley’s belief.
Del. Riley said he introduced the bill on behalf of a Henrico mother who was upset when a man French kissed her young daughter in a “daycare setting” and felt that person’s punishment was not appropriate for the situation, he recalled. |
<reponame>enigmampc/enigma-core<gh_stars>100-1000
use sgx_tseal::SgxSealedData;
use sgx_types::{sgx_attributes_t, sgx_sealed_data_t, sgx_status_t};
use sgx_types::marker::ContiguousMemory;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::string::*;
use std::untrusted::fs;
use std::untrusted::fs::{File, remove_file};
use common::errors_t::{EnclaveError, EnclaveError::*, EnclaveSystemError::*};
pub const SEAL_LOG_SIZE: usize = 2048;
#[derive(Copy, Clone, Default, Debug)]
pub struct SealedDocumentStorage<T: ?Sized> {
pub version: u32,
pub data: T,
}
unsafe impl<T> ContiguousMemory for SealedDocumentStorage<T> {}
impl<T> SealedDocumentStorage<T> where
T: Copy {
/// Safe seal
/// param: the_data : clear text to be sealed
/// param: sealed_log_out : the output of the sealed data
///
/// The flags are from here: https://github.com/intel/linux-sgx/blob/master/common/inc/sgx_attributes.h#L38
/// additional is a part of AES-GCM that you can authenticate data with the MAC without encrypting it.
pub fn seal(&self, sealed_log_out: &mut [u8; SEAL_LOG_SIZE]) -> Result<(), EnclaveError> {
let additional: [u8; 0] = [0_u8; 0];
let attribute_mask = sgx_attributes_t { flags: 0xffff_ffff_ffff_fff3, xfrm: 0 };
let sealed_data = SgxSealedData::<Self>::seal_data_ex(
sgx_types::SGX_KEYPOLICY_MRSIGNER, //key policy
attribute_mask,
0, //misc mask
&additional,
&self,
)?;
let sealed_log = sealed_log_out.as_mut_ptr();
let sealed_log_size: usize = SEAL_LOG_SIZE;
to_sealed_log(&sealed_data, sealed_log, sealed_log_size as u32);
Ok(())
}
/// Unseal sealed log
/// param: sealed_log_in : the encrypted blob
pub fn unseal(sealed_log_in: &mut [u8]) -> Result<Option<Self>, EnclaveError> {
let sealed_log_size: usize = SEAL_LOG_SIZE;
let sealed_log = sealed_log_in.as_mut_ptr();
let sealed_data = match from_sealed_log::<Self>(sealed_log, sealed_log_size as u32) {
Some(data) => data,
None => {
return Err(SystemError(OcallError { command: "unseal".to_string(), err: "No data in sealed log".to_string() }));
}
};
let unsealed_result = sealed_data.unseal_data();
match unsealed_result {
Ok(unsealed_data) => {
let udata = unsealed_data.get_decrypt_txt();
Ok(Some(*udata))
}
Err(err) => {
// TODO: Handle this. It can causes panic in Simulation Mode until deleting the file.
if err != sgx_status_t::SGX_ERROR_MAC_MISMATCH {
return Err(SystemError(OcallError { command: "unseal".to_string(), err: format!("{:?}", err) }));
}
Ok(None)
}
}
}
}
/// This casts sealed_log from *u8 to *sgx_sealed_data_t which aren't aligned the same way.
fn to_sealed_log<T: Copy + ContiguousMemory>(sealed_data: &SgxSealedData<T>, sealed_log: *mut u8,
sealed_log_size: u32, ) -> Option<*mut sgx_sealed_data_t> {
unsafe { sealed_data.to_raw_sealed_data_t(sealed_log as *mut sgx_sealed_data_t, sealed_log_size) }
}
// This casts a *sgx_sealed_data_t to *u8 which aren't aligned the same way.
fn from_sealed_log<'a, T: Copy + ContiguousMemory>(sealed_log: *mut u8, sealed_log_size: u32) -> Option<SgxSealedData<'a, T>> {
unsafe { SgxSealedData::<T>::from_raw_sealed_data_t(sealed_log as *mut sgx_sealed_data_t, sealed_log_size) }
}
/// Save new sealed document
pub fn save_sealed_document(path: &PathBuf, sealed_document: &[u8]) -> Result<(), EnclaveError> {
// TODO: handle error
let mut file = match File::create(path) {
Ok(opt) => opt,
Err(err) => {
return Err(SystemError(OcallError { command: "save_sealed_document".to_string(), err: format!("{:?}", err) }));
}
};
match file.write_all(&sealed_document) {
Ok(_) => debug_println!("Sealed document: {:?} written successfully.", path),
Err(err) => {
return Err(SystemError(OcallError { command: "sealed_document".to_string(), err: format!("{:?}", err) }));
}
}
Ok(())
}
/// Check if sealed document exists
pub fn is_document(path: &PathBuf) -> bool {
match fs::metadata(path) {
Ok(metadata) => metadata.is_file(),
Err(_) => false,
}
}
/// Load bytes of a sealed document in the provided mutable byte array
pub fn load_sealed_document(path: &PathBuf, sealed_document: &mut [u8]) -> Result<(), EnclaveError> {
let mut file = match File::open(path) {
Ok(opt) => opt,
Err(err) => {
return Err(SystemError(OcallError { command: "load_sealed_document".to_string(), err: format!("{:?}", err) }));
}
};
match file.read(sealed_document) {
Ok(_) => println!("Sealed document: {:?} loaded successfully.", path),
Err(err) => {
return Err(SystemError(OcallError { command: "load_sealed_document".to_string(), err: format!("{:?}", err) }));
}
};
Ok(())
}
//#[cfg(debug_assertions)]
pub mod tests {
use super::*;
//use std::untrusted::fs::*;
/* Test functions */
pub fn test_document_sealing_storage() {
// generate mock data
let doc: SealedDocumentStorage<[u8; 32]> = SealedDocumentStorage {
version: 0x1234,
data: [b'i'; 32],
};
// seal data
let mut sealed_log_in: [u8; SEAL_LOG_SIZE] = [0; SEAL_LOG_SIZE];
doc.seal(&mut sealed_log_in).expect("Unable to seal document");
// save sealed_log to file
let p = PathBuf::from("seal_test.sealed");
save_sealed_document(&p, &sealed_log_in).expect("Unable to save sealed document");
// load sealed_log from file
let mut sealed_log_out: [u8; SEAL_LOG_SIZE] = [0; SEAL_LOG_SIZE];
load_sealed_document(&p, &mut sealed_log_out).expect("Unable to load sealed document");
// unseal data
let unsealed_doc = SealedDocumentStorage::<[u8; 32]>::unseal(&mut sealed_log_out).expect("Unable to unseal document").unwrap();
// compare data
assert_eq!(doc.data, unsealed_doc.data);
// delete the file
let f = remove_file(&p);
assert!(f.is_ok());
}
}
|
// Returns true if the group has at least 4 digits and there are digits and dots
// ordered as 88:88
// pos: returns digit index of the first 8 in the 88:88 pattern if ret = true
bool DisplayDef::canShowTime( const uint8_t group, uint8_t& pos ) {
if ( group >= groupList.size() ) return false;
const DigitGroup& g = groupList[ group ];
int cntDigit1 = 0;
int cntDigit2 = 0;
bool foundDot = false;
uint8_t posTmp = 0;
std::for_each(g.digits.begin(), g.digits.end(),
[&cntDigit1,&cntDigit2,&foundDot,&posTmp](const Digit& d) {
if (foundDot) {
cntDigit2++;
if (cntDigit2 == 2) return;
}
else {
cntDigit1++;
if (d.hasDots) {
if (cntDigit1 >= 2) {
foundDot = true;
posTmp = cntDigit1 - 1;
}
else cntDigit1 = 0;
}
}
});
bool result = foundDot && cntDigit1 == 2 && cntDigit2 == 2;
if( result ) pos = posTmp;
return result;
} |
Vision-based traffic accident detection using matrix approximation
Vision-based traffic accident detection is a significant task in traffic video surveillance. In this paper, we propose a fast and effective approach to automatically detect traffic accident in a video. The key idea is to utilize low-rank matrix approximation based method. A critical observation that traffic accidents usually occur on road area and occupy a small part of image enlightens us the following research. Each frame is first divided into non-overlapping blocks associated with different weights based on the average velocity magnitude of blocks in the training time. The motion matrix of a video segmentation is then extracted. After using low-rank matrix approximation to associate normal traffic scenes with a set of motion subspaces, we identify traffic accident at the moment of the increase of approximation error. Experimental results on several surveillance videos demonstrate the effectiveness of our proposed method. |
<gh_stars>1-10
package assistant
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/gorilla/websocket"
"github.com/influxdata/telegraf/agent"
"github.com/influxdata/telegraf/internal"
)
/*
Assistant is a client to facilitate communications between Agent and Cloud.
*/
type Assistant struct {
config *AssistantConfig // Configuration for Assitant's conn to server
conn *websocket.Conn // Active websocket conn
running bool
agent *agent.Agent // Pointer to agent to issue commands
}
/*
AssistantConfig allows us to configure where to connect to and other params
for the agent.
*/
type AssistantConfig struct {
Host string
Path string
RetryInterval int
}
func NewAssistantConfig() *AssistantConfig {
return &AssistantConfig{
Host: "localhost:8080",
Path: "/assistant",
RetryInterval: 15,
}
}
// NewAssistant returns an Assistant for the given Config.
func NewAssistant(config *AssistantConfig, agent *agent.Agent) *Assistant {
return &Assistant{
config: config,
agent: agent,
}
}
type pluginInfo struct {
Name string
Type string
Config map[string]interface{}
UniqueId string
}
type requestType string
const (
GET_PLUGIN = requestType("GET_PLUGIN")
GET_PLUGIN_SCHEMA = requestType("GET_PLUGIN_SCHEMA")
UPDATE_PLUGIN = requestType("UPDATE_PLUGIN")
START_PLUGIN = requestType("START_PLUGIN")
STOP_PLUGIN = requestType("STOP_PLUGIN")
GET_RUNNING_PLUGINS = requestType("GET_RUNNING_PLUGINS")
GET_ALL_PLUGINS = requestType("GET_ALL_PLUGINS")
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
)
type request struct {
Operation requestType
UUID string
Plugin pluginInfo
}
type response struct {
Status string
UUID string
Data interface{}
}
func (a *Assistant) init(ctx context.Context) error {
token, exists := os.LookupEnv("INFLUX_TOKEN")
if !exists {
return fmt.Errorf("influx authorization token not found, please set in env")
}
header := http.Header{}
header.Add("Authorization", "Token "+token)
u := url.URL{Scheme: "ws", Host: a.config.Host, Path: a.config.Path}
log.Printf("D! [assistant] Attempting conn to [%s]", a.config.Host)
ws, _, err := websocket.DefaultDialer.Dial(u.String(), header)
for err != nil { // on error, retry conn again
log.Printf("E! [assistant] Failed to connect to [%s] due to: '%s'. Retrying in %ds... ",
a.config.Host, err, a.config.RetryInterval)
err = internal.SleepContext(ctx, time.Duration(a.config.RetryInterval)*time.Second)
if err != nil {
// Return because context was closed
return err
}
ws, _, err = websocket.DefaultDialer.Dial(u.String(), header)
}
a.conn = ws
log.Printf("D! [assistant] Successfully connected to %s", a.config.Host)
return nil
}
// Run starts the assistant listening to the server and handles and interrupts or closed connections
func (a *Assistant) Run(ctx context.Context) error {
err := a.init(ctx)
if err != nil {
log.Printf("E! [assistant] connection could not be established: %s", err.Error())
return err
}
a.running = true
go a.listen(ctx)
return nil
}
// listenToServer takes requests from the server and puts it in Requests.
func (a *Assistant) listen(ctx context.Context) {
defer a.conn.Close()
go a.shutdownOnContext(ctx)
for {
var req request
if err := a.conn.ReadJSON(&req); err != nil {
if !a.running {
log.Printf("I! [assistant] listener shutting down...")
return
}
log.Printf("E! [assistant] error while reading from server: %s", err)
// retrying a new websocket connection
err := a.init(ctx)
if err != nil {
log.Printf("E! [assistant] connection could not be re-established: %s", err)
return
}
err = a.conn.ReadJSON(&req)
if err != nil {
log.Printf("E! [assistant] re-established connection but could not read server request: %s", err)
return
}
}
res := a.handleRequest(ctx, &req)
if err := a.conn.WriteJSON(res); err != nil {
log.Printf("E! [assistant] Error while writing to server: %s", err)
a.conn.WriteJSON(response{FAILURE, req.UUID, "error marshalling config"})
}
}
}
func (a *Assistant) shutdownOnContext(ctx context.Context) {
<-ctx.Done()
a.running = false
a.conn.Close()
}
func (a *Assistant) handleRequest(ctx context.Context, req *request) response {
var resp interface{}
var err error
switch req.Operation {
case GET_PLUGIN:
resp, err = a.getPlugin(req)
case GET_PLUGIN_SCHEMA:
resp, err = a.getSchema(req)
case START_PLUGIN:
resp, err = a.startPlugin(ctx, req)
case STOP_PLUGIN:
resp, err = a.stopPlugin(req)
case UPDATE_PLUGIN:
resp, err = a.updatePlugin(req)
case GET_RUNNING_PLUGINS:
resp, err = a.getRunningPlugins(req)
case GET_ALL_PLUGINS:
resp, err = a.getAllPlugins(req)
default:
err = errors.New("invalid operation")
}
if err != nil {
return response{FAILURE, req.UUID, err.Error()}
}
return response{SUCCESS, req.UUID, resp}
}
// getPlugin returns the struct response containing config for a single plugin
func (a *Assistant) getPlugin(req *request) (interface{}, error) {
fmt.Print("D! [assistant] Received request: ", req.Operation, " for plugin ", req.Plugin.Name, "\n")
resp, err := a.agent.GetRunningPlugin(req.Plugin.UniqueId)
if err != nil {
return nil, err
}
return resp, nil
}
type pluginSchema struct {
Schema map[string]interface{}
Defaults map[string]interface{}
}
// getSchema returns the struct response containing config schema for a single plugin
func (a *Assistant) getSchema(req *request) (interface{}, error) {
fmt.Print("D! [assistant] Received request: ", req.Operation, " for plugin ", req.Plugin.Name, "\n")
var plugin interface{}
var err error
switch req.Plugin.Type {
case "INPUT":
plugin, err = a.agent.CreateInput(req.Plugin.Name)
case "OUTPUT":
plugin, err = a.agent.CreateOutput(req.Plugin.Name)
default:
err = fmt.Errorf("did not provide a valid plugin type")
}
if err != nil {
return nil, err
}
schema, err := a.agent.GetPluginTypes(plugin)
if err != nil {
return nil, err
}
defaults, err := a.agent.GetPluginValues(plugin)
if err != nil {
return nil, err
}
resp := pluginSchema{
Schema: schema,
Defaults: defaults,
}
return resp, nil
}
// startPlugin starts a single plugin
func (a *Assistant) startPlugin(ctx context.Context, req *request) (interface{}, error) {
fmt.Print("D! [assistant] Received request: ", req.Operation, " for plugin ", req.Plugin.Name, "\n")
var uid string
var err error
switch req.Plugin.Type {
case "INPUT":
uid, err = a.agent.StartInput(ctx, req.Plugin.Name)
case "OUTPUT":
uid, err = a.agent.StartOutput(ctx, req.Plugin.Name)
default:
err = fmt.Errorf("invalid plugin type")
}
if err != nil {
return nil, err
}
resp := map[string]string{
"id": uid,
}
return resp, nil
}
// updatePlugin updates a plugin with the config specified in request
func (a *Assistant) updatePlugin(req *request) (interface{}, error) {
fmt.Print("D! [assistant] Received request: ", req.Operation, " for plugin ", req.Plugin.UniqueId, "\n")
if req.Plugin.Config == nil {
return nil, errors.New("no configuration values provided")
}
var data interface{}
var err error
switch req.Plugin.Type {
case "INPUT":
data, err = a.agent.UpdateInputPlugin(req.Plugin.UniqueId, req.Plugin.Config)
case "OUTPUT":
data, err = a.agent.UpdateOutputPlugin(req.Plugin.UniqueId, req.Plugin.Config)
default:
err = fmt.Errorf("did not provide a valid plugin type")
}
if err != nil {
return nil, err
}
return data, nil
}
// stopPlugin stops a single plugin given a request
func (a *Assistant) stopPlugin(req *request) (interface{}, error) {
fmt.Print("D! [assistant] Received request: ", req.Operation, " for plugin ", req.Plugin.Name, "\n")
var err error
switch req.Plugin.Type {
case "INPUT":
err = a.agent.StopInputPlugin(req.Plugin.UniqueId, true)
case "OUTPUT":
err = a.agent.StopOutputPlugin(req.Plugin.UniqueId, true)
default:
err = fmt.Errorf("did not provide a valid plugin type")
}
if err != nil {
return nil, err
}
return fmt.Sprintf("%s stopped", req.Plugin.UniqueId), nil
}
type runningPlugins struct {
Inputs []map[string]string
Outputs []map[string]string
}
// getRunningPlugins returns an object with all running plugins
func (assistant *Assistant) getRunningPlugins(req *request) (interface{}, error) {
runningPlugins := runningPlugins{
Inputs: assistant.agent.GetRunningInputPlugins(),
Outputs: assistant.agent.GetRunningOutputPlugins(),
}
return runningPlugins, nil
}
type availablePlugins struct {
Inputs []string
Outputs []string
}
// getAllPlugins returns an object with the names of all available plugins
func (assistant *Assistant) getAllPlugins(req *request) (interface{}, error) {
availablePlugins := availablePlugins{
Inputs: agent.GetAllInputPlugins(),
Outputs: agent.GetAllOutputPlugins(),
}
return availablePlugins, nil
}
|
def macro(self, template, macro_name):
if asbool(self.request.registry.settings.get('reload_templates')):
return get_renderer(template).implementation().macros[macro_name]
else:
macro_path = template + '|' + macro_name
macro = self.macro_cache.get(macro_path)
if not macro:
self.macro_cache[macro_path] = macro = \
get_renderer(template).implementation().macros[macro_name]
return macro |
/**
* Created by Eric R. Campbell on 12/30/2015.
*/
public class Player {
private PlayerUUID playerId;
private Username username;
public Player(String username) {
playerId = new PlayerUUID();
this.username = new Username(username);
}
public Player() {
playerId = new PlayerUUID();
}
public boolean idMatch(PlayerUUID playerUUID) {
return playerUUID == playerId ? true : false;
}
public PlayerUUID getPlayerId() {
return playerId;
}
/*
* Acts as a wrapper class for UUID to provide additional security...
*/
public class PlayerUUID {
private UUID id;
public PlayerUUID() {
id = UUID.randomUUID();
}
public UUID getId() {
return id;
}
}
public class Username {
private String user;
public Username(String s) {
user = s;
}
public String getUsername() {
return user;
}
}
} |
<filename>epygi/generated.go<gh_stars>1-10
// Code generated by radius-dict-gen. DO NOT EDIT.
package epygi
import (
"strconv"
"layeh.com/radius"
"layeh.com/radius/rfc2865"
)
const (
_Epygi_VendorID = 16459
)
func _Epygi_AddVendor(p *radius.Packet, typ byte, attr radius.Attribute) (err error) {
var vsa radius.Attribute
vendor := make(radius.Attribute, 2+len(attr))
vendor[0] = typ
vendor[1] = byte(len(vendor))
copy(vendor[2:], attr)
vsa, err = radius.NewVendorSpecific(_Epygi_VendorID, vendor)
if err != nil {
return
}
p.Add(rfc2865.VendorSpecific_Type, vsa)
return
}
func _Epygi_GetsVendor(p *radius.Packet, typ byte) (values []radius.Attribute) {
for _, avp := range p.Attributes {
if avp.Type != rfc2865.VendorSpecific_Type {
continue
}
attr := avp.Attribute
vendorID, vsa, err := radius.VendorSpecific(attr)
if err != nil || vendorID != _Epygi_VendorID {
continue
}
for len(vsa) >= 3 {
vsaTyp, vsaLen := vsa[0], vsa[1]
if int(vsaLen) > len(vsa) || vsaLen < 3 {
break
}
if vsaTyp == typ {
values = append(values, vsa[2:int(vsaLen)])
}
vsa = vsa[int(vsaLen):]
}
}
return
}
func _Epygi_LookupVendor(p *radius.Packet, typ byte) (attr radius.Attribute, ok bool) {
for _, avp := range p.Attributes {
if avp.Type != rfc2865.VendorSpecific_Type {
continue
}
attr := avp.Attribute
vendorID, vsa, err := radius.VendorSpecific(attr)
if err != nil || vendorID != _Epygi_VendorID {
continue
}
for len(vsa) >= 3 {
vsaTyp, vsaLen := vsa[0], vsa[1]
if int(vsaLen) > len(vsa) || vsaLen < 3 {
break
}
if vsaTyp == typ {
return vsa[2:int(vsaLen)], true
}
vsa = vsa[int(vsaLen):]
}
}
return
}
func _Epygi_SetVendor(p *radius.Packet, typ byte, attr radius.Attribute) (err error) {
for i := 0; i < len(p.Attributes); {
avp := p.Attributes[i]
if avp.Type != rfc2865.VendorSpecific_Type {
i++
continue
}
vendorID, vsa, err := radius.VendorSpecific(avp.Attribute)
if err != nil || vendorID != _Epygi_VendorID {
i++
continue
}
for j := 0; len(vsa[j:]) >= 3; {
vsaTyp, vsaLen := vsa[0], vsa[1]
if int(vsaLen) > len(vsa[j:]) || vsaLen < 3 {
i++
break
}
if vsaTyp == typ {
vsa = append(vsa[:j], vsa[j+int(vsaLen):]...)
}
j += int(vsaLen)
}
if len(vsa) > 0 {
copy(avp.Attribute[4:], vsa)
i++
} else {
p.Attributes = append(p.Attributes[:i], p.Attributes[i+i:]...)
}
}
return _Epygi_AddVendor(p, typ, attr)
}
func _Epygi_DelVendor(p *radius.Packet, typ byte) {
vsaLoop:
for i := 0; i < len(p.Attributes); {
avp := p.Attributes[i]
if avp.Type != rfc2865.VendorSpecific_Type {
i++
continue
}
vendorID, vsa, err := radius.VendorSpecific(avp.Attribute)
if err != nil || vendorID != _Epygi_VendorID {
i++
continue
}
offset := 0
for len(vsa[offset:]) >= 3 {
vsaTyp, vsaLen := vsa[offset], vsa[offset+1]
if int(vsaLen) > len(vsa) || vsaLen < 3 {
continue vsaLoop
}
if vsaTyp == typ {
copy(vsa[offset:], vsa[offset+int(vsaLen):])
vsa = vsa[:len(vsa)-int(vsaLen)]
} else {
offset += int(vsaLen)
}
}
if offset == 0 {
p.Attributes = append(p.Attributes[:i], p.Attributes[i+1:]...)
} else {
i++
}
}
return
}
func EpygiAVPair_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 1, a)
}
func EpygiAVPair_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 1, a)
}
func EpygiAVPair_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiAVPair_Lookup(p)
return
}
func EpygiAVPair_GetString(p *radius.Packet) (value string) {
value, _ = EpygiAVPair_LookupString(p)
return
}
func EpygiAVPair_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 1) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiAVPair_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 1) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiAVPair_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 1)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiAVPair_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 1)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiAVPair_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 1, a)
}
func EpygiAVPair_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 1, a)
}
func EpygiAVPair_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 1)
}
func EpygiNASPort_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 2, a)
}
func EpygiNASPort_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 2, a)
}
func EpygiNASPort_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiNASPort_Lookup(p)
return
}
func EpygiNASPort_GetString(p *radius.Packet) (value string) {
value, _ = EpygiNASPort_LookupString(p)
return
}
func EpygiNASPort_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 2) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiNASPort_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 2) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiNASPort_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 2)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiNASPort_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 2)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiNASPort_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 2, a)
}
func EpygiNASPort_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 2, a)
}
func EpygiNASPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 2)
}
func EpygiH323RemoteAddress_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 23, a)
}
func EpygiH323RemoteAddress_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 23, a)
}
func EpygiH323RemoteAddress_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323RemoteAddress_Lookup(p)
return
}
func EpygiH323RemoteAddress_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323RemoteAddress_LookupString(p)
return
}
func EpygiH323RemoteAddress_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 23) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RemoteAddress_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 23) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RemoteAddress_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 23)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323RemoteAddress_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 23)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323RemoteAddress_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 23, a)
}
func EpygiH323RemoteAddress_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 23, a)
}
func EpygiH323RemoteAddress_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 23)
}
func EpygiH323ConfID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 24, a)
}
func EpygiH323ConfID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 24, a)
}
func EpygiH323ConfID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323ConfID_Lookup(p)
return
}
func EpygiH323ConfID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323ConfID_LookupString(p)
return
}
func EpygiH323ConfID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 24) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ConfID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 24) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ConfID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 24)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323ConfID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 24)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323ConfID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 24, a)
}
func EpygiH323ConfID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 24, a)
}
func EpygiH323ConfID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 24)
}
func EpygiH323SetupTime_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 25, a)
}
func EpygiH323SetupTime_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 25, a)
}
func EpygiH323SetupTime_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323SetupTime_Lookup(p)
return
}
func EpygiH323SetupTime_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323SetupTime_LookupString(p)
return
}
func EpygiH323SetupTime_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 25) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323SetupTime_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 25) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323SetupTime_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 25)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323SetupTime_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 25)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323SetupTime_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 25, a)
}
func EpygiH323SetupTime_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 25, a)
}
func EpygiH323SetupTime_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 25)
}
func EpygiH323CallOrigin_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 26, a)
}
func EpygiH323CallOrigin_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 26, a)
}
func EpygiH323CallOrigin_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323CallOrigin_Lookup(p)
return
}
func EpygiH323CallOrigin_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323CallOrigin_LookupString(p)
return
}
func EpygiH323CallOrigin_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 26) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CallOrigin_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 26) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CallOrigin_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 26)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323CallOrigin_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 26)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323CallOrigin_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 26, a)
}
func EpygiH323CallOrigin_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 26, a)
}
func EpygiH323CallOrigin_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 26)
}
func EpygiH323CallType_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 27, a)
}
func EpygiH323CallType_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 27, a)
}
func EpygiH323CallType_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323CallType_Lookup(p)
return
}
func EpygiH323CallType_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323CallType_LookupString(p)
return
}
func EpygiH323CallType_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 27) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CallType_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 27) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CallType_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 27)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323CallType_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 27)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323CallType_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 27, a)
}
func EpygiH323CallType_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 27, a)
}
func EpygiH323CallType_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 27)
}
func EpygiH323ConnectTime_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 28, a)
}
func EpygiH323ConnectTime_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 28, a)
}
func EpygiH323ConnectTime_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323ConnectTime_Lookup(p)
return
}
func EpygiH323ConnectTime_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323ConnectTime_LookupString(p)
return
}
func EpygiH323ConnectTime_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 28) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ConnectTime_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 28) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ConnectTime_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 28)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323ConnectTime_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 28)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323ConnectTime_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 28, a)
}
func EpygiH323ConnectTime_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 28, a)
}
func EpygiH323ConnectTime_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 28)
}
func EpygiH323DisconnectTime_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 29, a)
}
func EpygiH323DisconnectTime_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 29, a)
}
func EpygiH323DisconnectTime_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323DisconnectTime_Lookup(p)
return
}
func EpygiH323DisconnectTime_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323DisconnectTime_LookupString(p)
return
}
func EpygiH323DisconnectTime_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 29) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323DisconnectTime_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 29) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323DisconnectTime_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 29)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323DisconnectTime_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 29)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323DisconnectTime_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 29, a)
}
func EpygiH323DisconnectTime_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 29, a)
}
func EpygiH323DisconnectTime_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 29)
}
func EpygiH323DisconnectCause_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 30, a)
}
func EpygiH323DisconnectCause_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 30, a)
}
func EpygiH323DisconnectCause_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323DisconnectCause_Lookup(p)
return
}
func EpygiH323DisconnectCause_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323DisconnectCause_LookupString(p)
return
}
func EpygiH323DisconnectCause_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 30) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323DisconnectCause_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 30) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323DisconnectCause_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 30)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323DisconnectCause_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 30)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323DisconnectCause_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 30, a)
}
func EpygiH323DisconnectCause_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 30, a)
}
func EpygiH323DisconnectCause_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 30)
}
func EpygiH323VoiceQuality_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 31, a)
}
func EpygiH323VoiceQuality_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 31, a)
}
func EpygiH323VoiceQuality_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323VoiceQuality_Lookup(p)
return
}
func EpygiH323VoiceQuality_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323VoiceQuality_LookupString(p)
return
}
func EpygiH323VoiceQuality_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 31) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323VoiceQuality_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 31) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323VoiceQuality_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 31)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323VoiceQuality_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 31)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323VoiceQuality_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 31, a)
}
func EpygiH323VoiceQuality_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 31, a)
}
func EpygiH323VoiceQuality_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 31)
}
func EpygiH323GwID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 33, a)
}
func EpygiH323GwID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 33, a)
}
func EpygiH323GwID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323GwID_Lookup(p)
return
}
func EpygiH323GwID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323GwID_LookupString(p)
return
}
func EpygiH323GwID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 33) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323GwID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 33) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323GwID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 33)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323GwID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 33)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323GwID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 33, a)
}
func EpygiH323GwID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 33, a)
}
func EpygiH323GwID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 33)
}
func EpygiH323IncomingConfID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 35, a)
}
func EpygiH323IncomingConfID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 35, a)
}
func EpygiH323IncomingConfID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323IncomingConfID_Lookup(p)
return
}
func EpygiH323IncomingConfID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323IncomingConfID_LookupString(p)
return
}
func EpygiH323IncomingConfID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 35) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323IncomingConfID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 35) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323IncomingConfID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 35)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323IncomingConfID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 35)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323IncomingConfID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 35, a)
}
func EpygiH323IncomingConfID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 35, a)
}
func EpygiH323IncomingConfID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 35)
}
func EpygiH323CreditAmount_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 101, a)
}
func EpygiH323CreditAmount_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 101, a)
}
func EpygiH323CreditAmount_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323CreditAmount_Lookup(p)
return
}
func EpygiH323CreditAmount_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323CreditAmount_LookupString(p)
return
}
func EpygiH323CreditAmount_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 101) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CreditAmount_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 101) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CreditAmount_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 101)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323CreditAmount_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 101)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323CreditAmount_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 101, a)
}
func EpygiH323CreditAmount_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 101, a)
}
func EpygiH323CreditAmount_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 101)
}
func EpygiH323CreditTime_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 102, a)
}
func EpygiH323CreditTime_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 102, a)
}
func EpygiH323CreditTime_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323CreditTime_Lookup(p)
return
}
func EpygiH323CreditTime_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323CreditTime_LookupString(p)
return
}
func EpygiH323CreditTime_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 102) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CreditTime_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 102) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323CreditTime_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 102)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323CreditTime_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 102)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323CreditTime_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 102, a)
}
func EpygiH323CreditTime_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 102, a)
}
func EpygiH323CreditTime_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 102)
}
func EpygiH323ReturnCode_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 103, a)
}
func EpygiH323ReturnCode_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 103, a)
}
func EpygiH323ReturnCode_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323ReturnCode_Lookup(p)
return
}
func EpygiH323ReturnCode_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323ReturnCode_LookupString(p)
return
}
func EpygiH323ReturnCode_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 103) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ReturnCode_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 103) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323ReturnCode_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 103)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323ReturnCode_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 103)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323ReturnCode_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 103, a)
}
func EpygiH323ReturnCode_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 103, a)
}
func EpygiH323ReturnCode_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 103)
}
func EpygiH323PromptID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 104, a)
}
func EpygiH323PromptID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 104, a)
}
func EpygiH323PromptID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323PromptID_Lookup(p)
return
}
func EpygiH323PromptID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323PromptID_LookupString(p)
return
}
func EpygiH323PromptID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 104) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323PromptID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 104) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323PromptID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 104)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323PromptID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 104)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323PromptID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 104, a)
}
func EpygiH323PromptID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 104, a)
}
func EpygiH323PromptID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 104)
}
func EpygiH323TimeAndDay_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 105, a)
}
func EpygiH323TimeAndDay_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 105, a)
}
func EpygiH323TimeAndDay_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323TimeAndDay_Lookup(p)
return
}
func EpygiH323TimeAndDay_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323TimeAndDay_LookupString(p)
return
}
func EpygiH323TimeAndDay_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 105) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323TimeAndDay_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 105) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323TimeAndDay_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 105)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323TimeAndDay_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 105)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323TimeAndDay_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 105, a)
}
func EpygiH323TimeAndDay_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 105, a)
}
func EpygiH323TimeAndDay_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 105)
}
func EpygiH323RedirectNumber_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 106, a)
}
func EpygiH323RedirectNumber_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 106, a)
}
func EpygiH323RedirectNumber_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323RedirectNumber_Lookup(p)
return
}
func EpygiH323RedirectNumber_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323RedirectNumber_LookupString(p)
return
}
func EpygiH323RedirectNumber_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 106) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RedirectNumber_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 106) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RedirectNumber_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 106)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323RedirectNumber_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 106)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323RedirectNumber_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 106, a)
}
func EpygiH323RedirectNumber_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 106, a)
}
func EpygiH323RedirectNumber_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 106)
}
func EpygiH323PreferredLang_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 107, a)
}
func EpygiH323PreferredLang_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 107, a)
}
func EpygiH323PreferredLang_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323PreferredLang_Lookup(p)
return
}
func EpygiH323PreferredLang_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323PreferredLang_LookupString(p)
return
}
func EpygiH323PreferredLang_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 107) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323PreferredLang_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 107) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323PreferredLang_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 107)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323PreferredLang_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 107)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323PreferredLang_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 107, a)
}
func EpygiH323PreferredLang_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 107, a)
}
func EpygiH323PreferredLang_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 107)
}
func EpygiH323RedirectIPAddress_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 108, a)
}
func EpygiH323RedirectIPAddress_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 108, a)
}
func EpygiH323RedirectIPAddress_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323RedirectIPAddress_Lookup(p)
return
}
func EpygiH323RedirectIPAddress_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323RedirectIPAddress_LookupString(p)
return
}
func EpygiH323RedirectIPAddress_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 108) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RedirectIPAddress_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 108) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323RedirectIPAddress_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 108)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323RedirectIPAddress_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 108)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323RedirectIPAddress_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 108, a)
}
func EpygiH323RedirectIPAddress_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 108, a)
}
func EpygiH323RedirectIPAddress_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 108)
}
func EpygiH323BillingModel_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 109, a)
}
func EpygiH323BillingModel_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 109, a)
}
func EpygiH323BillingModel_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323BillingModel_Lookup(p)
return
}
func EpygiH323BillingModel_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323BillingModel_LookupString(p)
return
}
func EpygiH323BillingModel_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 109) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323BillingModel_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 109) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323BillingModel_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 109)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323BillingModel_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 109)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323BillingModel_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 109, a)
}
func EpygiH323BillingModel_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 109, a)
}
func EpygiH323BillingModel_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 109)
}
func EpygiH323Currency_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 110, a)
}
func EpygiH323Currency_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 110, a)
}
func EpygiH323Currency_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiH323Currency_Lookup(p)
return
}
func EpygiH323Currency_GetString(p *radius.Packet) (value string) {
value, _ = EpygiH323Currency_LookupString(p)
return
}
func EpygiH323Currency_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 110) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323Currency_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 110) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiH323Currency_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 110)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiH323Currency_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 110)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiH323Currency_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 110, a)
}
func EpygiH323Currency_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 110, a)
}
func EpygiH323Currency_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 110)
}
func EpygiRegExpDate_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 150, a)
}
func EpygiRegExpDate_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 150, a)
}
func EpygiRegExpDate_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiRegExpDate_Lookup(p)
return
}
func EpygiRegExpDate_GetString(p *radius.Packet) (value string) {
value, _ = EpygiRegExpDate_LookupString(p)
return
}
func EpygiRegExpDate_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 150) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiRegExpDate_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 150) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiRegExpDate_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 150)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiRegExpDate_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 150)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiRegExpDate_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 150, a)
}
func EpygiRegExpDate_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 150, a)
}
func EpygiRegExpDate_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 150)
}
func EpygiFiadID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 151, a)
}
func EpygiFiadID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 151, a)
}
func EpygiFiadID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiFiadID_Lookup(p)
return
}
func EpygiFiadID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiFiadID_LookupString(p)
return
}
func EpygiFiadID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 151) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiFiadID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 151) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiFiadID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 151)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiFiadID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 151)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiFiadID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 151, a)
}
func EpygiFiadID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 151, a)
}
func EpygiFiadID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 151)
}
func EpygiPortID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 152, a)
}
func EpygiPortID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 152, a)
}
func EpygiPortID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiPortID_Lookup(p)
return
}
func EpygiPortID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiPortID_LookupString(p)
return
}
func EpygiPortID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 152) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiPortID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 152) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiPortID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 152)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiPortID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 152)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiPortID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 152, a)
}
func EpygiPortID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 152, a)
}
func EpygiPortID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 152)
}
func EpygiAccessType_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 153, a)
}
func EpygiAccessType_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 153, a)
}
func EpygiAccessType_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiAccessType_Lookup(p)
return
}
func EpygiAccessType_GetString(p *radius.Packet) (value string) {
value, _ = EpygiAccessType_LookupString(p)
return
}
func EpygiAccessType_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 153) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiAccessType_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 153) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiAccessType_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 153)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiAccessType_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 153)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiAccessType_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 153, a)
}
func EpygiAccessType_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 153, a)
}
func EpygiAccessType_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 153)
}
func EpygiCallInfo_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 154, a)
}
func EpygiCallInfo_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 154, a)
}
func EpygiCallInfo_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiCallInfo_Lookup(p)
return
}
func EpygiCallInfo_GetString(p *radius.Packet) (value string) {
value, _ = EpygiCallInfo_LookupString(p)
return
}
func EpygiCallInfo_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 154) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCallInfo_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 154) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCallInfo_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 154)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiCallInfo_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 154)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiCallInfo_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 154, a)
}
func EpygiCallInfo_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 154, a)
}
func EpygiCallInfo_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 154)
}
func EpygiOrigCallID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 170, a)
}
func EpygiOrigCallID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 170, a)
}
func EpygiOrigCallID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiOrigCallID_Lookup(p)
return
}
func EpygiOrigCallID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiOrigCallID_LookupString(p)
return
}
func EpygiOrigCallID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 170) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiOrigCallID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 170) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiOrigCallID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 170)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiOrigCallID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 170)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiOrigCallID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 170, a)
}
func EpygiOrigCallID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 170, a)
}
func EpygiOrigCallID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 170)
}
func EpygiParentCallID_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 171, a)
}
func EpygiParentCallID_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 171, a)
}
func EpygiParentCallID_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiParentCallID_Lookup(p)
return
}
func EpygiParentCallID_GetString(p *radius.Packet) (value string) {
value, _ = EpygiParentCallID_LookupString(p)
return
}
func EpygiParentCallID_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 171) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiParentCallID_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 171) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiParentCallID_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 171)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiParentCallID_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 171)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiParentCallID_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 171, a)
}
func EpygiParentCallID_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 171, a)
}
func EpygiParentCallID_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 171)
}
type EpygiCallType uint32
const (
EpygiCallType_Value_Internal EpygiCallType = 0
EpygiCallType_Value_SIP EpygiCallType = 1
EpygiCallType_Value_H323 EpygiCallType = 2
EpygiCallType_Value_FXO EpygiCallType = 3
EpygiCallType_Value_T1E1CAS EpygiCallType = 4
EpygiCallType_Value_T1E1CCS EpygiCallType = 5
EpygiCallType_Value_ISDNPRI EpygiCallType = 6
)
var EpygiCallType_Strings = map[EpygiCallType]string{
EpygiCallType_Value_Internal: "Internal",
EpygiCallType_Value_SIP: "SIP",
EpygiCallType_Value_H323: "H.323",
EpygiCallType_Value_FXO: "FXO",
EpygiCallType_Value_T1E1CAS: "T1-E1-CAS",
EpygiCallType_Value_T1E1CCS: "T1-E1-CCS",
EpygiCallType_Value_ISDNPRI: "ISDN-PRI",
}
func (a EpygiCallType) String() string {
if str, ok := EpygiCallType_Strings[a]; ok {
return str
}
return "EpygiCallType(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiCallType_Add(p *radius.Packet, value EpygiCallType) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 172, a)
}
func EpygiCallType_Get(p *radius.Packet) (value EpygiCallType) {
value, _ = EpygiCallType_Lookup(p)
return
}
func EpygiCallType_Gets(p *radius.Packet) (values []EpygiCallType, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 172) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiCallType(i))
}
return
}
func EpygiCallType_Lookup(p *radius.Packet) (value EpygiCallType, err error) {
a, ok := _Epygi_LookupVendor(p, 172)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiCallType(i)
return
}
func EpygiCallType_Set(p *radius.Packet, value EpygiCallType) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 172, a)
}
func EpygiCallType_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 172)
}
func EpygiDeviceName_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 173, a)
}
func EpygiDeviceName_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 173, a)
}
func EpygiDeviceName_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiDeviceName_Lookup(p)
return
}
func EpygiDeviceName_GetString(p *radius.Packet) (value string) {
value, _ = EpygiDeviceName_LookupString(p)
return
}
func EpygiDeviceName_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 173) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiDeviceName_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 173) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiDeviceName_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 173)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiDeviceName_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 173)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiDeviceName_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 173, a)
}
func EpygiDeviceName_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 173, a)
}
func EpygiDeviceName_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 173)
}
type EpygiInterfaceName uint32
const (
EpygiInterfaceName_Value_Ethernet EpygiInterfaceName = 0
EpygiInterfaceName_Value_FXO EpygiInterfaceName = 1
EpygiInterfaceName_Value_T1E1User EpygiInterfaceName = 2
EpygiInterfaceName_Value_T1E1Network EpygiInterfaceName = 3
EpygiInterfaceName_Value_ISDN EpygiInterfaceName = 4
)
var EpygiInterfaceName_Strings = map[EpygiInterfaceName]string{
EpygiInterfaceName_Value_Ethernet: "Ethernet",
EpygiInterfaceName_Value_FXO: "FXO",
EpygiInterfaceName_Value_T1E1User: "T1-E1-User",
EpygiInterfaceName_Value_T1E1Network: "T1-E1-Network",
EpygiInterfaceName_Value_ISDN: "ISDN",
}
func (a EpygiInterfaceName) String() string {
if str, ok := EpygiInterfaceName_Strings[a]; ok {
return str
}
return "EpygiInterfaceName(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInterfaceName_Add(p *radius.Packet, value EpygiInterfaceName) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 174, a)
}
func EpygiInterfaceName_Get(p *radius.Packet) (value EpygiInterfaceName) {
value, _ = EpygiInterfaceName_Lookup(p)
return
}
func EpygiInterfaceName_Gets(p *radius.Packet) (values []EpygiInterfaceName, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 174) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInterfaceName(i))
}
return
}
func EpygiInterfaceName_Lookup(p *radius.Packet) (value EpygiInterfaceName, err error) {
a, ok := _Epygi_LookupVendor(p, 174)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInterfaceName(i)
return
}
func EpygiInterfaceName_Set(p *radius.Packet, value EpygiInterfaceName) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 174, a)
}
func EpygiInterfaceName_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 174)
}
type EpygiInterfaceNumber uint32
var EpygiInterfaceNumber_Strings = map[EpygiInterfaceNumber]string{}
func (a EpygiInterfaceNumber) String() string {
if str, ok := EpygiInterfaceNumber_Strings[a]; ok {
return str
}
return "EpygiInterfaceNumber(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInterfaceNumber_Add(p *radius.Packet, value EpygiInterfaceNumber) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 175, a)
}
func EpygiInterfaceNumber_Get(p *radius.Packet) (value EpygiInterfaceNumber) {
value, _ = EpygiInterfaceNumber_Lookup(p)
return
}
func EpygiInterfaceNumber_Gets(p *radius.Packet) (values []EpygiInterfaceNumber, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 175) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInterfaceNumber(i))
}
return
}
func EpygiInterfaceNumber_Lookup(p *radius.Packet) (value EpygiInterfaceNumber, err error) {
a, ok := _Epygi_LookupVendor(p, 175)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInterfaceNumber(i)
return
}
func EpygiInterfaceNumber_Set(p *radius.Packet, value EpygiInterfaceNumber) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 175, a)
}
func EpygiInterfaceNumber_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 175)
}
type EpygiTimeslotNumber uint32
var EpygiTimeslotNumber_Strings = map[EpygiTimeslotNumber]string{}
func (a EpygiTimeslotNumber) String() string {
if str, ok := EpygiTimeslotNumber_Strings[a]; ok {
return str
}
return "EpygiTimeslotNumber(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiTimeslotNumber_Add(p *radius.Packet, value EpygiTimeslotNumber) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 176, a)
}
func EpygiTimeslotNumber_Get(p *radius.Packet) (value EpygiTimeslotNumber) {
value, _ = EpygiTimeslotNumber_Lookup(p)
return
}
func EpygiTimeslotNumber_Gets(p *radius.Packet) (values []EpygiTimeslotNumber, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 176) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiTimeslotNumber(i))
}
return
}
func EpygiTimeslotNumber_Lookup(p *radius.Packet) (value EpygiTimeslotNumber, err error) {
a, ok := _Epygi_LookupVendor(p, 176)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiTimeslotNumber(i)
return
}
func EpygiTimeslotNumber_Set(p *radius.Packet, value EpygiTimeslotNumber) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 176, a)
}
func EpygiTimeslotNumber_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 176)
}
type EpygiOrigIpAddr uint32
var EpygiOrigIpAddr_Strings = map[EpygiOrigIpAddr]string{}
func (a EpygiOrigIpAddr) String() string {
if str, ok := EpygiOrigIpAddr_Strings[a]; ok {
return str
}
return "EpygiOrigIpAddr(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOrigIpAddr_Add(p *radius.Packet, value EpygiOrigIpAddr) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 177, a)
}
func EpygiOrigIpAddr_Get(p *radius.Packet) (value EpygiOrigIpAddr) {
value, _ = EpygiOrigIpAddr_Lookup(p)
return
}
func EpygiOrigIpAddr_Gets(p *radius.Packet) (values []EpygiOrigIpAddr, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 177) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOrigIpAddr(i))
}
return
}
func EpygiOrigIpAddr_Lookup(p *radius.Packet) (value EpygiOrigIpAddr, err error) {
a, ok := _Epygi_LookupVendor(p, 177)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOrigIpAddr(i)
return
}
func EpygiOrigIpAddr_Set(p *radius.Packet, value EpygiOrigIpAddr) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 177, a)
}
func EpygiOrigIpAddr_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 177)
}
type EpygiDestIpAddr uint32
var EpygiDestIpAddr_Strings = map[EpygiDestIpAddr]string{}
func (a EpygiDestIpAddr) String() string {
if str, ok := EpygiDestIpAddr_Strings[a]; ok {
return str
}
return "EpygiDestIpAddr(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDestIpAddr_Add(p *radius.Packet, value EpygiDestIpAddr) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 178, a)
}
func EpygiDestIpAddr_Get(p *radius.Packet) (value EpygiDestIpAddr) {
value, _ = EpygiDestIpAddr_Lookup(p)
return
}
func EpygiDestIpAddr_Gets(p *radius.Packet) (values []EpygiDestIpAddr, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 178) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDestIpAddr(i))
}
return
}
func EpygiDestIpAddr_Lookup(p *radius.Packet) (value EpygiDestIpAddr, err error) {
a, ok := _Epygi_LookupVendor(p, 178)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDestIpAddr(i)
return
}
func EpygiDestIpAddr_Set(p *radius.Packet, value EpygiDestIpAddr) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 178, a)
}
func EpygiDestIpAddr_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 178)
}
type EpygiOrigIpPort uint32
var EpygiOrigIpPort_Strings = map[EpygiOrigIpPort]string{}
func (a EpygiOrigIpPort) String() string {
if str, ok := EpygiOrigIpPort_Strings[a]; ok {
return str
}
return "EpygiOrigIpPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOrigIpPort_Add(p *radius.Packet, value EpygiOrigIpPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 179, a)
}
func EpygiOrigIpPort_Get(p *radius.Packet) (value EpygiOrigIpPort) {
value, _ = EpygiOrigIpPort_Lookup(p)
return
}
func EpygiOrigIpPort_Gets(p *radius.Packet) (values []EpygiOrigIpPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 179) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOrigIpPort(i))
}
return
}
func EpygiOrigIpPort_Lookup(p *radius.Packet) (value EpygiOrigIpPort, err error) {
a, ok := _Epygi_LookupVendor(p, 179)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOrigIpPort(i)
return
}
func EpygiOrigIpPort_Set(p *radius.Packet, value EpygiOrigIpPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 179, a)
}
func EpygiOrigIpPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 179)
}
type EpygiDestIpPort uint32
var EpygiDestIpPort_Strings = map[EpygiDestIpPort]string{}
func (a EpygiDestIpPort) String() string {
if str, ok := EpygiDestIpPort_Strings[a]; ok {
return str
}
return "EpygiDestIpPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDestIpPort_Add(p *radius.Packet, value EpygiDestIpPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 180, a)
}
func EpygiDestIpPort_Get(p *radius.Packet) (value EpygiDestIpPort) {
value, _ = EpygiDestIpPort_Lookup(p)
return
}
func EpygiDestIpPort_Gets(p *radius.Packet) (values []EpygiDestIpPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 180) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDestIpPort(i))
}
return
}
func EpygiDestIpPort_Lookup(p *radius.Packet) (value EpygiDestIpPort, err error) {
a, ok := _Epygi_LookupVendor(p, 180)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDestIpPort(i)
return
}
func EpygiDestIpPort_Set(p *radius.Packet, value EpygiDestIpPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 180, a)
}
func EpygiDestIpPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 180)
}
func EpygiCallingPartyNumber_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 181, a)
}
func EpygiCallingPartyNumber_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 181, a)
}
func EpygiCallingPartyNumber_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiCallingPartyNumber_Lookup(p)
return
}
func EpygiCallingPartyNumber_GetString(p *radius.Packet) (value string) {
value, _ = EpygiCallingPartyNumber_LookupString(p)
return
}
func EpygiCallingPartyNumber_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 181) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCallingPartyNumber_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 181) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCallingPartyNumber_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 181)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiCallingPartyNumber_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 181)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiCallingPartyNumber_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 181, a)
}
func EpygiCallingPartyNumber_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 181, a)
}
func EpygiCallingPartyNumber_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 181)
}
func EpygiCalledPartyNumber_Add(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 182, a)
}
func EpygiCalledPartyNumber_AddString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_AddVendor(p, 182, a)
}
func EpygiCalledPartyNumber_Get(p *radius.Packet) (value []byte) {
value, _ = EpygiCalledPartyNumber_Lookup(p)
return
}
func EpygiCalledPartyNumber_GetString(p *radius.Packet) (value string) {
value, _ = EpygiCalledPartyNumber_LookupString(p)
return
}
func EpygiCalledPartyNumber_Gets(p *radius.Packet) (values [][]byte, err error) {
var i []byte
for _, attr := range _Epygi_GetsVendor(p, 182) {
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCalledPartyNumber_GetStrings(p *radius.Packet) (values []string, err error) {
var i string
for _, attr := range _Epygi_GetsVendor(p, 182) {
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
}
return
}
func EpygiCalledPartyNumber_Lookup(p *radius.Packet) (value []byte, err error) {
a, ok := _Epygi_LookupVendor(p, 182)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.Bytes(a)
return
}
func EpygiCalledPartyNumber_LookupString(p *radius.Packet) (value string, err error) {
a, ok := _Epygi_LookupVendor(p, 182)
if !ok {
err = radius.ErrNoAttribute
return
}
value = radius.String(a)
return
}
func EpygiCalledPartyNumber_Set(p *radius.Packet, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 182, a)
}
func EpygiCalledPartyNumber_SetString(p *radius.Packet, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
return _Epygi_SetVendor(p, 182, a)
}
func EpygiCalledPartyNumber_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 182)
}
type EpygiDateTimeOrigination uint32
var EpygiDateTimeOrigination_Strings = map[EpygiDateTimeOrigination]string{}
func (a EpygiDateTimeOrigination) String() string {
if str, ok := EpygiDateTimeOrigination_Strings[a]; ok {
return str
}
return "EpygiDateTimeOrigination(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDateTimeOrigination_Add(p *radius.Packet, value EpygiDateTimeOrigination) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 183, a)
}
func EpygiDateTimeOrigination_Get(p *radius.Packet) (value EpygiDateTimeOrigination) {
value, _ = EpygiDateTimeOrigination_Lookup(p)
return
}
func EpygiDateTimeOrigination_Gets(p *radius.Packet) (values []EpygiDateTimeOrigination, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 183) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDateTimeOrigination(i))
}
return
}
func EpygiDateTimeOrigination_Lookup(p *radius.Packet) (value EpygiDateTimeOrigination, err error) {
a, ok := _Epygi_LookupVendor(p, 183)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDateTimeOrigination(i)
return
}
func EpygiDateTimeOrigination_Set(p *radius.Packet, value EpygiDateTimeOrigination) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 183, a)
}
func EpygiDateTimeOrigination_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 183)
}
type EpygiDateTimeConnect uint32
var EpygiDateTimeConnect_Strings = map[EpygiDateTimeConnect]string{}
func (a EpygiDateTimeConnect) String() string {
if str, ok := EpygiDateTimeConnect_Strings[a]; ok {
return str
}
return "EpygiDateTimeConnect(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDateTimeConnect_Add(p *radius.Packet, value EpygiDateTimeConnect) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 184, a)
}
func EpygiDateTimeConnect_Get(p *radius.Packet) (value EpygiDateTimeConnect) {
value, _ = EpygiDateTimeConnect_Lookup(p)
return
}
func EpygiDateTimeConnect_Gets(p *radius.Packet) (values []EpygiDateTimeConnect, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 184) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDateTimeConnect(i))
}
return
}
func EpygiDateTimeConnect_Lookup(p *radius.Packet) (value EpygiDateTimeConnect, err error) {
a, ok := _Epygi_LookupVendor(p, 184)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDateTimeConnect(i)
return
}
func EpygiDateTimeConnect_Set(p *radius.Packet, value EpygiDateTimeConnect) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 184, a)
}
func EpygiDateTimeConnect_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 184)
}
type EpygiDateTimeDisconnect uint32
var EpygiDateTimeDisconnect_Strings = map[EpygiDateTimeDisconnect]string{}
func (a EpygiDateTimeDisconnect) String() string {
if str, ok := EpygiDateTimeDisconnect_Strings[a]; ok {
return str
}
return "EpygiDateTimeDisconnect(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDateTimeDisconnect_Add(p *radius.Packet, value EpygiDateTimeDisconnect) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 185, a)
}
func EpygiDateTimeDisconnect_Get(p *radius.Packet) (value EpygiDateTimeDisconnect) {
value, _ = EpygiDateTimeDisconnect_Lookup(p)
return
}
func EpygiDateTimeDisconnect_Gets(p *radius.Packet) (values []EpygiDateTimeDisconnect, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 185) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDateTimeDisconnect(i))
}
return
}
func EpygiDateTimeDisconnect_Lookup(p *radius.Packet) (value EpygiDateTimeDisconnect, err error) {
a, ok := _Epygi_LookupVendor(p, 185)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDateTimeDisconnect(i)
return
}
func EpygiDateTimeDisconnect_Set(p *radius.Packet, value EpygiDateTimeDisconnect) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 185, a)
}
func EpygiDateTimeDisconnect_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 185)
}
type EpygiDuration uint32
var EpygiDuration_Strings = map[EpygiDuration]string{}
func (a EpygiDuration) String() string {
if str, ok := EpygiDuration_Strings[a]; ok {
return str
}
return "EpygiDuration(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiDuration_Add(p *radius.Packet, value EpygiDuration) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 186, a)
}
func EpygiDuration_Get(p *radius.Packet) (value EpygiDuration) {
value, _ = EpygiDuration_Lookup(p)
return
}
func EpygiDuration_Gets(p *radius.Packet) (values []EpygiDuration, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 186) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiDuration(i))
}
return
}
func EpygiDuration_Lookup(p *radius.Packet) (value EpygiDuration, err error) {
a, ok := _Epygi_LookupVendor(p, 186)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiDuration(i)
return
}
func EpygiDuration_Set(p *radius.Packet, value EpygiDuration) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 186, a)
}
func EpygiDuration_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 186)
}
type EpygiOutSourceRTPIP uint32
var EpygiOutSourceRTPIP_Strings = map[EpygiOutSourceRTPIP]string{}
func (a EpygiOutSourceRTPIP) String() string {
if str, ok := EpygiOutSourceRTPIP_Strings[a]; ok {
return str
}
return "EpygiOutSourceRTPIP(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutSourceRTPIP_Add(p *radius.Packet, value EpygiOutSourceRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 187, a)
}
func EpygiOutSourceRTPIP_Get(p *radius.Packet) (value EpygiOutSourceRTPIP) {
value, _ = EpygiOutSourceRTPIP_Lookup(p)
return
}
func EpygiOutSourceRTPIP_Gets(p *radius.Packet) (values []EpygiOutSourceRTPIP, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 187) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutSourceRTPIP(i))
}
return
}
func EpygiOutSourceRTPIP_Lookup(p *radius.Packet) (value EpygiOutSourceRTPIP, err error) {
a, ok := _Epygi_LookupVendor(p, 187)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutSourceRTPIP(i)
return
}
func EpygiOutSourceRTPIP_Set(p *radius.Packet, value EpygiOutSourceRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 187, a)
}
func EpygiOutSourceRTPIP_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 187)
}
type EpygiOutDestRTPIP uint32
var EpygiOutDestRTPIP_Strings = map[EpygiOutDestRTPIP]string{}
func (a EpygiOutDestRTPIP) String() string {
if str, ok := EpygiOutDestRTPIP_Strings[a]; ok {
return str
}
return "EpygiOutDestRTPIP(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutDestRTPIP_Add(p *radius.Packet, value EpygiOutDestRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 188, a)
}
func EpygiOutDestRTPIP_Get(p *radius.Packet) (value EpygiOutDestRTPIP) {
value, _ = EpygiOutDestRTPIP_Lookup(p)
return
}
func EpygiOutDestRTPIP_Gets(p *radius.Packet) (values []EpygiOutDestRTPIP, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 188) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutDestRTPIP(i))
}
return
}
func EpygiOutDestRTPIP_Lookup(p *radius.Packet) (value EpygiOutDestRTPIP, err error) {
a, ok := _Epygi_LookupVendor(p, 188)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutDestRTPIP(i)
return
}
func EpygiOutDestRTPIP_Set(p *radius.Packet, value EpygiOutDestRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 188, a)
}
func EpygiOutDestRTPIP_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 188)
}
type EpygiInSourceRTPIP uint32
var EpygiInSourceRTPIP_Strings = map[EpygiInSourceRTPIP]string{}
func (a EpygiInSourceRTPIP) String() string {
if str, ok := EpygiInSourceRTPIP_Strings[a]; ok {
return str
}
return "EpygiInSourceRTPIP(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInSourceRTPIP_Add(p *radius.Packet, value EpygiInSourceRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 189, a)
}
func EpygiInSourceRTPIP_Get(p *radius.Packet) (value EpygiInSourceRTPIP) {
value, _ = EpygiInSourceRTPIP_Lookup(p)
return
}
func EpygiInSourceRTPIP_Gets(p *radius.Packet) (values []EpygiInSourceRTPIP, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 189) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInSourceRTPIP(i))
}
return
}
func EpygiInSourceRTPIP_Lookup(p *radius.Packet) (value EpygiInSourceRTPIP, err error) {
a, ok := _Epygi_LookupVendor(p, 189)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInSourceRTPIP(i)
return
}
func EpygiInSourceRTPIP_Set(p *radius.Packet, value EpygiInSourceRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 189, a)
}
func EpygiInSourceRTPIP_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 189)
}
type EpygiInDestRTPIP uint32
var EpygiInDestRTPIP_Strings = map[EpygiInDestRTPIP]string{}
func (a EpygiInDestRTPIP) String() string {
if str, ok := EpygiInDestRTPIP_Strings[a]; ok {
return str
}
return "EpygiInDestRTPIP(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInDestRTPIP_Add(p *radius.Packet, value EpygiInDestRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 190, a)
}
func EpygiInDestRTPIP_Get(p *radius.Packet) (value EpygiInDestRTPIP) {
value, _ = EpygiInDestRTPIP_Lookup(p)
return
}
func EpygiInDestRTPIP_Gets(p *radius.Packet) (values []EpygiInDestRTPIP, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 190) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInDestRTPIP(i))
}
return
}
func EpygiInDestRTPIP_Lookup(p *radius.Packet) (value EpygiInDestRTPIP, err error) {
a, ok := _Epygi_LookupVendor(p, 190)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInDestRTPIP(i)
return
}
func EpygiInDestRTPIP_Set(p *radius.Packet, value EpygiInDestRTPIP) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 190, a)
}
func EpygiInDestRTPIP_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 190)
}
type EpygiOutSourceRTPPort uint32
var EpygiOutSourceRTPPort_Strings = map[EpygiOutSourceRTPPort]string{}
func (a EpygiOutSourceRTPPort) String() string {
if str, ok := EpygiOutSourceRTPPort_Strings[a]; ok {
return str
}
return "EpygiOutSourceRTPPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutSourceRTPPort_Add(p *radius.Packet, value EpygiOutSourceRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 191, a)
}
func EpygiOutSourceRTPPort_Get(p *radius.Packet) (value EpygiOutSourceRTPPort) {
value, _ = EpygiOutSourceRTPPort_Lookup(p)
return
}
func EpygiOutSourceRTPPort_Gets(p *radius.Packet) (values []EpygiOutSourceRTPPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 191) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutSourceRTPPort(i))
}
return
}
func EpygiOutSourceRTPPort_Lookup(p *radius.Packet) (value EpygiOutSourceRTPPort, err error) {
a, ok := _Epygi_LookupVendor(p, 191)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutSourceRTPPort(i)
return
}
func EpygiOutSourceRTPPort_Set(p *radius.Packet, value EpygiOutSourceRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 191, a)
}
func EpygiOutSourceRTPPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 191)
}
type EpygiOutDestRTPPort uint32
var EpygiOutDestRTPPort_Strings = map[EpygiOutDestRTPPort]string{}
func (a EpygiOutDestRTPPort) String() string {
if str, ok := EpygiOutDestRTPPort_Strings[a]; ok {
return str
}
return "EpygiOutDestRTPPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutDestRTPPort_Add(p *radius.Packet, value EpygiOutDestRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 192, a)
}
func EpygiOutDestRTPPort_Get(p *radius.Packet) (value EpygiOutDestRTPPort) {
value, _ = EpygiOutDestRTPPort_Lookup(p)
return
}
func EpygiOutDestRTPPort_Gets(p *radius.Packet) (values []EpygiOutDestRTPPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 192) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutDestRTPPort(i))
}
return
}
func EpygiOutDestRTPPort_Lookup(p *radius.Packet) (value EpygiOutDestRTPPort, err error) {
a, ok := _Epygi_LookupVendor(p, 192)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutDestRTPPort(i)
return
}
func EpygiOutDestRTPPort_Set(p *radius.Packet, value EpygiOutDestRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 192, a)
}
func EpygiOutDestRTPPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 192)
}
type EpygiInSourceRTPPort uint32
var EpygiInSourceRTPPort_Strings = map[EpygiInSourceRTPPort]string{}
func (a EpygiInSourceRTPPort) String() string {
if str, ok := EpygiInSourceRTPPort_Strings[a]; ok {
return str
}
return "EpygiInSourceRTPPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInSourceRTPPort_Add(p *radius.Packet, value EpygiInSourceRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 193, a)
}
func EpygiInSourceRTPPort_Get(p *radius.Packet) (value EpygiInSourceRTPPort) {
value, _ = EpygiInSourceRTPPort_Lookup(p)
return
}
func EpygiInSourceRTPPort_Gets(p *radius.Packet) (values []EpygiInSourceRTPPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 193) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInSourceRTPPort(i))
}
return
}
func EpygiInSourceRTPPort_Lookup(p *radius.Packet) (value EpygiInSourceRTPPort, err error) {
a, ok := _Epygi_LookupVendor(p, 193)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInSourceRTPPort(i)
return
}
func EpygiInSourceRTPPort_Set(p *radius.Packet, value EpygiInSourceRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 193, a)
}
func EpygiInSourceRTPPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 193)
}
type EpygiInDestRTPPort uint32
var EpygiInDestRTPPort_Strings = map[EpygiInDestRTPPort]string{}
func (a EpygiInDestRTPPort) String() string {
if str, ok := EpygiInDestRTPPort_Strings[a]; ok {
return str
}
return "EpygiInDestRTPPort(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInDestRTPPort_Add(p *radius.Packet, value EpygiInDestRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 194, a)
}
func EpygiInDestRTPPort_Get(p *radius.Packet) (value EpygiInDestRTPPort) {
value, _ = EpygiInDestRTPPort_Lookup(p)
return
}
func EpygiInDestRTPPort_Gets(p *radius.Packet) (values []EpygiInDestRTPPort, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 194) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInDestRTPPort(i))
}
return
}
func EpygiInDestRTPPort_Lookup(p *radius.Packet) (value EpygiInDestRTPPort, err error) {
a, ok := _Epygi_LookupVendor(p, 194)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInDestRTPPort(i)
return
}
func EpygiInDestRTPPort_Set(p *radius.Packet, value EpygiInDestRTPPort) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 194, a)
}
func EpygiInDestRTPPort_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 194)
}
type EpygiCallRedirectReason uint32
const (
EpygiCallRedirectReason_Value_NoReason EpygiCallRedirectReason = 0
EpygiCallRedirectReason_Value_CallForwardUncondit EpygiCallRedirectReason = 1
EpygiCallRedirectReason_Value_CallForwardBusy EpygiCallRedirectReason = 2
EpygiCallRedirectReason_Value_CallForwardNoAnswer EpygiCallRedirectReason = 3
EpygiCallRedirectReason_Value_CallTranfer EpygiCallRedirectReason = 4
EpygiCallRedirectReason_Value_CallPark EpygiCallRedirectReason = 5
EpygiCallRedirectReason_Value_CallPickup EpygiCallRedirectReason = 6
EpygiCallRedirectReason_Value_ManyExtensionRinging EpygiCallRedirectReason = 7
EpygiCallRedirectReason_Value_HuntGroup EpygiCallRedirectReason = 8
)
var EpygiCallRedirectReason_Strings = map[EpygiCallRedirectReason]string{
EpygiCallRedirectReason_Value_NoReason: "No-Reason",
EpygiCallRedirectReason_Value_CallForwardUncondit: "Call-Forward-Uncondit",
EpygiCallRedirectReason_Value_CallForwardBusy: "Call-Forward-Busy",
EpygiCallRedirectReason_Value_CallForwardNoAnswer: "Call-Forward-NoAnswer",
EpygiCallRedirectReason_Value_CallTranfer: "Call-Tranfer",
EpygiCallRedirectReason_Value_CallPark: "Call-Park",
EpygiCallRedirectReason_Value_CallPickup: "Call-Pickup",
EpygiCallRedirectReason_Value_ManyExtensionRinging: "ManyExtension-Ringing",
EpygiCallRedirectReason_Value_HuntGroup: "Hunt-Group",
}
func (a EpygiCallRedirectReason) String() string {
if str, ok := EpygiCallRedirectReason_Strings[a]; ok {
return str
}
return "EpygiCallRedirectReason(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiCallRedirectReason_Add(p *radius.Packet, value EpygiCallRedirectReason) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 195, a)
}
func EpygiCallRedirectReason_Get(p *radius.Packet) (value EpygiCallRedirectReason) {
value, _ = EpygiCallRedirectReason_Lookup(p)
return
}
func EpygiCallRedirectReason_Gets(p *radius.Packet) (values []EpygiCallRedirectReason, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 195) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiCallRedirectReason(i))
}
return
}
func EpygiCallRedirectReason_Lookup(p *radius.Packet) (value EpygiCallRedirectReason, err error) {
a, ok := _Epygi_LookupVendor(p, 195)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiCallRedirectReason(i)
return
}
func EpygiCallRedirectReason_Set(p *radius.Packet, value EpygiCallRedirectReason) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 195, a)
}
func EpygiCallRedirectReason_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 195)
}
type EpygiCallDisconnectReason uint32
const (
EpygiCallDisconnectReason_Value_CallIsRedirected EpygiCallDisconnectReason = 0
EpygiCallDisconnectReason_Value_CallOriginOnHook EpygiCallDisconnectReason = 1
EpygiCallDisconnectReason_Value_CallTeminOnHook EpygiCallDisconnectReason = 2
EpygiCallDisconnectReason_Value_DisconectedByCAC EpygiCallDisconnectReason = 3
EpygiCallDisconnectReason_Value_Other EpygiCallDisconnectReason = 4
)
var EpygiCallDisconnectReason_Strings = map[EpygiCallDisconnectReason]string{
EpygiCallDisconnectReason_Value_CallIsRedirected: "Call-Is-Redirected",
EpygiCallDisconnectReason_Value_CallOriginOnHook: "Call-Origin-OnHook",
EpygiCallDisconnectReason_Value_CallTeminOnHook: "Call-Temin-OnHook",
EpygiCallDisconnectReason_Value_DisconectedByCAC: "Disconected-by-CAC",
EpygiCallDisconnectReason_Value_Other: "Other",
}
func (a EpygiCallDisconnectReason) String() string {
if str, ok := EpygiCallDisconnectReason_Strings[a]; ok {
return str
}
return "EpygiCallDisconnectReason(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiCallDisconnectReason_Add(p *radius.Packet, value EpygiCallDisconnectReason) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 196, a)
}
func EpygiCallDisconnectReason_Get(p *radius.Packet) (value EpygiCallDisconnectReason) {
value, _ = EpygiCallDisconnectReason_Lookup(p)
return
}
func EpygiCallDisconnectReason_Gets(p *radius.Packet) (values []EpygiCallDisconnectReason, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 196) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiCallDisconnectReason(i))
}
return
}
func EpygiCallDisconnectReason_Lookup(p *radius.Packet) (value EpygiCallDisconnectReason, err error) {
a, ok := _Epygi_LookupVendor(p, 196)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiCallDisconnectReason(i)
return
}
func EpygiCallDisconnectReason_Set(p *radius.Packet, value EpygiCallDisconnectReason) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 196, a)
}
func EpygiCallDisconnectReason_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 196)
}
type EpygiOutRTPPayload uint32
var EpygiOutRTPPayload_Strings = map[EpygiOutRTPPayload]string{}
func (a EpygiOutRTPPayload) String() string {
if str, ok := EpygiOutRTPPayload_Strings[a]; ok {
return str
}
return "EpygiOutRTPPayload(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutRTPPayload_Add(p *radius.Packet, value EpygiOutRTPPayload) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 197, a)
}
func EpygiOutRTPPayload_Get(p *radius.Packet) (value EpygiOutRTPPayload) {
value, _ = EpygiOutRTPPayload_Lookup(p)
return
}
func EpygiOutRTPPayload_Gets(p *radius.Packet) (values []EpygiOutRTPPayload, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 197) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutRTPPayload(i))
}
return
}
func EpygiOutRTPPayload_Lookup(p *radius.Packet) (value EpygiOutRTPPayload, err error) {
a, ok := _Epygi_LookupVendor(p, 197)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutRTPPayload(i)
return
}
func EpygiOutRTPPayload_Set(p *radius.Packet, value EpygiOutRTPPayload) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 197, a)
}
func EpygiOutRTPPayload_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 197)
}
type EpygiOutRTPPacketSize uint32
var EpygiOutRTPPacketSize_Strings = map[EpygiOutRTPPacketSize]string{}
func (a EpygiOutRTPPacketSize) String() string {
if str, ok := EpygiOutRTPPacketSize_Strings[a]; ok {
return str
}
return "EpygiOutRTPPacketSize(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutRTPPacketSize_Add(p *radius.Packet, value EpygiOutRTPPacketSize) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 198, a)
}
func EpygiOutRTPPacketSize_Get(p *radius.Packet) (value EpygiOutRTPPacketSize) {
value, _ = EpygiOutRTPPacketSize_Lookup(p)
return
}
func EpygiOutRTPPacketSize_Gets(p *radius.Packet) (values []EpygiOutRTPPacketSize, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 198) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutRTPPacketSize(i))
}
return
}
func EpygiOutRTPPacketSize_Lookup(p *radius.Packet) (value EpygiOutRTPPacketSize, err error) {
a, ok := _Epygi_LookupVendor(p, 198)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutRTPPacketSize(i)
return
}
func EpygiOutRTPPacketSize_Set(p *radius.Packet, value EpygiOutRTPPacketSize) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 198, a)
}
func EpygiOutRTPPacketSize_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 198)
}
type EpygiOutRTPPackets uint32
var EpygiOutRTPPackets_Strings = map[EpygiOutRTPPackets]string{}
func (a EpygiOutRTPPackets) String() string {
if str, ok := EpygiOutRTPPackets_Strings[a]; ok {
return str
}
return "EpygiOutRTPPackets(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutRTPPackets_Add(p *radius.Packet, value EpygiOutRTPPackets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 199, a)
}
func EpygiOutRTPPackets_Get(p *radius.Packet) (value EpygiOutRTPPackets) {
value, _ = EpygiOutRTPPackets_Lookup(p)
return
}
func EpygiOutRTPPackets_Gets(p *radius.Packet) (values []EpygiOutRTPPackets, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 199) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutRTPPackets(i))
}
return
}
func EpygiOutRTPPackets_Lookup(p *radius.Packet) (value EpygiOutRTPPackets, err error) {
a, ok := _Epygi_LookupVendor(p, 199)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutRTPPackets(i)
return
}
func EpygiOutRTPPackets_Set(p *radius.Packet, value EpygiOutRTPPackets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 199, a)
}
func EpygiOutRTPPackets_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 199)
}
type EpygiOutRTPOctets uint32
var EpygiOutRTPOctets_Strings = map[EpygiOutRTPOctets]string{}
func (a EpygiOutRTPOctets) String() string {
if str, ok := EpygiOutRTPOctets_Strings[a]; ok {
return str
}
return "EpygiOutRTPOctets(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiOutRTPOctets_Add(p *radius.Packet, value EpygiOutRTPOctets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 200, a)
}
func EpygiOutRTPOctets_Get(p *radius.Packet) (value EpygiOutRTPOctets) {
value, _ = EpygiOutRTPOctets_Lookup(p)
return
}
func EpygiOutRTPOctets_Gets(p *radius.Packet) (values []EpygiOutRTPOctets, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 200) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiOutRTPOctets(i))
}
return
}
func EpygiOutRTPOctets_Lookup(p *radius.Packet) (value EpygiOutRTPOctets, err error) {
a, ok := _Epygi_LookupVendor(p, 200)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiOutRTPOctets(i)
return
}
func EpygiOutRTPOctets_Set(p *radius.Packet, value EpygiOutRTPOctets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 200, a)
}
func EpygiOutRTPOctets_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 200)
}
type EpygiInRTPPayload uint32
var EpygiInRTPPayload_Strings = map[EpygiInRTPPayload]string{}
func (a EpygiInRTPPayload) String() string {
if str, ok := EpygiInRTPPayload_Strings[a]; ok {
return str
}
return "EpygiInRTPPayload(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPPayload_Add(p *radius.Packet, value EpygiInRTPPayload) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 201, a)
}
func EpygiInRTPPayload_Get(p *radius.Packet) (value EpygiInRTPPayload) {
value, _ = EpygiInRTPPayload_Lookup(p)
return
}
func EpygiInRTPPayload_Gets(p *radius.Packet) (values []EpygiInRTPPayload, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 201) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPPayload(i))
}
return
}
func EpygiInRTPPayload_Lookup(p *radius.Packet) (value EpygiInRTPPayload, err error) {
a, ok := _Epygi_LookupVendor(p, 201)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPPayload(i)
return
}
func EpygiInRTPPayload_Set(p *radius.Packet, value EpygiInRTPPayload) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 201, a)
}
func EpygiInRTPPayload_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 201)
}
type EpygiInRTPPacketSize uint32
var EpygiInRTPPacketSize_Strings = map[EpygiInRTPPacketSize]string{}
func (a EpygiInRTPPacketSize) String() string {
if str, ok := EpygiInRTPPacketSize_Strings[a]; ok {
return str
}
return "EpygiInRTPPacketSize(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPPacketSize_Add(p *radius.Packet, value EpygiInRTPPacketSize) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 202, a)
}
func EpygiInRTPPacketSize_Get(p *radius.Packet) (value EpygiInRTPPacketSize) {
value, _ = EpygiInRTPPacketSize_Lookup(p)
return
}
func EpygiInRTPPacketSize_Gets(p *radius.Packet) (values []EpygiInRTPPacketSize, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 202) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPPacketSize(i))
}
return
}
func EpygiInRTPPacketSize_Lookup(p *radius.Packet) (value EpygiInRTPPacketSize, err error) {
a, ok := _Epygi_LookupVendor(p, 202)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPPacketSize(i)
return
}
func EpygiInRTPPacketSize_Set(p *radius.Packet, value EpygiInRTPPacketSize) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 202, a)
}
func EpygiInRTPPacketSize_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 202)
}
type EpygiInRTPPackets uint32
var EpygiInRTPPackets_Strings = map[EpygiInRTPPackets]string{}
func (a EpygiInRTPPackets) String() string {
if str, ok := EpygiInRTPPackets_Strings[a]; ok {
return str
}
return "EpygiInRTPPackets(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPPackets_Add(p *radius.Packet, value EpygiInRTPPackets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 203, a)
}
func EpygiInRTPPackets_Get(p *radius.Packet) (value EpygiInRTPPackets) {
value, _ = EpygiInRTPPackets_Lookup(p)
return
}
func EpygiInRTPPackets_Gets(p *radius.Packet) (values []EpygiInRTPPackets, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 203) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPPackets(i))
}
return
}
func EpygiInRTPPackets_Lookup(p *radius.Packet) (value EpygiInRTPPackets, err error) {
a, ok := _Epygi_LookupVendor(p, 203)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPPackets(i)
return
}
func EpygiInRTPPackets_Set(p *radius.Packet, value EpygiInRTPPackets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 203, a)
}
func EpygiInRTPPackets_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 203)
}
type EpygiInRTPOctets uint32
var EpygiInRTPOctets_Strings = map[EpygiInRTPOctets]string{}
func (a EpygiInRTPOctets) String() string {
if str, ok := EpygiInRTPOctets_Strings[a]; ok {
return str
}
return "EpygiInRTPOctets(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPOctets_Add(p *radius.Packet, value EpygiInRTPOctets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 204, a)
}
func EpygiInRTPOctets_Get(p *radius.Packet) (value EpygiInRTPOctets) {
value, _ = EpygiInRTPOctets_Lookup(p)
return
}
func EpygiInRTPOctets_Gets(p *radius.Packet) (values []EpygiInRTPOctets, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 204) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPOctets(i))
}
return
}
func EpygiInRTPOctets_Lookup(p *radius.Packet) (value EpygiInRTPOctets, err error) {
a, ok := _Epygi_LookupVendor(p, 204)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPOctets(i)
return
}
func EpygiInRTPOctets_Set(p *radius.Packet, value EpygiInRTPOctets) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 204, a)
}
func EpygiInRTPOctets_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 204)
}
type EpygiInRTPPacketsLost uint32
var EpygiInRTPPacketsLost_Strings = map[EpygiInRTPPacketsLost]string{}
func (a EpygiInRTPPacketsLost) String() string {
if str, ok := EpygiInRTPPacketsLost_Strings[a]; ok {
return str
}
return "EpygiInRTPPacketsLost(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPPacketsLost_Add(p *radius.Packet, value EpygiInRTPPacketsLost) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 205, a)
}
func EpygiInRTPPacketsLost_Get(p *radius.Packet) (value EpygiInRTPPacketsLost) {
value, _ = EpygiInRTPPacketsLost_Lookup(p)
return
}
func EpygiInRTPPacketsLost_Gets(p *radius.Packet) (values []EpygiInRTPPacketsLost, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 205) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPPacketsLost(i))
}
return
}
func EpygiInRTPPacketsLost_Lookup(p *radius.Packet) (value EpygiInRTPPacketsLost, err error) {
a, ok := _Epygi_LookupVendor(p, 205)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPPacketsLost(i)
return
}
func EpygiInRTPPacketsLost_Set(p *radius.Packet, value EpygiInRTPPacketsLost) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 205, a)
}
func EpygiInRTPPacketsLost_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 205)
}
type EpygiInRTPPacketsDupl uint32
var EpygiInRTPPacketsDupl_Strings = map[EpygiInRTPPacketsDupl]string{}
func (a EpygiInRTPPacketsDupl) String() string {
if str, ok := EpygiInRTPPacketsDupl_Strings[a]; ok {
return str
}
return "EpygiInRTPPacketsDupl(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPPacketsDupl_Add(p *radius.Packet, value EpygiInRTPPacketsDupl) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 206, a)
}
func EpygiInRTPPacketsDupl_Get(p *radius.Packet) (value EpygiInRTPPacketsDupl) {
value, _ = EpygiInRTPPacketsDupl_Lookup(p)
return
}
func EpygiInRTPPacketsDupl_Gets(p *radius.Packet) (values []EpygiInRTPPacketsDupl, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 206) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPPacketsDupl(i))
}
return
}
func EpygiInRTPPacketsDupl_Lookup(p *radius.Packet) (value EpygiInRTPPacketsDupl, err error) {
a, ok := _Epygi_LookupVendor(p, 206)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPPacketsDupl(i)
return
}
func EpygiInRTPPacketsDupl_Set(p *radius.Packet, value EpygiInRTPPacketsDupl) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 206, a)
}
func EpygiInRTPPacketsDupl_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 206)
}
type EpygiInRTPJitter uint32
var EpygiInRTPJitter_Strings = map[EpygiInRTPJitter]string{}
func (a EpygiInRTPJitter) String() string {
if str, ok := EpygiInRTPJitter_Strings[a]; ok {
return str
}
return "EpygiInRTPJitter(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPJitter_Add(p *radius.Packet, value EpygiInRTPJitter) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 207, a)
}
func EpygiInRTPJitter_Get(p *radius.Packet) (value EpygiInRTPJitter) {
value, _ = EpygiInRTPJitter_Lookup(p)
return
}
func EpygiInRTPJitter_Gets(p *radius.Packet) (values []EpygiInRTPJitter, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 207) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPJitter(i))
}
return
}
func EpygiInRTPJitter_Lookup(p *radius.Packet) (value EpygiInRTPJitter, err error) {
a, ok := _Epygi_LookupVendor(p, 207)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPJitter(i)
return
}
func EpygiInRTPJitter_Set(p *radius.Packet, value EpygiInRTPJitter) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 207, a)
}
func EpygiInRTPJitter_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 207)
}
type EpygiInRTPLatency uint32
var EpygiInRTPLatency_Strings = map[EpygiInRTPLatency]string{}
func (a EpygiInRTPLatency) String() string {
if str, ok := EpygiInRTPLatency_Strings[a]; ok {
return str
}
return "EpygiInRTPLatency(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func EpygiInRTPLatency_Add(p *radius.Packet, value EpygiInRTPLatency) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_AddVendor(p, 208, a)
}
func EpygiInRTPLatency_Get(p *radius.Packet) (value EpygiInRTPLatency) {
value, _ = EpygiInRTPLatency_Lookup(p)
return
}
func EpygiInRTPLatency_Gets(p *radius.Packet) (values []EpygiInRTPLatency, err error) {
var i uint32
for _, attr := range _Epygi_GetsVendor(p, 208) {
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, EpygiInRTPLatency(i))
}
return
}
func EpygiInRTPLatency_Lookup(p *radius.Packet) (value EpygiInRTPLatency, err error) {
a, ok := _Epygi_LookupVendor(p, 208)
if !ok {
err = radius.ErrNoAttribute
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = EpygiInRTPLatency(i)
return
}
func EpygiInRTPLatency_Set(p *radius.Packet, value EpygiInRTPLatency) (err error) {
a := radius.NewInteger(uint32(value))
return _Epygi_SetVendor(p, 208, a)
}
func EpygiInRTPLatency_Del(p *radius.Packet) {
_Epygi_DelVendor(p, 208)
}
|
/**
* The main method for the Application. It expects the first argument contains the program run id.
*
* @param args arguments provided to the application
* @throws Exception if failed to the the job
*/
private void doMain(String[] args) throws Exception {
Map<String, String> arguments = RuntimeArguments.fromPosixArray(args);
if (!arguments.containsKey(RUN_ID)) {
throw new IllegalArgumentException("Missing argument " + RUN_ID);
}
if (UserGroupInformation.isSecurityEnabled()) {
String principal = arguments.get(ClusterProperties.KERBEROS_PRINCIPAL);
String keytab = arguments.get(ClusterProperties.KERBEROS_KEYTAB);
if (principal != null && keytab != null) {
LOG.info("Login with kerberos principal {} and keytab {}", principal, keytab);
UserGroupInformation.loginUserFromKeytab(principal, keytab);
} else {
LOG.warn("Security enabled but no kerberos principal and keytab are provided");
}
}
Runtime.getRuntime().addShutdownHook(new Thread(runtimeJob::requestStop));
System.setProperty(Constants.Zookeeper.TWILL_ZK_SERVER_LOCALHOST, "false");
RunId runId = RunIds.fromString(arguments.get(RUN_ID));
CConfiguration cConf = CConfiguration.create();
cConf.setBoolean(Constants.Explore.EXPLORE_ENABLED, false);
cConf.set(Constants.CFG_HDFS_NAMESPACE, "/twill-" + runId);
try {
RemoteExecutionRuntimeJobEnvironment jobEnv = initialize(cConf);
runtimeJob.run(jobEnv);
} finally {
destroy();
}
} |
/**
* Returns a double with the given magnitude and the sign of {@code sign}.
* If {@code sign} is NaN, the sign of the result is positive.
* @since 1.6
*/
public static double copySign(double magnitude, double sign) {
long magnitudeBits = Double.doubleToRawLongBits(magnitude);
long signBits = Double.doubleToRawLongBits((sign != sign) ? 1.0 : sign);
magnitudeBits = (magnitudeBits & ~Double.SIGN_MASK) | (signBits & Double.SIGN_MASK);
return Double.longBitsToDouble(magnitudeBits);
} |
/*
Copyright 2018 <NAME>
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 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.
*/
// This file was generated by glatter.py script.
GLATTER_INLINE_OR_NOT
glatter_extension_support_status_GL_t glatter_get_extension_support_GL()
{
static glatter_extension_support_status_GL_t ess;
typedef glatter_es_record_t rt;
static rt e3614[] = {{4095424020, 38}, 0};
static rt e381f[] = {{3687839775, 51}, 0};
static rt e6bd [] = {{2229700285, 52}, 0};
static rt e2c1 [] = {{3085091521, 54}, 0};
static rt e3e22[] = {{597196322, 28}, 0};
static rt eaf7 [] = {{2933115639, 30}, 0};
static rt e2f59[] = {{3830902617, 31}, 0};
static rt e101b[] = {{23482395, 32}, 0};
static rt e3f81[] = {{3117563777, 33}, 0};
static rt e35c9[] = {{2229466569, 34}, 0};
static rt e8eb [] = {{2022082795, 35}, 0};
static rt e3ec9[] = {{3548692169, 36}, 0};
static rt e1d20[] = {{127589664, 37}, 0};
static rt e36d8[] = {{3934058200, 39}, 0};
static rt e36f7[] = {{3934058231, 40}, 0};
static rt e121b[] = {{2427064859, 41}, 0};
static rt e25bd[] = {{583280061, 42}, 0};
static rt e3250[] = {{3312333392, 43}, 0};
static rt e17f6[] = {{3119568886, 44}, 0};
static rt e3b96[] = {{1539570582, 45}, 0};
static rt e2918[] = {{1402415384, 46}, 0};
static rt e3b75[] = {{3153754997, 47}, 0};
static rt ebd1 [] = {{2704870353, 48}, 0};
static rt e27a0[] = {{380413856, 49}, 0};
static rt e100a[] = {{841535498, 50}, 0};
static rt e25e7[] = {{638166503, 53}, 0};
static rt e2a43[] = {{1790798403, 55}, 0};
static rt e2fa3[] = {{1263136675, 56}, 0};
static rt e312a[] = {{1214705962, 57}, 0};
static rt e3be0[] = {{2055846880, 58}, 0};
static rt e3be3[] = {{2055846883, 59}, 0};
static rt e3be7[] = {{2055846887, 60}, 0};
static rt e608 [] = {{3796387336, 61}, 0};
static rt e3f61[] = {{2136768353, 62}, 0};
static rt e1e29[] = {{4013121065, 63}, 0};
static rt e434 [] = {{2649261108, 64}, 0};
static rt e871 [] = {{1369704561, 65}, 0};
static rt e382e[] = {{2341763118, 66}, 0};
static rt efcf [] = {{687312847, 67}, 0};
static rt e1446[] = {{3063239750, 0}, 0};
static rt efe4 [] = {{1112559588, 1}, 0};
static rt e277d[] = {{3525322621, 2}, 0};
static rt e21f9[] = {{119120377, 3}, 0};
static rt e1945[] = {{978901317, 4}, 0};
static rt e1035[] = {{1354321973, 5}, 0};
static rt e3c [] = {{2451914812, 6}, 0};
static rt e2715[] = {{3930089237, 7}, 0};
static rt e222a[] = {{1365877290, 8}, {3515982378, 12}, 0};
static rt e1b15[] = {{1144249109, 9}, 0};
static rt e28cf[] = {{3893356751, 10}, 0};
static rt e205 [] = {{3469509125, 11}, 0};
static rt e2cb0[] = {{141421744, 13}, 0};
static rt e26e9[] = {{847111913, 14}, 0};
static rt e26c6[] = {{1540499142, 15}, 0};
static rt e6df [] = {{974915295, 16}, 0};
static rt e3795[] = {{1142765461, 17}, 0};
static rt e1e49[] = {{3761774153, 18}, 0};
static rt e3b67[] = {{1709996903, 19}, 0};
static rt e1f3b[] = {{3472219963, 20}, 0};
static rt e2914[] = {{2292820244, 21}, 0};
static rt e12c [] = {{4113137964, 22}, 0};
static rt e24f5[] = {{805922037, 23}, 0};
static rt eb37 [] = {{96701239, 24}, 0};
static rt e3bc3[] = {{2796125123, 25}, 0};
static rt e3cb5[] = {{982826165, 26}, 0};
static rt e24e8[] = {{1122788584, 27}, 0};
static rt e31fb[] = {{312046075, 29}, 0};
static rt e3b12[] = {{3331504914, 68}, 0};
static rt e12b6[] = {{2557956790, 69}, 0};
static rt e29a8[] = {{2808195496, 70}, 0};
static rt e1491[] = {{2297304209, 71}, 0};
static rt e1275[] = {{2890928757, 72}, 0};
static rt e730 [] = {{2115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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,e3ec9,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,e3f61,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,e3f81,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0
};
static int initialized = 0;
if (!initialized) {
const uint8_t* glv = (const uint8_t*)glatter_glGetString(GL_VERSION);
int new_way = 0;
if (glv) {
// if this fails, something might be wrong with the implementation
assert((int)glv[0] > 48 && (int)glv[0] < 58);
new_way = (int)glv[0] > 50; // i.e. gl version is 3 or higher
}
#ifdef GL_NUM_EXTENSIONS
if (new_way && glatter_get_proc_address_GL("glGetStringi") ) {
GLint n = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &n);
for (GLint i=0; i<n; i++) {
uint32_t hash = glatter_djb2( (const uint8_t*)glatter_glGetStringi(GL_EXTENSIONS, i) );
int index = -1;
rt* r = es_dispatch[ hash & (GLATTER_LOOKUP_SIZE-1) ];
for ( ; r && (r->hash | r->index); r++ ) {
if (r->hash == hash) {
index = r->index;
ess.inexed_extensions[index] = 1;
break;
}
}
if (index == -1) {
// (1) This scope will be reached if the implementation supports an extension
// not listed in the headers. This may happen if the headers are old or the
// extension is deprecated. The same condition repeats two more times below.
// It is not an error, thus there is nothing to do.
// The statement is left for debug purposes.
}
}
}
else {
#endif
uint32_t hash = 5381;
const uint8_t* ext_str = (const uint8_t*)glatter_glGetString(GL_EXTENSIONS);
for ( ; *ext_str; ext_str++) {
if (*ext_str == ' ') {
int index = -1;
rt* r = es_dispatch[ hash & (GLATTER_LOOKUP_SIZE-1) ];
for ( ; r && (r->hash | r->index); r++ ) {
if (r->hash == hash) {
index = r->index;
ess.inexed_extensions[index] = 1;
break;
}
}
if (index == -1) {
// (2)
}
// reset
hash = 5381;
continue;
}
hash = ((hash << 5) + hash) + (int)(*ext_str);
}
if (hash != 5381) {
int index = -1;
rt* r = es_dispatch[ hash & (GLATTER_LOOKUP_SIZE-1) ];
for ( ; r && (r->hash | r->index); r++ ) {
if (r->hash == hash) {
index = r->index;
ess.inexed_extensions[index] = 1;
break;
}
}
if (index == -1) {
// (3)
}
}
#ifdef GL_NUM_EXTENSIONS
}
#endif
initialized = 1;
}
return ess;
}
|
<reponame>kaustubh-karkare/todolist<filename>src/taskgroup.py<gh_stars>1-10
require task, prettytable
class TaskGroup:
def __init__(self,tasks,name=""):
self.name = name
self.__tasks = []
for task in tasks:
self.task_add(task)
def __repr__(self):
return self.__tasks.__repr__()
def task_list(self,unhide=False):
return [task for task in self.__tasks if unhide or not task.tag_check("hidden")]
def task_add(self,task):
if isinstance(task,Task) and not any(t==task for t in self.__tasks):
self.__tasks.append(task)
self.__tasks.sort(key=lambda x: x.raw().lower())
self.__tasks.sort(key=lambda x: x.group and x.group.name, reverse=True)
def task_remove(self,task):
if isinstance(task,Task) and task in self.__tasks:
self.__tasks.remove(task)
def tabulate(self, index=False):
data, tasks = [], self.task_list()
if len(tasks)==0: return "No Matching Tasks\n"
else: data.append(tasks[0].table_heading())
data.extend(task.table_fields() for task in tasks)
if index:
for i,row in enumerate(data):
data[i] = ["Index" if i==0 else str(i-1)]+data[i]
return prettytable(data)
def report(self):
z = [task.report() for task in self.task_list()]
if len(z)==0:
return "Performance Index = 0/0\n"
else:
x, y = map(sum, zip(*z))
return "Performance Index = %.2f%%\n" % (100.0*x/y)
def select(self,words):
words = [word for word in words if word!=""]
if len(words)==0: return self.__class__( self.__tasks )
tasks = []
for task in self.__tasks:
check = 1
for word in words:
if not word.startswith("~"): check &= word in task
elif word.startswith("~~"): check &= word[1:] in task
else: check &= word[1:] not in task
if check: tasks.append(task)
return self.__class__( tasks )
exports["TaskGroup"] = TaskGroup |
/* Copyright (c) 2008-2013, <NAME>
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#ifdef _MSC_VER
typedef unsigned char uint8_t;
#else
# include "stdint.h"
#endif
#ifdef BOOT_JAVAHOME
#if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER))
# define EXPORT __declspec(dllexport)
# define SYMBOL(x) binary_javahome_jar_##x
#else
# define EXPORT __attribute__ ((visibility("default"))) \
__attribute__ ((used))
# define SYMBOL(x) _binary_javahome_jar_##x
#endif
extern "C" {
extern const uint8_t SYMBOL(start)[];
extern const uint8_t SYMBOL(end)[];
EXPORT const uint8_t*
javahomeJar(unsigned* size)
{
*size = SYMBOL(end) - SYMBOL(start);
return SYMBOL(start);
}
}
#undef SYMBOL
#endif//BOOT_JAVAHOME
|
import logging
import boto3
import pandas as pd
ON_DEMAND_PRICING_CSV = 'https://tinyurl.com/yykw7p8c'
ON_DEMAND_PRICES = pd.read_csv(ON_DEMAND_PRICING_CSV,
error_bad_lines=False,
warn_bad_lines=False)
DF_COL_INSTANCE_TYPE = 'instance_type'
DF_COL_REGION = 'region'
DF_COL_SPOT_PRICE = 'spot_price'
DF_COL_ON_DEMAND_PRICE = 'on_demand_price'
LOGGER = logging.getLogger(__name__)
def get_all_regions():
"""
Get all regions served by AWS
:return: a list of string
"""
ec2 = boto3.client('ec2', 'us-east-1')
response = ec2.describe_regions()
return [region['RegionName'] for region in response['Regions']]
def get_spot_price(instance_types, region_name):
"""
Get spot price at current instant of an instance in a
given region
:param instance_types: EC2 instance type
:param region_name: AWS regions name
:return: a dictionary with instance type as key and spot price as value
"""
ec2_client = boto3.client('ec2', region_name=region_name)
response = ec2_client.describe_spot_price_history(
InstanceTypes=instance_types,
ProductDescriptions=['Linux/UNIX'],
MaxResults=len(instance_types) * 6)
spot_prices = {}
spot_price_list = response['SpotPriceHistory']
for sp in spot_price_list:
if sp['InstanceType'] not in spot_prices:
spot_prices[sp['InstanceType']] = float(sp['SpotPrice'])
instance_type_list = []
spot_price_list = []
for instance_type, spot_price in spot_prices.items():
instance_type_list.append(instance_type)
spot_price_list.append(spot_price)
return pd.DataFrame({DF_COL_INSTANCE_TYPE: instance_type_list,
DF_COL_SPOT_PRICE: spot_price_list})
def get_on_demand_price(instance_types, region_name):
"""
Get on demand price at current instant of an instance in a
given region
:param instance_types: EC2 instance types
:param region_name: AWS regions name
:return: a dictionary as instance type as key and
"""
instance_prices = ON_DEMAND_PRICES.loc[
(ON_DEMAND_PRICES['instanceType'].isin(instance_types)) &
(ON_DEMAND_PRICES['region'] == region_name) &
(ON_DEMAND_PRICES['operatingSystem'] == 'Linux')]
instance_type_list = instance_prices['instanceType']
on_demand_price_list = instance_prices['price']
return pd.DataFrame({DF_COL_INSTANCE_TYPE: instance_type_list,
DF_COL_ON_DEMAND_PRICE: on_demand_price_list})
def get_instance_pricing(instance_types):
"""
Get the spot and on demand price of an instance type
in all the regions at current instant
:param instance_types: EC2 instance type
:return: a pandas DataFrame with columns as
region, spot price and on demand price
"""
all_regions = get_all_regions()
price_df = pd.DataFrame({DF_COL_INSTANCE_TYPE: [],
DF_COL_REGION: [],
DF_COL_SPOT_PRICE: [],
DF_COL_ON_DEMAND_PRICE: []})
for region_name in all_regions:
spot_prices = get_spot_price(instance_types, region_name)
on_demand_prices = get_on_demand_price(instance_types, region_name)
both_prices = pd.merge(spot_prices, on_demand_prices,
on=DF_COL_INSTANCE_TYPE)
n_rows = both_prices.shape[0]
region_list = n_rows * [region_name]
both_prices[DF_COL_REGION] = region_list
both_prices = both_prices[[DF_COL_INSTANCE_TYPE, DF_COL_REGION,
DF_COL_SPOT_PRICE,
DF_COL_ON_DEMAND_PRICE]]
price_df = price_df.append(both_prices)
return price_df
|
package facebook
func minWindow(s string, t string) string {
if len(t) == 0 {
return ""
}
chars := make(map[byte]int)
for i := 0; i < len(t); i += 1 {
chars[t[i]]++
}
res := ""
listindexes := list{}
mapidx := make(map[byte]*queue)
charscount := 0
for i := 0; i < len(s); i += 1 {
if _, ok := chars[s[i]]; !ok {
continue
}
idx := &dnode{
val: i,
}
listindexes.append(idx)
if mapidx[s[i]] == nil {
mapidx[s[i]] = &queue{}
}
mapidx[s[i]].enqueue(&node{ val: idx })
charscount++
if mapidx[s[i]].size > chars[s[i]] {
// dequeue old index
oldidx := mapidx[s[i]].dequeue()
listindexes.remove(oldidx.val)
charscount--
}
if charscount < len(t) {
continue
}
l := listindexes.head.val
r := listindexes.tail.val
if len(res) == 0 || r - l + 1 < len(res) {
res = s[l:r+1]
}
}
return res
}
type node struct {
next *node
val *dnode
}
type queue struct {
head *node
tail *node
size int
}
func (q *queue) enqueue(x *node) {
if q.size == 0 {
q.head = x
q.tail = x
q.size++
return
}
q.tail.next = x
q.tail = x
q.size++
}
func (q *queue) dequeue() *node {
if q.size == 0 {
return nil
}
if q.size == 1 {
x := q.head
q.head = nil
q.tail = nil
q.size--
return x
}
x := q.head
q.head = q.head.next
x.next = nil
q.size--
return x
}
type dnode struct {
next *dnode
prev *dnode
val int
}
type list struct {
head *dnode
tail *dnode
size int
}
func (l *list) append(x *dnode) {
if l.size == 0 {
l.head = x
l.tail = x
l.size++
return
}
l.tail.next = x
x.prev = l.tail
l.tail = x
l.size++
}
func (l *list) remove(x *dnode) {
pr := x.prev
ne := x.next
if pr != nil {
pr.next = ne
}
if ne != nil {
ne.prev = pr
}
x.next = nil
x.prev = nil
l.size--
if l.head == x {
l.head = ne
}
if l.tail == x {
l.tail = pr
}
} |
<reponame>Charliego93/go-examples
// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.
package model
type ConfUser struct {
ID string `json:"id"`
UserName string `json:"userName"`
Email *string `json:"email"`
Phone *string `json:"phone"`
Meetups []*Meetup `json:"meetups"`
}
type Meetup struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
User *ConfUser `json:"user"`
}
|
def format_df(df_in: pd.DataFrame) -> pd.DataFrame:
df_new = df_in
if "date" in df_in.columns:
df_new.set_index("date", inplace=True)
df_new.index = pd.to_datetime(df_new.index, unit="s", origin="unix")
df_new.index = df_new.index.date
df_new = df_new[~df_new.index.duplicated(keep="last")]
return df_new |
package xyz.hsuyeemon.burpple.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import xyz.hsuyeemon.burpple.R;
import xyz.hsuyeemon.burpple.data.vo.PromotionVO;
import xyz.hsuyeemon.burpple.viewholders.ItemPromotionViewHolder;
/**
* Created by Dell on 1/6/2018.
*/
public class PromotionAdapter extends RecyclerView.Adapter<ItemPromotionViewHolder> {
private List<PromotionVO> mPromotionList;
public PromotionAdapter(){
mPromotionList= new ArrayList<>();
}
@Override
public ItemPromotionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context=parent.getContext();
LayoutInflater inflater= LayoutInflater.from(context);
View view=inflater.inflate(R.layout.item_promotion,parent,false);
ItemPromotionViewHolder itemPromotionViewHolder=new ItemPromotionViewHolder(view);
return itemPromotionViewHolder;
}
@Override
public void onBindViewHolder(ItemPromotionViewHolder holder, int position) {
holder.setPromotion(mPromotionList.get(position));
}
@Override
public int getItemCount() {
return mPromotionList.size();
}
public void setPromotion(List<PromotionVO> promotionList){
mPromotionList=promotionList;
notifyDataSetChanged();
}
}
|
def outLoop(self):
running = True
while(running):
line = self.pout.readline().decode(sys.stdout.encoding)
print(line, end='')
running='\n' in line
print('Finished') |
def read_pyproject_toml(
ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
) -> Optional[str]:
assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
if not value:
root = find_project_root(ctx.params.get("src", ()))
path = root / "pyproject.toml"
if path.is_file():
value = str(path)
else:
return None
try:
pyproject_toml = toml.load(value)
config = pyproject_toml.get("tool", {}).get("black", {})
except (toml.TomlDecodeError, OSError) as e:
raise click.FileError(
filename=value, hint=f"Error reading configuration file: {e}"
)
if not config:
return None
if ctx.default_map is None:
ctx.default_map = {}
ctx.default_map.update(
{k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
)
return value |
/**
* returns the square of the distance from p1 to p2 on the XZ plane
*/
public static float distanceToSquared(Point p1, Point p2) {
float distSquared =
(float)(Math.pow(p2.getX() - p1.getX(), 2) + Math.pow(p2.getZ() - p1.getZ(), 2));
return distSquared;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.