code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package jpelc.learning.designpatterns.factorymethod; public enum WeaponType { SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED(""); private String title; WeaponType(String title) { this.title = title; } @Override public String toString() { return title; } }
jpelc/java-design-patterns
factory-method/src/main/java/jpelc/learning/designpatterns/factorymethod/WeaponType.java
Java
gpl-2.0
324
// // avl.cc // // Copyright (C) 1996 Limit Point Systems, Inc. // // Author: Curtis Janssen <cljanss@limitpt.com> // Maintainer: LPS // // This file is part of the SC Toolkit. // // The SC Toolkit is free software; you can redistribute it and/or modify // it under the terms of the GNU Library General Public License as published by // the Free Software Foundation; either version 2, or (at your option) // any later version. // // The SC Toolkit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with the SC Toolkit; see the file COPYING.LIB. If not, write to // the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // // The U.S. Government is granted a limited license as per AL 91-7. // #ifdef HAVE_CONFIG_H #include <scconfig.h> #endif #include <util/container/avlset.h> #ifdef EXPLICIT_TEMPLATE_INSTANTIATION #define INST_COMP(T) \ template int compare(const T &, const T &) INST_COMP(int); INST_COMP(long); INST_COMP(double); INST_COMP(char); INST_COMP(unsigned char); template class EAVLMMapNode<int, AVLMapNode<int, int> >; template class EAVLMMap<int, AVLMapNode<int, int> >; template class AVLMapNode<int, int>; template class AVLMap<int, int>; template class AVLSet<int>; #endif
qsnake/mpqc
src/lib/util/container/avl.cc
C++
gpl-2.0
1,494
package org.anarres.qemu.qapi.api; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.anarres.qemu.qapi.common.*; /** * Autogenerated class. * * <pre>QApiStructDescriptor{name=NFSServer, data={type=NFSTransport, host=str}, innerTypes=null, fields=null, base=null}</pre> */ // QApiStructDescriptor{name=NFSServer, data={type=NFSTransport, host=str}, innerTypes=null, fields=null, base=null} @JsonInclude(JsonInclude.Include.NON_EMPTY) public class NFSServer extends QApiType { @SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") @JsonProperty("type") @Nonnull public NFSTransport type; @SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") @JsonProperty("host") @Nonnull public java.lang.String host; @Nonnull public NFSServer withType(NFSTransport value) { this.type = value; return this; } @Nonnull public NFSServer withHost(java.lang.String value) { this.host = value; return this; } public NFSServer() { } public NFSServer(NFSTransport type, java.lang.String host) { this.type = type; this.host = host; } @JsonIgnore @Override public java.util.List<java.lang.String> getFieldNames() { java.util.List<java.lang.String> names = super.getFieldNames(); names.add("type"); names.add("host"); return names; } @Override public Object getFieldByName(@Nonnull java.lang.String name) throws NoSuchFieldException { if ("type".equals(name)) return type; if ("host".equals(name)) return host; return super.getFieldByName(name); } }
shevek/qemu-java
qemu-qapi/src/main/java/org/anarres/qemu/qapi/api/NFSServer.java
Java
gpl-2.0
1,832
/* Copyright (C) 2013 Rainmeter Project Developers * * This Source Code Form is subject to the terms of the GNU General Public * License; either version 2 of the License, or (at your option) any later * version. If a copy of the GPL was not distributed with this file, You can * obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */ #include "StdAfx.h" #include "CanvasD2D.h" #include "TextFormatD2D.h" #include "Util/DWriteFontCollectionLoader.h" #include "Util/DWriteHelpers.h" #include "Util/WICBitmapLockGDIP.h" #include "../../Library/Util.h" namespace { D2D1_COLOR_F ToColorF(const Gdiplus::Color& color) { return D2D1::ColorF(color.GetR() / 255.0f, color.GetG() / 255.0f, color.GetB() / 255.0f, color.GetA() / 255.0f); } D2D1_RECT_F ToRectF(const Gdiplus::Rect& rect) { return D2D1::RectF((FLOAT)rect.X, (FLOAT)rect.Y, (FLOAT)(rect.X + rect.Width), (FLOAT)(rect.Y + rect.Height)); } D2D1_RECT_F ToRectF(const Gdiplus::RectF& rect) { return D2D1::RectF(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height); } } // namespace namespace Gfx { UINT CanvasD2D::c_Instances = 0; Microsoft::WRL::ComPtr<ID2D1Factory1> CanvasD2D::c_D2DFactory; Microsoft::WRL::ComPtr<IDWriteFactory1> CanvasD2D::c_DWFactory; Microsoft::WRL::ComPtr<IDWriteGdiInterop> CanvasD2D::c_DWGDIInterop; Microsoft::WRL::ComPtr<IWICImagingFactory> CanvasD2D::c_WICFactory; CanvasD2D::CanvasD2D() : Canvas(), m_Bitmap(), m_TextAntiAliasing(false), m_CanUseAxisAlignClip(false) { } CanvasD2D::~CanvasD2D() { Finalize(); } bool CanvasD2D::Initialize() { ++c_Instances; if (c_Instances == 1) { if (!IsWindows7OrGreater()) return false; D2D1_FACTORY_OPTIONS fo = {}; #ifdef _DEBUG fo.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; #endif HRESULT hr = D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, fo, c_D2DFactory.GetAddressOf()); if (FAILED(hr)) return false; hr = CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)c_WICFactory.GetAddressOf()); if (FAILED(hr)) return false; hr = DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(c_DWFactory), (IUnknown**)c_DWFactory.GetAddressOf()); if (FAILED(hr)) return false; hr = c_DWFactory->GetGdiInterop(c_DWGDIInterop.GetAddressOf()); if (FAILED(hr)) return false; hr = c_DWFactory->RegisterFontCollectionLoader(Util::DWriteFontCollectionLoader::GetInstance()); if (FAILED(hr)) return false; } return true; } void CanvasD2D::Finalize() { --c_Instances; if (c_Instances == 0) { c_D2DFactory.Reset(); c_WICFactory.Reset(); c_DWGDIInterop.Reset(); if (c_DWFactory) { c_DWFactory->UnregisterFontCollectionLoader(Util::DWriteFontCollectionLoader::GetInstance()); c_DWFactory.Reset(); } } } void CanvasD2D::Resize(int w, int h) { __super::Resize(w, h); m_Target.Reset(); m_Bitmap.Resize(w, h); m_GdipBitmap.reset(new Gdiplus::Bitmap(w, h, w * 4, PixelFormat32bppPARGB, m_Bitmap.GetData())); m_GdipGraphics.reset(new Gdiplus::Graphics(m_GdipBitmap.get())); } bool CanvasD2D::BeginDraw() { return true; } void CanvasD2D::EndDraw() { EndTargetDraw(); } bool CanvasD2D::BeginTargetDraw() { if (m_Target) return true; const D2D1_PIXEL_FORMAT format = D2D1::PixelFormat( DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED); const D2D1_RENDER_TARGET_PROPERTIES properties = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, format, 0.0f, // Default DPI 0.0f, // Default DPI D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE); // A new Direct2D render target must be created for each sequence of Direct2D draw operations // since we use GDI+ to render to the same pixel data. Without creating a new render target // each time, it has been found that Direct2D may overwrite the draws by GDI+ since it is // unaware of the changes made by GDI+. By creating a new render target and then releasing it // before the next GDI+ draw operations, we ensure that the pixel data result is as expected // Once GDI+ drawing is no longer needed, we change to recreate the render target only when the // bitmap size is changed. HRESULT hr = c_D2DFactory->CreateWicBitmapRenderTarget(&m_Bitmap, properties, &m_Target); if (SUCCEEDED(hr)) { SetTextAntiAliasing(m_TextAntiAliasing); m_Target->BeginDraw(); // Apply any transforms that occurred before creation of |m_Target|. UpdateTargetTransform(); return true; } return false; } void CanvasD2D::EndTargetDraw() { if (m_Target) { m_Target->EndDraw(); m_Target.Reset(); } } Gdiplus::Graphics& CanvasD2D::BeginGdiplusContext() { EndTargetDraw(); return *m_GdipGraphics; } void CanvasD2D::EndGdiplusContext() { } HDC CanvasD2D::GetDC() { EndTargetDraw(); HDC dcMemory = CreateCompatibleDC(nullptr); SelectObject(dcMemory, m_Bitmap.GetHandle()); return dcMemory; } void CanvasD2D::ReleaseDC(HDC dc) { DeleteDC(dc); } bool CanvasD2D::IsTransparentPixel(int x, int y) { if (!(x >= 0 && y >= 0 && x < m_W && y < m_H)) return false; bool transparent = true; DWORD* data = (DWORD*)m_Bitmap.GetData(); if (data) { DWORD pixel = data[y * m_W + x]; // Top-down DIB. transparent = (pixel & 0xFF000000) != 0; } return transparent; } void CanvasD2D::UpdateTargetTransform() { Gdiplus::Matrix gdipMatrix; m_GdipGraphics->GetTransform(&gdipMatrix); D2D1_MATRIX_3X2_F d2dMatrix; gdipMatrix.GetElements((Gdiplus::REAL*)&d2dMatrix); m_Target->SetTransform(d2dMatrix); m_CanUseAxisAlignClip = d2dMatrix._12 == 0.0f && d2dMatrix._21 == 0.0f && d2dMatrix._31 == 0.0f && d2dMatrix._32 == 0.0f; } void CanvasD2D::SetTransform(const Gdiplus::Matrix& matrix) { m_GdipGraphics->SetTransform(&matrix); if (m_Target) { UpdateTargetTransform(); } } void CanvasD2D::ResetTransform() { m_GdipGraphics->ResetTransform(); if (m_Target) { m_Target->SetTransform(D2D1::Matrix3x2F::Identity()); } } void CanvasD2D::RotateTransform(float angle, float x, float y, float dx, float dy) { m_GdipGraphics->TranslateTransform(x, y); m_GdipGraphics->RotateTransform(angle); m_GdipGraphics->TranslateTransform(dx, dy); if (m_Target) { UpdateTargetTransform(); } } void CanvasD2D::SetAntiAliasing(bool enable) { // TODO: Set m_Target aliasing? m_GdipGraphics->SetSmoothingMode( enable ? Gdiplus::SmoothingModeHighQuality : Gdiplus::SmoothingModeNone); m_GdipGraphics->SetPixelOffsetMode( enable ? Gdiplus::PixelOffsetModeHighQuality : Gdiplus::PixelOffsetModeDefault); } void CanvasD2D::SetTextAntiAliasing(bool enable) { // TODO: Add support for D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE? m_TextAntiAliasing = enable; if (m_Target) { m_Target->SetTextAntialiasMode( m_TextAntiAliasing ? D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE : D2D1_TEXT_ANTIALIAS_MODE_ALIASED); } } void CanvasD2D::Clear(const Gdiplus::Color& color) { if (!m_Target) // Use GDI+ if D2D render target has not been created. { m_GdipGraphics->Clear(color); return; } m_Target->Clear(ToColorF(color)); } void CanvasD2D::DrawTextW(const WCHAR* str, UINT strLen, const TextFormat& format, Gdiplus::RectF& rect, const Gdiplus::SolidBrush& brush, bool applyInlineFormatting) { if (!BeginTargetDraw()) return; Gdiplus::Color color; brush.GetColor(&color); Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush; HRESULT hr = m_Target->CreateSolidColorBrush(ToColorF(color), solidBrush.GetAddressOf()); if (FAILED(hr)) return; TextFormatD2D& formatD2D = (TextFormatD2D&)format; if (!formatD2D.CreateLayout( m_Target.Get(), str, strLen, rect.Width, rect.Height, !m_AccurateText && m_TextAntiAliasing)) return; D2D1_POINT_2F drawPosition; drawPosition.x = [&]() { if (!m_AccurateText) { const float xOffset = formatD2D.m_TextFormat->GetFontSize() / 6.0f; switch (formatD2D.GetHorizontalAlignment()) { case HorizontalAlignment::Left: return rect.X + xOffset; case HorizontalAlignment::Right: return rect.X - xOffset; } } return rect.X; } (); drawPosition.y = [&]() { // GDI+ compatibility. float yPos = rect.Y - formatD2D.m_LineGap; switch (formatD2D.GetVerticalAlignment()) { case VerticalAlignment::Bottom: yPos -= formatD2D.m_ExtraHeight; break; case VerticalAlignment::Center: yPos -= formatD2D.m_ExtraHeight / 2; break; } return yPos; } (); if (formatD2D.m_Trimming) { D2D1_RECT_F clipRect = ToRectF(rect); if (m_CanUseAxisAlignClip) { m_Target->PushAxisAlignedClip(clipRect, D2D1_ANTIALIAS_MODE_ALIASED); } else { const D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters(clipRect, nullptr, D2D1_ANTIALIAS_MODE_ALIASED); m_Target->PushLayer(layerParams, nullptr); } } // When different "effects" are used with inline coloring options, we need to // remove the previous inline coloring, then reapply them (if needed) - instead // of destroying/recreating the text layout. formatD2D.ResetInlineColoring(solidBrush.Get(), strLen); if (applyInlineFormatting) { formatD2D.ApplyInlineColoring(m_Target.Get(), &drawPosition); } m_Target->DrawTextLayout(drawPosition, formatD2D.m_TextLayout.Get(), solidBrush.Get()); if (applyInlineFormatting) { // Inline gradients require the drawing position, so in case that position // changes, we need a way to reset it after drawing time so on the next // iteration it will know the correct position. formatD2D.ResetGradientPosition(&drawPosition); } if (formatD2D.m_Trimming) { if (m_CanUseAxisAlignClip) { m_Target->PopAxisAlignedClip(); } else { m_Target->PopLayer(); } } } bool CanvasD2D::MeasureTextW(const WCHAR* str, UINT strLen, const TextFormat& format, Gdiplus::RectF& rect) { TextFormatD2D& formatD2D = (TextFormatD2D&)format; const DWRITE_TEXT_METRICS metrics = formatD2D.GetMetrics(str, strLen, !m_AccurateText); rect.Width = metrics.width; rect.Height = metrics.height; return true; } bool CanvasD2D::MeasureTextLinesW(const WCHAR* str, UINT strLen, const TextFormat& format, Gdiplus::RectF& rect, UINT& lines) { TextFormatD2D& formatD2D = (TextFormatD2D&)format; formatD2D.m_TextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP); const DWRITE_TEXT_METRICS metrics = formatD2D.GetMetrics(str, strLen, !m_AccurateText, rect.Width); rect.Width = metrics.width; rect.Height = metrics.height; lines = metrics.lineCount; if (rect.Height > 0.0f) { // GDI+ draws multi-line text even though the last line may be clipped slightly at the // bottom. This is a workaround to emulate that behaviour. rect.Height += 1.0f; } else { // GDI+ compatibility: Zero height text has no visible lines. lines = 0; } return true; } void CanvasD2D::DrawBitmap(Gdiplus::Bitmap* bitmap, const Gdiplus::Rect& dstRect, const Gdiplus::Rect& srcRect) { if (srcRect.Width != dstRect.Width || srcRect.Height != dstRect.Height) { // If the bitmap needs to be scaled, get rid of the D2D target and use the GDI+ code path // to draw the bitmap. This is due to antialiasing differences between GDI+ and D2D on // scaled bitmaps. EndTargetDraw(); } if (!m_Target) // Use GDI+ if D2D render target has not been created. { m_GdipGraphics->DrawImage( bitmap, dstRect, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, Gdiplus::UnitPixel); return; } // The D2D DrawBitmap seems to perform exactly like Gdiplus::Graphics::DrawImage since we are // not using a hardware accelerated render target. Nevertheless, we will use it to avoid // the EndDraw() call needed for GDI+ drawing. Util::WICBitmapLockGDIP* bitmapLock = new Util::WICBitmapLockGDIP(); Gdiplus::Rect lockRect(0, 0, bitmap->GetWidth(), bitmap->GetHeight()); Gdiplus::Status status = bitmap->LockBits( &lockRect, Gdiplus::ImageLockModeRead, PixelFormat32bppPARGB, bitmapLock->GetBitmapData()); if (status == Gdiplus::Ok) { D2D1_BITMAP_PROPERTIES props = D2D1::BitmapProperties( D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)); Microsoft::WRL::ComPtr<ID2D1Bitmap> d2dBitmap; HRESULT hr = m_Target->CreateSharedBitmap( __uuidof(IWICBitmapLock), bitmapLock, &props, d2dBitmap.GetAddressOf()); if (SUCCEEDED(hr)) { auto rDst = ToRectF(dstRect); auto rSrc = ToRectF(srcRect); m_Target->DrawBitmap(d2dBitmap.Get(), rDst, 1.0F, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, rSrc); } // D2D will still use the pixel data after this call (at the next Flush() or EndDraw()). bitmap->UnlockBits(bitmapLock->GetBitmapData()); } bitmapLock->Release(); } void CanvasD2D::DrawMaskedBitmap(Gdiplus::Bitmap* bitmap, Gdiplus::Bitmap* maskBitmap, const Gdiplus::Rect& dstRect, const Gdiplus::Rect& srcRect, const Gdiplus::Rect& srcRect2) { if (!BeginTargetDraw()) return; auto rDst = ToRectF(dstRect); auto rSrc = ToRectF(srcRect); Util::WICBitmapLockGDIP* bitmapLock = new Util::WICBitmapLockGDIP(); Gdiplus::Rect lockRect(srcRect2); Gdiplus::Status status = bitmap->LockBits( &lockRect, Gdiplus::ImageLockModeRead, PixelFormat32bppPARGB, bitmapLock->GetBitmapData()); if (status == Gdiplus::Ok) { D2D1_BITMAP_PROPERTIES props = D2D1::BitmapProperties( D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)); Microsoft::WRL::ComPtr<ID2D1Bitmap> d2dBitmap; HRESULT hr = m_Target->CreateSharedBitmap( __uuidof(IWICBitmapLock), bitmapLock, &props, d2dBitmap.GetAddressOf()); if (SUCCEEDED(hr)) { // Create bitmap brush from original |bitmap|. Microsoft::WRL::ComPtr<ID2D1BitmapBrush> brush; D2D1_BITMAP_BRUSH_PROPERTIES propertiesXClampYClamp = D2D1::BitmapBrushProperties( D2D1_EXTEND_MODE_CLAMP, D2D1_EXTEND_MODE_CLAMP, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR); // "Move" and "scale" the |bitmap| to match the destination. D2D1_MATRIX_3X2_F translate = D2D1::Matrix3x2F::Translation(rDst.left, rDst.top); D2D1_MATRIX_3X2_F scale = D2D1::Matrix3x2F::Scale( D2D1::SizeF((rDst.right - rDst.left) / (float)srcRect2.Width, (rDst.bottom - rDst.top) / (float)srcRect2.Height)); D2D1_BRUSH_PROPERTIES brushProps = D2D1::BrushProperties(1.0F, scale * translate); hr = m_Target->CreateBitmapBrush( d2dBitmap.Get(), propertiesXClampYClamp, brushProps, brush.GetAddressOf()); // Load the |maskBitmap| and use the bitmap brush to "fill" its contents. // Note: The image must be aliased when applying the opacity mask. if (SUCCEEDED(hr)) { Util::WICBitmapLockGDIP* maskBitmapLock = new Util::WICBitmapLockGDIP(); Gdiplus::Rect maskLockRect(0, 0, maskBitmap->GetWidth(), maskBitmap->GetHeight()); status = maskBitmap->LockBits( &maskLockRect, Gdiplus::ImageLockModeRead, PixelFormat32bppPARGB, maskBitmapLock->GetBitmapData()); if (status == Gdiplus::Ok) { D2D1_BITMAP_PROPERTIES maskProps = D2D1::BitmapProperties( D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)); Microsoft::WRL::ComPtr<ID2D1Bitmap> d2dMaskBitmap; hr = m_Target->CreateSharedBitmap( __uuidof(IWICBitmapLock), maskBitmapLock, &props, d2dMaskBitmap.GetAddressOf()); if (SUCCEEDED(hr)) { m_Target->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED); // required m_Target->FillOpacityMask( d2dMaskBitmap.Get(), brush.Get(), D2D1_OPACITY_MASK_CONTENT_GRAPHICS, &rDst, &rSrc); m_Target->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE); } maskBitmap->UnlockBits(bitmapLock->GetBitmapData()); } maskBitmapLock->Release(); } } bitmap->UnlockBits(bitmapLock->GetBitmapData()); } bitmapLock->Release(); } void CanvasD2D::FillRectangle(Gdiplus::Rect& rect, const Gdiplus::SolidBrush& brush) { if (!m_Target) // Use GDI+ if D2D render target has not been created. { m_GdipGraphics->FillRectangle(&brush, rect); return; } Gdiplus::Color color; brush.GetColor(&color); Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush; HRESULT hr = m_Target->CreateSolidColorBrush(ToColorF(color), solidBrush.GetAddressOf()); if (SUCCEEDED(hr)) { m_Target->FillRectangle(ToRectF(rect), solidBrush.Get()); } } } // namespace Gfx
tomkort/rainmeter
Common/Gfx/CanvasD2D.cpp
C++
gpl-2.0
16,684
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.IO; using System.Xml.Serialization; using System.Text; using System.Windows.Forms; using LJH.GeneralLibrary.Core.DAL; using LJH.GeneralLibrary.Core.UI; using LJH.Inventory.BusinessModel; namespace LJH.Inventory.UI.Forms { public partial class FrmMasterBaseEX : Form, IOperatorRender { public FrmMasterBaseEX() { InitializeComponent(); } #region 私有变量 protected List<object> _ShowingItems; protected List<object> _Items; private DataGridView _gridView; private Panel _PnlLeft; private Dictionary<string, int> _ColumnsSort = new Dictionary<string, int>(); //表示每一列的排序方式 private string _ColumnsConfig = System.IO.Path.Combine(Application.StartupPath, "ColumnsConf.xml"); private string _PnlLeftWidthConfig = System.IO.Path.Combine(Application.StartupPath, "PnlLeftWidthConf.xml"); #endregion. #region 私有方法 private void InitToolbar() { foreach (Control ctrl in this.Controls) { if (ctrl is ToolStrip && ctrl.Name == "menu") //初始化子窗体的菜单,如果有的话 { MenuStrip menu = ctrl as MenuStrip; if (menu.Items["btn_Add"] != null) menu.Items["btn_Add"].Click += btnAdd_Click; if (menu.Items["btn_Delete"] != null) menu.Items["btn_Delete"].Click += btnDelete_Click; if (menu.Items["btn_Export"] != null) menu.Items["btn_Export"].Click += btnExport_Click; if (menu.Items["btn_Fresh"] != null) menu.Items["btn_Fresh"].Click += btnFresh_Click; if (menu.Items["btn_SelectColumns"] != null) menu.Items["btn_SelectColumns"].Click += btnSelectColumns_Click; break; } } } private void InitGridView() { if (GridView != null) { if (ForSelect) { GridView.CellDoubleClick += GridView_DoubleClick1; } else { GridView.CellDoubleClick += GridView_DoubleClick; } GridView.CellMouseDown += GridView_CellMouseDown; GridView.Sorted += new EventHandler(GridView_Sorted); GridView.CellValueNeeded += GridView_CellValueNeeded; GridView.ColumnHeaderMouseClick += GridView_ColumnHeaderMouseClick; GridView.SelectionChanged += new EventHandler(GridView_SelectionChanged); if (GridView.ContextMenuStrip != null) { ContextMenuStrip menu = GridView.ContextMenuStrip; if (menu.Items["cMnu_Add"] != null) menu.Items["cMnu_Add"].Click += btnAdd_Click; if (menu.Items["cMnu_Edit"] != null) menu.Items["cMnu_Edit"].Click += btnEdit_Click; if (menu.Items["cMnu_Delete"] != null) menu.Items["cMnu_Delete"].Click += btnDelete_Click; if (menu.Items["cMnu_Export"] != null) menu.Items["cMnu_Export"].Click += btnExport_Click; if (menu.Items["cMnu_Fresh"] != null) menu.Items["cMnu_Fresh"].Click += btnFresh_Click; if (menu.Items["cMnu_SelectColumns"] != null) menu.Items["cMnu_SelectColumns"].Click += btnSelectColumns_Click; if (menu.Items["cMnu_SelectRows"] != null) { menu.Items["cMnu_SelectRows"].Visible = ForSelect; menu.Items["cMnu_SelectRows"].Click += cMnu_SelectRows_Click; } } } } private void InitGridViewColumns() { DataGridView grid = this.GridView; if (grid == null) return; string temp = GetConfig(_ColumnsConfig, string.Format("{0}_Columns", this.GetType().Name)); if (string.IsNullOrEmpty(temp)) return; string[] cols = temp.Split(','); int displayIndex = 0; for (int i = 0; i < cols.Length; i++) { string[] col_Temp = cols[i].Split(':'); if (col_Temp.Length >= 1 && grid.Columns.Contains(col_Temp[0])) { grid.Columns[col_Temp[0]].DisplayIndex = displayIndex; displayIndex++; if (col_Temp.Length >= 2 && col_Temp[1].Trim() == "0") { grid.Columns[col_Temp[0]].Visible = false; } else { grid.Columns[col_Temp[0]].Visible = true; } } } } private string[] GetAllVisiableColumns() { if (GridView != null) { List<string> cols = new List<string>(); foreach (DataGridViewColumn col in GridView.Columns) { if (col.Visible) cols.Add(col.Name); } return cols.ToArray(); } return null; } private void InitPnlLeft() { if (PnlLeft != null) { if (File.Exists(_PnlLeftWidthConfig)) { int temp = 0; string value = GetConfig(_PnlLeftWidthConfig, string.Format("{0}_PnlLeftWidth", this.GetType().Name)); if (!string.IsNullOrEmpty(value) && int.TryParse(value, out temp) && temp > 0) PnlLeft.Width = temp; } } } protected virtual List<object> FullTextSearch(List<object> data, string keyword) { if (string.IsNullOrEmpty(keyword)) return data; if (this.GridView == null) return data; if (data == null) return data; data = data.Where(item => { foreach (DataGridViewColumn col in GridView.Columns) { if (col.Visible) { object o = GetCellValue(item, col.Name); if (o != null && o.ToString().Contains(keyword)) return true; } } return false; }).ToList(); return data; } #endregion #region 公共属性 /// <summary> /// 获取或设置窗体是否是用来做选择用的,(此属性需要在窗体显示之前指定) /// </summary> public bool ForSelect { get; set; } /// <summary> /// 获取或设置窗体在选择模式下的选择项 /// </summary> public object SelectedItem { get; set; } /// <summary> /// 获取或设置是否支持多选 /// </summary> public bool MultiSelect { get; set; } /// <summary> /// 获取或设置查询条件 /// </summary> public SearchCondition SearchCondition { get; set; } #endregion #region 公共方法 /// <summary> /// 从数据库重新获取数据并刷新数据显示 /// </summary> public virtual void ReFreshData() { _Items = GetDataSource(); FreshView(); } /// <summary> /// 显示操作的权限 /// </summary> public virtual void ShowOperatorRights() { } #endregion #region 事件 public event EventHandler<ItemSelectedEventArgs> ItemSelected; #endregion #region 保护方法 /// <summary> /// 显示数据行的颜色 /// </summary> protected virtual void ShowRowBackColor() { int count = 0; foreach (DataGridViewRow row in this.GridView.Rows) { if (row.Visible) { count++; row.DefaultCellStyle.BackColor = (count % 2 == 1) ? Color.FromArgb(230, 230, 230) : Color.White; } } } /// <summary> /// 导出数据 /// </summary> protected virtual void ExportData() { try { if (GridView == null) return; SaveFileDialog dig = new SaveFileDialog(); dig.Filter = "Excel文档|*.xls;*.xlsx|所有文件(*.*)|*.*"; dig.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); if (dig.ShowDialog() == DialogResult.OK) { string path = dig.FileName; NPOIExcelHelper.Export(GridView, path, true); MessageBox.Show("导出成功"); } } catch (Exception ex) { MessageBox.Show("保存到电子表格时出现错误!"); } } /// <summary> /// 选择数据网格中要显示的列 /// </summary> protected virtual void SelectColumns() { FrmColumnSelection frm = new FrmColumnSelection(); frm.Selectee = this.GridView; frm.SelectedColumns = GetAllVisiableColumns(); if (frm.ShowDialog() == DialogResult.OK) { string[] cols = frm.SelectedColumns; if (cols != null && cols.Length > 0) { string temp = string.Join(",", cols); SaveConfig(_ColumnsConfig, string.Format("{0}_Columns", this.GetType().Name), temp); InitGridViewColumns(); } } } /// <summary> /// 进行删除数据操作 /// </summary> protected virtual void PerformDeleteData() { try { if (GridView == null) return; if (this.GridView.SelectedRows.Count > 0) { DialogResult result = MessageBox.Show("确实要删除所选项吗?", "确定", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { foreach (DataGridViewRow row in this.GridView.SelectedRows) { object item = GetRowTag(row); if (item != null && DeletingItem(item)) { row.Selected = false; _ShowingItems.Remove(item); _Items.Remove(item); } } GridView.RowCount = _ShowingItems.Count; GridView.Invalidate(); FreshStatusBar(); } } else { MessageBox.Show("没有选择项!", "Warning"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } /// <summary> /// 进行增加数据操作 /// </summary> protected virtual void PerformAddData() { try { FrmDetailBase detailForm = GetDetailForm(); if (detailForm != null) { detailForm.IsAdding = true; detailForm.ItemAdded += FrmDetail_ItemAdded; detailForm.ItemUpdated += FrmDetail_ItemUpdated; detailForm.ShowDialog(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } protected virtual void FrmDetail_ItemAdded(object obj, ItemAddedEventArgs args) { var item = args.AddedItem; if (_ShowingItems == null) _ShowingItems = new List<object>(); _ShowingItems.Insert(0, item); if (_Items == null) _Items = new List<object>(); _Items.Insert(0, item); if (GridView != null) { GridView.RowCount++; FreshStatusBar(); GridView.FirstDisplayedScrollingRowIndex = 0; foreach (DataGridViewRow r in GridView.SelectedRows) { r.Selected = false; } GridView.Rows[0].Selected = true; } } /// <summary> /// 进行修改数据操作 /// </summary> protected virtual void PerformUpdateData() { if (this.GridView != null && this.GridView.SelectedRows != null && this.GridView.SelectedRows.Count > 0) { var row = this.GridView.SelectedRows[0]; object pre = GetRowTag(row); if (pre != null) { FrmDetailBase detailForm = GetDetailForm(); if (detailForm != null) { detailForm.IsAdding = false; detailForm.UpdatingItem = pre; detailForm.ItemUpdated += FrmDetail_ItemUpdated; detailForm.ShowDialog(); } } } } protected virtual void FrmDetail_ItemUpdated(object obj, ItemUpdatedEventArgs args) { if (!object.ReferenceEquals(args.PreUpdatingItem, args.UpdatedItem)) FreshItem(args.PreUpdatingItem, args.UpdatedItem); //如果不是同一个对象 if (GridView != null) GridView.Invalidate(); } /// <summary> /// 更新本地数据里面的某个项 /// </summary> /// <param name="preVal"></param> /// <param name="newVal"></param> protected virtual void FreshItem(object preVal, object newVal) { try { var index = -1; if (preVal is SheetBase) index = _ShowingItems.FindIndex(it => (it as SheetBase).ID == (preVal as SheetBase).ID); else index = _ShowingItems.IndexOf(preVal); if (index >= 0) { _ShowingItems.RemoveAt(index); _ShowingItems.Insert(index, newVal); } if (preVal is SheetBase) index = _Items.FindIndex(it => (it as SheetBase).ID == (preVal as SheetBase).ID); else index = _Items.IndexOf(preVal); if (index >= 0) { _Items.RemoveAt(index); _Items.Insert(index, newVal); } } catch { } } /// <summary> /// 从某个配置文件中读取键为key的项的值 /// </summary> /// <param name="file"></param> /// <param name="key"></param> /// <returns></returns> protected string GetConfig(string file, string key) { string ret = null; if (File.Exists(file)) { try { XmlSerializer ser = new XmlSerializer(typeof(List<MyKeyValuePair>)); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { List<MyKeyValuePair> items = ser.Deserialize(fs) as List<MyKeyValuePair>; if (items != null && items.Count > 0) { MyKeyValuePair kv = items.SingleOrDefault(it => it.Key == key); ret = kv != null ? kv.Value : null; } } } catch (Exception ex) { LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); } } return ret; } /// <summary> /// 将某个配置保存到某个配置文件中 /// </summary> /// <param name="file"></param> /// <param name="key"></param> /// <param name="value"></param> protected void SaveConfig(string file, string key, string value) { try { XmlSerializer ser = new XmlSerializer(typeof(List<MyKeyValuePair>)); List<MyKeyValuePair> items = null; if (File.Exists(file)) { using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { items = ser.Deserialize(fs) as List<MyKeyValuePair>; } } if (items == null) items = new List<MyKeyValuePair>(); MyKeyValuePair kv = items.SingleOrDefault(it => it.Key == key); if (kv != null) { kv.Value = value; } else { items.Add(new MyKeyValuePair { Key = key, Value = value }); } using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { ser.Serialize(fs, items); } } catch (Exception ex) { LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); } } #endregion #region 子类要重写的方法 protected virtual Panel PnlLeft { get { if (_PnlLeft == null) { foreach (Control ctrl in this.Controls) { if (ctrl is Panel && ctrl.Name == "pnlLeft") { _PnlLeft = ctrl as Panel; break; } } } return _PnlLeft; } } protected virtual DataGridView GridView { get { if (_gridView == null) { foreach (Control ctrl in this.Controls) { if (ctrl is DataGridView) { _gridView = ctrl as DataGridView; } } } return _gridView; } } /// <summary> /// 初始化 /// </summary> protected virtual void Init() { ShowOperatorRights(); InitToolbar(); InitGridView(); InitGridViewColumns(); InitPnlLeft(); } /// <summary> /// 获取明细窗体 /// </summary> /// <returns></returns> protected virtual FrmDetailBase GetDetailForm() { return null; } /// <summary> /// 获取数据 /// </summary> /// <returns></returns> protected virtual List<object> GetDataSource() { return null; } protected virtual void FreshView() { _ShowingItems = _Items != null ? FilterData(_Items.ToList()) : null; if (GridView != null) { this.GridView.VirtualMode = true; this.GridView.RowCount = 0; this.GridView.RowCount = _ShowingItems != null ? _ShowingItems.Count : 0; this.GridView.Invalidate(); FreshStatusBar(); } } protected virtual List<object> FilterData(List<object> items) { return items; } protected virtual object GetCellValue(object item, string colName) { return null; } /// <summary> /// 刷新状态栏 /// </summary> protected virtual void FreshStatusBar() { this.toolStripStatusLabel1.Text = string.Format("总共 {0} 项", GridView.Rows.Count); } /// <summary> /// 删除数据 /// </summary> /// <param name="item"></param> /// <returns></returns> protected virtual bool DeletingItem(object item) { return false; } protected virtual object GetRowTag(DataGridViewRow r) { if (_ShowingItems.Count > r.Index) return _ShowingItems[r.Index]; return null; } protected virtual void SetRowStyle(DataGridViewRow row) { row.DefaultCellStyle.ForeColor = Color.Black; } #endregion #region 事件处理 private void FrmMasterBase_Load(object sender, EventArgs e) { Init(); if (GridView != null) //这一行不能少,如果没有这一行,窗体在设计时会出错 { btnFresh_Click(null, null); } } private void GridView_Sorted(object sender, EventArgs e) { ShowRowBackColor(); } private void btnAdd_Click(object sender, EventArgs e) { PerformAddData(); } private void btnEdit_Click(object sender, EventArgs e) { PerformUpdateData(); } private void btnDelete_Click(object sender, EventArgs e) { PerformDeleteData(); } private void btnFresh_Click(object sender, EventArgs e) { ReFreshData(); } private void btnExport_Click(object sender, EventArgs e) { ExportData(); } private void btnSelectColumns_Click(object sender, EventArgs e) { SelectColumns(); } private void cMnu_SelectRows_Click(object sender, EventArgs e) { if (GridView == null) return; foreach (DataGridViewRow row in GridView.SelectedRows) { var o = GetRowTag(row); if (o != null) { ItemSelectedEventArgs args = new ItemSelectedEventArgs() { SelectedItem = o }; if (this.ItemSelected != null) this.ItemSelected(this, args); row.Visible = false; } } } private void GridView_DoubleClick(object sender, DataGridViewCellEventArgs e) { PerformUpdateData(); } private void GridView_DoubleClick1(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { if (!MultiSelect) { this.SelectedItem = GetRowTag(this.GridView.Rows[e.RowIndex]); this.DialogResult = DialogResult.OK; this.Close(); } else { var item = GetRowTag(this.GridView.Rows[e.RowIndex]); ItemSelectedEventArgs args = new ItemSelectedEventArgs() { SelectedItem = item }; if (this.ItemSelected != null) this.ItemSelected(this, args); _ShowingItems.Remove(item); this.GridView.RowCount = _ShowingItems != null ? _ShowingItems.Count : 0; this.GridView.Invalidate(); FreshStatusBar(); } } } private void GridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) { try { if (e.RowIndex < _ShowingItems.Count) { object item = _ShowingItems[e.RowIndex]; GridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = (e.RowIndex % 2 == 1) ? Color.FromArgb(230, 230, 230) : Color.White; e.Value = GetCellValue(item, GridView.Columns[e.ColumnIndex].Name); SetRowStyle(GridView.Rows[e.RowIndex]); } else { GridView.Rows[e.RowIndex].Visible = false; } } catch (Exception ex) { } } private void GridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (_ShowingItems == null) return; if (GridView.Columns[e.ColumnIndex].SortMode != DataGridViewColumnSortMode.Automatic) return; if (!_ColumnsSort.ContainsKey(GridView.Columns[e.ColumnIndex].Name)) _ColumnsSort.Add(GridView.Columns[e.ColumnIndex].Name, 0); int sort = _ColumnsSort[GridView.Columns[e.ColumnIndex].Name]; if (sort != 1) { _ShowingItems = (from item in _ShowingItems let field = GetCellValue(item, GridView.Columns[e.ColumnIndex].Name) orderby field ascending select item).ToList(); _ColumnsSort[GridView.Columns[e.ColumnIndex].Name] = 1; //当前为升序 } else { _ShowingItems = (from item in _ShowingItems let field = GetCellValue(item, GridView.Columns[e.ColumnIndex].Name) orderby field descending select item).ToList(); _ColumnsSort[GridView.Columns[e.ColumnIndex].Name] = 2; //当前为降序 } GridView.Invalidate(); } private void GridView_SelectionChanged(object sender, EventArgs e) { var dgv = sender as DataGridView; for (int i = 0; i < dgv.RowCount; i++) { for (int j = 0; j < dgv.Columns.Count; j++) { if (dgv.Rows[i].Cells[j] is DataGridViewLinkCell) { var cell = dgv.Rows[i].Cells[j] as DataGridViewLinkCell; cell.LinkColor = cell.Selected ? Color.White : Color.Blue; } } } } private void GridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (e.RowIndex > -1) { foreach (DataGridViewRow row in GridView.SelectedRows) { row.Selected = false; } if (!GridView.Rows[e.RowIndex].Selected) { GridView.Rows[e.RowIndex].Selected = true; } } } } private void FrmMasterBase_FormClosed(object sender, FormClosedEventArgs e) { if (PnlLeft != null) { SaveConfig(_PnlLeftWidthConfig, string.Format("{0}_PnlLeftWidth", this.GetType().Name), PnlLeft.Width.ToString()); } } #endregion } }
ljh198275823/500-SteelRoll-Inventory
Source/LJH.Inventory.UI/Forms/FrmMasterBaseEX.cs
C#
gpl-2.0
27,659
<?php /* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */ namespace Icinga\Module\Monitoring\Backend\Ido\Query; class StatehistoryQuery extends IdoQuery { protected $types = array( 'soft_state' => 0, 'hard_state' => 1 ); protected $columnMap = array( 'statehistory' => array( 'raw_timestamp' => 'sh.state_time', 'timestamp' => 'UNIX_TIMESTAMP(sh.state_time)', 'state_time' => 'sh.state_time', 'object_id' => 'sho.object_id', 'type' => "(CASE WHEN sh.state_type = 1 THEN 'hard_state' ELSE 'soft_state' END)", 'state' => 'sh.state', 'state_type' => 'sh.state_type', 'output' => 'sh.output', 'attempt' => 'sh.current_check_attempt', 'max_attempts' => 'sh.max_check_attempts', 'host' => 'sho.name1 COLLATE latin1_general_ci', 'host_name' => 'sho.name1 COLLATE latin1_general_ci', 'service' => 'sho.name2 COLLATE latin1_general_ci', 'service_description' => 'sho.name2 COLLATE latin1_general_ci', 'service_host_name' => 'sho.name1 COLLATE latin1_general_ci', 'object_type' => "CASE WHEN sho.objecttype_id = 1 THEN 'host' ELSE 'service' END" ) ); public function whereToSql($col, $sign, $expression) { if ($col === 'UNIX_TIMESTAMP(sh.state_time)') { return 'sh.state_time ' . $sign . ' ' . $this->timestampForSql($this->valueToTimestamp($expression)); } elseif ($col === $this->columnMap['statehistory']['type'] && is_array($expression) === false && array_key_exists($expression, $this->types) === true ) { return 'sh.state_type ' . $sign . ' ' . $this->types[$expression]; } else { return parent::whereToSql($col, $sign, $expression); } } protected function joinBaseTables() { $this->select->from( array('sho' => $this->prefix . 'objects'), array() )->join( array('sh' => $this->prefix . 'statehistory'), 'sho.' . $this->object_id . ' = sh.' . $this->object_id . ' AND sho.is_active = 1', array() ); $this->joinedVirtualTables = array('statehistory' => true); } }
tunghoang/snmp-ts-stt-icingaweb2
modules/monitoring/library/Monitoring/Backend/Ido/Query/StatehistoryQuery.php
PHP
gpl-2.0
2,524
/* * Rvzware based in CAPAWARE 3D * * Rvzware is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * Rvzware is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this application; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * The Rvzware development team */ #include <sstream> #include <iosg/stdafx.h> #include <iosg/gui/OsgWidget.h> #include <iosg/OsgObjectRegistrySingleton.h> #include <cpw/common/ApplicationLog.h> using namespace cpw::iosg; unsigned int OsgIWidget::id=0; OsgIWidget::OsgIWidget(const std::string &url, const cpw::Point3d<float> &_position, const cpw::Point3d<float> &_size, const cpw::Point3d<float> &_rotation, const TAnchor &_anchor) : object(NULL), visible(true) { SetDefaultPath(url); unsigned int new_id = RequestId(); std::ostringstream temp; temp << new_id; id_string = temp.str(); osg::Matrix m; m.makeIdentity(); mt = new osg::MatrixTransform(); mt->setMatrix(m); anchor.x = _anchor.x; anchor.y = _anchor.y; anchor.w = _anchor.w; anchor.h = _anchor.h; ResizeScreen(20, 20); SetPosition(_position); SetSize(_size); scale.z = scale.y = scale.x = 1.0; SetRotation(_rotation); UpdateTransformationMatrix(); } OsgIWidget::~OsgIWidget(void) { } void OsgIWidget::SetObject(const std::string &filename) { if (object == NULL) { std::vector<osg::MatrixTransform *> mt_vec; // osg::ref_ptr<osg::Node> object; //if (obj_reg == NULL) // object = osgDB::readNodeFile(filename); //else OsgObjectRegistrySingleton *instance = OsgObjectRegistrySingleton::GetInstance(); if (instance) { OsgObjectRegistry *registry = instance->GetObjReg(); if (registry) { osg::Node *node = registry->GetObjectFromFile(filename); if (node) { object = (osg::Node *) node->clone(osg::CopyOp::DEEP_COPY_ALL); } } } if (object == NULL) { //ERROR, hay que controlar esto return; } osg::StateSet* stateset = object->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); object->setStateSet(stateset); OsgVisitorFirstGeode vfg; vfg.apply(*(object.get())); if (vfg.GetFoundGeode() == NULL) { //ERROR, hay que controlar esto return; } osg::Geode *geode = vfg.GetFoundGeode(); //grab the transformation osg::Node *temp_node = geode; while (temp_node->getNumParents() != 0) { temp_node = temp_node->getParent(0); std::string pname = temp_node->className(); if (temp_node->className() == std::string("MatrixTransform")) mt_vec.push_back((osg::MatrixTransform *) temp_node); } osg::Matrix tt_matrix; tt_matrix.makeIdentity(); for (std::vector<osg::MatrixTransform *>::iterator i = mt_vec.begin(); i != mt_vec.end(); i++) { tt_matrix = tt_matrix * (*i)->getMatrix(); } osg::BoundingBox bb = geode->getBoundingBox(); x_max = bb.xMax(); x_min = bb.xMin(); y_max = bb.yMax(); y_min = bb.yMin(); osg::Vec3 min(bb.xMin(), bb.yMin(), bb.zMin()); osg::Vec3 max(bb.xMax(), bb.yMax(), bb.zMax()); min = min * tt_matrix; max = max * tt_matrix; cpw::Point3d<float> new_scale; float xsize = max.x() - min.x(); float ysize = max.y() - min.y(); float zsize = max.z() - min.z(); new_scale.x = GetSize().x / xsize; new_scale.y = GetSize().y / ysize; new_scale.z = GetSize().z / zsize; SetScale(new_scale); sw = new osg::Switch(); sw->setAllChildrenOn(); sw->addChild(object.get()); GetMatrixTransform()->addChild(sw.get()); MarkTree(id_string, GetMatrixTransform()); UpdateTransformationMatrix(); } } void OsgIWidget::Move(const int &x, const int &y, const int &z) { } void OsgIWidget::Rotate(const int &x, const int &y, const int&z) { } void OsgIWidget::Scale(const int &x, const int &y, const int &z) { } void OsgIWidget::Update(osg::Matrix *mp) { //aqui es donde llega con la matriz propagada, no hace nada : UpdateTransformationMatrix(mp); } void OsgIWidget::UpdateTransformationMatrix(osg::Matrix *mp) { osg::Matrix m = mt->getMatrix(); osg::Matrix m_pos, m_scale, m_rotx, m_roty, m_rotz; m_rotx.makeRotate(rot.x, osg::Vec3(1.0, 0.0, 0.0)); m_roty.makeRotate(rot.y, osg::Vec3(0.0, 1.0, 0.0)); m_rotz.makeRotate(rot.z, osg::Vec3(0.0, 0.0, 1.0)); m_scale.makeScale(osg::Vec3(scale.x, scale.y, scale.z)); m_pos.makeTranslate(osg::Vec3(absolute_position.x, absolute_position.y, absolute_position.z)); mt->setMatrix(m_scale * m_rotx * m_roty * m_rotz * m_pos); if (mp != NULL) { //mt->setMatrix(mt->getMatrix() * (*mp)); osg::Matrix final_matrix = m_scale * m_rotx * m_roty * m_rotz * m_pos * (*mp); osg::Vec3 trans = final_matrix.getTrans(); osg::Vec3 scale = final_matrix.getScale(); //osg::Vec3 rotate = final_matrix.getR mt->setMatrix(final_matrix); //mt->setMatrix(*mp); } /* std::ostringstream debug_message; debug_message << "ap " << id_string << ": " << absolute_position.x << ", " << absolute_position.y; //cpw::ApplicationLog::GetInstance()->GetLogger()->NewLogMessage(debug_message.str()); */ } void OsgIWidget::SetPosition(const cpw::Point3d<float> &_position) { position = _position; absolute_position.x = (screen_x_size * anchor.w) + anchor.x + position.x; absolute_position.y = (screen_y_size * anchor.h) + anchor.y + position.y; absolute_position.z = position.z; UpdateTransformationMatrix(); } void OsgIWidget::SetSize(const cpw::Point3d<float> &_size) { cpw::Point3d<float> percent = _size; percent.x /= size.x; percent.y /= size.y; percent.z /= size.z; size = _size; //if (object != NULL) //{ scale.x *= percent.x; scale.y *= percent.y; scale.z *= percent.z; ////scale.x = size.x / (radius*2); ////scale.y = size.y / (radius*2); ////scale.z = size.z / (radius*2); //} UpdateTransformationMatrix(); } void OsgIWidget::SetRotation(const cpw::Point3d<float> &_rot) { rot = _rot; UpdateTransformationMatrix(); } void OsgIWidget::ResizeScreen(const int &x, const int &y) { screen_x_size = x; screen_y_size = y; SetPosition(position); } void OsgIWidget::SetAnchor(const float &w, const float &h, const int &offset_x, const int &offset_y) { anchor.w = w; anchor.h = h; anchor.x = offset_x; anchor.y = offset_y; SetPosition(position); //UpdateTransformationMatrix(); } void OsgIWidget::RotateX(const float &angle) { rot.x += angle; UpdateTransformationMatrix(); } void OsgIWidget::RotateY(const float &angle) { rot.y += angle; UpdateTransformationMatrix(); } void OsgIWidget::RotateZ(const float &angle) { rot.z += angle; UpdateTransformationMatrix(); } void OsgIWidget::MarkTree(const std::string &str, osg::Node *node) { node->setName(str); osg::Group *group = dynamic_cast<osg::Group *>(node); if (group != NULL) { for (unsigned int i=0; i<group->getNumChildren(); i++) MarkTree(str, group->getChild(i)); } else if (node->className() == std::string("Geode")) { osg::Geode *geode = (osg::Geode *) node; unsigned int drawable_count = geode->getNumDrawables(); for (unsigned int i=0; i<drawable_count; i++) { geode->getDrawable(i)->setName(str); } } } void OsgIWidget::GetBoundingBox(float &xmax, float &xmin, float &ymax, float &ymin) { xmax = x_max; xmin = x_min; ymax = y_max; ymin = y_min; } void OsgIWidget::SetVisible(const bool &_visible) { visible = _visible; if (sw != NULL) { if (visible) sw->setAllChildrenOn(); else sw->setAllChildrenOff(); } }
BackupTheBerlios/rvzware
src/iosg/gui/OsgWidget.cpp
C++
gpl-2.0
8,564
package freenet.node; import java.util.List; import java.util.Vector; import freenet.io.comm.Peer; public interface PacketFormat { boolean handleReceivedPacket(byte[] buf, int offset, int length, long now, Peer replyTo); /** * Maybe send something. A SINGLE PACKET. Don't send everything at once, for two reasons: * <ol> * <li>It is possible for a node to have a very long backlog.</li> * <li>Sometimes sending a packet can take a long time.</li> * <li>In the near future PacketSender will be responsible for output bandwidth throttling. So it makes sense to * send a single packet and round-robin.</li> * </ol> * @param ackOnly */ boolean maybeSendPacket(long now, Vector<ResendPacketItem> rpiTemp, int[] rpiIntTemp, boolean ackOnly) throws BlockedTooLongException; /** * Called when the peer has been disconnected. */ List<MessageItem> onDisconnect(); /** * Returns {@code false} if the packet format can't send packets because it must wait for some internal event. * For example, if a packet sequence number can not be allocated this method should return {@code false}, but if * nothing can be sent because there is no (external) data to send it should not. * Note that this only applies to packets being created from messages on the @see PeerMessageQueue. * @return {@code false} if the packet format can't send packets */ boolean canSend(); /** * @return The time at which the packet format will want to send an ack or similar. * 0 if there are already messages in flight. Long.MAX_VALUE if not supported or if * there is nothing to ack and nothing in flight. */ long timeNextUrgent(); void checkForLostPackets(); long timeCheckForLostPackets(); }
wnoisephx/fred-official
src/freenet/node/PacketFormat.java
Java
gpl-2.0
1,733
<?php /** * @package Gantry5 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license Dual License: MIT or GNU/GPLv2 and later * * http://opensource.org/licenses/MIT * http://www.gnu.org/licenses/gpl-2.0.html * * Gantry Framework code that extends GPL code is considered GNU/GPLv2 and later */ namespace Gantry\Component\Stylesheet; use Gantry\Component\Stylesheet\Less\Compiler; use Gantry\Framework\Base\Gantry; use RocketTheme\Toolbox\File\File; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; class LessCompiler extends CssCompiler { /** * @var string */ public $type = 'less'; /** * @var string */ public $name = 'LESS'; /** * @var Compiler */ protected $compiler; /** * Constructor. */ public function __construct() { parent::__construct(); $this->compiler = new Compiler(); if ($this->production) { $this->compiler->setFormatter('lessjs'); } else { $this->compiler->setFormatter('compressed'); $this->compiler->setPreserveComments(true); } } public function setFonts(array $fonts) { $this->fonts = $fonts; } public function compile($in) { return $this->compiler->compile($in); } public function resetCache() { } /** * @param string $in Filename without path or extension. * @return bool True if the output file was saved. */ public function compileFile($in) { // Buy some extra time as compilation may take a lot of time in shared environments. @set_time_limit(30); ob_start(); $gantry = Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; $out = $this->getCssUrl($in); $path = $locator->findResource($out, true, true); $file = File::instance($path); // Attempt to lock the file for writing. try { $file->lock(false); } catch (\Exception $e) { // Another process has locked the file; we will check this in a bit. } if ($file->locked() === false) { // File was already locked by another process, lets avoid compiling the same file twice. return false; } $paths = $locator->mergeResources($this->paths); // Set the lookup paths. $this->compiler->setBasePath($path); $this->compiler->setImportDir($paths); // Run the compiler. $this->compiler->setVariables($this->getVariables()); $css = $this->compiler->compileFile($in . '.less"'); $warnings = trim(ob_get_clean()); if ($warnings) { $this->warnings[$in] = explode("\n", $warnings); } if (!$this->production) { $warning = <<<WARN /* GANTRY5 DEVELOPMENT MODE ENABLED. WARNING: This file is automatically generated by Gantry5. Any modifications to this file will be lost! For more information on modifying CSS, please read: http://docs.gantry.org/gantry5/configure/styles http://docs.gantry.org/gantry5/tutorials/adding-a-custom-style-sheet */ WARN; $css = $warning . "\n\n" . $css; } $file->save($css); $file->unlock(); $file->free(); $this->createMeta($out, md5($css)); return true; } /** * @param string $name Name of function to register to the compiler. * @param callable $callback Function to run when called by the compiler. * @return $this */ public function registerFunction($name, callable $callback) { $this->compiler->registerFunction($name, $callback); return $this; } /** * @param string $name Name of function to unregister. * @return $this */ public function unregisterFunction($name) { $this->compiler->unregisterFunction($name); return $this; } }
JozefAB/neoacu
libraries/gantry5/classes/Gantry/Component/Stylesheet/LessCompiler.php
PHP
gpl-2.0
4,104
<?php /** * Generic icon view. * * @package Elgg * @subpackage Core * * @uses $vars['entity'] The entity the icon represents - uses getIconURL() method * @uses $vars['size'] topbar, tiny, small, medium (default), large, master * @uses $vars['href'] Optional override for link */ $entity = $vars['entity']; /* @var ElggObject $entity */ $sizes = array('small', 'medium', 'large', 'tiny', 'master', 'topbar'); $img_width = array('tiny' => 25, 'small' => 40, 'medium' => 100, 'large' => 200); // Get size if (!in_array($vars['size'], $sizes)) { $size = "medium"; } else { $size = $vars['size']; } if (isset($entity->name)) { $title = $entity->name; } else { $title = $entity->title; } $url = $entity->getURL(); if (isset($vars['href'])) { $url = $vars['href']; } $img_src = $entity->getIconURL($vars['size']); $img = "<img src=\"$img_src\" alt=\"$title\" width=\"{$img_width[$size]}\" />"; if ($url) { echo elgg_view('output/url', array( 'href' => $url, 'text' => $img, )); } else { echo $img; }
lorea/Elgg
mod/videolist/views/default/icon/object/videolist_item.php
PHP
gpl-2.0
1,025
package fr.inria.contraintes.biocham.modelData; import fr.inria.contraintes.biocham.BiochamDynamicTree; import fr.inria.contraintes.biocham.BiochamMainFrame; import fr.inria.contraintes.biocham.BiochamModel; import fr.inria.contraintes.biocham.BiochamModelElement; import fr.inria.contraintes.biocham.WorkbenchArea; import fr.inria.contraintes.biocham.customComponents.CustomToolTipButton; import fr.inria.contraintes.biocham.customComponents.DeleteButton; import fr.inria.contraintes.biocham.customComponents.ModifyButton; import fr.inria.contraintes.biocham.dialogs.DialogAddSpecification; import fr.inria.contraintes.biocham.graphicalEditor.Parser_SBGNRule2BiochamRule; import fr.inria.contraintes.biocham.menus.BiochamMenuBar; import fr.inria.contraintes.biocham.utils.SwingWorker; import fr.inria.contraintes.biocham.utils.Utils; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTree; import javax.swing.Spring; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; public class ParamTableRules implements Parameters, ActionListener{ private final static int H_CONST=70; private final static int W_CONST=10; Vector<Rule> rules; WorkbenchArea biocham; private JPanel panel; BiochamModel model; BiochamModelElement element; int savedResponses; boolean deleting=false, adding=false; ArrayList<String> uknownParams; Spring maxSpring; int north=0; HashMap<Integer,String> parentRules; boolean newAdded=false; boolean ignoreUndefinedParametersWarnings=false; boolean addRule=false; boolean fromGraph=false; int rulesCounter=0; boolean dontDraw=false; int counter=0; ModifyRule modifyListener; DeleteRule deleteListener; private boolean forDeleting=false; RulesModel rulesModel; RulesView view; public RulesView getView() { return view; } public void setView(RulesView view) { this.view = view; } public RulesModel getRulesModel() { return rulesModel; } public void setRulesModel(RulesModel rmodel) { this.rulesModel = rmodel; } private int calculatePreferredPanelHeight(){ int h=0; h=rules.size()*ParamTableRules.H_CONST; Utils.debugMsg("h="+h); return h; } private int calculatePreferredPanelWidth(){ int w=0; for(int i=0;i<rules.size();i++){ if(w<rules.get(i).getName().length()){ w=rules.get(i).getName().length(); } } w*=ParamTableRules.W_CONST; Utils.debugMsg("w="+w); return w; } public void setPanelPreferredSize(){ Dimension d=null; if(rules.size()>1){ d=new Dimension(calculatePreferredPanelWidth(),calculatePreferredPanelHeight()); }else{ d=new Dimension(100,100); } if(panel.getParent()!=null){ panel.getParent().setPreferredSize(d); Utils.debugMsg("PARENT IS NOT NULL"); }else{ Utils.debugMsg("PARENT ISSSSSS NULL"); }/*panel.setPreferredSize(null); panel.revalidate(); panel.repaint();*/ /*if(getPanel().getParent()!=null) getPanel().getParent().validate(); //getPanelCurrentX();getPanelCurrentY(); SwingWorker sw=new SwingWorker(){ @Override public Object construct() { Dimension d=new Dimension(getPanelCurrentX(),getPanelCurrentY()); getPanel().setPreferredSize(d); //getPanel().setLayout (null); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } d=null; return null; } @Override public void finished() { //getPanel().getParent().validate(); }}; sw.start(); //if(rules.size()<4) getPanel().setMaximumSize(new Dimension(100,80)); //getPanel().setMaximumSize(new Dimension(getPanelCurrentX(),getPanelCurrentY())); //getPanel().revalidate(); //getPanel().repaint(); */ } /*public int getPanelCurrentX(){ int x=(int) getPanel().getPreferredSize().getWidth(); int x=0; Spring maxSpring =null;// Spring.constant(10); SpringLayout layout = (SpringLayout) getPanel().getLayout(); int i=1; if(getPanel().getComponentCount()>3){ i=3; } maxSpring=layout.getConstraint(SpringLayout.WEST, getPanel().getComponent(getPanel().getComponentCount()-i)); x=maxSpring.getValue()+80; System.out.println("\nx="+x+"\n"); return x; } public int getPanelCurrentY(){ int y=(int) getPanel().getPreferredSize().getWidth(); int y=0; Spring maxSpring =null;// Spring.constant(10); SpringLayout layout = (SpringLayout) getPanel().getLayout(); maxSpring=layout.getConstraint(SpringLayout.NORTH, getPanel().getComponent(getPanel().getComponentCount()-1)); y=maxSpring.getValue()+80; System.out.println("\ny="+y+"\n"); return y; }*/ public ParamTableRules(BiochamModel m,WorkbenchArea workbench, JPanel p){ biocham=workbench; model=m; setPanel(p); rules=new Vector<Rule>(); element=model.getRules(); savedResponses=-1; uknownParams=new ArrayList<String>(); parentRules=new HashMap<Integer,String>(); Utils.modern.setBorderThickness(3); Utils.modern.enableAntiAliasing(true); modifyListener=new ModifyRule(); deleteListener=new DeleteRule(); rulesModel=new RulesModel(model); view=new RulesView(BiochamMainFrame.frame,rulesModel); } public String getName(int i) { return rules.get(i).getName(); } public String getValue(int i) { return rules.get(i).getValue(); } public int indexOf(String paramName) { int i=0; while (i<rules.size() && !getName(i).equals(paramName)) i++; if (i == rules.size()) return -1; return i; } public int indexOfExtendedPart(String paramName) { int i=0; while (i<rules.size() && !getValue(i).equals(paramName)) i++; if (i == rules.size()) return -1; return i; } public void resetParameter(String s) { //as the rule can't be modified, it can't be reseted to its original value too. } public void setValue(ArrayList list) { boolean b=SwingUtilities.isEventDispatchThread(); String arg1=((String) list.get(0)).trim(); String arg2=((String) list.get(1)).trim(); int i = indexOf(arg1); int j = indexOfExtendedPart(arg2); rulesModel.addRule(arg1, arg2); if(i<0 || j<0){ Rule rule=new Rule(arg1,arg2); rules.add(rule); BiochamModelElement element=model.getModelElement("Reactions"); if(i<0){ BiochamDynamicTree tree=new BiochamDynamicTree(arg1.trim()); tree.addRuleObject(rule); tree.setName(arg1); tree.tree.setName(arg1.trim()); element.addDtree(tree); getPanel().add(tree.tree); parentRules.put(rulesCounter,arg1.trim()); rulesCounter++; }else if(i>=0 && j<0){ Component[] comps=getPanel().getComponents(); for(int k=0;k<comps.length;k++){ if(comps[k].getName().equals(arg1)){ BiochamDynamicTree dtree=element.getDtree(arg1); dtree.addRuleObject(rule); //getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY())); //getPanel().revalidate(); break; } } comps=null; } //getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY())); //getPanel().revalidate(); }else{ //JOptionPane.showMessageDialog(BiochamMainFrame.frame,"\nThe rule "+arg1+" is already definied.\n"); } setFromGraph(false); refreshAfterAddingNew(); setNewAdded(false); //setPanelPreferredSize(); //getPanel().revalidate(); } public int size() { return rules.size(); } public void setModified(Component comp) { // There is no point yet of rule to be modified. } public class Rule{ private String name,value; Rule(String n,String v){ name=n; //the original rule value=v; //the expanded rule } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String toString() { return getValue(); } } class ModifyRule extends MouseAdapter{ public void mouseClicked(MouseEvent e) { Component button=(Component) e.getSource(); String name=button.getName(); modifyRule(name,true,true); button=null; name=null; } } class DeleteRule extends MouseAdapter{ public void mouseClicked(MouseEvent e) { int answ=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,"Are you sure you want to delete this reaction? ","Delete reaction rule",JOptionPane.YES_NO_OPTION); if(answ==JOptionPane.YES_OPTION){ Component button=(Component) e.getSource(); String name=button.getName(); deleteRule(name,true,true,true); button=null; name=null; } } } synchronized public JPanel refreshPanel(ArrayList cs) { int northBefore=25; Spring maxSpring = Spring.constant(BiochamModel.MIDDLE); int size=cs.size(); SpringLayout layout = (SpringLayout) getPanel().getLayout(); if(size!=0){ JTree jt; ArrayList<JTree> trees=new ArrayList<JTree>(); for(int i=0;i<size;i++){ if(cs.get(i) instanceof JTree){ trees.add((JTree)cs.get(i)); } } size=trees.size(); JTree treeBefore=null; for(int t=0;t<size;t++){ jt=trees.get(t); jt.setToolTipText("Show expanded rules..."); String s=jt.getName(); ArrayList<TreeNode> nodes = new ArrayList<TreeNode>(); TreeNode root = (TreeNode) jt.getModel().getRoot(); nodes.add(root); appendAllChildrenToList(nodes, root, true); jt.collapseRow(0); panel.add(jt); ModifyButton but1=new ModifyButton(); but1.setName(s); but1.addMouseListener(modifyListener); panel.add(but1); DeleteButton b2=new DeleteButton(); b2.setName(s); b2.addMouseListener(deleteListener); panel.add(b2); int nrthBefore=0; if(treeBefore!=null){ nrthBefore=layout.getConstraint(SpringLayout.NORTH,treeBefore).getValue(); } int p=1; if(t==0){ northBefore=25; }else{ p+=((DefaultMutableTreeNode)treeBefore.getModel().getRoot()).getChildCount(); northBefore=nrthBefore+p*treeBefore.getHeight()+20; } layout.putConstraint(SpringLayout.WEST, but1, 5, SpringLayout.WEST, panel); layout.putConstraint(SpringLayout.NORTH, but1, northBefore,SpringLayout.NORTH, panel); layout.putConstraint(SpringLayout.WEST, b2, 5, SpringLayout.EAST, but1); layout.putConstraint(SpringLayout.NORTH, b2, northBefore,SpringLayout.NORTH, panel); layout.putConstraint(SpringLayout.WEST, jt, 10, SpringLayout.EAST, b2); layout.putConstraint(SpringLayout.NORTH, jt, northBefore,SpringLayout.NORTH, panel); treeBefore=jt; nodes.clear(); nodes=null; s=null; root=null; } /*Component[] comps=getPanel().getComponents(); for(int i=0;i<comps.length/3;i++){ Spring x=Spring.sum(Spring.sum(layout.getConstraints(panel.getComponent(3*i)).getWidth(),Spring.constant(30)),Spring.constant(20)); System.out.println("********X-Spring="+x.getValue()); maxSpring = Spring.max(maxSpring, x); System.out.println("********maxX-Spring="+maxSpring.getValue()); // int v1=maxSpring.getValue(); } for(int i=0;i<comps.length/3;i++){ layout.putConstraint(SpringLayout.WEST, panel.getComponent(3*i+1), maxSpring, SpringLayout.WEST, panel); } int v1=maxSpring.getValue(); System.out.println("********maxX-Spring="+v1); comps=null; */ trees.clear(); trees=null; } String toolTipText="<html><i>Add a reaction rule to the current set of rules if any.</i></html>"; CustomToolTipButton addButton=new CustomToolTipButton("Add",toolTipText); addButton.setBalloonToolTipVisible(false); addButton.setName("Add"); addButton.setActionCommand("addRule"); addButton.addActionListener(this); toolTipText="<html><i>Shows kinetics in a separate window.</i></html>"; CustomToolTipButton showKineticsButton=new CustomToolTipButton("Show Kinetics",toolTipText); showKineticsButton.setBalloonToolTipVisible(false); showKineticsButton.setName("showKinetics"); showKineticsButton.setActionCommand("showKinetics"); showKineticsButton.addActionListener(biocham.tree.treeListener); toolTipText="<html><i>Export the kinetics to a file.</i></html>"; CustomToolTipButton exportKineticsButton=new CustomToolTipButton("Export Kinetics",toolTipText); exportKineticsButton.setBalloonToolTipVisible(false); exportKineticsButton.setName("exportKinetics"); exportKineticsButton.setActionCommand("exportKinetics"); exportKineticsButton.addActionListener(biocham.tree.treeListener); toolTipText="<html><i>Deletes all the reactions' rules.</i></html>"; CustomToolTipButton deleteAllButton=new CustomToolTipButton("Delete All",toolTipText); deleteAllButton.setBalloonToolTipVisible(false); deleteAllButton.setName("deleteAll"); deleteAllButton.setActionCommand("deleteAll"); deleteAllButton.addActionListener(this); toolTipText="<html><i>Launches the graphical reaction editor in a separate window.</i></html>"; CustomToolTipButton rgeButton=new CustomToolTipButton("Graphical Editor",toolTipText); rgeButton.setBalloonToolTipVisible(false); rgeButton.setName("launchGraphicalEditor"); rgeButton.setActionCommand("launchGraphicalEditor"); rgeButton.addActionListener(biocham.tree.treeListener); /*JLabel refreshButton=new JLabel(); refreshButton.setIcon(Icons.icons.get("Refresh3.png")); refreshButton.setName("refresh"); refreshButton.setText("Screen Refresh"); refreshButton.setForeground(Utils.refreshedColor); refreshButton.setToolTipText("Click to Refresh the Screen"); refreshButton.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent me) { refreshAfterAddingNew(); } }); */ if(panel.getComponents().length>0 && !(panel.getComponents()[0] instanceof JButton)){ //int len=getPanel().getComponents().length; //Spring n=layout.getConstraint(SpringLayout.NORTH,getPanel().getComponent(len-1)); panel.add(addButton); panel.add(showKineticsButton); panel.add(exportKineticsButton); panel.add(deleteAllButton); panel.add(rgeButton); int north=(northBefore+60); layout.putConstraint(SpringLayout.NORTH, addButton,north,SpringLayout.NORTH,panel); layout.putConstraint(SpringLayout.WEST, addButton, LEFT_OFF, SpringLayout.WEST, panel); layout.putConstraint(SpringLayout.NORTH, showKineticsButton, 0,SpringLayout.NORTH, addButton); layout.putConstraint(SpringLayout.WEST, showKineticsButton, 10, SpringLayout.EAST, addButton); layout.putConstraint(SpringLayout.NORTH, exportKineticsButton, 0,SpringLayout.NORTH, showKineticsButton); layout.putConstraint(SpringLayout.WEST, exportKineticsButton, 10, SpringLayout.EAST, showKineticsButton); layout.putConstraint(SpringLayout.NORTH, deleteAllButton, 0,SpringLayout.NORTH, exportKineticsButton); layout.putConstraint(SpringLayout.WEST, deleteAllButton, 10, SpringLayout.EAST, exportKineticsButton); layout.putConstraint(SpringLayout.NORTH, rgeButton, 0,SpringLayout.NORTH, deleteAllButton); layout.putConstraint(SpringLayout.WEST, rgeButton, 10, SpringLayout.EAST, deleteAllButton); }else{ panel.add(addButton); panel.add(rgeButton); layout.putConstraint(SpringLayout.NORTH, addButton, BiochamModel.HEIGHT,SpringLayout.NORTH, panel); layout.putConstraint(SpringLayout.NORTH, rgeButton, BiochamModel.HEIGHT,SpringLayout.NORTH, panel); layout.putConstraint(SpringLayout.WEST, addButton, 10, SpringLayout.WEST, panel); layout.putConstraint(SpringLayout.WEST, rgeButton, 10, SpringLayout.EAST, addButton); } //model.getRules().setSumChildren(sumChildren); //getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY())); /*if(!forDeleting){ setPanelPreferredSize(); }else{ forDeleting=false; getPanel().revalidate(); getPanel().repaint(); }*/ getPanel().revalidate(); getPanel().repaint(); //getPanel().revalidate(); BiochamMenuBar.refreshMenusContext(model); return panel; } private static void appendAllChildrenToList(ArrayList<TreeNode> nodes, TreeNode parent, boolean getChildChildren) { Enumeration children = parent.children(); if (children != null) { while (children.hasMoreElements()) { TreeNode node = (TreeNode) children.nextElement(); nodes.add(node); if (getChildChildren) { appendAllChildrenToList(nodes, node, getChildChildren); } } } } public void changeRules(final String oldRule, final String newRule){ SwingWorker sw=new SwingWorker(){ String s=""; @Override public Object construct() { setFromGraph(true); boolean has=false; String ruleToDelete=oldRule; if(oldRule.startsWith("{") && oldRule.endsWith("}")){ ruleToDelete=oldRule.substring(1,oldRule.length()-1); } if(oldRule.contains("<=")){ String tmp0=""; int ind=0; if(ruleToDelete.contains("for")){ tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+2); ind=ruleToDelete.indexOf("for")+2; } String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<")); String tmp0_1=""; if(ruleToDelete.contains("=[")){ tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("<="),ruleToDelete.indexOf("]")); } String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">")); ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r; } s="delete_rules({"+ruleToDelete+"}).\n"; model.sendToBiocham(s,"rules"); Component[] comps=getPanel().getComponents(); ArrayList cs=new ArrayList(); for(int i=0;i<comps.length;i++){ if(comps[i].getName().equals(oldRule)){ cs.add(comps[i]); } } for(int i=0;i<cs.size();i++){ if(cs.get(i) instanceof JTree){ JTree deletedTree=(JTree)cs.get(i); BiochamModelElement element=model.getModelElement("Reactions"); int ind=element.getNodeIndex(oldRule); if(ind>=0){ element.removeNodeDtree(ind); } JLabel delbut=(JLabel)cs.get(i+1); getPanel().remove(deletedTree); getPanel().remove(delbut); getPanel().validate(); } } forDeleting=true; int siz=rules.size(); ArrayList<Integer> al=new ArrayList<Integer>(); String cmd=""; for(int i=0;i<siz;i++){ if(rules.get(i).getName().equals(oldRule)){ if(has){ cmd+=","; } cmd+=rules.get(i).getValue(); has=true; al.add(i); } } siz=al.size(); for(int i=siz-1;i>=0;i--){ rules.removeElementAt(al.get(i)); } al.clear(); al=null; //oldRule+=","+cmd; comps=getPanel().getComponents(); cs.clear(); for(int i=0;i<comps.length;i++){ if((comps[i] instanceof JTree)){ cs.add(comps[i]); } } comps=null; getPanel().removeAll(); refreshPanel(cs); cs.clear(); cs=null; clearUknownParams(); /*try{ getPanel().getParent().validate(); getPanel().getParent().repaint(); }catch(Exception e){ e.printStackTrace(); }*/ return null; } @Override public void finished() { // at the end.. s="add_rules("+newRule+").\n"+"list_molecules.\n"; Parser_SBGNRule2BiochamRule.setDontDraw(true); model.sendToBiocham(s,"rules"); }}; sw.start(); } public void modifyRule(final String nmm,final boolean inGraphAlso, final boolean fromEverywhere){ String s = (String)JOptionPane.showInputDialog( BiochamMainFrame.frame, "", "Rule modification", JOptionPane.PLAIN_MESSAGE, null, null, nmm); // If a string was returned, say so. if ((s != null) && (s.length() > 0)) { deleteRule(nmm,true,true,false); sendRuleToBiocham(s); } } public void deleteRule(final String nmm,final boolean inGraphAlso, final boolean fromEverywhere,boolean verifyReversible) { boolean exit=false; forDeleting=true; try{ String s1=null, s2=null; String ruleToDelete=nmm; if(nmm.startsWith("{") && nmm.endsWith("}")){ ruleToDelete=nmm.substring(1,nmm.length()-1); } if(nmm.contains("<=")){ String rule1=null,rule2=null; for(int i=0;i<rules.size();i++){ if(rules.get(i).getName().equals(ruleToDelete)){ if(rule1==null){ rule1=rules.get(i).getValue(); }else{ rule2=rules.get(i).getValue(); break; } } } JCheckBox choice1 = new JCheckBox(rule1); choice1.setName(rule1); JCheckBox choice2 = new JCheckBox(rule2); choice2.setName(rule2); if(verifyReversible){ int answer=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,new Object[]{"Select which direction you want to delete:",choice1,choice2},"Delete Rule",JOptionPane.OK_CANCEL_OPTION); if(answer==JOptionPane.OK_OPTION){ //delete all the rule.... String tmp0=""; int ind=0; if(ruleToDelete.contains("for")){ tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+4); ind=ruleToDelete.indexOf("for")+4; } String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<")); String tmp0_1=""; if(ruleToDelete.contains("=[")){ tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("["),ruleToDelete.indexOf("]")+1); } String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">")+1); if(tmp0_1.equals("")){ ruleToDelete=tmp0+r+"=>"+p+","+tmp0+p+"=>"+r; }else{ ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r; } if(choice1.isSelected() && !choice2.isSelected()){ //delete all add just one..... s2="add_rules("+choice2.getName()+").\n list_molecules.\n"; }else if(!choice1.isSelected() && choice2.isSelected()){ //delete all add just one.... s2="add_rules("+choice1.getName()+").\n list_molecules.\n"; }else if(!choice1.isSelected() && !choice2.isSelected()){ //do nothing..... JOptionPane.showMessageDialog(BiochamMainFrame.frame, "You didn't choose any rule's direction to delete."); exit=true; } }else{ exit=true; } }else{ //delete all the rule.... String tmp0=""; int ind=0; if(ruleToDelete.contains("for")){ tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+4); ind=ruleToDelete.indexOf("for")+4; } String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<")); String tmp0_1=""; if(ruleToDelete.contains("=[")){ tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("["),ruleToDelete.indexOf("]")+1); } String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">")+1); if(tmp0_1.equals("")){ ruleToDelete=tmp0+r+"=>"+p+","+tmp0+p+"=>"+r; }else{ ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r; } } } if(!exit){ s1="delete_rules({"+ruleToDelete+"}).\n"; model.sendToBiocham(s1,"rules"); Component[] comps=getPanel().getComponents(); ArrayList cs=new ArrayList(); for(int i=0;i<comps.length;i++){ if(comps[i].getName().equals(nmm)){ cs.add(comps[i]); } } for(int i=0;i<cs.size();i++){ if(cs.get(i) instanceof JTree){ JTree deletedTree=(JTree)cs.get(i); BiochamModelElement element=model.getModelElement("Reactions"); int ind=element.getNodeIndex(nmm); if(ind>=0){ element.removeNodeDtree(ind); } JLabel delbut=(JLabel)cs.get(i+1); JLabel delbut2=(JLabel)cs.get(i+2); getPanel().remove(deletedTree); getPanel().remove(delbut); getPanel().remove(delbut2); } } try{ rules.removeElementAt(indexOf(nmm)); }catch(Exception e){ e.getStackTrace(); } if(nmm.contains("<=")){ try{ rules.removeElementAt(indexOf(nmm)); }catch(Exception e){} } comps=getPanel().getComponents(); cs.clear(); for(int i=0;i<comps.length;i++){ if((comps[i] instanceof JTree)){ cs.add(comps[i]); } } comps=null; getPanel().removeAll(); refreshPanel(cs); cs.clear(); cs=null; clearUknownParams(); for(int i=0;i<parentRules.size();i++){ if(parentRules.get(i)!=null && parentRules.get(i).equals(nmm)){ parentRules.remove(i); break; } } if(nmm.contains("<=")){ for(int i=0;i<parentRules.size();i++){ if(parentRules.get(i)!=null && parentRules.get(i).equals(nmm)){ parentRules.remove(i); break; } } } if(inGraphAlso && ruleToDelete!=null){ model.getGraphEditor().getGraph().deleteReaction(nmm,fromEverywhere); } if(s2!=null){ model.sendToBiocham(s2,"rules"); } } } catch(Exception e){ if(!exit){ model.getGraphEditor().getGraph().deleteReaction(nmm,fromEverywhere); } e.printStackTrace(); } BiochamMenuBar.refreshMenusContext(model); refreshAfterAddingNew(); } public void refreshAfterAddingNew() { ArrayList<Component> cs=new ArrayList<Component>(); Component[] comps=getPanel().getComponents(); for(int i=0;i<comps.length;i++){ if((comps[i] instanceof JTree)){ cs.add(comps[i]); } } getPanel().removeAll(); setPanel(refreshPanel(cs)); int o=getUknownParams().size(); if(o>0){ String s="Attention! These parameters have to be declared:"+"\n<html><font color=#4EE2EC>"; boolean exists=false; for(int i=0;i<o;i++){ s+=" "+getUknownParams().get(i); //add the rows for the uknown parameters..... int ukn=((ParamTableParameters)model.getParameters().getParamTable()).getUknown().size(); exists=false; for(int j=0;j<ukn;j++){ if(((ParamTableParameters)model.getParameters().getParamTable()).getUknown().get(j).equals(getUknownParams().get(i))){ exists=true; } } if(!exists){ ArrayList<String> sl=new ArrayList<String>(); sl.add(getUknownParams().get(i)); sl.add("You have to define the value of this parameter..."); ((ParamTableParameters)model.getParameters().getParamTable()).addUknownParameter(sl); sl.clear(); sl=null; } if(i<o-1){ s+=", "; } int m=(i+1)%4; if(m==0){ s+="<br> "; } } s+="</font><br><br></html>"; if(!isIgnoreUndefinedParametersWarnings() && !isAddRule()){ JOptionPane.showMessageDialog(BiochamMainFrame.frame, s); setAddRule(false); } //check if all molecules are declared.... if(!exists){ int molsSize=((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.size(); int initConcSize=((ParamTableInitConc)model.getInitConditions().getParamTable()).getInitConcentrations().size(); s=""; for(int i=0;i<molsSize;i++){ if(initConcSize==0){ s+="absent("+((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName()+").\n"; }else{ for(int j=0;j<initConcSize;j++){ if(!((ParamTableInitConc)model.getInitConditions().getParamTable()).getInitConcentrations().get(j).getName().equals(((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName())){ s+="absent("+((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName()+").\n"; } } } } model.sendToBiocham(s,"rules"); } } setPanelPreferredSize(); //getPanel().revalidate(); BiochamMenuBar.refreshMenusContext(model); } public int getSavedResponses() { return savedResponses; } public void setSavedResponses(int savedResponses) { this.savedResponses = savedResponses; } public void resetSavedResponses() { savedResponses=-1; } public boolean isDeleting() { return deleting; } public void setDeleting(boolean deleting) { this.deleting = deleting; } public boolean isAdding() { return adding; } public void setAdding(boolean adding) { this.adding = adding; } public Vector<Rule> getRules() { return rules; } public void addRule(Rule rule) { rules.add(rule); } public Rule createNewRule(String p, String v) { return new Rule(p,v); } public void disposeElements() { rules.clear(); rules=null; biocham=null; setPanel(null); model=null; element=null; uknownParams.clear(); uknownParams=null; parentRules.clear(); parentRules=null; } public ArrayList<String> getUknownParams() { return uknownParams; } public void clearUknownParams() { uknownParams.clear(); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="addRule"){ setFromGraph(false); model.getGraphEditor().getGraph().setAllAdded(false); addParameter(); BiochamMenuBar.refreshMenusContext(model); }else if(e.getActionCommand().equals("deleteAll")){ int asw=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,"Are you sure you want to delete all the model reactions?","Confirm",JOptionPane.YES_NO_OPTION); if(asw==JOptionPane.YES_OPTION){ /*for(int i=0;i<rules.size();i++){ model.sendToBiocham("delete_rules({"+rules.get(i).getName()+","+rules.get(i).getValue()+"}).\n"); }*/ model.sendToBiocham("clear_rules.\n"); model.sendToBiocham("list_molecules.\n"); rules.clear(); getPanel().removeAll(); ArrayList cs=new ArrayList(0); setPanel(refreshPanel(cs)); cs.clear(); cs=null; } } } public void addParameter() { model.getGraphEditor().getGraph().setAllAdded(false); setNewAdded(true); setSavedResponses(-1); element=model.getRules(); DialogAddSpecification adds=new DialogAddSpecification(BiochamMainFrame.frame, element, "Rules Operators",getPanel()); String value=adds.getFormula(); if(value!=null){ if(value.endsWith(".")){ value=value.substring(0,value.lastIndexOf(".")); } if(value!=null){ sendRuleToBiocham(value); } } } /** * @param value */ public void sendRuleToBiocham(String value) { ArrayList<Integer> al=new ArrayList<Integer>(); for(int k=0;k<rules.size();k++){ if(rules.get(k).getName().equals(value)){ al.add(k); } } for(int i=0;i<al.size();i++){ rules.removeElementAt(al.get(i)); } al.clear(); al=null; String s="add_rules("+value+").\n"; s+="list_molecules.\n"; model.sendToBiocham(s,"rules"); s=null; } public HashMap<Integer,String> getParentRules() { return parentRules; } public boolean isNewAdded() { return newAdded; } public void setNewAdded(boolean newAdded) { this.newAdded = newAdded; } public boolean isIgnoreUndefinedParametersWarnings() { return ignoreUndefinedParametersWarnings; } public void setIgnoreUndefinedParametersWarnings(boolean i) { this.ignoreUndefinedParametersWarnings = i; } public boolean isAddRule() { return addRule; } public void setAddRule(boolean addRule) { this.addRule = addRule; } public boolean isFromGraph() { return fromGraph; } public void setFromGraph(boolean fromGraph) { this.fromGraph = fromGraph; } public int getRulesCounter() { return rulesCounter; } public void setRulesCounter(int rulesCounter) { this.rulesCounter = rulesCounter; } public boolean isDontDraw() { return dontDraw; } public void setDontDraw(boolean dontDraw,int cnt) { this.counter=cnt; this.dontDraw = dontDraw; } public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; if(counter<=1){ this.dontDraw=false; } } public void setPanel(JPanel panel) { this.panel = panel; } public JPanel getPanel() { return panel; } }
Thomashuet/Biocham
gui/modelData/ParamTableRules.java
Java
gpl-2.0
32,668
<?php /* Template Name: Wide Header Image Page */ ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php if(get_the_post_thumbnail()): ?> <div class="wrapper-negative container-fluid wide-header"> <div class="row"> <div class="col-sm-12"> <?php the_post_thumbnail(full); ?> </div> </div> </div> <?php endif; ?> <?php get_template_part('templates/page', 'header'); ?> <div class="container wrapper"> <div class="row"> <div class="col-sm-12"> <?php the_content(); ?> </div> </div> </div> <?php endwhile; ?> <?php endif; ?>
vimpelli/novastar2015dev
wp-content/themes/novastar2015/templates/wideheaderimage.php
PHP
gpl-2.0
573
import { computed, toRefs } from '@vue/composition-api' export const useInputValueToggleProps = { label: { type: String }, options: { type: Array, default: () => ([ { value: 0 }, { value: 1, color: 'var(--primary)' } ]) }, hints: { type: Array } } export const useInputValueToggle = (valueProps, props, context) => { const { value: rxValue, onInput: rxOnInput } = valueProps const { options } = toRefs(props) // middleware const txValue = computed(() => options.value.findIndex(map => { if (!map.value && !rxValue.value) return true // compare False(y) w/ [null|undefined] else return `${map.value}` === `${rxValue.value}` // compare String(s) })) const txOnInput = value => { const { 0: { value: defaultValue } = {}, // 0th option is default [value]: { value: mappedValue } = {}, // map value (N) w/ Nth option [value]: { promise: mappedPromise } = {} // map promise } = options.value const rxValue = (mappedValue !== undefined) ? mappedValue : defaultValue if (mappedPromise) // handle Promise return mappedPromise(rxValue, props, context) else // otherwise emit return rxOnInput(rxValue) } // state const max = computed(() => `${options.value.length - 1}`) const label = computed(() => { const { 0: { label: defaultLabel } = {} , [txValue.value]: { label: mappedLabel } = {} } = options.value return mappedLabel || defaultLabel }) const color = computed(() => { const { 0: { color: defaultColor } = {} , [txValue.value]: { color: mappedColor } = {} } = options.value return mappedColor || defaultColor }) const icon = computed(() => { const { 0: { icon: defaultIcon } = {} , [txValue.value]: { icon: mappedIcon } = {} } = options.value return mappedIcon || defaultIcon }) const tooltip = computed(() => { const { 0: { tooltip: defaultTooltip } = {} , [txValue.value]: { tooltip: mappedTooltip } = {} } = options.value return mappedTooltip || defaultTooltip }) return { // middleware value: txValue, onInput: txOnInput, // state max, label, color, icon, tooltip } }
inverse-inc/packetfence
html/pfappserver/root/src/composables/useInputValueToggle.js
JavaScript
gpl-2.0
2,215
# -*- coding: utf-8 -*- """ *************************************************************************** v_univar.py --------------------- Date : December 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'December 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' def postProcessResults(alg): htmlFile = alg.getOutputFromName('html').value found = False f = open(htmlFile, "w") f.write("<h2>v.univar</h2>\n") for line in alg.consoleOutput: if found and not line.strip().endswith('exit'): f.write(line + "<br>\n") if 'v.univar' in line: found = True f.close()
bstroebl/QGIS
python/plugins/sextante/grass/ext/v_univar.py
Python
gpl-2.0
1,499
/* * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "QuestDef.h" #include "GameObject.h" #include "ObjectMgr.h" #include "PoolMgr.h" #include "SpellMgr.h" #include "Spell.h" #include "UpdateMask.h" #include "Opcodes.h" #include "WorldPacket.h" #include "World.h" #include "DatabaseEnv.h" #include "LootMgr.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "InstanceScript.h" #include "Battleground.h" #include "Util.h" #include "OutdoorPvPMgr.h" #include "BattlegroundAV.h" #include "ScriptMgr.h" GameObject::GameObject() : WorldObject(), m_goValue(new GameObjectValue) { m_objectType |= TYPEMASK_GAMEOBJECT; m_objectTypeId = TYPEID_GAMEOBJECT; m_updateFlag = (UPDATEFLAG_HAS_POSITION | UPDATEFLAG_POSITION | UPDATEFLAG_ROTATION); m_valuesCount = GAMEOBJECT_END; m_respawnTime = 0; m_respawnDelayTime = 300; m_lootState = GO_NOT_READY; m_spawnedByDefault = true; m_usetimes = 0; m_spellId = 0; m_cooldownTime = 0; m_goInfo = NULL; m_ritualOwner = NULL; m_goData = NULL; m_DBTableGuid = 0; m_rotation = 0; m_groupLootTimer = 0; lootingGroupLowGUID = 0; ResetLootMode(); // restore default loot mode } GameObject::~GameObject() { delete m_goValue; //if (m_uint32Values) // field array can be not exist if GameOBject not loaded // CleanupsBeforeDelete(); } void GameObject::CleanupsBeforeDelete(bool /*finalCleanup*/) { if (IsInWorld()) RemoveFromWorld(); if (m_uint32Values) // field array can be not exist if GameOBject not loaded { // Possible crash at access to deleted GO in Unit::m_gameobj if (uint64 owner_guid = GetOwnerGUID()) { Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid); if (owner) owner->RemoveGameObject(this,false); else { const char * ownerType = "creature"; if (IS_PLAYER_GUID(owner_guid)) ownerType = "player"; else if (IS_PET_GUID(owner_guid)) ownerType = "pet"; sLog.outError("Delete GameObject (GUID: %u Entry: %u SpellId %u LinkedGO %u) that lost references to owner (GUID %u Type '%s') GO list. Crash possible later.", GetGUIDLow(), GetGOInfo()->id, m_spellId, GetGOInfo()->GetLinkedGameObjectEntry(), GUID_LOPART(owner_guid), ownerType); } } } } void GameObject::AddToWorld() { ///- Register the gameobject for guid lookup if (!IsInWorld()) { if (m_zoneScript) m_zoneScript->OnGameObjectCreate(this, true); sObjectAccessor.AddObject(this); WorldObject::AddToWorld(); } } void GameObject::RemoveFromWorld() { ///- Remove the gameobject from the accessor if (IsInWorld()) { if (m_zoneScript) m_zoneScript->OnGameObjectCreate(this, false); // Possible crash at access to deleted GO in Unit::m_gameobj if (uint64 owner_guid = GetOwnerGUID()) { if (Unit * owner = GetOwner()) owner->RemoveGameObject(this,false); else sLog.outError("Delete GameObject (GUID: %u Entry: %u) that have references in not found creature %u GO list. Crash possible later.",GetGUIDLow(),GetGOInfo()->id,GUID_LOPART(owner_guid)); } WorldObject::RemoveFromWorld(); sObjectAccessor.RemoveObject(this); } } bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state, uint32 artKit) { ASSERT(map); SetMap(map); Relocate(x,y,z,ang); if (!IsPositionValid()) { sLog.outError("Gameobject (GUID: %u Entry: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)",guidlow,name_id,x,y); return false; } SetPhaseMask(phaseMask,false); SetZoneScript(); if (m_zoneScript) { name_id = m_zoneScript->GetGameObjectEntry(guidlow, name_id); if (!name_id) return false; } GameObjectInfo const* goinfo = sObjectMgr.GetGameObjectInfo(name_id); if (!goinfo) { sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f rotation0: %f rotation1: %f rotation2: %f rotation3: %f",guidlow, name_id, map->GetId(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3); return false; } Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT); m_goInfo = goinfo; if (goinfo->type >= MAX_GAMEOBJECT_TYPE) { sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist GO type '%u' in `gameobject_template`. It's will crash client if created.",guidlow,name_id,goinfo->type); return false; } SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0); SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1); UpdateRotationFields(rotation2,rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION, GAMEOBJECT_PARENTROTATION+2/3 SetFloatValue(OBJECT_FIELD_SCALE_X, goinfo->size); SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction); SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags); SetEntry(goinfo->id); SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId); // GAMEOBJECT_BYTES_1, index at 0, 1, 2 and 3 SetGoState(go_state); SetGoType(GameobjectTypes(goinfo->type)); SetGoArtKit(0); // unknown what this is SetByteValue(GAMEOBJECT_BYTES_1, 2, artKit); switch(goinfo->type) { case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING: m_goValue->building.health = goinfo->building.intactNumHits + goinfo->building.damagedNumHits; SetGoAnimProgress(255); break; case GAMEOBJECT_TYPE_TRANSPORT: SetUInt32Value(GAMEOBJECT_LEVEL, goinfo->transport.pause); if (goinfo->transport.startOpen) SetGoState(GO_STATE_ACTIVE); SetGoAnimProgress(animprogress); break; case GAMEOBJECT_TYPE_FISHINGNODE: SetGoAnimProgress(0); break; default: SetGoAnimProgress(animprogress); break; } LastUsedScriptID = GetGOInfo()->ScriptId; return true; } void GameObject::Update(uint32 diff) { if (IS_MO_TRANSPORT(GetGUID())) { //((Transport*)this)->Update(p_time); return; } switch (m_lootState) { case GO_NOT_READY: { switch(GetGoType()) { case GAMEOBJECT_TYPE_TRAP: { // Arming Time for GAMEOBJECT_TYPE_TRAP (6) GameObjectInfo const* goInfo = GetGOInfo(); // Bombs if (goInfo->trap.charges == 2) m_cooldownTime = time(NULL) + 10; // Hardcoded tooltip value else if (Unit* owner = GetOwner()) { if (owner->isInCombat()) m_cooldownTime = time(NULL) + goInfo->trap.startDelay; } m_lootState = GO_READY; break; } case GAMEOBJECT_TYPE_FISHINGNODE: { // fishing code (bobber ready) if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME) { // splash bobber (bobber ready now) Unit* caster = GetOwner(); if (caster && caster->GetTypeId() == TYPEID_PLAYER) { SetGoState(GO_STATE_ACTIVE); SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); UpdateData udata; udata.m_map = uint16(GetMapId()); WorldPacket packet; BuildValuesUpdateBlockForPlayer(&udata,caster->ToPlayer()); udata.BuildPacket(&packet); caster->ToPlayer()->GetSession()->SendPacket(&packet); SendCustomAnim(); } m_lootState = GO_READY; // can be successfully open with some chance } return; } default: m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY break; } // NO BREAK for switch (m_lootState) } case GO_READY: { if (m_respawnTime > 0) // timer on { if (m_respawnTime <= time(NULL)) // timer expired { m_respawnTime = 0; m_SkillupList.clear(); m_usetimes = 0; switch (GetGoType()) { case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now { Unit* caster = GetOwner(); if (caster && caster->GetTypeId() == TYPEID_PLAYER) { caster->FinishSpell(CURRENT_CHANNELED_SPELL); WorldPacket data(SMSG_FISH_ESCAPED,0); caster->ToPlayer()->GetSession()->SendPacket(&data); } // can be delete m_lootState = GO_JUST_DEACTIVATED; return; } case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds) if (GetGoState() != GO_STATE_READY) ResetDoorOrButton(); //flags in AB are type_button and we need to add them here so no break! default: if (!m_spawnedByDefault) // despawn timer { // can be despawned or destroyed SetLootState(GO_JUST_DEACTIVATED); return; } // respawn timer uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0; if (poolid) sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow()); else GetMap()->Add(this); break; } } } if (isSpawned()) { // traps can have time and can not have GameObjectInfo const* goInfo = GetGOInfo(); if (goInfo->type == GAMEOBJECT_TYPE_TRAP) { if (m_cooldownTime >= time(NULL)) return; // Type 2 - Bomb (will go away after casting it's spell) if (goInfo->trap.charges == 2) { if (goInfo->trap.spellId) CastSpell(NULL, goInfo->trap.spellId); // FIXME: null target won't work for target type 1 SetLootState(GO_JUST_DEACTIVATED); break; } // Type 0 and 1 - trap (type 0 will not get removed after casting a spell) Unit* owner = GetOwner(); Unit* ok = NULL; // pointer to appropriate target if found any bool IsBattlegroundTrap = false; //FIXME: this is activation radius (in different casting radius that must be selected from spell data) //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state float radius = (float)(goInfo->trap.radius)/2; // TODO rename radius to diameter (goInfo->trap.radius) should be (goInfo->trap.diameter) if (!radius) { if (goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call) return; else { if (m_respawnTime > 0) break; radius = (float)goInfo->trap.cooldown; // battlegrounds gameobjects has data2 == 0 && data5 == 3 IsBattlegroundTrap = true; if (!radius) return; } } // Note: this hack with search required until GO casting not implemented // search unfriendly creature if (owner) // hunter trap { Trinity::AnyUnfriendlyNoTotemUnitInObjectRangeCheck checker(this, owner, radius); Trinity::UnitSearcher<Trinity::AnyUnfriendlyNoTotemUnitInObjectRangeCheck> searcher(this, ok, checker); VisitNearbyGridObject(radius, searcher); if (!ok) VisitNearbyWorldObject(radius, searcher); } else // environmental trap { // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support // affect only players Player* player = NULL; Trinity::AnyPlayerInObjectRangeCheck checker(this, radius); Trinity::PlayerSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(this, player, checker); VisitNearbyWorldObject(radius, searcher); ok = player; } if (ok) { // some traps do not have spell but should be triggered if (goInfo->trap.spellId) CastSpell(ok, goInfo->trap.spellId); m_cooldownTime = time(NULL) + 4; // 4 seconds if (owner) // || goInfo->trap.charges == 1) SetLootState(GO_JUST_DEACTIVATED); if (IsBattlegroundTrap && ok->GetTypeId() == TYPEID_PLAYER) { //Battleground gameobjects case if (ok->ToPlayer()->InBattleground()) if (Battleground *bg = ok->ToPlayer()->GetBattleground()) bg->HandleTriggerBuff(GetGUID()); } } } else if (uint32 max_charges = goInfo->GetCharges()) { if (m_usetimes >= max_charges) { m_usetimes = 0; SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed } } } break; } case GO_ACTIVATED: { switch(GetGoType()) { case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: if (GetGOInfo()->GetAutoCloseTime() && (m_cooldownTime < time(NULL))) ResetDoorOrButton(); break; case GAMEOBJECT_TYPE_GOOBER: if (m_cooldownTime < time(NULL)) { RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); SetLootState(GO_JUST_DEACTIVATED); m_cooldownTime = 0; } break; case GAMEOBJECT_TYPE_CHEST: if (m_groupLootTimer) { if (m_groupLootTimer <= diff) { Group* group = sObjectMgr.GetGroupByGUID(lootingGroupLowGUID); if (group) group->EndRoll(&loot); m_groupLootTimer = 0; lootingGroupLowGUID = 0; } else m_groupLootTimer -= diff; } default: break; } break; } case GO_JUST_DEACTIVATED: { //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed if (GetGoType() == GAMEOBJECT_TYPE_GOOBER) { uint32 spellId = GetGOInfo()->goober.spellId; if (spellId) { std::set<uint32>::const_iterator it = m_unique_users.begin(); std::set<uint32>::const_iterator end = m_unique_users.end(); for (; it != end; ++it) { if (Unit* owner = Unit::GetUnit(*this, uint64(*it))) owner->CastSpell(owner, spellId, false); } m_unique_users.clear(); m_usetimes = 0; } SetGoState(GO_STATE_READY); //any return here in case battleground traps } if (GetOwnerGUID()) { if (Unit* owner = GetOwner()) { owner->RemoveGameObject(this, false); SetRespawnTime(0); Delete(); } return; } //burning flags in some battlegrounds, if you find better condition, just add it if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0) { SendObjectDeSpawnAnim(GetGUID()); //reset flags SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags); } loot.clear(); SetLootState(GO_READY); if (!m_respawnDelayTime) return; if (!m_spawnedByDefault) { m_respawnTime = 0; UpdateObjectVisibility(); return; } m_respawnTime = time(NULL) + m_respawnDelayTime; // if option not set then object will be saved at grid unload if (sWorld.getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY)) SaveRespawnTime(); UpdateObjectVisibility(); break; } } sScriptMgr.OnGameObjectUpdate(this, diff); } void GameObject::Refresh() { // not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway) if (m_respawnTime > 0 && m_spawnedByDefault) return; if (isSpawned()) GetMap()->Add(this); } void GameObject::AddUniqueUse(Player* player) { AddUse(); m_unique_users.insert(player->GetGUIDLow()); } void GameObject::Delete() { SetLootState(GO_NOT_READY); if (GetOwnerGUID()) if (Unit * owner = GetOwner()) owner->RemoveGameObject(this, false); ASSERT (!GetOwnerGUID()); SendObjectDeSpawnAnim(GetGUID()); SetGoState(GO_STATE_READY); SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags); uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0; if (poolid) sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow()); else AddObjectToRemoveList(); } void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner) { fishloot->clear(); uint32 zone, subzone; GetZoneAndAreaId(zone,subzone); // if subzone loot exist use it if (!fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner, true, true)) // else use zone loot (must exist in like case) fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner,true); } void GameObject::SaveToDB() { // this should only be used when the gameobject has already been loaded // preferably after adding to map, because mapid may not be valid otherwise GameObjectData const *data = sObjectMgr.GetGOData(m_DBTableGuid); if (!data) { sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!"); return; } SaveToDB(GetMapId(), data->spawnMask, data->phaseMask); } void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) { const GameObjectInfo *goI = GetGOInfo(); if (!goI) return; if (!m_DBTableGuid) m_DBTableGuid = GetGUIDLow(); // update in loaded data (changing data only in this place) GameObjectData& data = sObjectMgr.NewGOData(m_DBTableGuid); // data->guid = guid don't must be update at save data.id = GetEntry(); data.mapid = mapid; data.phaseMask = phaseMask; data.posX = GetPositionX(); data.posY = GetPositionY(); data.posZ = GetPositionZ(); data.orientation = GetOrientation(); data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0); data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1); data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2); data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3); data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime; data.animprogress = GetGoAnimProgress(); data.go_state = GetGoState(); data.spawnMask = spawnMask; data.artKit = GetGoArtKit(); // updated in DB std::ostringstream ss; ss << "INSERT INTO gameobject VALUES (" << m_DBTableGuid << ", " << GetEntry() << ", " << mapid << ", " << uint32(spawnMask) << "," // cast to prevent save as symbol << uint16(GetPhaseMask()) << "," // prevent out of range error << GetPositionX() << ", " << GetPositionY() << ", " << GetPositionZ() << ", " << GetOrientation() << ", " << GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", " << GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", " << GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", " << GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", " << m_respawnDelayTime << ", " << uint32(GetGoAnimProgress()) << ", " << uint32(GetGoState()) << ")"; SQLTransaction trans = WorldDatabase.BeginTransaction(); trans->PAppend("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid); trans->Append(ss.str().c_str()); WorldDatabase.CommitTransaction(trans); } bool GameObject::LoadFromDB(uint32 guid, Map *map) { GameObjectData const* data = sObjectMgr.GetGOData(guid); if (!data) { sLog.outErrorDb("Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid); return false; } uint32 entry = data->id; //uint32 map_id = data->mapid; // already used before call uint32 phaseMask = data->phaseMask; float x = data->posX; float y = data->posY; float z = data->posZ; float ang = data->orientation; float rotation0 = data->rotation0; float rotation1 = data->rotation1; float rotation2 = data->rotation2; float rotation3 = data->rotation3; uint32 animprogress = data->animprogress; GOState go_state = data->go_state; uint32 artKit = data->artKit; m_DBTableGuid = guid; if (map->GetInstanceId() != 0) guid = sObjectMgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT); if (!Create(guid,entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state, artKit)) return false; if (data->spawntimesecs >= 0) { m_spawnedByDefault = true; if (!GetGOInfo()->GetDespawnPossibility() && !GetGOInfo()->IsDespawnAtAction()) { SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN); m_respawnDelayTime = 0; m_respawnTime = 0; } else { m_respawnDelayTime = data->spawntimesecs; m_respawnTime = sObjectMgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId()); // ready to respawn if (m_respawnTime && m_respawnTime <= time(NULL)) { m_respawnTime = 0; sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0); } } } else { m_spawnedByDefault = false; m_respawnDelayTime = -data->spawntimesecs; m_respawnTime = 0; } m_goData = data; return true; } void GameObject::DeleteFromDB() { sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0); sObjectMgr.DeleteGOData(m_DBTableGuid); WorldDatabase.PExecute("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid); WorldDatabase.PExecute("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid); } GameObject* GameObject::GetGameObject(WorldObject& object, uint64 guid) { return object.GetMap()->GetGameObject(guid); } /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ bool GameObject::hasQuest(uint32 quest_id) const { QuestRelationBounds qr = sObjectMgr.GetGOQuestRelationBounds(GetEntry()); for (QuestRelations::const_iterator itr = qr.first; itr != qr.second; ++itr) { if (itr->second == quest_id) return true; } return false; } bool GameObject::hasInvolvedQuest(uint32 quest_id) const { QuestRelationBounds qir = sObjectMgr.GetGOQuestInvolvedRelationBounds(GetEntry()); for (QuestRelations::const_iterator itr = qir.first; itr != qir.second; ++itr) { if (itr->second == quest_id) return true; } return false; } bool GameObject::IsTransport() const { // If something is marked as a transport, don't transmit an out of range packet for it. GameObjectInfo const * gInfo = GetGOInfo(); if (!gInfo) return false; return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT; } // is Dynamic transport = non-stop Transport bool GameObject::IsDynTransport() const { // If something is marked as a transport, don't transmit an out of range packet for it. GameObjectInfo const * gInfo = GetGOInfo(); if (!gInfo) return false; return gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT || (gInfo->type == GAMEOBJECT_TYPE_TRANSPORT && !gInfo->transport.pause); } Unit* GameObject::GetOwner() const { return ObjectAccessor::GetUnit(*this, GetOwnerGUID()); } void GameObject::SaveRespawnTime() { if (m_goData && m_goData->dbData && m_respawnTime > time(NULL) && m_spawnedByDefault) sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime); } bool GameObject::isVisibleForInState(Player const* u, bool inVisibleList) const { // Not in world if (!IsInWorld() || !u->IsInWorld()) return false; // Transport always visible at this step implementation if (IsTransport() && IsInMap(u)) return true; // quick check visibility false cases for non-GM-mode if (!u->isGameMaster()) { // despawned and then not visible for non-GM in GM-mode if (!isSpawned()) return false; // special invisibility cases if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed) { Unit *owner = GetOwner(); if (owner && u->IsHostileTo(owner) && !canDetectTrap(u, GetDistance(u))) return false; } } // check distance return IsWithinDistInMap(u->m_seer,World::GetMaxVisibleDistanceForObject() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false); } bool GameObject::canDetectTrap(Player const* u, float distance) const { if (u->hasUnitState(UNIT_STAT_STUNNED)) return false; if (distance < GetGOInfo()->size) //collision return true; if (!u->HasInArc(M_PI, this)) //behind return false; if (u->HasAuraType(SPELL_AURA_DETECT_STEALTH)) return true; //Visible distance is modified by -Level Diff (every level diff = 0.25f in visible distance) float visibleDistance = (int32(u->getLevel()) - int32(GetOwner()->getLevel()))* 0.25f; //GetModifier for trap (miscvalue 1) //35y for aura 2836 //WARNING: these values are guessed, may be not blizzlike visibleDistance += u->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DETECT, 1)* 0.5f; return distance < visibleDistance; } void GameObject::Respawn() { if (m_spawnedByDefault && m_respawnTime > 0) { m_respawnTime = time(NULL); sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0); } } bool GameObject::ActivateToQuest(Player *pTarget) const { if (!sObjectMgr.IsGameObjectForQuests(GetEntry())) return false; switch (GetGoType()) { // scan GO chest with loot including quest items case GAMEOBJECT_TYPE_CHEST: { if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), pTarget)) { //TODO: fix this hack //look for battlegroundAV for some objects which are only activated after mine gots captured by own team if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S) if (Battleground *bg = pTarget->GetBattleground()) if (bg->GetTypeID(true) == BATTLEGROUND_AV && !(((BattlegroundAV*)bg)->PlayerCanDoMineQuest(GetEntry(),pTarget->GetTeam()))) return false; return true; } break; } case GAMEOBJECT_TYPE_GOOBER: { if (pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE || GetGOInfo()->goober.questId == -1) return true; break; } default: break; } return false; } void GameObject::TriggeringLinkedGameObject(uint32 trapEntry, Unit* target) { GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry); if (!trapInfo || trapInfo->type != GAMEOBJECT_TYPE_TRAP) return; SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId); if (!trapSpell) // checked at load already return; float range; SpellRangeEntry const * srentry = sSpellRangeStore.LookupEntry(trapSpell->rangeIndex); //get owner to check hostility of GameObject if (GetSpellMaxRangeForHostile(srentry) == GetSpellMaxRangeForHostile(srentry)) range = GetSpellMaxRangeForHostile(srentry); else { if (Unit *owner = GetOwner()) range = (float)owner->GetSpellMaxRangeForTarget(target, srentry); else //if no owner assume that object is hostile to target range = GetSpellMaxRangeForHostile(srentry); } // search nearest linked GO GameObject* trapGO = NULL; { // using original GO distance CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY())); Cell cell(p); cell.data.Part.reserved = ALL_DISTRICT; Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range); Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(this, trapGO,go_check); TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker); cell.Visit(p, object_checker, *GetMap(), *target, range); } // found correct GO if (trapGO) trapGO->CastSpell(target, trapInfo->trap.spellId); } GameObject* GameObject::LookupFishingHoleAround(float range) { GameObject* ok = NULL; CellPair p(Trinity::ComputeCellPair(GetPositionX(),GetPositionY())); Cell cell(p); cell.data.Part.reserved = ALL_DISTRICT; Trinity::NearestGameObjectFishingHole u_check(*this, range); Trinity::GameObjectSearcher<Trinity::NearestGameObjectFishingHole> checker(this, ok, u_check); TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::NearestGameObjectFishingHole>, GridTypeMapContainer > grid_object_checker(checker); cell.Visit(p, grid_object_checker, *GetMap(), *this, range); return ok; } void GameObject::ResetDoorOrButton() { if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED) return; SwitchDoorOrButton(false); SetLootState(GO_JUST_DEACTIVATED); m_cooldownTime = 0; } void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */) { if (m_lootState != GO_READY) return; if (!time_to_restore) time_to_restore = GetGOInfo()->GetAutoCloseTime(); SwitchDoorOrButton(true,alternative); SetLootState(GO_ACTIVATED); m_cooldownTime = time(NULL) + time_to_restore; } void GameObject::SetGoArtKit(uint8 kit) { SetByteValue(GAMEOBJECT_BYTES_1, 2, kit); GameObjectData *data = const_cast<GameObjectData*>(sObjectMgr.GetGOData(m_DBTableGuid)); if (data) data->artKit = kit; } void GameObject::SetGoArtKit(uint8 artkit, GameObject *go, uint32 lowguid) { const GameObjectData *data = NULL; if (go) { go->SetGoArtKit(artkit); data = go->GetGOData(); } else if (lowguid) data = sObjectMgr.GetGOData(lowguid); if (data) const_cast<GameObjectData*>(data)->artKit = artkit; } void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */) { if (activate) SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); else RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); if (GetGoState() == GO_STATE_READY) //if closed -> open SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE); else //if open -> close SetGoState(GO_STATE_READY); } void GameObject::Use(Unit* user) { // by default spell caster is user Unit* spellCaster = user; uint32 spellId = 0; bool triggered = false; switch(GetGoType()) { case GAMEOBJECT_TYPE_DOOR: //0 case GAMEOBJECT_TYPE_BUTTON: //1 //doors/buttons never really despawn, only reset to default state/flags UseDoorOrButton(); // activate script GetMap()->ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this); return; case GAMEOBJECT_TYPE_QUESTGIVER: //2 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID); player->SendPreparedGossip(this); return; } //Sitting: Wooden bench, chairs enzz case GAMEOBJECT_TYPE_CHAIR: //7 { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (user->GetTypeId() != TYPEID_PLAYER) return; if (!ChairListSlots.size()) // this is called once at first chair use to make list of available slots { if (info->chair.slots > 0) // sometimes chairs in DB have error in fields and we dont know number of slots for (uint32 i = 0; i < info->chair.slots; ++i) ChairListSlots[i] = 0; // Last user of current slot set to 0 (none sit here yet) else ChairListSlots[0] = 0; // error in DB, make one default slot } Player* player = (Player*)user; // a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one float lowestDist = DEFAULT_VISIBILITY_DISTANCE; uint32 nearest_slot = 0; float x_lowest = GetPositionX(); float y_lowest = GetPositionY(); // the object orientation + 1/2 pi // every slot will be on that straight line float orthogonalOrientation = GetOrientation()+M_PI*0.5f; // find nearest slot bool found_free_slot = false; for (ChairSlotAndUser::iterator itr = ChairListSlots.begin(); itr != ChairListSlots.end(); ++itr) { // the distance between this slot and the center of the go - imagine a 1D space float relativeDistance = (info->size*itr->first)-(info->size*(info->chair.slots-1)/2.0f); float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation); float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation); if (itr->second) { if (Player* ChairUser = sObjectMgr.GetPlayer(itr->second)) if (ChairUser->IsSitState() && ChairUser->getStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f) continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->getStandState() != UNIT_STAND_STATE_SIT check is required. else itr->second = 0; // This seat is unoccupied. else itr->second = 0; // The seat may of had an occupant, but they're offline. } found_free_slot = true; // calculate the distance between the player and this slot float thisDistance = player->GetDistance2d(x_i, y_i); /* debug code. It will spawn a npc on each slot to visualize them. Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000); std::ostringstream output; output << i << ": thisDist: " << thisDistance; helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0); */ if (thisDistance <= lowestDist) { nearest_slot = itr->first; lowestDist = thisDistance; x_lowest = x_i; y_lowest = y_i; } } if (found_free_slot) { ChairSlotAndUser::iterator itr = ChairListSlots.find(nearest_slot); if (itr != ChairListSlots.end()) { itr->second = player->GetGUID(); //this slot in now used by player player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height); return; } } //else //player->GetSession()->SendNotification("There's nowhere left for you to sit."); return; } //big gun, its a spell/aura case GAMEOBJECT_TYPE_GOOBER: //10 { GameObjectInfo const* info = GetGOInfo(); if (user->GetTypeId() == TYPEID_PLAYER) { Player* player = (Player*)user; if (info->goober.pageId) // show page... { WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8); data << GetGUID(); player->GetSession()->SendPacket(&data); } else if (info->goober.gossipID) { player->PrepareGossipMenu(this, info->goober.gossipID); player->SendPreparedGossip(this); } if (info->goober.eventId) { sLog.outDebug("Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetDBTableGUIDLow()); GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this); EventInform(info->goober.eventId); } // possible quest objective for active quests if (info->goober.questId && sObjectMgr.GetQuestTemplate(info->goober.questId)) { //Quest require to be active for GO using if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE) break; } if (Battleground* bg = player->GetBattleground()) bg->EventPlayerUsedGO(player, this); player->CastedCreatureOrGO(info->id, GetGUID(), 0); } if (uint32 trapEntry = info->goober.linkedTrapId) TriggeringLinkedGameObject(trapEntry, user); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); SetLootState(GO_ACTIVATED); uint32 time_to_restore = info->GetAutoCloseTime(); // this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389) if (time_to_restore && info->goober.customAnim) SendCustomAnim(); else SetGoState(GO_STATE_ACTIVE); m_cooldownTime = time(NULL) + time_to_restore; // cast this spell later if provided spellId = info->goober.spellId; spellCaster = NULL; break; } case GAMEOBJECT_TYPE_CAMERA: //13 { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (info->camera.cinematicId) player->SendCinematicStart(info->camera.cinematicId); if (info->camera.eventID) GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this); return; } //fishing bobber case GAMEOBJECT_TYPE_FISHINGNODE: //17 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->GetGUID() != GetOwnerGUID()) return; switch(getLootState()) { case GO_READY: // ready for loot { uint32 zone, subzone; GetZoneAndAreaId(zone,subzone); int32 zone_skill = sObjectMgr.GetFishingBaseSkillLevel(subzone); if (!zone_skill) zone_skill = sObjectMgr.GetFishingBaseSkillLevel(zone); //provide error, no fishable zone or area should be 0 if (!zone_skill) sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone); int32 skill = player->GetSkillValue(SKILL_FISHING); int32 chance; if (skill < zone_skill) { chance = int32(pow((double)skill/zone_skill,2) * 100); if (chance < 1) chance = 1; } else chance = 100; int32 roll = irand(1,100); sLog.outStaticDebug("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll); // but you will likely cause junk in areas that require a high fishing skill (not yet implemented) if (chance >= roll) { player->UpdateFishingSkill(); // prevent removing GO at spell cancel player->RemoveGameObject(this,false); SetOwnerGUID(player->GetGUID()); //TODO: find reasonable value for fishing hole search GameObject* ok = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); if (ok) { ok->Use(player); SetLootState(GO_JUST_DEACTIVATED); } else player->SendLoot(GetGUID(),LOOT_FISHING); } // TODO: else: junk break; } case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update break; default: { SetLootState(GO_JUST_DEACTIVATED); WorldPacket data(SMSG_FISH_NOT_HOOKED, 0); player->GetSession()->SendPacket(&data); break; } } player->FinishSpell(CURRENT_CHANNELED_SPELL); return; } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; Unit* owner = GetOwner(); GameObjectInfo const* info = GetGOInfo(); // ritual owner is set for GO's without owner (not summoned) if (!m_ritualOwner && !owner) m_ritualOwner = player; if (owner) { if (owner->GetTypeId() != TYPEID_PLAYER) return; // accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect) if (player == owner->ToPlayer() || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(owner->ToPlayer()))) return; // expect owner to already be channeling, so if not... if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) return; // in case summoning ritual caster is GO creator spellCaster = owner; } else { if (player != m_ritualOwner && (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(m_ritualOwner))) return; spellCaster = player; } AddUniqueUse(player); if (info->summoningRitual.animSpell) { player->CastSpell(player, info->summoningRitual.animSpell, true); // for this case, summoningRitual.spellId is always triggered triggered = true; } // full amount unique participants including original summoner if (GetUniqueUseCount() == info->summoningRitual.reqParticipants) { spellCaster = m_ritualOwner ? m_ritualOwner : spellCaster; spellId = info->summoningRitual.spellId; if (spellId == 62330) // GO store nonexistent spell, replace by expected { // spell have reagent and mana cost but it not expected use its // it triggered spell in fact casted at currently channeled GO spellId = 61993; triggered = true; } // finish owners spell if (owner) owner->FinishSpell(CURRENT_CHANNELED_SPELL); // can be deleted now, if if (!info->summoningRitual.ritualPersistent) SetLootState(GO_JUST_DEACTIVATED); else { // reset ritual for this GO m_ritualOwner = NULL; m_unique_users.clear(); m_usetimes = 0; } } else return; // go to end function to spell casting break; } case GAMEOBJECT_TYPE_SPELLCASTER: //22 { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (info->spellcaster.partyOnly) { Unit* caster = GetOwner(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) return; if (user->GetTypeId() != TYPEID_PLAYER || !user->ToPlayer()->IsInSameRaidWith(caster->ToPlayer())) return; } spellId = info->spellcaster.spellId; AddUse(); break; } case GAMEOBJECT_TYPE_MEETINGSTONE: //23 { GameObjectInfo const* info = GetGOInfo(); if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelection()); // accept only use by player from same raid as caster, except caster itself if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameRaidWith(player)) return; //required lvl checks! uint8 level = player->getLevel(); if (level < info->meetingstone.minLevel) return; level = targetPlayer->getLevel(); if (level < info->meetingstone.minLevel) return; if (info->id == 194097) spellId = 61994; // Ritual of Summoning else spellId = 59782; // Summoning Stone Effect break; } case GAMEOBJECT_TYPE_FLAGSTAND: // 24 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->CanUseBattlegroundObject()) { // in battleground check Battleground *bg = player->GetBattleground(); if (!bg) return; if (player->GetVehicle()) return; // BG flag click // AB: // 15001 // 15002 // 15003 // 15004 // 15005 bg->EventPlayerClickedOnFlag(player, this); return; //we don;t need to delete flag ... it is despawned! } break; } case GAMEOBJECT_TYPE_FISHINGHOLE: // 25 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; player->SendLoot(GetGUID(), LOOT_FISHINGHOLE); player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->id); return; } case GAMEOBJECT_TYPE_FLAGDROP: // 26 { if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; if (player->CanUseBattlegroundObject()) { // in battleground check Battleground *bg = player->GetBattleground(); if (!bg) return; if( player->GetVehicle()) return; // BG flag dropped // WS: // 179785 - Silverwing Flag // 179786 - Warsong Flag // EotS: // 184142 - Netherstorm Flag GameObjectInfo const* info = GetGOInfo(); if (info) { switch(info->id) { case 179785: // Silverwing Flag // check if it's correct bg if (bg->GetTypeID(true) == BATTLEGROUND_WS) bg->EventPlayerClickedOnFlag(player, this); break; case 179786: // Warsong Flag if (bg->GetTypeID(true) == BATTLEGROUND_WS) bg->EventPlayerClickedOnFlag(player, this); break; case 184142: // Netherstorm Flag if (bg->GetTypeID(true) == BATTLEGROUND_EY) bg->EventPlayerClickedOnFlag(player, this); break; } } //this cause to call return, all flags must be deleted here!! spellId = 0; Delete(); } break; } case GAMEOBJECT_TYPE_BARBER_CHAIR: //32 { GameObjectInfo const* info = GetGOInfo(); if (!info) return; if (user->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)user; // fallback, will always work player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET); WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0); player->GetSession()->SendPacket(&data); player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight); return; } default: sLog.outDebug("Unknown Object Type %u", GetGoType()); break; } if (!spellId) return; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) { if (user->GetTypeId() != TYPEID_PLAYER || !sOutdoorPvPMgr.HandleCustomSpell((Player*)user,spellId,this)) sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u)", spellId,GetEntry(),GetGoType()); else sLog.outDebug("WORLD: %u non-dbc spell was handled by OutdoorPvP", spellId); return; } if (spellCaster) spellCaster->CastSpell(user, spellInfo, triggered); else CastSpell(user, spellId); } void GameObject::CastSpell(Unit* target, uint32 spellId) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId); if (!spellInfo) return; bool self = false; for (uint8 i = 0; i < 3; ++i) { if (spellInfo->EffectImplicitTargetA[i] == TARGET_UNIT_CASTER) { self = true; break; } } if (self) { if (target) target->CastSpell(target, spellInfo, true); return; } //summon world trigger Creature *trigger = SummonTrigger(GetPositionX(), GetPositionY(), GetPositionZ(), 0, 1); if (!trigger) return; trigger->SetVisibility(VISIBILITY_OFF); //should this be true? if (Unit *owner = GetOwner()) { trigger->setFaction(owner->getFaction()); trigger->CastSpell(target ? target : trigger, spellInfo, true, 0, 0, owner->GetGUID()); } else { trigger->setFaction(14); // Set owner guid for target if no owner avalible - needed by trigger auras // - trigger gets despawned and there's no caster avalible (see AuraEffect::TriggerSpell()) trigger->CastSpell(target ? target : trigger, spellInfo, true, 0, 0, target ? target->GetGUID() : 0); } //trigger->setDeathState(JUST_DIED); //trigger->RemoveCorpse(); } void GameObject::SendCustomAnim() { WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4); data << GetGUID(); data << uint32(GetGoAnimProgress()); SendMessageToSet(&data, true); } bool GameObject::IsInRange(float x, float y, float z, float radius) const { GameObjectDisplayInfoEntry const * info = sGameObjectDisplayInfoStore.LookupEntry(GetUInt32Value(GAMEOBJECT_DISPLAYID)); if (!info) return IsWithinDist3d(x, y, z, radius); float sinA = sin(GetOrientation()); float cosA = cos(GetOrientation()); float dx = x - GetPositionX(); float dy = y - GetPositionY(); float dz = z - GetPositionZ(); float dist = sqrt(dx*dx + dy*dy); float sinB = dx / dist; float cosB = dy / dist; dx = dist * (cosA * cosB + sinA * sinB); dy = dist * (cosA * sinB - sinA * cosB); return dx < info->maxX + radius && dx > info->minX - radius && dy < info->maxY + radius && dy > info->minY - radius && dz < info->maxZ + radius && dz > info->minZ - radius; } void GameObject::TakenDamage(uint32 damage, Unit *who) { if (!m_goValue->building.health) return; Player* pwho = NULL; if (who) { if (who->GetTypeId() == TYPEID_PLAYER) pwho = who->ToPlayer(); else if (who->IsVehicle() && who->GetCharmerOrOwner()) pwho = who->GetCharmerOrOwner()->ToPlayer(); } if (m_goValue->building.health > damage) m_goValue->building.health -= damage; else m_goValue->building.health = 0; if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED)) // from damaged to destroyed { uint8 hitType = BG_OBJECT_DMG_HIT_TYPE_HIGH_DAMAGED; if (!m_goValue->building.health) { RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->building.destroyedDisplayId); EventInform(m_goInfo->building.destroyedEvent); if (pwho) if (Battleground* bg = pwho->GetBattleground()) bg->DestroyGate(pwho, this, m_goInfo->building.destroyedEvent); hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_DESTROYED; sScriptMgr.OnGameObjectDestroyed(pwho, this, m_goInfo->building.destroyedEvent); } if (pwho) if (Battleground* bg = pwho->GetBattleground()) bg->EventPlayerDamagedGO(pwho, this, hitType, m_goInfo->building.destroyedEvent); } else // from intact to damaged { uint8 hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_DAMAGED; if (m_goValue->building.health + damage < m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits) hitType = BG_OBJECT_DMG_HIT_TYPE_DAMAGED; if (m_goValue->building.health <= m_goInfo->building.damagedNumHits) { if (!m_goInfo->building.destroyedDisplayId) m_goValue->building.health = m_goInfo->building.damagedNumHits; else if (!m_goValue->building.health) m_goValue->building.health = 1; SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->building.damagedDisplayId); EventInform(m_goInfo->building.damagedEvent); hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_HIGH_DAMAGED; } if (pwho) if (Battleground* bg = pwho->GetBattleground()) bg->EventPlayerDamagedGO(pwho, this, hitType, m_goInfo->building.destroyedEvent); } SetGoAnimProgress(m_goValue->building.health*255/(m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits)); } void GameObject::Rebuild() { RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED + GO_FLAG_DESTROYED); SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->displayId); m_goValue->building.health = m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits; EventInform(m_goInfo->building.rebuildingEvent); } void GameObject::EventInform(uint32 eventId) { if (eventId && m_zoneScript) m_zoneScript->ProcessEvent(this, eventId); } // overwrite WorldObject function for proper name localization const char* GameObject::GetNameForLocaleIdx(LocaleConstant loc_idx) const { if (loc_idx != DEFAULT_LOCALE) { uint8 uloc_idx = uint8(loc_idx); if (GameObjectLocale const *cl = sObjectMgr.GetGameObjectLocale(GetEntry())) if (cl->Name.size() > uloc_idx && !cl->Name[uloc_idx].empty()) return cl->Name[uloc_idx].c_str(); } return GetName(); } void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/) { static double const atan_pow = atan(pow(2.0f, -20.0f)); double f_rot1 = sin(GetOrientation() / 2.0f); double f_rot2 = cos(GetOrientation() / 2.0f); int64 i_rot1 = int64(f_rot1 / atan_pow *(f_rot2 >= 0 ? 1.0f : -1.0f)); int64 rotation = (i_rot1 << 43 >> 43) & 0x00000000001FFFFF; //float f_rot2 = sin(0.0f / 2.0f); //int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f)); //rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000; //float f_rot3 = sin(0.0f / 2.0f); //int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f)); //rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000; m_rotation = rotation; if (rotation2 == 0.0f && rotation3 == 0.0f) { rotation2 = (float)f_rot1; rotation3 = (float)f_rot2; } SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2); SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3); }
milleniumcore/CactusEMU
src/server/game/Entities/GameObject/GameObject.cpp
C++
gpl-2.0
64,195
/**************************************************************************** ** Resource object code ** ** Created: Tue May 21 13:17:21 2013 ** by: The Resource Compiler for Qt version 4.8.2 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <QtCore/qglobal.h> QT_BEGIN_NAMESPACE QT_END_NAMESPACE int QT_MANGLE_NAMESPACE(qInitResources_teamworkpmtimer)() { return 1; } Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_teamworkpmtimer)) int QT_MANGLE_NAMESPACE(qCleanupResources_teamworkpmtimer)() { return 1; } Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_teamworkpmtimer))
katastrofa/TeamWorkTimer
src/GeneratedFiles/qrc_teamworkpmtimer.cpp
C++
gpl-2.0
717
<definitions targetNamespace="http://rs.tdwg.org/tapir/lsid/Authority" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:httpsns="http://www.omg.org/LSID/2003/DataServiceHTTPBindings"> <import namespace="http://www.omg.org/LSID/2003/DataServiceHTTPBindings" location="LSIDDataServiceHTTPBindings.wsdl" /> <!-- Example HTTP GET Services (urlEncoding) --> <service name="MyDataHTTPService"> <port name="MyDataServiceHTTPPort" binding="httpsns:LSIDDataHTTPBinding"> <http:address location="<?php print($LSIDDataAddress); ?>" /> </port> </service> <service name="MyMetadataHTTPService"> <port name="MyMetadataServiceHTTPPort" binding="httpsns:LSIDMetadataHTTPBinding"> <http:address location="<?php print($LSIDMetadataAddress); ?>" /> </port> </service> </definitions>
telabotanica/tapirlink
templates/LsidDataServices.wsdl.php
PHP
gpl-2.0
902
package drawing; import math.VectorMath; /** * * @author Mark Traquair - Started in 2013/14 */ public class Collision { VectorMath math = new VectorMath(); private boolean doTheMath(Point point1, Point point2){ //This is the dot product of point 2 - point1 return ((point2.getDx()-point1.getDx())*(point2.getX()-point1.getX()))+((point2.getDy()-point1.getDy())*(point2.getY()-point1.getY())) < 0; } public boolean colliding(Point p1, Point p2){ double dist = math.distance(p1.getX(), p2.getX(), p1.getY(), p2.getY()); return dist < (p1.getRadius()+p2.getRadius()); } /** * This function is responsible for doing the math for a 2d collision * between two points. Collisions are passed directly, hence void type. * * @param point1 The first point in the collision check * @param point2 The second point in the collision check */ public void Coll(Point point1, Point point2){ if (doTheMath(point1, point2)){ double velocity1x = (2*point2.getMass())/(point1.getMass()+point2.getMass()); double velocity1y; double V1xsubV2x = (point1.getDx()-point2.getDx()); double V1ysubV2y = (point1.getDy()-point2.getDy()); double X1xsubX2x = (point1.getX()-point2.getX()); double X1ysubX2y = (point1.getY()-point2.getY()); double magX1squared = Math.pow(X1xsubX2x,2)+Math.pow(X1ysubX2y,2); double velocity2x = (2*point1.getMass())/(point1.getMass()+point2.getMass()); double velocity2y; double V2xsubV1x = (point2.getDx()-point1.getDx()); double V2ysubV1y = (point2.getDy()-point1.getDy()); double X2xsubX1x = (point2.getX()-point1.getX()); double X2ysubX1y = (point2.getY()-point1.getY()); double magX2squared = Math.pow(X2xsubX1x,2)+Math.pow(X2ysubX1y,2); velocity1x *= ((V1xsubV2x*X1xsubX2x+V1ysubV2y*X1ysubX2y)/magX1squared); velocity2x *= ((V2xsubV1x*X2xsubX1x+V2ysubV1y*X2ysubX1y)/magX2squared); velocity1y = velocity1x; velocity2y = velocity2x; velocity1x *= X1xsubX2x; velocity1y *= X1ysubX2y; velocity2x *= X2xsubX1x; velocity2y *= X2ysubX1y; velocity1x = point1.getDx()-velocity1x; velocity1y = point1.getDy()-velocity1y; velocity2x = point2.getDx()-velocity2x; velocity2y = point2.getDy()-velocity2y; //System.out.println(point1.getVelocity()*point1.getMass()+point2.getVelocity()*point2.getMass()); point1.setDx(velocity1x); point1.setDy(velocity1y); point2.setDx(velocity2x); point2.setDy(velocity2y); //System.out.println(point1.getVelocity()*point1.getMass()+point2.getVelocity()*point2.getMass()); } } }
WorldsBestCoder/PlanetSimulation
src/drawing/Collision.java
Java
gpl-2.0
3,059
/* * Copyright (C) 2005-2014 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "system.h" #if defined(HAVE_X11) #include "video/videosync/VideoSyncDRM.h" #include "xf86drm.h" #include <sys/poll.h> #include <sys/time.h> #include "utils/TimeUtils.h" #include "utils/MathUtils.h" #include "windowing/WindowingFactory.h" #include "guilib/GraphicContext.h" #include "utils/log.h" bool CVideoSyncDRM::Setup(PUPDATECLOCK func) { CLog::Log(LOGDEBUG, "CVideoSyncDRM::%s - setting up DRM", __FUNCTION__); UpdateClock = func; m_fd = open("/dev/dri/card0", O_RDWR, 0); if (m_fd < 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - can't open /dev/dri/card0", __FUNCTION__); return false; } drmVBlank vbl; int ret; vbl.request.type = DRM_VBLANK_RELATIVE; vbl.request.sequence = 0; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return false; } m_abort = false; g_Windowing.Register(this); return true; } void CVideoSyncDRM::Run(volatile bool& stop) { drmVBlank vbl; VblInfo info; int ret; int crtc = g_Windowing.GetCrtc(); vbl.request.type = DRM_VBLANK_RELATIVE; if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | ((crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK)); } vbl.request.sequence = 0; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return; } info.start = CurrentHostCounter(); info.videoSync = this; vbl.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT); if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | ((crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK)); } vbl.request.sequence = 1; vbl.request.signal = (unsigned long)&info; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return; } drmEventContext evctx; memset(&evctx, 0, sizeof evctx); evctx.version = DRM_EVENT_CONTEXT_VERSION; evctx.vblank_handler = EventHandler; evctx.page_flip_handler = NULL; timeval timeout; fd_set fds; FD_ZERO(&fds); FD_SET(m_fd, &fds); while (!stop && !m_abort) { timeout.tv_sec = 1; timeout.tv_usec = 0; ret = select(m_fd + 1, &fds, NULL, NULL, &timeout); if (ret <= 0) { continue; } ret = drmHandleEvent(m_fd, &evctx); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmHandleEvent returned error", __FUNCTION__); break; } } } void CVideoSyncDRM::Cleanup() { close(m_fd); g_Windowing.Unregister(this); } void CVideoSyncDRM::EventHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data) { drmVBlank vbl; struct timeval end; VblInfo *info = (VblInfo*)data; int crtc = g_Windowing.GetCrtc(); vbl.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT); if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | ((crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK)); } vbl.request.sequence = 1; vbl.request.signal = (unsigned long)data; drmWaitVBlank(info->videoSync->m_fd, &vbl); uint64_t now = CurrentHostCounter(); float diff = (float)(now - info->start)/CurrentHostFrequency(); int vblanks = MathUtils::round_int(diff * info->videoSync->m_fps); info->start = now; info->videoSync->UpdateClock(vblanks, now); } void CVideoSyncDRM::OnResetDevice() { m_abort = true; } float CVideoSyncDRM::GetFps() { m_fps = g_graphicsContext.GetFPS(); return m_fps; } #endif
codesnake/xbmc
xbmc/video/videosync/VideoSyncDRM.cpp
C++
gpl-2.0
4,875
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = require('../../model/engine'); var util = require('../../lib/util'); module.exports = function(face, rootPath) { face.post('/api/register', bodyParser.json(), bodyParser.urlencoded(), register); face.get('/groups/:token', function(req, res) { res.sendFile(rootPath + 'assets/static/groups.html'); }); face.get('/api/groups/:token', function(req, res) { Account.getByToken(req.params.token).then(function(account) { return Engine.get(account.eid); }).then(function(engine) { var e = chip.getEngine(engine.sid); // I dunno what's going on here, but sometimes this gets weird e.loadGroups().then(function() { res.json({ synd: e.synd, groups: e.groups }); }); }); }); face.route('/api/group/:gid') .get(getGroup) .post(bodyParser.json(), bodyParser.urlencoded(), updateGroup, getGroup); face.put('/api/group', createGroup); }; function register(req, res) { return Syndicate.getByName(req.body.synd).then(function(synd) { if (synd) { return Engine.getBySynd(synd.sid).then(function(engine) { if (engine) { res.json({ error: 'Syndicate already registered' }); } else { var e = Engine.create({ sid: synd.sid }); var token = Math.random().toString(36).slice(2); return e.save().then(function() { return chip.db.queryAsync('INSERT INTO account SET ?', { email: req.body.email, eid: e.eid, token: token }); }).then(function(result) { chip.addEngine(e); res.json({ token: token }); }); } }); } else { res.json({ error: 'Syndicate not found' }); } }) }; function getGroup(req, res) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); res.json(g); }) } function createGroup(req, res) { var g = Group.create({ sid: req.body.sid, groupme_id: req.body.groupme_id, bot_key: req.body.bot_key, output: req.body.output == 'true', scout: req.body.scout == 'true', debug: req.body.debug == 'true' }); return g.save().then(function() { req.params.gid = g.gid; chip.addGroup(g); res.json(g); }); } function updateGroup(req, res, next) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); if (g) chip.removeGroup(g.groupme_id); else g = group; g.groupme_id = req.body.groupme_id; g.bot_key = req.body.bot_key; g.bot_id = null; g.output = req.body.output == 'true'; g.scout = req.body.scout == 'true'; g.debug = req.body.debug == 'true'; return g.save().then(function() { delete g.bot_id; g.getEngine().loadGroups().then(function() { res.json(g); }); }); }); } passport.use(new LocalStrategy( function(key, password, done) { //chip.db.queryAsync( /* connection.query("SELECT * FROM player p WHERE sid IS NOT NULL AND name='"+username+"'", function(err, result) { if (err) throw err; if (result.length > 0 && password == 'oredic37') { var player = User.createPlayer(result[0]); done(null, player); } else { done(null, null, { message: 'Invalid login' }); } }); */ }) ); passport.serializeUser(function(player, done) { done(null, player.pid); }); passport.deserializeUser(function(pid, done) { User.getUser(pid).then(function(user) { done(null, user); }); }); function loggedIn(req, res, next) { if (req.isAuthenticated()) { next(); } else { req.session.loginRedirect = req.url; res.redirect('/'); } }
uzrbin/chip
src/face/routes/account.js
JavaScript
gpl-2.0
3,788
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using System.Runtime.Serialization; #pragma warning disable CS0108 namespace KODIRPC.VideoLibrary { public class GetTVShows_filterStudio { public string studio { get; set; } } }
DerPate2010/Xbmc2ndScr
KODIRPC.Portable/KODIRPC/VideoLibrary/GetTVShows_filterStudio.cs
C#
gpl-2.0
291
using System.Collections.Generic; using Untech.Web.Core.Models.Post; namespace Untech.Web.Core.Services.Interfaces { public interface IPostTrackingService { List<PostPackage> Track(PostPackage package); } }
Happi-cat/Untech.Web
Untech.Web.Core/Services/Interfaces/IPostTrackingService.cs
C#
gpl-2.0
224
<?php /** * Internationalisation file for the InterwikiDetection extension * * @file * @ingroup Extensions */ $messages = array(); /* English * @author Nathan Larson */ $messages['en'] = array( 'interwikidetection' => 'Interwiki detection', 'interwikidetection-desc' => 'Links wikilinks to Wikipedia if the page does not exist on the local wiki but exists on Wikipedia', 'interwikidetection-wikipedia-url' => 'https://en.wikipedia.org/wiki/$1', );
Inclumedia/InterwikiDetection
InterwikiDetection.i18n.php
PHP
gpl-2.0
466
/*---------------------------------------------------------------------------*\ ## #### ###### | ## ## ## | Copyright: ICE Stroemungsfoschungs GmbH ## ## #### | ## ## ## | http://www.ice-sf.at ## #### ###### | ------------------------------------------------------------------------------- ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is based on OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Description Define versions and flags for swak to distinguish different features via #ifdef SourceFiles Contributors/Copyright: 2012-2015 Bernhard F.W. Gschaider <bgschaid@ice-sf.at> SWAK Revision: $Id$ \*---------------------------------------------------------------------------*/ #ifndef SwakMacroHeader_H #define SwakMacroHeader_H #include "foamVersion4swak.H" #define VERSION_NR(major,minor,patch) ( \ 10000 * major + \ 100 * minor + \ patch ) #define VERSION_NR2(major,minor) ( \ 10000 * major + \ 100 * minor + \ 99 ) #define FOAM_VERSION4SWAK VERSION_NR(FOAM_VERSION4SWAK_MAJOR,FOAM_VERSION4SWAK_MINOR,FOAM_VERSION4SWAK_PATCH_NUM) #if FOAM_VERSION4SWAK > VERSION_NR2(1,6) #define FOAM_HAS_SORTED_TOC #else #define FOAM_OLDTIME_PROBLEM #endif #if FOAM_VERSION4SWAK >= VERSION_NR(2,0,0) #error "This swak4Foam-version is only used for the 1.x-versions of OpenFOAM. For higher versions there is a special branch" #endif // in 1.6-ext the operation s1 & s2 of two symmetrical tensor fields does not yield a symmetric tensor #ifdef FOAM_DEV #define FOAM_SYMMTENSOR_WORKAROUND #endif // in 1.6-ext nextRelease a different Macro is used for the creation of certain patch types #ifdef FOAM_DEV #define FOAM_USE_MAKE_TEMPLATE_PATCH_TYPE #endif // Certain OpenFOAM-versions don't have all tensor operations defined #if FOAM_VERSION4SWAK < VERSION_NR(1,7,0) #define FOAM_INCOMPLETE_OPERATORS #endif // Certain OpenFOAM-versions don't have this method in fvMesh #if FOAM_VERSION4SWAK < VERSION_NR(1,7,0) #define FOAM_FV_MESH_HAS_NO_SOLVERDICT #endif // Additional tensor types in nextRelease #ifdef FOAM_DEV #define FOAM_DEV_ADDITIONAL_TENSOR_TYPES #endif // The kineamticPArcel has no property active in 1.6-ext #ifdef FOAM_DEV #define FOAM_KINEMTATIC_HAS_NO_ACTIVE_PROPERTY #endif #include "swakVersion.H" #include "DebugOStream.H" #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder1.7-libraries-swak4Foam
Libraries/swak4FoamParsers/include/swak.H
C++
gpl-2.0
3,398
# #LiloConf.py # import sys, re, os import logging import GrubConf class LiloImage(object): def __init__(self, lines, path): self.reset(lines, path) def __repr__(self): return ("title: %s\n" " root: %s\n" " kernel: %s\n" " args: %s\n" " initrd: %s\n" %(self.title, self.root, self.kernel, self.args, self.initrd)) def reset(self, lines, path): self._initrd = self._kernel = self._readonly = None self._args = "" self.title = "" self.lines = [] self.path = path self.root = "" map(self.set_from_line, lines) def set_from_line(self, line, replace = None): (com, arg) = GrubConf.grub_exact_split(line, 2) if self.commands.has_key(com): if self.commands[com] is not None: setattr(self, self.commands[com], re.sub('^"(.+)"$', r"\1", arg.strip())) else: logging.info("Ignored image directive %s" %(com,)) else: logging.warning("Unknown image directive %s" %(com,)) # now put the line in the list of lines if replace is None: self.lines.append(line) else: self.lines.pop(replace) self.lines.insert(replace, line) def set_kernel(self, val): self._kernel = (None, self.path + "/" + val) def get_kernel(self): return self._kernel kernel = property(get_kernel, set_kernel) def set_initrd(self, val): self._initrd = (None, self.path + "/" + val) def get_initrd(self): return self._initrd initrd = property(get_initrd, set_initrd) def set_args(self, val): self._args = val def get_args(self): args = self._args if self.root: args += " root=" + self.root if self.readonly: args += " ro" return args args = property(get_args, set_args) def set_readonly(self, val): self._readonly = 1 def get_readonly(self): return self._readonly readonly = property(get_readonly, set_readonly) # set up command handlers commands = { "label": "title", "root": "root", "rootnoverify": "root", "image": "kernel", "initrd": "initrd", "append": "args", "read-only": "readonly", "chainloader": None, "module": None} class LiloConfigFile(object): def __init__(self, fn = None): self.filename = fn self.images = [] self.timeout = -1 self._default = 0 if fn is not None: self.parse() def parse(self, buf = None): if buf is None: if self.filename is None: raise ValueError, "No config file defined to parse!" f = open(self.filename, 'r') lines = f.readlines() f.close() else: lines = buf.split("\n") path = os.path.dirname(self.filename) img = [] for l in lines: l = l.strip() # skip blank lines if len(l) == 0: continue # skip comments if l.startswith('#'): continue # new image if l.startswith("image"): if len(img) > 0: self.add_image(LiloImage(img, path)) img = [l] continue if len(img) > 0: img.append(l) continue (com, arg) = GrubConf.grub_exact_split(l, 2) if self.commands.has_key(com): if self.commands[com] is not None: setattr(self, self.commands[com], arg.strip()) else: logging.info("Ignored directive %s" %(com,)) else: logging.warning("Unknown directive %s" %(com,)) if len(img) > 0: self.add_image(LiloImage(img, path)) def add_image(self, image): self.images.append(image) def _get_default(self): for i in range(0, len(self.images) - 1): if self.images[i].title == self._default: return i return 0 def _set_default(self, val): self._default = val default = property(_get_default, _set_default) commands = { "default": "self.default", "timeout": "self.timeout", "prompt": None, "relocatable": None, } if __name__ == "__main__": if sys.argv < 2: raise RuntimeError, "Need a grub.conf to read" g = LiloConfigFile(sys.argv[1]) for i in g.images: print i #, i.title, i.root, i.kernel, i.args, i.initrd print g.default
mikesun/xen-cow-checkpointing
tools/pygrub/src/LiloConf.py
Python
gpl-2.0
4,887
<?php return array( 'maintenances' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'maintenanceid', 'fields' => array( 'maintenanceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'maintenance_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'active_since' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'active_till' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'hosts' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'hostid', 'fields' => array( 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'proxy_hostid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'disable_until' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'available' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'errors_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastaccess' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ipmi_authtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ipmi_privilege' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'ipmi_username' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 16, 'default' => '', ), 'ipmi_password' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 20, 'default' => '', ), 'ipmi_disable_until' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ipmi_available' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmp_disable_until' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmp_available' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'maintenanceid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'maintenances', 'ref_field' => '', ), 'maintenance_status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'maintenance_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'maintenance_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ipmi_errors_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmp_errors_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ipmi_error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'snmp_error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'jmx_disable_until' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'jmx_available' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'jmx_errors_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'jmx_error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'groups' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'groupid', 'fields' => array( 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'internal' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'screens' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'screenid', 'fields' => array( 'screenid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'hsize' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'vsize' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'templateid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), ), ), 'screens_items' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'screenitemid', 'fields' => array( 'screenitemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'screenid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'screens', 'ref_field' => 'screenid', ), 'resourcetype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'resourceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'width' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '320', ), 'height' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '200', ), 'x' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'y' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'colspan' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'rowspan' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'elements' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '25', ), 'valign' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'halign' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'style' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'dynamic' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'sort_triggers' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'slideshows' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'slideshowid', 'fields' => array( 'slideshowid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'delay' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'slides' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'slideid', 'fields' => array( 'slideid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'slideshowid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'slideshows', 'ref_field' => 'slideshowid', ), 'screenid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'screens', 'ref_field' => 'screenid', ), 'step' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'delay' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'drules' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'druleid', 'fields' => array( 'druleid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'proxy_hostid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'iprange' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'delay' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '3600', ), 'nextcheck' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'dchecks' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'dcheckid', 'fields' => array( 'dcheckid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'druleid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'drules', 'ref_field' => 'druleid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'snmp_community' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ports' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '0', ), 'snmpv3_securityname' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'snmpv3_securitylevel' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmpv3_authpassphrase' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'snmpv3_privpassphrase' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'uniq' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'applications' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'applicationid', 'fields' => array( 'applicationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'templateid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'applications', 'ref_field' => 'applicationid', ), ), ), 'httptest' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'httptestid', 'fields' => array( 'httptestid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'applicationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'applications', 'ref_field' => 'applicationid', ), 'nextcheck' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'delay' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '60', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'macros' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'agent' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'authentication' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'http_user' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'http_password' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'httpstep' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'httpstepid', 'fields' => array( 'httpstepid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'httptestid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'httptest', 'ref_field' => 'httptestid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'no' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'timeout' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '30', ), 'posts' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'required' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'status_codes' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'interface' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'interfaceid', 'fields' => array( 'interfaceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'main' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'useip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '127.0.0.1', ), 'dns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '10050', ), ), ), 'valuemaps' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'valuemapid', 'fields' => array( 'valuemapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'items' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'itemid', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmp_community' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'snmp_oid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'delay' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'history' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '90', ), 'trends' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '365', ), 'lastvalue' => array( 'null' => true, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'lastclock' => array( 'null' => true, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'prevvalue' => array( 'null' => true, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'trapper_hosts' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'units' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'multiplier' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'delta' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'prevorgvalue' => array( 'null' => true, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'snmpv3_securityname' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'snmpv3_securitylevel' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'snmpv3_authpassphrase' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'snmpv3_privpassphrase' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'formula' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '1', ), 'error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'lastlogsize' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), 'logtimefmt' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'templateid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'valuemapid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'valuemaps', 'ref_field' => '', ), 'delay_flex' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'params' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'ipmi_sensor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'data_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'authtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'username' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'password' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'publickey' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'privatekey' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'mtime' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastns' => array( 'null' => true, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'flags' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'filter' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'interfaceid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'interface', 'ref_field' => '', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'inventory_link' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lifetime' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '30', ), ), ), 'httpstepitem' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'httpstepitemid', 'fields' => array( 'httpstepitemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'httpstepid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'httpstep', 'ref_field' => 'httpstepid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'httptestitem' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'httptestitemid', 'fields' => array( 'httptestitemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'httptestid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'httptest', 'ref_field' => 'httptestid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'media_type' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'mediatypeid', 'fields' => array( 'mediatypeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'smtp_server' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'smtp_helo' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'smtp_email' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'exec_path' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'gsm_modem' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'username' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'passwd' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'users' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'userid', 'fields' => array( 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'alias' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'surname' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'passwd' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => '', ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'autologin' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'autologout' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '900', ), 'lang' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 5, 'default' => 'en_GB', ), 'refresh' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '30', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'theme' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => 'default', ), 'attempt_failed' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'attempt_ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'attempt_clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'rows_per_page' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => 50, ), ), ), 'usrgrp' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'usrgrpid', 'fields' => array( 'usrgrpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'gui_access' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'users_status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'debug_mode' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'users_groups' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'usrgrpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'usrgrp', 'ref_field' => 'usrgrpid', ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), ), ), 'scripts' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'scriptid', 'fields' => array( 'scriptid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'command' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'host_access' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'usrgrpid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'usrgrp', 'ref_field' => '', ), 'groupid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => '', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'confirmation' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'execute_on' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), ), ), 'actions' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'actionid', 'fields' => array( 'actionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'eventsource' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'evaltype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'esc_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'def_shortdata' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'def_longdata' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'recovery_msg' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'r_shortdata' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'r_longdata' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), ), ), 'operations' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'operationid', 'fields' => array( 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'actionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'actions', 'ref_field' => 'actionid', ), 'operationtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'esc_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'esc_step_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'esc_step_to' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'evaltype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'opmessage' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'operationid', 'fields' => array( 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'default_msg' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'subject' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'message' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'mediatypeid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'media_type', 'ref_field' => '', ), ), ), 'opmessage_grp' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opmessage_grpid', 'fields' => array( 'opmessage_grpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'usrgrpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'usrgrp', 'ref_field' => '', ), ), ), 'opmessage_usr' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opmessage_usrid', 'fields' => array( 'opmessage_usrid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => '', ), ), ), 'opcommand' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'operationid', 'fields' => array( 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'scriptid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'scripts', 'ref_field' => '', ), 'execute_on' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'authtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'username' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'password' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'publickey' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'privatekey' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'command' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), ), ), 'opcommand_hst' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opcommand_hstid', 'fields' => array( 'opcommand_hstid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'hostid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => '', ), ), ), 'opcommand_grp' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opcommand_grpid', 'fields' => array( 'opcommand_grpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => '', ), ), ), 'opgroup' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opgroupid', 'fields' => array( 'opgroupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => '', ), ), ), 'optemplate' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'optemplateid', 'fields' => array( 'optemplateid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'templateid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), ), ), 'opconditions' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'opconditionid', 'fields' => array( 'opconditionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'operationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'operations', 'ref_field' => 'operationid', ), 'conditiontype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'operator' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'conditions' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'conditionid', 'fields' => array( 'conditionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'actionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'actions', 'ref_field' => 'actionid', ), 'conditiontype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'operator' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'config' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'configid', 'fields' => array( 'configid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'alert_history' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'event_history' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'refresh_unsupported' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'work_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '1-5,00:00-24:00', ), 'alert_usrgrpid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'usrgrp', 'ref_field' => 'usrgrpid', ), 'event_ack_enable' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'event_expire' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '7', ), 'event_show_max' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '100', ), 'default_theme' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => 'originalblue', ), 'authentication_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ldap_host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ldap_port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => 389, ), 'ldap_base_dn' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ldap_bind_dn' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ldap_bind_password' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'ldap_search_attribute' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'dropdown_first_entry' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'dropdown_first_remember' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'discovery_groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => 'groupid', ), 'max_in_table' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '50', ), 'search_limit' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1000', ), 'severity_color_0' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'DBDBDB', ), 'severity_color_1' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'D6F6FF', ), 'severity_color_2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'FFF6A5', ), 'severity_color_3' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'FFB689', ), 'severity_color_4' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'FF9999', ), 'severity_color_5' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'FF3838', ), 'severity_name_0' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'Not classified', ), 'severity_name_1' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'Information', ), 'severity_name_2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'Warning', ), 'severity_name_3' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'Average', ), 'severity_name_4' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'High', ), 'severity_name_5' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => 'Disaster', ), 'ok_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1800', ), 'blink_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1800', ), 'problem_unack_color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'DC0000', ), 'problem_ack_color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'DC0000', ), 'ok_unack_color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '00AA00', ), 'ok_ack_color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '00AA00', ), 'problem_unack_style' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'problem_ack_style' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'ok_unack_style' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'ok_ack_style' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'snmptrap_logging' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'server_check_interval' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '60', ), ), ), 'triggers' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'triggerid', 'fields' => array( 'triggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'expression' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'priority' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastchange' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'comments' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'templateid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_flags' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'flags' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'trigger_depends' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'triggerdepid', 'fields' => array( 'triggerdepid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'triggerid_down' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'triggerid_up' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), ), ), 'functions' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'functionid', 'fields' => array( 'functionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'triggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'function' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 12, 'default' => '', ), 'parameter' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '0', ), ), ), 'graphs' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'graphid', 'fields' => array( 'graphid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'width' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'height' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'yaxismin' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0', ), 'yaxismax' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0', ), 'templateid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'graphs', 'ref_field' => 'graphid', ), 'show_work_period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'show_triggers' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'graphtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'show_legend' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'show_3d' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'percent_left' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0', ), 'percent_right' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0', ), 'ymin_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ymax_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ymin_itemid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'ymax_itemid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'flags' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'graphs_items' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'gitemid', 'fields' => array( 'gitemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'graphid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'graphs', 'ref_field' => 'graphid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'drawtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'sortorder' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '009600', ), 'yaxisside' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'calc_fnc' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'graph_theme' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'graphthemeid', 'fields' => array( 'graphthemeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'theme' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'backgroundcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'F0F0F0', ), 'graphcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'FFFFFF', ), 'graphbordercolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '222222', ), 'gridcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'CCCCCC', ), 'maingridcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'AAAAAA', ), 'gridbordercolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '000000', ), 'textcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '202020', ), 'highlightcolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'AA4444', ), 'leftpercentilecolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '11CC11', ), 'rightpercentilecolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'CC1111', ), 'nonworktimecolor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => 'CCCCCC', ), 'gridview' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => 1, ), 'legendview' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => 1, ), ), ), 'help_items' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'itemtype,key_', 'fields' => array( 'itemtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'description' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'globalmacro' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'globalmacroid', 'fields' => array( 'globalmacroid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'macro' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'hostmacro' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'hostmacroid', 'fields' => array( 'hostmacroid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'macro' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'hosts_groups' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'hostgroupid', 'fields' => array( 'hostgroupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => 'groupid', ), ), ), 'hosts_templates' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'hosttemplateid', 'fields' => array( 'hosttemplateid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'templateid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), ), ), 'items_applications' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'itemappid', 'fields' => array( 'itemappid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'applicationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'applications', 'ref_field' => 'applicationid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), ), ), 'mappings' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'mappingid', 'fields' => array( 'mappingid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'valuemapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'valuemaps', 'ref_field' => 'valuemapid', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'newvalue' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'media' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'mediaid', 'fields' => array( 'mediaid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'mediatypeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'media_type', 'ref_field' => 'mediatypeid', ), 'sendto' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'active' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'severity' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '63', ), 'period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '1-7,00:00-24:00', ), ), ), 'rights' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'rightid', 'fields' => array( 'rightid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'usrgrp', 'ref_field' => 'usrgrpid', ), 'permission' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => 'groupid', ), ), ), 'services' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'serviceid', 'fields' => array( 'serviceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'algorithm' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'triggerid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'showsla' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'goodsla' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '99.9', ), 'sortorder' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'services_links' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'linkid', 'fields' => array( 'linkid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'serviceupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'services', 'ref_field' => 'serviceid', ), 'servicedownid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'services', 'ref_field' => 'serviceid', ), 'soft' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'services_times' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'timeid', 'fields' => array( 'timeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'serviceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'services', 'ref_field' => 'serviceid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ts_from' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ts_to' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'note' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'icon_map' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'iconmapid', 'fields' => array( 'iconmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'default_iconid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), ), ), 'icon_mapping' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'iconmappingid', 'fields' => array( 'iconmappingid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'iconmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'icon_map', 'ref_field' => 'iconmapid', ), 'iconid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'inventory_link' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'expression' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'sortorder' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'sysmaps' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'sysmapid', 'fields' => array( 'sysmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'width' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '600', ), 'height' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '400', ), 'backgroundid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'label_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_location' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '3', ), 'highlight' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'expandproblem' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'markelements' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'show_unack' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'grid_size' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '50', ), 'grid_show' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'grid_align' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), 'label_format' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'label_type_host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_type_hostgroup' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_type_trigger' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_type_map' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_type_image' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '2', ), 'label_string_host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'label_string_hostgroup' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'label_string_trigger' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'label_string_map' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'label_string_image' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'iconmapid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'icon_map', 'ref_field' => '', ), 'expand_macros' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'sysmaps_elements' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'selementid', 'fields' => array( 'selementid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'sysmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps', 'ref_field' => 'sysmapid', ), 'elementid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'elementtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'iconid_off' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'iconid_on' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'label' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'label_location' => array( 'null' => true, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'x' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'y' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'iconid_disabled' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'iconid_maintenance' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'images', 'ref_field' => 'imageid', ), 'elementsubtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'areatype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'width' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '200', ), 'height' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '200', ), 'viewtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'use_iconmap' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '1', ), ), ), 'sysmaps_links' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'linkid', 'fields' => array( 'linkid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'sysmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps', 'ref_field' => 'sysmapid', ), 'selementid1' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps_elements', 'ref_field' => 'selementid', ), 'selementid2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps_elements', 'ref_field' => 'selementid', ), 'drawtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '000000', ), 'label' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'sysmaps_link_triggers' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'linktriggerid', 'fields' => array( 'linktriggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'linkid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps_links', 'ref_field' => 'linkid', ), 'triggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'drawtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'color' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 6, 'default' => '000000', ), ), ), 'sysmap_element_url' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'sysmapelementurlid', 'fields' => array( 'sysmapelementurlid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'selementid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps_elements', 'ref_field' => 'selementid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'sysmap_url' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'sysmapurlid', 'fields' => array( 'sysmapurlid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'sysmapid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'sysmaps', 'ref_field' => 'sysmapid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, ), 'url' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'elementtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'maintenances_hosts' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'maintenance_hostid', 'fields' => array( 'maintenance_hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'maintenanceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'maintenances', 'ref_field' => 'maintenanceid', ), 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), ), ), 'maintenances_groups' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'maintenance_groupid', 'fields' => array( 'maintenance_groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'maintenanceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'maintenances', 'ref_field' => 'maintenanceid', ), 'groupid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'groups', 'ref_field' => 'groupid', ), ), ), 'timeperiods' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'timeperiodid', 'fields' => array( 'timeperiodid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'timeperiod_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'every' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'month' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'dayofweek' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'day' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'start_time' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'period' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'start_date' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'maintenances_windows' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'maintenance_timeperiodid', 'fields' => array( 'maintenance_timeperiodid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'maintenanceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'maintenances', 'ref_field' => 'maintenanceid', ), 'timeperiodid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'timeperiods', 'ref_field' => 'timeperiodid', ), ), ), 'regexps' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'regexpid', 'fields' => array( 'regexpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'test_string' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), ), ), 'expressions' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'expressionid', 'fields' => array( 'expressionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'regexpid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'regexps', 'ref_field' => 'regexpid', ), 'expression' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'expression_type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'exp_delimiter' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 1, 'default' => '', ), 'case_sensitive' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'nodes' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'nodeid', 'fields' => array( 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '0', ), 'ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '10051', ), 'nodetype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'masterid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), ), ), 'node_cksum' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => '', 'fields' => array( 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), 'tablename' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'recordid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'cksumtype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'cksum' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'sync' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), ), ), 'ids' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'nodeid,table_name,field_name', 'fields' => array( 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), 'table_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'field_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'nextid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), ), ), 'alerts' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'alertid', 'fields' => array( 'alertid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'actionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'actions', 'ref_field' => 'actionid', ), 'eventid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'events', 'ref_field' => 'eventid', ), 'userid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'mediatypeid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'media_type', 'ref_field' => 'mediatypeid', ), 'sendto' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 100, 'default' => '', ), 'subject' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'message' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'retries' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'error' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'nextcheck' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'esc_step' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'alerttype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => '', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0.0000', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_sync' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0.0000', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_uint' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => '', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_uint_sync' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_str' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => '', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_str_sync' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'nodeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'ref_table' => 'nodes', 'ref_field' => 'nodeid', ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_log' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'timestamp' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'source' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'severity' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'logeventid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'history_text' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'proxy_history' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'timestamp' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'source' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'severity' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'logeventid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'proxy_dhistory' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'druleid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'drules', 'ref_field' => 'druleid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'dcheckid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'dchecks', 'ref_field' => 'dcheckid', ), 'dns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'events' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'eventid', 'fields' => array( 'eventid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'source' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'object' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'objectid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'acknowledged' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_changed' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'trends' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'itemid,clock', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'num' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_min' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0.0000', ), 'value_avg' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0.0000', ), 'value_max' => array( 'null' => false, 'type' => DB::FIELD_TYPE_FLOAT, 'length' => 16, 'default' => '0.0000', ), ), ), 'trends_uint' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'itemid,clock', 'fields' => array( 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'num' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_min' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), 'value_avg' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), 'value_max' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, 'default' => '0', ), ), ), 'acknowledges' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'acknowledgeid', 'fields' => array( 'acknowledgeid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'eventid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'events', 'ref_field' => 'eventid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'message' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'auditlog' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'auditid', 'fields' => array( 'auditid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'action' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'resourcetype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'details' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '0', ), 'ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'resourceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'resourcename' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'auditlog_details' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'auditdetailid', 'fields' => array( 'auditdetailid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'auditid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'auditlog', 'ref_field' => 'auditid', ), 'table_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'field_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'oldvalue' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'newvalue' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), ), ), 'service_alarms' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'servicealarmid', 'fields' => array( 'servicealarmid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'serviceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'services', 'ref_field' => 'serviceid', ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'autoreg_host' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'autoreg_hostid', 'fields' => array( 'autoreg_hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'proxy_hostid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'listen_ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'listen_port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'listen_dns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'proxy_autoreg_host' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'id', 'fields' => array( 'id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_UINT, 'length' => 20, ), 'clock' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'host' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'listen_ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'listen_port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'listen_dns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'dhosts' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'dhostid', 'fields' => array( 'dhostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'druleid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'drules', 'ref_field' => 'druleid', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastup' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastdown' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'dservices' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'dserviceid', 'fields' => array( 'dserviceid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'dhostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'dhosts', 'ref_field' => 'dhostid', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'port' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastup' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'lastdown' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'dcheckid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'dchecks', 'ref_field' => 'dcheckid', ), 'ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'dns' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), ), ), 'escalations' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'escalationid', 'fields' => array( 'escalationid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'actionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'actions', 'ref_field' => 'actionid', ), 'triggerid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'eventid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'events', 'ref_field' => 'eventid', ), 'r_eventid' => array( 'null' => true, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'events', 'ref_field' => 'eventid', ), 'nextcheck' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'esc_step' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'globalvars' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'globalvarid', 'fields' => array( 'globalvarid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'snmp_lastsize' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'graph_discovery' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'graphdiscoveryid', 'fields' => array( 'graphdiscoveryid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'graphid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'graphs', 'ref_field' => 'graphid', ), 'parent_graphid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'graphs', 'ref_field' => 'graphid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), ), ), 'host_inventory' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'hostid', 'fields' => array( 'hostid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'hosts', 'ref_field' => 'hostid', ), 'inventory_mode' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'type_full' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'alias' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'os' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'os_full' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'os_short' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'serialno_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'serialno_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'tag' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'asset_tag' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'macaddress_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'macaddress_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'hardware' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'hardware_full' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'software' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'software_full' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'software_app_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'software_app_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'software_app_c' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'software_app_d' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'software_app_e' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'contact' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'location' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'location_lat' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 16, 'default' => '', ), 'location_lon' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 16, 'default' => '', ), 'notes' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'chassis' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'model' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'hw_arch' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => '', ), 'vendor' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'contract_number' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'installer_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'deployment_status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'url_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url_c' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'host_networks' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'host_netmask' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'host_router' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'oob_ip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'oob_netmask' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'oob_router' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 39, 'default' => '', ), 'date_hw_purchase' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'date_hw_install' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'date_hw_expiry' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'date_hw_decomm' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'site_address_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'site_address_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'site_address_c' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'site_city' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'site_state' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'site_country' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'site_zip' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'site_rack' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'site_notes' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'poc_1_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'poc_1_email' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'poc_1_phone_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_1_phone_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_1_cell' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_1_screen' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_1_notes' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), 'poc_2_name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'poc_2_email' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 128, 'default' => '', ), 'poc_2_phone_a' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_2_phone_b' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_2_cell' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_2_screen' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'poc_2_notes' => array( 'null' => false, 'type' => DB::FIELD_TYPE_TEXT, 'default' => '', ), ), ), 'housekeeper' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'housekeeperid', 'fields' => array( 'housekeeperid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'tablename' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'field' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '', ), 'value' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'value', ), ), ), 'images' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'imageid', 'fields' => array( 'imageid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'imagetype' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 64, 'default' => '0', ), 'image' => array( 'null' => false, 'type' => DB::FIELD_TYPE_BLOB, 'length' => 2048, 'default' => '', ), ), ), 'item_discovery' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'itemdiscoveryid', 'fields' => array( 'itemdiscoveryid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'parent_itemid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'items', 'ref_field' => 'itemid', ), 'key_' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'lastcheck' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'ts_delete' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'profiles' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'profileid', 'fields' => array( 'profileid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'idx' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 96, 'default' => '', ), 'idx2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'value_id' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'default' => '0', ), 'value_int' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'value_str' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'source' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 96, 'default' => '', ), 'type' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'sessions' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'sessionid', 'fields' => array( 'sessionid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 32, 'default' => '', ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'lastaccess' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), 'status' => array( 'null' => false, 'type' => DB::FIELD_TYPE_INT, 'length' => 10, 'default' => '0', ), ), ), 'trigger_discovery' => array( 'type' => DB::TABLE_TYPE_CONFIG, 'key' => 'triggerdiscoveryid', 'fields' => array( 'triggerdiscoveryid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'triggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'parent_triggerid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'triggers', 'ref_field' => 'triggerid', ), 'name' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), 'user_history' => array( 'type' => DB::TABLE_TYPE_HISTORY, 'key' => 'userhistoryid', 'fields' => array( 'userhistoryid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, ), 'userid' => array( 'null' => false, 'type' => DB::FIELD_TYPE_ID, 'length' => 20, 'ref_table' => 'users', 'ref_field' => 'userid', ), 'title1' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url1' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'title2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url2' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'title3' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url3' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'title4' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url4' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'title5' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), 'url5' => array( 'null' => false, 'type' => DB::FIELD_TYPE_CHAR, 'length' => 255, 'default' => '', ), ), ), ); ?>
gheja/zabbix-ext
frontends/php/include/schema.inc.php
PHP
gpl-2.0
123,223
package ch.hgdev.toposuite.transfer; import android.content.Context; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Interface implementing the Strategy design pattern in order to provide an * easy way to save an object into a file. * * @author HGdev */ public interface SaveStrategy { /** * Save the content of the object into a file stored in the default app * directory. * * @param context The current Android Context. * @param filename The file name. * @return The number of line written in the target file. */ int saveAsCSV(Context context, String filename) throws IOException; /** * Save the content of the object into a file identified by its path. * * @param context The current Android Context. * @param path The path where to store the file. * @param filename The file name. * @return The number of line written in the target file. */ int saveAsCSV(Context context, String path, String filename) throws IOException; /** * Save the content of the object into a file identified by its output * stream. * * @param context The current Android Context. * @param outputStream An opened output stream. This method must close the output * stream. * @return The number of line written in the target file. */ int saveAsCSV(Context context, FileOutputStream outputStream) throws IOException; /** * @param context The Current Android Context. * @param file The file to which to save * @return The number of lines written in the target file. */ int saveAsCSV(Context context, File file) throws IOException; }
hgdev-ch/toposuite-android
app/src/main/java/ch/hgdev/toposuite/transfer/SaveStrategy.java
Java
gpl-2.0
1,754
<?php /** * @package Warp Theme Framework * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl.html GNU/GPL */ // no direct access defined('_JEXEC') or die; JHtml::_('behavior.keepalive'); JHtml::_('behavior.formvalidation'); JHtml::_('behavior.noframes'); ?> <div id="system"> <?php if ($this->params->get('show_page_heading')) : ?> <h1 class="title"><?php echo $this->escape($this->params->get('page_heading')); ?></h1> <?php endif; ?> <form class="submission small style" action="<?php echo JRoute::_('index.php?option=com_users&task=reset.complete'); ?>" method="post"> <?php foreach ($this->form->getFieldsets() as $fieldset): ?> <p><?php echo JText::_($fieldset->label); ?></p> <fieldset> <?php foreach ($this->form->getFieldset($fieldset->name) as $name => $field): ?> <div><?php echo $field->label.$field->input; ?></div> <?php endforeach; ?> </fieldset> <?php endforeach; ?> <div> <button type="submit"><?php echo JText::_('JSUBMIT'); ?></button> </div> <?php echo JHtml::_('form.token'); ?> </form> </div>
NavaINT1876/ccustoms
templates/yoo_showroom/warp/systems/joomla/layouts/com_users/reset/complete.php
PHP
gpl-2.0
1,178
/* * file: canmessagemodel.cpp * author: jrenken * * $Rev: 74 $ * $Author: jrenken $ * $Date: 2012-08-30 15:50:09 +0200 (Do, 30 Aug 2012) $ * $Id: canmessagemodel.cpp 74 2012-08-30 13:50:09Z jrenken $ */ #include <QByteArray> #include "canmessagemodel.h" CanMessageModel::CanMessageModel(Type type, QObject *parent) : QAbstractTableModel(parent), mType(type), mShowTrigger(true) { // TODO Auto-generated constructor stub } CanMessageModel::~CanMessageModel() { // TODO Auto-generated destructor stub } void CanMessageModel::setData(const CanMessages & data) { mMessages = data; } void CanMessageModel::addMessage(const QCanMessage& msg, bool count) { QCanMessage nmsg = msg; bool isNew = false; if (mMessages.contains(msg.frame.id())) { nmsg.sinceLast = msg.time - mMessages.value(msg.frame.id()).time; if (count) nmsg.count = mMessages.value(msg.frame.id()).count + 1; } else { nmsg.sinceLast = 0; if (count) nmsg.count = 1; isNew = true; } mMessages.insert(msg.frame.id(), nmsg); int idx = mMessages.keys().indexOf(msg.frame.id()); if (isNew) { reset(); } emit dataChanged(index(idx, 1), index(idx, 4)); } void CanMessageModel::replaceMessage(const QCanMessage& oldMsg, const QCanMessage& newMsg) { mMessages.remove(oldMsg.frame.id()); addMessage(newMsg); } void CanMessageModel::deleteMessage(const QCanMessage& msg) { if (mMessages.remove(msg.frame.id()) > 0) reset(); } void CanMessageModel::deleteAll() { mMessages.clear(); reset(); } void CanMessageModel::setShowTrigger(bool show) { mShowTrigger = show; reset(); } int CanMessageModel::rowCount(const QModelIndex &) const { return mMessages.size(); } int CanMessageModel::columnCount(const QModelIndex &) const { if (mShowTrigger) return 6; return 5; } QVariant CanMessageModel::data(const QModelIndex &index, int role) const { if ((role != Qt::DisplayRole) && (role != Qt::UserRole)) return QVariant(); QCanMessage msg = mMessages.value(mMessages.keys().at(index.row())); if (role == Qt::UserRole) { return QByteArray((const char*) &msg, sizeof(QCanMessage)); } switch (index.column()) { case 0: if (msg.frame.isExtendedId()) { return QString("0x%1").arg(msg.frame.id(), 8, 16, QLatin1Char('0')); } return QString("0x%1").arg(msg.frame.id(), 3, 16, QLatin1Char('0')); case 1: return msg.frame.dlc(); case 2: if (msg.frame.isRtr()) { return tr("Remote Request"); } else { QString s; for (int i = 0; i < msg.frame.dlc(); i++) { s += QString("%1 ").arg(msg.frame[i], 2, 16, QLatin1Char('0')); } return s; } break; case 3: if (mType == Transmit) { if (msg.autoTrigger) return msg.period; return "Wait"; } return msg.sinceLast; case 4: return msg.count; case 5: return ( msg.autoTrigger ? tr("Auto") : tr("Manual")); } return QVariant(); } QVariant CanMessageModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case 0: return tr("Message"); case 1: return tr("Length"); case 2: return tr("Data"); case 3: return tr("Period"); case 4: return tr("Count"); case 5: return tr("Trigger"); } } return QVariant(); }
jrenken/qtaddon-qtcansocket
examples/canview/canmessagemodel.cpp
C++
gpl-2.0
3,360
/* ** Blue Dust - File code (cut-down, read only) */ #include <stdio.h> #include <stdlib.h> #include "BDDiskFile.h" #include "BDTypes.h" CBDDiskFile::CBDDiskFile() { m_fp = 0; } CBDDiskFile::~CBDDiskFile() { Close(); } int CBDDiskFile::Open(const char *pFilename) { m_fp = fopen(pFilename, "r"); if (!m_fp) return 0; // return 1; } int CBDDiskFile::Close(void) { if (m_fp) fclose(m_fp); m_fp = NULL; return 1; } int CBDDiskFile::GetChar(char *pC) { int c; if (!m_fp) return 0; if ((c = fgetc(m_fp)) == EOF) return 0; fseek(m_fp, -1, SEEK_CUR); *pC = (char)c; return 1; } int CBDDiskFile::ReadChar(char *pC) { int c; if (!m_fp) return 0; if ((c = fgetc(m_fp)) == EOF) return 0; *pC = (char)c; return 1; } int CBDDiskFile::Seek(long iAmount, int iFrom) { if (!m_fp) return 0; // switch(iFrom) { case BD_SEEK_SET: if (fseek(m_fp, iAmount, SEEK_SET)) return 0; break; case BD_SEEK_CUR: if (fseek(m_fp, iAmount, SEEK_CUR)) return 0; break; case BD_SEEK_END: if (fseek(m_fp, iAmount, SEEK_END)) return 0; break; } return 1; } int CBDDiskFile::EndOfFile(void) { if (m_fp) return feof(m_fp); else return 1; }
MarquisdeGeek/html_parser
parse/cmn/BDDiskFile.cpp
C++
gpl-2.0
1,208
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.service.operator; import java.util.Collections; import java.util.Map; import java.util.Set; import org.n52.sos.exception.ConfigurationException; import org.n52.sos.ogc.ows.OwsExceptionReport; import org.n52.sos.request.operator.RequestOperatorRepository; import org.n52.sos.util.AbstractConfiguringServiceLoaderRepository; import org.n52.sos.util.CollectionHelper; import org.n52.sos.util.MultiMaps; import org.n52.sos.util.SetMultiMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * @author Christian Autermann <c.autermann@52north.org> * * @since 4.0.0 */ public class ServiceOperatorRepository extends AbstractConfiguringServiceLoaderRepository<ServiceOperator> { private static class LazyHolder { private static final ServiceOperatorRepository INSTANCE = new ServiceOperatorRepository(); private LazyHolder() {}; } /** * Implemented ServiceOperator */ private final Map<ServiceOperatorKey, ServiceOperator> serviceOperators = Maps.newHashMap(); /** supported SOS versions */ private final SetMultiMap<String, String> supportedVersions = MultiMaps.newSetMultiMap(); /** supported services */ private final Set<String> supportedServices = Sets.newHashSet(); /** * Load implemented request listener * * @throws ConfigurationException * If no request listener is implemented */ private ServiceOperatorRepository() throws ConfigurationException { super(ServiceOperator.class, false); load(false); } public static ServiceOperatorRepository getInstance() { return LazyHolder.INSTANCE; } /** * Load the implemented request listener and add them to a map with * operation name as key * * @param implementations * the loaded implementations * * @throws ConfigurationException * If no request listener is implemented */ @Override protected void processConfiguredImplementations(final Set<ServiceOperator> implementations) throws ConfigurationException { serviceOperators.clear(); supportedServices.clear(); supportedVersions.clear(); for (final ServiceOperator so : implementations) { serviceOperators.put(so.getServiceOperatorKey(), so); supportedVersions.add(so.getServiceOperatorKey().getService(), so.getServiceOperatorKey() .getVersion()); supportedServices.add(so.getServiceOperatorKey().getService()); } } /** * Update/reload the implemented request listener * * @throws ConfigurationException * If no request listener is implemented */ @Override public void update() throws ConfigurationException { RequestOperatorRepository.getInstance().update(); super.update(); } /** * @return the implemented request listener */ public Map<ServiceOperatorKey, ServiceOperator> getServiceOperators() { return Collections.unmodifiableMap(serviceOperators); } public Set<ServiceOperatorKey> getServiceOperatorKeyTypes() { return getServiceOperators().keySet(); } public ServiceOperator getServiceOperator(final ServiceOperatorKey sok) { return serviceOperators.get(sok); } /** * @param service * the service * @param version * the version * @return the implemented request listener * * * @throws OwsExceptionReport */ public ServiceOperator getServiceOperator(final String service, final String version) throws OwsExceptionReport { return getServiceOperator(new ServiceOperatorKey(service, version)); } /** * @return the supportedVersions * * @deprecated use getSupporteVersions(String service) */ @Deprecated public Set<String> getSupportedVersions() { return getAllSupportedVersions(); } public Set<String> getAllSupportedVersions() { return CollectionHelper.union(supportedVersions.values()); } /** * @param service * the service * @return the supportedVersions * */ public Set<String> getSupportedVersions(final String service) { if (isServiceSupported(service)) { return Collections.unmodifiableSet(supportedVersions.get(service)); } return Sets.newHashSet(); } /** * @param version * the version * @return the supportedVersions * * @deprecated use isVersionSupported(String service, String version) */ @Deprecated public boolean isVersionSupported(final String version) { return getAllSupportedVersions().contains(version); } /** * @param service * the service * @param version * the version * @return the supportedVersions * */ public boolean isVersionSupported(final String service, final String version) { return isServiceSupported(service) && supportedVersions.get(service).contains(version); } /** * @return the supportedVersions */ public Set<String> getSupportedServices() { return Collections.unmodifiableSet(supportedServices); } public boolean isServiceSupported(final String service) { return supportedServices.contains(service); } }
ahuarte47/SOS
core/api/src/main/java/org/n52/sos/service/operator/ServiceOperatorRepository.java
Java
gpl-2.0
6,805
class Solution { public: int singleNumber(vector<int>& nums) { const int n = nums.size(); if (n == 1) return nums[0]; int result = nums[0]; for (int i = 1; i < n; ++i){ result ^= nums[i]; } return result; } };
ztongfighton/Leetcode-Answers
Single Number.cpp
C++
gpl-2.0
278
<?PHP /* Copyright (C) 2001-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2008 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis@dolibarr.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * \file htdocs/fourn/commande/liste.php * \ingroup fournisseur * \brief Liste des commandes fournisseurs * \version $Id$ */ require("./pre.inc.php"); $langs->load("orders"); $sref=isset($_GET['search_ref'])?$_GET['search_ref']:$_POST['search_ref']; $snom=isset($_GET['search_nom'])?$_GET['search_nom']:$_POST['search_nom']; $suser=isset($_GET['search_user'])?$_GET['search_user']:$_POST['search_user']; $sttc=isset($_GET['search_ttc'])?$_GET['search_ttc']:$_POST['search_ttc']; $sall=isset($_GET['search_all'])?$_GET['search_all']:$_POST['search_all']; $page = ( is_numeric($_GET["page"]) ? $_GET["page"] : 0 ); $socid = ( is_numeric($_GET["socid"]) ? $_GET["socid"] : 0 ); $sortorder = $_GET["sortorder"]; $sortfield = $_GET["sortfield"]; // Security check $orderid = isset($_GET["orderid"])?$_GET["orderid"]:''; if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'commande_fournisseur', $orderid,''); /* * View */ $title = $langs->trans("SuppliersOrders"); if ($socid > 0) { $fourn = new Fournisseur($db); $fourn->fetch($socid); $title .= ' (<a href="liste.php">'.$fourn->nom.'</a>)'; } llxHeader('',$title); $commandestatic=new CommandeFournisseur($db); if ($sortorder == "") $sortorder="DESC"; if ($sortfield == "") $sortfield="cf.date_creation"; $offset = $conf->liste_limit * $page ; /* * Mode Liste */ $sql = "SELECT s.rowid as socid, s.nom, ".$db->pdate("cf.date_commande")." as dc,"; $sql.= " cf.rowid,cf.ref, cf.fk_statut, cf.total_ttc, cf.fk_user_author,"; $sql.= " u.login"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s,"; $sql.= " ".MAIN_DB_PREFIX."commande_fournisseur as cf"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ")"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON cf.fk_user_author = u.rowid"; $sql.= " WHERE cf.fk_soc = s.rowid "; $sql.= " AND s.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($sref) { $sql.= " AND cf.ref LIKE '%".addslashes($sref)."%'"; } if ($snom) { $sql.= " AND s.nom LIKE '%".addslashes($snom)."%'"; } if ($suser) { $sql.= " AND u.login LIKE '%".addslashes($suser)."%'"; } if ($sttc) { $sql .= " AND total_ttc = ".price2num($sttc); } if ($sall) { $sql.= " AND (cf.ref like '%".addslashes($sall)."%' OR cf.note like '%".addslashes($sall)."%')"; } if ($socid) $sql.= " AND s.rowid = ".$socid; if (strlen($_GET["statut"])) { $sql .= " AND fk_statut =".$_GET["statut"]; } $sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit+1, $offset); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; print_barre_liste($title, $page, "liste.php", "", $sortfield, $sortorder, '', $num); print '<form action="liste.php" method="GET">'; print '<table class="liste">'; print '<tr class="liste_titre">'; print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"cf.ref","","",'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom","","",'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Author"),$_SERVER["PHP_SELF"],"u.login","","",'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"total_ttc","","",'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("OrderDate"),$_SERVER["PHP_SELF"],"dc","","",'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"cf.fk_statut","","",'align="right"',$sortfield,$sortorder); print "</tr>\n"; print '<tr class="liste_titre">'; print '<td class="liste_titre"><input type="text" class="flat" name="search_ref" value="'.$sref.'"></td>'; print '<td class="liste_titre"><input type="text" class="flat" name="search_nom" value="'.$snom.'"></td>'; print '<td class="liste_titre"><input type="text" class="flat" name="search_user" value="'.$suser.'"></td>'; print '<td class="liste_titre"><input type="text" class="flat" name="search_ttc" value="'.$sttc.'"></td>'; print '<td colspan="2" class="liste_titre" align="right">'; print '<input type="image" class="liste_titre" name="button_search" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/search.png" alt="'.$langs->trans("Search").'">'; print '</td>'; print '</tr>'; $var=true; $userstatic = new User($db); while ($i < min($num,$conf->liste_limit)) { $obj = $db->fetch_object($resql); $var=!$var; print "<tr $bc[$var]>"; // Ref print '<td><a href="'.DOL_URL_ROOT.'/fourn/commande/fiche.php?id='.$obj->rowid.'">'.img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.'</a></td>'."\n"; // Company print '<td><a href="'.DOL_URL_ROOT.'/fourn/fiche.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"),"company").' '; print $obj->nom.'</a></td>'."\n"; // Author $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; print "<td>"; if ($userstatic->id) print $userstatic->getLoginUrl(1); else print "&nbsp;"; print "</td>"; // Amount print '<td align="right" width="100">'.price($obj->total_ttc)."</td>"; // Date print "<td align=\"center\" width=\"100\">"; if ($obj->dc) { print dol_print_date($obj->dc,"day"); } else { print "-"; } print '</td>'; // Statut print '<td align="right">'.$commandestatic->LibStatut($obj->fk_statut, 5).'</td>'; print "</tr>\n"; $i++; } print "</table>\n"; print "</form>\n"; $db->free($resql); } else { dol_print_error($db); } $db->close(); llxFooter('$Date$ - $Revision$'); ?>
philazerty/dolibarr
htdocs/fourn/commande/liste.php
PHP
gpl-2.0
6,930
/* Copyright(C) 2013 Danny Sok <danny.sok@outlook.com> This program is free software : you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.If not, see <http://www.gnu.org/licenses/>. */ // ---------------------------------------- // Filename: AIGame.cpp // Description: Represents the state of the game from the AI perspective // Author: Danny Sok // Date Created: 9/08/2013 // Date Last Modified: 27/09/2013 #include "AIGame.h" #include "..\game\Game.h" AIGame::~AIGame() { //destroy(); } void AIGame::init() { m_hands.reserve(4); m_deck.reserve(52); } void AIGame::init(std::vector< std::vector<Card> > hands, int playerPos, int passCount, bool isFreeReign) { m_hands = hands; m_originalPlayerPos = playerPos; m_playerPos = playerPos; m_passCount = passCount; m_playerCount = Game::getInstance().getPlayerCount(); m_isGuessMode = false; m_isFreeReign = isFreeReign; m_turnCount++; m_depthCount = 1; } void AIGame::init(std::vector<Card> deck, std::vector<Card> playerHand, int playerPos, int passCount, bool isFreeReign) { m_deck = deck; m_playerPos = playerPos; m_originalPlayerPos = playerPos; m_passCount = passCount; m_playerCount = Game::getInstance().getPlayerCount(); m_isGuessMode = true; m_isFreeReign = isFreeReign; m_depthCount = 1; m_turnCount++; m_playerHand.insert(m_playerHand.end(), playerHand.begin(), playerHand.end()); deal(); } void AIGame::initAddedHands(int playerPos, int passCount, int originalPlayerPos, bool guessMode, bool isFreeReign, int depth) { m_playerPos = playerPos; m_originalPlayerPos = originalPlayerPos; m_playerCount = Game::getInstance().getPlayerCount(); m_passCount = passCount % m_playerCount; m_isGuessMode = guessMode; //m_isGuessMode = guessMode; m_isFreeReign = isFreeReign; m_depthCount = depth+1; // This will be needed to ensure we don't use too much memory. Just say the game is over. m_turnCount++; } void AIGame::destroy() { m_hands.clear(); m_hands.shrink_to_fit(); m_deck.clear(); m_deck.shrink_to_fit(); } void AIGame::setGuessMode(bool b) { m_isGuessMode = b; } void AIGame::deal() { int size = 0; for (int i = 0; i < m_playerCount; i++) { if (i != m_playerPos) { std::vector<Card> hand; if (Game::getInstance().getPlayer(i)->lock()) { size = Game::getInstance().getPlayer(i)->getCards().size(); Game::getInstance().getPlayer(i)->unlock(); } for (int j = 0; j < size; j++) { m_deck[j].clearImgs(); hand.push_back(m_deck[j]); } m_hands.push_back(sortCards(hand)); } else { //m_hands[m_playerPos].insert(m_hands[m_playerPos].end(), m_playerHand.begin(), m_playerHand.end()); m_hands.push_back(m_playerHand); } } } void AIGame::addHand(std::vector<Card> hand) { m_hands.push_back(hand); } int AIGame::getPlayerCount() { return m_playerCount; } int AIGame::getPassCount() { return m_passCount; } std::vector<Card> AIGame::getHand(int pos) { return m_hands[pos]; } bool AIGame::isOver() { bool b = false; if (m_depthCount >= 2) return true; // Stop generating any children once we are 10 nodes deep // If it isn't guess mode (i.e. god mode) then search for a winner normally if (!m_isGuessMode) { if (isWinner()) return true; } // otherwise for guess mode, stop the search once it hits a free reign turn else { if (isWinner()) return true; else if (isFreeReign()) return true; } return b; } bool AIGame::isWinner(int playerNum) { return m_hands[playerNum].size() == 0; } bool AIGame::isWinner() { return m_hands[m_originalPlayerPos].size() == 0; } bool AIGame::isFreeReign(int playerNum) { return m_isFreeReign && m_originalPlayerPos == playerNum; } bool AIGame::isFreeReign() { return m_isFreeReign && m_originalPlayerPos == m_playerPos; } std::vector<Card> AIGame::sortCards(std::vector<Card> pHand) { auto hand = pHand; //std::sort(cards.begin(), cards.end(), cmp()); int swapped; int i; for (i = 1; i < hand.size(); i++) { swapped = 0; //this flag is to check if the array is already sorted int j; Card temp; for(j = 0; j < hand.size() - i; j++) { if (hand[j].getNumber() > hand[j + 1].getNumber()) { if (! (hand[j + 1].getNumber() == Ace || hand[j + 1].getNumber() == Two) ) { temp = hand[j]; hand[j] = hand[j+1]; hand[j+1] = temp; swapped = 1; } } else if (hand[j].getNumber() < hand[j + 1].getNumber()) { if (hand[j].getNumber() == Ace || hand[j].getNumber() == Two) { temp = hand[j]; hand[j] = hand[j+1]; hand[j+1] = temp; swapped = 1; } } else //if left.Number == right.Number { if (hand[j].getSuite() > hand[j + 1].getSuite()) { temp = hand[j]; hand[j] = hand[j+1]; hand[j+1] = temp; swapped = 1; } } if (hand[j].getNumber() == Two && hand[j + 1].getNumber() == Ace) { temp = hand[j]; hand[j] = hand[j+1]; hand[j+1] = temp; swapped = 1; } } if(!swapped){ break; //if it is sorted then stop } } return hand; } int AIGame::getOriginalPlayerPos() { return m_originalPlayerPos; } int AIGame::getDepth() { return m_depthCount; }
danruto/Thirteen
src/ai/AIGame.cpp
C++
gpl-2.0
5,626
#include "Common.h" #include "Database/DatabaseEnv.h" #include "ItemPrototype.h" #include "World.h" #include "SpellMgr.h" #include "PlayerbotAI.h" #include "PlayerbotMgr.h" #include "PlayerbotDeathKnightAI.h" #include "PlayerbotDruidAI.h" #include "PlayerbotHunterAI.h" #include "PlayerbotMageAI.h" #include "PlayerbotPaladinAI.h" #include "PlayerbotPriestAI.h" #include "PlayerbotRogueAI.h" #include "PlayerbotShamanAI.h" #include "PlayerbotWarlockAI.h" #include "PlayerbotWarriorAI.h" #include "Player.h" #include "ObjectMgr.h" #include "Chat.h" #include "WorldPacket.h" #include "Spell.h" #include "Unit.h" #include "SpellAuras.h" #include "SharedDefines.h" #include "Log.h" #include "GossipDef.h" // returns a float in range of.. float rand_float(float low, float high) { return (rand() / (static_cast<float> (RAND_MAX) + 1.0)) * (high - low) + low; } /* * Packets often compress the GUID (global unique identifier) * This function extracts the guid from the packet and decompresses it. * The first word (8 bits) in the packet represents how many words in the following packet(s) are part of * the guid and what weight they hold. I call it the mask. For example) if mask is 01001001, * there will be only 3 words. The first word is shifted to the left 0 times, * the second is shifted 3 times, and the third is shifted 6. * * Possibly use ByteBuffer::readPackGUID? */ uint64 extractGuid(WorldPacket& packet) { uint8 mask; packet >> mask; uint64 guid = 0; uint8 bit = 0; uint8 testMask = 1; while (true) { if (mask & testMask) { uint8 word; packet >> word; guid += (word << bit); } if (bit == 7) break; ++bit; testMask <<= 1; } return guid; } // ChatHandler already implements some useful commands the master can call on bots // These commands are protected inside the ChatHandler class so this class provides access to the commands // we'd like to call on our bots class PlayerbotChatHandler: protected ChatHandler { public: explicit PlayerbotChatHandler(Player* pMasterPlayer) : ChatHandler(pMasterPlayer) {} bool revive(const Player& botPlayer) { return HandleReviveCommand(botPlayer.GetName()); } bool teleport(const Player& botPlayer) { return HandleNamegoCommand(botPlayer.GetName()); } void sysmessage(const char *str) { SendSysMessage(str); } bool dropQuest(const char *str) { return HandleQuestRemove(str); } }; PlayerbotAI::PlayerbotAI(PlayerbotMgr* const mgr, Player* const bot) : m_mgr(mgr), m_bot(bot), m_ignoreAIUpdatesUntilTime(0), m_combatOrder(ORDERS_NONE), m_ScenarioType(SCENARIO_PVEEASY), m_TimeDoneEating(0), m_TimeDoneDrinking(0), m_CurrentlyCastingSpellId(0), m_spellIdCommand(0), m_targetGuidCommand(0), m_classAI(0) { // set bot state and needed item list m_botState = BOTSTATE_NORMAL; SetQuestNeedItems(); // reset some pointers m_targetChanged = false; m_targetType = TARGET_NORMAL; m_targetCombat = 0; m_targetAssist = 0; m_targetProtect = 0; // start following master (will also teleport bot to master) SetMovementOrder( MOVEMENT_FOLLOW, GetMaster() ); // get class specific ai switch (m_bot->getClass()) { case CLASS_PRIEST: m_combatStyle = COMBAT_RANGED; m_classAI = (PlayerbotClassAI*) new PlayerbotPriestAI(GetMaster(), m_bot, this); break; case CLASS_MAGE: m_combatStyle = COMBAT_RANGED; m_classAI = (PlayerbotClassAI*) new PlayerbotMageAI(GetMaster(), m_bot, this); break; case CLASS_WARLOCK: m_combatStyle = COMBAT_RANGED; m_classAI = (PlayerbotClassAI*) new PlayerbotWarlockAI(GetMaster(), m_bot, this); break; case CLASS_WARRIOR: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*) new PlayerbotWarriorAI(GetMaster(), m_bot, this); break; case CLASS_SHAMAN: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*) new PlayerbotShamanAI(GetMaster(), m_bot, this); break; case CLASS_PALADIN: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*) new PlayerbotPaladinAI(GetMaster(), m_bot, this); break; case CLASS_ROGUE: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*) new PlayerbotRogueAI(GetMaster(), m_bot, this); break; case CLASS_DRUID: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*) new PlayerbotDruidAI(GetMaster(), m_bot, this); break; case CLASS_HUNTER: m_combatStyle = COMBAT_RANGED; m_classAI = (PlayerbotClassAI*)new PlayerbotHunterAI(GetMaster(), m_bot, this); break; case CLASS_DEATH_KNIGHT: m_combatStyle = COMBAT_MELEE; m_classAI = (PlayerbotClassAI*)new PlayerbotDeathKnightAI(GetMaster(), m_bot, this); break; } } PlayerbotAI::~PlayerbotAI() { if (m_classAI) delete m_classAI; } Player* PlayerbotAI::GetMaster() const { return m_mgr->GetMaster(); } // finds spell ID for matching substring args // in priority of full text match, spells not taking reagents, and highest rank uint32 PlayerbotAI::getSpellId(const char* args, bool master) const { if (!*args) return 0; std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) return 0; // converting string that we try to find to lower case wstrToLower(wnamepart); int loc = 0; if (master) loc = GetMaster()->GetSession()->GetSessionDbcLocale(); else loc = m_bot->GetSession()->GetSessionDbcLocale(); uint32 foundSpellId = 0; bool foundExactMatch = false; bool foundMatchUsesNoReagents = false; for (PlayerSpellMap::iterator itr = m_bot->GetSpellMap().begin(); itr != m_bot->GetSpellMap().end(); ++itr) { uint32 spellId = itr->first; if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled || IsPassiveSpell(spellId)) continue; const SpellEntry* pSpellInfo = sSpellStore.LookupEntry(spellId); if (!pSpellInfo) continue; const std::string name = pSpellInfo->SpellName[loc]; if (name.empty() || !Utf8FitTo(name, wnamepart)) continue; bool isExactMatch = (name.length() == wnamepart.length()) ? true : false; bool usesNoReagents = (pSpellInfo->Reagent[0] <= 0) ? true : false; // if we already found a spell bool useThisSpell = true; if (foundSpellId > 0) { if (isExactMatch && !foundExactMatch) {} else if (usesNoReagents && !foundMatchUsesNoReagents) {} else if (spellId > foundSpellId) {} else useThisSpell = false; } if (useThisSpell) { foundSpellId = spellId; foundExactMatch = isExactMatch; foundMatchUsesNoReagents = usesNoReagents; } } return foundSpellId; } /* * Send a list of equipment that is in bot's inventor that is currently unequipped. * This is called when the master is inspecting the bot. */ void PlayerbotAI::SendNotEquipList(Player& player) { // find all unequipped items and put them in // a vector of dynamically created lists where the vector index is from 0-18 // and the list contains Item* that can be equipped to that slot // Note: each dynamically created list in the vector must be deleted at end // so NO EARLY RETURNS! // see enum EquipmentSlots in Player.h to see what equipment slot each index in vector // is assigned to. (The first is EQUIPMENT_SLOT_HEAD=0, and last is EQUIPMENT_SLOT_TABARD=18) std::list<Item*>* equip[19]; for (uint8 i = 0; i < 19; ++i) equip[i] = NULL; // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!pItem) continue; uint16 dest; uint8 msg = m_bot->CanEquipItem(NULL_SLOT, dest, pItem, !pItem->IsBag()); if (msg != EQUIP_ERR_OK) continue; // the dest looks like it includes the old loc in the 8 higher bits // so casting it to a uint8 strips them uint8 equipSlot = uint8(dest); if (!(equipSlot >= 0 && equipSlot < 19)) continue; // create a list if one doesn't already exist if (equip[equipSlot] == NULL) equip[equipSlot] = new std::list<Item*>; std::list<Item*>* itemListForEqSlot = equip[equipSlot]; itemListForEqSlot->push_back(pItem); } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (!pItem) continue; uint16 equipSlot; uint8 msg = m_bot->CanEquipItem(NULL_SLOT, equipSlot, pItem, !pItem->IsBag()); if (msg != EQUIP_ERR_OK) continue; if (!(equipSlot >= 0 && equipSlot < 19)) continue; // create a list if one doesn't already exist if (equip[equipSlot] == NULL) equip[equipSlot] = new std::list<Item*>; std::list<Item*>* itemListForEqSlot = equip[equipSlot]; itemListForEqSlot->push_back(pItem); } } } TellMaster("Here's all the items in my inventory that I can equip."); ChatHandler ch(GetMaster()); const std::string descr[] = { "head", "neck", "shoulders", "body", "chest", "waist", "legs", "feet", "wrists", "hands", "finger1", "finger2", "trinket1", "trinket2", "back", "mainhand", "offhand", "ranged", "tabard" }; // now send client all items that can be equipped by slot for (uint8 equipSlot = 0; equipSlot < 19; ++equipSlot) { if (equip[equipSlot] == NULL) continue; std::list<Item*>* itemListForEqSlot = equip[equipSlot]; std::ostringstream out; out << descr[equipSlot] << ": "; for (std::list<Item*>::iterator it = itemListForEqSlot->begin(); it != itemListForEqSlot->end(); ++it) { const ItemPrototype* const pItemProto = (*it)->GetProto(); std::string itemName = pItemProto->Name1; ItemLocalization(itemName, pItemProto->ItemId); out << " |cffffffff|Hitem:" << pItemProto->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; } ch.SendSysMessage(out.str().c_str()); delete itemListForEqSlot; // delete list of Item* } } void PlayerbotAI::SendQuestItemList( Player& player ) { std::ostringstream out; for( BotNeedItem::iterator itr=m_needItemList.begin(); itr!=m_needItemList.end(); ++itr ) { const ItemPrototype * pItemProto = sObjectMgr.GetItemPrototype( itr->first ); std::string itemName = pItemProto->Name1; ItemLocalization(itemName, pItemProto->ItemId); out << " " << itr->second << "x|cffffffff|Hitem:" << pItemProto->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; } TellMaster( "Here's a list of all items I need for quests:" ); TellMaster( out.str().c_str() ); } void PlayerbotAI::SendOrders( Player& player ) { std::ostringstream out; if( !m_combatOrder ) out << "Got no combat orders!"; else if( m_combatOrder&ORDERS_TANK ) out << "I TANK"; else if( m_combatOrder&ORDERS_ASSIST ) out << "I ASSIST " << (m_targetAssist?m_targetAssist->GetName():"unknown"); else if( m_combatOrder&ORDERS_HEAL ) out << "I HEAL"; if( (m_combatOrder&ORDERS_PRIMARY) && (m_combatOrder&ORDERS_SECONDARY) ) out << " and "; if( m_combatOrder&ORDERS_PROTECT ) out << "I PROTECT " << (m_targetProtect?m_targetProtect->GetName():"unknown"); out << "."; if( m_mgr->m_confDebugWhisper ) { out << " " << (IsInCombat()?"I'm in COMBAT! ":"Not in combat. "); out << "Current state is "; if( m_botState == BOTSTATE_NORMAL ) out << "NORMAL"; else if( m_botState == BOTSTATE_COMBAT ) out << "COMBAT"; else if( m_botState == BOTSTATE_DEAD ) out << "DEAD"; else if( m_botState == BOTSTATE_DEADRELEASED ) out << "RELEASED"; else if( m_botState == BOTSTATE_LOOTING ) out << "LOOTING"; out << ". Movement order is "; if( m_movementOrder == MOVEMENT_NONE ) out << "NONE"; else if( m_movementOrder == MOVEMENT_FOLLOW ) out << "FOLLOW " << (m_followTarget?m_followTarget->GetName():"unknown"); else if( m_movementOrder == MOVEMENT_STAY ) out << "STAY"; out << ". Got " << m_attackerInfo.size() << " attacker(s) in list."; out << " Next action in " << (m_ignoreAIUpdatesUntilTime-time(0)) << "sec."; } TellMaster( out.str().c_str() ); } // handle outgoing packets the server would send to the client void PlayerbotAI::HandleBotOutgoingPacket(const WorldPacket& packet) { switch (packet.GetOpcode()) { case SMSG_DUEL_WINNER: { m_bot->HandleEmoteCommand(EMOTE_ONESHOT_APPLAUD); return; } case SMSG_DUEL_COMPLETE: { m_ignoreAIUpdatesUntilTime = time(0) + 4; m_ScenarioType = SCENARIO_PVEEASY; m_bot->GetMotionMaster()->Clear(true); return; } case SMSG_DUEL_OUTOFBOUNDS: { m_bot->HandleEmoteCommand(EMOTE_ONESHOT_CHICKEN); return; } case SMSG_DUEL_REQUESTED: { m_ignoreAIUpdatesUntilTime = 0; WorldPacket p(packet); uint64 flagGuid; p >> flagGuid; uint64 playerGuid; p >> playerGuid; Player* const pPlayer = ObjectAccessor::FindPlayer(playerGuid); if (canObeyCommandFrom(*pPlayer)) { m_bot->GetMotionMaster()->Clear(true); WorldPacket* const packet = new WorldPacket(CMSG_DUEL_ACCEPTED, 8); *packet << flagGuid; m_bot->GetSession()->QueuePacket(packet); // queue the packet to get around race condition // follow target in casting range float angle = rand_float(0, M_PI_F); float dist = rand_float(4, 10); m_bot->GetMotionMaster()->Clear(true); m_bot->GetMotionMaster()->MoveFollow(pPlayer, dist, angle); m_bot->SetSelection(playerGuid); m_ignoreAIUpdatesUntilTime = time(0) + 4; m_ScenarioType = SCENARIO_DUEL; } return; } case SMSG_INVENTORY_CHANGE_FAILURE: { TellMaster("I can't use that."); return; } case SMSG_SPELL_FAILURE: { WorldPacket p(packet); uint64 casterGuid = extractGuid(p); if (casterGuid != m_bot->GetGUID()) return; uint32 spellId; p >> spellId; if (m_CurrentlyCastingSpellId == spellId) { m_ignoreAIUpdatesUntilTime = time(0) + 1; m_CurrentlyCastingSpellId = 0; } return; } // if a change in speed was detected for the master // make sure we have the same mount status case SMSG_FORCE_RUN_SPEED_CHANGE: { WorldPacket p(packet); uint64 guid = extractGuid(p); if (guid != GetMaster()->GetGUID()) return; if (GetMaster()->IsMounted() && !m_bot->IsMounted()) { //Player Part if (!GetMaster()->GetAurasByType(SPELL_AURA_MOUNTED).empty()) { int32 master_speed1 = 0; int32 master_speed2 = 0; master_speed1 = GetMaster()->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetSpellProto()->EffectBasePoints[1]; master_speed2 = GetMaster()->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetSpellProto()->EffectBasePoints[2]; //Bot Part uint32 spellMount = 0; for(PlayerSpellMap::iterator itr = m_bot->GetSpellMap().begin(); itr != m_bot->GetSpellMap().end(); ++itr) { uint32 spellId = itr->first; if(itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled || IsPassiveSpell(spellId)) continue; const SpellEntry* pSpellInfo = sSpellStore.LookupEntry(spellId); if (!pSpellInfo) continue; if(pSpellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOUNTED) { if(pSpellInfo->EffectApplyAuraName[1] == SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED) { if(pSpellInfo->EffectBasePoints[1] == master_speed1) { spellMount = spellId; break; } } else if((pSpellInfo->EffectApplyAuraName[1] == SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED) && (pSpellInfo->EffectApplyAuraName[2] == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED)) { if((pSpellInfo->EffectBasePoints[1] == master_speed1) && (pSpellInfo->EffectBasePoints[2] == master_speed2)) { spellMount = spellId; break; } } else if((pSpellInfo->EffectApplyAuraName[2] == SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED) && (pSpellInfo->EffectApplyAuraName[1] == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED)) { if((pSpellInfo->EffectBasePoints[2] == master_speed2) && (pSpellInfo->EffectBasePoints[1] == master_speed1)) { spellMount = spellId; break; } } } } if(spellMount > 0) m_bot->CastSpell(m_bot, spellMount, false); } } else if (!GetMaster()->IsMounted() && m_bot->IsMounted()) { WorldPacket emptyPacket; m_bot->GetSession()->HandleCancelMountAuraOpcode(emptyPacket); //updated code } return; } // handle flying acknowledgement case SMSG_MOVE_SET_CAN_FLY: { WorldPacket p(packet); uint64 guid = extractGuid(p); if (guid != m_bot->GetGUID()) return; m_bot->m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING); //m_bot->SetSpeed(MOVE_RUN, GetMaster()->GetSpeed(MOVE_FLIGHT) +0.1f, true); return; } // handle dismount flying acknowledgement case SMSG_MOVE_UNSET_CAN_FLY: { WorldPacket p(packet); uint64 guid = extractGuid(p); if (guid != m_bot->GetGUID()) return; m_bot->m_movementInfo.RemoveMovementFlag(MOVEFLAG_FLYING); //m_bot->SetSpeed(MOVE_RUN,GetMaster()->GetSpeedRate(MOVE_RUN),true); return; } // If the leader role was given to the bot automatically give it to the master // if the master is in the group, otherwise leave group case SMSG_GROUP_SET_LEADER: { WorldPacket p(packet); std::string name; p >> name; if (m_bot->GetGroup() && name == m_bot->GetName()) { if (m_bot->GetGroup()->IsMember(GetMaster()->GetGUID())) { p.resize(8); p << GetMaster()->GetGUID(); m_bot->GetSession()->HandleGroupSetLeaderOpcode(p); } else { p.clear(); // not really needed m_bot->GetSession()->HandleGroupDisbandOpcode(p); // packet not used updated code } } return; } // If the master leaves the group, then the bot leaves too case SMSG_PARTY_COMMAND_RESULT: { WorldPacket p(packet); uint32 operation; p >> operation; std::string member; p >> member; uint32 result; p >> result; p.clear(); if (operation == PARTY_OP_LEAVE) { if (member == GetMaster()->GetName()) m_bot->GetSession()->HandleGroupDisbandOpcode(p); // packet not used updated code } return; } // Handle Group invites (auto accept if master is in group, otherwise decline & send message case SMSG_GROUP_INVITE: { if (m_bot->GetGroupInvite()) { const Group* const grp = m_bot->GetGroupInvite(); if (!grp) return; Player* const inviter = sObjectMgr.GetPlayer(grp->GetLeaderGUID()); if (!inviter) return; WorldPacket p; if (!canObeyCommandFrom(*inviter)) { std::string buf = "I can't accept your invite unless you first invite my master "; buf += GetMaster()->GetName(); buf += "."; SendWhisper(buf, *inviter); m_bot->GetSession()->HandleGroupDeclineOpcode(p); // packet not used } else m_bot->GetSession()->HandleGroupAcceptOpcode(p); // packet not used } return; } // Handle when another player opens the trade window with the bot // also sends list of tradable items bot can trade if bot is allowed to obey commands from case SMSG_TRADE_STATUS: { if (m_bot->GetTrader() == NULL) break; WorldPacket p(packet); uint32 status; p >> status; p.resize(4); //4 == TRADE_STATUS_TRADE_ACCEPT if (status == 4) m_bot->GetSession()->HandleAcceptTradeOpcode(p); // packet not used //1 == TRADE_STATUS_BEGIN_TRADE else if (status == 1) { m_bot->GetSession()->HandleBeginTradeOpcode(p); // packet not used if (!canObeyCommandFrom(*(m_bot->GetTrader()))) { SendWhisper("I'm not allowed to trade you any of my items, but you are free to give me money or items.", *(m_bot->GetTrader())); return; } // list out items available for trade std::ostringstream out; // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { const Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem && pItem->CanBeTraded()) { const ItemPrototype* const pItemProto = pItem->GetProto(); std::string itemName = pItemProto->Name1; ItemLocalization(itemName, pItemProto->ItemId); out << " |cffffffff|Hitem:" << pItemProto->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; if (pItem->GetCount() > 1) out << "x" << pItem->GetCount() << ' '; } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { const Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem && pItem->CanBeTraded()) { const ItemPrototype* const pItemProto = pItem->GetProto(); std::string itemName = pItemProto->Name1; ItemLocalization(itemName, pItemProto->ItemId); // item link format: http://www.wowwiki.com/ItemString // itemId, enchantId, jewelId1, jewelId2, jewelId3, jewelId4, suffixId, uniqueId out << " |cffffffff|Hitem:" << pItemProto->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; if (pItem->GetCount() > 1) out << "x" << pItem->GetCount() << ' '; } } } } // calculate how much money bot has uint32 copper = m_bot->GetMoney(); uint32 gold = uint32(copper / 10000); copper -= (gold * 10000); uint32 silver = uint32(copper / 100); copper -= (silver * 100); // send bot the message std::ostringstream whisper; whisper << "I have |cff00ff00" << gold << "|r|cfffffc00g|r|cff00ff00" << silver << "|r|cffcdcdcds|r|cff00ff00" << copper << "|r|cffffd333c|r" << " and the following items:"; SendWhisper(whisper.str().c_str(), *(m_bot->GetTrader())); ChatHandler ch(m_bot->GetTrader()); ch.SendSysMessage(out.str().c_str()); } return; } case SMSG_SPELL_GO: { WorldPacket p(packet); uint64 castItemGuid = extractGuid(p); uint64 casterGuid = extractGuid(p); if (casterGuid != m_bot->GetGUID()) return; uint32 spellId; p >> spellId; uint16 castFlags; p >> castFlags; uint32 msTime; p >> msTime; uint8 numHit; p >> numHit; if (m_CurrentlyCastingSpellId == spellId) { Spell* const pSpell = m_bot->FindCurrentSpellBySpellId(spellId); if (!pSpell) return; if (pSpell->IsChannelActive() || pSpell->IsAutoRepeat()) m_ignoreAIUpdatesUntilTime = time(0) + (GetSpellDuration(pSpell->m_spellInfo) / 1000) + 1; else if (pSpell->IsAutoRepeat()) m_ignoreAIUpdatesUntilTime = time(0) + 6; else { m_ignoreAIUpdatesUntilTime = time(0) + 1; m_CurrentlyCastingSpellId = 0; } } return; } /* uncomment this and your bots will tell you all their outgoing packet opcode names case SMSG_MONSTER_MOVE: case SMSG_UPDATE_WORLD_STATE: case SMSG_COMPRESSED_UPDATE_OBJECT: case MSG_MOVE_SET_FACING: case MSG_MOVE_STOP: case MSG_MOVE_HEARTBEAT: case MSG_MOVE_STOP_STRAFE: case MSG_MOVE_START_STRAFE_LEFT: case SMSG_UPDATE_OBJECT: case MSG_MOVE_START_FORWARD: case MSG_MOVE_START_STRAFE_RIGHT: case SMSG_DESTROY_OBJECT: case MSG_MOVE_START_BACKWARD: case SMSG_AURA_UPDATE_ALL: case MSG_MOVE_FALL_LAND: case MSG_MOVE_JUMP: return; default: { const char* oc = LookupOpcodeName(packet.GetOpcode()); std::ostringstream out; out << "botout: " << oc; sLog.outError(out.str().c_str()); //TellMaster(oc); } */ } } uint8 PlayerbotAI::GetHealthPercent(const Unit& target) const { return (static_cast<float> (target.GetHealth()) / target.GetMaxHealth()) * 100; } uint8 PlayerbotAI::GetHealthPercent() const { return GetHealthPercent(*m_bot); } uint8 PlayerbotAI::GetManaPercent(const Unit& target) const { return (static_cast<float> (target.GetPower(POWER_MANA)) / target.GetMaxPower(POWER_MANA)) * 100; } uint8 PlayerbotAI::GetManaPercent() const { return GetManaPercent(*m_bot); } uint8 PlayerbotAI::GetBaseManaPercent(const Unit& target) const { if (target.GetPower(POWER_MANA) >= target.GetCreateMana()) return (100); else return (static_cast<float> (target.GetPower(POWER_MANA)) / target.GetMaxPower(POWER_MANA)) * 100; } uint8 PlayerbotAI::GetBaseManaPercent() const { return GetBaseManaPercent(*m_bot); } uint8 PlayerbotAI::GetRageAmount(const Unit& target) const { return (static_cast<float> (target.GetPower(POWER_RAGE))); } uint8 PlayerbotAI::GetRageAmount() const { return GetRageAmount(*m_bot); } uint8 PlayerbotAI::GetEnergyAmount(const Unit& target) const { return (static_cast<float> (target.GetPower(POWER_ENERGY))); } uint8 PlayerbotAI::GetEnergyAmount() const { return GetEnergyAmount(*m_bot); } uint8 PlayerbotAI::GetRunicPower(const Unit& target) const { return (static_cast<float>(target.GetPower(POWER_RUNIC_POWER))); } uint8 PlayerbotAI::GetRunicPower() const { return GetRunicPower(*m_bot); } //typedef std::pair<uint32, uint8> spellEffectPair; //typedef std::multimap<spellEffectPair, Aura*> AuraMap; bool PlayerbotAI::HasAura(uint32 spellId, const Unit& player) const { if(spellId <= 0) return false; for (Unit::AuraMap::const_iterator iter = player.GetAuras().begin(); iter != player.GetAuras().end(); ++iter) { if (iter->second->GetId() == spellId) return true; } return false; } bool PlayerbotAI::HasAura(const char* spellName) const { return HasAura(spellName, *m_bot); } bool PlayerbotAI::HasAura(const char* spellName, const Unit& player) const { uint32 spellId = getSpellId(spellName); return (spellId) ? HasAura(spellId, player) : false; } // looks through all items / spells that bot could have to get a mount Item* PlayerbotAI::FindMount(uint32 matchingRidingSkill) const { // list out items in main backpack Item* partialMatch = NULL; for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto) || pItemProto->RequiredSkill != SKILL_RIDING) continue; if (pItemProto->RequiredSkillRank == matchingRidingSkill) return pItem; else if (!partialMatch || (partialMatch && partialMatch->GetProto()->RequiredSkillRank < pItemProto->RequiredSkillRank)) partialMatch = pItem; } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto) || pItemProto->RequiredSkill != SKILL_RIDING) continue; if (pItemProto->RequiredSkillRank == matchingRidingSkill) return pItem; else if (!partialMatch || (partialMatch && partialMatch->GetProto()->RequiredSkillRank < pItemProto->RequiredSkillRank)) partialMatch = pItem; } } } } return partialMatch; } Item* PlayerbotAI::FindFood() const { // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_FOOD) { // if is FOOD // this enum is no longer defined in mangos. Is it no longer valid? // according to google it was 11 if (pItemProto->Spells[0].SpellCategory == 11) return pItem; } } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; // this enum is no longer defined in mangos. Is it no longer valid? // according to google it was 11 if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_FOOD) { // if is FOOD // this enum is no longer defined in mangos. Is it no longer valid? // according to google it was 11 // if (pItemProto->Spells[0].SpellCategory == SPELL_CATEGORY_FOOD) if (pItemProto->Spells[0].SpellCategory == 11) return pItem; } } } } } return NULL; } Item* PlayerbotAI::FindDrink() const { // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_FOOD) { // if (pItemProto->Spells[0].SpellCategory == SPELL_CATEGORY_DRINK) // this enum is no longer defined in mangos. Is it no longer valid? // according to google it was 59 // if (pItemProto->Spells[0].SpellCategory == 59) if (pItemProto->Spells[0].SpellCategory == 59) return pItem; } } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_FOOD) { // if is WATER // SPELL_CATEGORY_DRINK is no longer defined in an enum in mangos // google says the valus is 59. Is this still valid? // if (pItemProto->Spells[0].SpellCategory == SPELL_CATEGORY_DRINK) if (pItemProto->Spells[0].SpellCategory == 59) return pItem; } } } } } return NULL; } Item* PlayerbotAI::FindBandage() const { // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_BANDAGE) return pItem; } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == ITEM_SUBCLASS_BANDAGE) return pItem; } } } } return NULL; } //Find Poison ...Natsukawa Item* PlayerbotAI::FindPoison() const { // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == 6) return pItem; } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto || !m_bot->CanUseItem(pItemProto)) continue; if (pItemProto->Class == ITEM_CLASS_CONSUMABLE && pItemProto->SubClass == 6) return pItem; } } } } return NULL; } void PlayerbotAI::InterruptCurrentCastingSpell() { //TellMaster("I'm interrupting my current spell!"); WorldPacket* const packet = new WorldPacket(CMSG_CANCEL_CAST, 5); //changed from thetourist suggestion *packet << m_CurrentlyCastingSpellId; *packet << m_targetGuidCommand; //changed from thetourist suggestion m_CurrentlyCastingSpellId = 0; m_bot->GetSession()->QueuePacket(packet); } void PlayerbotAI::Feast() { // stand up if we are done feasting if (!(m_bot->GetHealth() < m_bot->GetMaxHealth() || (m_bot->getPowerType() == POWER_MANA && m_bot->GetPower(POWER_MANA) < m_bot->GetMaxPower(POWER_MANA)))) { m_bot->SetStandState(UNIT_STAND_STATE_STAND); return; } // wait 3 seconds before checking if we need to drink more or eat more time_t currentTime = time(0); m_ignoreAIUpdatesUntilTime = currentTime + 3; // should we drink another if (m_bot->getPowerType() == POWER_MANA && currentTime > m_TimeDoneDrinking && ((static_cast<float> (m_bot->GetPower(POWER_MANA)) / m_bot->GetMaxPower(POWER_MANA)) < 0.8)) { Item* pItem = FindDrink(); if (pItem != NULL) { UseItem(*pItem); m_TimeDoneDrinking = currentTime + 30; return; } TellMaster("I need water."); } // should we eat another if (currentTime > m_TimeDoneEating && ((static_cast<float> (m_bot->GetHealth()) / m_bot->GetMaxHealth()) < 0.8)) { Item* pItem = FindFood(); if (pItem != NULL) { //TellMaster("eating now..."); UseItem(*pItem); m_TimeDoneEating = currentTime + 30; return; } TellMaster("I need food."); } // if we are no longer eating or drinking // because we are out of items or we are above 80% in both stats if (currentTime > m_TimeDoneEating && currentTime > m_TimeDoneDrinking) { TellMaster("done feasting!"); m_bot->SetStandState(UNIT_STAND_STATE_STAND); } } // intelligently sets a reasonable combat order for this bot // based on its class / level / etc void PlayerbotAI::GetCombatTarget( Unit* forcedTarget ) { // set combat state, and clear looting, etc... if( m_botState != BOTSTATE_COMBAT ) { SetState( BOTSTATE_COMBAT ); SetQuestNeedItems(); m_lootCreature.clear(); m_lootCurrent = 0; m_targetCombat = 0; } // update attacker info now UpdateAttackerInfo(); // check for attackers on protected unit, and make it a forcedTarget if any if( !forcedTarget && (m_combatOrder&ORDERS_PROTECT) && m_targetProtect!=0 ) { Unit *newTarget = FindAttacker( (ATTACKERINFOTYPE)(AIT_VICTIMNOTSELF|AIT_HIGHESTTHREAT), m_targetProtect ); if( newTarget && newTarget!=m_targetCombat ) { forcedTarget = newTarget; m_targetType = TARGET_THREATEN; if( m_mgr->m_confDebugWhisper ) TellMaster( "Changing target to %s to protect %s", forcedTarget->GetName(), m_targetProtect->GetName() ); } } else if( forcedTarget ) { if( m_mgr->m_confDebugWhisper ) TellMaster( "Changing target to %s by force!", forcedTarget->GetName() ); m_targetType = (m_combatOrder==ORDERS_TANK ? TARGET_THREATEN : TARGET_NORMAL); } // we already have a target and we are not forced to change it if( m_targetCombat && !forcedTarget ) return; // are we forced on a target? if( forcedTarget ) { m_targetCombat = forcedTarget; m_targetChanged = true; } // do we have to assist someone? if( !m_targetCombat && (m_combatOrder&ORDERS_ASSIST) && m_targetAssist!=0 ) { m_targetCombat = FindAttacker( (ATTACKERINFOTYPE)(AIT_VICTIMNOTSELF|AIT_LOWESTTHREAT), m_targetAssist ); if( m_mgr->m_confDebugWhisper && m_targetCombat ) TellMaster( "Attacking %s to assist %s", m_targetCombat->GetName(), m_targetAssist->GetName() ); m_targetType = (m_combatOrder==ORDERS_TANK ? TARGET_THREATEN : TARGET_NORMAL); m_targetChanged = true; } // are there any other attackers? if( !m_targetCombat ) { m_targetCombat = FindAttacker(); m_targetType = (m_combatOrder==ORDERS_TANK ? TARGET_THREATEN : TARGET_NORMAL); m_targetChanged = true; } // no attacker found anyway if (!m_targetCombat) { m_targetType = TARGET_NORMAL; m_targetChanged = false; return; } // if thing to attack is in a duel, then ignore and don't call updateAI for 6 seconds // this method never gets called when the bot is in a duel and this code // prevents bot from helping if (m_targetCombat->GetTypeId() == TYPEID_PLAYER && dynamic_cast<Player*> (m_targetCombat)->duel) { m_ignoreAIUpdatesUntilTime = time(0) + 6; return; } m_bot->SetSelection(m_targetCombat->GetGUID()); m_ignoreAIUpdatesUntilTime = time(0) + 1; if (m_bot->getStandState() != UNIT_STAND_STATE_STAND) m_bot->SetStandState(UNIT_STAND_STATE_STAND); m_bot->Attack(m_targetCombat, true); // add thingToAttack to loot list m_lootCreature.push_back( m_targetCombat->GetGUID() ); // set movement generators for combat movement MovementClear(); return; } void PlayerbotAI::DoNextCombatManeuver() { // check for new targets GetCombatTarget(); // check if we have a target - fixes crash reported by rrtn (kill hunter's pet bug) // if current target for attacks doesn't make sense anymore // clear our orders so we can get orders in next update if( !m_targetCombat || m_targetCombat->isDead() || !m_targetCombat->IsInWorld() || !m_bot->IsHostileTo(m_targetCombat) ) { m_bot->AttackStop(); m_bot->SetSelection(0); MovementReset(); m_bot->InterruptNonMeleeSpells(true); m_targetCombat = 0; m_targetChanged = false; m_targetType = TARGET_NORMAL; return; } // do opening moves, if we changed target if( m_targetChanged ) { if( GetClassAI() ) m_targetChanged = GetClassAI()->DoFirstCombatManeuver( m_targetCombat ); else m_targetChanged = false; } // do normal combat movement DoCombatMovement(); if (GetClassAI() && !m_targetChanged ) (GetClassAI())->DoNextCombatManeuver( m_targetCombat ); } void PlayerbotAI::DoCombatMovement() { if( !m_targetCombat ) return; float targetDist = m_bot->GetDistance( m_targetCombat ); if( m_combatStyle==COMBAT_MELEE && !m_bot->hasUnitState( UNIT_STAT_CHASE ) && ( (m_movementOrder==MOVEMENT_STAY && targetDist<=ATTACK_DISTANCE) || (m_movementOrder!=MOVEMENT_STAY) ) ) { // melee combat - chase target if in range or if we are not forced to stay m_bot->GetMotionMaster()->MoveChase( m_targetCombat ); } else if( m_combatStyle==COMBAT_RANGED && m_movementOrder!=MOVEMENT_STAY ) { // ranged combat - just move within spell range // TODO: just follow in spell range! how to determine bots spell range? if( targetDist>25.0f ) { m_bot->GetMotionMaster()->MoveChase( m_targetCombat ); } else { MovementClear(); } } } void PlayerbotAI::SetQuestNeedItems() { // reset values first m_needItemList.clear(); m_lootCreature.clear(); m_lootCurrent = 0; // run through accepted quests, get quest infoand data for( QuestStatusMap::iterator iter=m_bot->getQuestStatusMap().begin(); iter!=m_bot->getQuestStatusMap().end(); ++iter ) { const Quest *qInfo = sObjectMgr.GetQuestTemplate( iter->first ); if( !qInfo ) continue; QuestStatusData *qData = &iter->second; // only check quest if it is incomplete if( qData->m_status != QUEST_STATUS_INCOMPLETE ) continue; // check for items we not have enough of for( int i=0; i<QUEST_OBJECTIVES_COUNT; i++ ) { if( !qInfo->ReqItemCount[i] || (qInfo->ReqItemCount[i]-qData->m_itemcount[i])<=0 ) continue; m_needItemList[qInfo->ReqItemId[i]] = (qInfo->ReqItemCount[i]-qData->m_itemcount[i]); } } } void PlayerbotAI::SetState( BotState state ) { //sLog.outDebug( "[PlayerbotAI]: %s switch state %d to %d", m_bot->GetName(), m_botState, state ); m_botState = state; } void PlayerbotAI::DoLoot() { if( !m_lootCurrent && m_lootCreature.empty() ) { //sLog.outDebug( "[PlayerbotAI]: %s reset loot list / go back to idle", m_bot->GetName() ); m_botState = BOTSTATE_NORMAL; SetQuestNeedItems(); return; } if( !m_lootCurrent ) { m_lootCurrent = m_lootCreature.front(); m_lootCreature.pop_front(); Creature *c = m_bot->GetMap()->GetCreature( m_lootCurrent ); // check if we got a creature and if it is still a corpse, otherwise bot runs to spawn point if( !c || c->getDeathState()!=CORPSE || GetMaster()->GetDistance( c )>BOTLOOT_DISTANCE ) { m_lootCurrent = 0; return; } m_bot->GetMotionMaster()->MovePoint( c->GetMapId(), c->GetPositionX(), c->GetPositionY(), c->GetPositionZ() ); //sLog.outDebug( "[PlayerbotAI]: %s is going to loot '%s' deathState=%d", m_bot->GetName(), c->GetName(), c->getDeathState() ); } else { Creature *c = m_bot->GetMap()->GetCreature( m_lootCurrent ); if( !c || c->getDeathState()!=CORPSE || GetMaster()->GetDistance( c )>BOTLOOT_DISTANCE ) { m_lootCurrent = 0; return; } if( m_bot->IsWithinDistInMap( c, INTERACTION_DISTANCE ) ) { // check for needed items m_bot->SendLoot( m_lootCurrent, LOOT_CORPSE ); Loot *loot = &c->loot; uint32 lootNum = loot->GetMaxSlotInLootFor( m_bot ); //sLog.outDebug( "[PlayerbotAI]: %s looting: '%s' got %d items", m_bot->GetName(), c->GetName(), loot->GetMaxSlotInLootFor( m_bot ) ); for( uint32 l=0; l<lootNum; l++ ) { QuestItem *qitem=0, *ffaitem=0, *conditem=0; LootItem *item = loot->LootItemInSlot( l, m_bot, &qitem, &ffaitem, &conditem ); if( !item ) continue; if( !qitem && item->is_blocked ) { m_bot->SendLootRelease( m_bot->GetLootGUID() ); continue; } if( m_needItemList[item->itemid]>0 ) { //sLog.outDebug( "[PlayerbotAI]: %s looting: needed item '%s'", m_bot->GetName(), sObjectMgr.GetItemLocale(item->itemid)->Name ); ItemPosCountVec dest; if( m_bot->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, item->itemid, item->count ) == EQUIP_ERR_OK ) { Item * newitem = m_bot->StoreNewItem( dest, item->itemid, true, item->randomPropertyId); if( qitem ) { qitem->is_looted = true; if( item->freeforall || loot->GetPlayerQuestItems().size() == 1 ) m_bot->SendNotifyLootItemRemoved( l ); else loot->NotifyQuestItemRemoved( qitem->index ); } else { if( ffaitem ) { ffaitem->is_looted=true; m_bot->SendNotifyLootItemRemoved( l ); } else { if( conditem ) conditem->is_looted=true; loot->NotifyItemRemoved( l ); } } if (!item->freeforall) item->is_looted = true; --loot->unlootedCount; m_bot->SendNewItem( newitem, uint32(item->count), false, false, true ); m_bot->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count ); } } } // release loot // if( uint64 lguid = m_bot->GetLootGUID() && m_bot->GetSession() ) m_bot->GetSession()->DoLootRelease( m_lootCurrent ); //else if( !m_bot->GetSession() ) // sLog.outDebug( "[PlayerbotAI]: %s has no session. Cannot release loot!", m_bot->GetName() ); // clear movement target, take next target on next update m_bot->GetMotionMaster()->Clear(); m_bot->GetMotionMaster()->MoveIdle(); SetQuestNeedItems(); //sLog.outDebug( "[PlayerbotAI]: %s looted target 0x%08X", m_bot->GetName(), m_lootCurrent ); } } } void PlayerbotAI::AcceptQuest( Quest const *qInfo, Player *pGiver ) { if( !qInfo || !pGiver ) return; uint32 quest = qInfo->GetQuestId(); if( !pGiver->CanShareQuest( qInfo->GetQuestId() ) ) { // giver can't share quest m_bot->SetDivider( 0 ); return; } if( !m_bot->CanTakeQuest( qInfo, false ) ) { // can't take quest m_bot->SetDivider( 0 ); return; } if( m_bot->GetDivider() != 0 ) { // send msg to quest giving player pGiver->SendPushToPartyResponse( m_bot, QUEST_PARTY_MSG_ACCEPT_QUEST ); m_bot->SetDivider( 0 ); } if( m_bot->CanAddQuest( qInfo, false ) ) { m_bot->AddQuest( qInfo, pGiver ); if( m_bot->CanCompleteQuest( quest ) ) m_bot->CompleteQuest( quest ); // Runsttren: did not add typeid switch from WorldSession::HandleQuestgiverAcceptQuestOpcode! // I think it's not needed, cause typeid should be TYPEID_PLAYER - and this one is not handled // there and there is no default case also. if( qInfo->GetSrcSpell() > 0 ) m_bot->CastSpell( m_bot, qInfo->GetSrcSpell(), true ); } } void PlayerbotAI::TurnInQuests( WorldObject *questgiver ) { uint64 giverGUID = questgiver->GetGUID(); if( !m_bot->IsInMap( questgiver ) ) TellMaster("hey you are turning in quests without me!"); else { m_bot->SetSelection( giverGUID ); // auto complete every completed quest this NPC has m_bot->PrepareQuestMenu( giverGUID ); QuestMenu& questMenu = m_bot->PlayerTalkClass->GetQuestMenu(); for (uint32 iI = 0; iI < questMenu.MenuItemCount(); ++iI) { QuestMenuItem const& qItem = questMenu.GetItem(iI); uint32 questID = qItem.m_qId; Quest const* pQuest = sObjectMgr.GetQuestTemplate(questID); std::ostringstream out; std::string questTitle = pQuest->GetTitle(); QuestLocalization(questTitle, questID); QuestStatus status = m_bot->GetQuestStatus(questID); // if quest is complete, turn it in if (status == QUEST_STATUS_COMPLETE) { // if bot hasn't already turned quest in if (! m_bot->GetQuestRewardStatus(questID)) { // auto reward quest if no choice in reward if (pQuest->GetRewChoiceItemsCount() == 0) { if (m_bot->CanRewardQuest(pQuest, false)) { m_bot->RewardQuest(pQuest, 0, questgiver, false); out << "Quest complete: |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } else { out << "|cffff0000Unable to turn quest in:|r |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } } // auto reward quest if one item as reward else if (pQuest->GetRewChoiceItemsCount() == 1) { int rewardIdx = 0; ItemPrototype const *pRewardItem = sObjectMgr.GetItemPrototype(pQuest->RewChoiceItemId[rewardIdx]); std::string itemName = pRewardItem->Name1; ItemLocalization(itemName, pRewardItem->ItemId); if (m_bot->CanRewardQuest(pQuest, rewardIdx, false)) { m_bot->RewardQuest(pQuest, rewardIdx, questgiver, true); std::string itemName = pRewardItem->Name1; ItemLocalization(itemName, pRewardItem->ItemId); out << "Quest complete: " << " |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r reward: |cffffffff|Hitem:" << pRewardItem->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; } else { out << "|cffff0000Unable to turn quest in:|r " << "|cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r" << " reward: |cffffffff|Hitem:" << pRewardItem->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; } } // else multiple rewards - let master pick else { out << "What reward should I take for |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r? "; for (uint8 i=0; i < pQuest->GetRewChoiceItemsCount(); ++i) { ItemPrototype const * const pRewardItem = sObjectMgr.GetItemPrototype(pQuest->RewChoiceItemId[i]); std::string itemName = pRewardItem->Name1; ItemLocalization(itemName, pRewardItem->ItemId); out << "|cffffffff|Hitem:" << pRewardItem->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r"; } } } } else if (status == QUEST_STATUS_INCOMPLETE) { out << "|cffff0000Quest incomplete:|r " << " |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } else if (status == QUEST_STATUS_AVAILABLE){ out << "|cff00ff00Quest available:|r " << " |cff808080|Hquest:" << questID << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } if (! out.str().empty()) TellMaster(out.str()); } } } bool PlayerbotAI::IsInCombat() { bool inCombat = false; inCombat |= m_bot->isInCombat(); inCombat |= GetMaster()->isInCombat(); if( m_bot->GetGroup() ) { GroupReference *ref = m_bot->GetGroup()->GetFirstMember(); while( ref ) { inCombat |= ref->getSource()->isInCombat(); ref = ref->next(); } } return inCombat; } void PlayerbotAI::UpdateAttackerInfo() { // clear old list m_attackerInfo.clear(); // check own attackers HostileReference *ref = m_bot->getHostileRefManager().getFirst(); while( ref ) { ThreatManager *target = ref->getSource(); uint64 guid = target->getOwner()->GetGUID(); m_attackerInfo[guid].attacker = target->getOwner(); m_attackerInfo[guid].victim = target->getOwner()->getVictim(); m_attackerInfo[guid].threat = target->getThreat( m_bot ); m_attackerInfo[guid].count = 1; m_attackerInfo[guid].source = 1; ref = ref->next(); } // check master's attackers ref = GetMaster()->getHostileRefManager().getFirst(); while( ref ) { ThreatManager *target = ref->getSource(); uint64 guid = target->getOwner()->GetGUID(); if( m_attackerInfo.find( guid ) == m_attackerInfo.end() ) { m_attackerInfo[guid].attacker = target->getOwner(); m_attackerInfo[guid].victim = target->getOwner()->getVictim(); m_attackerInfo[guid].count = 0; m_attackerInfo[guid].source = 2; } m_attackerInfo[guid].threat = target->getThreat( m_bot ); m_attackerInfo[guid].count++; ref = ref->next(); } // check all group members now if( m_bot->GetGroup() ) { GroupReference *gref = m_bot->GetGroup()->GetFirstMember(); while( gref ) { if( gref->getSource() == m_bot || gref->getSource() == GetMaster() ) { gref = gref->next(); continue; } ref = gref->getSource()->getHostileRefManager().getFirst(); while( ref ) { ThreatManager *target = ref->getSource(); uint64 guid = target->getOwner()->GetGUID(); if( m_attackerInfo.find( guid ) == m_attackerInfo.end() ) { m_attackerInfo[guid].attacker = target->getOwner(); m_attackerInfo[guid].victim = target->getOwner()->getVictim(); m_attackerInfo[guid].count = 0; m_attackerInfo[guid].source = 3; } m_attackerInfo[guid].threat = target->getThreat( m_bot ); m_attackerInfo[guid].count++; ref = ref->next(); } gref = gref->next(); } } // get highest threat not caused by bot for every entry in AttackerInfoList... for( AttackerInfoList::iterator itr=m_attackerInfo.begin(); itr!=m_attackerInfo.end(); ++itr ) { if( !itr->second.attacker ) continue; Unit *a = itr->second.attacker; float t = 0.00; std::list<HostileReference*>::const_iterator i=a->getThreatManager().getThreatList().begin(); for( ; i!=a->getThreatManager().getThreatList().end(); ++i ) { if( (*i)->getThreat() > t && (*i)->getTarget() != m_bot ) t = (*i)->getThreat(); } m_attackerInfo[itr->first].threat2 = t; } // DEBUG: output attacker info //sLog.outBasic( "[PlayerbotAI]: %s m_attackerInfo = {", m_bot->GetName() ); //for( AttackerInfoList::iterator i=m_attackerInfo.begin(); i!=m_attackerInfo.end(); ++i ) // sLog.outBasic( "[PlayerbotAI]: [%016I64X] { %08X, %08X, %.2f, %.2f, %d, %d }", // i->first, // (i->second.attacker?i->second.attacker->GetGUIDLow():0), // (i->second.victim?i->second.victim->GetGUIDLow():0), // i->second.threat, // i->second.threat2, // i->second.count, // i->second.source ); //sLog.outBasic( "[PlayerbotAI]: };" ); } uint32 PlayerbotAI::EstRepairAll() { uint32 TotalCost = 0; // equipped, backpack, bags itself for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) TotalCost += EstRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i )); // bank, buyback and keys not repaired // items in inventory bags for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j) for(int i = 0; i < MAX_BAG_SIZE; ++i) TotalCost += EstRepair(( (j << 8) | i )); return TotalCost; } uint32 PlayerbotAI::EstRepair(uint16 pos) { Item* item = m_bot->GetItemByPos(pos); uint32 TotalCost = 0; if(!item) return TotalCost; uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); if(!maxDurability) return TotalCost; uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); uint32 LostDurability = maxDurability - curDurability; if(LostDurability>0) { ItemPrototype const *ditemProto = item->GetProto(); DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel); if(!dcost) { sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel); return TotalCost; } uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2; DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId); if(!dQualitymodEntry) { sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId); return TotalCost; } uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)]; uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod)); if (costs==0) //fix for ITEM_QUALITY_ARTIFACT costs = 1; TotalCost = costs; } return TotalCost; } Unit *PlayerbotAI::FindAttacker( ATTACKERINFOTYPE ait, Unit *victim ) { // list empty? why are we here? if( m_attackerInfo.empty() ) return 0; // not searching something specific - return first in list if( !ait ) return (m_attackerInfo.begin())->second.attacker; float t = ( (ait & AIT_HIGHESTTHREAT) ? 0.00 : 9999.00 ); Unit *a = 0; AttackerInfoList::iterator itr = m_attackerInfo.begin(); for( ; itr != m_attackerInfo.end(); ++itr ) { if( (ait & AIT_VICTIMSELF) && !(ait & AIT_VICTIMNOTSELF) && itr->second.victim != m_bot ) continue; if( !(ait & AIT_VICTIMSELF) && (ait & AIT_VICTIMNOTSELF) && itr->second.victim == m_bot ) continue; if( (ait & AIT_VICTIMNOTSELF) && victim && itr->second.victim != victim ) continue; if( !(ait & (AIT_LOWESTTHREAT|AIT_HIGHESTTHREAT)) ) { a = itr->second.attacker; itr = m_attackerInfo.end(); } else { if( (ait & AIT_HIGHESTTHREAT) && /*(itr->second.victim==m_bot) &&*/ itr->second.threat>=t ) { t = itr->second.threat; a = itr->second.attacker; } else if( (ait & AIT_LOWESTTHREAT) && /*(itr->second.victim==m_bot) &&*/ itr->second.threat<=t ) { t = itr->second.threat; a = itr->second.attacker; } } } return a; } void PlayerbotAI::SetCombatOrderByStr( std::string str, Unit *target ) { CombatOrderType co; if( str == "tank" ) co = ORDERS_TANK; else if( str == "assist" ) co = ORDERS_ASSIST; else if( str == "heal" ) co = ORDERS_HEAL; else if( str == "protect" ) co = ORDERS_PROTECT; else co = ORDERS_RESET; SetCombatOrder( co, target ); } void PlayerbotAI::SetCombatOrder( CombatOrderType co, Unit *target ) { if( (co == ORDERS_ASSIST || co == ORDERS_PROTECT) && !target ) return; if( co == ORDERS_RESET ) { m_combatOrder = ORDERS_NONE; m_targetAssist = 0; m_targetProtect = 0; return; } if( co == ORDERS_PROTECT ) m_targetProtect = target; else if( co == ORDERS_ASSIST ) m_targetAssist = target; if( (co&ORDERS_PRIMARY) ) m_combatOrder = (CombatOrderType)(((uint32)m_combatOrder&(uint32)ORDERS_SECONDARY)|(uint32)co); else m_combatOrder = (CombatOrderType)(((uint32)m_combatOrder&(uint32)ORDERS_PRIMARY)|(uint32)co); } void PlayerbotAI::SetMovementOrder( MovementOrderType mo, Unit *followTarget ) { m_movementOrder = mo; m_followTarget = followTarget; MovementReset(); } void PlayerbotAI::MovementReset() { // stop moving... MovementClear(); if( m_movementOrder == MOVEMENT_FOLLOW ) { if( !m_followTarget ) return; // target player is teleporting... if( m_followTarget->GetTypeId()==TYPEID_PLAYER && ((Player*)m_followTarget)->IsBeingTeleported() ) return; // check if bot needs to teleport to reach target... if( !m_bot->isInCombat() ) { if( m_followTarget->GetTypeId()==TYPEID_PLAYER && ((Player*)m_followTarget)->GetCorpse() ) { if( !FollowCheckTeleport( *((Player*)m_followTarget)->GetCorpse() ) ) return; } else { if( !FollowCheckTeleport( *m_followTarget ) ) return; } } if( m_bot->isAlive() ) { float angle = rand_float(0, M_PI_F); float dist = rand_float( m_mgr->m_confFollowDistance[0], m_mgr->m_confFollowDistance[1] ); m_bot->GetMotionMaster()->MoveFollow( m_followTarget, dist, angle ); } } } void PlayerbotAI::MovementUpdate() { // send heartbeats to world WorldPacket data; m_bot->BuildHeartBeatMsg( &data ); m_bot->SendMessageToSet( &data, false ); // call set position (updates states, exploration, etc.) m_bot->SetPosition( m_bot->GetPositionX(), m_bot->GetPositionY(), m_bot->GetPositionZ(), m_bot->GetOrientation(), false ); } void PlayerbotAI::MovementClear() { // stop... m_bot->GetMotionMaster()->Clear( true ); m_bot->clearUnitState( UNIT_STAT_CHASE ); m_bot->clearUnitState( UNIT_STAT_FOLLOW ); // stand up... if (!m_bot->IsStandState()) m_bot->SetStandState(UNIT_STAND_STATE_STAND); } bool PlayerbotAI::IsMoving() { return (m_bot->GetMotionMaster()->GetCurrentMovementGeneratorType() == IDLE_MOTION_TYPE ? false : true); } void PlayerbotAI::SetInFront( const Unit* obj ) { // removed SendUpdateToPlayer (is not updating movement/orientation) if( !m_bot->HasInArc( M_PI_F, obj ) ) m_bot->SetInFront( obj ); } // some possible things to use in AI //GetRandomContactPoint //GetPower, GetMaxPower // HasSpellCooldown // IsAffectedBySpellmod // isMoving // hasUnitState(FLAG) FLAG like: UNIT_STAT_ROOT, UNIT_STAT_CONFUSED, UNIT_STAT_STUNNED // hasAuraType void PlayerbotAI::UpdateAI(const uint32 p_time) { if (m_bot->IsBeingTeleported() || m_bot->GetTrader()) return; time_t currentTime = time(0); if (currentTime < m_ignoreAIUpdatesUntilTime) return; // default updates occur every two seconds m_ignoreAIUpdatesUntilTime = time(0) + 2; // send heartbeat MovementUpdate(); if( !m_bot->isAlive() ) { if( m_botState != BOTSTATE_DEAD && m_botState != BOTSTATE_DEADRELEASED ) { //sLog.outDebug( "[PlayerbotAI]: %s died and is not in correct state...", m_bot->GetName() ); // clear loot list on death m_lootCreature.clear(); m_lootCurrent = 0; // clear combat orders m_bot->SetSelection(0); m_bot->GetMotionMaster()->Clear(true); // set state to dead SetState( BOTSTATE_DEAD ); // wait 30sec m_ignoreAIUpdatesUntilTime = time(0) + 30; } else if( m_botState == BOTSTATE_DEAD ) { // become ghost if( m_bot->GetCorpse() ){ //sLog.outDebug( "[PlayerbotAI]: %s already has a corpse...", m_bot->GetName() ); SetState( BOTSTATE_DEADRELEASED ); return; } m_bot->SetBotDeathTimer(); m_bot->BuildPlayerRepop(); // relocate ghost WorldLocation loc; Corpse *corpse = m_bot->GetCorpse(); corpse->GetPosition( loc ); m_bot->TeleportTo( loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z, m_bot->GetOrientation() ); // set state to released SetState( BOTSTATE_DEADRELEASED ); } else if( m_botState == BOTSTATE_DEADRELEASED ) { // get bot's corpse Corpse *corpse = m_bot->GetCorpse(); if( !corpse ) { //sLog.outDebug( "[PlayerbotAI]: %s has no corpse!", m_bot->GetName() ); return; } // teleport ghost from graveyard to corpse //sLog.outDebug( "[PlayerbotAI]: Teleport %s to corpse...", m_bot->GetName() ); FollowCheckTeleport( *corpse ); // check if we are allowed to resurrect now if( corpse->GetGhostTime() + m_bot->GetCorpseReclaimDelay( corpse->GetType()==CORPSE_RESURRECTABLE_PVP ) > time(0) ) { m_ignoreAIUpdatesUntilTime = corpse->GetGhostTime() + m_bot->GetCorpseReclaimDelay( corpse->GetType()==CORPSE_RESURRECTABLE_PVP ); //sLog.outDebug( "[PlayerbotAI]: %s has to wait for %d seconds to revive...", m_bot->GetName(), m_ignoreAIUpdatesUntilTime-time(0) ); return; } // resurrect now //sLog.outDebug( "[PlayerbotAI]: Reviving %s to corpse...", m_bot->GetName() ); m_ignoreAIUpdatesUntilTime = time(0) + 6; PlayerbotChatHandler ch(GetMaster()); if (! ch.revive(*m_bot)) { ch.sysmessage(".. could not be revived .."); return; } // set back to normal SetState( BOTSTATE_NORMAL ); } } else { // if we are casting a spell then interrupt it // make sure any actions that cast a spell set a proper m_ignoreAIUpdatesUntilTime! Spell* const pSpell = GetCurrentSpell(); if (pSpell && !(pSpell->IsChannelActive() || pSpell->IsAutoRepeat())) InterruptCurrentCastingSpell(); // direct cast command from master else if (m_spellIdCommand != 0) { Unit* pTarget = ObjectAccessor::GetUnit(*m_bot, m_targetGuidCommand); if (pTarget != NULL) CastSpell(m_spellIdCommand, *pTarget); m_spellIdCommand = 0; m_targetGuidCommand = 0; } // handle combat (either self/master/group in combat, or combat state and valid target) else if ( IsInCombat() || (m_botState == BOTSTATE_COMBAT && m_targetCombat) ) DoNextCombatManeuver(); // bot was in combat recently - loot now else if (m_botState == BOTSTATE_COMBAT) { SetState( BOTSTATE_LOOTING ); m_attackerInfo.clear(); } else if (m_botState == BOTSTATE_LOOTING) DoLoot(); /* // are we sitting, if so feast if possible else if (m_bot->getStandState() == UNIT_STAND_STATE_SIT) Feast(); */ // if commanded to follow master and not already following master then follow master else if (!m_bot->isInCombat() && !IsMoving() ) MovementReset(); // do class specific non combat actions else if (GetClassAI()) (GetClassAI())->DoNonCombatActions(); } } Spell* PlayerbotAI::GetCurrentSpell() const { if (m_CurrentlyCastingSpellId == 0) return NULL; Spell* const pSpell = m_bot->FindCurrentSpellBySpellId(m_CurrentlyCastingSpellId); return pSpell; } void PlayerbotAI::TellMaster(const std::string& text) const { SendWhisper(text, *GetMaster()); } void PlayerbotAI::TellMaster( const char *fmt, ... ) const { char temp_buf[1024]; va_list ap; va_start( ap, fmt ); size_t temp_len = vsnprintf( temp_buf, 1024, fmt, ap ); va_end( ap ); std::string str = temp_buf; TellMaster( str ); } void PlayerbotAI::SendWhisper(const std::string& text, Player& player) const { WorldPacket data(SMSG_MESSAGECHAT, 200); m_bot->BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, LANG_UNIVERSAL); player.GetSession()->SendPacket(&data); } bool PlayerbotAI::canObeyCommandFrom(const Player& player) const { return player.GetSession()->GetAccountId() == GetMaster()->GetSession()->GetAccountId(); } bool PlayerbotAI::CastSpell(const char* args) { uint32 spellId = getSpellId(args); return (spellId) ? CastSpell(spellId) : false; } bool PlayerbotAI::CastSpell(uint32 spellId, Unit& target) { uint64 oldSel = m_bot->GetSelection(); m_bot->SetSelection(target.GetGUID()); bool rv = CastSpell(spellId); m_bot->SetSelection(oldSel); return rv; } bool PlayerbotAI::CastSpell(uint32 spellId) { // some AIs don't check if the bot doesn't have spell before using it // so just return false when this happens if (spellId == 0) return false; // check spell cooldown if( m_bot->HasSpellCooldown( spellId ) ) return false; // see Creature.cpp 1738 for reference // don't allow bot to cast damage spells on friends const SpellEntry* const pSpellInfo = sSpellStore.LookupEntry(spellId); if (!pSpellInfo) { TellMaster("missing spell entry in CastSpell."); return false; } // set target uint64 targetGUID = m_bot->GetSelection(); Unit* pTarget = ObjectAccessor::GetUnit(*m_bot, m_bot->GetSelection()); if (IsPositiveSpell(spellId)) { if (pTarget && !m_bot->IsFriendlyTo(pTarget)) pTarget = m_bot; } else { if (pTarget && m_bot->IsFriendlyTo(pTarget)) return false; // search for Creature::reachWithSpellAttack to also see some examples of spell distance usage if (!m_bot->isInFrontInMap(pTarget, 10)) { m_bot->SetInFront(pTarget); MovementUpdate(); } } if (HasAura(spellId, *pTarget)) return false; // stop movement to prevent cancel spell casting MovementClear(); // actually cast spell m_bot->CastSpell(pTarget, pSpellInfo, false); Spell* const pSpell = m_bot->FindCurrentSpellBySpellId(spellId); if (!pSpell) return false; m_CurrentlyCastingSpellId = spellId; m_ignoreAIUpdatesUntilTime = time(0) + (int32)((float)pSpell->GetCastTime()/1000.0f) + 1; // if this caused the caster to move (blink) update the position // I think this is normally done on the client // this should be done on spell success /* if (name == "Blink") { float x,y,z; m_bot->GetPosition(x,y,z); m_bot->GetNearPoint(m_bot, x, y, z, 1, 5, 0); m_bot->Relocate(x,y,z); WorldPacket data; m_bot->BuildHeartBeatMsg(&data); m_bot->SendMessageToSet(&data,true); } */ return true; } Item* PlayerbotAI::FindItem(uint32 ItemId) { // list out items in main backpack //INVENTORY_SLOT_ITEM_START = 23 //INVENTORY_SLOT_ITEM_END = 39 for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { // sLog.outDebug("[%s's]backpack slot = %u",m_bot->GetName(),slot); // 23 to 38 = 16 Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); // 255, 23 to 38 if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto ) continue; if( pItemProto->ItemId == ItemId) // have required item return pItem; } } // list out items in other removable backpacks //INVENTORY_SLOT_BAG_START = 19 //INVENTORY_SLOT_BAG_END = 23 for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) // 20 to 23 = 4 { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); // 255, 20 to 23 if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { sLog.outDebug("[%s's]bag[%u] slot = %u",m_bot->GetName(),bag,slot); // 1 to bagsize = ? Item* const pItem = m_bot->GetItemByPos(bag, slot); // 20 to 23, 1 to bagsize if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto ) continue; if( pItemProto->ItemId == ItemId ) // have required item return pItem; } } } } return NULL; } bool PlayerbotAI::HasPick() { QueryResult *result; // list out equiped items for( uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; slot++) { Item* const pItem = m_bot->GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); if (pItem ) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto ) continue; result = WorldDatabase.PQuery("SELECT TotemCategory FROM item_template WHERE entry = '%i'", pItemProto->ItemId); if (result) { Field *fields = result->Fetch(); uint32 tc = fields[0].GetUInt32(); // sLog.outDebug("HasPick %u",tc); if(tc == 165 || tc == 167) // pick = 165, hammer = 162 or hammer pick = 167 return true; } } } // list out items in backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { // sLog.outDebug("[%s's]backpack slot = %u",m_bot->GetName(),slot); // 23 to 38 = 16 Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); // 255, 23 to 38 if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto ) continue; result = WorldDatabase.PQuery("SELECT TotemCategory FROM item_template WHERE entry = '%i'", pItemProto->ItemId); if (result) { Field *fields = result->Fetch(); uint32 tc = fields[0].GetUInt32(); // sLog.outDebug("HasPick %u",tc); if(tc == 165 || tc == 167) // pick = 165, hammer = 162 or hammer pick = 167 return true; } } } // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) // 20 to 23 = 4 { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); // 255, 20 to 23 if (pBag) { for (uint8 slot = 0; slot < pBag->GetBagSize(); ++slot) { // sLog.outDebug("[%s's]bag[%u] slot = %u",m_bot->GetName(),bag,slot); // 1 to bagsize = ? Item* const pItem = m_bot->GetItemByPos(bag, slot); // 20 to 23, 1 to bagsize if (pItem) { const ItemPrototype* const pItemProto = pItem->GetProto(); if (!pItemProto ) continue; result = WorldDatabase.PQuery("SELECT TotemCategory FROM item_template WHERE entry = '%i'", pItemProto->ItemId); if (result) { Field *fields = result->Fetch(); uint32 tc = fields[0].GetUInt32(); // sLog.outDebug("HasPick %u",tc); if(tc == 165 || tc == 167) return true; } } } } } std::ostringstream out; out << "|cffffffffI do not have a pick!"; TellMaster( out.str().c_str() ); return false; } // extracts all item ids in format below // I decided to roll my own extractor rather then use the one in ChatHandler // because this one works on a const string, and it handles multiple links // |color|linkType:key:something1:...:somethingN|h[name]|h|r void PlayerbotAI::extractItemIds(const std::string& text, std::list<uint32>& itemIds) const { uint8 pos = 0; while (true) { int i = text.find("Hitem:", pos); if (i == -1) break; pos = i + 6; int endPos = text.find(':', pos); if (endPos == -1) break; std::string idC = text.substr(pos, endPos - pos); uint32 id = atol(idC.c_str()); pos = endPos; if (id) itemIds.push_back(id); } } bool PlayerbotAI::extractGOinfo(const std::string& text, uint32 &guid, uint32 &entry, int &mapid, float &x, float &y, float &z) const { // Link format // |cFFFFFF00|Hfound:" << guid << ':' << entry << ':' << x << ':' << y << ':' << z << ':' << mapid << ':' << "|h[" << gInfo->name << "]|h|r"; // |cFFFFFF00|Hfound:5093:1731:-9295:-270:81.874:0:|h[Copper Vein]|h|r uint8 pos = 0; // extract GO guid int i = text.find("Hfound:", pos); // base H = 11 if (i == -1) // break if error return false; pos = i + 7; //start of window in text 11 + 7 = 18 int endPos = text.find(':', pos); // end of window in text 22 if (endPos == -1) //break if error return false; std::string guidC = text.substr(pos, endPos - pos); // get string within window i.e guid 22 - 18 = 4 guid = atol(guidC.c_str()); // convert ascii to long int // extract GO entry pos = endPos + 1; endPos = text.find(':', pos); // end of window in text if (endPos == -1) //break if error return false; std::string entryC = text.substr(pos, endPos - pos); // get string within window i.e entry entry = atol(entryC.c_str()); // convert ascii to float // extract GO x pos = endPos + 1; endPos = text.find(':', pos); // end of window in text if (endPos == -1) //break if error return false; std::string xC = text.substr(pos, endPos - pos); // get string within window i.e x x = atof(xC.c_str()); // convert ascii to float // extract GO y pos = endPos + 1; endPos = text.find(':', pos); // end of window in text if (endPos == -1) //break if error return false; std::string yC = text.substr(pos, endPos - pos); // get string within window i.e y y = atof(yC.c_str()); // convert ascii to float // extract GO z pos = endPos + 1; endPos = text.find(':', pos); // end of window in text if (endPos == -1) //break if error return false; std::string zC = text.substr(pos, endPos - pos); // get string within window i.e z z = atof(zC.c_str()); // convert ascii to float //extract GO mapid pos = endPos + 1; endPos = text.find(':', pos); // end of window in text if (endPos == -1) //break if error return false; std::string mapidC = text.substr(pos, endPos - pos); // get string within window i.e mapid mapid = atoi(mapidC.c_str()); // convert ascii to int pos = endPos; // end return true; } // extracts currency in #g#s#c format uint32 PlayerbotAI::extractMoney(const std::string& text) const { // if user specified money in ##g##s##c format std::string acum = ""; uint32 copper = 0; for (uint8 i = 0; i < text.length(); i++) { if (text[i] == 'g') { copper += (atol(acum.c_str()) * 100 * 100); acum = ""; } else if (text[i] == 'c') { copper += atol(acum.c_str()); acum = ""; } else if (text[i] == 's') { copper += (atol(acum.c_str()) * 100); acum = ""; } else if (text[i] == ' ') break; else if (text[i] >= 48 && text[i] <= 57) acum += text[i]; else { copper = 0; break; } } return copper; } // finds items in equipment and adds Item* to foundItemList // also removes found item IDs from itemIdSearchList when found void PlayerbotAI::findItemsInEquip(std::list<uint32>& itemIdSearchList, std::list<Item*>& foundItemList) const { for( uint8 slot=EQUIPMENT_SLOT_START; itemIdSearchList.size()>0 && slot<EQUIPMENT_SLOT_END; slot++ ) { Item* const pItem = m_bot->GetItemByPos( INVENTORY_SLOT_BAG_0, slot ); if( !pItem ) continue; for (std::list<uint32>::iterator it = itemIdSearchList.begin(); it != itemIdSearchList.end(); ++it) { if (pItem->GetProto()->ItemId != *it) continue; foundItemList.push_back(pItem); itemIdSearchList.erase(it); break; } } } // finds items in inventory and adds Item* to foundItemList // also removes found item IDs from itemIdSearchList when found void PlayerbotAI::findItemsInInv(std::list<uint32>& itemIdSearchList, std::list<Item*>& foundItemList) const { // look for items in main bag for (uint8 slot = INVENTORY_SLOT_ITEM_START; itemIdSearchList.size() > 0 && slot < INVENTORY_SLOT_ITEM_END; ++slot) { Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!pItem) continue; for (std::list<uint32>::iterator it = itemIdSearchList.begin(); it != itemIdSearchList.end(); ++it) { if (pItem->GetProto()->ItemId != *it) continue; foundItemList.push_back(pItem); itemIdSearchList.erase(it); break; } } // for all for items in other bags for (uint8 bag = INVENTORY_SLOT_BAG_START; itemIdSearchList.size() > 0 && bag < INVENTORY_SLOT_BAG_END; ++bag) { Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (!pBag) continue; for (uint8 slot = 0; itemIdSearchList.size() > 0 && slot < pBag->GetBagSize(); ++slot) { Item* const pItem = m_bot->GetItemByPos(bag, slot); if (!pItem) continue; for (std::list<uint32>::iterator it = itemIdSearchList.begin(); it != itemIdSearchList.end(); ++it) { if (pItem->GetProto()->ItemId != *it) continue; foundItemList.push_back(pItem); itemIdSearchList.erase(it); break; } } } } // submits packet to use an item void PlayerbotAI::UseItem(Item& item) { uint8 bagIndex = item.GetBagSlot(); uint8 slot = item.GetSlot(); uint8 cast_count = 1; uint32 spellid = 0; // only used in combat uint64 item_guid = item.GetGUID(); uint32 glyphIndex = 0; // ?? uint8 unk_flags = 0; // not 0x02 // create target data // note other targets are possible but not supported at the moment // see SpellCastTargets::read in Spell.cpp to see other options // for setting target uint32 target = TARGET_FLAG_SELF; WorldPacket* const packet = new WorldPacket(CMSG_USE_ITEM, 1 + 1 + 1 + 4 + 8 + 4 + 1); *packet << bagIndex << slot << cast_count << spellid << item_guid << glyphIndex << unk_flags << target; m_bot->GetSession()->QueuePacket(packet); // queue the packet to get around race condition // certain items cause player to sit (food,drink) // tell bot to stop following if this is the case // (doesn't work since we queued the packet!) // maybe its not needed??? //if (! m_bot->IsStandState()) // m_bot->GetMotionMaster()->Clear(); } // submits packet to use an item void PlayerbotAI::EquipItem(Item& item) { uint8 bagIndex = item.GetBagSlot(); uint8 slot = item.GetSlot(); WorldPacket* const packet = new WorldPacket(CMSG_AUTOEQUIP_ITEM, 2); *packet << bagIndex << slot; m_bot->GetSession()->QueuePacket(packet); } // submits packet to trade an item (trade window must already be open) // default slot is -1 which means trade slots 0 to 5. if slot is set // to TRADE_SLOT_NONTRADED (which is slot 6) item will be shown in the // 'Will not be traded' slot. bool PlayerbotAI::TradeItem(const Item& item, int8 slot) { sLog.outDebug( "[PlayerbotAI::TradeItem]: slot=%d, hasTrader=%d, itemInTrade=%d, itemTradeable=%d", slot, (m_bot->GetTrader()?1:0), (item.IsInTrade()?1:0), (item.CanBeTraded()?1:0) ); if (!m_bot->GetTrader() || item.IsInTrade() || (!item.CanBeTraded() && slot!=TRADE_SLOT_NONTRADED) ) return false; int8 tradeSlot = -1; TradeData* pTrade = m_bot->GetTradeData(); if( (slot>=0 && slot<TRADE_SLOT_COUNT) && pTrade->GetTraderData()->GetItem(TradeSlots(slot)) == NULL ) tradeSlot = slot; else { for( uint8 i=0; i<TRADE_SLOT_TRADED_COUNT && tradeSlot==-1; i++ ) { if( pTrade->GetTraderData()->GetItem(TradeSlots(i)) == NULL ) tradeSlot = i; } } if( tradeSlot == -1 ) return false; WorldPacket* const packet = new WorldPacket(CMSG_SET_TRADE_ITEM, 3); *packet << (uint8) tradeSlot << (uint8) item.GetBagSlot() << (uint8) item.GetSlot(); m_bot->GetSession()->QueuePacket(packet); return true; } // submits packet to trade copper (trade window must be open) bool PlayerbotAI::TradeCopper(uint32 copper) { if (copper > 0) { WorldPacket* const packet = new WorldPacket(CMSG_SET_TRADE_GOLD, 4); *packet << copper; m_bot->GetSession()->QueuePacket(packet); return true; } return false; } /*void PlayerbotAI::Stay() { m_IsFollowingMaster = false; m_bot->GetMotionMaster()->Clear(true); m_bot->HandleEmoteCommand(EMOTE_ONESHOT_SALUTE); }*/ /*bool PlayerbotAI::Follow(Player& player) { if (GetMaster()->IsBeingTeleported()) return false; m_IsFollowingMaster = true; if (!m_bot->IsStandState()) m_bot->SetStandState(UNIT_STAND_STATE_STAND); if (!m_bot->isInCombat()) { // follow player or his corpse if dead (stops bot from running to graveyard if player repops...) if( player.GetCorpse() ) { if( !FollowCheckTeleport( *player.GetCorpse() ) ) return false; } else { if( !FollowCheckTeleport( player ) ) return false; } } if (m_bot->isAlive()) { float angle = rand_float(0, M_PI); float dist = rand_float(0.5f, 1.0f); m_bot->GetMotionMaster()->Clear(true); m_bot->GetMotionMaster()->MoveFollow(&player, dist, angle); return true; } return false; }*/ bool PlayerbotAI::FollowCheckTeleport( WorldObject &obj ) { // if bot has strayed too far from the master, teleport bot if (!m_bot->IsWithinDistInMap( &obj, 50, true ) && GetMaster()->isAlive()) { m_ignoreAIUpdatesUntilTime = time(0) + 6; PlayerbotChatHandler ch(GetMaster()); if (! ch.teleport(*m_bot)) { ch.sysmessage(".. could not be teleported .."); //sLog.outDebug( "[PlayerbotAI]: %s failed to teleport", m_bot->GetName() ); return false; } } return true; } void PlayerbotAI::HandleTeleportAck() { m_ignoreAIUpdatesUntilTime = time(0) + 6; m_bot->GetMotionMaster()->Clear(true); if (m_bot->IsBeingTeleportedNear()) { WorldPacket p = WorldPacket(MSG_MOVE_TELEPORT_ACK, 8 + 4 + 4); p.appendPackGUID(m_bot->GetGUID()); p << (uint32) 0; // supposed to be flags? not used currently p << (uint32) time(0); // time - not currently used m_bot->GetSession()->HandleMoveTeleportAck(p); } else if (m_bot->IsBeingTeleportedFar()) m_bot->GetSession()->HandleMoveWorldportAckOpcode(); } // Localization support void PlayerbotAI::ItemLocalization(std::string& itemName, const uint32 itemID) const { uint32 loc = GetMaster()->GetSession()->GetSessionDbLocaleIndex(); std::wstring wnamepart; ItemLocale const *pItemInfo = sObjectMgr.GetItemLocale(itemID); if (pItemInfo) { if (pItemInfo->Name.size() > loc && !pItemInfo->Name[loc].empty()) { const std::string name = pItemInfo->Name[loc]; if (Utf8FitTo(name, wnamepart)) itemName = name.c_str(); } } } void PlayerbotAI::QuestLocalization(std::string& questTitle, const uint32 questID) const { uint32 loc = GetMaster()->GetSession()->GetSessionDbLocaleIndex(); std::wstring wnamepart; QuestLocale const *pQuestInfo = sObjectMgr.GetQuestLocale(questID); if (pQuestInfo) { if (pQuestInfo->Title.size() > loc && !pQuestInfo->Title[loc].empty()) { const std::string title = pQuestInfo->Title[loc]; if (Utf8FitTo(title, wnamepart)) questTitle = title.c_str(); } } } // handle commands sent through chat channels void PlayerbotAI::HandleCommand(const std::string& text, Player& fromPlayer) { // ignore any messages from Addons if (text.empty() || text.find("X-Perl") != std::wstring::npos || text.find("HealBot") != std::wstring::npos || text.find("LOOT_OPENED") != std::wstring::npos || text.find("CTRA") != std::wstring::npos) return; // if message is not from a player in the masters account auto reply and ignore if (!canObeyCommandFrom(fromPlayer)) { std::string msg = "I can't talk to you. Please speak to my master "; msg += GetMaster()->GetName(); SendWhisper(msg, fromPlayer); m_bot->HandleEmoteCommand(EMOTE_ONESHOT_NO); } // if in the middle of a trade, and player asks for an item/money else if (m_bot->GetTrader() && m_bot->GetTrader()->GetGUID() == fromPlayer.GetGUID()) { uint32 copper = extractMoney(text); if (copper > 0) TradeCopper(copper); std::list<uint32> itemIds; extractItemIds(text, itemIds); if (itemIds.size() == 0) SendWhisper("Show me what item you want by shift clicking the item in the chat window.", fromPlayer); else if( !strncmp( text.c_str(), "nt ", 3 ) ) { if( itemIds.size() > 1 ) SendWhisper( "There is only one 'Will not be traded' slot. Shift-click just one item, please!", fromPlayer ); else { std::list<Item*> itemList; findItemsInEquip( itemIds, itemList ); findItemsInInv( itemIds, itemList ); if( itemList.size()>0 ) TradeItem( (**itemList.begin()), TRADE_SLOT_NONTRADED ); else SendWhisper( "I do not have this item equipped or in my bags!", fromPlayer ); } } else { std::list<Item*> itemList; findItemsInInv(itemIds, itemList); for (std::list<Item*>::iterator it = itemList.begin(); it != itemList.end(); ++it) TradeItem(**it); } } // if we are turning in a quest else if (text == "reset") { SetState( BOTSTATE_NORMAL ); MovementReset(); SetQuestNeedItems(); UpdateAttackerInfo(); m_lootCreature.clear(); m_lootCurrent = 0; m_targetCombat = 0; // do we want to reset all states on this command? // m_combatOrder = ORDERS_NONE; // m_targetCombat = 0; // m_targetAssisst = 0; // m_targetProtect = 0; } else if (text == "report") SendQuestItemList( *GetMaster() ); else if (text == "orders") SendOrders( *GetMaster() ); else if (text == "follow" || text == "come") SetMovementOrder( MOVEMENT_FOLLOW, GetMaster() ); else if (text == "stay" || text == "stop") SetMovementOrder( MOVEMENT_STAY ); else if (text == "attack") { uint64 attackOnGuid = fromPlayer.GetSelection(); if (attackOnGuid) { Unit* thingToAttack = ObjectAccessor::GetUnit(*m_bot, attackOnGuid); if (!m_bot->IsFriendlyTo(thingToAttack) && m_bot->IsWithinLOSInMap(thingToAttack)) GetCombatTarget( thingToAttack ); } else { TellMaster("No target is selected."); m_bot->HandleEmoteCommand(EMOTE_ONESHOT_TALK); } } // handle cast command else if (text.size() > 2 && text.substr(0, 2) == "c " || text.size() > 5 && text.substr(0, 5) == "cast ") { std::string spellStr = text.substr(text.find(" ") + 1); uint32 spellId = (uint32) atol(spellStr.c_str()); // try and get spell ID by name if (spellId == 0) spellId = getSpellId(spellStr.c_str(), true); uint64 castOnGuid = fromPlayer.GetSelection(); if (spellId != 0 && castOnGuid != 0 && m_bot->HasSpell(spellId)) { m_spellIdCommand = spellId; m_targetGuidCommand = castOnGuid; } } // use items else if (text.size() > 2 && text.substr(0, 2) == "u " || text.size() > 4 && text.substr(0, 4) == "use ") { std::list<uint32> itemIds; std::list<Item*> itemList; extractItemIds(text, itemIds); findItemsInInv(itemIds, itemList); for (std::list<Item*>::iterator it = itemList.begin(); it != itemList.end(); ++it) UseItem(**it); } // equip items else if (text.size() > 2 && text.substr(0, 2) == "e " || text.size() > 6 && text.substr(0, 6) == "equip ") { std::list<uint32> itemIds; std::list<Item*> itemList; extractItemIds(text, itemIds); findItemsInInv(itemIds, itemList); for (std::list<Item*>::iterator it = itemList.begin(); it != itemList.end(); ++it) EquipItem(**it); } // find item in world else if (text.size() > 2 && text.substr(0, 2) == "f " || text.size() > 5 && text.substr(0, 5) == "find ") { uint32 guid; float x,y,z; uint32 entry; int mapid; if(extractGOinfo(text, guid, entry, mapid, x, y, z)) { // sLog.outDebug("find: guid : %u entry : %u x : (%f) y : (%f) z : (%f) mapid : %d",guid, entry, x, y, z, mapid); m_bot->UpdateGroundPositionZ(x,y,z); SetMovementOrder( MOVEMENT_STAY ); m_bot->GetMotionMaster()->MovePoint( mapid, x, y, z ); } else SendWhisper("I have no info on that object", fromPlayer); } // get project: 18:50 03/05/10 rev.3 allows bots to retrieve all lootable & quest items from gameobjects else if (text.size() > 2 && text.substr(0, 2) == "g " || text.size() > 4 && text.substr(0, 4) == "get ") { uint32 guid; float x,y,z; uint32 entry; int mapid; bool looted = false; if (extractGOinfo(text, guid, entry, mapid, x, y, z)) { //sLog.outDebug("find: guid : %u entry : %u x : (%f) y : (%f) z : (%f) mapid : %d",guid, entry, x, y, z, mapid); m_lootCurrent = MAKE_NEW_GUID(guid, entry, HIGHGUID_GAMEOBJECT); GameObject *go = m_bot->GetMap()->GetGameObject(m_lootCurrent); if (!go) { m_lootCurrent = 0; return; } if ( !go->isSpawned() ) return; m_bot->UpdateGroundPositionZ(x,y,z); m_bot->GetMotionMaster()->MovePoint( mapid, x, y, z ); m_bot->SetPosition(x, y, z, m_bot->GetOrientation()); m_bot->SendLoot( m_lootCurrent, LOOT_CORPSE ); Loot *loot = &go->loot; uint32 lootNum = loot->GetMaxSlotInLootFor( m_bot ); // sLog.outDebug( "[PlayerbotAI]: GetGOType %u - %s looting: '%s' got %d items", go->GetGoType(), m_bot->GetName(), go->GetGOInfo()->name, loot->GetMaxSlotInLootFor( m_bot )); if(lootNum == 0) // Handle opening gameobjects that contain no items { uint32 lockId = go->GetGOInfo()->GetLockId(); LockEntry const *lockInfo = sLockStore.LookupEntry(lockId); if(lockInfo) { for(int i = 0; i < 8; ++i) { uint32 skillId = SkillByLockType(LockType(lockInfo->Index[i])); if(skillId > 0) { if (m_bot->HasSkill(skillId)) // Has skill { uint32 reqSkillValue = lockInfo->Skill[i]; uint32 SkillValue = m_bot->GetPureSkillValue(skillId); if (SkillValue >= reqSkillValue) { // sLog.outDebug("[PlayerbotAI]i: skillId : %u SkillValue : %u reqSkillValue : %u",skillId,SkillValue,reqSkillValue); m_bot->UpdateGatherSkill(skillId, SkillValue, reqSkillValue); looted = true; } } break; } } } } for ( uint32 l=0; l<lootNum; l++ ) { // sLog.outDebug("[PlayerbotAI]: lootNum : %u",lootNum); QuestItem *qitem=0, *ffaitem=0, *conditem=0; LootItem *item = loot->LootItemInSlot( l, m_bot, &qitem, &ffaitem, &conditem ); if ( !item ) continue; if ( !qitem && item->is_blocked ) { m_bot->SendLootRelease( m_lootCurrent ); continue; } if ( m_needItemList[item->itemid]>0 ) { ItemPosCountVec dest; if ( m_bot->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, item->itemid, item->count ) == EQUIP_ERR_OK ) { Item * newitem = m_bot->StoreNewItem( dest, item->itemid, true, item->randomPropertyId); if ( qitem ) { qitem->is_looted = true; if ( item->freeforall || loot->GetPlayerQuestItems().size() == 1 ) m_bot->SendNotifyLootItemRemoved( l ); else loot->NotifyQuestItemRemoved( qitem->index ); } else { if ( ffaitem ) { ffaitem->is_looted=true; m_bot->SendNotifyLootItemRemoved( l ); } else { if ( conditem ) conditem->is_looted=true; loot->NotifyItemRemoved( l ); } } if (!item->freeforall) item->is_looted = true; --loot->unlootedCount; m_bot->SendNewItem( newitem, uint32(item->count), false, false, true ); m_bot->GetAchievementMgr().UpdateAchievementCriteria( ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count ); looted = true; } continue; } uint32 lockId = go->GetGOInfo()->GetLockId(); LockEntry const *lockInfo = sLockStore.LookupEntry(lockId); if(lockInfo) { uint32 skillId = 0; uint32 reqSkillValue = 0; for(int i = 0; i < 8; ++i) { skillId = SkillByLockType(LockType(lockInfo->Index[i])); if(skillId > 0) { reqSkillValue = lockInfo->Skill[i]; break; } } if (m_bot->HasSkill(skillId) || skillId == SKILL_NONE) // Has skill or skill not required { if((skillId == SKILL_MINING) && !HasPick()) continue; ItemPosCountVec dest; if ( m_bot->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, item->itemid, item->count) == EQUIP_ERR_OK ) { Item* pItem = m_bot->StoreNewItem (dest,item->itemid,true,item->randomPropertyId); uint32 SkillValue = m_bot->GetPureSkillValue(skillId); if (SkillValue >= reqSkillValue) { m_bot->SendNewItem(pItem, uint32(item->count), false, false, true); m_bot->UpdateGatherSkill(skillId, SkillValue, reqSkillValue); --loot->unlootedCount; looted = true; } } } } } // release loot if(looted) m_bot->GetSession()->DoLootRelease( m_lootCurrent ); else m_bot->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); // sLog.outDebug( "[PlayerbotAI]: %s looted target 0x%08X", m_bot->GetName(), m_lootCurrent ); SetQuestNeedItems(); } else SendWhisper("I have no info on that object", fromPlayer); } else if (text == "quests") { bool hasIncompleteQuests = false; std::ostringstream incomout; incomout << "my incomplete quests are:"; bool hasCompleteQuests = false; std::ostringstream comout; comout << "my complete quests are:"; for (uint16 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) { if(uint32 questId = m_bot->GetQuestSlotQuestId(slot)) { Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId); std::string questTitle = pQuest->GetTitle(); m_bot->GetPlayerbotAI()->QuestLocalization(questTitle, questId); if (m_bot->GetQuestStatus(questId) == QUEST_STATUS_COMPLETE) { hasCompleteQuests = true; comout << " |cFFFFFF00|Hquest:" << questId << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } else { hasIncompleteQuests = true; incomout << " |cFFFFFF00|Hquest:" << questId << ':' << pQuest->GetQuestLevel() << "|h[" << questTitle << "]|h|r"; } } } if (hasCompleteQuests) SendWhisper(comout.str(), fromPlayer); if (hasIncompleteQuests) SendWhisper(incomout.str(), fromPlayer); if (! hasCompleteQuests && ! hasIncompleteQuests) SendWhisper("I have no quests!", fromPlayer); } // drop a quest else if (text.size() > 5 && text.substr(0, 5) == "drop ") { uint64 oldSelectionGUID = 0; if (fromPlayer.GetSelection() != m_bot->GetGUID()) { oldSelectionGUID = m_bot->GetGUID(); fromPlayer.SetSelection(m_bot->GetGUID()); } PlayerbotChatHandler ch(GetMaster()); if (! ch.dropQuest(text.substr(5).c_str())) ch.sysmessage("ERROR: could not drop quest"); if (oldSelectionGUID) fromPlayer.SetSelection(oldSelectionGUID); } else if (text == "spells") { int loc = GetMaster()->GetSession()->GetSessionDbcLocale(); std::ostringstream posOut; std::ostringstream negOut; const std::string ignoreList = ",Opening,Closing,Stuck,Remove Insignia,Opening - No Text,Grovel,Duel,Honorless Target,"; std::string alreadySeenList = ","; for (PlayerSpellMap::iterator itr = m_bot->GetSpellMap().begin(); itr != m_bot->GetSpellMap().end(); ++itr) { const uint32 spellId = itr->first; if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled || IsPassiveSpell(spellId)) continue; const SpellEntry* const pSpellInfo = sSpellStore.LookupEntry(spellId); if (!pSpellInfo) continue; //|| name.find("Teleport") != -1 std::string comp = ","; comp.append(pSpellInfo->SpellName[loc]); comp.append(","); if (!(ignoreList.find(comp) == std::string::npos && alreadySeenList.find(comp) == std::string::npos)) continue; alreadySeenList += pSpellInfo->SpellName[loc]; alreadySeenList += ","; if (IsPositiveSpell(spellId)) posOut << " |cffffffff|Hspell:" << spellId << "|h[" << pSpellInfo->SpellName[loc] << "]|h|r"; else negOut << " |cffffffff|Hspell:" << spellId << "|h[" << pSpellInfo->SpellName[loc] << "]|h|r"; } ChatHandler ch(&fromPlayer); SendWhisper("here's my non-attack spells:", fromPlayer); ch.SendSysMessage(posOut.str().c_str()); SendWhisper("and here's my attack spells:", fromPlayer); ch.SendSysMessage(negOut.str().c_str()); } // survey project: 18:30 29/04/10 rev.3 filter out event triggered objects & now updates list else if (text == "survey") { uint32 count = 0; std::ostringstream detectout; QueryResult *result; GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr.GetActiveEventList(); std::ostringstream eventFilter; eventFilter << " AND (event IS NULL "; bool initString = true; for (GameEventMgr::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr) { if (initString) { eventFilter << "OR event IN (" <<*itr; initString =false; } else eventFilter << "," << *itr; } if (!initString) eventFilter << "))"; else eventFilter << ")"; result = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, map, " "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject " "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10", m_bot->GetPositionX(), m_bot->GetPositionY(), m_bot->GetPositionZ(), m_bot->GetMapId(),eventFilter.str().c_str()); if (result) { do { Field *fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); uint32 entry = fields[1].GetUInt32(); float x = fields[2].GetFloat(); float y = fields[3].GetFloat(); float z = fields[4].GetFloat(); int mapid = fields[5].GetUInt16(); GameObject *go = m_bot->GetMap()->GetGameObject(MAKE_NEW_GUID(guid, entry, HIGHGUID_GAMEOBJECT)); if (!go) continue; if ( !go->isSpawned() ) continue; detectout << "|cFFFFFF00|Hfound:" << guid << ":" << entry << ":" << x << ":" << y << ":" << z << ":" << mapid << ":" << "|h[" << go->GetGOInfo()->name << "]|h|r"; ++count; } while (result->NextRow()); delete result; } SendWhisper(detectout.str().c_str(), fromPlayer); } // stats project: 10:00 19/04/10 rev.1 display bot statistics else if (text == "stats") { std::ostringstream out; uint32 totalused = 0; // list out items in main backpack for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) { const Item* const pItem = m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (pItem) totalused++; } uint32 totalfree = 16 - totalused; // list out items in other removable backpacks for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*) m_bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) { ItemPrototype const* pBagProto = pBag->GetProto(); if (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) totalfree = totalfree + pBag->GetFreeSlots(); } } // calculate how much money bot has uint32 copper = m_bot->GetMoney(); uint32 gold = uint32(copper / 10000); copper -= (gold * 10000); uint32 silver = uint32(copper / 100); copper -= (silver * 100); out << "|cffffffff[|h|cff00ffff" << m_bot->GetName() << "|h|cffffffff]" << " has |r|cff00ff00" << gold << "|r|cfffffc00g|r|cff00ff00" << silver << "|r|cffcdcdcds|r|cff00ff00" << copper << "|r|cffffd333c" << "|h|cffffffff bag slots |h|cff00ff00" << totalfree; // estimate how much item damage the bot has copper = EstRepairAll(); gold = uint32(copper / 10000); copper -= (gold * 10000); silver = uint32(copper / 100); copper -= (silver * 100); out << "|h|cffffffff & item damage cost " << "|r|cff00ff00" << gold << "|r|cfffffc00g|r|cff00ff00" << silver << "|r|cffcdcdcds|r|cff00ff00" << copper << "|r|cffffd333c"; ChatHandler ch(&fromPlayer); ch.SendSysMessage(out.str().c_str()); } else { // if this looks like an item link, reward item it completed quest and talking to NPC std::list<uint32> itemIds; extractItemIds(text, itemIds); if (!itemIds.empty()) { uint32 itemId = itemIds.front(); bool wasRewarded = false; uint64 questRewarderGUID = m_bot->GetSelection(); Object* const pNpc = (WorldObject*) m_bot->GetObjectByTypeMask(questRewarderGUID, TYPEMASK_CREATURE_OR_GAMEOBJECT); if (!pNpc) return; QuestMenu& questMenu = m_bot->PlayerTalkClass->GetQuestMenu(); for (uint32 iI = 0; !wasRewarded && iI < questMenu.MenuItemCount(); ++iI) { QuestMenuItem const& qItem = questMenu.GetItem(iI); uint32 questID = qItem.m_qId; Quest const* pQuest = sObjectMgr.GetQuestTemplate(questID); QuestStatus status = m_bot->GetQuestStatus(questID); // if quest is complete, turn it in if (status == QUEST_STATUS_COMPLETE && ! m_bot->GetQuestRewardStatus(questID) && pQuest->GetRewChoiceItemsCount() > 1 && m_bot->CanRewardQuest(pQuest, false)) { for (uint8 rewardIdx=0; !wasRewarded && rewardIdx < pQuest->GetRewChoiceItemsCount(); ++rewardIdx) { ItemPrototype const * const pRewardItem = sObjectMgr.GetItemPrototype(pQuest->RewChoiceItemId[rewardIdx]); if (itemId == pRewardItem->ItemId) { m_bot->RewardQuest(pQuest, rewardIdx, pNpc, false); std::string questTitle = pQuest->GetTitle(); m_bot->GetPlayerbotAI()->QuestLocalization(questTitle, questID); std::string itemName = pRewardItem->Name1; m_bot->GetPlayerbotAI()->ItemLocalization(itemName, pRewardItem->ItemId); std::ostringstream out; out << "|cffffffff|Hitem:" << pRewardItem->ItemId << ":0:0:0:0:0:0:0" << "|h[" << itemName << "]|h|r rewarded"; SendWhisper(out.str(), fromPlayer); wasRewarded = true; } } } } } else { std::string msg = "What? follow, stay, (c)ast <spellname>, spells, (e)quip <itemlink>, (u)se <itemlink>, drop <questlink>, report, quests, stats"; SendWhisper(msg, fromPlayer); m_bot->HandleEmoteCommand(EMOTE_ONESHOT_TALK); } } }
3raZar3/Dark-Ice
src/game/PlayerbotAI.cpp
C++
gpl-2.0
122,644
#ifndef UTILITY_COMPAT_HPP #define UTILITY_COMPAT_HPP #include <boost/date_time/posix_time/posix_time.hpp> namespace utility { struct tm strptime( const char* timestamp ); } #endif
ajfazan/opensource
utility/compat.hpp
C++
gpl-2.0
189
<?php namespace MockSockets\Assertions { use MockSockets\JsonRpc\JsonRpcRequest; class MethodNameAssertion implements Assertion { private $expectedMethod; public function __construct($name) { if (!is_string($name)) { throw new \InvalidArgumentException('$name must be a string'); } $this->expectedMethod = $name; } public function verify(JsonRpcRequest $request) { return ($request->getMethod() == $this->expectedMethod); } } }
aztech-dev/php-mock-jsonrpc
MockSockets/Assertions/MethodNameAssertion.class.php
PHP
gpl-2.0
621
/* Copyright (c) 2005, 2006 by CodeSourcery. All rights reserved. This file is available for license from CodeSourcery, Inc. under the terms of a commercial license and under the GPL. It is not part of the VSIPL++ reference implementation and is not available under the BSD license. */ /** @file benchmarks/conv.cpp @author Jules Bergmann @date 2005-07-11 @brief VSIPL++ Library: Benchmark for 1D Convolution. */ /*********************************************************************** Included Files ***********************************************************************/ #include <iostream> #include <vsip/initfin.hpp> #include <vsip/support.hpp> #include <vsip/math.hpp> #include <vsip/signal.hpp> #include <vsip/opt/dispatch_diagnostics.hpp> #include <vsip_csl/test.hpp> #include "loop.hpp" using namespace vsip; /*********************************************************************** Definitions ***********************************************************************/ template <support_region_type Supp, typename T> struct t_conv1 : Benchmark_base { static length_type const Dec = 1; char const* what() { return "t_conv1"; } float ops_per_point(length_type size) { length_type output_size; if (Supp == support_full) output_size = ((size + coeff_size_ - 2)/Dec) + 1; else if (Supp == support_same) output_size = ((size-1)/Dec) + 1; else /* (Supp == support_min) */ output_size = ((size-1)/Dec) - ((coeff_size_-1)/Dec) + 1; float ops = coeff_size_ * output_size * (vsip::impl::Ops_info<T>::mul + vsip::impl::Ops_info<T>::add); return ops / size; } int riob_per_point(length_type) { return -1; } int wiob_per_point(length_type) { return -1; } int mem_per_point(length_type) { return 2*sizeof(T); } void operator()(length_type size, length_type loop, float& time) { length_type output_size; if (Supp == support_full) output_size = ((size + coeff_size_ - 2)/Dec) + 1; else if (Supp == support_same) output_size = ((size-1)/Dec) + 1; else /* (Supp == support_min) */ output_size = ((size-1)/Dec) - ((coeff_size_-1)/Dec) + 1; Vector<T> in (size, T()); Vector<T> out(output_size); Vector<T> coeff(coeff_size_, T()); coeff(0) = T(1); coeff(1) = T(2); symmetry_type const symmetry = nonsym; typedef Convolution<const_Vector, symmetry, Supp, T> conv_type; conv_type conv(coeff, Domain<1>(size), Dec); vsip::impl::profile::Timer t1; t1.start(); for (index_type l=0; l<loop; ++l) conv(in, out); t1.stop(); time = t1.delta(); } t_conv1(length_type coeff_size) : coeff_size_(coeff_size) {} void diag() { using namespace vsip_csl::dispatcher; typedef typename Dispatcher<op::conv<1, nonsym, Supp, T> >::backend backend; std::cout << "BE: " << Backend_name<backend>::name() << std::endl; } length_type coeff_size_; }; void defaults(Loop1P& loop) { loop.loop_start_ = 5000; loop.start_ = 4; loop.user_param_ = 16; } int test(Loop1P& loop, int what) { typedef complex<float> cf_type; switch (what) { case 1: loop(t_conv1<support_full, float>(loop.user_param_)); break; case 2: loop(t_conv1<support_same, float>(loop.user_param_)); break; case 3: loop(t_conv1<support_min, float>(loop.user_param_)); break; case 4: loop(t_conv1<support_full, cf_type>(loop.user_param_)); break; case 5: loop(t_conv1<support_same, cf_type>(loop.user_param_)); break; case 6: loop(t_conv1<support_min, cf_type>(loop.user_param_)); break; case 0: std::cout << "conv -- 1D convolution\n" << " -1 -- float, support=full\n" << " -2 -- float, support=same\n" << " -3 -- float, support=min\n" << " -4 -- complex<float>, support=full\n" << " -5 -- complex<float>, support=same\n" << " -6 -- complex<float>, support=min\n" << "\n" << " Parameters:\n" << " -param N -- size of coefficient vector (default 16)\n" << " -start N -- starting problem size 2^N (default 4 or 16 points)\n" << " -loop_start N -- initial number of calibration loops (default 5000)\n" ; default: return 0; } return 1; }
maxywb/vsipl
sourceryvsipl++-2.3/share/sourceryvsipl++/benchmarks/conv.cpp
C++
gpl-2.0
4,313
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file @brief This file defines all numerical functions */ #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" /* It is necessary to include set_var.h instead of item.h because there are dependencies on include order for set_var.h and item.h. This will be resolved later. */ #include "sql_class.h" // set_var.h: THD #include "set_var.h" #include "rpl_slave.h" // for wait_for_master_pos #include "sql_show.h" // append_identifier #include "strfunc.h" // find_type #include "sql_parse.h" // is_update_query #include "sql_acl.h" // EXECUTE_ACL #include "mysqld.h" // LOCK_uuid_generator #include "rpl_mi.h" #include "sql_time.h" #include <m_ctype.h> #include <hash.h> #include <time.h> #include <ft_global.h> #include <my_bit.h> #include "sp_head.h" #include "sp_rcontext.h" #include "sp.h" #include "set_var.h" #include "debug_sync.h" #include <mysql/plugin.h> #include <mysql/service_thd_wait.h> #include "rpl_gtid.h" using std::min; using std::max; bool check_reserved_words(LEX_STRING *name) { if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") || !my_strcasecmp(system_charset_info, name->str, "LOCAL") || !my_strcasecmp(system_charset_info, name->str, "SESSION")) return TRUE; return FALSE; } /** @return TRUE if item is a constant */ bool eval_const_cond(Item *cond) { return ((Item_func*) cond)->val_int() ? TRUE : FALSE; } /** Test if the sum of arguments overflows the ulonglong range. */ static inline bool test_if_sum_overflows_ull(ulonglong arg1, ulonglong arg2) { return ULONGLONG_MAX - arg1 < arg2; } void Item_func::set_arguments(List<Item> &list) { allowed_arg_cols= 1; arg_count=list.elements; args= tmp_arg; // If 2 arguments if (arg_count <= 2 || (args=(Item**) sql_alloc(sizeof(Item*)*arg_count))) { List_iterator_fast<Item> li(list); Item *item; Item **save_args= args; while ((item=li++)) { *(save_args++)= item; with_sum_func|=item->with_sum_func; } } list.empty(); // Fields are used } Item_func::Item_func(List<Item> &list) :allowed_arg_cols(1) { set_arguments(list); } Item_func::Item_func(THD *thd, Item_func *item) :Item_result_field(thd, item), const_item_cache(0), allowed_arg_cols(item->allowed_arg_cols), used_tables_cache(item->used_tables_cache), not_null_tables_cache(item->not_null_tables_cache), arg_count(item->arg_count) { if (arg_count) { if (arg_count <=2) args= tmp_arg; else { if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count))) return; } memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count); } } /* Resolve references to table column for a function and its argument SYNOPSIS: fix_fields() thd Thread object ref Pointer to where this object is used. This reference is used if we want to replace this object with another one (for example in the summary functions). DESCRIPTION Call fix_fields() for all arguments to the function. The main intention is to allow all Item_field() objects to setup pointers to the table fields. Sets as a side effect the following class variables: maybe_null Set if any argument may return NULL with_sum_func Set if any of the arguments contains a sum function used_tables_cache Set to union of the tables used by arguments str_value.charset If this is a string function, set this to the character set for the first argument. If any argument is binary, this is set to binary If for any item any of the defaults are wrong, then this can be fixed in the fix_length_and_dec() function that is called after this one or by writing a specialized fix_fields() for the item. RETURN VALUES FALSE ok TRUE Got error. Stored with my_error(). */ bool Item_func::fix_fields(THD *thd, Item **ref) { DBUG_ASSERT(fixed == 0 || basic_const_item()); Item **arg,**arg_end; uchar buff[STACK_BUFF_ALLOC]; // Max argument in function Switch_resolve_place SRP(thd->lex->current_select ? &thd->lex->current_select->resolve_place : NULL, st_select_lex::RESOLVE_NONE, thd->lex->current_select); used_tables_cache= get_initial_pseudo_tables(); not_null_tables_cache= 0; const_item_cache=1; /* Use stack limit of STACK_MIN_SIZE * 2 since on some platforms a recursive call to fix_fields requires more than STACK_MIN_SIZE bytes (e.g. for MIPS, it takes about 22kB to make one recursive call to Item_func::fix_fields()) */ if (check_stack_overrun(thd, STACK_MIN_SIZE * 2, buff)) return TRUE; // Fatal error if flag is set! if (arg_count) { // Print purify happy for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++) { Item *item; /* We can't yet set item to *arg as fix_fields may change *arg We shouldn't call fix_fields() twice, so check 'fixed' field first */ if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg))) return TRUE; /* purecov: inspected */ item= *arg; if (allowed_arg_cols) { if (item->check_cols(allowed_arg_cols)) return 1; } else { /* we have to fetch allowed_arg_cols from first argument */ DBUG_ASSERT(arg == args); // it is first argument allowed_arg_cols= item->cols(); DBUG_ASSERT(allowed_arg_cols); // Can't be 0 any more } if (item->maybe_null) maybe_null=1; with_sum_func= with_sum_func || item->with_sum_func; used_tables_cache|= item->used_tables(); not_null_tables_cache|= item->not_null_tables(); const_item_cache&= item->const_item(); with_subselect|= item->has_subquery(); with_stored_program|= item->has_stored_program(); } } fix_length_and_dec(); if (thd->is_error()) // An error inside fix_length_and_dec occured return TRUE; fixed= 1; return FALSE; } void Item_func::fix_after_pullout(st_select_lex *parent_select, st_select_lex *removed_select) { Item **arg,**arg_end; used_tables_cache= get_initial_pseudo_tables(); not_null_tables_cache= 0; const_item_cache=1; if (arg_count) { for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++) { Item *const item= *arg; item->fix_after_pullout(parent_select, removed_select); used_tables_cache|= item->used_tables(); not_null_tables_cache|= item->not_null_tables(); const_item_cache&= item->const_item(); } } } bool Item_func::walk(Item_processor processor, bool walk_subquery, uchar *argument) { if (arg_count) { Item **arg,**arg_end; for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) { if ((*arg)->walk(processor, walk_subquery, argument)) return 1; } } return (this->*processor)(argument); } void Item_func::traverse_cond(Cond_traverser traverser, void *argument, traverse_order order) { if (arg_count) { Item **arg,**arg_end; switch (order) { case(PREFIX): (*traverser)(this, argument); for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) { (*arg)->traverse_cond(traverser, argument, order); } break; case (POSTFIX): for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) { (*arg)->traverse_cond(traverser, argument, order); } (*traverser)(this, argument); } } else (*traverser)(this, argument); } /** Transform an Item_func object with a transformer callback function. The function recursively applies the transform method to each argument of the Item_func node. If the call of the method for an argument item returns a new item the old item is substituted for a new one. After this the transformer is applied to the root node of the Item_func object. @param transformer the transformer callback function to be applied to the nodes of the tree of the object @param argument parameter to be passed to the transformer @return Item returned as the result of transformation of the root node */ Item *Item_func::transform(Item_transformer transformer, uchar *argument) { DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare()); if (arg_count) { Item **arg,**arg_end; for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) { Item *new_item= (*arg)->transform(transformer, argument); if (!new_item) return 0; /* THD::change_item_tree() should be called only if the tree was really transformed, i.e. when a new item has been created. Otherwise we'll be allocating a lot of unnecessary memory for change records at each execution. */ if (*arg != new_item) current_thd->change_item_tree(arg, new_item); } } return (this->*transformer)(argument); } /** Compile Item_func object with a processor and a transformer callback functions. First the function applies the analyzer to the root node of the Item_func object. Then if the analizer succeeeds (returns TRUE) the function recursively applies the compile method to each argument of the Item_func node. If the call of the method for an argument item returns a new item the old item is substituted for a new one. After this the transformer is applied to the root node of the Item_func object. @param analyzer the analyzer callback function to be applied to the nodes of the tree of the object @param[in,out] arg_p parameter to be passed to the processor @param transformer the transformer callback function to be applied to the nodes of the tree of the object @param arg_t parameter to be passed to the transformer @return Item returned as result of transformation of the node, the same item if no transformation applied, or NULL if transformation caused an error. */ Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) { if (!(this->*analyzer)(arg_p)) return this; if (arg_count) { Item **arg,**arg_end; for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) { /* The same parameter value of arg_p must be passed to analyze any argument of the condition formula. */ uchar *arg_v= *arg_p; Item *new_item= (*arg)->compile(analyzer, &arg_v, transformer, arg_t); if (new_item == NULL) return NULL; if (*arg != new_item) current_thd->change_item_tree(arg, new_item); } } return (this->*transformer)(arg_t); } /** See comments in Item_cmp_func::split_sum_func() */ void Item_func::split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List<Item> &fields) { Item **arg, **arg_end; for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++) (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE); } void Item_func::update_used_tables() { used_tables_cache= get_initial_pseudo_tables(); const_item_cache=1; with_subselect= false; with_stored_program= false; for (uint i=0 ; i < arg_count ; i++) { args[i]->update_used_tables(); used_tables_cache|=args[i]->used_tables(); const_item_cache&=args[i]->const_item(); with_subselect|= args[i]->has_subquery(); with_stored_program|= args[i]->has_stored_program(); } } table_map Item_func::used_tables() const { return used_tables_cache; } table_map Item_func::not_null_tables() const { return not_null_tables_cache; } void Item_func::print(String *str, enum_query_type query_type) { str->append(func_name()); str->append('('); print_args(str, 0, query_type); str->append(')'); } void Item_func::print_args(String *str, uint from, enum_query_type query_type) { for (uint i=from ; i < arg_count ; i++) { if (i != from) str->append(','); args[i]->print(str, query_type); } } void Item_func::print_op(String *str, enum_query_type query_type) { str->append('('); for (uint i=0 ; i < arg_count-1 ; i++) { args[i]->print(str, query_type); str->append(' '); str->append(func_name()); str->append(' '); } args[arg_count-1]->print(str, query_type); str->append(')'); } bool Item_func::eq(const Item *item, bool binary_cmp) const { /* Assume we don't have rtti */ if (this == item) return 1; if (item->type() != FUNC_ITEM) return 0; Item_func *item_func=(Item_func*) item; Item_func::Functype func_type; if ((func_type= functype()) != item_func->functype() || arg_count != item_func->arg_count || (func_type != Item_func::FUNC_SP && func_name() != item_func->func_name()) || (func_type == Item_func::FUNC_SP && my_strcasecmp(system_charset_info, func_name(), item_func->func_name()))) return 0; for (uint i=0; i < arg_count ; i++) if (!args[i]->eq(item_func->args[i], binary_cmp)) return 0; return 1; } Field *Item_func::tmp_table_field(TABLE *table) { Field *field= NULL; switch (result_type()) { case INT_RESULT: if (max_char_length() > MY_INT32_NUM_DECIMAL_DIGITS) field= new Field_longlong(max_char_length(), maybe_null, item_name.ptr(), unsigned_flag); else field= new Field_long(max_char_length(), maybe_null, item_name.ptr(), unsigned_flag); break; case REAL_RESULT: field= new Field_double(max_char_length(), maybe_null, item_name.ptr(), decimals); break; case STRING_RESULT: return make_string_field(table); break; case DECIMAL_RESULT: field= Field_new_decimal::create_from_item(this); break; case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); field= 0; break; } if (field) field->init(table); return field; } my_decimal *Item_func::val_decimal(my_decimal *decimal_value) { DBUG_ASSERT(fixed); longlong nr= val_int(); if (null_value) return 0; /* purecov: inspected */ int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value); return decimal_value; } String *Item_real_func::val_str(String *str) { DBUG_ASSERT(fixed == 1); double nr= val_real(); if (null_value) return 0; /* purecov: inspected */ str->set_real(nr, decimals, collation.collation); return str; } my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value) { DBUG_ASSERT(fixed); double nr= val_real(); if (null_value) return 0; /* purecov: inspected */ double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value); return decimal_value; } void Item_func::fix_num_length_and_dec() { uint fl_length= 0; decimals=0; for (uint i=0 ; i < arg_count ; i++) { set_if_bigger(decimals,args[i]->decimals); set_if_bigger(fl_length, args[i]->max_length); } max_length=float_length(decimals); if (fl_length > max_length) { decimals= NOT_FIXED_DEC; max_length= float_length(NOT_FIXED_DEC); } } void Item_func_numhybrid::fix_num_length_and_dec() {} /** Count max_length and decimals for temporal functions. @param item Argument array @param nitems Number of arguments in the array. @retval False on success, true on error. */ void Item_func::count_datetime_length(Item **item, uint nitems) { unsigned_flag= 0; decimals= 0; if (field_type() != MYSQL_TYPE_DATE) { for (uint i= 0; i < nitems; i++) set_if_bigger(decimals, field_type() == MYSQL_TYPE_TIME ? item[i]->time_precision() : item[i]->datetime_precision()); } set_if_smaller(decimals, DATETIME_MAX_DECIMALS); uint len= decimals ? (decimals + 1) : 0; switch (field_type()) { case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: len+= MAX_DATETIME_WIDTH; break; case MYSQL_TYPE_DATE: case MYSQL_TYPE_NEWDATE: len+= MAX_DATE_WIDTH; break; case MYSQL_TYPE_TIME: len+= MAX_TIME_WIDTH; break; default: DBUG_ASSERT(0); } fix_char_length(len); } /** Set max_length/decimals of function if function is fixed point and result length/precision depends on argument ones. */ void Item_func::count_decimal_length() { int max_int_part= 0; decimals= 0; unsigned_flag= 1; for (uint i=0 ; i < arg_count ; i++) { set_if_bigger(decimals, args[i]->decimals); set_if_bigger(max_int_part, args[i]->decimal_int_part()); set_if_smaller(unsigned_flag, args[i]->unsigned_flag); } int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION); fix_char_length(my_decimal_precision_to_length_no_truncation(precision, decimals, unsigned_flag)); } /** Set max_length of if it is maximum length of its arguments. */ void Item_func::count_only_length(Item **item, uint nitems) { uint32 char_length= 0; unsigned_flag= 1; for (uint i= 0; i < nitems; i++) { set_if_bigger(char_length, item[i]->max_char_length()); set_if_smaller(unsigned_flag, item[i]->unsigned_flag); } fix_char_length(char_length); } /** Set max_length/decimals of function if function is floating point and result length/precision depends on argument ones. */ void Item_func::count_real_length() { uint32 length= 0; decimals= 0; max_length= 0; for (uint i=0 ; i < arg_count ; i++) { if (decimals != NOT_FIXED_DEC) { set_if_bigger(decimals, args[i]->decimals); set_if_bigger(length, (args[i]->max_length - args[i]->decimals)); } set_if_bigger(max_length, args[i]->max_length); } if (decimals != NOT_FIXED_DEC) { max_length= length; length+= decimals; if (length < max_length) // If previous operation gave overflow max_length= UINT_MAX32; else max_length= length; } } /** Calculate max_length and decimals for STRING_RESULT functions. @param field_type Field type. @param items Argument array. @param nitems Number of arguments. @retval False on success, true on error. */ bool Item_func::count_string_result_length(enum_field_types field_type, Item **items, uint nitems) { if (agg_arg_charsets_for_string_result(collation, items, nitems)) return true; if (is_temporal_type(field_type)) count_datetime_length(items, nitems); else { decimals= NOT_FIXED_DEC; count_only_length(items, nitems); } return false; } void Item_func::signal_divide_by_null() { THD *thd= current_thd; if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO) push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_DIVISION_BY_ZERO, ER(ER_DIVISION_BY_ZERO)); null_value= 1; } Item *Item_func::get_tmp_table_item(THD *thd) { if (!with_sum_func && !const_item()) return new Item_field(result_field); return copy_or_same(thd); } double Item_int_func::val_real() { DBUG_ASSERT(fixed == 1); return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int(); } String *Item_int_func::val_str(String *str) { DBUG_ASSERT(fixed == 1); longlong nr=val_int(); if (null_value) return 0; str->set_int(nr, unsigned_flag, collation.collation); return str; } void Item_func_connection_id::fix_length_and_dec() { Item_int_func::fix_length_and_dec(); unsigned_flag= 1; } bool Item_func_connection_id::fix_fields(THD *thd, Item **ref) { if (Item_int_func::fix_fields(thd, ref)) return TRUE; thd->thread_specific_used= TRUE; value= thd->variables.pseudo_thread_id; return FALSE; } /** Check arguments here to determine result's type for a numeric function of two arguments. */ void Item_num_op::find_num_type(void) { DBUG_ENTER("Item_num_op::find_num_type"); DBUG_PRINT("info", ("name %s", func_name())); DBUG_ASSERT(arg_count == 2); Item_result r0= args[0]->numeric_context_result_type(); Item_result r1= args[1]->numeric_context_result_type(); DBUG_ASSERT(r0 != STRING_RESULT && r1 != STRING_RESULT); if (r0 == REAL_RESULT || r1 == REAL_RESULT) { /* Since DATE/TIME/DATETIME data types return INT_RESULT/DECIMAL_RESULT type codes, we should never get to here when both fields are temporal. */ DBUG_ASSERT(!args[0]->is_temporal() || !args[1]->is_temporal()); count_real_length(); max_length= float_length(decimals); hybrid_type= REAL_RESULT; } else if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT) { hybrid_type= DECIMAL_RESULT; result_precision(); } else { DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT); decimals= 0; hybrid_type=INT_RESULT; result_precision(); } DBUG_PRINT("info", ("Type: %s", (hybrid_type == REAL_RESULT ? "REAL_RESULT" : hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : hybrid_type == INT_RESULT ? "INT_RESULT" : "--ILLEGAL!!!--"))); DBUG_VOID_RETURN; } /** Set result type for a numeric function of one argument (can be also used by a numeric function of many arguments, if the result type depends only on the first argument) */ void Item_func_num1::find_num_type() { DBUG_ENTER("Item_func_num1::find_num_type"); DBUG_PRINT("info", ("name %s", func_name())); switch (hybrid_type= args[0]->result_type()) { case INT_RESULT: unsigned_flag= args[0]->unsigned_flag; break; case STRING_RESULT: case REAL_RESULT: hybrid_type= REAL_RESULT; max_length= float_length(decimals); break; case DECIMAL_RESULT: break; default: DBUG_ASSERT(0); } DBUG_PRINT("info", ("Type: %s", (hybrid_type == REAL_RESULT ? "REAL_RESULT" : hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : hybrid_type == INT_RESULT ? "INT_RESULT" : "--ILLEGAL!!!--"))); DBUG_VOID_RETURN; } void Item_func_num1::fix_num_length_and_dec() { decimals= args[0]->decimals; max_length= args[0]->max_length; } void Item_func_numhybrid::fix_length_and_dec() { fix_num_length_and_dec(); find_num_type(); } String *Item_func_numhybrid::val_str(String *str) { DBUG_ASSERT(fixed == 1); switch (hybrid_type) { case DECIMAL_RESULT: { my_decimal decimal_value, *val; if (!(val= decimal_op(&decimal_value))) return 0; // null is set my_decimal_round(E_DEC_FATAL_ERROR, val, decimals, FALSE, val); str->set_charset(collation.collation); my_decimal2string(E_DEC_FATAL_ERROR, val, 0, 0, 0, str); break; } case INT_RESULT: { longlong nr= int_op(); if (null_value) return 0; /* purecov: inspected */ str->set_int(nr, unsigned_flag, collation.collation); break; } case REAL_RESULT: { double nr= real_op(); if (null_value) return 0; /* purecov: inspected */ str->set_real(nr, decimals, collation.collation); break; } case STRING_RESULT: switch (field_type()) { case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return val_string_from_datetime(str); case MYSQL_TYPE_DATE: return val_string_from_date(str); case MYSQL_TYPE_TIME: return val_string_from_time(str); default: break; } return str_op(&str_value); default: DBUG_ASSERT(0); } return str; } double Item_func_numhybrid::val_real() { DBUG_ASSERT(fixed == 1); switch (hybrid_type) { case DECIMAL_RESULT: { my_decimal decimal_value, *val; double result; if (!(val= decimal_op(&decimal_value))) return 0.0; // null is set my_decimal2double(E_DEC_FATAL_ERROR, val, &result); return result; } case INT_RESULT: { longlong result= int_op(); return unsigned_flag ? (double) ((ulonglong) result) : (double) result; } case REAL_RESULT: return real_op(); case STRING_RESULT: { switch (field_type()) { case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return val_real_from_decimal(); default: break; } char *end_not_used; int err_not_used; String *res= str_op(&str_value); return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(), &end_not_used, &err_not_used) : 0.0); } default: DBUG_ASSERT(0); } return 0.0; } longlong Item_func_numhybrid::val_int() { DBUG_ASSERT(fixed == 1); switch (hybrid_type) { case DECIMAL_RESULT: { my_decimal decimal_value, *val; if (!(val= decimal_op(&decimal_value))) return 0; // null is set longlong result; my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result); return result; } case INT_RESULT: return int_op(); case REAL_RESULT: return (longlong) rint(real_op()); case STRING_RESULT: { switch (field_type()) { case MYSQL_TYPE_DATE: return val_int_from_date(); case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return val_int_from_datetime(); case MYSQL_TYPE_TIME: return val_int_from_time(); default: break; } int err_not_used; String *res; if (!(res= str_op(&str_value))) return 0; char *end= (char*) res->ptr() + res->length(); const CHARSET_INFO *cs= res->charset(); return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used); } default: DBUG_ASSERT(0); } return 0; } my_decimal *Item_func_numhybrid::val_decimal(my_decimal *decimal_value) { my_decimal *val= decimal_value; DBUG_ASSERT(fixed == 1); switch (hybrid_type) { case DECIMAL_RESULT: val= decimal_op(decimal_value); break; case INT_RESULT: { longlong result= int_op(); int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, decimal_value); break; } case REAL_RESULT: { double result= (double)real_op(); double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value); break; } case STRING_RESULT: { switch (field_type()) { case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return val_decimal_from_date(decimal_value); case MYSQL_TYPE_TIME: return val_decimal_from_time(decimal_value); default: break; } String *res; if (!(res= str_op(&str_value))) return NULL; str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(), res->length(), res->charset(), decimal_value); break; } case ROW_RESULT: default: DBUG_ASSERT(0); } return val; } bool Item_func_numhybrid::get_date(MYSQL_TIME *ltime, uint fuzzydate) { DBUG_ASSERT(fixed == 1); switch (field_type()) { case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return date_op(ltime, fuzzydate); case MYSQL_TYPE_TIME: return get_date_from_time(ltime); default: return Item::get_date_from_non_temporal(ltime, fuzzydate); } } bool Item_func_numhybrid::get_time(MYSQL_TIME *ltime) { DBUG_ASSERT(fixed == 1); switch (field_type()) { case MYSQL_TYPE_TIME: return time_op(ltime); case MYSQL_TYPE_DATE: return get_time_from_date(ltime); case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return get_time_from_datetime(ltime); default: return Item::get_time_from_non_temporal(ltime); } } void Item_func_signed::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("cast(")); args[0]->print(str, query_type); str->append(STRING_WITH_LEN(" as signed)")); } longlong Item_func_signed::val_int_from_str(int *error) { char buff[MAX_FIELD_WIDTH], *end, *start; uint32 length; String tmp(buff,sizeof(buff), &my_charset_bin), *res; longlong value; const CHARSET_INFO *cs; /* For a string result, we must first get the string and then convert it to a longlong */ if (!(res= args[0]->val_str(&tmp))) { null_value= 1; *error= 0; return 0; } null_value= 0; start= (char *)res->ptr(); length= res->length(); cs= res->charset(); end= start + length; value= cs->cset->strtoll10(cs, start, &end, error); if (*error > 0 || end != start+ length) { ErrConvString err(res); push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_TRUNCATED_WRONG_VALUE, ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER", err.ptr()); } return value; } longlong Item_func_signed::val_int() { longlong value; int error; if (args[0]->cast_to_int_type() != STRING_RESULT || args[0]->is_temporal()) { value= args[0]->val_int(); null_value= args[0]->null_value; return value; } value= val_int_from_str(&error); if (value < 0 && error == 0) { push_warning(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, "Cast to signed converted positive out-of-range integer to " "it's negative complement"); } return value; } void Item_func_unsigned::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("cast(")); args[0]->print(str, query_type); str->append(STRING_WITH_LEN(" as unsigned)")); } longlong Item_func_unsigned::val_int() { longlong value; int error; if (args[0]->cast_to_int_type() == DECIMAL_RESULT) { my_decimal tmp, *dec= args[0]->val_decimal(&tmp); if (!(null_value= args[0]->null_value)) my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &value); else value= 0; return value; } else if (args[0]->cast_to_int_type() != STRING_RESULT || args[0]->is_temporal()) { value= args[0]->val_int(); null_value= args[0]->null_value; return value; } value= val_int_from_str(&error); if (error < 0) push_warning(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, "Cast to unsigned converted negative integer to it's " "positive complement"); return value; } String *Item_decimal_typecast::val_str(String *str) { my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); if (null_value) return NULL; my_decimal2string(E_DEC_FATAL_ERROR, tmp, 0, 0, 0, str); return str; } double Item_decimal_typecast::val_real() { my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); double res; if (null_value) return 0.0; my_decimal2double(E_DEC_FATAL_ERROR, tmp, &res); return res; } longlong Item_decimal_typecast::val_int() { my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); longlong res; if (null_value) return 0; my_decimal2int(E_DEC_FATAL_ERROR, tmp, unsigned_flag, &res); return res; } my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec) { my_decimal tmp_buf, *tmp= args[0]->val_decimal(&tmp_buf); bool sign; uint precision; if ((null_value= args[0]->null_value)) return NULL; my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec); sign= dec->sign(); if (unsigned_flag) { if (sign) { my_decimal_set_zero(dec); goto err; } } precision= my_decimal_length_to_precision(max_length, decimals, unsigned_flag); if (precision - decimals < (uint) my_decimal_intg(dec)) { max_my_decimal(dec, precision, decimals); dec->sign(sign); goto err; } return dec; err: push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, ER(ER_WARN_DATA_OUT_OF_RANGE), item_name.ptr(), 1L); return dec; } void Item_decimal_typecast::print(String *str, enum_query_type query_type) { char len_buf[20*3 + 1]; char *end; uint precision= my_decimal_length_to_precision(max_length, decimals, unsigned_flag); str->append(STRING_WITH_LEN("cast(")); args[0]->print(str, query_type); str->append(STRING_WITH_LEN(" as decimal(")); end=int10_to_str(precision, len_buf,10); str->append(len_buf, (uint32) (end - len_buf)); str->append(','); end=int10_to_str(decimals, len_buf,10); str->append(len_buf, (uint32) (end - len_buf)); str->append(')'); str->append(')'); } double Item_func_plus::real_op() { double value= args[0]->val_real() + args[1]->val_real(); if ((null_value=args[0]->null_value || args[1]->null_value)) return 0.0; return check_float_overflow(value); } longlong Item_func_plus::int_op() { longlong val0= args[0]->val_int(); longlong val1= args[1]->val_int(); longlong res= val0 + val1; bool res_unsigned= FALSE; if ((null_value= args[0]->null_value || args[1]->null_value)) return 0; /* First check whether the result can be represented as a (bool unsigned_flag, longlong value) pair, then check if it is compatible with this Item's unsigned_flag by calling check_integer_overflow(). */ if (args[0]->unsigned_flag) { if (args[1]->unsigned_flag || val1 >= 0) { if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1)) goto err; res_unsigned= TRUE; } else { /* val1 is negative */ if ((ulonglong) val0 > (ulonglong) LONGLONG_MAX) res_unsigned= TRUE; } } else { if (args[1]->unsigned_flag) { if (val0 >= 0) { if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1)) goto err; res_unsigned= TRUE; } else { if ((ulonglong) val1 > (ulonglong) LONGLONG_MAX) res_unsigned= TRUE; } } else { if (val0 >=0 && val1 >= 0) res_unsigned= TRUE; else if (val0 < 0 && val1 < 0 && res >= 0) goto err; } } return check_integer_overflow(res, res_unsigned); err: return raise_integer_overflow(); } /** Calculate plus of two decimals. @param decimal_value Buffer that can be used to store result @retval 0 Value was NULL; In this case null_value is set @retval \# Value of operation as a decimal */ my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value) { my_decimal value1, *val1; my_decimal value2, *val2; val1= args[0]->val_decimal(&value1); if ((null_value= args[0]->null_value)) return 0; val2= args[1]->val_decimal(&value2); if (!(null_value= (args[1]->null_value || check_decimal_overflow(my_decimal_add(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, decimal_value, val1, val2)) > 3))) return decimal_value; return 0; } /** Set precision of results for additive operations (+ and -) */ void Item_func_additive_op::result_precision() { decimals= max(args[0]->decimals, args[1]->decimals); int arg1_int= args[0]->decimal_precision() - args[0]->decimals; int arg2_int= args[1]->decimal_precision() - args[1]->decimals; int precision= max(arg1_int, arg2_int) + 1 + decimals; /* Integer operations keep unsigned_flag if one of arguments is unsigned */ if (result_type() == INT_RESULT) unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; else unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, unsigned_flag); } /** The following function is here to allow the user to force subtraction of UNSIGNED BIGINT to return negative values. */ void Item_func_additive_op::fix_length_and_dec() { Item_num_op::fix_length_and_dec(); if (unsigned_flag && (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION)) unsigned_flag=0; } double Item_func_minus::real_op() { double value= args[0]->val_real() - args[1]->val_real(); if ((null_value=args[0]->null_value || args[1]->null_value)) return 0.0; return check_float_overflow(value); } longlong Item_func_minus::int_op() { longlong val0= args[0]->val_int(); longlong val1= args[1]->val_int(); longlong res= val0 - val1; bool res_unsigned= FALSE; if ((null_value= args[0]->null_value || args[1]->null_value)) return 0; /* First check whether the result can be represented as a (bool unsigned_flag, longlong value) pair, then check if it is compatible with this Item's unsigned_flag by calling check_integer_overflow(). */ if (args[0]->unsigned_flag) { if (args[1]->unsigned_flag) { if ((ulonglong) val0 < (ulonglong) val1) { if (res >= 0) goto err; } else res_unsigned= TRUE; } else { if (val1 >= 0) { if ((ulonglong) val0 > (ulonglong) val1) res_unsigned= TRUE; } else { if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) -val1)) goto err; res_unsigned= TRUE; } } } else { if (args[1]->unsigned_flag) { if ((ulonglong) (val0 - LONGLONG_MIN) < (ulonglong) val1) goto err; } else { if (val0 > 0 && val1 < 0) res_unsigned= TRUE; else if (val0 < 0 && val1 > 0 && res >= 0) goto err; } } return check_integer_overflow(res, res_unsigned); err: return raise_integer_overflow(); } /** See Item_func_plus::decimal_op for comments. */ my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value) { my_decimal value1, *val1; my_decimal value2, *val2= val1= args[0]->val_decimal(&value1); if ((null_value= args[0]->null_value)) return 0; val2= args[1]->val_decimal(&value2); if (!(null_value= (args[1]->null_value || (check_decimal_overflow(my_decimal_sub(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, decimal_value, val1, val2)) > 3)))) return decimal_value; return 0; } double Item_func_mul::real_op() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real() * args[1]->val_real(); if ((null_value=args[0]->null_value || args[1]->null_value)) return 0.0; return check_float_overflow(value); } longlong Item_func_mul::int_op() { DBUG_ASSERT(fixed == 1); longlong a= args[0]->val_int(); longlong b= args[1]->val_int(); longlong res; ulonglong res0, res1; ulong a0, a1, b0, b1; bool res_unsigned= FALSE; bool a_negative= FALSE, b_negative= FALSE; if ((null_value= args[0]->null_value || args[1]->null_value)) return 0; /* First check whether the result can be represented as a (bool unsigned_flag, longlong value) pair, then check if it is compatible with this Item's unsigned_flag by calling check_integer_overflow(). Let a = a1 * 2^32 + a0 and b = b1 * 2^32 + b0. Then a * b = (a1 * 2^32 + a0) * (b1 * 2^32 + b0) = a1 * b1 * 2^64 + + (a1 * b0 + a0 * b1) * 2^32 + a0 * b0; We can determine if the above sum overflows the ulonglong range by sequentially checking the following conditions: 1. If both a1 and b1 are non-zero. 2. Otherwise, if (a1 * b0 + a0 * b1) is greater than ULONG_MAX. 3. Otherwise, if (a1 * b0 + a0 * b1) * 2^32 + a0 * b0 is greater than ULONGLONG_MAX. Since we also have to take the unsigned_flag for a and b into account, it is easier to first work with absolute values and set the correct sign later. */ if (!args[0]->unsigned_flag && a < 0) { a_negative= TRUE; a= -a; } if (!args[1]->unsigned_flag && b < 0) { b_negative= TRUE; b= -b; } a0= 0xFFFFFFFFUL & a; a1= ((ulonglong) a) >> 32; b0= 0xFFFFFFFFUL & b; b1= ((ulonglong) b) >> 32; if (a1 && b1) goto err; res1= (ulonglong) a1 * b0 + (ulonglong) a0 * b1; if (res1 > 0xFFFFFFFFUL) goto err; res1= res1 << 32; res0= (ulonglong) a0 * b0; if (test_if_sum_overflows_ull(res1, res0)) goto err; res= res1 + res0; if (a_negative != b_negative) { if ((ulonglong) res > (ulonglong) LONGLONG_MIN + 1) goto err; res= -res; } else res_unsigned= TRUE; return check_integer_overflow(res, res_unsigned); err: return raise_integer_overflow(); } /** See Item_func_plus::decimal_op for comments. */ my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value) { my_decimal value1, *val1; my_decimal value2, *val2; val1= args[0]->val_decimal(&value1); if ((null_value= args[0]->null_value)) return 0; val2= args[1]->val_decimal(&value2); if (!(null_value= (args[1]->null_value || (check_decimal_overflow(my_decimal_mul(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, decimal_value, val1, val2)) > 3)))) return decimal_value; return 0; } void Item_func_mul::result_precision() { /* Integer operations keep unsigned_flag if one of arguments is unsigned */ if (result_type() == INT_RESULT) unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; else unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE); uint est_prec = args[0]->decimal_precision() + args[1]->decimal_precision(); uint precision= min<uint>(est_prec, DECIMAL_MAX_PRECISION); max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, unsigned_flag); } double Item_func_div::real_op() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); double val2= args[1]->val_real(); if ((null_value= args[0]->null_value || args[1]->null_value)) return 0.0; if (val2 == 0.0) { signal_divide_by_null(); return 0.0; } return check_float_overflow(value/val2); } my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value) { my_decimal value1, *val1; my_decimal value2, *val2; int err; val1= args[0]->val_decimal(&value1); if ((null_value= args[0]->null_value)) return 0; val2= args[1]->val_decimal(&value2); if ((null_value= args[1]->null_value)) return 0; if ((err= check_decimal_overflow(my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW & ~E_DEC_DIV_ZERO, decimal_value, val1, val2, prec_increment))) > 3) { if (err == E_DEC_DIV_ZERO) signal_divide_by_null(); null_value= 1; return 0; } return decimal_value; } void Item_func_div::result_precision() { uint precision= min<uint>(args[0]->decimal_precision() + args[1]->decimals + prec_increment, DECIMAL_MAX_PRECISION); /* Integer operations keep unsigned_flag if one of arguments is unsigned */ if (result_type() == INT_RESULT) unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; else unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; decimals= min<uint>(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE); max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, unsigned_flag); } void Item_func_div::fix_length_and_dec() { DBUG_ENTER("Item_func_div::fix_length_and_dec"); prec_increment= current_thd->variables.div_precincrement; Item_num_op::fix_length_and_dec(); switch(hybrid_type) { case REAL_RESULT: { decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment; set_if_smaller(decimals, NOT_FIXED_DEC); uint tmp=float_length(decimals); if (decimals == NOT_FIXED_DEC) max_length= tmp; else { max_length=args[0]->max_length - args[0]->decimals + decimals; set_if_smaller(max_length,tmp); } break; } case INT_RESULT: hybrid_type= DECIMAL_RESULT; DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT")); result_precision(); break; case DECIMAL_RESULT: result_precision(); break; default: DBUG_ASSERT(0); } maybe_null= 1; // devision by zero DBUG_VOID_RETURN; } /* Integer division */ longlong Item_func_int_div::val_int() { DBUG_ASSERT(fixed == 1); /* Perform division using DECIMAL math if either of the operands has a non-integer type */ if (args[0]->result_type() != INT_RESULT || args[1]->result_type() != INT_RESULT) { my_decimal tmp; my_decimal *val0p= args[0]->val_decimal(&tmp); if ((null_value= args[0]->null_value)) return 0; my_decimal val0= *val0p; my_decimal *val1p= args[1]->val_decimal(&tmp); if ((null_value= args[1]->null_value)) return 0; my_decimal val1= *val1p; int err; if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, &tmp, &val0, &val1, 0)) > 3) { if (err == E_DEC_DIV_ZERO) signal_divide_by_null(); return 0; } my_decimal truncated; const bool do_truncate= true; if (my_decimal_round(E_DEC_FATAL_ERROR, &tmp, 0, do_truncate, &truncated)) DBUG_ASSERT(false); longlong res; if (my_decimal2int(E_DEC_FATAL_ERROR, &truncated, unsigned_flag, &res) & E_DEC_OVERFLOW) raise_integer_overflow(); return res; } longlong val0=args[0]->val_int(); longlong val1=args[1]->val_int(); bool val0_negative, val1_negative, res_negative; ulonglong uval0, uval1, res; if ((null_value= (args[0]->null_value || args[1]->null_value))) return 0; if (val1 == 0) { signal_divide_by_null(); return 0; } val0_negative= !args[0]->unsigned_flag && val0 < 0; val1_negative= !args[1]->unsigned_flag && val1 < 0; res_negative= val0_negative != val1_negative; uval0= (ulonglong) (val0_negative ? -val0 : val0); uval1= (ulonglong) (val1_negative ? -val1 : val1); res= uval0 / uval1; if (res_negative) { if (res > (ulonglong) LONGLONG_MAX) return raise_integer_overflow(); res= (ulonglong) (-(longlong) res); } return check_integer_overflow(res, !res_negative); } void Item_func_int_div::fix_length_and_dec() { Item_result argtype= args[0]->result_type(); /* use precision ony for the data type it is applicable for and valid */ max_length=args[0]->max_length - (argtype == DECIMAL_RESULT || argtype == INT_RESULT ? args[0]->decimals : 0); maybe_null=1; unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag; } longlong Item_func_mod::int_op() { DBUG_ASSERT(fixed == 1); longlong val0= args[0]->val_int(); longlong val1= args[1]->val_int(); bool val0_negative, val1_negative; ulonglong uval0, uval1; ulonglong res; if ((null_value= args[0]->null_value || args[1]->null_value)) return 0; /* purecov: inspected */ if (val1 == 0) { signal_divide_by_null(); return 0; } /* '%' is calculated by integer division internally. Since dividing LONGLONG_MIN by -1 generates SIGFPE, we calculate using unsigned values and then adjust the sign appropriately. */ val0_negative= !args[0]->unsigned_flag && val0 < 0; val1_negative= !args[1]->unsigned_flag && val1 < 0; uval0= (ulonglong) (val0_negative ? -val0 : val0); uval1= (ulonglong) (val1_negative ? -val1 : val1); res= uval0 % uval1; return check_integer_overflow(val0_negative ? -(longlong) res : res, !val0_negative); } double Item_func_mod::real_op() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); double val2= args[1]->val_real(); if ((null_value= args[0]->null_value || args[1]->null_value)) return 0.0; /* purecov: inspected */ if (val2 == 0.0) { signal_divide_by_null(); return 0.0; } return fmod(value,val2); } my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value) { my_decimal value1, *val1; my_decimal value2, *val2; val1= args[0]->val_decimal(&value1); if ((null_value= args[0]->null_value)) return 0; val2= args[1]->val_decimal(&value2); if ((null_value= args[1]->null_value)) return 0; switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value, val1, val2)) { case E_DEC_TRUNCATED: case E_DEC_OK: return decimal_value; case E_DEC_DIV_ZERO: signal_divide_by_null(); default: null_value= 1; return 0; } } void Item_func_mod::result_precision() { decimals= max(args[0]->decimals, args[1]->decimals); max_length= max(args[0]->max_length, args[1]->max_length); } void Item_func_mod::fix_length_and_dec() { Item_num_op::fix_length_and_dec(); maybe_null= 1; unsigned_flag= args[0]->unsigned_flag; } double Item_func_neg::real_op() { double value= args[0]->val_real(); null_value= args[0]->null_value; return -value; } longlong Item_func_neg::int_op() { longlong value= args[0]->val_int(); if ((null_value= args[0]->null_value)) return 0; if (args[0]->unsigned_flag && (ulonglong) value > (ulonglong) LONGLONG_MAX + 1ULL) return raise_integer_overflow(); // For some platforms we need special handling of LONGLONG_MIN to // guarantee overflow. if (value == LONGLONG_MIN && !args[0]->unsigned_flag && !unsigned_flag) return raise_integer_overflow(); return check_integer_overflow(-value, !args[0]->unsigned_flag && value < 0); } my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value) { my_decimal val, *value= args[0]->val_decimal(&val); if (!(null_value= args[0]->null_value)) { my_decimal2decimal(value, decimal_value); my_decimal_neg(decimal_value); return decimal_value; } return 0; } void Item_func_neg::fix_num_length_and_dec() { decimals= args[0]->decimals; /* 1 add because sign can appear */ max_length= args[0]->max_length + 1; } void Item_func_neg::fix_length_and_dec() { DBUG_ENTER("Item_func_neg::fix_length_and_dec"); Item_func_num1::fix_length_and_dec(); /* If this is in integer context keep the context as integer if possible (This is how multiplication and other integer functions works) Use val() to get value as arg_type doesn't mean that item is Item_int or Item_real due to existence of Item_param. */ if (hybrid_type == INT_RESULT && args[0]->const_item()) { longlong val= args[0]->val_int(); if ((ulonglong) val >= (ulonglong) LONGLONG_MIN && ((ulonglong) val != (ulonglong) LONGLONG_MIN || args[0]->type() != INT_ITEM)) { /* Ensure that result is converted to DECIMAL, as longlong can't hold the negated number */ hybrid_type= DECIMAL_RESULT; DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT")); } } unsigned_flag= 0; DBUG_VOID_RETURN; } double Item_func_abs::real_op() { double value= args[0]->val_real(); null_value= args[0]->null_value; return fabs(value); } longlong Item_func_abs::int_op() { longlong value= args[0]->val_int(); if ((null_value= args[0]->null_value)) return 0; if (unsigned_flag) return value; /* -LONGLONG_MIN = LONGLONG_MAX + 1 => outside of signed longlong range */ if (value == LONGLONG_MIN) return raise_integer_overflow(); return (value >= 0) ? value : -value; } my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value) { my_decimal val, *value= args[0]->val_decimal(&val); if (!(null_value= args[0]->null_value)) { my_decimal2decimal(value, decimal_value); if (decimal_value->sign()) my_decimal_neg(decimal_value); return decimal_value; } return 0; } void Item_func_abs::fix_length_and_dec() { Item_func_num1::fix_length_and_dec(); unsigned_flag= args[0]->unsigned_flag; } /** Gateway to natural LOG function. */ double Item_func_ln::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value= args[0]->null_value)) return 0.0; if (value <= 0.0) { signal_divide_by_null(); return 0.0; } return log(value); } /** Extended but so slower LOG function. We have to check if all values are > zero and first one is not one as these are the cases then result is not a number. */ double Item_func_log::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value= args[0]->null_value)) return 0.0; if (value <= 0.0) { signal_divide_by_null(); return 0.0; } if (arg_count == 2) { double value2= args[1]->val_real(); if ((null_value= args[1]->null_value)) return 0.0; if (value2 <= 0.0 || value == 1.0) { signal_divide_by_null(); return 0.0; } return log(value2) / log(value); } return log(value); } double Item_func_log2::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; if (value <= 0.0) { signal_divide_by_null(); return 0.0; } return log(value) / M_LN2; } double Item_func_log10::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value= args[0]->null_value)) return 0.0; if (value <= 0.0) { signal_divide_by_null(); return 0.0; } return log10(value); } double Item_func_exp::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; /* purecov: inspected */ return check_float_overflow(exp(value)); } double Item_func_sqrt::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=(args[0]->null_value || value < 0))) return 0.0; /* purecov: inspected */ return sqrt(value); } double Item_func_pow::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); double val2= args[1]->val_real(); if ((null_value=(args[0]->null_value || args[1]->null_value))) return 0.0; /* purecov: inspected */ return check_float_overflow(pow(value,val2)); } // Trigonometric functions double Item_func_acos::val_real() { DBUG_ASSERT(fixed == 1); /* One can use this to defer SELECT processing. */ DEBUG_SYNC(current_thd, "before_acos_function"); // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug) volatile double value= args[0]->val_real(); if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0)))) return 0.0; return acos(value); } double Item_func_asin::val_real() { DBUG_ASSERT(fixed == 1); // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug) volatile double value= args[0]->val_real(); if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0)))) return 0.0; return asin(value); } double Item_func_atan::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; if (arg_count == 2) { double val2= args[1]->val_real(); if ((null_value=args[1]->null_value)) return 0.0; return check_float_overflow(atan2(value,val2)); } return atan(value); } double Item_func_cos::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; return cos(value); } double Item_func_sin::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; return sin(value); } double Item_func_tan::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; return check_float_overflow(tan(value)); } double Item_func_cot::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0.0; return check_float_overflow(1.0 / tan(value)); } // Shift-functions, same as << and >> in C/C++ longlong Item_func_shift_left::val_int() { DBUG_ASSERT(fixed == 1); uint shift; ulonglong res= ((ulonglong) args[0]->val_int() << (shift=(uint) args[1]->val_int())); if (args[0]->null_value || args[1]->null_value) { null_value=1; return 0; } null_value=0; return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0)); } longlong Item_func_shift_right::val_int() { DBUG_ASSERT(fixed == 1); uint shift; ulonglong res= (ulonglong) args[0]->val_int() >> (shift=(uint) args[1]->val_int()); if (args[0]->null_value || args[1]->null_value) { null_value=1; return 0; } null_value=0; return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0)); } longlong Item_func_bit_neg::val_int() { DBUG_ASSERT(fixed == 1); ulonglong res= (ulonglong) args[0]->val_int(); if ((null_value=args[0]->null_value)) return 0; return ~res; } // Conversion functions void Item_func_integer::fix_length_and_dec() { max_length=args[0]->max_length - args[0]->decimals+1; uint tmp=float_length(decimals); set_if_smaller(max_length,tmp); decimals=0; } void Item_func_int_val::fix_num_length_and_dec() { ulonglong tmp_max_length= (ulonglong ) args[0]->max_length - (args[0]->decimals ? args[0]->decimals + 1 : 0) + 2; max_length= tmp_max_length > (ulonglong) 4294967295U ? (uint32) 4294967295U : (uint32) tmp_max_length; uint tmp= float_length(decimals); set_if_smaller(max_length,tmp); decimals= 0; } void Item_func_int_val::find_num_type() { DBUG_ENTER("Item_func_int_val::find_num_type"); DBUG_PRINT("info", ("name %s", func_name())); switch(hybrid_type= args[0]->result_type()) { case STRING_RESULT: case REAL_RESULT: hybrid_type= REAL_RESULT; max_length= float_length(decimals); break; case INT_RESULT: case DECIMAL_RESULT: /* -2 because in most high position can't be used any digit for longlong and one position for increasing value during operation */ if ((args[0]->max_length - args[0]->decimals) >= (DECIMAL_LONGLONG_DIGITS - 2)) { hybrid_type= DECIMAL_RESULT; } else { unsigned_flag= args[0]->unsigned_flag; hybrid_type= INT_RESULT; } break; default: DBUG_ASSERT(0); } DBUG_PRINT("info", ("Type: %s", (hybrid_type == REAL_RESULT ? "REAL_RESULT" : hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : hybrid_type == INT_RESULT ? "INT_RESULT" : "--ILLEGAL!!!--"))); DBUG_VOID_RETURN; } longlong Item_func_ceiling::int_op() { longlong result; switch (args[0]->result_type()) { case INT_RESULT: result= args[0]->val_int(); null_value= args[0]->null_value; break; case DECIMAL_RESULT: { my_decimal dec_buf, *dec; if ((dec= Item_func_ceiling::decimal_op(&dec_buf))) my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); else result= 0; break; } default: result= (longlong)Item_func_ceiling::real_op(); }; return result; } double Item_func_ceiling::real_op() { /* the volatile's for BUG #3051 to calm optimizer down (because of gcc's bug) */ volatile double value= args[0]->val_real(); null_value= args[0]->null_value; return ceil(value); } my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value) { my_decimal val, *value= args[0]->val_decimal(&val); if (!(null_value= (args[0]->null_value || my_decimal_ceiling(E_DEC_FATAL_ERROR, value, decimal_value) > 1))) return decimal_value; return 0; } longlong Item_func_floor::int_op() { longlong result; switch (args[0]->result_type()) { case INT_RESULT: result= args[0]->val_int(); null_value= args[0]->null_value; break; case DECIMAL_RESULT: { my_decimal dec_buf, *dec; if ((dec= Item_func_floor::decimal_op(&dec_buf))) my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); else result= 0; break; } default: result= (longlong)Item_func_floor::real_op(); }; return result; } double Item_func_floor::real_op() { /* the volatile's for BUG #3051 to calm optimizer down (because of gcc's bug) */ volatile double value= args[0]->val_real(); null_value= args[0]->null_value; return floor(value); } my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value) { my_decimal val, *value= args[0]->val_decimal(&val); if (!(null_value= (args[0]->null_value || my_decimal_floor(E_DEC_FATAL_ERROR, value, decimal_value) > 1))) return decimal_value; return 0; } void Item_func_round::fix_length_and_dec() { int decimals_to_set; longlong val1; bool val1_unsigned; unsigned_flag= args[0]->unsigned_flag; if (!args[1]->const_item()) { decimals= args[0]->decimals; max_length= float_length(decimals); if (args[0]->result_type() == DECIMAL_RESULT) { max_length++; hybrid_type= DECIMAL_RESULT; } else hybrid_type= REAL_RESULT; return; } val1= args[1]->val_int(); if ((null_value= args[1]->is_null())) return; val1_unsigned= args[1]->unsigned_flag; if (val1 < 0) decimals_to_set= val1_unsigned ? INT_MAX : 0; else decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1; if (args[0]->decimals == NOT_FIXED_DEC) { decimals= min(decimals_to_set, NOT_FIXED_DEC); max_length= float_length(decimals); hybrid_type= REAL_RESULT; return; } switch (args[0]->result_type()) { case REAL_RESULT: case STRING_RESULT: hybrid_type= REAL_RESULT; decimals= min(decimals_to_set, NOT_FIXED_DEC); max_length= float_length(decimals); break; case INT_RESULT: if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS)) { int length_can_increase= MY_TEST(!truncate && (val1 < 0) && !val1_unsigned); max_length= args[0]->max_length + length_can_increase; /* Here we can keep INT_RESULT */ hybrid_type= INT_RESULT; decimals= 0; break; } /* fall through */ case DECIMAL_RESULT: { hybrid_type= DECIMAL_RESULT; decimals_to_set= min(DECIMAL_MAX_SCALE, decimals_to_set); int decimals_delta= args[0]->decimals - decimals_to_set; int precision= args[0]->decimal_precision(); int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1; precision-= decimals_delta - length_increase; decimals= min(decimals_to_set, DECIMAL_MAX_SCALE); max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, unsigned_flag); break; } default: DBUG_ASSERT(0); /* This result type isn't handled */ } } double my_double_round(double value, longlong dec, bool dec_unsigned, bool truncate) { double tmp; bool dec_negative= (dec < 0) && !dec_unsigned; ulonglong abs_dec= dec_negative ? -dec : dec; /* tmp2 is here to avoid return the value with 80 bit precision This will fix that the test round(0.1,1) = round(0.1,1) is true Tagging with volatile is no guarantee, it may still be optimized away... */ volatile double tmp2; tmp=(abs_dec < array_elements(log_10) ? log_10[abs_dec] : pow(10.0,(double) abs_dec)); // Pre-compute these, to avoid optimizing away e.g. 'floor(v/tmp) * tmp'. volatile double value_div_tmp= value / tmp; volatile double value_mul_tmp= value * tmp; if (dec_negative && my_isinf(tmp)) tmp2= 0.0; else if (!dec_negative && my_isinf(value_mul_tmp)) tmp2= value; else if (truncate) { if (value >= 0.0) tmp2= dec < 0 ? floor(value_div_tmp) * tmp : floor(value_mul_tmp) / tmp; else tmp2= dec < 0 ? ceil(value_div_tmp) * tmp : ceil(value_mul_tmp) / tmp; } else tmp2=dec < 0 ? rint(value_div_tmp) * tmp : rint(value_mul_tmp) / tmp; return tmp2; } double Item_func_round::real_op() { double value= args[0]->val_real(); if (!(null_value= args[0]->null_value || args[1]->null_value)) return my_double_round(value, args[1]->val_int(), args[1]->unsigned_flag, truncate); return 0.0; } /* Rounds a given value to a power of 10 specified as the 'to' argument, avoiding overflows when the value is close to the ulonglong range boundary. */ static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to) { ulonglong tmp= value / to * to; return (value - tmp < (to >> 1)) ? tmp : tmp + to; } longlong Item_func_round::int_op() { longlong value= args[0]->val_int(); longlong dec= args[1]->val_int(); decimals= 0; ulonglong abs_dec; if ((null_value= args[0]->null_value || args[1]->null_value)) return 0; if ((dec >= 0) || args[1]->unsigned_flag) return value; // integer have not digits after point abs_dec= -dec; longlong tmp; if(abs_dec >= array_elements(log_10_int)) return 0; tmp= log_10_int[abs_dec]; if (truncate) value= (unsigned_flag) ? ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp; else value= (unsigned_flag || value >= 0) ? my_unsigned_round((ulonglong) value, tmp) : -(longlong) my_unsigned_round((ulonglong) -value, tmp); return value; } my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value) { my_decimal val, *value= args[0]->val_decimal(&val); longlong dec= args[1]->val_int(); if (dec >= 0 || args[1]->unsigned_flag) dec= min<ulonglong>(dec, decimals); else if (dec < INT_MIN) dec= INT_MIN; if (!(null_value= (args[0]->null_value || args[1]->null_value || my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec, truncate, decimal_value) > 1))) return decimal_value; return 0; } void Item_func_rand::seed_random(Item *arg) { /* TODO: do not do reinit 'rand' for every execute of PS/SP if args[0] is a constant. */ uint32 tmp= (uint32) arg->val_int(); randominit(rand, (uint32) (tmp*0x10001L+55555555L), (uint32) (tmp*0x10000001L)); } bool Item_func_rand::fix_fields(THD *thd,Item **ref) { if (Item_real_func::fix_fields(thd, ref)) return TRUE; if (arg_count) { // Only use argument once in query /* Allocate rand structure once: we must use thd->stmt_arena to create rand in proper mem_root if it's a prepared statement or stored procedure. No need to send a Rand log event if seed was given eg: RAND(seed), as it will be replicated in the query as such. */ if (!rand && !(rand= (struct rand_struct*) thd->stmt_arena->alloc(sizeof(*rand)))) return TRUE; } else { /* Save the seed only the first time RAND() is used in the query Once events are forwarded rather than recreated, the following can be skipped if inside the slave thread */ if (!thd->rand_used) { thd->rand_used= 1; thd->rand_saved_seed1= thd->rand.seed1; thd->rand_saved_seed2= thd->rand.seed2; } rand= &thd->rand; } return FALSE; } double Item_func_rand::val_real() { DBUG_ASSERT(fixed == 1); if (arg_count) { if (!args[0]->const_item()) seed_random(args[0]); else if (first_eval) { /* Constantness of args[0] may be set during JOIN::optimize(), if arg[0] is a field item of "constant" table. Thus, we have to evaluate seed_random() for constant arg there but not at the fix_fields method. */ first_eval= FALSE; seed_random(args[0]); } } return my_rnd(rand); } longlong Item_func_sign::val_int() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); null_value=args[0]->null_value; return value < 0.0 ? -1 : (value > 0 ? 1 : 0); } double Item_func_units::val_real() { DBUG_ASSERT(fixed == 1); double value= args[0]->val_real(); if ((null_value=args[0]->null_value)) return 0; return check_float_overflow(value * mul + add); } void Item_func_min_max::fix_length_and_dec() { uint string_arg_count= 0; int max_int_part=0; bool datetime_found= FALSE; decimals=0; max_length=0; maybe_null=0; cmp_type= args[0]->temporal_with_date_as_number_result_type(); for (uint i=0 ; i < arg_count ; i++) { set_if_bigger(max_length, args[i]->max_length); set_if_bigger(decimals, args[i]->decimals); set_if_bigger(max_int_part, args[i]->decimal_int_part()); if (args[i]->maybe_null) maybe_null=1; cmp_type= item_cmp_type(cmp_type, args[i]->temporal_with_date_as_number_result_type()); if (args[i]->result_type() == STRING_RESULT) string_arg_count++; if (args[i]->result_type() != ROW_RESULT && args[i]->is_temporal_with_date()) { datetime_found= TRUE; if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME) datetime_item= args[i]; } } if (string_arg_count == arg_count) { // We compare as strings only if all arguments were strings. agg_arg_charsets_for_string_result_with_comparison(collation, args, arg_count); if (datetime_found) { thd= current_thd; compare_as_dates= TRUE; /* We should not do this: cached_field_type= datetime_item->field_type(); count_datetime_length(args, arg_count); because compare_as_dates can be TRUE but result type can still be VARCHAR. */ } } else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT)) { collation.set_numeric(); fix_char_length(my_decimal_precision_to_length_no_truncation(max_int_part + decimals, decimals, unsigned_flag)); } else if (cmp_type == REAL_RESULT) fix_char_length(float_length(decimals)); cached_field_type= agg_field_type(args, arg_count); } /* Compare item arguments in the DATETIME context. SYNOPSIS cmp_datetimes() value [out] found least/greatest DATE/DATETIME value DESCRIPTION Compare item arguments as DATETIME values and return the index of the least/greatest argument in the arguments array. The correct integer DATE/DATETIME value of the found argument is stored to the value pointer, if latter is provided. RETURN 0 If one of arguments is NULL or there was a execution error # index of the least/greatest argument */ uint Item_func_min_max::cmp_datetimes(longlong *value) { longlong UNINIT_VAR(min_max); uint min_max_idx= 0; for (uint i=0; i < arg_count ; i++) { Item **arg= args + i; bool is_null; longlong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null); /* Check if we need to stop (because of error or KILL) and stop the loop */ if (thd->is_error()) { null_value= 1; return 0; } if ((null_value= args[i]->null_value)) return 0; if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0) { min_max= res; min_max_idx= i; } } if (value) *value= min_max; return min_max_idx; } uint Item_func_min_max::cmp_times(longlong *value) { longlong UNINIT_VAR(min_max); uint min_max_idx= 0; for (uint i=0; i < arg_count ; i++) { longlong res= args[i]->val_time_temporal(); if ((null_value= args[i]->null_value)) return 0; if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0) { min_max= res; min_max_idx= i; } } if (value) *value= min_max; return min_max_idx; } String *Item_func_min_max::val_str(String *str) { DBUG_ASSERT(fixed == 1); if (compare_as_dates) { if (is_temporal()) { /* In case of temporal data types, we always return string value according the format of the data type. For example, in case of LEAST(time_column, datetime_column) the result date type is DATETIME, so we return a 'YYYY-MM-DD hh:mm:ss' string even if time_column wins (conversion from TIME to DATETIME happens in this case). */ longlong result; cmp_datetimes(&result); if (null_value) return 0; MYSQL_TIME ltime; TIME_from_longlong_packed(&ltime, field_type(), result); return (null_value= my_TIME_to_str(&ltime, str, decimals)) ? (String *) 0 : str; } else { /* In case of VARCHAR result type we just return val_str() value of the winning item AS IS, without conversion. */ String *str_res; uint min_max_idx= cmp_datetimes(NULL); if (null_value) return 0; str_res= args[min_max_idx]->val_str(str); if (args[min_max_idx]->null_value) { // check if the call to val_str() above returns a NULL value null_value= 1; return NULL; } str_res->set_charset(collation.collation); return str_res; } } switch (cmp_type) { case INT_RESULT: { longlong nr=val_int(); if (null_value) return 0; str->set_int(nr, unsigned_flag, collation.collation); return str; } case DECIMAL_RESULT: { my_decimal dec_buf, *dec_val= val_decimal(&dec_buf); if (null_value) return 0; my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str); return str; } case REAL_RESULT: { double nr= val_real(); if (null_value) return 0; /* purecov: inspected */ str->set_real(nr, decimals, collation.collation); return str; } case STRING_RESULT: { String *UNINIT_VAR(res); for (uint i=0; i < arg_count ; i++) { if (i == 0) res=args[i]->val_str(str); else { String *res2; res2= args[i]->val_str(res == str ? &tmp_value : str); if (res2) { int cmp= sortcmp(res,res2,collation.collation); if ((cmp_sign < 0 ? cmp : -cmp) < 0) res=res2; } } if ((null_value= args[i]->null_value)) return 0; } res->set_charset(collation.collation); return res; } case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); return 0; } return 0; // Keep compiler happy } bool Item_func_min_max::get_date(MYSQL_TIME *ltime, uint fuzzydate) { DBUG_ASSERT(fixed == 1); if (compare_as_dates) { longlong result; cmp_datetimes(&result); if (null_value) return true; TIME_from_longlong_packed(ltime, datetime_item->field_type(), result); int warnings; return check_date(ltime, non_zero_date(ltime), fuzzydate, &warnings); } switch (field_type()) { case MYSQL_TYPE_TIME: return get_date_from_time(ltime); case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATE: DBUG_ASSERT(0); // Should have been processed in "compare_as_dates" block. default: return get_date_from_non_temporal(ltime, fuzzydate); } } bool Item_func_min_max::get_time(MYSQL_TIME *ltime) { DBUG_ASSERT(fixed == 1); if (compare_as_dates) { longlong result; cmp_datetimes(&result); if (null_value) return true; TIME_from_longlong_packed(ltime, datetime_item->field_type(), result); datetime_to_time(ltime); return false; } switch (field_type()) { case MYSQL_TYPE_TIME: { longlong result; cmp_times(&result); if (null_value) return true; TIME_from_longlong_time_packed(ltime, result); return false; } break; case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: DBUG_ASSERT(0); // Should have been processed in "compare_as_dates" block. default: return get_time_from_non_temporal(ltime); break; } } double Item_func_min_max::val_real() { DBUG_ASSERT(fixed == 1); double value=0.0; if (compare_as_dates) { longlong result= 0; (void)cmp_datetimes(&result); return double_from_datetime_packed(datetime_item->field_type(), result); } for (uint i=0; i < arg_count ; i++) { if (i == 0) value= args[i]->val_real(); else { double tmp= args[i]->val_real(); if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0) value=tmp; } if ((null_value= args[i]->null_value)) break; } return value; } longlong Item_func_min_max::val_int() { DBUG_ASSERT(fixed == 1); longlong value=0; if (compare_as_dates) { longlong result= 0; (void)cmp_datetimes(&result); return longlong_from_datetime_packed(datetime_item->field_type(), result); } /* TS-TODO: val_str decides which type to use using cmp_type. val_int, val_decimal, val_real do not check cmp_type and decide data type according to the method type. This is probably not good: mysql> select least('11', '2'), least('11', '2')+0, concat(least(11,2)); +------------------+--------------------+---------------------+ | least('11', '2') | least('11', '2')+0 | concat(least(11,2)) | +------------------+--------------------+---------------------+ | 11 | 2 | 2 | +------------------+--------------------+---------------------+ 1 row in set (0.00 sec) Should not the second column return 11? I.e. compare as strings and return '11', then convert to number. */ for (uint i=0; i < arg_count ; i++) { if (i == 0) value=args[i]->val_int(); else { longlong tmp=args[i]->val_int(); if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0) value=tmp; } if ((null_value= args[i]->null_value)) break; } return value; } my_decimal *Item_func_min_max::val_decimal(my_decimal *dec) { DBUG_ASSERT(fixed == 1); my_decimal tmp_buf, *tmp, *UNINIT_VAR(res); if (compare_as_dates) { longlong value= 0; (void)cmp_datetimes(&value); return my_decimal_from_datetime_packed(dec, datetime_item->field_type(), value); } for (uint i=0; i < arg_count ; i++) { if (i == 0) res= args[i]->val_decimal(dec); else { tmp= args[i]->val_decimal(&tmp_buf); // Zero if NULL if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0) { if (tmp == &tmp_buf) { /* Move value out of tmp_buf as this will be reused on next loop */ my_decimal2decimal(tmp, dec); res= dec; } else res= tmp; } } if ((null_value= args[i]->null_value)) { res= 0; break; } } if (res) { /* Need this to make val_str() always return fixed number of fractional digits, according to "decimals". */ my_decimal_round(E_DEC_FATAL_ERROR, res, decimals, false, res); } return res; } longlong Item_func_length::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); if (!res) { null_value=1; return 0; /* purecov: inspected */ } null_value=0; return (longlong) res->length(); } longlong Item_func_char_length::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); if (!res) { null_value=1; return 0; /* purecov: inspected */ } null_value=0; return (longlong) res->numchars(); } longlong Item_func_coercibility::val_int() { DBUG_ASSERT(fixed == 1); null_value= 0; return (longlong) args[0]->collation.derivation; } void Item_func_locate::fix_length_and_dec() { max_length= MY_INT32_NUM_DECIMAL_DIGITS; agg_arg_charsets_for_comparison(cmp_collation, args, 2); } longlong Item_func_locate::val_int() { DBUG_ASSERT(fixed == 1); String *a=args[0]->val_str(&value1); String *b=args[1]->val_str(&value2); if (!a || !b) { null_value=1; return 0; /* purecov: inspected */ } null_value=0; /* must be longlong to avoid truncation */ longlong start= 0; longlong start0= 0; my_match_t match; if (arg_count == 3) { start0= start= args[2]->val_int() - 1; if ((start < 0) || (start > a->length())) return 0; /* start is now sufficiently valid to pass to charpos function */ start= a->charpos((int) start); if (start + b->length() > a->length()) return 0; } if (!b->length()) // Found empty string at start return start + 1; if (!cmp_collation.collation->coll->instr(cmp_collation.collation, a->ptr()+start, (uint) (a->length()-start), b->ptr(), b->length(), &match, 1)) return 0; return (longlong) match.mb_len + start0 + 1; } void Item_func_locate::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("locate(")); args[1]->print(str, query_type); str->append(','); args[0]->print(str, query_type); if (arg_count == 3) { str->append(','); args[2]->print(str, query_type); } str->append(')'); } longlong Item_func_validate_password_strength::val_int() { String *field= args[0]->val_str(&value); if ((null_value= args[0]->null_value)) return 0; return (check_password_strength(field)); } longlong Item_func_field::val_int() { DBUG_ASSERT(fixed == 1); if (cmp_type == STRING_RESULT) { String *field; if (!(field= args[0]->val_str(&value))) return 0; for (uint i=1 ; i < arg_count ; i++) { String *tmp_value=args[i]->val_str(&tmp); if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation)) return (longlong) (i); } } else if (cmp_type == INT_RESULT) { longlong val= args[0]->val_int(); if (args[0]->null_value) return 0; for (uint i=1; i < arg_count ; i++) { if (val == args[i]->val_int() && !args[i]->null_value) return (longlong) (i); } } else if (cmp_type == DECIMAL_RESULT) { my_decimal dec_arg_buf, *dec_arg, dec_buf, *dec= args[0]->val_decimal(&dec_buf); if (args[0]->null_value) return 0; for (uint i=1; i < arg_count; i++) { dec_arg= args[i]->val_decimal(&dec_arg_buf); if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec)) return (longlong) (i); } } else { double val= args[0]->val_real(); if (args[0]->null_value) return 0; for (uint i=1; i < arg_count ; i++) { if (val == args[i]->val_real() && !args[i]->null_value) return (longlong) (i); } } return 0; } void Item_func_field::fix_length_and_dec() { maybe_null=0; max_length=3; cmp_type= args[0]->result_type(); for (uint i=1; i < arg_count ; i++) cmp_type= item_cmp_type(cmp_type, args[i]->result_type()); if (cmp_type == STRING_RESULT) agg_arg_charsets_for_comparison(cmp_collation, args, arg_count); } longlong Item_func_ascii::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); if (!res) { null_value=1; return 0; } null_value=0; return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0); } longlong Item_func_ord::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); if (!res) { null_value=1; return 0; } null_value=0; if (!res->length()) return 0; #ifdef USE_MB if (use_mb(res->charset())) { register const char *str=res->ptr(); register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length()); if (!l) return (longlong)((uchar) *str); while (l--) n=(n<<8)|(uint32)((uchar) *str++); return (longlong) n; } #endif return (longlong) ((uchar) (*res)[0]); } /* Search after a string in a string of strings separated by ',' */ /* Returns number of found type >= 1 or 0 if not found */ /* This optimizes searching in enums to bit testing! */ void Item_func_find_in_set::fix_length_and_dec() { decimals=0; max_length=3; // 1-999 if (args[0]->const_item() && args[1]->type() == FIELD_ITEM) { Field *field= ((Item_field*) args[1])->field; if (field->real_type() == MYSQL_TYPE_SET) { String *find=args[0]->val_str(&value); if (find) { // find is not NULL pointer so args[0] is not a null-value DBUG_ASSERT(!args[0]->null_value); enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(), find->length(), 0); enum_bit=0; if (enum_value) enum_bit=LL(1) << (enum_value-1); } } } agg_arg_charsets_for_comparison(cmp_collation, args, 2); } static const char separator=','; longlong Item_func_find_in_set::val_int() { DBUG_ASSERT(fixed == 1); if (enum_value) { // enum_value is set iff args[0]->const_item() in fix_length_and_dec(). DBUG_ASSERT(args[0]->const_item()); ulonglong tmp= (ulonglong) args[1]->val_int(); null_value= args[1]->null_value; /* No need to check args[0]->null_value since enum_value is set iff args[0] is a non-null const item. Note: no DBUG_ASSERT on args[0]->null_value here because args[0] may have been replaced by an Item_cache on which val_int() has not been called. See BUG#11766317 */ if (!null_value) { if (tmp & enum_bit) return enum_value; } return 0L; } String *find=args[0]->val_str(&value); String *buffer=args[1]->val_str(&value2); if (!find || !buffer) { null_value=1; return 0; /* purecov: inspected */ } null_value=0; int diff; if ((diff=buffer->length() - find->length()) >= 0) { my_wc_t wc= 0; const CHARSET_INFO *cs= cmp_collation.collation; const char *str_begin= buffer->ptr(); const char *str_end= buffer->ptr(); const char *real_end= str_end+buffer->length(); const uchar *find_str= (const uchar *) find->ptr(); uint find_str_len= find->length(); int position= 0; while (1) { int symbol_len; if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, (uchar*) real_end)) > 0) { const char *substr_end= str_end + symbol_len; bool is_last_item= (substr_end == real_end); bool is_separator= (wc == (my_wc_t) separator); if (is_separator || is_last_item) { position++; if (is_last_item && !is_separator) str_end= substr_end; if (!my_strnncoll(cs, (const uchar *) str_begin, (uint) (str_end - str_begin), find_str, find_str_len)) return (longlong) position; else str_begin= substr_end; } str_end= substr_end; } else if (str_end - str_begin == 0 && find_str_len == 0 && wc == (my_wc_t) separator) return (longlong) ++position; else return LL(0); } } return 0; } longlong Item_func_bit_count::val_int() { DBUG_ASSERT(fixed == 1); ulonglong value= (ulonglong) args[0]->val_int(); if ((null_value= args[0]->null_value)) return 0; /* purecov: inspected */ return (longlong) my_count_bits(value); } /**************************************************************************** ** Functions to handle dynamic loadable functions ** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su> ** Rewritten by monty. ****************************************************************************/ #ifdef HAVE_DLOPEN void udf_handler::cleanup() { if (!not_original) { if (initialized) { if (u_d->func_deinit != NULL) { Udf_func_deinit deinit= u_d->func_deinit; (*deinit)(&initid); } free_udf(u_d); initialized= FALSE; } if (buffers) // Because of bug in ecc delete [] buffers; buffers= 0; } } bool udf_handler::fix_fields(THD *thd, Item_result_field *func, uint arg_count, Item **arguments) { uchar buff[STACK_BUFF_ALLOC]; // Max argument in function DBUG_ENTER("Item_udf_func::fix_fields"); if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) DBUG_RETURN(TRUE); // Fatal error flag is set! udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1); if (!tmp_udf) { my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str); DBUG_RETURN(TRUE); } u_d=tmp_udf; args=arguments; /* Fix all arguments */ func->maybe_null=0; used_tables_cache=0; const_item_cache=1; if ((f_args.arg_count=arg_count)) { if (!(f_args.arg_type= (Item_result*) sql_alloc(f_args.arg_count*sizeof(Item_result)))) { free_udf(u_d); DBUG_RETURN(TRUE); } uint i; Item **arg,**arg_end; for (i=0, arg=arguments, arg_end=arguments+arg_count; arg != arg_end ; arg++,i++) { if (!(*arg)->fixed && (*arg)->fix_fields(thd, arg)) DBUG_RETURN(1); // we can't assign 'item' before, because fix_fields() can change arg Item *item= *arg; if (item->check_cols(1)) DBUG_RETURN(TRUE); /* TODO: We should think about this. It is not always right way just to set an UDF result to return my_charset_bin if one argument has binary sorting order. The result collation should be calculated according to arguments derivations in some cases and should not in other cases. Moreover, some arguments can represent a numeric input which doesn't effect the result character set and collation. There is no a general rule for UDF. Everything depends on the particular user defined function. */ if (item->collation.collation->state & MY_CS_BINSORT) func->collation.set(&my_charset_bin); if (item->maybe_null) func->maybe_null=1; func->with_sum_func= func->with_sum_func || item->with_sum_func; used_tables_cache|=item->used_tables(); const_item_cache&=item->const_item(); f_args.arg_type[i]=item->result_type(); } //TODO: why all following memory is not allocated with 1 call of sql_alloc? if (!(buffers=new String[arg_count]) || !(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) || !(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) || !(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) || !(num_buffer= (char*) sql_alloc(arg_count * ALIGN_SIZE(sizeof(double)))) || !(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) || !(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count * sizeof(long)))) { free_udf(u_d); DBUG_RETURN(TRUE); } } func->fix_length_and_dec(); initid.max_length=func->max_length; initid.maybe_null=func->maybe_null; initid.const_item=const_item_cache; initid.decimals=func->decimals; initid.ptr=0; if (u_d->func_init) { char init_msg_buff[MYSQL_ERRMSG_SIZE]; char *to=num_buffer; for (uint i=0; i < arg_count; i++) { /* For a constant argument i, args->args[i] points to the argument value. For non-constant, args->args[i] is NULL. */ f_args.args[i]= NULL; /* Non-const unless updated below. */ f_args.lengths[i]= arguments[i]->max_length; f_args.maybe_null[i]= (char) arguments[i]->maybe_null; f_args.attributes[i]= (char*) arguments[i]->item_name.ptr(); f_args.attribute_lengths[i]= arguments[i]->item_name.length(); if (arguments[i]->const_item()) { switch (arguments[i]->result_type()) { case STRING_RESULT: case DECIMAL_RESULT: { String *res= arguments[i]->val_str(&buffers[i]); if (arguments[i]->null_value) continue; f_args.args[i]= (char*) res->c_ptr_safe(); f_args.lengths[i]= res->length(); break; } case INT_RESULT: *((longlong*) to)= arguments[i]->val_int(); if (arguments[i]->null_value) continue; f_args.args[i]= to; to+= ALIGN_SIZE(sizeof(longlong)); break; case REAL_RESULT: *((double*) to)= arguments[i]->val_real(); if (arguments[i]->null_value) continue; f_args.args[i]= to; to+= ALIGN_SIZE(sizeof(double)); break; case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); break; } } } Udf_func_init init= u_d->func_init; if ((error=(uchar) init(&initid, &f_args, init_msg_buff))) { my_error(ER_CANT_INITIALIZE_UDF, MYF(0), u_d->name.str, init_msg_buff); free_udf(u_d); DBUG_RETURN(TRUE); } func->max_length= min<size_t>(initid.max_length, MAX_BLOB_WIDTH); func->maybe_null=initid.maybe_null; const_item_cache=initid.const_item; /* Keep used_tables_cache in sync with const_item_cache. See the comment in Item_udf_func::update_used tables. */ if (!const_item_cache && !used_tables_cache) used_tables_cache= RAND_TABLE_BIT; func->decimals= min<uint>(initid.decimals, NOT_FIXED_DEC); } initialized=1; if (error) { my_error(ER_CANT_INITIALIZE_UDF, MYF(0), u_d->name.str, ER(ER_UNKNOWN_ERROR)); DBUG_RETURN(TRUE); } DBUG_RETURN(FALSE); } bool udf_handler::get_arguments() { if (error) return 1; // Got an error earlier char *to= num_buffer; uint str_count=0; for (uint i=0; i < f_args.arg_count; i++) { f_args.args[i]=0; switch (f_args.arg_type[i]) { case STRING_RESULT: case DECIMAL_RESULT: { String *res=args[i]->val_str(&buffers[str_count++]); if (!(args[i]->null_value)) { f_args.args[i]= (char*) res->ptr(); f_args.lengths[i]= res->length(); break; } } case INT_RESULT: *((longlong*) to) = args[i]->val_int(); if (!args[i]->null_value) { f_args.args[i]=to; to+= ALIGN_SIZE(sizeof(longlong)); } break; case REAL_RESULT: *((double*) to)= args[i]->val_real(); if (!args[i]->null_value) { f_args.args[i]=to; to+= ALIGN_SIZE(sizeof(double)); } break; case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); break; } } return 0; } /** @return (String*)NULL in case of NULL values */ String *udf_handler::val_str(String *str,String *save_str) { uchar is_null_tmp=0; ulong res_length; DBUG_ENTER("udf_handler::val_str"); if (get_arguments()) DBUG_RETURN(0); char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)= (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)) u_d->func; if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH) { // This happens VERY seldom if (str->alloc(MAX_FIELD_WIDTH)) { error=1; DBUG_RETURN(0); } } char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length, &is_null_tmp, &error); DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length)); if (is_null_tmp || !res || error) // The !res is for safety { DBUG_PRINT("info", ("Null or error")); DBUG_RETURN(0); } if (res == str->ptr()) { str->length(res_length); DBUG_PRINT("exit", ("str: %*.s", (int) str->length(), str->ptr())); DBUG_RETURN(str); } save_str->set(res, res_length, str->charset()); DBUG_PRINT("exit", ("save_str: %s", save_str->ptr())); DBUG_RETURN(save_str); } /* For the moment, UDF functions are returning DECIMAL values as strings */ my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf) { char buf[DECIMAL_MAX_STR_LENGTH+1], *end; ulong res_length= DECIMAL_MAX_STR_LENGTH; if (get_arguments()) { *null_value=1; return 0; } char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)= (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)) u_d->func; char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error); if (is_null || error) { *null_value= 1; return 0; } end= res+ res_length; str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end); return dec_buf; } void Item_udf_func::cleanup() { udf.cleanup(); Item_func::cleanup(); } void Item_udf_func::print(String *str, enum_query_type query_type) { str->append(func_name()); str->append('('); for (uint i=0 ; i < arg_count ; i++) { if (i != 0) str->append(','); args[i]->print_item_w_name(str, query_type); } str->append(')'); } double Item_func_udf_float::val_real() { DBUG_ASSERT(fixed == 1); DBUG_ENTER("Item_func_udf_float::val"); DBUG_PRINT("info",("result_type: %d arg_count: %d", args[0]->result_type(), arg_count)); DBUG_RETURN(udf.val(&null_value)); } String *Item_func_udf_float::val_str(String *str) { DBUG_ASSERT(fixed == 1); double nr= val_real(); if (null_value) return 0; /* purecov: inspected */ str->set_real(nr,decimals,&my_charset_bin); return str; } longlong Item_func_udf_int::val_int() { DBUG_ASSERT(fixed == 1); DBUG_ENTER("Item_func_udf_int::val_int"); DBUG_RETURN(udf.val_int(&null_value)); } String *Item_func_udf_int::val_str(String *str) { DBUG_ASSERT(fixed == 1); longlong nr=val_int(); if (null_value) return 0; str->set_int(nr, unsigned_flag, &my_charset_bin); return str; } longlong Item_func_udf_decimal::val_int() { my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); longlong result; if (null_value) return 0; my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); return result; } double Item_func_udf_decimal::val_real() { my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); double result; if (null_value) return 0.0; my_decimal2double(E_DEC_FATAL_ERROR, dec, &result); return result; } my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf) { DBUG_ASSERT(fixed == 1); DBUG_ENTER("Item_func_udf_decimal::val_decimal"); DBUG_PRINT("info",("result_type: %d arg_count: %d", args[0]->result_type(), arg_count)); DBUG_RETURN(udf.val_decimal(&null_value, dec_buf)); } String *Item_func_udf_decimal::val_str(String *str) { my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); if (null_value) return 0; if (str->length() < DECIMAL_MAX_STR_LENGTH) str->length(DECIMAL_MAX_STR_LENGTH); my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf); my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str); return str; } void Item_func_udf_decimal::fix_length_and_dec() { fix_num_length_and_dec(); } /* Default max_length is max argument length */ void Item_func_udf_str::fix_length_and_dec() { DBUG_ENTER("Item_func_udf_str::fix_length_and_dec"); max_length=0; for (uint i = 0; i < arg_count; i++) set_if_bigger(max_length,args[i]->max_length); DBUG_VOID_RETURN; } String *Item_func_udf_str::val_str(String *str) { DBUG_ASSERT(fixed == 1); String *res=udf.val_str(str,&str_value); null_value = !res; return res; } /** @note This has to come last in the udf_handler methods, or C for AIX version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.) */ udf_handler::~udf_handler() { /* Everything should be properly cleaned up by this moment. */ DBUG_ASSERT(not_original || !(initialized || buffers)); } #else bool udf_handler::get_arguments() { return 0; } #endif /* HAVE_DLOPEN */ /* ** User level locks */ mysql_mutex_t LOCK_user_locks; static HASH hash_user_locks; class User_level_lock { uchar *key; size_t key_length; public: int count; bool locked; mysql_cond_t cond; my_thread_id thread_id; void set_thread(THD *thd) { thread_id= thd->thread_id; } User_level_lock(const uchar *key_arg,uint length, ulong id) :key_length(length),count(1),locked(1), thread_id(id) { key= (uchar*) my_memdup(key_arg,length,MYF(0)); mysql_cond_init(key_user_level_lock_cond, &cond, NULL); if (key) { if (my_hash_insert(&hash_user_locks,(uchar*) this)) { my_free(key); key=0; } } } ~User_level_lock() { if (key) { my_hash_delete(&hash_user_locks,(uchar*) this); my_free(key); } mysql_cond_destroy(&cond); } inline bool initialized() { return key != 0; } friend void item_user_lock_release(User_level_lock *ull); friend uchar *ull_get_key(const User_level_lock *ull, size_t *length, my_bool not_used); }; uchar *ull_get_key(const User_level_lock *ull, size_t *length, my_bool not_used __attribute__((unused))) { *length= ull->key_length; return ull->key; } #ifdef HAVE_PSI_INTERFACE static PSI_mutex_key key_LOCK_user_locks; static PSI_mutex_info all_user_mutexes[]= { { &key_LOCK_user_locks, "LOCK_user_locks", PSI_FLAG_GLOBAL} }; static void init_user_lock_psi_keys(void) { int count; count= array_elements(all_user_mutexes); mysql_mutex_register("sql", all_user_mutexes, count); } #endif static bool item_user_lock_inited= 0; void item_user_lock_init(void) { #ifdef HAVE_PSI_INTERFACE init_user_lock_psi_keys(); #endif mysql_mutex_init(key_LOCK_user_locks, &LOCK_user_locks, MY_MUTEX_INIT_SLOW); my_hash_init(&hash_user_locks,system_charset_info, 16,0,0,(my_hash_get_key) ull_get_key,NULL,0); item_user_lock_inited= 1; } void item_user_lock_free(void) { if (item_user_lock_inited) { item_user_lock_inited= 0; my_hash_free(&hash_user_locks); mysql_mutex_destroy(&LOCK_user_locks); } } void item_user_lock_release(User_level_lock *ull) { ull->locked=0; ull->thread_id= 0; if (--ull->count) mysql_cond_signal(&ull->cond); else delete ull; } /** Wait until we are at or past the given position in the master binlog on the slave. */ longlong Item_master_pos_wait::val_int() { DBUG_ASSERT(fixed == 1); THD* thd = current_thd; String *log_name = args[0]->val_str(&value); int event_count= 0; null_value=0; if (thd->slave_thread || !log_name || !log_name->length()) { null_value = 1; return 0; } #ifdef HAVE_REPLICATION longlong pos = (ulong)args[1]->val_int(); longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ; if (active_mi == NULL || (event_count = active_mi->rli->wait_for_pos(thd, log_name, pos, timeout)) == -2) { null_value = 1; event_count=0; } #endif return event_count; } longlong Item_master_gtid_set_wait::val_int() { DBUG_ASSERT(fixed == 1); THD* thd = current_thd; String *gtid= args[0]->val_str(&value); int event_count= 0; null_value=0; if (thd->slave_thread || !gtid || 0 == gtid_mode) { null_value = 1; return event_count; } #if defined(HAVE_REPLICATION) longlong timeout = (arg_count== 2) ? args[1]->val_int() : 0; if (active_mi && active_mi->rli) { if ((event_count = active_mi->rli->wait_for_gtid_set(thd, gtid, timeout)) == -2) { null_value = 1; event_count=0; } } else /* Replication has not been set up, we should return NULL; */ null_value = 1; #endif return event_count; } /** Return 1 if both arguments are Gtid_sets and the first is a subset of the second. Generate an error if any of the arguments is not a Gtid_set. */ longlong Item_func_gtid_subset::val_int() { DBUG_ENTER("Item_func_gtid_subset::val_int()"); if (args[0]->null_value || args[1]->null_value) { null_value= true; DBUG_RETURN(0); } String *string1, *string2; const char *charp1, *charp2; int ret= 1; enum_return_status status; // get strings without lock if ((string1= args[0]->val_str(&buf1)) != NULL && (charp1= string1->c_ptr_safe()) != NULL && (string2= args[1]->val_str(&buf2)) != NULL && (charp2= string2->c_ptr_safe()) != NULL) { Sid_map sid_map(NULL/*no rwlock*/); // compute sets while holding locks const Gtid_set sub_set(&sid_map, charp1, &status); if (status == RETURN_STATUS_OK) { const Gtid_set super_set(&sid_map, charp2, &status); if (status == RETURN_STATUS_OK) ret= sub_set.is_subset(&super_set) ? 1 : 0; } } DBUG_RETURN(ret); } /** Enables a session to wait on a condition until a timeout or a network disconnect occurs. @remark The connection is polled every m_interrupt_interval nanoseconds. */ class Interruptible_wait { THD *m_thd; struct timespec m_abs_timeout; static const ulonglong m_interrupt_interval; public: Interruptible_wait(THD *thd) : m_thd(thd) {} ~Interruptible_wait() {} public: /** Set the absolute timeout. @param timeout The amount of time in nanoseconds to wait */ void set_timeout(ulonglong timeout) { /* Calculate the absolute system time at the start so it can be controlled in slices. It relies on the fact that once the absolute time passes, the timed wait call will fail automatically with a timeout error. */ set_timespec_nsec(m_abs_timeout, timeout); } /** The timed wait. */ int wait(mysql_cond_t *, mysql_mutex_t *); }; /** Time to wait before polling the connection status. */ const ulonglong Interruptible_wait::m_interrupt_interval= 5 * ULL(1000000000); /** Wait for a given condition to be signaled. @param cond The condition variable to wait on. @param mutex The associated mutex. @remark The absolute timeout is preserved across calls. @retval return value from mysql_cond_timedwait */ int Interruptible_wait::wait(mysql_cond_t *cond, mysql_mutex_t *mutex) { int error; struct timespec timeout; while (1) { /* Wait for a fixed interval. */ set_timespec_nsec(timeout, m_interrupt_interval); /* But only if not past the absolute timeout. */ if (cmp_timespec(timeout, m_abs_timeout) > 0) timeout= m_abs_timeout; error= mysql_cond_timedwait(cond, mutex, &timeout); if (error == ETIMEDOUT || error == ETIME) { /* Return error if timed out or connection is broken. */ if (!cmp_timespec(timeout, m_abs_timeout) || !m_thd->is_connected()) break; } /* Otherwise, propagate status to the caller. */ else break; } return error; } /** Get a user level lock. If the thread has an old lock this is first released. @retval 1 : Got lock @retval 0 : Timeout @retval NULL : Error */ longlong Item_func_get_lock::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); ulonglong timeout= args[1]->val_int(); THD *thd=current_thd; User_level_lock *ull; int error; Interruptible_wait timed_cond(thd); DBUG_ENTER("Item_func_get_lock::val_int"); /* In slave thread no need to get locks, everything is serialized. Anyway there is no way to make GET_LOCK() work on slave like it did on master (i.e. make it return exactly the same value) because we don't have the same other concurrent threads environment. No matter what we return here, it's not guaranteed to be same as on master. */ if (thd->slave_thread) DBUG_RETURN(1); mysql_mutex_lock(&LOCK_user_locks); if (!res || !res->length()) { mysql_mutex_unlock(&LOCK_user_locks); null_value=1; DBUG_RETURN(0); } DBUG_PRINT("info", ("lock %.*s, thd=%ld", res->length(), res->ptr(), (long) thd->real_id)); null_value=0; if (thd->ull) { item_user_lock_release(thd->ull); thd->ull=0; } if (!(ull= ((User_level_lock *) my_hash_search(&hash_user_locks, (uchar*) res->ptr(), (size_t) res->length())))) { ull= new User_level_lock((uchar*) res->ptr(), (size_t) res->length(), thd->thread_id); if (!ull || !ull->initialized()) { delete ull; mysql_mutex_unlock(&LOCK_user_locks); null_value=1; // Probably out of memory DBUG_RETURN(0); } ull->set_thread(thd); thd->ull=ull; mysql_mutex_unlock(&LOCK_user_locks); DBUG_PRINT("info", ("made new lock")); DBUG_RETURN(1); // Got new lock } ull->count++; DBUG_PRINT("info", ("ull->count=%d", ull->count)); /* Structure is now initialized. Try to get the lock. Set up control struct to allow others to abort locks. */ THD_STAGE_INFO(thd, stage_user_lock); thd->mysys_var->current_mutex= &LOCK_user_locks; thd->mysys_var->current_cond= &ull->cond; timed_cond.set_timeout(timeout * ULL(1000000000)); error= 0; thd_wait_begin(thd, THD_WAIT_USER_LOCK); while (ull->locked && !thd->killed) { DBUG_PRINT("info", ("waiting on lock")); error= timed_cond.wait(&ull->cond, &LOCK_user_locks); if (error == ETIMEDOUT || error == ETIME) { DBUG_PRINT("info", ("lock wait timeout")); break; } error= 0; } thd_wait_end(thd); if (ull->locked) { if (!--ull->count) { DBUG_ASSERT(0); delete ull; // Should never happen } if (!error) // Killed (thd->killed != 0) { error=1; null_value=1; // Return NULL } } else // We got the lock { ull->locked=1; ull->set_thread(thd); ull->thread_id= thd->thread_id; thd->ull=ull; error=0; DBUG_PRINT("info", ("got the lock")); } mysql_mutex_unlock(&LOCK_user_locks); mysql_mutex_lock(&thd->mysys_var->mutex); thd->mysys_var->current_mutex= 0; thd->mysys_var->current_cond= 0; mysql_mutex_unlock(&thd->mysys_var->mutex); DBUG_RETURN(!error ? 1 : 0); } /** Release a user level lock. @return - 1 if lock released - 0 if lock wasn't held - (SQL) NULL if no such lock */ longlong Item_func_release_lock::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); User_level_lock *ull; longlong result; THD *thd=current_thd; DBUG_ENTER("Item_func_release_lock::val_int"); if (!res || !res->length()) { null_value=1; DBUG_RETURN(0); } DBUG_PRINT("info", ("lock %.*s", res->length(), res->ptr())); null_value=0; result=0; mysql_mutex_lock(&LOCK_user_locks); if (!(ull= ((User_level_lock*) my_hash_search(&hash_user_locks, (const uchar*) res->ptr(), (size_t) res->length())))) { null_value=1; } else { DBUG_PRINT("info", ("ull->locked=%d ull->thread=%lu thd=%lu", (int) ull->locked, (long)ull->thread_id, (long)thd->thread_id)); if (ull->locked && current_thd->thread_id == ull->thread_id) { DBUG_PRINT("info", ("release lock")); result=1; // Release is ok item_user_lock_release(ull); thd->ull=0; } } mysql_mutex_unlock(&LOCK_user_locks); DBUG_RETURN(result); } longlong Item_func_last_insert_id::val_int() { THD *thd= current_thd; DBUG_ASSERT(fixed == 1); if (arg_count) { longlong value= args[0]->val_int(); null_value= args[0]->null_value; /* LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as documented in the manual. We don't want to touch first_successful_insert_id_in_cur_stmt because it would make LAST_INSERT_ID(X) take precedence over an generated auto_increment value for this row. */ thd->arg_of_last_insert_id_function= TRUE; thd->first_successful_insert_id_in_prev_stmt= value; return value; } return static_cast<longlong>(thd->read_first_successful_insert_id_in_prev_stmt()); } bool Item_func_last_insert_id::fix_fields(THD *thd, Item **ref) { thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT); return Item_int_func::fix_fields(thd, ref); } /* This function is just used to test speed of different functions */ longlong Item_func_benchmark::val_int() { DBUG_ASSERT(fixed == 1); char buff[MAX_FIELD_WIDTH]; String tmp(buff,sizeof(buff), &my_charset_bin); my_decimal tmp_decimal; THD *thd=current_thd; ulonglong loop_count; loop_count= (ulonglong) args[0]->val_int(); if (args[0]->null_value || (!args[0]->unsigned_flag && (((longlong) loop_count) < 0))) { if (!args[0]->null_value) { char buff[22]; llstr(((longlong) loop_count), buff); push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE), "count", buff, "benchmark"); } null_value= 1; return 0; } null_value=0; for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++) { switch (args[1]->result_type()) { case REAL_RESULT: (void) args[1]->val_real(); break; case INT_RESULT: (void) args[1]->val_int(); break; case STRING_RESULT: (void) args[1]->val_str(&tmp); break; case DECIMAL_RESULT: (void) args[1]->val_decimal(&tmp_decimal); break; case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); return 0; } } return 0; } void Item_func_benchmark::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("benchmark(")); args[0]->print(str, query_type); str->append(','); args[1]->print(str, query_type); str->append(')'); } /** This function is just used to create tests with time gaps. */ longlong Item_func_sleep::val_int() { THD *thd= current_thd; Interruptible_wait timed_cond(thd); mysql_cond_t cond; double timeout; int error; DBUG_ASSERT(fixed == 1); timeout= args[0]->val_real(); /* On 64-bit OSX mysql_cond_timedwait() waits forever if passed abstime time has already been exceeded by the system time. When given a very short timeout (< 10 mcs) just return immediately. We assume that the lines between this test and the call to mysql_cond_timedwait() will be executed in less than 0.00001 sec. */ if (timeout < 0.00001) return 0; timed_cond.set_timeout((ulonglong) (timeout * 1000000000.0)); mysql_cond_init(key_item_func_sleep_cond, &cond, NULL); mysql_mutex_lock(&LOCK_user_locks); THD_STAGE_INFO(thd, stage_user_sleep); thd->mysys_var->current_mutex= &LOCK_user_locks; thd->mysys_var->current_cond= &cond; error= 0; thd_wait_begin(thd, THD_WAIT_SLEEP); while (!thd->killed) { error= timed_cond.wait(&cond, &LOCK_user_locks); if (error == ETIMEDOUT || error == ETIME) break; error= 0; } thd_wait_end(thd); mysql_mutex_unlock(&LOCK_user_locks); mysql_mutex_lock(&thd->mysys_var->mutex); thd->mysys_var->current_mutex= 0; thd->mysys_var->current_cond= 0; mysql_mutex_unlock(&thd->mysys_var->mutex); mysql_cond_destroy(&cond); return MY_TEST(!error); // Return 1 killed } static user_var_entry *get_variable(HASH *hash, const Name_string &name, bool create_if_not_exists) { user_var_entry *entry; if (!(entry = (user_var_entry*) my_hash_search(hash, (uchar*) name.ptr(), name.length())) && create_if_not_exists) { if (!my_hash_inited(hash)) return 0; if (!(entry= user_var_entry::create(name))) return 0; if (my_hash_insert(hash,(uchar*) entry)) { my_free(entry); return 0; } } return entry; } void Item_func_set_user_var::cleanup() { Item_func::cleanup(); entry= NULL; } bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists) { if (entry && thd->thread_id == entry_thread_id) goto end; // update entry->update_query_id for PS if (!(entry= get_variable(&thd->user_vars, name, create_if_not_exists))) { entry_thread_id= 0; return TRUE; } entry_thread_id= thd->thread_id; end: /* Remember the last query which updated it, this way a query can later know if this variable is a constant item in the query (it is if update_query_id is different from query_id). If this object has delayed setting of non-constness, we delay this until Item_func_set-user_var::save_item_result(). */ if (!delayed_non_constness) entry->update_query_id= thd->query_id; return FALSE; } /* When a user variable is updated (in a SET command or a query like SELECT @a:= ). */ bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref) { DBUG_ASSERT(fixed == 0); /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */ if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE)) return TRUE; /* As it is wrong and confusing to associate any character set with NULL, @a should be latin2 after this query sequence: SET @a=_latin2'string'; SET @a=NULL; I.e. the second query should not change the charset to the current default value, but should keep the original value assigned during the first query. In order to do it, we don't copy charset from the argument if the argument is NULL and the variable has previously been initialized. */ null_item= (args[0]->type() == NULL_ITEM); if (!entry->collation.collation || !null_item) entry->collation.set(args[0]->collation.derivation == DERIVATION_NUMERIC ? default_charset() : args[0]->collation.collation, DERIVATION_IMPLICIT); collation.set(entry->collation.collation, DERIVATION_IMPLICIT); cached_result_type= args[0]->result_type(); return FALSE; } void Item_func_set_user_var::fix_length_and_dec() { maybe_null=args[0]->maybe_null; decimals=args[0]->decimals; collation.set(DERIVATION_IMPLICIT); if (args[0]->collation.derivation == DERIVATION_NUMERIC) fix_length_and_charset(args[0]->max_char_length(), default_charset()); else { fix_length_and_charset(args[0]->max_char_length(), args[0]->collation.collation); } unsigned_flag= args[0]->unsigned_flag; } /* Mark field in read_map NOTES This is used by filesort to register used fields in a a temporary column read set or to register used fields in a view */ bool Item_func_set_user_var::register_field_in_read_map(uchar *arg) { if (result_field) { TABLE *table= (TABLE *) arg; if (result_field->table == table || !table) bitmap_set_bit(result_field->table->read_set, result_field->field_index); } return 0; } bool user_var_entry::realloc(uint length) { if (length <= extra_size) { /* Enough space to store value in value struct */ free_value(); m_ptr= internal_buffer_ptr(); } else { /* Allocate an external buffer */ if (m_length != length) { if (m_ptr == internal_buffer_ptr()) m_ptr= 0; if (!(m_ptr= (char*) my_realloc(m_ptr, length, MYF(MY_ALLOW_ZERO_PTR | MY_WME | ME_FATALERROR)))) return true; } } return false; } /** Set value to user variable. @param ptr pointer to buffer with new value @param length length of new value @param type type of new value @retval false on success @retval true on allocation error */ bool user_var_entry::store(void *from, uint length, Item_result type) { // Store strings with end \0 if (realloc(length + MY_TEST(type == STRING_RESULT))) return true; if (type == STRING_RESULT) m_ptr[length]= 0; // Store end \0 memmove(m_ptr, from, length); if (type == DECIMAL_RESULT) ((my_decimal*) m_ptr)->fix_buffer_pointer(); m_length= length; m_type= type; return false; } /** Set value to user variable. @param ptr pointer to buffer with new value @param length length of new value @param type type of new value @param cs charset info for new value @param dv derivation for new value @param unsigned_arg indiates if a value of type INT_RESULT is unsigned @note Sets error and fatal error if allocation fails. @retval false success @retval true failure */ bool user_var_entry::store(void *ptr, uint length, Item_result type, const CHARSET_INFO *cs, Derivation dv, bool unsigned_arg) { if (store(ptr, length, type)) return true; collation.set(cs, dv); unsigned_flag= unsigned_arg; return false; } bool Item_func_set_user_var::update_hash(void *ptr, uint length, Item_result res_type, const CHARSET_INFO *cs, Derivation dv, bool unsigned_arg) { /* If we set a variable explicitely to NULL then keep the old result type of the variable */ // args[0]->null_value could be outdated if (args[0]->type() == Item::FIELD_ITEM) null_value= ((Item_field*)args[0])->field->is_null(); else null_value= args[0]->null_value; if (null_value && null_item) res_type= entry->type(); // Don't change type of item if (null_value) entry->set_null_value(res_type); else if (entry->store(ptr, length, res_type, cs, dv, unsigned_arg)) { null_value= 1; return 1; } return 0; } /** Get the value of a variable as a double. */ double user_var_entry::val_real(my_bool *null_value) { if ((*null_value= (m_ptr == 0))) return 0.0; switch (m_type) { case REAL_RESULT: return *(double*) m_ptr; case INT_RESULT: return (double) *(longlong*) m_ptr; case DECIMAL_RESULT: { double result; my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, &result); return result; } case STRING_RESULT: return my_atof(m_ptr); // This is null terminated case ROW_RESULT: DBUG_ASSERT(1); // Impossible break; } return 0.0; // Impossible } /** Get the value of a variable as an integer. */ longlong user_var_entry::val_int(my_bool *null_value) const { if ((*null_value= (m_ptr == 0))) return LL(0); switch (m_type) { case REAL_RESULT: return (longlong) *(double*) m_ptr; case INT_RESULT: return *(longlong*) m_ptr; case DECIMAL_RESULT: { longlong result; my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, 0, &result); return result; } case STRING_RESULT: { int error; return my_strtoll10(m_ptr, (char**) 0, &error);// String is null terminated } case ROW_RESULT: DBUG_ASSERT(1); // Impossible break; } return LL(0); // Impossible } /** Get the value of a variable as a string. */ String *user_var_entry::val_str(my_bool *null_value, String *str, uint decimals) { if ((*null_value= (m_ptr == 0))) return (String*) 0; switch (m_type) { case REAL_RESULT: str->set_real(*(double*) m_ptr, decimals, collation.collation); break; case INT_RESULT: if (!unsigned_flag) str->set(*(longlong*) m_ptr, collation.collation); else str->set(*(ulonglong*) m_ptr, collation.collation); break; case DECIMAL_RESULT: str_set_decimal((my_decimal *) m_ptr, str, collation.collation); break; case STRING_RESULT: if (str->copy(m_ptr, m_length, collation.collation)) str= 0; // EOM error case ROW_RESULT: DBUG_ASSERT(1); // Impossible break; } return(str); } /** Get the value of a variable as a decimal. */ my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val) { if ((*null_value= (m_ptr == 0))) return 0; switch (m_type) { case REAL_RESULT: double2my_decimal(E_DEC_FATAL_ERROR, *(double*) m_ptr, val); break; case INT_RESULT: int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) m_ptr, 0, val); break; case DECIMAL_RESULT: my_decimal2decimal((my_decimal *) m_ptr, val); break; case STRING_RESULT: str2my_decimal(E_DEC_FATAL_ERROR, m_ptr, m_length, collation.collation, val); break; case ROW_RESULT: DBUG_ASSERT(1); // Impossible break; } return(val); } /** This functions is invoked on SET \@variable or \@variable:= expression. Evaluate (and check expression), store results. @note For now it always return OK. All problem with value evaluating will be caught by thd->is_error() check in sql_set_variables(). @retval FALSE OK. */ bool Item_func_set_user_var::check(bool use_result_field) { DBUG_ENTER("Item_func_set_user_var::check"); if (use_result_field && !result_field) use_result_field= FALSE; switch (cached_result_type) { case REAL_RESULT: { save_result.vreal= use_result_field ? result_field->val_real() : args[0]->val_real(); break; } case INT_RESULT: { save_result.vint= use_result_field ? result_field->val_int() : args[0]->val_int(); unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag: args[0]->unsigned_flag; break; } case STRING_RESULT: { save_result.vstr= use_result_field ? result_field->val_str(&value) : args[0]->val_str(&value); break; } case DECIMAL_RESULT: { save_result.vdec= use_result_field ? result_field->val_decimal(&decimal_buff) : args[0]->val_decimal(&decimal_buff); break; } case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); break; } DBUG_RETURN(FALSE); } /** @brief Evaluate and store item's result. This function is invoked on "SELECT ... INTO @var ...". @param item An item to get value from. */ void Item_func_set_user_var::save_item_result(Item *item) { DBUG_ENTER("Item_func_set_user_var::save_item_result"); switch (cached_result_type) { case REAL_RESULT: save_result.vreal= item->val_result(); break; case INT_RESULT: save_result.vint= item->val_int_result(); unsigned_flag= item->unsigned_flag; break; case STRING_RESULT: save_result.vstr= item->str_result(&value); break; case DECIMAL_RESULT: save_result.vdec= item->val_decimal_result(&decimal_buff); break; case ROW_RESULT: default: // Should never happen DBUG_ASSERT(0); break; } /* Set the ID of the query that last updated this variable. This is usually set by Item_func_set_user_var::set_entry(), but if this item has delayed setting of non-constness, we must do it now. */ if (delayed_non_constness) entry->update_query_id= current_thd->query_id; DBUG_VOID_RETURN; } /** This functions is invoked on SET \@variable or \@variable:= expression. @note We have to store the expression as such in the variable, independent of the value method used by the user @retval 0 OK @retval 1 EOM Error */ bool Item_func_set_user_var::update() { bool res= 0; DBUG_ENTER("Item_func_set_user_var::update"); switch (cached_result_type) { case REAL_RESULT: { res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal), REAL_RESULT, default_charset(), DERIVATION_IMPLICIT, 0); break; } case INT_RESULT: { res= update_hash((void*) &save_result.vint, sizeof(save_result.vint), INT_RESULT, default_charset(), DERIVATION_IMPLICIT, unsigned_flag); break; } case STRING_RESULT: { if (!save_result.vstr) // Null value res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, 0); else res= update_hash((void*) save_result.vstr->ptr(), save_result.vstr->length(), STRING_RESULT, save_result.vstr->charset(), DERIVATION_IMPLICIT, 0); break; } case DECIMAL_RESULT: { if (!save_result.vdec) // Null value res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, 0); else res= update_hash((void*) save_result.vdec, sizeof(my_decimal), DECIMAL_RESULT, default_charset(), DERIVATION_IMPLICIT, 0); break; } case ROW_RESULT: default: // This case should never be chosen DBUG_ASSERT(0); break; } DBUG_RETURN(res); } double Item_func_set_user_var::val_real() { DBUG_ASSERT(fixed == 1); check(0); update(); // Store expression return entry->val_real(&null_value); } longlong Item_func_set_user_var::val_int() { DBUG_ASSERT(fixed == 1); check(0); update(); // Store expression return entry->val_int(&null_value); } String *Item_func_set_user_var::val_str(String *str) { DBUG_ASSERT(fixed == 1); check(0); update(); // Store expression return entry->val_str(&null_value, str, decimals); } my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val) { DBUG_ASSERT(fixed == 1); check(0); update(); // Store expression return entry->val_decimal(&null_value, val); } double Item_func_set_user_var::val_result() { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return entry->val_real(&null_value); } longlong Item_func_set_user_var::val_int_result() { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return entry->val_int(&null_value); } bool Item_func_set_user_var::val_bool_result() { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return entry->val_int(&null_value) != 0; } String *Item_func_set_user_var::str_result(String *str) { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return entry->val_str(&null_value, str, decimals); } my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val) { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return entry->val_decimal(&null_value, val); } bool Item_func_set_user_var::is_null_result() { DBUG_ASSERT(fixed == 1); check(TRUE); update(); // Store expression return is_null(); } // just the assignment, for use in "SET @a:=5" type self-prints void Item_func_set_user_var::print_assignment(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("@")); str->append(name); str->append(STRING_WITH_LEN(":=")); args[0]->print(str, query_type); } // parenthesize assignment for use in "EXPLAIN EXTENDED SELECT (@e:=80)+5" void Item_func_set_user_var::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("(")); print_assignment(str, query_type); str->append(STRING_WITH_LEN(")")); } bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg) { if (result_field) { check(1); update(); return protocol->store(result_field); } return Item::send(protocol, str_arg); } void Item_func_set_user_var::make_field(Send_field *tmp_field) { if (result_field) { result_field->make_field(tmp_field); DBUG_ASSERT(tmp_field->table_name != 0); if (Item::item_name.is_set()) tmp_field->col_name=Item::item_name.ptr(); // Use user supplied name } else Item::make_field(tmp_field); } /* Save the value of a user variable into a field SYNOPSIS save_in_field() field target field to save the value to no_conversion flag indicating whether conversions are allowed DESCRIPTION Save the function value into a field and update the user variable accordingly. If a result field is defined and the target field doesn't coincide with it then the value from the result field will be used as the new value of the user variable. The reason to have this method rather than simply using the result field in the val_xxx() methods is that the value from the result field not always can be used when the result field is defined. Let's consider the following cases: 1) when filling a tmp table the result field is defined but the value of it is undefined because it has to be produced yet. Thus we can't use it. 2) on execution of an INSERT ... SELECT statement the save_in_field() function will be called to fill the data in the new record. If the SELECT part uses a tmp table then the result field is defined and should be used in order to get the correct result. The difference between the SET_USER_VAR function and regular functions like CONCAT is that the Item_func objects for the regular functions are replaced by Item_field objects after the values of these functions have been stored in a tmp table. Yet an object of the Item_field class cannot be used to update a user variable. Due to this we have to handle the result field in a special way here and in the Item_func_set_user_var::send() function. RETURN VALUES FALSE Ok TRUE Error */ type_conversion_status Item_func_set_user_var::save_in_field(Field *field, bool no_conversions, bool can_use_result_field) { bool use_result_field= (!can_use_result_field ? 0 : (result_field && result_field != field)); type_conversion_status error; /* Update the value of the user variable */ check(use_result_field); update(); if (result_type() == STRING_RESULT || (result_type() == REAL_RESULT && field->result_type() == STRING_RESULT)) { String *result; const CHARSET_INFO *cs= collation.collation; char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns str_value.set_quick(buff, sizeof(buff), cs); result= entry->val_str(&null_value, &str_value, decimals); if (null_value) { str_value.set_quick(0, 0, cs); return set_field_to_null_with_conversions(field, no_conversions); } /* NOTE: If null_value == FALSE, "result" must be not NULL. */ field->set_notnull(); error=field->store(result->ptr(),result->length(),cs); str_value.set_quick(0, 0, cs); } else if (result_type() == REAL_RESULT) { double nr= entry->val_real(&null_value); if (null_value) return set_field_to_null(field); field->set_notnull(); error=field->store(nr); } else if (result_type() == DECIMAL_RESULT) { my_decimal decimal_value; my_decimal *val= entry->val_decimal(&null_value, &decimal_value); if (null_value) return set_field_to_null(field); field->set_notnull(); error=field->store_decimal(val); } else { longlong nr= entry->val_int(&null_value); if (null_value) return set_field_to_null_with_conversions(field, no_conversions); field->set_notnull(); error=field->store(nr, unsigned_flag); } return error; } String * Item_func_get_user_var::val_str(String *str) { DBUG_ASSERT(fixed == 1); DBUG_ENTER("Item_func_get_user_var::val_str"); if (!var_entry) DBUG_RETURN((String*) 0); // No such variable DBUG_RETURN(var_entry->val_str(&null_value, str, decimals)); } double Item_func_get_user_var::val_real() { DBUG_ASSERT(fixed == 1); if (!var_entry) return 0.0; // No such variable return (var_entry->val_real(&null_value)); } my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec) { DBUG_ASSERT(fixed == 1); if (!var_entry) return 0; return var_entry->val_decimal(&null_value, dec); } longlong Item_func_get_user_var::val_int() { DBUG_ASSERT(fixed == 1); if (!var_entry) return LL(0); // No such variable return (var_entry->val_int(&null_value)); } /** Get variable by name and, if necessary, put the record of variable use into the binary log. When a user variable is invoked from an update query (INSERT, UPDATE etc), stores this variable and its value in thd->user_var_events, so that it can be written to the binlog (will be written just before the query is written, see log.cc). @param thd Current thread @param name Variable name @param[out] out_entry variable structure or NULL. The pointer is set regardless of whether function succeeded or not. @retval 0 OK @retval 1 Failed to put appropriate record into binary log */ static int get_var_with_binlog(THD *thd, enum_sql_command sql_command, Name_string &name, user_var_entry **out_entry) { BINLOG_USER_VAR_EVENT *user_var_event; user_var_entry *var_entry; var_entry= get_variable(&thd->user_vars, name, 0); /* Any reference to user-defined variable which is done from stored function or trigger affects their execution and the execution of the calling statement. We must log all such variables even if they are not involved in table-updating statements. */ if (!(opt_bin_log && (is_update_query(sql_command) || thd->in_sub_stmt))) { *out_entry= var_entry; return 0; } if (!var_entry) { /* If the variable does not exist, it's NULL, but we want to create it so that it gets into the binlog (if it didn't, the slave could be influenced by a variable of the same name previously set by another thread). We create it like if it had been explicitly set with SET before. The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'. sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION' in dispatch_command()). Instead of building a one-element list to pass to sql_set_variables(), we could instead manually call check() and update(); this would save memory and time; but calling sql_set_variables() makes one unique place to maintain (sql_set_variables()). Manipulation with lex is necessary since free_underlaid_joins is going to release memory belonging to the main query. */ List<set_var_base> tmp_var_list; LEX *sav_lex= thd->lex, lex_tmp; thd->lex= &lex_tmp; lex_start(thd); tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name, new Item_null(), false))); /* Create the variable */ if (sql_set_variables(thd, &tmp_var_list)) { thd->lex= sav_lex; goto err; } thd->lex= sav_lex; if (!(var_entry= get_variable(&thd->user_vars, name, 0))) goto err; } else if (var_entry->used_query_id == thd->query_id || mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id)) { /* If this variable was already stored in user_var_events by this query (because it's used in more than one place in the query), don't store it. */ *out_entry= var_entry; return 0; } uint size; /* First we need to store value of var_entry, when the next situation appears: > set @a:=1; > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1); We have to write to binlog value @a= 1. We allocate the user_var_event on user_var_events_alloc pool, not on the this-statement-execution pool because in SPs user_var_event objects may need to be valid after current [SP] statement execution pool is destroyed. */ size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length(); if (!(user_var_event= (BINLOG_USER_VAR_EVENT *) alloc_root(thd->user_var_events_alloc, size))) goto err; user_var_event->value= (char*) user_var_event + ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)); user_var_event->user_var_event= var_entry; user_var_event->type= var_entry->type(); user_var_event->charset_number= var_entry->collation.collation->number; user_var_event->unsigned_flag= var_entry->unsigned_flag; if (!var_entry->ptr()) { /* NULL value*/ user_var_event->length= 0; user_var_event->value= 0; } else { user_var_event->length= var_entry->length(); memcpy(user_var_event->value, var_entry->ptr(), var_entry->length()); } /* Mark that this variable has been used by this query */ var_entry->used_query_id= thd->query_id; if (insert_dynamic(&thd->user_var_events, &user_var_event)) goto err; *out_entry= var_entry; return 0; err: *out_entry= var_entry; return 1; } void Item_func_get_user_var::fix_length_and_dec() { THD *thd=current_thd; int error; maybe_null=1; decimals=NOT_FIXED_DEC; max_length=MAX_BLOB_WIDTH; error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry); /* If the variable didn't exist it has been created as a STRING-type. 'var_entry' is NULL only if there occured an error during the call to get_var_with_binlog. */ if (!error && var_entry) { m_cached_result_type= var_entry->type(); unsigned_flag= var_entry->unsigned_flag; max_length= var_entry->length(); collation.set(var_entry->collation); switch(m_cached_result_type) { case REAL_RESULT: fix_char_length(DBL_DIG + 8); break; case INT_RESULT: fix_char_length(MAX_BIGINT_WIDTH); decimals=0; break; case STRING_RESULT: max_length= MAX_BLOB_WIDTH - 1; break; case DECIMAL_RESULT: fix_char_length(DECIMAL_MAX_STR_LENGTH); decimals= DECIMAL_MAX_SCALE; break; case ROW_RESULT: // Keep compiler happy default: DBUG_ASSERT(0); break; } } else { collation.set(&my_charset_bin, DERIVATION_IMPLICIT); null_value= 1; m_cached_result_type= STRING_RESULT; max_length= MAX_BLOB_WIDTH; } } bool Item_func_get_user_var::const_item() const { return (!var_entry || current_thd->query_id != var_entry->update_query_id); } enum Item_result Item_func_get_user_var::result_type() const { return m_cached_result_type; } void Item_func_get_user_var::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("(@")); append_identifier(current_thd, str, name); str->append(')'); } bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const { /* Assume we don't have rtti */ if (this == item) return 1; // Same item is same. /* Check if other type is also a get_user_var() object */ if (item->type() != FUNC_ITEM || ((Item_func*) item)->functype() != functype()) return 0; Item_func_get_user_var *other=(Item_func_get_user_var*) item; return name.eq_bin(other->name); } bool Item_func_get_user_var::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it) { Item_func_set_user_var *suv= new Item_func_set_user_var(name, *it, false); /* Item_func_set_user_var is not fixed after construction, call fix_fields(). */ return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update()); } bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref) { DBUG_ASSERT(fixed == 0); DBUG_ASSERT(thd->lex->exchange); if (Item::fix_fields(thd, ref) || !(entry= get_variable(&thd->user_vars, name, 1))) return TRUE; entry->set_type(STRING_RESULT); /* Let us set the same collation which is used for loading of fields in LOAD DATA INFILE. (Since Item_user_var_as_out_param is used only there). */ entry->collation.set(thd->lex->exchange->cs ? thd->lex->exchange->cs : thd->variables.collation_database); entry->update_query_id= thd->query_id; return FALSE; } void Item_user_var_as_out_param::set_null_value(const CHARSET_INFO* cs) { entry->set_null_value(STRING_RESULT); } void Item_user_var_as_out_param::set_value(const char *str, uint length, const CHARSET_INFO* cs) { entry->store((void*) str, length, STRING_RESULT, cs, DERIVATION_IMPLICIT, 0 /* unsigned_arg */); } double Item_user_var_as_out_param::val_real() { DBUG_ASSERT(0); return 0.0; } longlong Item_user_var_as_out_param::val_int() { DBUG_ASSERT(0); return 0; } String* Item_user_var_as_out_param::val_str(String *str) { DBUG_ASSERT(0); return 0; } my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer) { DBUG_ASSERT(0); return 0; } void Item_user_var_as_out_param::print(String *str, enum_query_type query_type) { str->append('@'); append_identifier(current_thd, str, name); } Item_func_get_system_var:: Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg, LEX_STRING *component_arg, const char *name_arg, size_t name_len_arg) :var(var_arg), var_type(var_type_arg), orig_var_type(var_type_arg), component(*component_arg), cache_present(0) { /* copy() will allocate the name */ item_name.copy(name_arg, (uint) name_len_arg); } bool Item_func_get_system_var::is_written_to_binlog() { return var->is_written_to_binlog(var_type); } void Item_func_get_system_var::update_null_value() { THD *thd= current_thd; int save_no_errors= thd->no_errors; thd->no_errors= TRUE; Item::update_null_value(); thd->no_errors= save_no_errors; } void Item_func_get_system_var::fix_length_and_dec() { char *cptr; maybe_null= TRUE; max_length= 0; if (var->check_type(var_type)) { if (var_type != OPT_DEFAULT) { my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0), var->name.str, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL"); return; } /* As there was no local variable, return the global value */ var_type= OPT_GLOBAL; } switch (var->show_type()) { case SHOW_LONG: case SHOW_INT: case SHOW_HA_ROWS: case SHOW_LONGLONG: unsigned_flag= TRUE; collation.set_numeric(); fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS); decimals=0; break; case SHOW_SIGNED_LONG: unsigned_flag= FALSE; collation.set_numeric(); fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS); decimals=0; break; case SHOW_CHAR: case SHOW_CHAR_PTR: mysql_mutex_lock(&LOCK_global_system_variables); cptr= var->show_type() == SHOW_CHAR ? (char*) var->value_ptr(current_thd, var_type, &component) : *(char**) var->value_ptr(current_thd, var_type, &component); if (cptr) max_length= system_charset_info->cset->numchars(system_charset_info, cptr, cptr + strlen(cptr)); mysql_mutex_unlock(&LOCK_global_system_variables); collation.set(system_charset_info, DERIVATION_SYSCONST); max_length*= system_charset_info->mbmaxlen; decimals=NOT_FIXED_DEC; break; case SHOW_LEX_STRING: { mysql_mutex_lock(&LOCK_global_system_variables); LEX_STRING *ls= ((LEX_STRING*)var->value_ptr(current_thd, var_type, &component)); max_length= system_charset_info->cset->numchars(system_charset_info, ls->str, ls->str + ls->length); mysql_mutex_unlock(&LOCK_global_system_variables); collation.set(system_charset_info, DERIVATION_SYSCONST); max_length*= system_charset_info->mbmaxlen; decimals=NOT_FIXED_DEC; } break; case SHOW_BOOL: case SHOW_MY_BOOL: unsigned_flag= FALSE; collation.set_numeric(); fix_char_length(1); decimals=0; break; case SHOW_DOUBLE: unsigned_flag= FALSE; decimals= 6; collation.set_numeric(); fix_char_length(DBL_DIG + 6); break; default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); break; } } void Item_func_get_system_var::print(String *str, enum_query_type query_type) { str->append(item_name); } enum Item_result Item_func_get_system_var::result_type() const { switch (var->show_type()) { case SHOW_BOOL: case SHOW_MY_BOOL: case SHOW_INT: case SHOW_LONG: case SHOW_SIGNED_LONG: case SHOW_LONGLONG: case SHOW_HA_ROWS: return INT_RESULT; case SHOW_CHAR: case SHOW_CHAR_PTR: case SHOW_LEX_STRING: return STRING_RESULT; case SHOW_DOUBLE: return REAL_RESULT; default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); return STRING_RESULT; // keep the compiler happy } } enum_field_types Item_func_get_system_var::field_type() const { switch (var->show_type()) { case SHOW_BOOL: case SHOW_MY_BOOL: case SHOW_INT: case SHOW_LONG: case SHOW_SIGNED_LONG: case SHOW_LONGLONG: case SHOW_HA_ROWS: return MYSQL_TYPE_LONGLONG; case SHOW_CHAR: case SHOW_CHAR_PTR: case SHOW_LEX_STRING: return MYSQL_TYPE_VARCHAR; case SHOW_DOUBLE: return MYSQL_TYPE_DOUBLE; default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); return MYSQL_TYPE_VARCHAR; // keep the compiler happy } } /* Uses var, var_type, component, cache_present, used_query_id, thd, cached_llval, null_value, cached_null_value */ #define get_sys_var_safe(type) \ do { \ type value; \ mysql_mutex_lock(&LOCK_global_system_variables); \ value= *(type*) var->value_ptr(thd, var_type, &component); \ mysql_mutex_unlock(&LOCK_global_system_variables); \ cache_present |= GET_SYS_VAR_CACHE_LONG; \ used_query_id= thd->query_id; \ cached_llval= null_value ? 0 : (longlong) value; \ cached_null_value= null_value; \ return cached_llval; \ } while (0) longlong Item_func_get_system_var::val_int() { THD *thd= current_thd; if (cache_present && thd->query_id == used_query_id) { if (cache_present & GET_SYS_VAR_CACHE_LONG) { null_value= cached_null_value; return cached_llval; } else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) { null_value= cached_null_value; cached_llval= (longlong) cached_dval; cache_present|= GET_SYS_VAR_CACHE_LONG; return cached_llval; } else if (cache_present & GET_SYS_VAR_CACHE_STRING) { null_value= cached_null_value; if (!null_value) cached_llval= longlong_from_string_with_check (cached_strval.charset(), cached_strval.c_ptr(), cached_strval.c_ptr() + cached_strval.length()); else cached_llval= 0; cache_present|= GET_SYS_VAR_CACHE_LONG; return cached_llval; } } switch (var->show_type()) { case SHOW_INT: get_sys_var_safe (uint); case SHOW_LONG: get_sys_var_safe (ulong); case SHOW_SIGNED_LONG: get_sys_var_safe (long); case SHOW_LONGLONG: get_sys_var_safe (ulonglong); case SHOW_HA_ROWS: get_sys_var_safe (ha_rows); case SHOW_BOOL: get_sys_var_safe (bool); case SHOW_MY_BOOL: get_sys_var_safe (my_bool); case SHOW_DOUBLE: { double dval= val_real(); used_query_id= thd->query_id; cached_llval= (longlong) dval; cache_present|= GET_SYS_VAR_CACHE_LONG; return cached_llval; } case SHOW_CHAR: case SHOW_CHAR_PTR: case SHOW_LEX_STRING: { String *str_val= val_str(NULL); // Treat empty strings as NULL, like val_real() does. if (str_val && str_val->length()) cached_llval= longlong_from_string_with_check (system_charset_info, str_val->c_ptr(), str_val->c_ptr() + str_val->length()); else { null_value= TRUE; cached_llval= 0; } cache_present|= GET_SYS_VAR_CACHE_LONG; return cached_llval; } default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); return 0; // keep the compiler happy } } String* Item_func_get_system_var::val_str(String* str) { THD *thd= current_thd; if (cache_present && thd->query_id == used_query_id) { if (cache_present & GET_SYS_VAR_CACHE_STRING) { null_value= cached_null_value; return null_value ? NULL : &cached_strval; } else if (cache_present & GET_SYS_VAR_CACHE_LONG) { null_value= cached_null_value; if (!null_value) cached_strval.set (cached_llval, collation.collation); cache_present|= GET_SYS_VAR_CACHE_STRING; return null_value ? NULL : &cached_strval; } else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) { null_value= cached_null_value; if (!null_value) cached_strval.set_real (cached_dval, decimals, collation.collation); cache_present|= GET_SYS_VAR_CACHE_STRING; return null_value ? NULL : &cached_strval; } } str= &cached_strval; switch (var->show_type()) { case SHOW_CHAR: case SHOW_CHAR_PTR: case SHOW_LEX_STRING: { mysql_mutex_lock(&LOCK_global_system_variables); char *cptr= var->show_type() == SHOW_CHAR ? (char*) var->value_ptr(thd, var_type, &component) : *(char**) var->value_ptr(thd, var_type, &component); if (cptr) { size_t len= var->show_type() == SHOW_LEX_STRING ? ((LEX_STRING*)(var->value_ptr(thd, var_type, &component)))->length : strlen(cptr); if (str->copy(cptr, len, collation.collation)) { null_value= TRUE; str= NULL; } } else { null_value= TRUE; str= NULL; } mysql_mutex_unlock(&LOCK_global_system_variables); break; } case SHOW_INT: case SHOW_LONG: case SHOW_SIGNED_LONG: case SHOW_LONGLONG: case SHOW_HA_ROWS: case SHOW_BOOL: case SHOW_MY_BOOL: str->set (val_int(), collation.collation); break; case SHOW_DOUBLE: str->set_real (val_real(), decimals, collation.collation); break; default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); str= NULL; break; } cache_present|= GET_SYS_VAR_CACHE_STRING; used_query_id= thd->query_id; cached_null_value= null_value; return str; } double Item_func_get_system_var::val_real() { THD *thd= current_thd; if (cache_present && thd->query_id == used_query_id) { if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) { null_value= cached_null_value; return cached_dval; } else if (cache_present & GET_SYS_VAR_CACHE_LONG) { null_value= cached_null_value; cached_dval= (double)cached_llval; cache_present|= GET_SYS_VAR_CACHE_DOUBLE; return cached_dval; } else if (cache_present & GET_SYS_VAR_CACHE_STRING) { null_value= cached_null_value; if (!null_value) cached_dval= double_from_string_with_check (cached_strval.charset(), cached_strval.c_ptr(), cached_strval.c_ptr() + cached_strval.length()); else cached_dval= 0; cache_present|= GET_SYS_VAR_CACHE_DOUBLE; return cached_dval; } } switch (var->show_type()) { case SHOW_DOUBLE: mysql_mutex_lock(&LOCK_global_system_variables); cached_dval= *(double*) var->value_ptr(thd, var_type, &component); mysql_mutex_unlock(&LOCK_global_system_variables); used_query_id= thd->query_id; cached_null_value= null_value; if (null_value) cached_dval= 0; cache_present|= GET_SYS_VAR_CACHE_DOUBLE; return cached_dval; case SHOW_CHAR: case SHOW_LEX_STRING: case SHOW_CHAR_PTR: { mysql_mutex_lock(&LOCK_global_system_variables); char *cptr= var->show_type() == SHOW_CHAR ? (char*) var->value_ptr(thd, var_type, &component) : *(char**) var->value_ptr(thd, var_type, &component); // Treat empty strings as NULL, like val_int() does. if (cptr && *cptr) cached_dval= double_from_string_with_check (system_charset_info, cptr, cptr + strlen (cptr)); else { null_value= TRUE; cached_dval= 0; } mysql_mutex_unlock(&LOCK_global_system_variables); used_query_id= thd->query_id; cached_null_value= null_value; cache_present|= GET_SYS_VAR_CACHE_DOUBLE; return cached_dval; } case SHOW_INT: case SHOW_LONG: case SHOW_SIGNED_LONG: case SHOW_LONGLONG: case SHOW_HA_ROWS: case SHOW_BOOL: case SHOW_MY_BOOL: cached_dval= (double) val_int(); cache_present|= GET_SYS_VAR_CACHE_DOUBLE; used_query_id= thd->query_id; cached_null_value= null_value; return cached_dval; default: my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str); return 0; } } bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const { /* Assume we don't have rtti */ if (this == item) return 1; // Same item is same. /* Check if other type is also a get_user_var() object */ if (item->type() != FUNC_ITEM || ((Item_func*) item)->functype() != functype()) return 0; Item_func_get_system_var *other=(Item_func_get_system_var*) item; return (var == other->var && var_type == other->var_type); } void Item_func_get_system_var::cleanup() { Item_func::cleanup(); cache_present= 0; var_type= orig_var_type; cached_strval.free(); } void Item_func_match::init_search(bool no_order) { DBUG_ENTER("Item_func_match::init_search"); /* We will skip execution if the item is not fixed with fix_field */ if (!fixed) DBUG_VOID_RETURN; /* Check if init_search() has been called before */ if (ft_handler) { /* We should reset ft_handler as it is cleaned up on destruction of FT_SELECT object (necessary in case of re-execution of subquery). TODO: FT_SELECT should not clean up ft_handler. */ if (join_key) table->file->ft_handler= ft_handler; DBUG_VOID_RETURN; } if (key == NO_SUCH_KEY) { List<Item> fields; fields.push_back(new Item_string(" ",1, cmp_collation.collation)); for (uint i=1; i < arg_count; i++) fields.push_back(args[i]); concat_ws=new Item_func_concat_ws(fields); /* Above function used only to get value and do not need fix_fields for it: Item_string - basic constant fields - fix_fields() was already called for this arguments Item_func_concat_ws - do not need fix_fields() to produce value */ concat_ws->quick_fix_field(); } if (master) { join_key=master->join_key=join_key|master->join_key; master->init_search(no_order); ft_handler=master->ft_handler; join_key=master->join_key; DBUG_VOID_RETURN; } String *ft_tmp= 0; // MATCH ... AGAINST (NULL) is meaningless, but possible if (!(ft_tmp=key_item()->val_str(&value))) { ft_tmp= &value; value.set("",0,cmp_collation.collation); } if (ft_tmp->charset() != cmp_collation.collation) { uint dummy_errors; search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(), cmp_collation.collation, &dummy_errors); ft_tmp= &search_value; } if (join_key && !no_order) flags|=FT_SORTED; ft_handler=table->file->ft_init_ext(flags, key, ft_tmp); if (join_key) table->file->ft_handler=ft_handler; DBUG_VOID_RETURN; } bool Item_func_match::fix_fields(THD *thd, Item **ref) { DBUG_ASSERT(fixed == 0); Item *UNINIT_VAR(item); // Safe as arg_count is > 1 maybe_null=1; join_key=0; /* const_item is assumed in quite a bit of places, so it would be difficult to remove; If it would ever to be removed, this should include modifications to find_best and auto_close as complement to auto_init code above. */ if (Item_func::fix_fields(thd, ref) || !args[0]->const_during_execution()) { my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST"); return TRUE; } bool allows_multi_table_search= true; const_item_cache=0; for (uint i=1 ; i < arg_count ; i++) { item=args[i]; if (item->type() == Item::REF_ITEM) args[i]= item= *((Item_ref *)item)->ref; if (item->type() != Item::FIELD_ITEM) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "AGAINST"); return TRUE; } allows_multi_table_search &= allows_search_on_non_indexed_columns(((Item_field *)item)->field->table); } /* Check that all columns come from the same table. We've already checked that columns in MATCH are fields so PARAM_TABLE_BIT can only appear from AGAINST argument. */ if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables()) key=NO_SUCH_KEY; if (key == NO_SUCH_KEY && !allows_multi_table_search) { my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH"); return TRUE; } table=((Item_field *)item)->field->table; if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT)) { my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0)); return 1; } table->fulltext_searched=1; return agg_item_collations_for_comparison(cmp_collation, func_name(), args+1, arg_count-1, 0); } bool Item_func_match::fix_index() { Item_field *item; uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr; uint max_cnt=0, mkeys=0, i; /* We will skip execution if the item is not fixed with fix_field */ if (!fixed) return false; if (key == NO_SUCH_KEY) return 0; if (!table) goto err; for (keynr=0 ; keynr < table->s->keys ; keynr++) { if ((table->key_info[keynr].flags & HA_FULLTEXT) && (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) : table->s->keys_in_use.is_set(keynr))) { ft_to_key[fts]=keynr; ft_cnt[fts]=0; fts++; } } if (!fts) goto err; for (i=1; i < arg_count; i++) { item=(Item_field*)args[i]; for (keynr=0 ; keynr < fts ; keynr++) { KEY *ft_key=&table->key_info[ft_to_key[keynr]]; uint key_parts=ft_key->user_defined_key_parts; for (uint part=0 ; part < key_parts ; part++) { if (item->field->eq(ft_key->key_part[part].field)) ft_cnt[keynr]++; } } } for (keynr=0 ; keynr < fts ; keynr++) { if (ft_cnt[keynr] > max_cnt) { mkeys=0; max_cnt=ft_cnt[mkeys]=ft_cnt[keynr]; ft_to_key[mkeys]=ft_to_key[keynr]; continue; } if (max_cnt && ft_cnt[keynr] == max_cnt) { mkeys++; ft_cnt[mkeys]=ft_cnt[keynr]; ft_to_key[mkeys]=ft_to_key[keynr]; continue; } } for (keynr=0 ; keynr <= mkeys ; keynr++) { // partial keys doesn't work if (max_cnt < arg_count-1 || max_cnt < table->key_info[ft_to_key[keynr]].user_defined_key_parts) continue; key=ft_to_key[keynr]; return 0; } err: if (allows_search_on_non_indexed_columns(table)) { key=NO_SUCH_KEY; return 0; } my_message(ER_FT_MATCHING_KEY_NOT_FOUND, ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0)); return 1; } bool Item_func_match::eq(const Item *item, bool binary_cmp) const { /* We ignore FT_SORTED flag when checking for equality since result is equvialent regardless of sorting */ if (item->type() != FUNC_ITEM || ((Item_func*)item)->functype() != FT_FUNC || (flags | FT_SORTED) != (((Item_func_match*)item)->flags | FT_SORTED)) return 0; Item_func_match *ifm=(Item_func_match*) item; if (key == ifm->key && table == ifm->table && key_item()->eq(ifm->key_item(), binary_cmp)) return 1; return 0; } double Item_func_match::val_real() { DBUG_ASSERT(fixed == 1); DBUG_ENTER("Item_func_match::val"); if (ft_handler == NULL) DBUG_RETURN(-1.0); if (key != NO_SUCH_KEY && table->null_row) /* NULL row from an outer join */ DBUG_RETURN(0.0); if (join_key) { if (table->file->ft_handler) DBUG_RETURN(ft_handler->please->get_relevance(ft_handler)); join_key=0; } if (key == NO_SUCH_KEY) { String *a= concat_ws->val_str(&value); if ((null_value= (a == 0)) || !a->length()) DBUG_RETURN(0); DBUG_RETURN(ft_handler->please->find_relevance(ft_handler, (uchar *)a->ptr(), a->length())); } DBUG_RETURN(ft_handler->please->find_relevance(ft_handler, table->record[0], 0)); } void Item_func_match::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("(match ")); print_args(str, 1, query_type); str->append(STRING_WITH_LEN(" against (")); args[0]->print(str, query_type); if (flags & FT_BOOL) str->append(STRING_WITH_LEN(" in boolean mode")); else if (flags & FT_EXPAND) str->append(STRING_WITH_LEN(" with query expansion")); str->append(STRING_WITH_LEN("))")); } longlong Item_func_bit_xor::val_int() { DBUG_ASSERT(fixed == 1); ulonglong arg1= (ulonglong) args[0]->val_int(); ulonglong arg2= (ulonglong) args[1]->val_int(); if ((null_value= (args[0]->null_value || args[1]->null_value))) return 0; return (longlong) (arg1 ^ arg2); } /*************************************************************************** System variables ****************************************************************************/ /** Return value of an system variable base[.name] as a constant item. @param thd Thread handler @param var_type global / session @param name Name of base or system variable @param component Component. @note If component.str = 0 then the variable name is in 'name' @return - 0 : error - # : constant item */ Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name, LEX_STRING component) { sys_var *var; LEX_STRING *base_name, *component_name; if (component.str) { base_name= &component; component_name= &name; } else { base_name= &name; component_name= &component; // Empty string } if (!(var= find_sys_var(thd, base_name->str, base_name->length))) return 0; if (component.str) { if (!var->is_struct()) { my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str); return 0; } } thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT); set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH); var->do_deprecated_warning(thd); return new Item_func_get_system_var(var, var_type, component_name, NULL, 0); } /** Check a user level lock. Sets null_value=TRUE on error. @retval 1 Available @retval 0 Already taken, or error */ longlong Item_func_is_free_lock::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); User_level_lock *ull; null_value=0; if (!res || !res->length()) { null_value=1; return 0; } mysql_mutex_lock(&LOCK_user_locks); ull= (User_level_lock *) my_hash_search(&hash_user_locks, (uchar*) res->ptr(), (size_t) res->length()); mysql_mutex_unlock(&LOCK_user_locks); if (!ull || !ull->locked) return 1; return 0; } longlong Item_func_is_used_lock::val_int() { DBUG_ASSERT(fixed == 1); String *res=args[0]->val_str(&value); User_level_lock *ull; null_value=1; if (!res || !res->length()) return 0; mysql_mutex_lock(&LOCK_user_locks); ull= (User_level_lock *) my_hash_search(&hash_user_locks, (uchar*) res->ptr(), (size_t) res->length()); mysql_mutex_unlock(&LOCK_user_locks); if (!ull || !ull->locked) return 0; null_value=0; return ull->thread_id; } longlong Item_func_row_count::val_int() { DBUG_ASSERT(fixed == 1); THD *thd= current_thd; return thd->get_row_count_func(); } Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name) :Item_func(), context(context_arg), m_name(name), m_sp(NULL), sp_result_field(NULL) { maybe_null= 1; m_name->init_qname(current_thd); dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); dummy_table->s= (TABLE_SHARE*) (dummy_table+1); with_stored_program= true; } Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name, List<Item> &list) :Item_func(list), context(context_arg), m_name(name), m_sp(NULL),sp_result_field(NULL) { maybe_null= 1; m_name->init_qname(current_thd); dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); dummy_table->s= (TABLE_SHARE*) (dummy_table+1); with_stored_program= true; } void Item_func_sp::cleanup() { if (sp_result_field) { delete sp_result_field; sp_result_field= NULL; } m_sp= NULL; dummy_table->alias= NULL; Item_func::cleanup(); tables_locked_cache= false; with_stored_program= true; } const char * Item_func_sp::func_name() const { THD *thd= current_thd; /* Calculate length to avoid reallocation of string for sure */ uint len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) + m_name->m_name.length)*2 + //characters*quoting 2 + // ` and ` (m_name->m_explicit_name ? 3 : 0) + // '`', '`' and '.' for the db 1 + // end of string ALIGN_SIZE(1)); // to avoid String reallocation String qname((char *)alloc_root(thd->mem_root, len), len, system_charset_info); qname.length(0); if (m_name->m_explicit_name) { append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length); qname.append('.'); } append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length); return qname.ptr(); } table_map Item_func_sp::get_initial_pseudo_tables() const { return m_sp->m_chistics->detistic ? 0 : RAND_TABLE_BIT; } void my_missing_function_error(const LEX_STRING &token, const char *func_name) { if (token.length && is_lex_native_function (&token)) my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name); else my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name); } /** @brief Initialize the result field by creating a temporary dummy table and assign it to a newly created field object. Meta data used to create the field is fetched from the sp_head belonging to the stored proceedure found in the stored procedure functon cache. @note This function should be called from fix_fields to init the result field. It is some what related to Item_field. @see Item_field @param thd A pointer to the session and thread context. @return Function return error status. @retval TRUE is returned on an error @retval FALSE is returned on success. */ bool Item_func_sp::init_result_field(THD *thd) { LEX_STRING empty_name= { C_STRING_WITH_LEN("") }; TABLE_SHARE *share; DBUG_ENTER("Item_func_sp::init_result_field"); DBUG_ASSERT(m_sp == NULL); DBUG_ASSERT(sp_result_field == NULL); if (!(m_sp= sp_find_routine(thd, SP_TYPE_FUNCTION, m_name, &thd->sp_func_cache, TRUE))) { my_missing_function_error (m_name->m_name, m_name->m_qname.str); context->process_error(thd); DBUG_RETURN(TRUE); } /* A Field need to be attached to a Table. Below we "create" a dummy table by initializing the needed pointers. */ share= dummy_table->s; dummy_table->alias = ""; dummy_table->maybe_null = maybe_null; dummy_table->in_use= thd; dummy_table->copy_blobs= TRUE; share->table_cache_key = empty_name; share->table_name = empty_name; if (!(sp_result_field= m_sp->create_result_field(max_length, item_name.ptr(), dummy_table))) { DBUG_RETURN(TRUE); } if (sp_result_field->pack_length() > sizeof(result_buf)) { void *tmp; if (!(tmp= sql_alloc(sp_result_field->pack_length()))) DBUG_RETURN(TRUE); sp_result_field->move_field((uchar*) tmp); } else sp_result_field->move_field(result_buf); sp_result_field->set_null_ptr((uchar *) &null_value, 1); DBUG_RETURN(FALSE); } /** @brief Initialize local members with values from the Field interface. @note called from Item::fix_fields. */ void Item_func_sp::fix_length_and_dec() { DBUG_ENTER("Item_func_sp::fix_length_and_dec"); DBUG_ASSERT(sp_result_field); decimals= sp_result_field->decimals(); max_length= sp_result_field->field_length; collation.set(sp_result_field->charset()); maybe_null= 1; unsigned_flag= MY_TEST(sp_result_field->flags & UNSIGNED_FLAG); DBUG_VOID_RETURN; } void Item_func_sp::update_null_value() { /* This method is called when we try to check if the item value is NULL. We call Item_func_sp::execute() to get value of null_value attribute as a side effect of its execution. We ignore any error since update_null_value() doesn't return value. We used to delegate nullability check to Item::update_null_value as a result of a chain of function calls: Item_func_isnull::val_int --> Item_func::is_null --> Item::update_null_value -->Item_func_sp::val_int --> Field_varstring::val_int Such approach resulted in a call of push_warning_printf() in case if a stored program value couldn't be cast to integer (the case when for example there was a stored function that declared as returning varchar(1) and a function's implementation returned "Y" from its body). */ execute(); } /** @brief Execute function & store value in field. @return Function returns error status. @retval FALSE on success. @retval TRUE if an error occurred. */ bool Item_func_sp::execute() { THD *thd= current_thd; /* Execute function and store the return value in the field. */ if (execute_impl(thd)) { null_value= 1; context->process_error(thd); if (thd->killed) thd->send_kill_message(); return TRUE; } /* Check that the field (the value) is not NULL. */ null_value= sp_result_field->is_null(); return null_value; } /** @brief Execute function and store the return value in the field. @note This function was intended to be the concrete implementation of the interface function execute. This was never realized. @return The error state. @retval FALSE on success @retval TRUE if an error occurred. */ bool Item_func_sp::execute_impl(THD *thd) { bool err_status= TRUE; Sub_statement_state statement_state; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_security_ctx= thd->security_ctx; #endif enum enum_sp_data_access access= (m_sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ? SP_DEFAULT_ACCESS_MAPPING : m_sp->m_chistics->daccess; DBUG_ENTER("Item_func_sp::execute_impl"); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (context->security_ctx) { /* Set view definer security context */ thd->security_ctx= context->security_ctx; } #endif if (sp_check_access(thd)) goto error; /* Throw an error if a non-deterministic function is called while statement-based replication (SBR) is active. */ if (!m_sp->m_chistics->detistic && !trust_function_creators && (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) && (mysql_bin_log.is_open() && thd->variables.binlog_format == BINLOG_FORMAT_STMT)) { my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0)); goto error; } /* Disable the binlogging if this is not a SELECT statement. If this is a SELECT, leave binlogging on, so execute_function() code writes the function call into binlog. */ thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION); err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field); thd->restore_sub_statement_state(&statement_state); error: #ifndef NO_EMBEDDED_ACCESS_CHECKS thd->security_ctx= save_security_ctx; #endif DBUG_RETURN(err_status); } void Item_func_sp::make_field(Send_field *tmp_field) { DBUG_ENTER("Item_func_sp::make_field"); DBUG_ASSERT(sp_result_field); sp_result_field->make_field(tmp_field); if (item_name.is_set()) tmp_field->col_name= item_name.ptr(); DBUG_VOID_RETURN; } enum enum_field_types Item_func_sp::field_type() const { DBUG_ENTER("Item_func_sp::field_type"); DBUG_ASSERT(sp_result_field); DBUG_RETURN(sp_result_field->type()); } Item_result Item_func_sp::result_type() const { DBUG_ENTER("Item_func_sp::result_type"); DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp)); DBUG_ASSERT(sp_result_field); DBUG_RETURN(sp_result_field->result_type()); } longlong Item_func_found_rows::val_int() { DBUG_ASSERT(fixed == 1); return current_thd->found_rows(); } Field * Item_func_sp::tmp_table_field(TABLE *t_arg) { DBUG_ENTER("Item_func_sp::tmp_table_field"); DBUG_ASSERT(sp_result_field); DBUG_RETURN(sp_result_field); } /** @brief Checks if requested access to function can be granted to user. If function isn't found yet, it searches function first. If function can't be found or user don't have requested access error is raised. @param thd thread handler @return Indication if the access was granted or not. @retval FALSE Access is granted. @retval TRUE Requested access can't be granted or function doesn't exists. */ bool Item_func_sp::sp_check_access(THD *thd) { DBUG_ENTER("Item_func_sp::sp_check_access"); DBUG_ASSERT(m_sp); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (check_routine_access(thd, EXECUTE_ACL, m_sp->m_db.str, m_sp->m_name.str, 0, FALSE)) DBUG_RETURN(TRUE); #endif DBUG_RETURN(FALSE); } bool Item_func_sp::fix_fields(THD *thd, Item **ref) { bool res; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_security_ctx= thd->security_ctx; #endif DBUG_ENTER("Item_func_sp::fix_fields"); DBUG_ASSERT(fixed == 0); #ifndef NO_EMBEDDED_ACCESS_CHECKS /* Checking privileges to execute the function while creating view and executing the function of select. */ if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) || (thd->lex->sql_command == SQLCOM_CREATE_VIEW)) { if (context->security_ctx) { /* Set view definer security context */ thd->security_ctx= context->security_ctx; } /* Check whether user has execute privilege or not */ res= check_routine_access(thd, EXECUTE_ACL, m_name->m_db.str, m_name->m_name.str, 0, FALSE); thd->security_ctx= save_security_ctx; if (res) { context->process_error(thd); DBUG_RETURN(res); } } #endif /* We must call init_result_field before Item_func::fix_fields() to make m_sp and result_field members available to fix_length_and_dec(), which is called from Item_func::fix_fields(). */ res= init_result_field(thd); if (res) DBUG_RETURN(res); res= Item_func::fix_fields(thd, ref); /* These is reset/set by Item_func::fix_fields. */ with_stored_program= true; if (!m_sp->m_chistics->detistic || !tables_locked_cache) const_item_cache= false; if (res) DBUG_RETURN(res); if (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) { /* Here we check privileges of the stored routine only during view creation, in order to validate the view. A runtime check is perfomed in Item_func_sp::execute(), and this method is not called during context analysis. Notice, that during view creation we do not infer into stored routine bodies and do not check privileges of its statements, which would probably be a good idea especially if the view has SQL SECURITY DEFINER and the used stored procedure has SQL SECURITY DEFINER. */ res= sp_check_access(thd); #ifndef NO_EMBEDDED_ACCESS_CHECKS /* Try to set and restore the security context to see whether it's valid */ Security_context *save_secutiry_ctx; res= m_sp->set_security_ctx(thd, &save_secutiry_ctx); if (!res) m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx); #endif /* ! NO_EMBEDDED_ACCESS_CHECKS */ } DBUG_RETURN(res); } void Item_func_sp::update_used_tables() { Item_func::update_used_tables(); if (!m_sp->m_chistics->detistic) const_item_cache= false; /* This is reset by Item_func::update_used_tables(). */ with_stored_program= true; } /* uuid_short handling. The short uuid is defined as a longlong that contains the following bytes: Bytes Comment 1 Server_id & 255 4 Startup time of server in seconds 3 Incrementor This means that an uuid is guaranteed to be unique even in a replication environment if the following holds: - The last byte of the server id is unique - If you between two shutdown of the server don't get more than an average of 2^24 = 16M calls to uuid_short() per second. */ ulonglong uuid_value; void uuid_short_init() { uuid_value= ((((ulonglong) server_id) << 56) + (((ulonglong) server_start_time) << 24)); } longlong Item_func_uuid_short::val_int() { ulonglong val; mysql_mutex_lock(&LOCK_uuid_generator); val= uuid_value++; mysql_mutex_unlock(&LOCK_uuid_generator); return (longlong) val; }
sachintaware/webscalesql-5.6
sql/item_func.cc
C++
gpl-2.0
183,480
#!/usr/bin/env python2.7 import os import sys this_dir = os.path.dirname(os.path.abspath(__file__)) trunk_dir = os.path.split(this_dir)[0] sys.path.insert(0,trunk_dir) from ikol.dbregister import DataBase from ikol import var if os.path.exists(var.DB_PATH): os.remove(var.DB_PATH) DB = DataBase(var.DB_PATH) DB.insertPlaylist("loLWOCl7nlk","test") DB.insertPlaylist("loLWO357nlk","testb") DB.insertVideo("KDk2341oEQQ","loLWOCl7nlk","test") DB.insertVideo("KDktIWeoE23","loLWOCl7nlk","testb") print DB.getAllVideosByPlaylist("loLWOCl7nlk") print DB.getVideoById("KDk2341oEQQ")
lokiteitor/ikol
test/DBtest.py
Python
gpl-2.0
589
<?php /** * File containing the basket_cleanup.php cronjob * * @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2013.5 * @package kernel */ $ini = eZINI::instance(); // Check if this should be run in a cronjob $useCronjob = $ini->variable( 'Session', 'BasketCleanup' ) == 'cronjob'; if ( !$useCronjob ) return; // Only do basket cleanup once in a while $freq = $ini->variable( 'Session', 'BasketCleanupAverageFrequency' ); if ( mt_rand( 1, max( $freq, 1 ) ) != 1 ) return; $maxTime = $ini->variable( 'Session', 'BasketCleanupTime' ); $idleTime = $ini->variable( 'Session', 'BasketCleanupIdleTime' ); $fetchLimit = $ini->variable( 'Session', 'BasketCleanupFetchLimit' ); $cli->output( "Cleaning up expired baskets" ); eZDBGarbageCollector::collectBaskets( $maxTime, $idleTime, $fetchLimit ); ?>
alafon/ezpublish-community-built
ezpublish_legacy/cronjobs/basket_cleanup.php
PHP
gpl-2.0
930
/* Copyright (C) 2005 Kimmo Pekkola This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <windows.h> #include <string> #include <vector> #include <time.h> #include <shlwapi.h> #include <random> #include "../API/RainmeterAPI.h" #include "../../Common/StringUtil.h" #define BUFFER_SIZE 4096 template <typename T> T GetRandomNumber(T size) { static std::mt19937 s_Engine((unsigned)time(nullptr)); const std::uniform_int_distribution<T> distribution(0, size); return distribution(s_Engine); } struct MeasureData { std::wstring pathname; std::wstring separator; std::vector<std::wstring> files; std::wstring value; }; void ScanFolder(std::vector<std::wstring>& files, std::vector<std::wstring>& filters, bool bSubfolders, const std::wstring& path) { // Get folder listing WIN32_FIND_DATA fileData; // Data structure describes the file found HANDLE hSearch; // Search handle returned by FindFirstFile std::wstring searchPath = path + L"*"; hSearch = FindFirstFile(searchPath.c_str(), &fileData); if (hSearch == INVALID_HANDLE_VALUE) return; // No more files found do { if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (bSubfolders && wcscmp(fileData.cFileName, L".") != 0 && wcscmp(fileData.cFileName, L"..") != 0) { ScanFolder(files, filters, bSubfolders, path + fileData.cFileName + L"\\"); } } else { if (!filters.empty()) { for (size_t i = 0; i < filters.size(); ++i) { if (!filters[i].empty() && PathMatchSpec(fileData.cFileName, filters[i].c_str())) { files.push_back(path + fileData.cFileName); break; } } } else { files.push_back(path + fileData.cFileName); } } } while (FindNextFile(hSearch, &fileData)); FindClose(hSearch); } PLUGIN_EXPORT void Initialize(void** data, void* rm) { MeasureData* measure = new MeasureData; *data = measure; } PLUGIN_EXPORT void Reload(void* data, void* rm, double* maxValue) { MeasureData* measure = (MeasureData*)data; measure->pathname = RmReadPath(rm, L"PathName", L""); if (PathIsDirectory(measure->pathname.c_str())) { std::vector<std::wstring> fileFilters; LPCWSTR filter = RmReadString(rm, L"FileFilter", L""); if (*filter) { std::wstring ext = filter; size_t start = 0; size_t pos = ext.find(L';'); while (pos != std::wstring::npos) { fileFilters.push_back(ext.substr(start, pos - start)); start = pos + 1; pos = ext.find(L';', pos + 1); } fileFilters.push_back(ext.substr(start)); } if (measure->pathname[measure->pathname.size() - 1] != L'\\') { measure->pathname += L"\\"; } // Scan files measure->files.clear(); bool bSubfolders = RmReadInt(rm, L"Subfolders", 1) == 1; ScanFolder(measure->files, fileFilters, bSubfolders, measure->pathname); } else { measure->separator = RmReadString(rm, L"Separator", L"\n"); } } PLUGIN_EXPORT double Update(void* data) { MeasureData* measure = (MeasureData*)data; if (measure->files.empty()) { BYTE buffer[BUFFER_SIZE + 2]; buffer[BUFFER_SIZE] = 0; // Read the file FILE* file = _wfopen(measure->pathname.c_str(), L"r"); if (file) { // Check if the file is unicode or ascii fread(buffer, sizeof(WCHAR), 1, file); fseek(file, 0, SEEK_END); long size = ftell(file); if (size > 0) { // Go to a random place long pos = GetRandomNumber(size); fseek(file, (pos / 2) * 2, SEEK_SET); measure->value.clear(); if (0xFEFF == *(WCHAR*)buffer) { // It's unicode WCHAR* wBuffer = (WCHAR*)buffer; // Read until we find the first separator WCHAR* sepPos1 = nullptr; WCHAR* sepPos2 = nullptr; do { size_t len = fread(buffer, sizeof(BYTE), BUFFER_SIZE, file); buffer[len] = 0; buffer[len + 1] = 0; sepPos1 = wcsstr(wBuffer, measure->separator.c_str()); if (sepPos1 == nullptr) { // The separator wasn't found if (feof(file)) { // End of file reached -> read from start fseek(file, 2, SEEK_SET); len = fread(buffer, sizeof(BYTE), BUFFER_SIZE, file); buffer[len] = 0; buffer[len + 1] = 0; sepPos1 = wBuffer; } // else continue reading } else { sepPos1 += measure->separator.size(); } } while (sepPos1 == nullptr); // Find the second separator do { sepPos2 = wcsstr(sepPos1, measure->separator.c_str()); if (sepPos2 == nullptr) { // The separator wasn't found if (feof(file)) { // End of file reached -> read the rest measure->value += sepPos1; break; } else { measure->value += sepPos1; // else continue reading size_t len = fread(buffer, sizeof(BYTE), BUFFER_SIZE, file); buffer[len] = 0; buffer[len + 1] = 0; sepPos1 = wBuffer; } } else { if (sepPos2) { *sepPos2 = 0; } // Read until we find the second separator measure->value += sepPos1; } } while (sepPos2 == nullptr); } else { // It's ascii char* aBuffer = (char*)buffer; const std::string separator = StringUtil::Narrow(measure->separator); const char* separatorSz = separator.c_str(); // Read until we find the first separator char* sepPos1 = nullptr; char* sepPos2 = nullptr; do { size_t len = fread(buffer, sizeof(char), BUFFER_SIZE, file); aBuffer[len] = 0; sepPos1 = strstr(aBuffer, separatorSz); if (sepPos1 == nullptr) { // The separator wasn't found if (feof(file)) { // End of file reached -> read from start fseek(file, 0, SEEK_SET); len = fread(buffer, sizeof(char), BUFFER_SIZE, file); aBuffer[len] = 0; sepPos1 = aBuffer; } // else continue reading } else { sepPos1 += separator.size(); } } while (sepPos1 == nullptr); // Find the second separator do { sepPos2 = strstr(sepPos1, separatorSz); if (sepPos2 == nullptr) { // The separator wasn't found if (feof(file)) { // End of file reached -> read the rest measure->value += StringUtil::Widen(sepPos1); break; } else { measure->value += StringUtil::Widen(sepPos1); // else continue reading size_t len = fread(buffer, sizeof(char), BUFFER_SIZE, file); aBuffer[len] = 0; sepPos1 = aBuffer; } } else { if (sepPos2) { *sepPos2 = 0; } // Read until we find the second separator measure->value += StringUtil::Widen(sepPos1); } } while (sepPos2 == nullptr); } } fclose(file); } } else { // Select the filename measure->value = measure->files[GetRandomNumber(measure->files.size() - 1)]; } return 0; } PLUGIN_EXPORT LPCWSTR GetString(void* data) { MeasureData* measure = (MeasureData*)data; return measure->value.c_str(); } PLUGIN_EXPORT void Finalize(void* data) { MeasureData* measure = (MeasureData*)data; delete measure; }
pyq881120/rainmeter
Plugins/PluginQuote/Quote.cpp
C++
gpl-2.0
8,297
/**************************************************************************** ** Meta object code from reading C++ file 'ColorController.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Source Files/Application/Color/ColorController.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ColorController.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ColorController_t { QByteArrayData data[1]; char stringdata0[16]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ColorController_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ColorController_t qt_meta_stringdata_ColorController = { { QT_MOC_LITERAL(0, 0, 15) // "ColorController" }, "ColorController" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ColorController[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void ColorController::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject ColorController::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_ColorController.data, qt_meta_data_ColorController, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ColorController::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ColorController::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ColorController.stringdata0)) return static_cast<void*>(const_cast< ColorController*>(this)); return QObject::qt_metacast(_clname); } int ColorController::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
FlorianPO/SpriteEditor
SQT/GeneratedFiles/Release/moc_ColorController.cpp
C++
gpl-2.0
2,743
//unit GR32_RepaintOpt; #include "stdafx.h" #include "GR32_RepaintOpt.h" void InflateArea(var Area: TRect; Dx, Dy: Integer); { if Area.Left > Area.Right then Dx := -Dx; if Area.Top > Area.Bottom then Dy := -Dy; Dec(Area.Left, Dx); Dec(Area.Top, Dy); Inc(Area.Right, Dx); Inc(Area.Bottom, Dy); } type TLayerCollectionAccess = class(TLayerCollection); { TCustomRepaintManager } constructor TCustomRepaintOptimizer.Create(Buffer: TBitmap32; InvalidRects: TRectList); { FLayerCollections := TList.Create; FInvalidRects := InvalidRects; FBuffer := Buffer; } destructor TCustomRepaintOptimizer.Destroy; var I: Integer; { for I := 0 to FLayerCollections.Count - 1 do UnregisterLayerCollection(TLayerCollection(FLayerCollections[I])); FLayerCollections.Free; inherited; } function TCustomRepaintOptimizer.GetEnabled: Boolean; { Result := FEnabled; } void TCustomRepaintOptimizer.SetEnabled(const Value: Boolean); { FEnabled := Value; } void TCustomRepaintOptimizer.RegisterLayerCollection(Layers: TLayerCollection); { if FLayerCollections.IndexOf(Layers) = -1 then { FLayerCollections.Add(Layers); TLayerCollectionAccess(Layers).OnListNotify := LayerCollectionNotifyHandler; } } void TCustomRepaintOptimizer.UnregisterLayerCollection(Layers: TLayerCollection); { TLayerCollectionAccess(Layers).OnListNotify := nil; FLayerCollections.Remove(Layers); } void TCustomRepaintOptimizer.{Paint; { // do nothing by default } void TCustomRepaintOptimizer.EndPaint; { // do nothing by default } void TCustomRepaintOptimizer.{PaintBuffer; { // do nothing by default } void TCustomRepaintOptimizer.EndPaintBuffer; { // do nothing by default }
hyperiris/openhyper
graphic32/GR32_RepaintOpt.cpp
C++
gpl-2.0
1,794
<?php /** * @package External_Login * @subpackage Component * @author Christophe Demko <chdemko@gmail.com> * @author Ioannis Barounis <contact@johnbarounis.com> * @author Alexandre Gandois <alexandre.gandois@etudiant.univ-lr.fr> * @copyright Copyright (C) 2008-2018 Christophe Demko, Ioannis Barounis, Alexandre Gandois. All rights reserved. * @license GNU General Public License, version 2. http://www.gnu.org/licenses/gpl-2.0.html * @link http://www.chdemko.com */ // No direct access to this file defined('_JEXEC') or die; // Import Joomla view library jimport('joomla.application.component.view'); /** * Logs View of External Login component * * @package External_Login * @subpackage Component * * @since 2.1.0 */ class ExternalloginViewLogs extends JViewLegacy { /** * Execute and display a layout script. * * @param string $tpl The name of the layout file to parse. * * @return void|JError * * @see Overload JView::display * * @since 2.1.0 */ public function display($tpl = null) { // Get data from the model $items = $this->get('Items'); $pagination = $this->get('Pagination'); $state = $this->get('State'); // Check for errors. if (count($errors = $this->get('Errors'))) { $app = JFactory::getApplication(); $app->enqueueMessage(implode('<br />', $errors), 'error'); $app->redirect('index.php'); return false; } // Assign data to the view $this->items = $items; $this->pagination = $pagination; $this->state = $state; // Set the toolbar $this->addToolBar(); $this->sidebar = JHtml::_('sidebar.render'); // Display the template parent::display($tpl); } /** * Setting the toolbar * * @return void * * @since 2.1.0 */ protected function addToolbar() { // Load specific css component JHtml::_('stylesheet', 'com_externallogin/administrator/externallogin.css', array(), true); // Set the toolbar JToolBarHelper::title(JText::_('COM_EXTERNALLOGIN_MANAGER_LOGS'), 'list-view'); $bar = JToolBar::getInstance('toolbar'); $bar->appendButton('Confirm', 'COM_EXTERNALLOGIN_MSG_LOGS_DELETE', 'delete', 'JTOOLBAR_DELETE', 'logs.delete', false); $bar->appendButton('Link', 'download', 'COM_EXTERNALLOGIN_TOOLBAR_LOGS_DOWNLOAD', 'index.php?option=com_externallogin&view=logs&format=csv'); JToolBarHelper::preferences('com_externallogin'); JToolBarHelper::divider(); JToolBarHelper::help('COM_EXTERNALLOGIN_HELP_MANAGER_LOGS'); JHtml::_('sidebar.addentry', JText::_('COM_EXTERNALLOGIN_SUBMENU_SERVERS'), 'index.php?option=com_externallogin', false); JHtml::_('sidebar.addentry', JText::_('COM_EXTERNALLOGIN_SUBMENU_USERS'), 'index.php?option=com_externallogin&view=users', false); JHtml::_('sidebar.addentry', JText::_('COM_EXTERNALLOGIN_SUBMENU_LOGS'), 'index.php?option=com_externallogin&view=logs', true); JHtml::_('sidebar.addentry', JText::_('COM_EXTERNALLOGIN_SUBMENU_ABOUT'), 'index.php?option=com_externallogin&view=about', false); JHtml::_('sidebar.setaction', 'index.php?option=com_externallogin&view=logs'); JHtml::_( 'sidebar.addFilter', JText::_('COM_EXTERNALLOGIN_OPTION_SELECT_PRIORITY'), 'filter_priority', JHtml::_('select.options', ExternalloginHelper::getPriorities(), 'value', 'text', $this->state->get('filter.priority'), true) ); JHtml::_( 'sidebar.addFilter', JText::_('JOPTION_SELECT_PUBLISHED'), 'filter_category', JHtml::_('select.options', ExternalloginHelper::getCategories(), 'value', 'text', $this->state->get('filter.category'), true) ); } /** * Returns an array of fields the table can be sorted by * * @return array Array containing the field name to sort by as the key and display text as value * * @since 3.0 */ protected function getSortFields() { return array( 'a.priority' => JText::_('COM_EXTERNALLOGIN_HEADING_PRIORITY'), 'a.category' => JText::_('COM_EXTERNALLOGIN_HEADING_CATEGORY'), 'a.date' => JText::_('COM_EXTERNALLOGIN_HEADING_DATE'), 'a.message' => JText::_('COM_EXTERNALLOGIN_HEADING_MESSAGE') ); } }
emundus/v6
administrator/components/com_externallogin/views/logs/view.html.php
PHP
gpl-2.0
4,116
<?php get_header(); ?> <?php include( get_template_directory() . '/functions/get-options.php' ); /* include theme options */ ?> <!--BEGIN #primary .hfeed--> <div id="primary" class="hfeed"> <?php if( function_exists('bcn_display')) : echo '<p class="breadcrumb">'; bcn_display(); echo '</p>'; endif; ?> <?php $category = get_the_category(); if ($category[0]) { // echo '<h1><a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a></h1>'; echo '<h1 class="mainTitle"> ' . $category[0]->cat_name . '</h1>'; } ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', 'blog' ); ?> <?php endwhile; ?> <!--BEGIN .navigation .page-navigation --> <div class="navigation page-navigation"> <?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } else { ?> <div class="nav-next"><?php next_posts_link(__('&larr; Older Entries', 'framework')) ?></div> <div class="nav-previous"><?php previous_posts_link(__('Newer Entries &rarr;', 'framework')) ?></div> <?php } ?> <!--END .navigation ,page-navigation --> </div> <?php endif; ?> <!--END #primary .hfeed--> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
marcelijanowski/jaxa
wp-content/themes/Loveit-theme/category-blog.php
PHP
gpl-2.0
1,375
<?PHP // // Release $Name$ // // Copyright (c)2002-2003 Matthias Finck, Dirk Fust, Oliver Hankel, Iver Jackewitz, Michael Janneck, // Martti Jeenicke, Detlev Krause, Irina L. Marinescu, Timo Nolte, Bernd Pape, // Edouard Simon, Monique Strauss, Jose Manuel Gonzalez Vazquez, Johannes Schultze // // This file is part of CommSy. // // CommSy is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // CommSy 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 have received a copy of the GNU General Public License // along with CommSy. include_once 'functions/text_functions.php'; /** date functions are needed for method _newVersion() */ include_once 'functions/date_functions.php'; require_once('functions/security_functions'); /* * some spezific constants */ define('CS_STATUS_WP_ADMIN', 'administrator'); define('CS_STATUS_WP_EDITOR', 'editor'); define('CS_STATUS_WP_AUTHOR', 'author'); define('CS_STATUS_WP_CONTRI', 'contributor'); /** * Wordpress Manager */ class cs_wordpress_manager extends cs_manager { protected $CW = false; protected $wp_user = false; private $_wp_screenshot_array = array(); private $_wp_skin_option_array = array(); private $_with_session_caching = false; public function __construct($environment) { parent::__construct($environment); $this->wp_user = $this->_environment->getCurrentUser()->_getItemData(); $portal_item = $this->_environment->getCurrentPortalItem(); $wordpress_path_url = $portal_item->getWordpressUrl(); if ($portal_item->getWordpressPortalActive()) { $this->CW = $this->getSoapClient(); } } /** create a wordpress - internal, do not use -> use method save * this method creates a wordpress * */ public function createWordpress($item) { try { $wordpressId = $item->getWordpressId(); if ($wordpressId == 0) { $wpUser = $this->_getCurrentAuthItem(); $wpBlog = array('title' => $item->getTitle(), 'path' => $this->_environment->getCurrentPortalID().'_'.$item->getItemID(), 'cid' => $item->getItemID(), 'pid' => $this->_environment->getCurrentPortalID()); $result = $this->CW->createBlog($this->_environment->getSessionID(), $wpUser, $wpBlog); $item->setWordpressId($result['blog_id']); $item->save(); // set timezone $this->_setWordpressOption('timezone_string', date_default_timezone_get(), true, $item); } // set commsy context id $this->_setWordpressOption('commsy_context_id', $item->getItemID(), true, $item); // set Title $this->_setWordpressOption('blogname', $item->getWordpressTitle(), true, $item); // set Description $this->_setWordpressOption('blogdescription', $item->getWordpressDescription(), true, $item); // set default role $this->_setWordpressOption('default_role', $item->getWordpressMemberRole(), true, $item); // set Comments $this->_setWordpressOption('default_comment_status', ($item->getWordpressUseComments()==1) ? 'open' : 'closed', true, $item); $this->_setWordpressOption('comment_moderation', ($item->getWordpressUseCommentsModeration()==1) ? '1' : '', true, $item); // set theme $this->_setWordpressOption('template', $item->getWordpressSkin(), true, $item); $this->_setWordpressOption('stylesheet', $item->getWordpressSkin(), true, $item); // set plugin calendar $calendar = $item->getWordpressUseCalendar(); $tagcloud = $item->getWordpressUseTagCloud(); $plugins = $this->_getWordpressOption('active_plugins'); $pluginsArray = @unserialize($plugins); if (!$pluginsArray) { $pluginsArray = array(); } if (!$plugins) { // insert if ($calendar=='1') { $pluginsArray[] = 'calendar/calendar.php'; } if ($tagcloud=='1') { $pluginsArray[] = 'nktagcloud/nktagcloud.php'; } if (count($pluginsArray)>0) { $this->_setWordpressOption('active_plugins', $pluginsArray, false, $item); } } else { // update if ($calendar=='1' && strstr($plugins, 'calendar')==false) { $pluginsArray[] = 'calendar/calendar.php'; } elseif ($calendar!=='1') { $key = array_search('calendar/calendar.php', $pluginsArray); unset($pluginsArray[$key]); } if ($tagcloud=='1' && strstr($plugins, 'nktagcloud')==false) { $pluginsArray[] = 'nktagcloud/nktagcloud.php'; } elseif ($tagcloud!=='1') { $key = array_search('nktagcloud/nktagcloud.php', $pluginsArray); unset($pluginsArray[$key]); } $this->_setWordpressOption('active_plugins', $pluginsArray, true, $item); } } catch (Exception $e) { return new SoapFault('createWordpress', $e->getMessage()); } return true; } public function deleteWordpress($wordpress_id) { $retour = $this->CW->deleteBlog($this->_environment->getSessionID(), $wordpress_id); if (is_soap_fault($retour)) { $retour = false; } return $retour; } //------------------------------------------ //------------- Materialexport ------------- public function exportItemToWordpress($current_item_id, $rubric) { global $c_commsy_domain; global $c_commsy_url_path; global $c_single_entry_point; global $class_factory; $wpUser = $this->_getCurrentAuthItem(); $portal_item = $this->_environment->getCurrentPortalItem(); $wordpress_path_url = $portal_item->getWordpressUrl(); $context = $this->_environment->getCurrentContextItem(); $wordpressId = $context->getWordpressId(); $comment_status = $context->getWordpressUseComments(); #$wordpress_post_id = ''; // Material Item $material_manager = $this->_environment->getMaterialManager(); $material_version_list = $material_manager->getVersionList($current_item_id); $item = $material_version_list->getFirst(); // Informationen $author = $item->getAuthor(); $description = $item->getDescription(); if (empty($author)) { $author = $item->getModificatorItem()->getFullName(); } // Dateien $file_links = ''; $file_list = $item->getFileList(); $file_link_array_images = array(); if (!$file_list->isEmpty()) { $file_array = $file_list->to_array(); $file_link_array = array(); foreach ($file_array as $file) { $fileUrl = $this->CW->insertFile($this->_environment->getSessionID(), array('name' => $file->getDisplayName(), 'data' => base64_encode(file_get_contents($file->getDiskFileName()))), $wordpressId); if (!is_soap_fault($fileUrl)) { $file_link_array[] = '<a href="'.$fileUrl.'" title="'.$file->getDisplayName().'">'.$file->getDisplayName().'</a>'; $file_link_array_images[$file->getDisplayName()] = $fileUrl; // Add files to Wordpress media-library $file_post = array( 'post_content' =>'', 'post_content_filtered'=>'', 'post_title' =>mysql_escape_mimic($file->getDisplayName()), 'post_excerpt' =>'', 'post_status' =>'inherit', 'post_type' =>'attachment', 'comment_status' =>(($comment_status=='1') ? 'open' : 'closed'), // aus einstellungen übernehmen 'ping_status' =>'open', 'post_password' =>'', 'post_name' =>mysql_escape_mimic($file->getDisplayName()), 'to_ping' =>'', 'pinged' =>'', 'post_modified' =>$item->getModificationDate(), 'post_modified_gmt' =>$item->getModificationDate(), 'post_parent' =>'0', // wenn kein parent 'menu_order' =>'0', 'guid' =>$fileUrl, 'post_mime_type' =>mysql_escape_mimic($file->getMime())); $wordpress_post_id = $file->getWordpressPostId(); $wpPostId = $this->CW->insertPost($this->_environment->getSessionID(), $file_post, $wpUser, $wordpressId, 'Material', $wordpress_post_id); if ($wordpress_post_id == '') { $file->setWordpressPostId($wpPostId); $file->update(); } } } if (!empty($file_link_array)) { $file_links = '<br />Dateien:<br /> '.implode(' | ', $file_link_array); } } $params = array(); $params['environment'] = $this->_environment; $wordpress_view = $class_factory->getClass(WORDPRESS_VIEW, $params); $wordpress_view->setItem($item); $description = $wordpress_view->formatForWordpress($description, $file_link_array_images); $post_content = $this->encodeUmlaute($description); $post_content = 'Author: '.$author.'<br />'.$this->encodeUrl($post_content); $post_title = $item->getTitle(); $post_content_complete = ''; $post_content .= $file_links; // Abschnitte $sub_item_list = $item->getSectionList(); $sub_item_descriptions = ''; $post_content_complete .= $post_content; if (!$sub_item_list->isEmpty()) { $size = $sub_item_list->getCount(); $index_start = 1; $sub_item_link_array = array(); $sub_item_description_array = array(); for ($index = $index_start; $index <= $size; $index++) { $sub_item = $sub_item_list->get($index); $sub_item_link_array[] = '<a href="#section'.$index.'" title="' . $sub_item->getTitle() . '">' . $sub_item->getTitle() . '</a>'; // Abschnitt fuer Wordpress vorbereiten $description = $sub_item->getDescription(); $params = array(); $description = $this->encodeUmlaute($description); $description = $this->encodeUrl($description); $description = '<a name="section'.$index.'"></a>'.$description; // Dateien (Abschnitte) $file_list = $sub_item->getFileList(); if (!$file_list->isEmpty()) { $file_array = $file_list->to_array(); $file_link_array = array(); foreach ($file_array as $file) { $fileUrl = $this->CW->insertFile($this->_environment->getSessionID(), array('name' => $file->getDisplayName(), 'data' => base64_encode(file_get_contents($file->getDiskFileName()))), $wordpressId); if (!is_soap_fault($fileUrl)) { $file_link_array[] = '<a href="'.$fileUrl.'" title="'.$file->getDisplayName().'">'.$file->getDisplayName().'</a>' ; } } $file_links = ''; if (!empty($file_link_array)) { $file_links = '<br />Dateien:<br /> '.implode(' | ', $file_link_array); } } if (!empty($file_links)) { $sub_item_description_array[] = $description.$file_links; } else { $sub_item_description_array[] = $description; } } $sub_item_links = 'Abschnitte: <br />'.implode('<br />', $sub_item_link_array); $sub_item_descriptions = '<hr />'.implode('<hr />', $sub_item_description_array); // attach each section to the item $post_content_complete .= '<br />'.$sub_item_links.$sub_item_descriptions; } // Link zurueck ins CommSy $post_content_complete .= '<hr /><a href="' . $c_commsy_domain . $c_commsy_url_path . '/'.$c_single_entry_point.'?cid=' . $this->_environment->getCurrentContextID() . '&mod='.$rubric.'&fct=detail&iid=' . $current_item_id . '" title="'.$item->getTitle().'">"' . $item->getTitle() . '" im CommSy</a>'; // delete rn out of post_content if (stristr($post_content_complete, '<!-- KFC TEXT')) { $post_content_complete = str_replace("\r\n", '', $post_content_complete); } else { $post_content_complete = str_replace("\r\n", '<br/>', $post_content_complete); } $post = array( 'post_content' => mysql_escape_mimic($post_content_complete), 'post_content_filtered'=> '', 'post_title' => mysql_escape_mimic($post_title), 'post_excerpt' => mysql_escape_mimic($post_content), 'post_status' =>'publish', 'post_type' =>'post', 'comment_status' =>(($comment_status=='1') ? 'open' : 'closed'), // aus einstellungen übernehmen 'ping_status' =>'open', 'post_password' =>'', 'post_name' => mysql_escape_mimic(str_replace(' ', '-', $post_title)), 'to_ping' =>'', 'pinged' =>'', 'post_modified' =>$item->getModificationDate(), 'post_modified_gmt' =>$item->getModificationDate(), 'post_parent' =>'0', // wenn kein parent 'menu_order' =>'0', 'guid' =>''); $wordpress_post_id = $item->getExportToWordpress(); $wpPostId = $this->CW->insertPost($this->_environment->getSessionID(), $post, $wpUser, $wordpressId, 'Material', $wordpress_post_id); if (!is_soap_fault($wpPostId)) { $item->setExportToWordpress($wpPostId); $item->save(); } } public function encodeUmlaute($html) { $html = str_replace("ä", "&auml;", $html); $html = str_replace("Ä", "&Auml;", $html); $html = str_replace("ö", "&ouml;", $html); $html = str_replace("Ö", "&Ouml;", $html); $html = str_replace("ü", "&uuml;", $html); $html = str_replace("Ü", "&Uuml;", $html); $html = str_replace("ß", "&szlig;", $html); return $html; } public function encodeUrl($html) { $html = str_replace("%E4", "ae", $html); $html = str_replace("%C4", "AE", $html); $html = str_replace("%F6", "oe", $html); $html = str_replace("%D6", "OE", $html); $html = str_replace("%FC", "ue", $html); $html = str_replace("%DC", "UE", $html); $html = str_replace("%DF", "ss", $html); return $html; } public function encodeUrlToHtml($html) { $html = str_replace("%E4", "&auml;", $html); $html = str_replace("%C4", "&Auml;", $html); $html = str_replace("%F6", "&ouml;", $html); $html = str_replace("%D6", "&Ouml;", $html); $html = str_replace("%FC", "&uuml;", $html); $html = str_replace("%DC", "&Uuml;", $html); $html = str_replace("%DF", "&szlig;", $html); return $html; } public function existsItemToWordpress($wordpress_post_id) { $contextItem = $this->_environment->getCurrentContextItem(); $retour = $this->CW->getPostExists($this->_environment->getSessionID(), (int) $wordpress_post_id, $contextItem->getWordpressId()); if (is_soap_fault($retour)) { $retour = false; } return $retour; } public function getExportToWordpressLink($wordpress_post_id) { $portal_item = $this->_environment->getCurrentPortalItem(); $wordpress_path_url = $portal_item->getWordpressUrl(); return '<a target="_blank" href="' . $wordpress_path_url . $this->_environment->getCurrentPortalID() . '_' . $this->_environment->getCurrentContextID() . '/?p='.$wordpress_post_id.'&commsy_session_id='.$this->_environment->getSessionID().'">zum Artikel</a>'; } public function getSoapWsdlUrl() { $portal_item = $this->_environment->getCurrentPortalItem(); $wordpress_path_url = $portal_item->getWordpressUrl(); return $wordpress_path_url . '?wsdl'; } public function getSoapClient() { $options = array("trace" => 1, "exceptions" => 1); global $symfonyContainer; $c_proxy_ip = $symfonyContainer->getParameter('commsy.settings.proxy_ip'); $c_proxy_port = $symfonyContainer->getParameter('commsy.settings.proxy_port'); if ($c_proxy_ip) { $options['proxy_host'] = $c_proxy_ip; } if ($c_proxy_port) { $options['proxy_port'] = $c_proxy_port; } $retour = null; try { $retour = new SoapClient($this->getSoapWsdlUrl(), $options); } catch (SoapFault $sf) { include_once 'functions/error_functions.php'; trigger_error('SOAP Error: '.$sf->faultstring, E_USER_ERROR); } return $retour; } protected function _setWordpressOption($option_name, $option_value, $update=true, $item) { $option_value = is_array($option_value) ? serialize($option_value) : $option_value; if ($update==true) { $this->CW->updateOption($this->_environment->getSessionID(), $option_name, $option_value, $item->getWordpressId()); } else { $this->CW->insertOption($this->_environment->getSessionID(), $option_name, $option_value, $item->getWordpressId()); } } protected function _getWordpressOption($option_name) { return $this->CW->getOption($this->_environment->getSessionID(), $option_name, $this->_environment->getCurrentContextItem()->getWordpressId()); } protected function _getCurrentAuthItem() { // get user data out of the current portal user object // and status from the current user in the current context $current_user_item = $this->_environment->getPortalUserItem(); $result = array( 'login' => $current_user_item->getUserID(), 'email' => $current_user_item->getEmail(), 'firstname' => $current_user_item->getFirstName(), 'lastname' => $current_user_item->getLastName(), 'commsy_id' => $this->_environment->getCurrentPortalID(), 'display_name' => trim($current_user_item->getFirstName()).' '.trim($current_user_item->getLastName()) ); unset($current_user_item); // TBD: change to soap authentication at WP // for commsy internal accounts get md5-password $session_manager = $this->_environment->getSessionManager(); $session_item = $session_manager->get($this->_environment->getSessionID()); $auth_source_id = $session_item->getValue('auth_source'); $auth_source_manager = $this->_environment->getAuthSourceManager(); $auth_source_item = $auth_source_manager->getItem($auth_source_id); if ($auth_source_item->isCommSyDefault()) { $user_id = $session_item->getValue('user_id'); $commsy_id = $session_item->getValue('commsy_id'); $authentication = $this->_environment->getAuthenticationObject(); $authManager = $authentication->getAuthManagerByAuthSourceItem($auth_source_item); $authManager->setContextID($commsy_id); $auth_item = $authManager->getItem($user_id); $result['password'] = $auth_item->getPasswordMD5(); unset($auth_item); unset($authManager); unset($authentication); } else { // dummy password for external accounts include_once 'functions/date_functions.php'; $result['password'] = md5(getCurrentDateTimeInMySQL().rand(1, 999).$this->_environment->getConfiguration('c_security_key')); } unset($auth_source_manager); unset($auth_source_item); return $result; } // returns an array of default skins public function getSkins() { $retour = ''; if (!empty($this->_wp_skin_option_array)) { $retour = $this->_wp_skin_option_array; } else { try { $skins = $this->CW->getSkins($this->_environment->getSessionID()); $skinOptions = array(); if (!empty($skins)) { foreach ($skins as $name => $skin) { $templateDirectory = $skin['template']; $skinOptions[$name] = $templateDirectory; $screenshotUrl = $skin['screenshot']; if (!empty($screenshotUrl)) { $this->_wp_screenshot_array[$templateDirectory] = $screenshotUrl; } else { $this->_wp_screenshot_array[$templateDirectory] = 'screenshot.png'; } } } $this->_wp_skin_option_array = $skinOptions; $retour = $this->_wp_skin_option_array; } catch (Exception $e) { echo $e->getMessage(); exit; } } return $retour; } public function getScreenshotFilenameForTheme($name) { $retour = 'screenshot.png'; if (!empty($this->_wp_screenshot_array[$name])) { $retour = $this->_wp_screenshot_array[$name]; } return $retour; } /** ask, if user is allowed to export an item to wordpress * this method returns a boolean, if an user is allowed to export an item * * @param int wordpress_id the id of the wordpress blog * @param string user_login the user_id of the user * @return bool retour true: user is allowed, false: user is not allowed */ public function isUserAllowedToExportItem($wordpress_id, $user_login) { $retour = false; if (!empty($wordpress_id) and $user_login != 'root') { $session_item = $this->_environment->getSessionItem(); if ($this->_with_session_caching and $session_item->issetValue('wordpress_allowed_export_item_'.$wordpress_id) ) { $value = $session_item->getValue('wordpress_allowed_export_item_'.$wordpress_id); if ($value == 1) { $retour = true; } } else { if (empty($this->CW) and is_object($this->CW)) { $role = $this->CW->getUserRole($session_item->getSessionID(), $wordpress_id, $user_login); } if (empty($role) or is_soap_fault($role)) { $current_context = $this->_environment->getCurrentContextItem(); $role = $current_context->getWordpressMemberRole(); } if (!empty($role)) { if ($role == CS_STATUS_WP_ADMIN or $role == CS_STATUS_WP_EDITOR or $role == CS_STATUS_WP_AUTHOR or $role == CS_STATUS_WP_CONTRI ) { $retour = true; } if ($this->_with_session_caching) { $session_value = -1; if ($retour) { $session_value = 1; } $session_item->setValue('wordpress_allowed_export_item_'.$wordpress_id, $session_value); } } } unset($session_item); } return $retour; } /** ask, if user is allowed to configure the wordpress blog * this method returns a boolean, if an user is allowed to configure a wordpress blog * * @param int wordpress_id the id of the wordpress blog * @param string user_login the user_id of the user * @return bool retour true: user is allowed, false: user is not allowed */ public function isUserAllowedToConfig($wordpress_id, $user_login) { $retour = false; if (!empty($wordpress_id)) { $session_item = $this->_environment->getSessionItem(); if ($this->_with_session_caching and $session_item->issetValue('wordpress_allowed_config_'.$wordpress_id)) { $value = $session_item->getValue('wordpress_allowed_config_'.$wordpress_id); if ($value == 1) { $retour = true; } } else { $role = $this->CW->getUserRole($session_item->getSessionID(), $wordpress_id, $user_login); if (empty($role) or is_soap_fault($role)) { $current_context = $this->_environment->getCurrentContextItem(); $role = $current_context->getWordpressMemberRole(); unset($current_context); } if (empty($role)) { $current_user_item = $this->_environment->getCurrentUserItem(); if ($current_user_item->isModerator()) { $role = CS_STATUS_WP_ADMIN; } unset($current_user_item); } if (!empty($role)) { if ($role == CS_STATUS_WP_ADMIN) { $retour = true; } if ($this->_with_session_caching) { $session_value = -1; if ($retour) { $session_value = 1; } $session_item->setValue('wordpress_allowed_config_'.$wordpress_id, $session_value); } } } unset($session_item); } else { $current_user_item = $this->_environment->getCurrentUserItem(); if ($current_user_item->isModerator()) { $role = CS_STATUS_WP_ADMIN; } unset($current_user_item); if (!empty($role)) { if ($role == CS_STATUS_WP_ADMIN) { $retour = true; } if ($this->_with_session_caching) { $session_value = -1; if ($retour) { $session_value = 1; } $session_item->setValue('wordpress_allowed_config_'.$wordpress_id, $session_value); } } } return $retour; } }
commsy/commsy
legacy/classes/cs_wordpress_manager.php
PHP
gpl-2.0
27,924
<?php /** Functions for DB layer * * PHP version 5 * * @category File * @package crawler DB * @author Malitsky Alexander <a.malitsky@gmail.com> * @license GNU GENERAL PUBLIC LICENSE */ /** * Gets all onSale apartments from the last snapshot. * * @param object $db MYSQLi connection * @param integer $bId Internal building ID * @return array|bool */ function r9mkLoadSnapFromDB($db, $bId){ if(!($res = $db -> query("SELECT d.bId, d.extFlatId, 1 AS status, d.flPrice AS price FROM (SELECT MAX(a.snapId) as snapId FROM snapshots AS a WHERE a.bId=$bId GROUP BY a.flatId) as b JOIN snapshots AS d ON b.snapId = d.snapId WHERE d.flStatus=1 ORDER BY d.extFlatId;"))){ echo "<p class='error'>Error: db SELECT query for building $bId failed: (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; return false; } for ($fromdb = array(); $tmp = $res -> fetch_assoc();) { $fromdb[] = $tmp; } $res -> close(); return $fromdb; } /** * Findes all flats updated between from and till dates. * * @param object $db MYSQLi connection to database * @param integer $bId Internal building ID * @param integer $from unixtime * @param integer $till unixtime * @return array|bool */ function getListOfUpdatedFlats($db, $bId, $from = NULL, $till = NULL){ $query = "SELECT DISTINCT flatId FROM snapshots WHERE bId = $bId " .($from ? " AND snapDate >= '".date('Y-m-d 22:00:00', $from)."'":'') .($till ? " AND snapDate <= '".date('Y-m-d 22:00:00', $till)."'":'') ." ORDER BY flatId;"; if(!($res = $db -> query($query))){ echo "<p class='error'>Error: db query for list of updated flats (from: '".$from."' & till: '".$till."') of building $bId failed: (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; return false; } for ($list = array(); $tmp = $res -> fetch_assoc();) { $list[] = $tmp; } $res -> close(); unset($tmp); if(!empty($list)){ return $list; } else { echo "<p class='warn'>Warn: Empty result returned from DB on fetching list of updated flats (from: '".$from."' & till: '".$till."') for building $bId. [".__FUNCTION__."]</p>\r\n"; return false; } } /** * Saves selected flats to database * * @param object $db MYSQLi connection to database * @param array $flats Flats array to update [bId, extFlatId, status, price] * @param integer $bId Internal building ID * @return bool */ function updateSnapDB($db, $flats, $bId){ $flatIdShift = array(1 => -126496, 2 => -127673, 3 => -188761);//to count flatId from extFlatId if(!($updStmt = $db -> prepare("INSERT INTO snapshots(bId, extFlatId, flatId, flStatus, flPrice) VALUES ($bId, ?, ?, ?, ?);"))){ echo "<p class='error'>Error: UPDATE statement preparation for building $bId failed : (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; return false; } foreach ($flats as $flat){ $flat['id'] = $flat['extFlatId'] + $flatIdShift[$bId]; $updStmt -> bind_param('iiii', $flat['extFlatId'], $flat['id'], $flat['status'], $flat['price']); if (!$updStmt -> execute()) { echo "<p class='error'>Error: UPDATE statement execution for building $bId failed: (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; return false; } } $updStmt -> close(); return true; } /** * Saves all flats from WEB to backup database * * @param object $db MYSQLi connection to DB * @param array $flats * @param integer $bId Internal building ID * @return bool */ function saveBackupSnapDB($db, $flats, $bId){ $flatIdShift = array(1 => -126496, 2 => -127673, 3 => -188761);//to count flatId from extFlatId if(!($updStmt = $db -> prepare("INSERT INTO snapbackup(bId, extFlatId, flatId, flStatus, flPrice) VALUES ($bId, ?, ?, ?, ?);"))){ echo "<p class='error'>Error: UPDATE statement prepare for building $bId failed: (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; return false; } foreach ($flats as $flat){ $flat['id'] = $flat['extFlatId'] + $flatIdShift[$bId]; $updStmt -> bind_param('iiii', $flat['extFlatId'], $flat['id'], $flat['status'], $flat['price']); if (!$updStmt -> execute()) { echo "<p class='error'>Error: UPDATE execution for building $bId failed: (".$db->errno.") ".$db->error.". [".__FUNCTION__."]</p>\r\n"; } } $updStmt -> close(); return true; }
amalitsky/new-buildings-story
db.php
PHP
gpl-2.0
4,505
<? /* ----------------------------------------------------------------------------------------- $Id: cash.php 1102 2005-07-24 15:05:38Z mz $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(cod.php,v 1.28 2003/02/14); www.oscommerce.com (c) 2003 nextcommerce (invoice.php,v 1.4 2003/08/13); www.nextcommerce.org Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ define('MODULE_PAYMENT_CASH_TEXT_DESCRIPTION', 'Barzahlung'); define('MODULE_PAYMENT_CASH_TEXT_TITLE', 'Barzahlung'); define('MODULE_PAYMENT_CASH_TEXT_INFO', ''); define('MODULE_PAYMENT_CASH_STATUS_TITLE', 'Barzahlungsmodul aktivieren'); define('MODULE_PAYMENT_CASH_STATUS_DESC', 'M&ouml;chten Sie Zahlungen per Barzahlung akzeptieren?'); define('MODULE_PAYMENT_CASH_ORDER_STATUS_ID_TITLE', 'Bestellstatus festlegen'); define('MODULE_PAYMENT_CASH_ORDER_STATUS_ID_DESC', 'Bestellungen, welche mit diesem Modul gemacht werden, auf diesen Status setzen'); define('MODULE_PAYMENT_CASH_SORT_ORDER_TITLE', 'Anzeigereihenfolge'); define('MODULE_PAYMENT_CASH_SORT_ORDER_DESC', 'Reihenfolge der Anzeige. Kleinste Ziffer wird zuerst angezeigt.'); define('MODULE_PAYMENT_CASH_ZONE_TITLE', 'Zahlungszone'); define('MODULE_PAYMENT_CASH_ZONE_DESC', 'Wenn eine Zone ausgew&auml;hlt ist, gilt die Zahlungsmethode nur f&uuml;r diese Zone.'); define('MODULE_PAYMENT_CASH_ALLOWED_TITLE', 'Erlaubte Zonen'); define('MODULE_PAYMENT_CASH_ALLOWED_DESC', 'Geben Sie <b>einzeln</b> die Zonen an, welche f&uuml;r dieses Modul erlaubt sein sollen. (z.B. AT,DE (wenn leer, werden alle Zonen erlaubt))'); ?>
mcules/self-commerce
lang/translate_0815/german/modules/payment/cash.php
PHP
gpl-2.0
1,902
package gerhard2202.culinaromancy.item; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; import java.util.Random; public class ItemGourmetChicken extends ItemCulinaromancyFood { public ItemGourmetChicken() { super("gourmetChicken", 7, 8.2F, false); } @Override public int getMaxItemUseDuration(ItemStack stack) { return 32; } @Override public void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { Random buffChance = new Random(); int result = buffChance.nextInt(100) + 1; if (result <= 50) { player.addPotionEffect(new PotionEffect(MobEffects.SPEED, 1600, 0, false, false)); } } }
gerhard2202/Culinaromancy
src/main/java/gerhard2202/culinaromancy/item/ItemGourmetChicken.java
Java
gpl-2.0
856
<?php /* Copyright (C) NAVER <http://www.navercorp.com> */ /** * - DB parent class * - usage of db in XE is via xml * - there are 2 types of xml - query xml, schema xml * - in case of query xml, DB::executeQuery() method compiles xml file into php code and then execute it * - query xml has unique query id, and will be created in module * - queryid = module_name.query_name * * @author NAVER (developers@xpressengine.com) * @package /classes/db * @version 0.1 */ class DB { static $isSupported = FALSE; /** * priority of DBMS * @var array */ protected static $priority_dbms = array( 'mysqli' => 6, 'cubrid' => 2, 'mssql' => 1 ); /** * operations for condition * @var array */ protected static $cond_operation = array( 'equal' => '=', 'more' => '>=', 'excess' => '>', 'less' => '<=', 'below' => '<', 'notequal' => '<>', 'notnull' => 'is not null', 'null' => 'is null', ); /** * master database connection string * @var array */ protected $master_db = NULL; /** * array of slave databases connection strings * @var array */ protected $slave_db = NULL; protected $result = NULL; /** * error code (0 means no error) * @var int */ protected $errno = 0; /** * error message * @var string */ protected $errstr = ''; /** * query string of latest executed query * @var string */ protected $query = ''; protected $connection = ''; /** * elapsed time of latest executed query * @var int */ protected $elapsed_time = 0; /** * elapsed time of latest executed DB class * @var int */ protected $elapsed_dbclass_time = 0; /** * transaction flag * @var boolean */ protected $transaction_started = FALSE; protected $is_connected = FALSE; /** * returns enable list in supported dbms list * will be written by classes/DB/DB***.class.php * @var array */ protected static $supported_list = array(); /** * location of query cache * @var string */ protected $cache_file = 'files/cache/queries/'; /** * stores database type: 'mysql','cubrid','mssql' etc. or 'db' when database is not yet set * @var string */ public $db_type; public $db_version = ''; /** * flag to decide if class prepared statements or not (when supported); can be changed from db.config.info * @var string */ public $use_prepared_statements; /** * leve of transaction * @var unknown */ protected $transactionNestedLevel = 0; /** * returns instance of certain db type * @param string $db_type type of db * @return DB return DB object instance */ public static function getInstance($db_type = NULL) { if(!$db_type) { $db_type = config('db.master.type'); if (config('db.master.engine') === 'innodb') { $db_type .= '_innodb'; } } if(!$db_type && Context::isInstalled()) { return new Object(-1, 'msg_db_not_setted'); } if(!isset($GLOBALS['__DB__'])) { $GLOBALS['__DB__'] = array(); } if(!isset($GLOBALS['__DB__'][$db_type])) { $class_name = 'DB' . ucfirst($db_type); $class_file = RX_BASEDIR . "classes/db/$class_name.class.php"; if(!file_exists($class_file)) { return new Object(-1, 'msg_db_not_setted'); } // get a singletone instance of the database driver class require_once($class_file); $GLOBALS['__DB__'][$db_type] = new $class_name; $GLOBALS['__DB__'][$db_type]->db_type = $db_type; } return $GLOBALS['__DB__'][$db_type]; } /** * returns instance of db * @return DB return DB object instance */ public static function create() { return new static(); } /** * constructor * @return void */ public function __construct() { $this->cache_file = _XE_PATH_ . $this->cache_file; } /** * returns list of supported dbms list * this list return by directory list * check by instance can creatable * @return array return supported DBMS list */ public static function getSupportedList() { return self::_getSupportedList(); } /** * returns enable list in supported dbms list * this list return by child class * @return array return enable DBMS list in supported dbms list */ public static function getEnableList() { if(!self::$supported_list) { $oDB = new DB(); self::$supported_list = self::_getSupportedList(); } $enableList = array(); if(is_array(self::$supported_list)) { foreach(self::$supported_list AS $key => $value) { if($value->enable) { $enableList[] = $value; } } } return $enableList; } /** * returns list of disable in supported dbms list * this list return by child class * @return array return disable DBMS list in supported dbms list */ public static function getDisableList() { if(!self::$supported_list) { $oDB = new DB(); self::$supported_list = self::_getSupportedList(); } $disableList = array(); if(is_array(self::$supported_list)) { foreach(self::$supported_list AS $key => $value) { if(!$value->enable) { $disableList[] = $value; } } } return $disableList; } /** * returns list of supported dbms list * * @return array return supported DBMS list */ protected static function _getSupportedList() { if(self::$supported_list) { return self::$supported_list; } $get_supported_list = array(); $db_classes_path = _XE_PATH_ . "classes/db/"; $filter = "/^DB([^\.]+)\.class\.php/i"; $supported_list = FileHandler::readDir($db_classes_path, $filter, TRUE); // after creating instance of class, check is supported foreach ($supported_list as $db_type) { if (strncasecmp($db_type, 'mysql', 5) === 0 && strtolower($db_type) !== 'mysqli') { continue; } $class_name = sprintf("DB%s%s", strtoupper(substr($db_type, 0, 1)), strtolower(substr($db_type, 1))); $class_file = sprintf(_XE_PATH_ . "classes/db/%s.class.php", $class_name); if (!file_exists($class_file)) { continue; } require_once($class_file); $oDB = new $class_name(); $obj = new stdClass; $obj->db_type = $db_type; $obj->enable = $oDB->isSupported() ? TRUE : FALSE; unset($oDB); $get_supported_list[] = $obj; } // sort usort($get_supported_list, function($a, $b) { $priority_a = isset(self::$priority_dbms[$a->db_type]) ? self::$priority_dbms[$a->db_type] : 0; $priority_b = isset(self::$priority_dbms[$b->db_type]) ? self::$priority_dbms[$b->db_type] : 0; return $a - $b; }); return self::$supported_list = $get_supported_list; } /** * Return dbms supportable status * The value is set in the child class * @return boolean true: is supported, false: is not supported */ public function isSupported() { return self::$isSupported; } /** * Return connected status * @param string $type master or slave * @param int $indx key of server list * @return boolean true: connected, false: not connected */ public function isConnected($type = 'master', $indx = 0) { if($type == 'master') { return $this->master_db["is_connected"] ? TRUE : FALSE; } else { return $this->slave_db[$indx]["is_connected"] ? TRUE : FALSE; } } /** * start recording log * @param string $query query string * @return void */ public function actStart($query) { $this->setError(0, 'success'); $this->query = $query; $this->act_start = microtime(true); $this->elapsed_time = 0; } /** * finish recording log * @return void */ public function actFinish() { if(!$this->query) { return; } $this->act_finish = microtime(true); $elapsed_time = $this->act_finish - $this->act_start; $this->elapsed_time = $elapsed_time; $GLOBALS['__db_elapsed_time__'] += $elapsed_time; $site_module_info = Context::get('site_module_info'); $log = array(); $log['query'] = $this->query; $log['elapsed_time'] = $elapsed_time; $log['connection'] = $this->connection; $log['query_id'] = $this->query_id; $log['module'] = $site_module_info->module; $log['act'] = Context::get('act'); $log['time'] = date('Y-m-d H:i:s'); $log['backtrace'] = array(); if (config('debug.enabled') && ($this->isError() || in_array('queries', config('debug.display_content')))) { $bt = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); foreach($bt as $no => $call) { if($call['function'] == 'executeQuery' || $call['function'] == 'executeQueryArray') { $call_no = $no; $call_no++; $log['called_file'] = $bt[$call_no]['file']; $log['called_line'] = $bt[$call_no]['line']; $call_no++; $log['called_method'] = $bt[$call_no]['class'].$bt[$call_no]['type'].$bt[$call_no]['function']; $log['backtrace'] = array_slice($bt, $call_no, 1); break; } } } else { $log['called_file'] = $log['called_line'] = $log['called_method'] = null; $log['backtrace'] = array(); } // leave error log if an error occured if($this->isError()) { $log['result'] = 'error'; $log['errno'] = $this->errno; $log['errstr'] = $this->errstr; } else { $log['result'] = 'success'; $log['errno'] = null; $log['errstr'] = null; } $this->setQueryLog($log); } /** * set query debug log * @param array $log values set query debug * @return void */ public function setQueryLog($log) { Rhymix\Framework\Debug::addQuery($log); } /** * set error * @param int $errno error code * @param string $errstr error message * @return void */ public function setError($errno = 0, $errstr = 'success') { $this->errno = $errno; $this->errstr = $errstr; } /** * Return error status * @return boolean true: error, false: no error */ public function isError() { return ($this->errno !== 0); } /** * Returns object of error info * @return object object of error */ public function getError() { $this->errstr = Context::convertEncodingStr($this->errstr); return new Object($this->errno, $this->errstr); } /** * Execute Query that result of the query xml file * This function finds xml file or cache file of $query_id, compiles it and then execute it * @param string $query_id query id (module.queryname) * @param array|object $args arguments for query * @param array $arg_columns column list. if you want get specific colums from executed result, add column list to $arg_columns * @return object result of query */ public function executeQuery($query_id, $args = NULL, $arg_columns = NULL, $type = NULL) { static $cache_file = array(); if(!$query_id) { return new Object(-1, 'msg_invalid_queryid'); } if(!$this->db_type) { return; } $this->actDBClassStart(); $this->query_id = $query_id; if(!isset($cache_file[$query_id]) || !file_exists($cache_file[$query_id])) { $id_args = explode('.', $query_id); if(count($id_args) == 2) { $target = 'modules'; $module = $id_args[0]; $id = $id_args[1]; } elseif(count($id_args) == 3) { $target = $id_args[0]; $typeList = array('addons' => 1, 'widgets' => 1); if(!isset($typeList[$target])) { $this->actDBClassFinish(); return; } $module = $id_args[1]; $id = $id_args[2]; } if(!$target || !$module || !$id) { $this->actDBClassFinish(); return new Object(-1, 'msg_invalid_queryid'); } $xml_file = sprintf('%s%s/%s/queries/%s.xml', _XE_PATH_, $target, $module, $id); if(!file_exists($xml_file)) { $this->actDBClassFinish(); return new Object(-1, 'msg_invalid_queryid'); } // look for cache file $cache_file[$query_id] = $this->checkQueryCacheFile($query_id, $xml_file); } $result = $this->_executeQuery($cache_file[$query_id], $args, $query_id, $arg_columns, $type); $this->actDBClassFinish(); // execute query return $result; } /** * Look for query cache file * @param string $query_id query id for finding * @param string $xml_file original xml query file * @return string cache file */ public function checkQueryCacheFile($query_id, $xml_file) { // first try finding cache file $cache_file = sprintf('%s%s%s.%s.%s.cache.php', _XE_PATH_, $this->cache_file, $query_id, __ZBXE_VERSION__, $this->db_type); $cache_time = -1; if(file_exists($cache_file)) { $cache_time = filemtime($cache_file); } // if there is no cache file or is not new, find original xml query file and parse it if($cache_time < filemtime($xml_file) || $cache_time < filemtime(_XE_PATH_ . 'classes/db/DB.class.php') || $cache_time < filemtime(_XE_PATH_ . 'classes/xml/XmlQueryParser.class.php')) { $oParser = new XmlQueryParser(); $oParser->parse($query_id, $xml_file, $cache_file); } return $cache_file; } /** * Execute query and return the result * @param string $cache_file cache file of query * @param array|object $source_args arguments for query * @param string $query_id query id * @param array $arg_columns column list. if you want get specific colums from executed result, add column list to $arg_columns * @return object result of query */ public function _executeQuery($cache_file, $source_args, $query_id, $arg_columns, $type) { global $lang; if(!in_array($type, array('master','slave'))) $type = 'slave'; if(!file_exists($cache_file)) { return new Object(-1, 'msg_invalid_queryid'); } if($source_args) { $args = clone $source_args; } $output = include($cache_file); if($output instanceof Object && !$output->toBool()) { return $output; } if(!is_object($output) || !method_exists($output, 'getAction')) { return new Object(-1, sprintf(lang('msg_failed_to_load_query'), $query_id)); } // execute appropriate query switch($output->getAction()) { case 'insert' : case 'insert-select' : $this->resetCountCache($output->tables); $output = $this->_executeInsertAct($output); break; case 'update' : $this->resetCountCache($output->tables); $output = $this->_executeUpdateAct($output); break; case 'delete' : $this->resetCountCache($output->tables); $output = $this->_executeDeleteAct($output); break; case 'select' : $arg_columns = is_array($arg_columns) ? $arg_columns : array(); $output->setColumnList($arg_columns); $connection = $this->_getConnection($type); $output = $this->_executeSelectAct($output, $connection); break; } if($this->isError()) { $output = $this->getError(); } elseif(!($output instanceof Object)) { $output = new Object(); } $output->add('_query', $this->query); $output->add('_elapsed_time', sprintf("%0.5f", $this->elapsed_time)); return $output; } /** * Returns counter cache data * @param array|string $tables tables to get data * @param string $condition condition to get data * @return int count of cache data */ public function getCountCache($tables, $condition) { return FALSE; } /** * Save counter cache data * @param array|string $tables tables to save data * @param string $condition condition to save data * @param int $count count of cache data to save * @return void */ public function putCountCache($tables, $condition, $count = 0) { return FALSE; } /** * Reset counter cache data * @param array|string $tables tables to reset cache data * @return boolean true: success, false: failed */ public function resetCountCache($tables) { return FALSE; } /** * Drop tables * @param string $table_name * @return void */ public function dropTable($table_name) { if(!$table_name) { return; } $query = sprintf("drop table %s%s", $this->prefix, $table_name); $this->_query($query); } /** * Return select query string * @param object $query * @param boolean $with_values * @return string */ public function getSelectSql($query, $with_values = TRUE) { $select = $query->getSelectString($with_values); if($select == '') { return new Object(-1, "Invalid query"); } $select = 'SELECT ' . $select; $from = $query->getFromString($with_values); if($from == '') { return new Object(-1, "Invalid query"); } $from = ' FROM ' . $from; $where = $query->getWhereString($with_values); if($where != '') { $where = ' WHERE ' . $where; } $tableObjects = $query->getTables(); $index_hint_list = ''; foreach($tableObjects as $tableObject) { if(is_a($tableObject, 'CubridTableWithHint')) { $index_hint_list .= $tableObject->getIndexHintString() . ', '; } } $index_hint_list = substr($index_hint_list, 0, -2); if($index_hint_list != '') { $index_hint_list = 'USING INDEX ' . $index_hint_list; } $groupBy = $query->getGroupByString(); if($groupBy != '') { $groupBy = ' GROUP BY ' . $groupBy; } $orderBy = $query->getOrderByString(); if($orderBy != '') { $orderBy = ' ORDER BY ' . $orderBy; } $limit = $query->getLimitString(); if($limit != '') { $limit = ' LIMIT ' . $limit; } return $select . ' ' . $from . ' ' . $where . ' ' . $index_hint_list . ' ' . $groupBy . ' ' . $orderBy . ' ' . $limit; } /** * Given a SELECT statement that uses click count * returns the corresponding update sql string * for databases that don't have click count support built in * (aka all besides CUBRID) * * Function does not check if click count columns exist! * You must call $query->usesClickCount() before using this function * * @param $queryObject */ public function getClickCountQuery($queryObject) { $new_update_columns = array(); $click_count_columns = $queryObject->getClickCountColumns(); foreach($click_count_columns as $click_count_column) { $click_count_column_name = $click_count_column->column_name; $increase_by_1 = new Argument($click_count_column_name, null); $increase_by_1->setColumnOperation('+'); $increase_by_1->ensureDefaultValue(1); $update_expression = new UpdateExpression($click_count_column_name, $increase_by_1); $new_update_columns[] = $update_expression; } $queryObject->columns = $new_update_columns; return $queryObject; } /** * Return delete query string * @param object $query * @param boolean $with_values * @param boolean $with_priority * @return string */ public function getDeleteSql($query, $with_values = TRUE, $with_priority = FALSE) { $sql = 'DELETE '; $sql .= $with_priority ? $query->getPriority() : ''; $tables = $query->getTables(); $sql .= $tables[0]->getAlias(); $from = $query->getFromString($with_values); if($from == '') { return new Object(-1, "Invalid query"); } $sql .= ' FROM ' . $from; $where = $query->getWhereString($with_values); if($where != '') { $sql .= ' WHERE ' . $where; } return $sql; } /** * Return update query string * @param object $query * @param boolean $with_values * @param boolean $with_priority * @return string */ public function getUpdateSql($query, $with_values = TRUE, $with_priority = FALSE) { $columnsList = $query->getUpdateString($with_values); if($columnsList == '') { return new Object(-1, "Invalid query"); } $tables = $query->getFromString($with_values); if($tables == '') { return new Object(-1, "Invalid query"); } $where = $query->getWhereString($with_values); if($where != '') { $where = ' WHERE ' . $where; } $priority = $with_priority ? $query->getPriority() : ''; return "UPDATE $priority $tables SET $columnsList " . $where; } /** * Return insert query string * @param object $query * @param boolean $with_values * @param boolean $with_priority * @return string */ public function getInsertSql($query, $with_values = TRUE, $with_priority = FALSE) { $tableName = $query->getFirstTableName(); $values = $query->getInsertString($with_values); $priority = $with_priority ? $query->getPriority() : ''; return "INSERT $priority INTO $tableName \n $values"; } /** * Return index from slave server list * @return int */ public function _getSlaveConnectionStringIndex() { $max = count($this->slave_db); $indx = rand(0, $max - 1); return $indx; } /** * Return connection resource * @param string $type use 'master' or 'slave'. default value is 'master' * @param int $indx if indx value is NULL, return rand number in slave server list * @return resource */ public function _getConnection($type = 'master', $indx = NULL) { if($type == 'master' || $this->transactionNestedLevel) { if(!$this->master_db['is_connected']) { $this->_connect($type); } $this->connection = 'master (' . $this->master_db['host'] . ')'; return $this->master_db["resource"]; } if($indx === NULL) { $indx = $this->_getSlaveConnectionStringIndex($type); } if($this->slave_db[$indx]['host'] == $this->master_db['host'] && $this->slave_db[$indx]['port'] == $this->master_db['port']) { if(!$this->master_db['is_connected']) { $this->_connect($type); } $this->connection = 'master (' . $this->master_db['host'] . ')'; return $this->master_db["resource"]; } if(!$this->slave_db[$indx]['is_connected']) { $this->_connect($type, $indx); } $this->connection = 'slave (' . $this->slave_db[$indx]['host'] . ')'; return $this->slave_db[$indx]["resource"]; } /** * check db information exists * @return boolean */ public function _dbInfoExists() { return ($this->master_db && count($this->slave_db)); } /** * DB disconnection * * @param resource $connection * @return void */ protected function _close($connection) { } /** * DB disconnection * @param string $type 'master' or 'slave' * @param int $indx number in slave dbms server list * @return void */ public function close($type = 'master', $indx = 0) { if(!$this->isConnected($type, $indx)) { return; } if($type == 'master') { $connection = &$this->master_db; } else { $connection = &$this->slave_db[$indx]; } $this->commit(); $this->_close($connection["resource"]); $connection["is_connected"] = FALSE; } /** * DB transaction start * this method is protected * @return boolean */ protected function _begin($transactionLevel = 0) { return TRUE; } /** * DB transaction start * @return void */ public function begin() { if(!$this->isConnected()) { return; } if($this->_begin($this->transactionNestedLevel)) { $this->transaction_started = TRUE; $this->transactionNestedLevel++; } } /** * DB transaction rollback * this method is protected * @return boolean */ protected function _rollback($transactionLevel = 0) { return TRUE; } /** * DB transaction rollback * @return void */ public function rollback() { if(!$this->isConnected() || !$this->transaction_started) { return; } if($this->_rollback($this->transactionNestedLevel)) { $this->transactionNestedLevel--; if(!$this->transactionNestedLevel) { $this->transaction_started = FALSE; } } } /** * DB transaction commit * this method is protected * @return boolean */ protected function _commit() { return TRUE; } /** * DB transaction commit * @param boolean $force regardless transaction start status or connect status, forced to commit * @return void */ public function commit($force = FALSE) { if(!$force && (!$this->isConnected() || !$this->transaction_started)) { return; } if($this->transactionNestedLevel == 1 && $this->_commit()) { $this->transaction_started = FALSE; $this->transactionNestedLevel = 0; } else { $this->transactionNestedLevel--; } } /** * Execute the query * this method is protected * @param string $query * @param resource $connection * @return void */ protected function __query($query, $connection) { } /** * Execute the query * * @param string $query * @param resource $connection * @return resource */ public function _query($query, $connection = NULL) { if($connection == NULL) { $connection = $this->_getConnection('master'); } // Notify to start a query execution $this->actStart($query); // Run the query statement $result = $this->__query($query, $connection); // Notify to complete a query execution $this->actFinish(); // Return result return $result; } /** * DB info settings * this method is protected * @return void */ protected function _setDBInfo() { $db_info = config('db'); $this->master_db = $db_info['master']; $this->slave_db = $db_info ? array_values($db_info) : null; $this->prefix = $this->master_db['prefix']; $this->use_prepared_statements = config('use_prepared_statements'); } /** * DB Connect * this method is protected * @param array $connection * @return void */ protected function __connect($connection) { } /** * If have a task after connection, add a taks in this method * this method is protected * @param resource $connection * @return void */ protected function _afterConnect($connection) { } /** * DB Connect * this method is protected * @param string $type 'master' or 'slave' * @param int $indx number in slave dbms server list * @return void */ protected function _connect($type = 'master', $indx = 0) { if($this->isConnected($type, $indx)) { return; } // Ignore if no DB information exists if(!$this->_dbInfoExists()) { return; } if($type == 'master') { $connection = &$this->master_db; } else { $connection = &$this->slave_db[$indx]; } $result = $this->__connect($connection); if($result === NULL || $result === FALSE) { $connection["is_connected"] = FALSE; return; } // Check connections $connection["resource"] = $result; $connection["is_connected"] = TRUE; // Save connection info for db logs $this->connection = $type . ' (' . $connection['host'] . ')'; // regist $this->close callback register_shutdown_function(array($this, "close")); $this->_afterConnect($result); } /** * Start recording DBClass log * @return void */ public function actDBClassStart() { $this->setError(0, 'success'); $this->act_dbclass_start = microtime(true); $this->elapsed_dbclass_time = 0; } /** * Finish recording DBClass log * @return void */ public function actDBClassFinish() { if(!$this->query) { return; } $this->act_dbclass_finish = microtime(true); $elapsed_dbclass_time = $this->act_dbclass_finish - $this->act_dbclass_start; $this->elapsed_dbclass_time = $elapsed_dbclass_time; $GLOBALS['__dbclass_elapsed_time__'] += $elapsed_dbclass_time; } /** * Returns a database specific parser instance * used for escaping expressions and table/column identifiers * * Requires an implementation of the DB class (won't work if database is not set) * this method is singleton * * @param boolean $force force load DBParser instance * @return DBParser */ public function getParser($force = FALSE) { static $dbParser = NULL; if(!$dbParser || $force) { $oDB = DB::getInstance(); $dbParser = $oDB->getParser(); } return $dbParser; } } /* End of file DB.class.php */ /* Location: ./classes/db/DB.class.php */
SoneYours/rhymix
classes/db/DB.class.php
PHP
gpl-2.0
27,162
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.iucn.whp.dbservice.service.base; import com.iucn.whp.dbservice.service.inscription_criteria_lkpLocalServiceUtil; import java.util.Arrays; /** * @author Brian Wing Shun Chan */ public class inscription_criteria_lkpLocalServiceClpInvoker { public inscription_criteria_lkpLocalServiceClpInvoker() { _methodName0 = "addinscription_criteria_lkp"; _methodParameterTypes0 = new String[] { "com.iucn.whp.dbservice.model.inscription_criteria_lkp" }; _methodName1 = "createinscription_criteria_lkp"; _methodParameterTypes1 = new String[] { "int" }; _methodName2 = "deleteinscription_criteria_lkp"; _methodParameterTypes2 = new String[] { "int" }; _methodName3 = "deleteinscription_criteria_lkp"; _methodParameterTypes3 = new String[] { "com.iucn.whp.dbservice.model.inscription_criteria_lkp" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "fetchinscription_criteria_lkp"; _methodParameterTypes9 = new String[] { "int" }; _methodName10 = "getinscription_criteria_lkp"; _methodParameterTypes10 = new String[] { "int" }; _methodName11 = "getPersistedModel"; _methodParameterTypes11 = new String[] { "java.io.Serializable" }; _methodName12 = "getinscription_criteria_lkps"; _methodParameterTypes12 = new String[] { "int", "int" }; _methodName13 = "getinscription_criteria_lkpsCount"; _methodParameterTypes13 = new String[] { }; _methodName14 = "updateinscription_criteria_lkp"; _methodParameterTypes14 = new String[] { "com.iucn.whp.dbservice.model.inscription_criteria_lkp" }; _methodName15 = "updateinscription_criteria_lkp"; _methodParameterTypes15 = new String[] { "com.iucn.whp.dbservice.model.inscription_criteria_lkp", "boolean" }; _methodName426 = "getBeanIdentifier"; _methodParameterTypes426 = new String[] { }; _methodName427 = "setBeanIdentifier"; _methodParameterTypes427 = new String[] { "java.lang.String" }; _methodName432 = "getAllInscriptionCriteria"; _methodParameterTypes432 = new String[] { }; } public Object invokeMethod(String name, String[] parameterTypes, Object[] arguments) throws Throwable { if (_methodName0.equals(name) && Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.addinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]); } if (_methodName1.equals(name) && Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.createinscription_criteria_lkp(((Integer)arguments[0]).intValue()); } if (_methodName2.equals(name) && Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.deleteinscription_criteria_lkp(((Integer)arguments[0]).intValue()); } if (_methodName3.equals(name) && Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.deleteinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]); } if (_methodName4.equals(name) && Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.dynamicQuery(); } if (_methodName5.equals(name) && Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]); } if (_methodName6.equals(name) && Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0], ((Integer)arguments[1]).intValue(), ((Integer)arguments[2]).intValue()); } if (_methodName7.equals(name) && Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0], ((Integer)arguments[1]).intValue(), ((Integer)arguments[2]).intValue(), (com.liferay.portal.kernel.util.OrderByComparator)arguments[3]); } if (_methodName8.equals(name) && Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]); } if (_methodName9.equals(name) && Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.fetchinscription_criteria_lkp(((Integer)arguments[0]).intValue()); } if (_methodName10.equals(name) && Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkp(((Integer)arguments[0]).intValue()); } if (_methodName11.equals(name) && Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getPersistedModel((java.io.Serializable)arguments[0]); } if (_methodName12.equals(name) && Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkps(((Integer)arguments[0]).intValue(), ((Integer)arguments[1]).intValue()); } if (_methodName13.equals(name) && Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkpsCount(); } if (_methodName14.equals(name) && Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.updateinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]); } if (_methodName15.equals(name) && Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.updateinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0], ((Boolean)arguments[1]).booleanValue()); } if (_methodName426.equals(name) && Arrays.deepEquals(_methodParameterTypes426, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getBeanIdentifier(); } if (_methodName427.equals(name) && Arrays.deepEquals(_methodParameterTypes427, parameterTypes)) { inscription_criteria_lkpLocalServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]); } if (_methodName432.equals(name) && Arrays.deepEquals(_methodParameterTypes432, parameterTypes)) { return inscription_criteria_lkpLocalServiceUtil.getAllInscriptionCriteria(); } throw new UnsupportedOperationException(); } private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName426; private String[] _methodParameterTypes426; private String _methodName427; private String[] _methodParameterTypes427; private String _methodName432; private String[] _methodParameterTypes432; }
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/src/com/iucn/whp/dbservice/service/base/inscription_criteria_lkpLocalServiceClpInvoker.java
Java
gpl-2.0
9,411
/* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define MYSQL_LEX 1 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" #include "unireg.h" #include "sql_parse.h" // parse_sql #include "strfunc.h" // find_string_in_array #include "sql_db.h" // get_default_db_collation #include "sql_time.h" // interval_type_to_name, // date_add_interval, // calc_time_diff #include "tztime.h" // my_tz_find, my_tz_OFFSET0, struct Time_zone #include "sql_acl.h" // EVENT_ACL, SUPER_ACL #include "sp.h" // load_charset, load_collation #include "events.h" #include "event_data_objects.h" #include "event_db_repository.h" #include "sp_head.h" #include "sql_show.h" // append_definer, append_identifier /** @addtogroup Event_Scheduler @{ */ /*************************************************************************/ /** Event_creation_ctx -- creation context of events. */ class Event_creation_ctx :public Stored_program_creation_ctx, public Sql_alloc { public: static bool load_from_db(THD *thd, MEM_ROOT *event_mem_root, const char *db_name, const char *event_name, TABLE *event_tbl, Stored_program_creation_ctx **ctx); public: virtual Stored_program_creation_ctx *clone(MEM_ROOT *mem_root) { return new (mem_root) Event_creation_ctx(m_client_cs, m_connection_cl, m_db_cl); } protected: virtual Object_creation_ctx *create_backup_ctx(THD *thd) const { /* We can avoid usual backup/restore employed in stored programs since we know that this is a top level statement and the worker thread is allocated exclusively to execute this event. */ return NULL; } private: Event_creation_ctx(const CHARSET_INFO *client_cs, const CHARSET_INFO *connection_cl, const CHARSET_INFO *db_cl) : Stored_program_creation_ctx(client_cs, connection_cl, db_cl) { } }; /************************************************************************** Event_creation_ctx implementation. **************************************************************************/ bool Event_creation_ctx::load_from_db(THD *thd, MEM_ROOT *event_mem_root, const char *db_name, const char *event_name, TABLE *event_tbl, Stored_program_creation_ctx **ctx) { /* Load character set/collation attributes. */ const CHARSET_INFO *client_cs; const CHARSET_INFO *connection_cl; const CHARSET_INFO *db_cl; bool invalid_creation_ctx= FALSE; if (load_charset(event_mem_root, event_tbl->field[ET_FIELD_CHARACTER_SET_CLIENT], thd->variables.character_set_client, &client_cs)) { sql_print_warning("Event '%s'.'%s': invalid value " "in column mysql.event.character_set_client.", (const char *) db_name, (const char *) event_name); invalid_creation_ctx= TRUE; } if (load_collation(event_mem_root, event_tbl->field[ET_FIELD_COLLATION_CONNECTION], thd->variables.collation_connection, &connection_cl)) { sql_print_warning("Event '%s'.'%s': invalid value " "in column mysql.event.collation_connection.", (const char *) db_name, (const char *) event_name); invalid_creation_ctx= TRUE; } if (load_collation(event_mem_root, event_tbl->field[ET_FIELD_DB_COLLATION], NULL, &db_cl)) { sql_print_warning("Event '%s'.'%s': invalid value " "in column mysql.event.db_collation.", (const char *) db_name, (const char *) event_name); invalid_creation_ctx= TRUE; } /* If we failed to resolve the database collation, load the default one from the disk. */ if (!db_cl) db_cl= get_default_db_collation(thd, db_name); /* Create the context. */ *ctx= new Event_creation_ctx(client_cs, connection_cl, db_cl); return invalid_creation_ctx; } /*************************************************************************/ /* Initiliazes dbname and name of an Event_queue_element_for_exec object SYNOPSIS Event_queue_element_for_exec::init() RETURN VALUE FALSE OK TRUE Error (OOM) */ bool Event_queue_element_for_exec::init(LEX_STRING db, LEX_STRING n) { if (!(dbname.str= my_strndup(db.str, dbname.length= db.length, MYF(MY_WME)))) return TRUE; if (!(name.str= my_strndup(n.str, name.length= n.length, MYF(MY_WME)))) { my_free(dbname.str); return TRUE; } return FALSE; } /* Destructor SYNOPSIS Event_queue_element_for_exec::~Event_queue_element_for_exec() */ Event_queue_element_for_exec::~Event_queue_element_for_exec() { my_free(dbname.str); my_free(name.str); } /* Constructor SYNOPSIS Event_basic::Event_basic() */ Event_basic::Event_basic() { DBUG_ENTER("Event_basic::Event_basic"); /* init memory root */ init_sql_alloc(&mem_root, 256, 512); dbname.str= name.str= NULL; dbname.length= name.length= 0; time_zone= NULL; DBUG_VOID_RETURN; } /* Destructor SYNOPSIS Event_basic::Event_basic() */ Event_basic::~Event_basic() { DBUG_ENTER("Event_basic::~Event_basic"); free_root(&mem_root, MYF(0)); DBUG_VOID_RETURN; } /* Short function to load a char column into a LEX_STRING SYNOPSIS Event_basic::load_string_field() field_name The field( enum_events_table_field is not actually used because it's unknown in event_data_objects.h) fields The Field array field_value The value */ bool Event_basic::load_string_fields(Field **fields, ...) { bool ret= FALSE; va_list args; enum enum_events_table_field field_name; LEX_STRING *field_value; DBUG_ENTER("Event_basic::load_string_fields"); va_start(args, fields); field_name= (enum enum_events_table_field) va_arg(args, int); while (field_name < ET_FIELD_COUNT) { field_value= va_arg(args, LEX_STRING *); if ((field_value->str= get_field(&mem_root, fields[field_name])) == NullS) { ret= TRUE; break; } field_value->length= strlen(field_value->str); field_name= (enum enum_events_table_field) va_arg(args, int); } va_end(args); DBUG_RETURN(ret); } bool Event_basic::load_time_zone(THD *thd, const LEX_STRING tz_name) { String str(tz_name.str, &my_charset_latin1); time_zone= my_tz_find(thd, &str); return (time_zone == NULL); } /* Constructor SYNOPSIS Event_queue_element::Event_queue_element() */ Event_queue_element::Event_queue_element(): on_completion(Event_parse_data::ON_COMPLETION_DROP), status(Event_parse_data::ENABLED), expression(0), dropped(FALSE), execution_count(0) { DBUG_ENTER("Event_queue_element::Event_queue_element"); starts= ends= execute_at= last_executed= 0; starts_null= ends_null= execute_at_null= TRUE; DBUG_VOID_RETURN; } /* Destructor SYNOPSIS Event_queue_element::Event_queue_element() */ Event_queue_element::~Event_queue_element() { } /* Constructor SYNOPSIS Event_timed::Event_timed() */ Event_timed::Event_timed(): created(0), modified(0), sql_mode(0) { DBUG_ENTER("Event_timed::Event_timed"); init(); DBUG_VOID_RETURN; } /* Destructor SYNOPSIS Event_timed::~Event_timed() */ Event_timed::~Event_timed() { } /* Constructor SYNOPSIS Event_job_data::Event_job_data() */ Event_job_data::Event_job_data() :sql_mode(0) { } /* Init all member variables SYNOPSIS Event_timed::init() */ void Event_timed::init() { DBUG_ENTER("Event_timed::init"); definer_user.str= definer_host.str= body.str= comment.str= NULL; definer_user.length= definer_host.length= body.length= comment.length= 0; sql_mode= 0; DBUG_VOID_RETURN; } /** Load an event's body from a row from mysql.event. @details This method is silent on errors and should behave like that. Callers should handle throwing of error messages. The reason is that the class should not know about how to deal with communication. @return Operation status @retval FALSE OK @retval TRUE Error */ bool Event_job_data::load_from_row(THD *thd, TABLE *table) { char *ptr; size_t len; LEX_STRING tz_name; DBUG_ENTER("Event_job_data::load_from_row"); if (!table) DBUG_RETURN(TRUE); if (table->s->fields < ET_FIELD_COUNT) DBUG_RETURN(TRUE); if (load_string_fields(table->field, ET_FIELD_DB, &dbname, ET_FIELD_NAME, &name, ET_FIELD_BODY, &body, ET_FIELD_DEFINER, &definer, ET_FIELD_TIME_ZONE, &tz_name, ET_FIELD_COUNT)) DBUG_RETURN(TRUE); if (load_time_zone(thd, tz_name)) DBUG_RETURN(TRUE); Event_creation_ctx::load_from_db(thd, &mem_root, dbname.str, name.str, table, &creation_ctx); ptr= strchr(definer.str, '@'); if (! ptr) ptr= definer.str; len= ptr - definer.str; definer_user.str= strmake_root(&mem_root, definer.str, len); definer_user.length= len; len= definer.length - len - 1; /* 1:because of @ */ definer_host.str= strmake_root(&mem_root, ptr + 1, len); definer_host.length= len; sql_mode= (sql_mode_t) table->field[ET_FIELD_SQL_MODE]->val_int(); DBUG_RETURN(FALSE); } /** Load an event's body from a row from mysql.event. @details This method is silent on errors and should behave like that. Callers should handle throwing of error messages. The reason is that the class should not know about how to deal with communication. @return Operation status @retval FALSE OK @retval TRUE Error */ bool Event_queue_element::load_from_row(THD *thd, TABLE *table) { char *ptr; MYSQL_TIME time; LEX_STRING tz_name; DBUG_ENTER("Event_queue_element::load_from_row"); if (!table) DBUG_RETURN(TRUE); if (table->s->fields < ET_FIELD_COUNT) DBUG_RETURN(TRUE); if (load_string_fields(table->field, ET_FIELD_DB, &dbname, ET_FIELD_NAME, &name, ET_FIELD_DEFINER, &definer, ET_FIELD_TIME_ZONE, &tz_name, ET_FIELD_COUNT)) DBUG_RETURN(TRUE); if (load_time_zone(thd, tz_name)) DBUG_RETURN(TRUE); starts_null= table->field[ET_FIELD_STARTS]->is_null(); my_bool not_used= FALSE; if (!starts_null) { table->field[ET_FIELD_STARTS]->get_date(&time, TIME_NO_ZERO_DATE); starts= my_tz_OFFSET0->TIME_to_gmt_sec(&time,&not_used); } ends_null= table->field[ET_FIELD_ENDS]->is_null(); if (!ends_null) { table->field[ET_FIELD_ENDS]->get_date(&time, TIME_NO_ZERO_DATE); ends= my_tz_OFFSET0->TIME_to_gmt_sec(&time,&not_used); } if (!table->field[ET_FIELD_INTERVAL_EXPR]->is_null()) expression= table->field[ET_FIELD_INTERVAL_EXPR]->val_int(); else expression= 0; /* If neigher STARTS and ENDS is set, then both fields are empty. Hence, if ET_FIELD_EXECUTE_AT is empty there is an error. */ execute_at_null= table->field[ET_FIELD_EXECUTE_AT]->is_null(); DBUG_ASSERT(!(starts_null && ends_null && !expression && execute_at_null)); if (!expression && !execute_at_null) { if (table->field[ET_FIELD_EXECUTE_AT]->get_date(&time, TIME_NO_ZERO_DATE)) DBUG_RETURN(TRUE); execute_at= my_tz_OFFSET0->TIME_to_gmt_sec(&time,&not_used); } /* We load the interval type from disk as string and then map it to an integer. This decouples the values of enum interval_type and values actually stored on disk. Therefore the type can be reordered without risking incompatibilities of data between versions. */ if (!table->field[ET_FIELD_TRANSIENT_INTERVAL]->is_null()) { int i; char buff[MAX_FIELD_WIDTH]; String str(buff, sizeof(buff), &my_charset_bin); LEX_STRING tmp; table->field[ET_FIELD_TRANSIENT_INTERVAL]->val_str(&str); if (!(tmp.length= str.length())) DBUG_RETURN(TRUE); tmp.str= str.c_ptr_safe(); i= find_string_in_array(interval_type_to_name, &tmp, system_charset_info); if (i < 0) DBUG_RETURN(TRUE); interval= (interval_type) i; } if (!table->field[ET_FIELD_LAST_EXECUTED]->is_null()) { table->field[ET_FIELD_LAST_EXECUTED]->get_date(&time, TIME_NO_ZERO_DATE); last_executed= my_tz_OFFSET0->TIME_to_gmt_sec(&time,&not_used); } if ((ptr= get_field(&mem_root, table->field[ET_FIELD_STATUS])) == NullS) DBUG_RETURN(TRUE); DBUG_PRINT("load_from_row", ("Event [%s] is [%s]", name.str, ptr)); /* Set event status (ENABLED | SLAVESIDE_DISABLED | DISABLED) */ switch (ptr[0]) { case 'E' : status = Event_parse_data::ENABLED; break; case 'S' : status = Event_parse_data::SLAVESIDE_DISABLED; break; case 'D' : default: status = Event_parse_data::DISABLED; break; } if ((ptr= get_field(&mem_root, table->field[ET_FIELD_ORIGINATOR])) == NullS) DBUG_RETURN(TRUE); originator = table->field[ET_FIELD_ORIGINATOR]->val_int(); /* ToDo : Andrey . Find a way not to allocate ptr on event_mem_root */ if ((ptr= get_field(&mem_root, table->field[ET_FIELD_ON_COMPLETION])) == NullS) DBUG_RETURN(TRUE); on_completion= (ptr[0]=='D'? Event_parse_data::ON_COMPLETION_DROP: Event_parse_data::ON_COMPLETION_PRESERVE); DBUG_RETURN(FALSE); } /** Load an event's body from a row from mysql.event. @details This method is silent on errors and should behave like that. Callers should handle throwing of error messages. The reason is that the class should not know about how to deal with communication. @return Operation status @retval FALSE OK @retval TRUE Error */ bool Event_timed::load_from_row(THD *thd, TABLE *table) { char *ptr; size_t len; DBUG_ENTER("Event_timed::load_from_row"); if (Event_queue_element::load_from_row(thd, table)) DBUG_RETURN(TRUE); if (load_string_fields(table->field, ET_FIELD_BODY, &body, ET_FIELD_BODY_UTF8, &body_utf8, ET_FIELD_COUNT)) DBUG_RETURN(TRUE); if (Event_creation_ctx::load_from_db(thd, &mem_root, dbname.str, name.str, table, &creation_ctx)) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_EVENT_INVALID_CREATION_CTX, ER(ER_EVENT_INVALID_CREATION_CTX), (const char *) dbname.str, (const char *) name.str); } ptr= strchr(definer.str, '@'); if (! ptr) ptr= definer.str; len= ptr - definer.str; definer_user.str= strmake_root(&mem_root, definer.str, len); definer_user.length= len; len= definer.length - len - 1; /* 1:because of @ */ definer_host.str= strmake_root(&mem_root, ptr + 1, len); definer_host.length= len; created= table->field[ET_FIELD_CREATED]->val_int(); modified= table->field[ET_FIELD_MODIFIED]->val_int(); comment.str= get_field(&mem_root, table->field[ET_FIELD_COMMENT]); if (comment.str != NullS) comment.length= strlen(comment.str); else comment.length= 0; sql_mode= (sql_mode_t) table->field[ET_FIELD_SQL_MODE]->val_int(); DBUG_RETURN(FALSE); } /* add_interval() adds a specified interval to time 'ltime' in time zone 'time_zone', and returns the result converted to the number of seconds since epoch (aka Unix time; in UTC time zone). Zero result means an error. */ static my_time_t add_interval(MYSQL_TIME *ltime, const Time_zone *time_zone, interval_type scale, INTERVAL interval) { if (date_add_interval(ltime, scale, interval)) return 0; my_bool not_used; return time_zone->TIME_to_gmt_sec(ltime, &not_used); } /* Computes the sum of a timestamp plus interval. SYNOPSIS get_next_time() time_zone event time zone next the sum start add interval_value to this time time_now current time i_value quantity of time type interval to add i_type type of interval to add (SECOND, MINUTE, HOUR, WEEK ...) RETURN VALUE 0 OK 1 Error NOTES 1) If the interval is conversible to SECOND, like MINUTE, HOUR, DAY, WEEK. Then we use TIMEDIFF()'s implementation as underlying and number of seconds as resolution for computation. 2) In all other cases - MONTH, QUARTER, YEAR we use MONTH as resolution and PERIOD_DIFF()'s implementation */ static bool get_next_time(const Time_zone *time_zone, my_time_t *next, my_time_t start, my_time_t time_now, int i_value, interval_type i_type) { DBUG_ENTER("get_next_time"); DBUG_PRINT("enter", ("start: %lu now: %lu", (long) start, (long) time_now)); DBUG_ASSERT(start <= time_now); longlong months=0, seconds=0; switch (i_type) { case INTERVAL_YEAR: months= i_value*12; break; case INTERVAL_QUARTER: /* Has already been converted to months */ case INTERVAL_YEAR_MONTH: case INTERVAL_MONTH: months= i_value; break; case INTERVAL_WEEK: /* WEEK has already been converted to days */ case INTERVAL_DAY: seconds= i_value*24*3600; break; case INTERVAL_DAY_HOUR: case INTERVAL_HOUR: seconds= i_value*3600; break; case INTERVAL_DAY_MINUTE: case INTERVAL_HOUR_MINUTE: case INTERVAL_MINUTE: seconds= i_value*60; break; case INTERVAL_DAY_SECOND: case INTERVAL_HOUR_SECOND: case INTERVAL_MINUTE_SECOND: case INTERVAL_SECOND: seconds= i_value; break; case INTERVAL_DAY_MICROSECOND: case INTERVAL_HOUR_MICROSECOND: case INTERVAL_MINUTE_MICROSECOND: case INTERVAL_SECOND_MICROSECOND: case INTERVAL_MICROSECOND: /* We should return an error here so SHOW EVENTS/ SELECT FROM I_S.EVENTS would give an error then. */ DBUG_RETURN(1); break; case INTERVAL_LAST: DBUG_ASSERT(0); } DBUG_PRINT("info", ("seconds: %ld months: %ld", (long) seconds, (long) months)); MYSQL_TIME local_start; MYSQL_TIME local_now; /* Convert times from UTC to local. */ { time_zone->gmt_sec_to_TIME(&local_start, start); time_zone->gmt_sec_to_TIME(&local_now, time_now); } INTERVAL interval; memset(&interval, 0, sizeof(interval)); my_time_t next_time= 0; if (seconds) { longlong seconds_diff; long microsec_diff; bool negative= calc_time_diff(&local_now, &local_start, 1, &seconds_diff, &microsec_diff); if (!negative) { /* The formula below returns the interval that, when added to local_start, will always give the time in the future. */ interval.second= seconds_diff - seconds_diff % seconds + seconds; next_time= add_interval(&local_start, time_zone, INTERVAL_SECOND, interval); if (next_time == 0) goto done; } if (next_time <= time_now) { /* If 'negative' is true above, then 'next_time == 0', and 'next_time <= time_now' is also true. If negative is false, then next_time was set, but perhaps to the value that is less then time_now. See below for elaboration. */ DBUG_ASSERT(negative || next_time > 0); /* If local_now < local_start, i.e. STARTS time is in the future according to the local time (it always in the past according to UTC---this is a prerequisite of this function), then STARTS is almost always in the past according to the local time too. However, in the time zone that has backward Daylight Saving Time shift, the following may happen: suppose we have a backward DST shift at certain date after 2:59:59, i.e. local time goes 1:59:59, 2:00:00, ... , 2:59:59, (shift here) 2:00:00 (again), ... , 2:59:59 (again), 3:00:00, ... . Now suppose the time has passed the first 2:59:59, has been shifted backward, and now is (the second) 2:20:00. The user does CREATE EVENT with STARTS 'current-date 2:40:00'. Local time 2:40:00 from create statement is treated by time functions as the first such time, so according to UTC it comes before the second 2:20:00. But according to local time it is obviously in the future, so we end up in this branch. Since we are in the second pass through 2:00:00--2:59:59, and any local time form this interval is treated by system functions as the time from the first pass, we have to find the time for the next execution that is past the DST-affected interval (past the second 2:59:59 for our example, i.e. starting from 3:00:00). We do this in the loop until the local time is mapped onto future UTC time. 'start' time is in the past, so we may use 'do { } while' here, and add the first interval right away. Alternatively, it could be that local_now >= local_start. Now for the example above imagine we do CREATE EVENT with STARTS 'current-date 2:10:00'. Local start 2:10 is in the past (now is local 2:20), so we add an interval, and get next execution time, say, 2:40. It is in the future according to local time, but, again, since we are in the second pass through 2:00:00--2:59:59, 2:40 will be converted into UTC time in the past. So we will end up in this branch again, and may add intervals in a 'do { } while' loop. Note that for any given event we may end up here only if event next execution time will map to the time interval that is passed twice, and only if the server was started during the second pass, or the event is being created during the second pass. After that, we never will get here (unless we again start the server during the second pass). In other words, such a condition is extremely rare. */ interval.second= seconds; do { next_time= add_interval(&local_start, time_zone, INTERVAL_SECOND, interval); if (next_time == 0) goto done; } while (next_time <= time_now); } } else { long diff_months= ((long) local_now.year - (long) local_start.year)*12 + ((long) local_now.month - (long) local_start.month); /* Unlike for seconds above, the formula below returns the interval that, when added to the local_start, will give the time in the past, or somewhere in the current month. We are interested in the latter case, to see if this time has already passed, or is yet to come this month. Note that the time is guaranteed to be in the past unless (diff_months % months == 0), but no good optimization is possible here, because (diff_months % months == 0) is what will happen most of the time, as get_next_time() will be called right after the execution of the event. We could pass last_executed time to this function, and see if the execution has already happened this month, but for that we will have to convert last_executed from seconds since epoch to local broken-down time, and this will greatly reduce the effect of the optimization. So instead we keep the code simple and clean. */ interval.month= (ulong) (diff_months - diff_months % months); next_time= add_interval(&local_start, time_zone, INTERVAL_MONTH, interval); if (next_time == 0) goto done; if (next_time <= time_now) { interval.month= (ulong) months; next_time= add_interval(&local_start, time_zone, INTERVAL_MONTH, interval); if (next_time == 0) goto done; } } DBUG_ASSERT(time_now < next_time); *next= next_time; done: DBUG_PRINT("info", ("next_time: %ld", (long) next_time)); DBUG_RETURN(next_time == 0); } /* Computes next execution time. SYNOPSIS Event_queue_element::compute_next_execution_time() RETURN VALUE FALSE OK TRUE Error NOTES The time is set in execute_at, if no more executions the latter is set to 0. */ bool Event_queue_element::compute_next_execution_time() { my_time_t time_now; DBUG_ENTER("Event_queue_element::compute_next_execution_time"); DBUG_PRINT("enter", ("starts: %lu ends: %lu last_executed: %lu this: 0x%lx", (long) starts, (long) ends, (long) last_executed, (long) this)); if (status != Event_parse_data::ENABLED) { DBUG_PRINT("compute_next_execution_time", ("Event %s is DISABLED", name.str)); goto ret; } /* If one-time, no need to do computation */ if (!expression) { /* Let's check whether it was executed */ if (last_executed) { DBUG_PRINT("info",("One-time event %s.%s of was already executed", dbname.str, name.str)); dropped= (on_completion == Event_parse_data::ON_COMPLETION_DROP); DBUG_PRINT("info",("One-time event will be dropped: %d.", dropped)); status= Event_parse_data::DISABLED; } goto ret; } time_now= (my_time_t) current_thd->query_start(); DBUG_PRINT("info",("NOW: [%lu]", (ulong) time_now)); /* if time_now is after ends don't execute anymore */ if (!ends_null && ends < time_now) { DBUG_PRINT("info", ("NOW after ENDS, don't execute anymore")); /* time_now is after ends. don't execute anymore */ execute_at= 0; execute_at_null= TRUE; if (on_completion == Event_parse_data::ON_COMPLETION_DROP) dropped= TRUE; DBUG_PRINT("info", ("Dropped: %d", dropped)); status= Event_parse_data::DISABLED; goto ret; } /* Here time_now is before or equals ends if the latter is set. Let's check whether time_now is before starts. If so schedule for starts. */ if (!starts_null && time_now <= starts) { if (time_now == starts && starts == last_executed) { /* do nothing or we will schedule for second time execution at starts. */ } else { DBUG_PRINT("info", ("STARTS is future, NOW <= STARTS,sched for STARTS")); /* starts is in the future time_now before starts. Scheduling for starts */ execute_at= starts; execute_at_null= FALSE; goto ret; } } if (!starts_null && !ends_null) { /* Both starts and m_ends are set and time_now is between them (incl.) If last_executed is set then increase with m_expression. The new MYSQL_TIME is after m_ends set execute_at to 0. And check for on_completion If not set then schedule for now. */ DBUG_PRINT("info", ("Both STARTS & ENDS are set")); if (!last_executed) { DBUG_PRINT("info", ("Not executed so far.")); } { my_time_t next_exec; if (get_next_time(time_zone, &next_exec, starts, time_now, (int) expression, interval)) goto err; /* There was previous execution */ if (ends < next_exec) { DBUG_PRINT("info", ("Next execution of %s after ENDS. Stop executing.", name.str)); /* Next execution after ends. No more executions */ execute_at= 0; execute_at_null= TRUE; if (on_completion == Event_parse_data::ON_COMPLETION_DROP) dropped= TRUE; status= Event_parse_data::DISABLED; } else { DBUG_PRINT("info",("Next[%lu]", (ulong) next_exec)); execute_at= next_exec; execute_at_null= FALSE; } } goto ret; } else if (starts_null && ends_null) { /* starts is always set, so this is a dead branch !! */ DBUG_PRINT("info", ("Neither STARTS nor ENDS are set")); /* Both starts and m_ends are not set, so we schedule for the next based on last_executed. */ if (last_executed) { my_time_t next_exec; if (get_next_time(time_zone, &next_exec, starts, time_now, (int) expression, interval)) goto err; execute_at= next_exec; DBUG_PRINT("info",("Next[%lu]", (ulong) next_exec)); } else { /* last_executed not set. Schedule the event for now */ DBUG_PRINT("info", ("Execute NOW")); execute_at= time_now; } execute_at_null= FALSE; } else { /* either starts or m_ends is set */ if (!starts_null) { DBUG_PRINT("info", ("STARTS is set")); /* - starts is set. - starts is not in the future according to check made before Hence schedule for starts + m_expression in case last_executed is not set, otherwise to last_executed + m_expression */ if (!last_executed) { DBUG_PRINT("info", ("Not executed so far.")); } { my_time_t next_exec; if (get_next_time(time_zone, &next_exec, starts, time_now, (int) expression, interval)) goto err; execute_at= next_exec; DBUG_PRINT("info",("Next[%lu]", (ulong) next_exec)); } execute_at_null= FALSE; } else { /* this is a dead branch, because starts is always set !!! */ DBUG_PRINT("info", ("STARTS is not set. ENDS is set")); /* - m_ends is set - m_ends is after time_now or is equal Hence check for m_last_execute and increment with m_expression. If last_executed is not set then schedule for now */ if (!last_executed) execute_at= time_now; else { my_time_t next_exec; if (get_next_time(time_zone, &next_exec, starts, time_now, (int) expression, interval)) goto err; if (ends < next_exec) { DBUG_PRINT("info", ("Next execution after ENDS. Stop executing.")); execute_at= 0; execute_at_null= TRUE; status= Event_parse_data::DISABLED; if (on_completion == Event_parse_data::ON_COMPLETION_DROP) dropped= TRUE; } else { DBUG_PRINT("info", ("Next[%lu]", (ulong) next_exec)); execute_at= next_exec; execute_at_null= FALSE; } } } goto ret; } ret: DBUG_PRINT("info", ("ret: 0 execute_at: %lu", (long) execute_at)); DBUG_RETURN(FALSE); err: DBUG_PRINT("info", ("ret=1")); DBUG_RETURN(TRUE); } /* Set the internal last_executed MYSQL_TIME struct to now. NOW is the time according to thd->query_start(), so the THD's clock. SYNOPSIS Event_queue_element::mark_last_executed() thd thread context */ void Event_queue_element::mark_last_executed(THD *thd) { last_executed= (my_time_t) thd->query_start(); execution_count++; } static void append_datetime(String *buf, Time_zone *time_zone, my_time_t secs, const char *name, uint len) { char dtime_buff[20*2+32];/* +32 to make my_snprintf_{8bit|ucs2} happy */ buf->append(STRING_WITH_LEN(" ")); buf->append(name, len); buf->append(STRING_WITH_LEN(" '")); /* Pass the buffer and the second param tells fills the buffer and returns the number of chars to copy. */ MYSQL_TIME time; time_zone->gmt_sec_to_TIME(&time, secs); buf->append(dtime_buff, my_datetime_to_str(&time, dtime_buff, 0)); buf->append(STRING_WITH_LEN("'")); } /* Get SHOW CREATE EVENT as string SYNOPSIS Event_timed::get_create_event(THD *thd, String *buf) thd Thread buf String*, should be already allocated. CREATE EVENT goes inside. RETURN VALUE 0 OK EVEX_MICROSECOND_UNSUP Error (for now if mysql.event has been tampered and MICROSECONDS interval or derivative has been put there. */ int Event_timed::get_create_event(THD *thd, String *buf) { char tmp_buf[2 * STRING_BUFFER_USUAL_SIZE]; String expr_buf(tmp_buf, sizeof(tmp_buf), system_charset_info); expr_buf.length(0); DBUG_ENTER("get_create_event"); DBUG_PRINT("ret_info",("body_len=[%d]body=[%s]", (int) body.length, body.str)); if (expression && Events::reconstruct_interval_expression(&expr_buf, interval, expression)) DBUG_RETURN(EVEX_MICROSECOND_UNSUP); buf->append(STRING_WITH_LEN("CREATE ")); append_definer(thd, buf, &definer_user, &definer_host); buf->append(STRING_WITH_LEN("EVENT ")); append_identifier(thd, buf, name.str, name.length); if (expression) { buf->append(STRING_WITH_LEN(" ON SCHEDULE EVERY ")); buf->append(expr_buf); buf->append(' '); LEX_STRING *ival= &interval_type_to_name[interval]; buf->append(ival->str, ival->length); if (!starts_null) append_datetime(buf, time_zone, starts, STRING_WITH_LEN("STARTS")); if (!ends_null) append_datetime(buf, time_zone, ends, STRING_WITH_LEN("ENDS")); } else { append_datetime(buf, time_zone, execute_at, STRING_WITH_LEN("ON SCHEDULE AT")); } if (on_completion == Event_parse_data::ON_COMPLETION_DROP) buf->append(STRING_WITH_LEN(" ON COMPLETION NOT PRESERVE ")); else buf->append(STRING_WITH_LEN(" ON COMPLETION PRESERVE ")); if (status == Event_parse_data::ENABLED) buf->append(STRING_WITH_LEN("ENABLE")); else if (status == Event_parse_data::SLAVESIDE_DISABLED) buf->append(STRING_WITH_LEN("DISABLE ON SLAVE")); else buf->append(STRING_WITH_LEN("DISABLE")); if (comment.length) { buf->append(STRING_WITH_LEN(" COMMENT ")); append_unescaped(buf, comment.str, comment.length); } buf->append(STRING_WITH_LEN(" DO ")); buf->append(body.str, body.length); DBUG_RETURN(0); } /** Get an artificial stored procedure to parse as an event definition. */ bool Event_job_data::construct_sp_sql(THD *thd, String *sp_sql) { LEX_STRING buffer; const uint STATIC_SQL_LENGTH= 44; DBUG_ENTER("Event_job_data::construct_sp_sql"); /* Allocate a large enough buffer on the thread execution memory root to avoid multiple [re]allocations on system heap */ buffer.length= STATIC_SQL_LENGTH + name.length + body.length; if (! (buffer.str= (char*) thd->alloc(buffer.length))) DBUG_RETURN(TRUE); sp_sql->set(buffer.str, buffer.length, system_charset_info); sp_sql->length(0); sp_sql->append(C_STRING_WITH_LEN("CREATE ")); sp_sql->append(C_STRING_WITH_LEN("PROCEDURE ")); /* Let's use the same name as the event name to perhaps produce a better error message in case it is a part of some parse error. We're using append_identifier here to successfully parse events with reserved names. */ append_identifier(thd, sp_sql, name.str, name.length); /* The default SQL security of a stored procedure is DEFINER. We have already activated the security context of the event, so let's execute the procedure with the invoker rights to save on resets of security contexts. */ sp_sql->append(C_STRING_WITH_LEN("() SQL SECURITY INVOKER ")); sp_sql->append(body.str, body.length); DBUG_RETURN(thd->is_fatal_error); } /** Get DROP EVENT statement to binlog the drop of ON COMPLETION NOT PRESERVE event. */ bool Event_job_data::construct_drop_event_sql(THD *thd, String *sp_sql) { LEX_STRING buffer; const uint STATIC_SQL_LENGTH= 14; DBUG_ENTER("Event_job_data::construct_drop_event_sql"); buffer.length= STATIC_SQL_LENGTH + name.length*2 + dbname.length*2; if (! (buffer.str= (char*) thd->alloc(buffer.length))) DBUG_RETURN(TRUE); sp_sql->set(buffer.str, buffer.length, system_charset_info); sp_sql->length(0); sp_sql->append(C_STRING_WITH_LEN("DROP EVENT ")); append_identifier(thd, sp_sql, dbname.str, dbname.length); sp_sql->append('.'); append_identifier(thd, sp_sql, name.str, name.length); DBUG_RETURN(thd->is_fatal_error); } /** Compiles and executes the event (the underlying sp_head object) @retval TRUE error (reported to the error log) @retval FALSE success */ bool Event_job_data::execute(THD *thd, bool drop) { String sp_sql; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context event_sctx, *save_sctx= NULL; #endif List<Item> empty_item_list; bool ret= TRUE; sql_digest_state *parent_digest= thd->m_digest; PSI_statement_locker *parent_locker= thd->m_statement_psi; DBUG_ENTER("Event_job_data::execute"); mysql_reset_thd_for_next_command(thd); /* MySQL parser currently assumes that current database is either present in THD or all names in all statements are fully specified. And yet not fully specified names inside stored programs must be be supported, even if the current database is not set: CREATE PROCEDURE db1.p1() BEGIN CREATE TABLE t1; END// -- in this example t1 should be always created in db1 and the statement must parse even if there is no current database. To support this feature and still address the parser limitation, we need to set the current database here. We don't have to call mysql_change_db, since the checks performed in it are unnecessary for the purpose of parsing, and mysql_change_db will be invoked anyway later, to activate the procedure database before it's executed. */ thd->set_db(dbname.str, dbname.length); lex_start(thd); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (event_sctx.change_security_context(thd, &definer_user, &definer_host, &dbname, &save_sctx)) { sql_print_error("Event Scheduler: " "[%s].[%s.%s] execution failed, " "failed to authenticate the user.", definer.str, dbname.str, name.str); goto end; } #endif if (check_access(thd, EVENT_ACL, dbname.str, NULL, NULL, 0, 0)) { /* This aspect of behavior is defined in the worklog, and this is how triggers work too: if TRIGGER privilege is revoked from trigger definer, triggers are not executed. */ sql_print_error("Event Scheduler: " "[%s].[%s.%s] execution failed, " "user no longer has EVENT privilege.", definer.str, dbname.str, name.str); goto end; } if (construct_sp_sql(thd, &sp_sql)) goto end; /* Set up global thread attributes to reflect the properties of this Event. We can simply reset these instead of usual backup/restore employed in stored programs since we know that this is a top level statement and the worker thread is allocated exclusively to execute this event. */ thd->variables.sql_mode= sql_mode; thd->variables.time_zone= time_zone; thd->set_query(sp_sql.c_ptr_safe(), sp_sql.length()); { Parser_state parser_state; if (parser_state.init(thd, thd->query(), thd->query_length())) goto end; thd->m_digest= NULL; thd->m_statement_psi= NULL; if (parse_sql(thd, & parser_state, creation_ctx)) { sql_print_error("Event Scheduler: " "%serror during compilation of %s.%s", thd->is_fatal_error ? "fatal " : "", (const char *) dbname.str, (const char *) name.str); thd->m_digest= parent_digest; thd->m_statement_psi= parent_locker; goto end; } thd->m_digest= parent_digest; thd->m_statement_psi= parent_locker; } { sp_head *sphead= thd->lex->sphead; DBUG_ASSERT(sphead); if (thd->enable_slow_log) sphead->m_flags|= sp_head::LOG_SLOW_STATEMENTS; sphead->m_flags|= sp_head::LOG_GENERAL_LOG; sphead->set_info(0, 0, &thd->lex->sp_chistics, sql_mode); sphead->set_creation_ctx(creation_ctx); sphead->optimize(); ret= sphead->execute_procedure(thd, &empty_item_list); /* There is no pre-locking and therefore there should be no tables open and locked left after execute_procedure. */ } end: if (drop && !thd->is_fatal_error) { /* We must do it here since here we're under the right authentication ID of the event definer. */ sql_print_information("Event Scheduler: Dropping %s.%s", (const char *) dbname.str, (const char *) name.str); /* Construct a query for the binary log, to ensure the event is dropped on the slave */ if (construct_drop_event_sql(thd, &sp_sql)) ret= 1; else { ulong saved_master_access; thd->set_query(sp_sql.c_ptr_safe(), sp_sql.length()); /* NOTE: even if we run in read-only mode, we should be able to lock the mysql.event table for writing. In order to achieve this, we should call mysql_lock_tables() under the super-user. Same goes for transaction access mode. Temporarily reset it to read-write. */ saved_master_access= thd->security_ctx->master_access; thd->security_ctx->master_access |= SUPER_ACL; bool save_tx_read_only= thd->tx_read_only; thd->tx_read_only= false; ret= Events::drop_event(thd, dbname, name, FALSE); thd->tx_read_only= save_tx_read_only; thd->security_ctx->master_access= saved_master_access; } } #ifndef NO_EMBEDDED_ACCESS_CHECKS if (save_sctx) event_sctx.restore_security_context(thd, save_sctx); #endif thd->lex->unit.cleanup(); thd->end_statement(); thd->cleanup_after_query(); /* Avoid races with SHOW PROCESSLIST */ thd->reset_query(); DBUG_PRINT("info", ("EXECUTED %s.%s ret: %d", dbname.str, name.str, ret)); DBUG_RETURN(ret); } /* Checks whether two events are in the same schema SYNOPSIS event_basic_db_equal() db Schema et Compare et->dbname to `db` RETURN VALUE TRUE Equal FALSE Not equal */ bool event_basic_db_equal(LEX_STRING db, Event_basic *et) { return !sortcmp_lex_string(et->dbname, db, system_charset_info); } /* Checks whether an event has equal `db` and `name` SYNOPSIS event_basic_identifier_equal() db Schema name Name et The event object RETURN VALUE TRUE Equal FALSE Not equal */ bool event_basic_identifier_equal(LEX_STRING db, LEX_STRING name, Event_basic *b) { return !sortcmp_lex_string(name, b->name, system_charset_info) && !sortcmp_lex_string(db, b->dbname, system_charset_info); } /** @} (End of group Event_Scheduler) */
facebook/mysql-5.6
sql/event_data_objects.cc
C++
gpl-2.0
44,132
<?php class Inc_Testimonials_Carousel extends Abstract_Inc_Shortcode implements Inc_Shortcode_Designer { static $POST_ID_ATTR = "post_id"; static $COUNT_ATTR = "count"; function render($attr, $inner_content = null, $code = "") { $default_attr = array( Inc_Testimonials_Carousel::$POST_ID_ATTR => '', Inc_Testimonials_Carousel::$COUNT_ATTR => '3', Inc_Carousel_Settings::$CS_AUTO_ATTR => '5',); extract(shortcode_atts($default_attr, $attr)); $content = ''; if (empty($post_id)) { if (isset($inner_content) && !empty($inner_content)) { $inner_content = str_replace("[bq", "<li>[bq", $inner_content); $inner_content = str_replace("[/bq]", "[/bq]</li>", $inner_content); $inner_content = do_shortcode($this->prepare_content($inner_content)); } } else { $inner_content = ''; $post = Post_Util::get_post_by_id($post_id); if ($post) { $count = empty($count) ? 9999 : intval($count); $shortcodes = Post_Util::get_all_shortcodes_of_type('bq', $post); if (count($shortcodes) > 0) { $i = 0; foreach ($shortcodes as $sc) { if ($i < $count) { $inner_content .= '<li>' . do_shortcode($sc) . '</li>'; } $i++; } } } else { return $this->get_error("No post find with the ID: " . $post_id); } } if (isset($inner_content) && !empty($inner_content)) { $id = uniqid('tc-'); $content .= "<ul id=\"$id\" class=\"testimonial-carousel\">$inner_content</ul>"; $carousel_setting = new Inc_Carousel_Settings('#' . $id, $attr, $default_attr); $content .= $carousel_setting->get_carousel_settings(); } return $content; } function get_names() { return array('testimonials_carousel'); } function get_visual_editor_form() { $content = '<form id="sc-testimonials-carousel-form" class="generic-form" method="post" action="#" data-sc="testimonials_carousel">'; $content .= '<fieldset>'; $content .= '<p>' . __('Insert the page ID which contains the testimonials', INCEPTIO_THEME_NAME) . '</p>'; $content .= '<div>'; $content .= '<label for="sc-testimonials-carousel-postid">' . __('Post ID', INCEPTIO_THEME_NAME) . ':</label>'; $content .= '<input id="sc-testimonials-carousel-postid" name="sc-testimonials-carousel-postid" type="text" data-attr-name="' . Inc_Testimonials_Carousel::$POST_ID_ATTR . '" data-attr-type="attr">'; $content .= '</div>'; $content .= '<div>'; $content .= '<label for="sc-testimonials-carousel-count">' . __('No. of Testimonials', INCEPTIO_THEME_NAME) . ':</label>'; $content .= '<input id="sc-testimonials-carousel-count" name="sc-testimonials-carousel-count" type="text" value="3" data-attr-name="' . Inc_Testimonials_Carousel::$COUNT_ATTR . '" data-attr-type="attr">'; $content .= '</div>'; $content .= '<div >'; $content .= '<input id="sc-testimonials-carousel-form-submit" type="submit" name="submit" value="' . __('Insert Testimonials Carousel', INCEPTIO_THEME_NAME) . '" class="button-primary">'; $content .= '</div>'; $content .= '</fieldset>'; $content .= '</form>'; return $content; } function get_group_title() { return __('Dynamic Elements', INCEPTIO_THEME_NAME); } function get_title() { return __('Testimonials Carousel', INCEPTIO_THEME_NAME); } }
arkev/UM-Virtual
wp-content/themes/inceptio/api/shortcode/Inc_Testimonials_Carousel.php
PHP
gpl-2.0
3,818
/*************************************************************************** qgscomposerview.cpp ------------------- begin : January 2005 copyright : (C) 2005 by Radim Blazek email : blazek@itc.it ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <QApplication> #include <QMainWindow> #include <QMouseEvent> #include <QKeyEvent> #include <QClipboard> #include <QMimeData> #include <QGridLayout> #include <QScrollBar> #include <QDesktopWidget> #include "qgsapplication.h" #include "qgscomposerview.h" #include "qgscomposerarrow.h" #include "qgscomposerframe.h" #include "qgscomposerpolygon.h" #include "qgscomposerpolyline.h" #include "qgscomposerhtml.h" #include "qgscomposerlabel.h" #include "qgscomposerlegend.h" #include "qgscomposermap.h" #include "qgscomposermousehandles.h" #include "qgscomposeritemgroup.h" #include "qgscomposerpicture.h" #include "qgscomposerruler.h" #include "qgscomposerscalebar.h" #include "qgscomposershape.h" #include "qgscomposerattributetablev2.h" #include "qgsaddremovemultiframecommand.h" #include "qgspaperitem.h" #include "qgsmapcanvas.h" #include "qgscursors.h" #include "qgscomposerutils.h" #include "qgssettings.h" #define MIN_VIEW_SCALE 0.05 #define MAX_VIEW_SCALE 1000.0 QgsComposerView::QgsComposerView( QWidget *parent, const char *name, Qt::WindowFlags f ) : QGraphicsView( parent ) , mCurrentTool( Select ) , mPreviousTool( Select ) , mRubberBandItem( nullptr ) , mRubberBandLineItem( nullptr ) , mMoveContentItem( nullptr ) , mMarqueeSelect( false ) , mMarqueeZoom( false ) , mTemporaryZoomStatus( QgsComposerView::Inactive ) , mPaintingEnabled( true ) , mHorizontalRuler( nullptr ) , mVerticalRuler( nullptr ) , mMoveContentSearchRadius( 25 ) , mNodesItem( nullptr ) , mNodesItemIndex( -1 ) , mToolPanning( false ) , mMousePanning( false ) , mKeyPanning( false ) , mMovingItemContent( false ) , mPreviewEffect( nullptr ) { Q_UNUSED( f ); Q_UNUSED( name ); setResizeAnchor( QGraphicsView::AnchorViewCenter ); setMouseTracking( true ); viewport()->setMouseTracking( true ); setFrameShape( QFrame::NoFrame ); mPreviewEffect = new QgsPreviewEffect( this ); viewport()->setGraphicsEffect( mPreviewEffect ); } void QgsComposerView::setCurrentTool( QgsComposerView::Tool t ) { mCurrentTool = t; //update mouse cursor for current tool if ( !composition() ) { return; } // do not display points of NodesItem by default mNodesItemIndex = -1; mNodesItem = nullptr; mPolygonItem.reset(); mPolylineItem.reset(); displayNodes( false ); deselectNode(); switch ( t ) { case QgsComposerView::Pan: { //lock cursor to prevent composer items changing it composition()->setPreventCursorChange( true ); viewport()->setCursor( defaultCursorForTool( Pan ) ); break; } case QgsComposerView::Zoom: { //lock cursor to prevent composer items changing it composition()->setPreventCursorChange( true ); //set the cursor to zoom in viewport()->setCursor( defaultCursorForTool( Zoom ) ); break; } case QgsComposerView::AddArrow: case QgsComposerView::AddHtml: case QgsComposerView::AddMap: case QgsComposerView::AddLegend: case QgsComposerView::AddLabel: case QgsComposerView::AddScalebar: case QgsComposerView::AddPicture: case QgsComposerView::AddRectangle: case QgsComposerView::AddEllipse: case QgsComposerView::AddPolygon: case QgsComposerView::AddPolyline: case QgsComposerView::AddTriangle: case QgsComposerView::AddTable: case QgsComposerView::AddAttributeTable: { //using a drawing tool //lock cursor to prevent composer items changing it composition()->setPreventCursorChange( true ); viewport()->setCursor( defaultCursorForTool( mCurrentTool ) ); break; } case QgsComposerView::EditNodesItem: { composition()->setPreventCursorChange( true ); viewport()->setCursor( defaultCursorForTool( mCurrentTool ) ); displayNodes(); break; } default: { //not using pan tool, composer items can change cursor composition()->setPreventCursorChange( false ); viewport()->setCursor( Qt::ArrowCursor ); } } } void QgsComposerView::mousePressEvent( QMouseEvent *e ) { if ( !composition() ) { return; } if ( mRubberBandItem || mRubberBandLineItem || mKeyPanning || mMousePanning || mToolPanning || mMovingItemContent ) { //ignore clicks during certain operations return; } if ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) { //ignore clicks while dragging/resizing items return; } QPointF scenePoint = mapToScene( e->pos() ); QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint ); mMousePressStartPos = e->pos(); if ( e->button() == Qt::RightButton ) { //ignore right clicks for now //TODO - show context menu return; } else if ( e->button() == Qt::MidButton ) { //pan composer with middle button mMousePanning = true; mMouseLastXY = e->pos(); if ( composition() ) { //lock cursor to closed hand cursor composition()->setPreventCursorChange( true ); } viewport()->setCursor( Qt::ClosedHandCursor ); return; } switch ( mCurrentTool ) { //select/deselect items and pass mouse event further case Select: { //check if we are clicking on a selection handle if ( composition()->selectionHandles()->isVisible() ) { //selection handles are being shown, get mouse action for current cursor position QgsComposerMouseHandles::MouseAction mouseAction = composition()->selectionHandles()->mouseActionForScenePos( scenePoint ); if ( mouseAction != QgsComposerMouseHandles::MoveItem && mouseAction != QgsComposerMouseHandles::NoAction && mouseAction != QgsComposerMouseHandles::SelectItem ) { //mouse is over a resize handle, so propagate event onward QGraphicsView::mousePressEvent( e ); return; } } QgsComposerItem *selectedItem = nullptr; QgsComposerItem *previousSelectedItem = nullptr; if ( e->modifiers() & Qt::ControlModifier ) { //CTRL modifier, so we are trying to select the next item below the current one //first, find currently selected item QList<QgsComposerItem *> selectedItems = composition()->selectedComposerItems(); if ( !selectedItems.isEmpty() ) { previousSelectedItem = selectedItems.at( 0 ); } } if ( previousSelectedItem ) { //select highest item just below previously selected item at position of event selectedItem = composition()->composerItemAt( scenePoint, previousSelectedItem, true ); //if we didn't find a lower item we'll use the top-most as fall-back //this duplicates mapinfo/illustrator/etc behavior where ctrl-clicks are "cyclic" if ( !selectedItem ) { selectedItem = composition()->composerItemAt( scenePoint, true ); } } else { //select topmost item at position of event selectedItem = composition()->composerItemAt( scenePoint, true ); } if ( !selectedItem ) { //not clicking over an item, so start marquee selection startMarqueeSelect( scenePoint ); break; } if ( ( !selectedItem->selected() ) && //keep selection if an already selected item pressed !( e->modifiers() & Qt::ShiftModifier ) ) //keep selection if shift key pressed { composition()->setAllDeselected(); } if ( ( e->modifiers() & Qt::ShiftModifier ) && ( selectedItem->selected() ) ) { //SHIFT-clicking a selected item deselects it selectedItem->setSelected( false ); //Check if we have any remaining selected items, and if so, update the item panel QList<QgsComposerItem *> selectedItems = composition()->selectedComposerItems(); if ( !selectedItems.isEmpty() ) { emit selectedItemChanged( selectedItems.at( 0 ) ); } } else { selectedItem->setSelected( true ); QGraphicsView::mousePressEvent( e ); emit selectedItemChanged( selectedItem ); } break; } case Zoom: { if ( !( e->modifiers() & Qt::AltModifier ) ) { //zoom in action startMarqueeZoom( scenePoint ); } else { //zoom out action, so zoom out and recenter on clicked point double scaleFactor = 2; //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); //transform the mouse pos to scene coordinates QPointF scenePoint = mapToScene( e->pos() ); visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() ); QRectF boundsRect = visibleRect.toRectF(); //zoom view to fit desired bounds fitInView( boundsRect, Qt::KeepAspectRatio ); } break; } case Pan: { //pan action mToolPanning = true; mMouseLastXY = e->pos(); viewport()->setCursor( Qt::ClosedHandCursor ); break; } case MoveItemContent: { //get a list of items at clicked position QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos() ); if ( itemsAtCursorPos.isEmpty() ) { //no items at clicked position return; } //find highest non-locked QgsComposerItem at clicked position //(other graphics items may be higher, e.g., selection handles) QList<QGraphicsItem *>::iterator itemIter = itemsAtCursorPos.begin(); for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter ) { QgsComposerItem *item = dynamic_cast<QgsComposerItem *>( ( *itemIter ) ); if ( item && !item->positionLock() ) { //we've found the highest QgsComposerItem mMoveContentStartPos = scenePoint; mMoveContentItem = item; mMovingItemContent = true; break; } } //no QgsComposerItem at clicked position return; } case EditNodesItem: { QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos().x(), e->pos().y(), mMoveContentSearchRadius, mMoveContentSearchRadius ); if ( itemsAtCursorPos.isEmpty() ) return; mNodesItemIndex = -1; mNodesItem = nullptr; QList<QGraphicsItem *>::iterator itemIter = itemsAtCursorPos.begin(); for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter ) { QgsComposerItem *item = dynamic_cast<QgsComposerItem *>( ( *itemIter ) ); if ( item && !item->positionLock() ) { if ( ( item->type() == QgsComposerItem::ComposerPolygon || item->type() == QgsComposerItem::ComposerPolyline ) ) { QgsComposerNodesItem *itemP = static_cast<QgsComposerNodesItem *>( item ); int index = itemP->nodeAtPosition( scenePoint ); if ( index != -1 ) { mNodesItemIndex = index; mNodesItem = itemP; mMoveContentStartPos = scenePoint; } } } if ( mNodesItemIndex != -1 ) { composition()->beginCommand( mNodesItem, tr( "Move item node" ) ); setSelectedNode( mNodesItem, mNodesItemIndex ); break; } } break; } //create rubber band for adding line items case AddArrow: { mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandLineItem = new QGraphicsLineItem( snappedScenePoint.x(), snappedScenePoint.y(), snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandLineItem->setPen( QPen( QBrush( QColor( 227, 22, 22, 200 ) ), 0 ) ); mRubberBandLineItem->setZValue( 1000 ); scene()->addItem( mRubberBandLineItem ); scene()->update(); break; } //create rubber band for adding rectangular items case AddMap: case AddRectangle: case AddTriangle: case AddEllipse: case AddHtml: case AddPicture: case AddLabel: case AddLegend: case AddTable: case AddAttributeTable: { QTransform t; mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 ); mRubberBandItem->setBrush( Qt::NoBrush ); mRubberBandItem->setPen( QPen( QBrush( QColor( 227, 22, 22, 200 ) ), 0 ) ); mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() ); t.translate( snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandItem->setTransform( t ); mRubberBandItem->setZValue( 1000 ); scene()->addItem( mRubberBandItem ); scene()->update(); } break; case AddScalebar: if ( composition() ) { QgsComposerScaleBar *newScaleBar = new QgsComposerScaleBar( composition() ); newScaleBar->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 20, 20 ) ); composition()->addComposerScaleBar( newScaleBar ); QList<const QgsComposerMap *> mapItemList = composition()->composerMapItems(); if ( !mapItemList.isEmpty() ) { newScaleBar->setComposerMap( mapItemList.at( 0 ) ); } newScaleBar->applyDefaultSize(); //4 segments, 1/5 of composer map width composition()->setAllDeselected(); newScaleBar->setSelected( true ); emit selectedItemChanged( newScaleBar ); emit actionFinished(); composition()->pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) ); } break; case AddPolygon: { if ( !mPolygonItem ) { mPolygonItem.reset( new QGraphicsPolygonItem() ); mPolygonItem->setBrush( Qt::NoBrush ); mPolygonItem->setPen( QPen( QBrush( QColor( 227, 22, 22, 200 ) ), 0 ) ); mPolygonItem->setZValue( 1000 ); scene()->addItem( mPolygonItem.get() ); scene()->update(); } break; } case AddPolyline: { if ( !mPolylineItem && !mPolygonItem ) { mPolygonItem.reset( new QGraphicsPolygonItem() ); mPolylineItem.reset( new QGraphicsPathItem() ); mPolylineItem->setPen( QPen( QBrush( QColor( 227, 22, 22, 200 ) ), 0 ) ); mPolylineItem->setZValue( 1000 ); } break; } default: break; } } QCursor QgsComposerView::defaultCursorForTool( Tool currentTool ) { switch ( currentTool ) { case Select: return Qt::ArrowCursor; case Zoom: { QPixmap myZoomQPixmap = QPixmap( ( const char ** )( zoom_in ) ); return QCursor( myZoomQPixmap, 7, 7 ); } case Pan: return Qt::OpenHandCursor; case MoveItemContent: return Qt::ArrowCursor; case EditNodesItem: return Qt::CrossCursor; case AddArrow: case AddMap: case AddRectangle: case AddTriangle: case AddEllipse: case AddPolygon: case AddPolyline: case AddHtml: case AddLabel: case AddScalebar: case AddLegend: case AddPicture: case AddTable: case AddAttributeTable: { QPixmap myCrosshairQPixmap = QPixmap( ( const char ** )( cross_hair_cursor ) ); return QCursor( myCrosshairQPixmap, 8, 8 ); } } return Qt::ArrowCursor; } void QgsComposerView::addShape( Tool currentTool ) { QgsComposerShape::Shape shape = QgsComposerShape::Ellipse; if ( currentTool == AddRectangle ) shape = QgsComposerShape::Rectangle; else if ( currentTool == AddTriangle ) shape = QgsComposerShape::Triangle; if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { removeRubberBand(); return; } if ( composition() ) { QgsComposerShape *composerShape = new QgsComposerShape( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height(), composition() ); composerShape->setShapeType( shape ); //new shapes use symbol v2 by default composerShape->setUseSymbol( true ); composition()->addComposerShape( composerShape ); removeRubberBand(); composition()->setAllDeselected(); composerShape->setSelected( true ); emit selectedItemChanged( composerShape ); emit actionFinished(); composition()->pushAddRemoveCommand( composerShape, tr( "Shape added" ) ); } } void QgsComposerView::updateRulers() { if ( mHorizontalRuler ) { mHorizontalRuler->setSceneTransform( viewportTransform() ); } if ( mVerticalRuler ) { mVerticalRuler->setSceneTransform( viewportTransform() ); } } void QgsComposerView::removeRubberBand() { if ( mRubberBandItem ) { scene()->removeItem( mRubberBandItem ); delete mRubberBandItem; mRubberBandItem = nullptr; } } void QgsComposerView::startMarqueeSelect( QPointF &scenePoint ) { mMarqueeSelect = true; QTransform t; mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 ); mRubberBandItem->setBrush( QBrush( QColor( 224, 178, 76, 63 ) ) ); mRubberBandItem->setPen( QPen( QBrush( QColor( 254, 58, 29, 100 ) ), 0, Qt::DotLine ) ); mRubberBandStartPos = QPointF( scenePoint.x(), scenePoint.y() ); t.translate( scenePoint.x(), scenePoint.y() ); mRubberBandItem->setTransform( t ); mRubberBandItem->setZValue( 1000 ); scene()->addItem( mRubberBandItem ); scene()->update(); } void QgsComposerView::endMarqueeSelect( QMouseEvent *e ) { mMarqueeSelect = false; bool subtractingSelection = false; if ( e->modifiers() & Qt::ShiftModifier ) { //shift modifer means adding to selection, nothing required here } else if ( e->modifiers() & Qt::ControlModifier ) { //control modifier means subtract from current selection subtractingSelection = true; } else { //not adding to or removing from selection, so clear current selection composition()->setAllDeselected(); } if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { //just a click, do nothing removeRubberBand(); return; } QRectF boundsRect = QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ); //determine item selection mode, default to intersection Qt::ItemSelectionMode selectionMode = Qt::IntersectsItemShape; if ( e->modifiers() & Qt::AltModifier ) { //alt modifier switches to contains selection mode selectionMode = Qt::ContainsItemShape; } //find all items in rubber band QList<QGraphicsItem *> itemList = composition()->items( boundsRect, selectionMode ); QList<QGraphicsItem *>::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { QgsComposerItem *mypItem = dynamic_cast<QgsComposerItem *>( *itemIt ); QgsPaperItem *paperItem = dynamic_cast<QgsPaperItem *>( *itemIt ); if ( mypItem && !paperItem ) { if ( !mypItem->positionLock() ) { if ( subtractingSelection ) { mypItem->setSelected( false ); } else { mypItem->setSelected( true ); } } } } removeRubberBand(); //update item panel QList<QgsComposerItem *> selectedItemList = composition()->selectedComposerItems(); if ( !selectedItemList.isEmpty() ) { emit selectedItemChanged( selectedItemList[0] ); } } void QgsComposerView::startMarqueeZoom( QPointF &scenePoint ) { mMarqueeZoom = true; QTransform t; mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 ); mRubberBandItem->setBrush( QBrush( QColor( 70, 50, 255, 25 ) ) ); mRubberBandItem->setPen( QPen( QColor( 70, 50, 255, 100 ) ) ); mRubberBandStartPos = QPointF( scenePoint.x(), scenePoint.y() ); t.translate( scenePoint.x(), scenePoint.y() ); mRubberBandItem->setTransform( t ); mRubberBandItem->setZValue( 1000 ); scene()->addItem( mRubberBandItem ); scene()->update(); } void QgsComposerView::endMarqueeZoom( QMouseEvent *e ) { mMarqueeZoom = false; QRectF boundsRect; if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { //just a click, so zoom to clicked point and recenter double scaleFactor = 0.5; //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); //transform the mouse pos to scene coordinates QPointF scenePoint = mapToScene( e->pos() ); visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() ); boundsRect = visibleRect.toRectF(); } else { //marquee zoom //zoom bounds are size marquee object boundsRect = QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ); } removeRubberBand(); //zoom view to fit desired bounds fitInView( boundsRect, Qt::KeepAspectRatio ); if ( mTemporaryZoomStatus == QgsComposerView::ActiveUntilMouseRelease ) { //user was using the temporary keyboard activated zoom tool //and the control or space key was released before mouse button, so end temporary zoom mTemporaryZoomStatus = QgsComposerView::Inactive; setCurrentTool( mPreviousTool ); } } void QgsComposerView::mouseReleaseEvent( QMouseEvent *e ) { if ( !composition() ) { return; } if ( e->button() != Qt::LeftButton && ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) ) { //ignore clicks while dragging/resizing items return; } QPoint mousePressStopPoint = e->pos(); int diffX = mousePressStopPoint.x() - mMousePressStartPos.x(); int diffY = mousePressStopPoint.y() - mMousePressStartPos.y(); //was this just a click? or a click and drag? bool clickOnly = false; if ( qAbs( diffX ) < 2 && qAbs( diffY ) < 2 ) { clickOnly = true; } QPointF scenePoint = mapToScene( e->pos() ); if ( mMousePanning || mToolPanning ) { mMousePanning = false; mToolPanning = false; if ( clickOnly && e->button() == Qt::MidButton ) { //middle mouse button click = recenter on point //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); visibleRect.scale( 1, scenePoint.x(), scenePoint.y() ); QRectF boundsRect = visibleRect.toRectF(); //zoom view to fit desired bounds fitInView( boundsRect, Qt::KeepAspectRatio ); } //set new cursor if ( mCurrentTool != Pan ) { if ( composition() ) { //allow composer items to change cursor composition()->setPreventCursorChange( false ); } } viewport()->setCursor( defaultCursorForTool( mCurrentTool ) ); } if ( e->button() == Qt::RightButton ) { switch ( mCurrentTool ) { case AddPolygon: { if ( mPolygonItem ) { QPolygonF poly = mPolygonItem->polygon(); // last (temporary) point is removed poly.remove( poly.count() - 1 ); if ( poly.size() >= 3 ) { mPolygonItem->setPolygon( poly ); // add polygon in composition QgsComposerPolygon *composerPolygon = new QgsComposerPolygon( mPolygonItem->polygon(), composition() ); composition()->addComposerPolygon( composerPolygon ); // select the polygon composition()->setAllDeselected(); composerPolygon->setSelected( true ); emit selectedItemChanged( composerPolygon ); composition()->pushAddRemoveCommand( composerPolygon, tr( "Polygon added" ) ); } // clean scene()->removeItem( mPolygonItem.get() ); mPolygonItem.reset(); emit actionFinished(); } break; } case AddPolyline: { if ( mPolygonItem && mPolylineItem ) { // ignore the last point due to release event before doubleClick event QPolygonF poly = mPolygonItem->polygon(); // last (temporary) point is removed poly.remove( poly.count() - 1 ); if ( poly.size() >= 2 ) { mPolygonItem->setPolygon( poly ); // add polygon in composition QgsComposerPolyline *composerPolyline = new QgsComposerPolyline( mPolygonItem->polygon(), composition() ); composition()->addComposerPolyline( composerPolyline ); // select the polygon composition()->setAllDeselected(); composerPolyline->setSelected( true ); emit selectedItemChanged( composerPolyline ); composition()->pushAddRemoveCommand( composerPolyline, tr( "Polyline added" ) ); } // clean scene()->removeItem( mPolylineItem.get() ); mPolygonItem.reset(); mPolylineItem.reset(); emit actionFinished(); } break; } default: e->ignore(); } } //for every other tool, ignore clicks of non-left button if ( e->button() != Qt::LeftButton ) { return; } if ( mMarqueeSelect ) { endMarqueeSelect( e ); return; } switch ( mCurrentTool ) { case Select: { QGraphicsView::mouseReleaseEvent( e ); break; } case Zoom: { if ( mMarqueeZoom ) { endMarqueeZoom( e ); } break; } case MoveItemContent: { if ( mMoveContentItem ) { //update map preview if composer map QgsComposerMap *composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem ); if ( composerMap ) { composerMap->setOffset( 0, 0 ); } double moveX = scenePoint.x() - mMoveContentStartPos.x(); double moveY = scenePoint.y() - mMoveContentStartPos.y(); composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) ); mMoveContentItem->moveContent( -moveX, -moveY ); composition()->endCommand(); mMoveContentItem = nullptr; mMovingItemContent = false; } break; } case EditNodesItem: { if ( mNodesItemIndex != -1 ) { if ( scenePoint != mMoveContentStartPos ) composition()->endCommand(); else composition()->cancelCommand(); } break; } case AddArrow: if ( !composition() || !mRubberBandLineItem ) { scene()->removeItem( mRubberBandLineItem ); delete mRubberBandLineItem; mRubberBandLineItem = nullptr; return; } else { QgsComposerArrow *composerArrow = new QgsComposerArrow( mRubberBandLineItem->line().p1(), mRubberBandLineItem->line().p2(), composition() ); composition()->addComposerArrow( composerArrow ); composition()->setAllDeselected(); composerArrow->setSelected( true ); emit selectedItemChanged( composerArrow ); scene()->removeItem( mRubberBandLineItem ); delete mRubberBandLineItem; mRubberBandLineItem = nullptr; emit actionFinished(); composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) ); } break; case AddRectangle: case AddTriangle: case AddEllipse: addShape( mCurrentTool ); break; case AddPolygon: { if ( mPolygonItem ) addPolygonNode( scenePoint ); break; } case AddPolyline: { if ( mPolygonItem && mPolylineItem ) { addPolygonNode( scenePoint ); // rebuild a new qpainter path QPainterPath path; path.addPolygon( mPolygonItem->polygon() ); mPolylineItem->setPath( path ); // add it to the scene scene()->addItem( mPolylineItem.get() ); scene()->update(); } break; } case AddMap: if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { removeRubberBand(); return; } else { QgsComposerMap *composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ); if ( mCanvas ) { composerMap->zoomToExtent( mCanvas->mapSettings().visibleExtent() ); composerMap->setLayers( mCanvas->mapSettings().layers() ); } composition()->addComposerMap( composerMap ); composition()->setAllDeselected(); composerMap->setSelected( true ); emit selectedItemChanged( composerMap ); removeRubberBand(); emit actionFinished(); composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) ); } break; case AddPicture: if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { removeRubberBand(); return; } else { QgsComposerPicture *newPicture = new QgsComposerPicture( composition() ); newPicture->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ) ); composition()->addComposerPicture( newPicture ); composition()->setAllDeselected(); newPicture->setSelected( true ); emit selectedItemChanged( newPicture ); removeRubberBand(); emit actionFinished(); composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) ); } break; case AddLabel: if ( !composition() || !mRubberBandItem ) { removeRubberBand(); return; } else { QgsComposerLabel *newLabelItem = new QgsComposerLabel( composition() ); newLabelItem->setText( tr( "QGIS" ) ); newLabelItem->adjustSizeToText(); //make sure label size is sufficient to fit text double labelWidth = qMax( mRubberBandItem->rect().width(), newLabelItem->rect().width() ); double labelHeight = qMax( mRubberBandItem->rect().height(), newLabelItem->rect().height() ); newLabelItem->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), labelWidth, labelHeight ) ); composition()->addComposerLabel( newLabelItem ); composition()->setAllDeselected(); newLabelItem->setSelected( true ); emit selectedItemChanged( newLabelItem ); removeRubberBand(); emit actionFinished(); composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) ); } break; case AddLegend: if ( !composition() || !mRubberBandItem ) { removeRubberBand(); return; } else { QgsComposerLegend *newLegend = new QgsComposerLegend( composition() ); QList<const QgsComposerMap *> mapItemList = composition()->composerMapItems(); if ( !mapItemList.isEmpty() ) { newLegend->setComposerMap( mapItemList.at( 0 ) ); } newLegend->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ) ); composition()->addComposerLegend( newLegend ); newLegend->updateLegend(); composition()->setAllDeselected(); newLegend->setSelected( true ); emit selectedItemChanged( newLegend ); removeRubberBand(); emit actionFinished(); composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) ); } break; case AddAttributeTable: if ( !composition() || !mRubberBandItem ) { removeRubberBand(); return; } else { QgsComposerAttributeTableV2 *newTable = new QgsComposerAttributeTableV2( composition(), true ); QList<const QgsComposerMap *> mapItemList = composition()->composerMapItems(); if ( !mapItemList.isEmpty() ) { newTable->setComposerMap( mapItemList.at( 0 ) ); } QgsAddRemoveMultiFrameCommand *command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added, newTable, composition(), tr( "Attribute table added" ) ); composition()->undoStack()->push( command ); QgsComposerFrame *frame = new QgsComposerFrame( composition(), newTable, mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ); composition()->beginMultiFrameCommand( newTable, tr( "Attribute table frame added" ) ); newTable->addFrame( frame ); composition()->endMultiFrameCommand(); composition()->setAllDeselected(); frame->setSelected( true ); emit selectedItemChanged( frame ); removeRubberBand(); emit actionFinished(); } break; case AddHtml: if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) ) { removeRubberBand(); return; } else { QgsComposerHtml *composerHtml = new QgsComposerHtml( composition(), true ); QgsAddRemoveMultiFrameCommand *command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added, composerHtml, composition(), tr( "HTML item added" ) ); composition()->undoStack()->push( command ); QgsComposerFrame *frame = new QgsComposerFrame( composition(), composerHtml, mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ); composition()->beginMultiFrameCommand( composerHtml, tr( "HTML frame added" ) ); composerHtml->addFrame( frame ); composition()->endMultiFrameCommand(); composition()->setAllDeselected(); frame->setSelected( true ); emit selectedItemChanged( frame ); removeRubberBand(); emit actionFinished(); } break; default: break; } } void QgsComposerView::mouseMoveEvent( QMouseEvent *e ) { if ( !composition() ) { return; } bool shiftModifier = false; bool altModifier = false; if ( e->modifiers() & Qt::ShiftModifier ) { //shift key depressed shiftModifier = true; } if ( e->modifiers() & Qt::AltModifier ) { //alt key depressed altModifier = true; } mMouseCurrentXY = e->pos(); //update cursor position in composer status bar emit cursorPosChanged( mapToScene( e->pos() ) ); updateRulers(); if ( mHorizontalRuler ) { mHorizontalRuler->updateMarker( e->posF() ); } if ( mVerticalRuler ) { mVerticalRuler->updateMarker( e->posF() ); } if ( mToolPanning || mMousePanning || mKeyPanning ) { //panning, so scroll view horizontalScrollBar()->setValue( horizontalScrollBar()->value() - ( e->x() - mMouseLastXY.x() ) ); verticalScrollBar()->setValue( verticalScrollBar()->value() - ( e->y() - mMouseLastXY.y() ) ); mMouseLastXY = e->pos(); return; } else if ( ( e->buttons() == Qt::NoButton ) && ( !mPolygonItem ) ) { if ( mCurrentTool == Select ) { QGraphicsView::mouseMoveEvent( e ); } } else { QPointF scenePoint = mapToScene( e->pos() ); if ( mMarqueeSelect || mMarqueeZoom ) { updateRubberBandRect( scenePoint ); return; } switch ( mCurrentTool ) { case Select: QGraphicsView::mouseMoveEvent( e ); break; case AddArrow: { updateRubberBandLine( scenePoint, shiftModifier ); break; } case AddMap: case AddRectangle: case AddTriangle: case AddEllipse: case AddHtml: case AddPicture: case AddLabel: case AddLegend: case AddTable: case AddAttributeTable: //adjust rubber band item { updateRubberBandRect( scenePoint, shiftModifier, altModifier ); break; } case AddPolygon: { if ( mPolygonItem ) movePolygonNode( scenePoint, shiftModifier ); break; } case AddPolyline: { if ( mPolygonItem && mPolylineItem ) { movePolygonNode( scenePoint, shiftModifier ); // rebuild a new qpainter path QPainterPath path; path.addPolygon( mPolygonItem->polygon() ); mPolylineItem->setPath( path ); } break; } case MoveItemContent: { //update map preview if composer map QgsComposerMap *composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem ); if ( composerMap ) { composerMap->setOffset( scenePoint.x() - mMoveContentStartPos.x(), scenePoint.y() - mMoveContentStartPos.y() ); composerMap->update(); } break; } case EditNodesItem: { if ( mNodesItemIndex != -1 ) { QPointF scenePoint = mapToScene( e->pos() ); mNodesItem->moveNode( mNodesItemIndex, scenePoint ); scene()->update(); } break; } default: break; } } } void QgsComposerView::updateRubberBandRect( QPointF &pos, const bool constrainSquare, const bool fromCenter ) { if ( !mRubberBandItem ) { return; } double x = 0; double y = 0; double width = 0; double height = 0; double dx = pos.x() - mRubberBandStartPos.x(); double dy = pos.y() - mRubberBandStartPos.y(); if ( constrainSquare ) { if ( fabs( dx ) > fabs( dy ) ) { width = fabs( dx ); height = width; } else { height = fabs( dy ); width = height; } x = mRubberBandStartPos.x() - ( ( dx < 0 ) ? width : 0 ); y = mRubberBandStartPos.y() - ( ( dy < 0 ) ? height : 0 ); } else { //not constraining if ( dx < 0 ) { x = pos.x(); width = -dx; } else { x = mRubberBandStartPos.x(); width = dx; } if ( dy < 0 ) { y = pos.y(); height = -dy; } else { y = mRubberBandStartPos.y(); height = dy; } } if ( fromCenter ) { x = mRubberBandStartPos.x() - width; y = mRubberBandStartPos.y() - height; width *= 2.0; height *= 2.0; } mRubberBandItem->setRect( 0, 0, width, height ); QTransform t; t.translate( x, y ); mRubberBandItem->setTransform( t ); } void QgsComposerView::updateRubberBandLine( QPointF pos, const bool constrainAngles ) { if ( !mRubberBandLineItem ) { return; } //snap to grid QPointF snappedScenePoint = composition()->snapPointToGrid( pos ); QLineF newLine = QLineF( mRubberBandStartPos, snappedScenePoint ); if ( constrainAngles ) { //movement is contrained to 45 degree angles double angle = QgsComposerUtils::snappedAngle( newLine.angle() ); newLine.setAngle( angle ); } mRubberBandLineItem->setLine( newLine ); } void QgsComposerView::mouseDoubleClickEvent( QMouseEvent *e ) { QPointF scenePoint = mapToScene( e->pos() ); switch ( mCurrentTool ) { case EditNodesItem: { // erase status previously set by the mousePressEvent method if ( mNodesItemIndex != -1 ) { mNodesItem = nullptr; mNodesItemIndex = -1; deselectNode(); } // search items in composer QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos().x(), e->pos().y(), mMoveContentSearchRadius, mMoveContentSearchRadius ); if ( itemsAtCursorPos.isEmpty() ) return; bool rc = false; QList<QGraphicsItem *>::iterator itemIter = itemsAtCursorPos.begin(); for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter ) { QgsComposerItem *item = dynamic_cast<QgsComposerItem *>( ( *itemIter ) ); if ( item && !item->positionLock() ) { if ( ( item->type() == QgsComposerItem::ComposerPolygon || item->type() == QgsComposerItem::ComposerPolyline ) ) { QgsComposerNodesItem *itemP = dynamic_cast<QgsComposerNodesItem *>( item ); composition()->beginCommand( itemP, tr( "Add item node" ) ); rc = itemP->addNode( scenePoint ); if ( rc ) { composition()->endCommand(); mNodesItem = itemP; mNodesItemIndex = mNodesItem->nodeAtPosition( scenePoint ); } else composition()->cancelCommand(); } } if ( rc ) break; } if ( rc ) { setSelectedNode( mNodesItem, mNodesItemIndex ); scene()->update(); } break; } default: break; } } void QgsComposerView::copyItems( ClipboardMode mode ) { if ( !composition() ) { return; } QList<QgsComposerItem *> composerItemList = composition()->selectedComposerItems(); QList<QgsComposerItem *>::iterator itemIt = composerItemList.begin(); QDomDocument doc; QDomElement documentElement = doc.createElement( QStringLiteral( "ComposerItemClipboard" ) ); for ( ; itemIt != composerItemList.end(); ++itemIt ) { // copy each item in a group QgsComposerItemGroup *itemGroup = dynamic_cast<QgsComposerItemGroup *>( *itemIt ); if ( itemGroup && composition() ) { QSet<QgsComposerItem *> groupedItems = itemGroup->items(); QSet<QgsComposerItem *>::iterator it = groupedItems.begin(); for ( ; it != groupedItems.end(); ++it ) { ( *it )->writeXml( documentElement, doc ); } } ( *itemIt )->writeXml( documentElement, doc ); if ( mode == ClipboardModeCut ) { composition()->removeComposerItem( *itemIt ); } } doc.appendChild( documentElement ); //if it's a copy, we have to remove the UUIDs since we don't want any duplicate UUID if ( mode == ClipboardModeCopy ) { // remove all uuid attributes QDomNodeList composerItemsNodes = doc.elementsByTagName( QStringLiteral( "ComposerItem" ) ); for ( int i = 0; i < composerItemsNodes.count(); ++i ) { QDomNode composerItemNode = composerItemsNodes.at( i ); if ( composerItemNode.isElement() ) { composerItemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) ); } } } QMimeData *mimeData = new QMimeData; mimeData->setData( QStringLiteral( "text/xml" ), doc.toByteArray() ); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData( mimeData ); } void QgsComposerView::pasteItems( PasteMode mode ) { if ( !composition() ) { return; } QDomDocument doc; QClipboard *clipboard = QApplication::clipboard(); if ( doc.setContent( clipboard->mimeData()->data( QStringLiteral( "text/xml" ) ) ) ) { QDomElement docElem = doc.documentElement(); if ( docElem.tagName() == QLatin1String( "ComposerItemClipboard" ) ) { if ( composition() ) { QPointF pt; if ( mode == QgsComposerView::PasteModeCursor || mode == QgsComposerView::PasteModeInPlace ) { // place items at cursor position pt = mapToScene( mapFromGlobal( QCursor::pos() ) ); } else { // place items in center of viewport pt = mapToScene( viewport()->rect().center() ); } bool pasteInPlace = ( mode == PasteModeInPlace ); composition()->addItemsFromXml( docElem, doc, nullptr, true, &pt, pasteInPlace ); } } } //switch back to select tool so that pasted items can be moved/resized (#8958) setCurrentTool( QgsComposerView::Select ); } void QgsComposerView::deleteSelectedItems() { if ( !composition() ) { return; } if ( mCurrentTool == QgsComposerView::EditNodesItem ) { if ( mNodesItemIndex != -1 ) { composition()->beginCommand( mNodesItem, tr( "Remove item node" ) ); if ( mNodesItem->removeNode( mNodesItemIndex ) ) { composition()->endCommand(); if ( mNodesItem->nodesSize() > 0 ) { mNodesItemIndex = mNodesItem->selectedNode(); // setSelectedNode( mNodesItem, mNodesItemIndex ); } else { mNodesItemIndex = -1; mNodesItem = nullptr; } scene()->update(); } else { composition()->cancelCommand(); } } } else { QList<QgsComposerItem *> composerItemList = composition()->selectedComposerItems(); QList<QgsComposerItem *>::iterator itemIt = composerItemList.begin(); //delete selected items for ( ; itemIt != composerItemList.end(); ++itemIt ) { if ( composition() ) { composition()->removeComposerItem( *itemIt ); } } } } void QgsComposerView::selectAll() { if ( !composition() ) { return; } //select all items in composer QList<QGraphicsItem *> itemList = composition()->items(); QList<QGraphicsItem *>::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { QgsComposerItem *mypItem = dynamic_cast<QgsComposerItem *>( *itemIt ); QgsPaperItem *paperItem = dynamic_cast<QgsPaperItem *>( *itemIt ); if ( mypItem && !paperItem ) { if ( !mypItem->positionLock() ) { mypItem->setSelected( true ); } else { //deselect all locked items mypItem->setSelected( false ); } emit selectedItemChanged( mypItem ); } } } void QgsComposerView::selectNone() { if ( !composition() ) { return; } composition()->setAllDeselected(); } void QgsComposerView::selectInvert() { if ( !composition() ) { return; } //check all items in composer QList<QGraphicsItem *> itemList = composition()->items(); QList<QGraphicsItem *>::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { QgsComposerItem *mypItem = dynamic_cast<QgsComposerItem *>( *itemIt ); QgsPaperItem *paperItem = dynamic_cast<QgsPaperItem *>( *itemIt ); if ( mypItem && !paperItem ) { //flip selected state for items (and deselect any locked items) if ( mypItem->selected() || mypItem->positionLock() ) { mypItem->setSelected( false ); } else { mypItem->setSelected( true ); emit selectedItemChanged( mypItem ); } } } } void QgsComposerView::keyPressEvent( QKeyEvent *e ) { if ( !composition() ) { return; } if ( mKeyPanning || mMousePanning || mToolPanning || mMovingItemContent || composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) { return; } if ( mTemporaryZoomStatus != QgsComposerView::Inactive ) { //temporary keyboard based zoom is active if ( e->isAutoRepeat() ) { return; } //respond to changes in ctrl key status if ( !( e->modifiers() & Qt::ControlModifier ) && !mMarqueeZoom ) { //space pressed, but control key was released, end of temporary zoom tool mTemporaryZoomStatus = QgsComposerView::Inactive; setCurrentTool( mPreviousTool ); } else if ( !( e->modifiers() & Qt::ControlModifier ) && mMarqueeZoom ) { //control key released, but user is mid-way through a marquee zoom //so end temporary zoom when user releases the mouse button mTemporaryZoomStatus = QgsComposerView::ActiveUntilMouseRelease; } else { //both control and space pressed //set cursor to zoom in/out depending on shift key status QPixmap myZoomQPixmap = QPixmap( ( const char ** )( ( e->modifiers() & Qt::AltModifier ) ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); } return; } if ( mCurrentTool != QgsComposerView::Zoom && ( mRubberBandItem || mRubberBandLineItem ) ) { //disable keystrokes while drawing a box return; } if ( e->key() == Qt::Key_Space && ! e->isAutoRepeat() ) { if ( !( e->modifiers() & Qt::ControlModifier ) ) { // Pan composer with space bar mKeyPanning = true; mMouseLastXY = mMouseCurrentXY; if ( composition() ) { //prevent cursor changes while panning composition()->setPreventCursorChange( true ); } viewport()->setCursor( Qt::ClosedHandCursor ); return; } else { //ctrl+space pressed, so switch to temporary keyboard based zoom tool mTemporaryZoomStatus = QgsComposerView::Active; mPreviousTool = mCurrentTool; setCurrentTool( Zoom ); //set cursor to zoom in/out depending on alt key status QPixmap myZoomQPixmap = QPixmap( ( const char ** )( ( e->modifiers() & Qt::AltModifier ) ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); return; } } if ( mCurrentTool == QgsComposerView::Zoom ) { //using the zoom tool, respond to changes in alt key status and update mouse cursor accordingly if ( ! e->isAutoRepeat() ) { QPixmap myZoomQPixmap = QPixmap( ( const char ** )( ( e->modifiers() & Qt::AltModifier ) ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); } return; } QList<QgsComposerItem *> composerItemList = composition()->selectedComposerItems(); QList<QgsComposerItem *>::iterator itemIt = composerItemList.begin(); // increment used for cursor key item movement double increment = 1.0; if ( e->modifiers() & Qt::ShiftModifier ) { //holding shift while pressing cursor keys results in a big step increment = 10.0; } else if ( e->modifiers() & Qt::AltModifier ) { //holding alt while pressing cursor keys results in a 1 pixel step double viewScale = transform().m11(); if ( viewScale > 0 ) { increment = 1 / viewScale; } } if ( e->key() == Qt::Key_Left ) { if ( mCurrentTool == EditNodesItem ) { if ( mNodesItemIndex != -1 ) { QPointF currentPos; if ( mNodesItem->nodePosition( mNodesItemIndex, currentPos ) ) { currentPos.setX( currentPos.x() - increment ); composition()->beginCommand( mNodesItem, tr( "Move item node" ) ); mNodesItem->moveNode( mNodesItemIndex, currentPos ); composition()->endCommand(); scene()->update(); } } } else { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( -1 * increment, 0.0 ); ( *itemIt )->endCommand(); } } } else if ( e->key() == Qt::Key_Right ) { if ( mCurrentTool == EditNodesItem ) { if ( mNodesItemIndex != -1 ) { QPointF currentPos; if ( mNodesItem->nodePosition( mNodesItemIndex, currentPos ) ) { currentPos.setX( currentPos.x() + increment ); composition()->beginCommand( mNodesItem, tr( "Move item node" ) ); mNodesItem->moveNode( mNodesItemIndex, currentPos ); composition()->endCommand(); scene()->update(); } } } else { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( increment, 0.0 ); ( *itemIt )->endCommand(); } } } else if ( e->key() == Qt::Key_Down ) { if ( mCurrentTool == EditNodesItem ) { if ( mNodesItemIndex != -1 ) { QPointF currentPos; if ( mNodesItem->nodePosition( mNodesItemIndex, currentPos ) ) { currentPos.setY( currentPos.y() + increment ); composition()->beginCommand( mNodesItem, tr( "Move item node" ) ); mNodesItem->moveNode( mNodesItemIndex, currentPos ); composition()->endCommand(); scene()->update(); } } } else { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( 0.0, increment ); ( *itemIt )->endCommand(); } } } else if ( e->key() == Qt::Key_Up ) { if ( mCurrentTool == EditNodesItem ) { if ( mNodesItemIndex != -1 ) { QPointF currentPos; if ( mNodesItem->nodePosition( mNodesItemIndex, currentPos ) ) { currentPos.setY( currentPos.y() - increment ); composition()->beginCommand( mNodesItem, tr( "Move item node" ) ); mNodesItem->moveNode( mNodesItemIndex, currentPos ); composition()->endCommand(); scene()->update(); } } } else { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( 0.0, -1 * increment ); ( *itemIt )->endCommand(); } } } } void QgsComposerView::keyReleaseEvent( QKeyEvent *e ) { if ( e->key() == Qt::Key_Space && !e->isAutoRepeat() && mKeyPanning ) { //end of panning with space key mKeyPanning = false; //reset cursor if ( mCurrentTool != Pan ) { if ( composition() ) { //allow cursor changes again composition()->setPreventCursorChange( false ); } } viewport()->setCursor( defaultCursorForTool( mCurrentTool ) ); return; } else if ( e->key() == Qt::Key_Space && !e->isAutoRepeat() && mTemporaryZoomStatus != QgsComposerView::Inactive ) { //temporary keyboard-based zoom tool is active and space key has been released if ( mMarqueeZoom ) { //currently in the middle of a marquee operation, so don't switch tool back immediately //instead, wait until mouse button has been released before switching tool back mTemporaryZoomStatus = QgsComposerView::ActiveUntilMouseRelease; } else { //switch tool back mTemporaryZoomStatus = QgsComposerView::Inactive; setCurrentTool( mPreviousTool ); } } else if ( mCurrentTool == QgsComposerView::Zoom ) { //if zoom tool is active, respond to changes in the alt key status and update cursor accordingly if ( ! e->isAutoRepeat() ) { QPixmap myZoomQPixmap = QPixmap( ( const char ** )( ( e->modifiers() & Qt::AltModifier ) ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); } return; } } void QgsComposerView::wheelEvent( QWheelEvent *event ) { if ( mRubberBandItem || mRubberBandLineItem ) { //ignore wheel events while marquee operations are active (e.g., creating new item) return; } if ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) { //ignore wheel events while dragging/resizing items return; } if ( currentTool() == MoveItemContent ) { //move item content tool, so scroll events get handled by the selected composer item QPointF scenePoint = mapToScene( event->pos() ); //select topmost item at position of event QgsComposerItem *item = composition()->composerItemAt( scenePoint, true ); if ( item ) { if ( item->isSelected() ) { QgsSettings settings; //read zoom mode QgsComposerItem::ZoomMode zoomMode = ( QgsComposerItem::ZoomMode )settings.value( QStringLiteral( "qgis/wheel_action" ), 2 ).toInt(); if ( zoomMode == QgsComposerItem::NoZoom ) { //do nothing return; } double zoomFactor = settings.value( QStringLiteral( "qgis/zoom_factor" ), 2.0 ).toDouble(); if ( event->modifiers() & Qt::ControlModifier ) { //holding ctrl while wheel zooming results in a finer zoom zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0; } zoomFactor = event->delta() > 0 ? zoomFactor : 1 / zoomFactor; QPointF itemPoint = item->mapFromScene( scenePoint ); item->beginCommand( tr( "Zoom item content" ), QgsComposerMergeCommand::ItemZoomContent ); item->zoomContent( zoomFactor, itemPoint, zoomMode ); item->endCommand(); } } } else { //not using move item content tool, so zoom whole composition wheelZoom( event ); } } void QgsComposerView::wheelZoom( QWheelEvent *event ) { //get mouse wheel zoom behavior settings QgsSettings mySettings; double zoomFactor = mySettings.value( QStringLiteral( "qgis/zoom_factor" ), 2 ).toDouble(); if ( event->modifiers() & Qt::ControlModifier ) { //holding ctrl while wheel zooming results in a finer zoom zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 10.0; } //calculate zoom scale factor bool zoomIn = event->delta() > 0; double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor ); //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); //transform the mouse pos to scene coordinates QPointF scenePoint = mapToScene( event->pos() ); //adjust view center QgsPoint oldCenter( visibleRect.center() ); QgsPoint newCenter( scenePoint.x() + ( ( oldCenter.x() - scenePoint.x() ) * scaleFactor ), scenePoint.y() + ( ( oldCenter.y() - scenePoint.y() ) * scaleFactor ) ); centerOn( newCenter.x(), newCenter.y() ); //zoom composition if ( zoomIn ) { scaleSafe( zoomFactor ); } else { scaleSafe( 1 / zoomFactor ); } //update composition for new zoom emit zoomLevelChanged(); updateRulers(); update(); //redraw cached map items QList<QGraphicsItem *> itemList = composition()->items(); QList<QGraphicsItem *>::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { QgsComposerMap *mypItem = dynamic_cast<QgsComposerMap *>( *itemIt ); if ( ( mypItem ) && ( mypItem->previewMode() == QgsComposerMap::Render ) ) { mypItem->updateCachedImage(); } } } void QgsComposerView::setZoomLevel( double zoomLevel ) { double dpi = QgsApplication::desktop()->logicalDpiX(); //monitor dpi is not always correct - so make sure the value is sane if ( ( dpi < 60 ) || ( dpi > 250 ) ) dpi = 72; //desired pixel width for 1mm on screen double scale = qBound( MIN_VIEW_SCALE, zoomLevel * dpi / 25.4, MAX_VIEW_SCALE ); setTransform( QTransform::fromScale( scale, scale ) ); updateRulers(); update(); emit zoomLevelChanged(); } void QgsComposerView::scaleSafe( double scale ) { double currentScale = transform().m11(); scale *= currentScale; scale = qBound( MIN_VIEW_SCALE, scale, MAX_VIEW_SCALE ); setTransform( QTransform::fromScale( scale, scale ) ); } void QgsComposerView::setPreviewModeEnabled( bool enabled ) { if ( !mPreviewEffect ) { return; } mPreviewEffect->setEnabled( enabled ); } void QgsComposerView::setPreviewMode( QgsPreviewEffect::PreviewMode mode ) { if ( !mPreviewEffect ) { return; } mPreviewEffect->setMode( mode ); } void QgsComposerView::setMapCanvas( QgsMapCanvas *canvas ) { mCanvas = canvas; } QgsMapCanvas *QgsComposerView::mapCanvas() const { return mCanvas; } void QgsComposerView::paintEvent( QPaintEvent *event ) { if ( mPaintingEnabled ) { QGraphicsView::paintEvent( event ); event->accept(); } else { event->ignore(); } } void QgsComposerView::hideEvent( QHideEvent *e ) { emit composerViewHide( this ); e->ignore(); } void QgsComposerView::showEvent( QShowEvent *e ) { emit composerViewShow( this ); e->ignore(); } void QgsComposerView::resizeEvent( QResizeEvent *event ) { QGraphicsView::resizeEvent( event ); emit zoomLevelChanged(); updateRulers(); } void QgsComposerView::scrollContentsBy( int dx, int dy ) { QGraphicsView::scrollContentsBy( dx, dy ); updateRulers(); } void QgsComposerView::setComposition( QgsComposition *c ) { setScene( c ); if ( mHorizontalRuler ) { mHorizontalRuler->setComposition( c ); } if ( mVerticalRuler ) { mVerticalRuler->setComposition( c ); } //emit compositionSet, so that composer windows can update for the new composition emit compositionSet( c ); } QgsComposition *QgsComposerView::composition() { if ( scene() ) { QgsComposition *c = dynamic_cast<QgsComposition *>( scene() ); if ( c ) { return c; } } return nullptr; } void QgsComposerView::groupItems() { if ( !composition() ) { return; } //group selected items QList<QgsComposerItem *> selectionList = composition()->selectedComposerItems(); QgsComposerItemGroup *itemGroup = composition()->groupItems( selectionList ); if ( !itemGroup ) { //group could not be created return; } itemGroup->setSelected( true ); emit selectedItemChanged( itemGroup ); } void QgsComposerView::ungroupItems() { if ( !composition() ) { return; } //hunt through selection for any groups, and ungroup them QList<QgsComposerItem *> selectionList = composition()->selectedComposerItems(); QList<QgsComposerItem *>::iterator itemIter = selectionList.begin(); for ( ; itemIter != selectionList.end(); ++itemIter ) { QgsComposerItemGroup *itemGroup = dynamic_cast<QgsComposerItemGroup *>( *itemIter ); if ( itemGroup ) { composition()->ungroupItems( itemGroup ); } } } QMainWindow *QgsComposerView::composerWindow() { QMainWindow *composerObject = nullptr; QObject *currentObject = parent(); if ( !currentObject ) { return qobject_cast<QMainWindow *>( currentObject ); } while ( true ) { composerObject = qobject_cast<QMainWindow *>( currentObject ); if ( composerObject || !currentObject->parent() ) { return composerObject; } currentObject = currentObject->parent(); } return nullptr; } void QgsComposerView::addPolygonNode( QPointF scenePoint ) { QPolygonF polygon = mPolygonItem->polygon(); polygon.append( QPointF( scenePoint.x(), scenePoint.y() ) ); if ( polygon.size() == 1 ) polygon.append( QPointF( scenePoint.x(), scenePoint.y() ) ); mPolygonItem->setPolygon( polygon ); } void QgsComposerView::movePolygonNode( QPointF scenePoint, bool constrainAngle ) { QPolygonF polygon = mPolygonItem->polygon(); if ( polygon.isEmpty() ) return; if ( polygon.size() > 1 && constrainAngle ) { QPointF start = polygon.at( polygon.size() - 2 ); QLineF newLine = QLineF( start, scenePoint ); //movement is contrained to 45 degree angles double angle = QgsComposerUtils::snappedAngle( newLine.angle() ); newLine.setAngle( angle ); scenePoint = newLine.p2(); } polygon.replace( polygon.size() - 1, scenePoint ); mPolygonItem->setPolygon( polygon ); } void QgsComposerView::displayNodes( const bool display ) { QList<QgsComposerNodesItem *> nodesShapes; composition()->composerItems( nodesShapes ); QList<QgsComposerNodesItem *>::iterator it = nodesShapes.begin(); for ( ; it != nodesShapes.end(); ++it ) ( *it )->setDisplayNodes( display ); scene()->update(); } void QgsComposerView::setSelectedNode( QgsComposerNodesItem *shape, const int index ) { QList<QgsComposerNodesItem *> nodesShapes; composition()->composerItems( nodesShapes ); QList<QgsComposerNodesItem *>::iterator it = nodesShapes.begin(); for ( ; it != nodesShapes.end(); ++it ) { if ( ( *it ) == shape ) { ( *it )->setSelectedNode( index ); selectNone(); ( *it )->setSelected( true ); emit selectedItemChanged( ( *it ) ); } else ( *it )->deselectNode(); } scene()->update(); } void QgsComposerView::deselectNode() { QList<QgsComposerNodesItem *> nodesShapes; composition()->composerItems( nodesShapes ); QList<QgsComposerNodesItem *>::iterator it = nodesShapes.begin(); for ( ; it != nodesShapes.end(); ++it ) ( *it )->deselectNode(); scene()->update(); }
myarjunar/QGIS
src/gui/qgscomposerview.cpp
C++
gpl-2.0
66,042
<?php // Slider extension, https://github.com/datenstrom/yellow-extensions/tree/master/source/slider class YellowSlider { const VERSION = "0.8.13"; public $yellow; // access to API // Handle initialisation public function onLoad($yellow) { $this->yellow = $yellow; $this->yellow->system->setDefault("sliderStyle", "loop"); $this->yellow->system->setDefault("sliderAutoplay", "0"); } // Handle page content of shortcut public function onParseContentShortcut($page, $name, $text, $type) { $output = null; if ($name=="slider" && ($type=="block" || $type=="inline")) { list($pattern, $style, $size, $autoplay) = $this->yellow->toolbox->getTextArguments($text); if (empty($style)) $style = $this->yellow->system->get("sliderStyle"); if (empty($size)) $size = "100%"; if (empty($autoplay)) $autoplay = $this->yellow->system->get("sliderAutoplay"); if (empty($pattern)) { $pattern = "unknown"; $files = $this->yellow->media->clean(); } else { $images = $this->yellow->system->get("coreImageDirectory"); $files = $this->yellow->media->index(true, true)->match("#$images$pattern#"); } if ($this->yellow->extension->isExisting("image")) { if (count($files)) { $page->setLastModified($files->getModified()); $output = "<div class=\"splide\" data-arrows=\"false\" data-rewind=\"true\" data-clickable=\"true\" data-type=\"".htmlspecialchars($style)."\""; if ($autoplay!=0) $output .= " data-autoplay=\"true\" data-interval=\"".htmlspecialchars($autoplay)."\""; $output .= ">\n"; $output .= "<div class=\"splide__track\"><div class=\"splide__list\">"; foreach ($files as $file) { list($src, $width, $height) = $this->yellow->extension->get("image")->getImageInformation($file->fileName, $size, $size); $caption = $this->yellow->language->isText($file->fileName) ? $this->yellow->language->getText($file->fileName) : ""; $alt = empty($caption) ? basename($file->getLocation(true)) : $caption; $output .= "<div class=\"splide__slide\"><img src=\"".htmlspecialchars($src)."\""; if ($width && $height) $output .= " width=\"".htmlspecialchars($width)."\" height=\"".htmlspecialchars($height)."\""; $output .= " alt=\"".htmlspecialchars($alt)."\" title=\"".htmlspecialchars($alt)."\""; $output .= " /></div>\n"; } $output .= "</div></div></div>"; } else { $page->error(500, "Slider '$pattern' does not exist!"); } } else { $page->error(500, "Slider requires 'image' extension!"); } } return $output; } // Handle page extra data public function onParsePageExtra($page, $name) { $output = null; if ($name=="header") { $extensionLocation = $this->yellow->system->get("coreServerBase").$this->yellow->system->get("coreExtensionLocation"); $output = "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"{$extensionLocation}slider.css\" />\n"; $output .= "<script type=\"text/javascript\" defer=\"defer\" src=\"{$extensionLocation}slider-splide.min.js\"></script>\n"; $output .= "<script type=\"text/javascript\" defer=\"defer\" src=\"{$extensionLocation}slider.js\"></script>\n"; } return $output; } }
datenstrom/yellow-plugins
source/slider/slider.php
PHP
gpl-2.0
3,789
/* general map generation class Since September 2013 | mark@prmanenttourist.ch This code is provided as-is under the GPL v2 licence, which is available via http://www.gnu.org/licenses/gpl-2.0.html, and may be freely used, adapted and built upon. No guarantee is provided or implied. Test your code! http://www.gnu.org/licenses/gpl.html Simplify generation of Google Maps on a web page The existing default usage via Google's own implementation is great, but this version adds an improved overlay function, the option to add MarkerLabel functionality by setting an option to true, and much easier addition of custom map styles. • Labels are displayed with the markers. Label content is displayed directly in the map. • Markercontent is displayed in the overlay when a marker is clicked. • The current implementation (July 2015) requires that markerclusterer_compiled.js and markerwithlabel_packed.js be linked in the HTML head if you need to use this functionality. This file is quite heavy and heavily commented. Use class.googlemaps.min.js instead. See class.googlemaps.html for a demo of how to use this script with a couple of simple options. */ var mhmli_googlemaps_rootclass, MarkerWithLabel, marker, bounds, mhmli_googlemaps, google, customStyle; (function($){ mhmli_googlemaps = { map: null, mapContainer: null, infowindow: null, infowindowContent: null, locations: [], pins: [], map_clustered: null, //////////////////////////////////////////////////////////////////////////////// // Options. Can be reset externally before drawing the map. text: { reset: 'Reset', close: 'Close' }, asset_path:'', pin_default: function(){ return null; }, useStyledMarkers: false, options: { cluster: false, // cluster markers together, when there are too many to be displayed in one go clusterstyles: null, // array containing custom attributes for the MarkerClusterer object. e.g. styles. mapTypeID: null, // e,g. google.maps.MapTypeId.HYBRID mapTypes: null, // array of types google.maps.MapTypeId lat_default: 46.817918, // default latitude lon_default: 8.227386, // default longitude zoomlevel_start: 7, // default zoom level zoomlevel_default: 7, // default zoom level zoomlevel_near: 10, // if map zooms when clicking on a marker, the zoom level to go to zoomlevel_minimum: 1, // don't let the user zoom out to more than this zoom level focus_centre: true, // when clicking on a marker, should the map centre itself on the clicked marker showLabels: false, // should labels be added to the markers? fitToBounds: false, // should the map automatically set itself to include all markers in the default view? hasInfoWindow: true, // does an infowindow appear when clicking on a marker focus_zoom: true, // when clicking on a marker, should the map zoom in to the clicked marker icon_offset: [0,0], // default icon offset icon_size: [16,16], // default icon size icon: null // optional: use your own icon }, controls: { // these options are here in order to comply with Google logic for separating controls and other options blockUI: false, // completely block all UI options including zoom, scroll etc resetbutton:true, // add a reset button to the map? visualRefresh:true, // use the new Google Maps (Summer 2013) - https://developers.google.com/maps/documentation/javascript/basics#VisualRefresh disableDefaultUI: false, // disable all default map features with one command panControl: false, // enable/disable pan controls mapTypeControl: false, // enable/disable map type controls scaleControl: true, // enable/disable scaling (zoom) controls streetViewControl: false, // enable/disable street view control overviewMapControl: false, // enable/disable overview control (bottom right; small controller to see where current section of map is, in relation to e.g. Europe) zoomControl: true, // enable/disable zoom control. if zoomControlOptions are set, they will override this option. zoomControlOptions: { // customization of individual zoom control options - https://developers.google.com/maps/documentation/javascript/controls#ControlOptions style: null, position:null } }, //////////////////////////////////////////////////////////////////////////////// setMapStyle: function(mapStyle) { if (mapStyle && mapStyle!==null) { if(this.options.mapTypes && this.options.mapTypes.length){ this.options.mapTypes.push(customStyle); } var customStyle = new google.maps.StyledMapType( mapStyle, { name: 'customStyle' }); this.map.mapTypes.set('customStyle', customStyle); this.map.setMapTypeId('customStyle'); } },//setMapStyle //////////////////////////////////////////////////////////////////////////////// Marker: function(atts) { if(atts.baseClass.options.showLabels){ marker = new MarkerWithLabel({ position: atts.position, zIndex: atts.zIndex, map: atts.map, icon: atts.icon, labelContent: atts.labelContent, markerContent: atts.markerContent, labelAnchor: new google.maps.Point(12,8), title: atts.title, locationID: atts.locationID }); }else{ marker = new google.maps.Marker({ position: atts.position, zIndex: atts.zIndex, map: atts.map, icon: atts.icon, labelContent: atts.labelContent, markerContent: atts.markerContent, title: atts.title, locationID: atts.locationID }); } marker.baseClass = atts.baseClass; return marker; },//Marker //////////////////////////////////////////////////////////////////////////////// makeMap: function(divID, layout) { if(this.controls.visualRefresh){ google.maps.visualRefresh = true; } this.mapContainer = $('#'+divID); var mapOptions = { zoom: this.options.zoomlevel_default, center: this.centrePoint(), panControl: this.controls.panControl, mapTypeControl: this.controls.mapTypeControl, scaleControl: this.controls.scaleControl, streetViewControl: this.controls.streetViewControl, overviewMapControl: this.controls.overviewMapControl, zoomControl: this.controls.zoomControl, zoomControlOptions: this.controls.zoomControlOptions }; if(this.options.mapTypes && this.options.mapTypes.length){ mapOptions.mapTypeControlOptions = { mapTypeIds: this.options.mapTypes }; mapOptions.mapTypeControl = true; } if(this.options.mapTypeID){ mapOptions.mapTypeId = this.options.mapTypeID; } if(this.controls.disableDefaultUI){ mapOptions.disableDefaultUI = true; } if(this.controls.blockUI){ mapOptions.draggable = false; mapOptions.zoomable = false; mapOptions.scrollwheel = false; mapOptions.navigationControl = false; mapOptions.mapTypeControl = false; mapOptions.scaleControl = false; mapOptions.draggable = false; } this.map = new google.maps.Map(document.getElementById(divID), mapOptions); this.map.setZoom(this.options.zoomlevel_start); this.setMapStyle(layout); if(this.options.fitToBounds){ bounds = new google.maps.LatLngBounds(); } var marker, i, baseClass=this, markers = []; for (i in this.locations) { if(this.locations.hasOwnProperty(i)){ var rp = this.locations[i].rankedPosition; marker = new this.Marker({ //map: this.map, position: new google.maps.LatLng(this.locations[i].longitude, this.locations[i].latitude), title: this.locations[i].title, labelContent: this.locations[i].labelContent, markerContent: this.locations[i].markerContent, rankedPosition: rp + '', zIndex: 10000 - i, locationID: this.locations[i].locationID, icon: this.options.icon, baseClass: this }); if(this.locations[i] && this.locations[i].icon){ var icon_offset = this.locations[i].offset ? this.locations[i].offset : this.options.icon_offset; var icon_size = this.locations[i].icon_size ? this.locations[i].icon_size : this.options.icon_size; marker.setIcon({ url: this.locations[i].icon, anchor: new google.maps.Point(icon_offset[0],icon_offset[1]), size: new google.maps.Size(icon_size[0], icon_size[1]) }); } if(this.options.fitToBounds){ bounds.extend(marker.position); } google.maps.event.addListener(marker, 'click', function(event){ baseClass.markerClickHandler(event,this,baseClass); }); markers.push(marker); } } google.maps.event.addListener(this.map, 'zoom_changed', function() { if (baseClass.map.getZoom() < baseClass.options.zoomlevel_minimum){ baseClass.map.setZoom(baseClass.options.zoomlevel_minimum); } }); if(this.options.cluster){ var markerClustererExtras = this.options.clusterstyles ? {styles:this.options.clusterstyles} : {}; this.map_clustered = new MarkerClusterer(this.map, markers, markerClustererExtras); }else{ for (var i = 0; i < markers.length; i++) { markers[i].setMap(this.map); } } if(this.options.fitToBounds){ this.map.fitBounds(bounds); } this.addResetButton(); this.monitorEscapeButton(); },//makeMap //////////////////////////////////////////////////////////////////////////////// centrePoint: function(){ return new google.maps.LatLng(this.options.lat_default, this.options.lon_default); },//centrePoint //////////////////////////////////////////////////////////////////////////////// resetMap: function(){ this.hideOverlay(); this.map.setZoom(this.options.zoomlevel_default); this.map.setCenter(this.centrePoint()); },//resetMap //////////////////////////////////////////////////////////////////////////////// markerClickHandler: function(event,marker,baseClass){ if(baseClass.options.focus_centre){ baseClass.map.panTo(marker.getPosition()); } if(baseClass.options.focus_zoom){ var currentZoom = baseClass.map.getZoom(); if(currentZoom < baseClass.options.zoomlevel_near){ baseClass.map.setZoom(baseClass.options.zoomlevel_near); } } if(baseClass.options.hasInfoWindow){ baseClass.showOverlay(baseClass.map, marker); } },//markerClickHandler //////////////////////////////////////////////////////////////////////////////// showOverlay: function(map,marker){ if(!this.infowindow){ this.infowindow = $('<div class="overlay window"><div class="wrapper"><div class="inner"><a class="close button" href="#">' +this.text.close+ '</a><div class="content"></div></div></div></div>'); this.infowindowContent = this.infowindow.find('div.content'); var mhmli_googlemaps_rootclass = this; this.infowindow.find('a.close').click(function(e){ e.preventDefault(); mhmli_googlemaps_rootclass.hideOverlay(); }); this.mapContainer.append(this.infowindow); } this.fillOverlay(marker.markerContent); this.infowindow.show(); },//showOverlay //////////////////////////////////////////////////////////////////////////////// fillOverlay: function(content){ if(this.infowindowContent){ this.infowindowContent.html(content); } },//fillOverlay //////////////////////////////////////////////////////////////////////////////// hideOverlay: function(){ if(this.infowindow){ this.infowindowContent.empty(); this.infowindow.hide(); } },//hideOverlay //////////////////////////////////////////////////////////////////////////////// addResetButton: function(){ if(this.controls.resetbutton){ this.resetButton = $('<button class="reset">' +this.text.reset+ '</button>'); baseClass=this; this.resetButton.click(function(event){ baseClass.resetMap(); }); $(this.map.b).append(this.resetButton); } },//addResetButton //////////////////////////////////////////////////////////////////////////////// monitorEscapeButton: function(){ mhmli_googlemaps_rootclass = this; $(document).keydown(function(e) { if(e.keyCode === 27 && mhmli_googlemaps_rootclass.hideOverlay){ mhmli_googlemaps_rootclass.hideOverlay(); } }); }//monitorEscapeButton }; })(jQuery);
mhmli/mhmli_googlemaps
general class/class.googlemaps.js
JavaScript
gpl-2.0
12,311
<?php die("Access Denied"); ?>#x#s:881:" 1403080887<?xml version="1.0" encoding="utf-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> <ShortName>Inppnet - Instituto Nacional de Parapsicologia Psicometafísica</ShortName> <Description>Instituto Nacional de Parapsicologia Psicometafísica. Cursos Online</Description> <InputEncoding>UTF-8</InputEncoding> <Image type="image/vnd.microsoft.icon" width="16" height="16">http://sala.inppnet.com.br/templates/ja_university/favicon.ico</Image> <Url type="application/opensearchdescription+xml" rel="self" template="http://sala.inppnet.com.br/index.php?option=com_search&amp;view=article&amp;id=164:terapia-floral&amp;catid=14:sample-data-articles&amp;Itemid=579&amp;format=opensearch"/> <Url type="text/html" template="http://sala.inppnet.com.br/index.php?option=com_search&amp;searchword={searchTerms}"/> </OpenSearchDescription> ";
damasiorafael/inppnet
cache/t3_pages/53bbb79b4980f60ea0786b85df096904-cache-t3_pages-3bce912d507110e794c2a34ff19c1ed3.php
PHP
gpl-2.0
923
<?php /** * The template for displaying all single posts. * * @package tub */ get_header(); ?> <!-- single.php --> <!-- Hero --> <div class="hero js-heroImage"> <img class="hero--image" src="<?php bloginfo(template_directory) ?>/images/header.jpg" alt="The Unassisted Baby"> <div class="overlay"></div> </div> <!-- Content --> <main id="content" class="site_content" role="main"> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('post'); ?>> <h1 class="post--title"><?php the_title(); ?></h1> <p class="post--meta">written on <?php the_date(); ?></p> <div class="post--content"> <?php the_content(); ?> </div> <footer class="post--footer"> <p class="post--footer--prev"> <?php previous_post_link('%link', '<i class="fa fa-long-arrow-left"></i> PREV POST'); ?> </p> <p class="post--footer--next"> <?php next_post_link('%link', 'NEXT POST <i class="fa fa-long-arrow-right"></i>'); ?> </p> </footer> </article> <?php get_sidebar(); ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </main> <?php get_footer(); ?>
joshevensen/theunassistedbaby.com
wp-content/themes/tub/single.php
PHP
gpl-2.0
1,305
package demos.nehe.lesson27; import demos.common.GLDisplay; import demos.common.LessonNativeLoader; /** * @author Abdul Bezrati */ public class Lesson27 extends LessonNativeLoader { public static void main(String[] args) { GLDisplay neheGLDisplay = GLDisplay .createGLDisplay("Lesson 27: Shadows"); Renderer renderer = new Renderer(); InputHandler inputHandler = new InputHandler(renderer, neheGLDisplay); neheGLDisplay.addGLEventListener(renderer); neheGLDisplay.addKeyListener(inputHandler); neheGLDisplay.start(); } }
Jotschi/jogl2-example
src/main/java/demos/nehe/lesson27/Lesson27.java
Java
gpl-2.0
562
/* * RAFTools - Copyright (C) 2016 Zane van Iperen. * Contact: zane@zanevaniperen.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, and only * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Any and all GPL restrictions may be circumvented with permission from the * the original author. */ package net.vs49688.rafview.cli.commands; import java.io.*; import net.vs49688.rafview.interpreter.*; public class RamInfo implements ICommand { private final PrintStream m_Console; public RamInfo(PrintStream out) { m_Console = out; } @Override public void process(String cmdLine, String[] args) throws CommandException, Exception { long mb = 1048576; Runtime r = Runtime.getRuntime(); m_Console.printf("Total Memory: %d MB\n", r.totalMemory() / mb); m_Console.printf("Free Memory: %d MB\n", r.freeMemory() / mb); m_Console.printf("Used Memory: %d MB\n", (r.totalMemory() - r.freeMemory()) / mb); m_Console.printf("Max Memory: %d MB\n", r.maxMemory() / mb); } @Override public String getCommand() { return "raminfo"; } @Override public String getUsageString() { return ""; } @Override public String getDescription() { return "Show the system's current memory usage"; } }
vs49688/RAFTools
src/main/java/net/vs49688/rafview/cli/commands/RamInfo.java
Java
gpl-2.0
1,855
<?php namespace TYPO3\Flow\Security\Aspect; /* * * This script belongs to the TYPO3 Flow framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Flow\Annotations as Flow; use TYPO3\Flow\Aop\JoinPointInterface; use TYPO3\Flow\Persistence\EmptyQueryResult; use TYPO3\Flow\Persistence\QueryInterface; use TYPO3\Flow\Reflection\ObjectAccess; use TYPO3\Flow\Security\Exception\InvalidQueryRewritingConstraintException; use Doctrine\Common\Collections\Collection; /** * An aspect which rewrites persistence query to filter objects one should not be able to retrieve. * * @Flow\Scope("singleton") * @Flow\Aspect */ class PersistenceQueryRewritingAspect_Original { /** * @Flow\Inject * @var \TYPO3\Flow\Security\Policy\PolicyService */ protected $policyService; /** * @Flow\Inject * @var \TYPO3\Flow\Security\Context */ protected $securityContext; /** * @Flow\Inject * @var \TYPO3\Flow\Session\SessionInterface */ protected $session; /** * @Flow\Inject * @var \TYPO3\Flow\Reflection\ReflectionService */ protected $reflectionService; /** * @Flow\Inject * @var \TYPO3\Flow\Persistence\PersistenceManagerInterface */ protected $persistenceManager; /** * @Flow\Inject * @var \TYPO3\Flow\Object\ObjectManagerInterface */ protected $objectManager; /** * Array of registered global objects that can be accessed as operands * @var array */ protected $globalObjects = array(); /** * @var \SplObjectStorage */ protected $alreadyRewrittenQueries; /** * Inject global settings, retrieves the registered global objects that might be used as operands * * @param array $settings The current Flow settings * @return void */ public function injectSettings($settings) { $this->globalObjects = $settings['aop']['globalObjects']; } /** * Constructor */ public function __construct() { $this->alreadyRewrittenQueries = new \SplObjectStorage(); } /** * Rewrites the QOM query, by adding appropriate constraints according to the policy * * @Flow\Around("setting(TYPO3.Flow.security.enable) && within(TYPO3\Flow\Persistence\QueryInterface) && method(.*->(execute|count)())") * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current joinpoint * @return mixed */ public function rewriteQomQuery(JoinPointInterface $joinPoint) { $result = $joinPoint->getAdviceChain()->proceed($joinPoint); if ($this->securityContext->areAuthorizationChecksDisabled() === TRUE || $this->policyService->hasPolicyEntriesForEntities() === FALSE) { return $result; } if ($this->securityContext->isInitialized() === FALSE) { if ($this->securityContext->canBeInitialized() === TRUE) { $this->securityContext->initialize(); } else { return $result; } } /** @var $query QueryInterface */ $query = $joinPoint->getProxy(); if ($this->alreadyRewrittenQueries->contains($query)) { return $joinPoint->getAdviceChain()->proceed($joinPoint); } else { $this->alreadyRewrittenQueries->attach($query); } $entityType = $query->getType(); $authenticatedRoles = $this->securityContext->getRoles(); if ($this->policyService->hasPolicyEntryForEntityType($entityType, $authenticatedRoles)) { if ($this->policyService->isGeneralAccessForEntityTypeGranted($entityType, $authenticatedRoles) === FALSE) { return ($joinPoint->getMethodName() === 'count') ? 0 : new EmptyQueryResult($query); } $policyConstraintsDefinition = $this->policyService->getResourcesConstraintsForEntityTypeAndRoles($entityType, $authenticatedRoles); $additionalCalculatedConstraints = $this->getQomConstraintForConstraintDefinitions($policyConstraintsDefinition, $query); if ($query->getConstraint() !== NULL && $additionalCalculatedConstraints !== NULL) { $query->matching($query->logicalAnd($query->getConstraint(), $additionalCalculatedConstraints)); } elseif ($additionalCalculatedConstraints !== NULL) { $query->matching($additionalCalculatedConstraints); } } return $joinPoint->getAdviceChain()->proceed($joinPoint); } /** * Checks, if the current policy allows the retrieval of the object fetched by getObjectDataByIdentifier() * * @Flow\Around("within(TYPO3\Flow\Persistence\PersistenceManagerInterface) && method(.*->getObjectByIdentifier()) && setting(TYPO3.Flow.security.enable)") * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current joinpoint * @return array The object data of the original object, or NULL if access is not permitted */ public function checkAccessAfterFetchingAnObjectByIdentifier(JoinPointInterface $joinPoint) { $result = $joinPoint->getAdviceChain()->proceed($joinPoint); if ($this->securityContext->areAuthorizationChecksDisabled() === TRUE || $this->policyService->hasPolicyEntriesForEntities() === FALSE) { return $result; } if ($this->securityContext->isInitialized() === FALSE) { if ($this->securityContext->canBeInitialized() === TRUE) { $this->securityContext->initialize(); } else { return $result; } } $authenticatedRoles = $this->securityContext->getRoles(); $entityType = $this->reflectionService->getClassNameByObject($result); if ($this->policyService->hasPolicyEntryForEntityType($entityType, $authenticatedRoles)) { if ($this->policyService->isGeneralAccessForEntityTypeGranted($entityType, $authenticatedRoles) === FALSE) { return NULL; } $policyConstraintsDefinition = $this->policyService->getResourcesConstraintsForEntityTypeAndRoles($entityType, $authenticatedRoles); if ($this->checkConstraintDefinitionsOnResultObject($policyConstraintsDefinition, $result) === FALSE) { return NULL; } } return $result; } /** * Builds a QOM constraint object for an array of constraint expressions * * @param array $constraintDefinitions The constraint expressions * @param \TYPO3\Flow\Persistence\QueryInterface $query The query object to build the constraint with * @return \TYPO3\Flow\Persistence\Generic\Qom\Constraint The build constraint object */ protected function getQomConstraintForConstraintDefinitions(array $constraintDefinitions, QueryInterface $query) { $resourceConstraintObjects = array(); foreach ($constraintDefinitions as $resourceConstraintsDefinition) { $resourceConstraintObject = NULL; foreach ($resourceConstraintsDefinition as $operator => $policyConstraintsDefinition) { foreach ($policyConstraintsDefinition as $key => $singlePolicyConstraintDefinition) { if ($key === 'subConstraints') { $currentConstraint = $this->getQomConstraintForConstraintDefinitions(array($singlePolicyConstraintDefinition), $query); } else { $currentConstraint = $this->getQomConstraintForSingleConstraintDefinition($singlePolicyConstraintDefinition, $query); } if ($resourceConstraintObject === NULL) { $resourceConstraintObject = $currentConstraint; continue; } switch ($operator) { case '&&': $resourceConstraintObject = $query->logicalAnd($resourceConstraintObject, $currentConstraint); break; case '&&!': $resourceConstraintObject = $query->logicalAnd($resourceConstraintObject, $query->logicalNot($currentConstraint)); break; case '||': $resourceConstraintObject = $query->logicalOr($resourceConstraintObject, $currentConstraint); break; case '||!': $resourceConstraintObject = $query->logicalOr($resourceConstraintObject, $query->logicalNot($currentConstraint)); break; } } } $resourceConstraintObjects[] = $query->logicalNot($resourceConstraintObject); } if (count($resourceConstraintObjects) > 1) { return $query->logicalAnd($resourceConstraintObjects); } elseif (count($resourceConstraintObjects) === 1) { return current($resourceConstraintObjects); } else { return NULL; } } /** * Builds a QOM constraint object for one single constraint expression * * @param array $constraintDefinition The constraint expression * @param \TYPO3\Flow\Persistence\QueryInterface $query The query object to build the constraint with * @return \TYPO3\Flow\Persistence\Generic\Qom\Constraint The build constraint object * @throws \TYPO3\Flow\Security\Exception\InvalidQueryRewritingConstraintException */ protected function getQomConstraintForSingleConstraintDefinition(array $constraintDefinition, QueryInterface $query) { if (!is_array($constraintDefinition['leftValue']) && strpos($constraintDefinition['leftValue'], 'this.') === 0) { $propertyName = substr($constraintDefinition['leftValue'], 5); $operand = $this->getValueForOperand($constraintDefinition['rightValue']); } elseif (!is_array($constraintDefinition['rightValue']) && strpos($constraintDefinition['rightValue'], 'this.') === 0) { $propertyName = substr($constraintDefinition['rightValue'], 5); $operand = $this->getValueForOperand($constraintDefinition['leftValue']); } else { throw new InvalidQueryRewritingConstraintException('An entity constraint has to have one operand that references to "this.". Got: "' . $constraintDefinition['leftValue'] . '" and "' . $constraintDefinition['rightValue'] . '"', 1267881842); } switch ($constraintDefinition['operator']) { case '==': return $query->equals($propertyName, $operand); break; case '!=': return $query->logicalNot($query->equals($propertyName, $operand)); break; case '<': return $query->lessThan($propertyName, $operand); break; case '>': return $query->greaterThan($propertyName, $operand); break; case '<=': return $query->lessThanOrEqual($propertyName, $operand); break; case '>=': return $query->greaterThanOrEqual($propertyName, $operand); break; case 'in': return $query->in($propertyName, $operand); break; case 'contains': return $query->contains($propertyName, $operand); break; case 'matches': $compositeConstraint = NULL; foreach ($operand as $operandEntry) { $currentConstraint = $query->contains($propertyName, $operandEntry); if ($compositeConstraint === NULL) { $compositeConstraint = $currentConstraint; continue; } $compositeConstraint = $query->logicalAnd($currentConstraint, $compositeConstraint); } return $compositeConstraint; break; } throw new InvalidQueryRewritingConstraintException('The configured operator of the entity constraint is not valid. Got: ' . $constraintDefinition['operator'], 1270483540); } /** * Checks, if the given constraints hold for the passed result. * * @param array $constraintDefinitions The constraint definitions array * @param object $result The result object returned by the persistence manager * @return boolean TRUE if the query result is valid for the given constraint */ protected function checkConstraintDefinitionsOnResultObject(array $constraintDefinitions, $result) { foreach ($constraintDefinitions as $resourceConstraintsDefinition) { $resourceResult = TRUE; foreach ($resourceConstraintsDefinition as $operator => $policyConstraintsDefinition) { foreach ($policyConstraintsDefinition as $key => $singlePolicyConstraintDefinition) { if ($key === 'subConstraints') { $currentResult = $this->checkConstraintDefinitionsOnResultObject(array($singlePolicyConstraintDefinition), $result); } else { $currentResult = $this->checkSingleConstraintDefinitionOnResultObject($singlePolicyConstraintDefinition, $result); } switch ($operator) { case '&&': $resourceResult = $currentResult && $resourceResult; break; case '&&!': $resourceResult = (!$currentResult) && $resourceResult; break; case '||': $resourceResult = $currentResult || $resourceResult; break; case '||!': $resourceResult = (!$currentResult) && $resourceResult; break; } } } if ($resourceResult === TRUE) { return FALSE; } } return TRUE; } /** * Checks, if the given constraint holds for the passed result. * * @param array $constraintDefinition The constraint definition array * @param object $result The result object returned by the persistence manager * @return boolean TRUE if the query result is valid for the given constraint * @throws \TYPO3\Flow\Security\Exception\InvalidQueryRewritingConstraintException */ protected function checkSingleConstraintDefinitionOnResultObject(array $constraintDefinition, $result) { $referenceToThisFound = FALSE; if (!is_array($constraintDefinition['leftValue']) && strpos($constraintDefinition['leftValue'], 'this.') === 0) { $referenceToThisFound = TRUE; $propertyPath = substr($constraintDefinition['leftValue'], 5); $leftOperand = $this->getObjectValueByPath($result, $propertyPath); } else { $leftOperand = $this->getValueForOperand($constraintDefinition['leftValue']); } if (!is_array($constraintDefinition['rightValue']) && strpos($constraintDefinition['rightValue'], 'this.') === 0) { $referenceToThisFound = TRUE; $propertyPath = substr($constraintDefinition['rightValue'], 5); $rightOperand = $this->getObjectValueByPath($result, $propertyPath); } else { $rightOperand = $this->getValueForOperand($constraintDefinition['rightValue']); } if ($referenceToThisFound === FALSE) { throw new InvalidQueryRewritingConstraintException('An entity security constraint must have at least one operand that references to "this.". Got: "' . $constraintDefinition['leftValue'] . '" and "' . $constraintDefinition['rightValue'] . '"', 1277218400); } if (is_object($leftOperand) && ( $this->reflectionService->isClassAnnotatedWith($this->reflectionService->getClassNameByObject($leftOperand), 'TYPO3\Flow\Annotations\Entity') || $this->reflectionService->isClassAnnotatedWith($this->reflectionService->getClassNameByObject($leftOperand), 'Doctrine\ORM\Mapping\Entity') ) ) { $originalLeftOperand = $leftOperand; $leftOperand = $this->persistenceManager->getIdentifierByObject($leftOperand); } if (is_object($rightOperand) && ( $this->reflectionService->isClassAnnotatedWith($this->reflectionService->getClassNameByObject($rightOperand), 'TYPO3\Flow\Annotations\Entity') || $this->reflectionService->isClassAnnotatedWith($this->reflectionService->getClassNameByObject($rightOperand), 'Doctrine\ORM\Mapping\Entity') ) ) { $originalRightOperand = $rightOperand; $rightOperand = $this->persistenceManager->getIdentifierByObject($rightOperand); } switch ($constraintDefinition['operator']) { case '!=': return ($leftOperand !== $rightOperand); break; case '==': return ($leftOperand === $rightOperand); break; case '<': return ($leftOperand < $rightOperand); break; case '>': return ($leftOperand > $rightOperand); break; case '<=': return ($leftOperand <= $rightOperand); break; case '>=': return ($leftOperand >= $rightOperand); break; case 'in': if ($rightOperand instanceof Collection) { return $rightOperand->contains(isset($originalLeftOperand) ? $originalLeftOperand : $leftOperand); } return in_array((isset($originalLeftOperand) ? $originalLeftOperand : $leftOperand), $rightOperand); break; case 'contains': if ($leftOperand instanceof Collection) { return $leftOperand->contains(isset($originalRightOperand) ? $originalRightOperand : $rightOperand); } return in_array((isset($originalRightOperand) ? $originalRightOperand : $rightOperand), $leftOperand); break; case 'matches': if ($leftOperand instanceof Collection) { $leftOperand = $leftOperand->toArray(); } if ($rightOperand instanceof Collection) { $rightOperand = $rightOperand->toArray(); } return (count(array_intersect($leftOperand, $rightOperand)) !== 0); break; } throw new InvalidQueryRewritingConstraintException('The configured operator of the entity constraint is not valid. Got: ' . $constraintDefinition['operator'], 1277222521); } /** * Returns the static value of the given operand, this might be also a global object * * @param mixed $expression The expression string representing the operand * @return mixed The calculated value */ protected function getValueForOperand($expression) { if (is_array($expression)) { $result = array(); foreach ($expression as $expressionEntry) { $result[] = $this->getValueForOperand($expressionEntry); } return $result; } elseif (is_numeric($expression)) { return $expression; } elseif ($expression === 'TRUE') { return TRUE; } elseif ($expression === 'FALSE') { return FALSE; } elseif ($expression === 'NULL') { return NULL; } elseif (strpos($expression, 'current.') === 0) { $objectAccess = explode('.', $expression, 3); $globalObjectsRegisteredClassName = $this->globalObjects[$objectAccess[1]]; $globalObject = $this->objectManager->get($globalObjectsRegisteredClassName); return $this->getObjectValueByPath($globalObject, $objectAccess[2]); } else { return trim($expression, '"\''); } } /** * Redirects directly to \TYPO3\Flow\Reflection\ObjectAccess::getPropertyPath($result, $propertyPath) * This is only needed for unit tests! * * @param mixed $object The object to fetch the property from * @param string $path The path to the property to be fetched * @return mixed The property value */ protected function getObjectValueByPath($object, $path) { return ObjectAccess::getPropertyPath($object, $path); } } namespace TYPO3\Flow\Security\Aspect; use Doctrine\ORM\Mapping as ORM; use TYPO3\Flow\Annotations as Flow; /** * An aspect which rewrites persistence query to filter objects one should not be able to retrieve. * @\TYPO3\Flow\Annotations\Scope("singleton") * @\TYPO3\Flow\Annotations\Aspect */ class PersistenceQueryRewritingAspect extends PersistenceQueryRewritingAspect_Original implements \TYPO3\Flow\Object\Proxy\ProxyInterface { /** * Autogenerated Proxy Method */ public function __construct() { if (get_class($this) === 'TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect') \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->setInstance('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect', $this); parent::__construct(); if ('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect' === get_class($this)) { $this->Flow_Proxy_injectProperties(); } } /** * Autogenerated Proxy Method */ public function __wakeup() { if (get_class($this) === 'TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect') \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->setInstance('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect', $this); if (property_exists($this, 'Flow_Persistence_RelatedEntities') && is_array($this->Flow_Persistence_RelatedEntities)) { $persistenceManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface'); foreach ($this->Flow_Persistence_RelatedEntities as $entityInformation) { $entity = $persistenceManager->getObjectByIdentifier($entityInformation['identifier'], $entityInformation['entityType'], TRUE); if (isset($entityInformation['entityPath'])) { $this->$entityInformation['propertyName'] = \TYPO3\Flow\Utility\Arrays::setValueByPath($this->$entityInformation['propertyName'], $entityInformation['entityPath'], $entity); } else { $this->$entityInformation['propertyName'] = $entity; } } unset($this->Flow_Persistence_RelatedEntities); } $this->Flow_Proxy_injectProperties(); } /** * Autogenerated Proxy Method */ public function __sleep() { $result = NULL; $this->Flow_Object_PropertiesToSerialize = array(); $reflectionService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Reflection\ReflectionService'); $reflectedClass = new \ReflectionClass('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect'); $allReflectedProperties = $reflectedClass->getProperties(); foreach ($allReflectedProperties as $reflectionProperty) { $propertyName = $reflectionProperty->name; if (in_array($propertyName, array('Flow_Aop_Proxy_targetMethodsAndGroupedAdvices', 'Flow_Aop_Proxy_groupedAdviceChains', 'Flow_Aop_Proxy_methodIsInAdviceMode'))) continue; if (isset($this->Flow_Injected_Properties) && is_array($this->Flow_Injected_Properties) && in_array($propertyName, $this->Flow_Injected_Properties)) continue; if ($reflectionService->isPropertyAnnotatedWith('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect', $propertyName, 'TYPO3\Flow\Annotations\Transient')) continue; if (is_array($this->$propertyName) || (is_object($this->$propertyName) && ($this->$propertyName instanceof \ArrayObject || $this->$propertyName instanceof \SplObjectStorage ||$this->$propertyName instanceof \Doctrine\Common\Collections\Collection))) { foreach ($this->$propertyName as $key => $value) { $this->searchForEntitiesAndStoreIdentifierArray((string)$key, $value, $propertyName); } } if (is_object($this->$propertyName) && !$this->$propertyName instanceof \Doctrine\Common\Collections\Collection) { if ($this->$propertyName instanceof \Doctrine\ORM\Proxy\Proxy) { $className = get_parent_class($this->$propertyName); } else { $varTagValues = $reflectionService->getPropertyTagValues('TYPO3\Flow\Security\Aspect\PersistenceQueryRewritingAspect', $propertyName, 'var'); if (count($varTagValues) > 0) { $className = trim($varTagValues[0], '\\'); } if (\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->isRegistered($className) === FALSE) { $className = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getObjectNameByClassName(get_class($this->$propertyName)); } } if ($this->$propertyName instanceof \TYPO3\Flow\Persistence\Aspect\PersistenceMagicInterface && !\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface')->isNewObject($this->$propertyName) || $this->$propertyName instanceof \Doctrine\ORM\Proxy\Proxy) { if (!property_exists($this, 'Flow_Persistence_RelatedEntities') || !is_array($this->Flow_Persistence_RelatedEntities)) { $this->Flow_Persistence_RelatedEntities = array(); $this->Flow_Object_PropertiesToSerialize[] = 'Flow_Persistence_RelatedEntities'; } $identifier = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface')->getIdentifierByObject($this->$propertyName); if (!$identifier && $this->$propertyName instanceof \Doctrine\ORM\Proxy\Proxy) { $identifier = current(\TYPO3\Flow\Reflection\ObjectAccess::getProperty($this->$propertyName, '_identifier', TRUE)); } $this->Flow_Persistence_RelatedEntities[$propertyName] = array( 'propertyName' => $propertyName, 'entityType' => $className, 'identifier' => $identifier ); continue; } if ($className !== FALSE && (\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getScope($className) === \TYPO3\Flow\Object\Configuration\Configuration::SCOPE_SINGLETON || $className === 'TYPO3\Flow\Object\DependencyInjection\DependencyProxy')) { continue; } } $this->Flow_Object_PropertiesToSerialize[] = $propertyName; } $result = $this->Flow_Object_PropertiesToSerialize; return $result; } /** * Autogenerated Proxy Method */ private function searchForEntitiesAndStoreIdentifierArray($path, $propertyValue, $originalPropertyName) { if (is_array($propertyValue) || (is_object($propertyValue) && ($propertyValue instanceof \ArrayObject || $propertyValue instanceof \SplObjectStorage))) { foreach ($propertyValue as $key => $value) { $this->searchForEntitiesAndStoreIdentifierArray($path . '.' . $key, $value, $originalPropertyName); } } elseif ($propertyValue instanceof \TYPO3\Flow\Persistence\Aspect\PersistenceMagicInterface && !\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface')->isNewObject($propertyValue) || $propertyValue instanceof \Doctrine\ORM\Proxy\Proxy) { if (!property_exists($this, 'Flow_Persistence_RelatedEntities') || !is_array($this->Flow_Persistence_RelatedEntities)) { $this->Flow_Persistence_RelatedEntities = array(); $this->Flow_Object_PropertiesToSerialize[] = 'Flow_Persistence_RelatedEntities'; } if ($propertyValue instanceof \Doctrine\ORM\Proxy\Proxy) { $className = get_parent_class($propertyValue); } else { $className = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getObjectNameByClassName(get_class($propertyValue)); } $identifier = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface')->getIdentifierByObject($propertyValue); if (!$identifier && $propertyValue instanceof \Doctrine\ORM\Proxy\Proxy) { $identifier = current(\TYPO3\Flow\Reflection\ObjectAccess::getProperty($propertyValue, '_identifier', TRUE)); } $this->Flow_Persistence_RelatedEntities[$originalPropertyName . '.' . $path] = array( 'propertyName' => $originalPropertyName, 'entityType' => $className, 'identifier' => $identifier, 'entityPath' => $path ); $this->$originalPropertyName = \TYPO3\Flow\Utility\Arrays::setValueByPath($this->$originalPropertyName, $path, NULL); } } /** * Autogenerated Proxy Method */ private function Flow_Proxy_injectProperties() { $this->injectSettings(\TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Configuration\ConfigurationManager')->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow')); $policyService_reference = &$this->policyService; $this->policyService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Security\Policy\PolicyService'); if ($this->policyService === NULL) { $this->policyService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('16231078e783810895dba92e364c25f7', $policyService_reference); if ($this->policyService === NULL) { $this->policyService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('16231078e783810895dba92e364c25f7', $policyService_reference, 'TYPO3\Flow\Security\Policy\PolicyService', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Security\Policy\PolicyService'); }); } } $securityContext_reference = &$this->securityContext; $this->securityContext = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Security\Context'); if ($this->securityContext === NULL) { $this->securityContext = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('48836470c14129ade5f39e28c4816673', $securityContext_reference); if ($this->securityContext === NULL) { $this->securityContext = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('48836470c14129ade5f39e28c4816673', $securityContext_reference, 'TYPO3\Flow\Security\Context', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Security\Context'); }); } } $session_reference = &$this->session; $this->session = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Session\SessionInterface'); if ($this->session === NULL) { $this->session = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('3055dab6d586d9b0b7e34ad0e5d2b702', $session_reference); if ($this->session === NULL) { $this->session = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('3055dab6d586d9b0b7e34ad0e5d2b702', $session_reference, 'TYPO3\Flow\Session\SessionInterface', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Session\SessionInterface'); }); } } $reflectionService_reference = &$this->reflectionService; $this->reflectionService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Reflection\ReflectionService'); if ($this->reflectionService === NULL) { $this->reflectionService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('921ad637f16d2059757a908fceaf7076', $reflectionService_reference); if ($this->reflectionService === NULL) { $this->reflectionService = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('921ad637f16d2059757a908fceaf7076', $reflectionService_reference, 'TYPO3\Flow\Reflection\ReflectionService', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Reflection\ReflectionService'); }); } } $persistenceManager_reference = &$this->persistenceManager; $this->persistenceManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Persistence\PersistenceManagerInterface'); if ($this->persistenceManager === NULL) { $this->persistenceManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('f1bc82ad47156d95485678e33f27c110', $persistenceManager_reference); if ($this->persistenceManager === NULL) { $this->persistenceManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('f1bc82ad47156d95485678e33f27c110', $persistenceManager_reference, 'TYPO3\Flow\Persistence\Doctrine\PersistenceManager', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Persistence\PersistenceManagerInterface'); }); } } $objectManager_reference = &$this->objectManager; $this->objectManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getInstance('TYPO3\Flow\Object\ObjectManagerInterface'); if ($this->objectManager === NULL) { $this->objectManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->getLazyDependencyByHash('0c3c44be7be16f2a287f1fb2d068dde4', $objectManager_reference); if ($this->objectManager === NULL) { $this->objectManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->createLazyDependency('0c3c44be7be16f2a287f1fb2d068dde4', $objectManager_reference, 'TYPO3\Flow\Object\ObjectManager', function() { return \TYPO3\Flow\Core\Bootstrap::$staticObjectManager->get('TYPO3\Flow\Object\ObjectManagerInterface'); }); } } $this->Flow_Injected_Properties = array ( 0 => 'settings', 1 => 'policyService', 2 => 'securityContext', 3 => 'session', 4 => 'reflectionService', 5 => 'persistenceManager', 6 => 'objectManager', ); } } #
garvitdelhi/emulate
Data/Temporary/Development/Cache/Code/Flow_Object_Classes/TYPO3_Flow_Security_Aspect_PersistenceQueryRewritingAspect.php
PHP
gpl-2.0
31,121
<?php get_header(); /* Template Name: About Page */ ?> <?php // check if the flexible content field has rows of data if( have_rows('content_type') ): // loop through the rows of data while ( have_rows('content_type') ) : the_row(); // type 1 if( get_row_layout() == 'main_image' ): ?> <div class="container"> <div class="row"> <div class="col-xs-12 text-center"> <img src="<?php the_sub_field('image'); ?>" alt=""> </div> </div> </div> <?php // type 2 elseif( get_row_layout() == 'main_text' ): ?> <div style="padding:150px 0px; background-color:<?php the_sub_field('bg_color');?>"> <div class="container"> <div class="col-xs-12 text-center"> <h1><?php the_sub_field('text');?></h1> </div> </div> </div> <?php // type 3 elseif( get_row_layout() == 'col2' ): ?> <div class="container"> <div class="col-xs-12 col-sm-6"> <?php the_sub_field('col1');?> </div> <div class="col-xs-12 col-sm-6"> <?php the_sub_field('col2');?> </div> </div> </div> <?php endif; endwhile; else : // no layouts found endif; ?> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <?php $accordion = get_field('accordion'); $i = 1; foreach($accordion as $row){ ?> <div class="panel panel-default"> <div class="panel-heading" role="tab"> <h4 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#<?php echo 'a'.$i; ?>" aria-expanded="true" aria-controls="collapseOne"> <?php echo $row['title']; ?> </a> </h4> </div> <div id="<?php echo 'a'.$i; ?>" class="panel-collapse collapse <?php if($i==1){ echo 'in';}?>" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> <?php echo $row['content']; ?> </div> </div> </div> <?php $i++; } ?> </div> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <?php $slides = get_field('slides'); $i = 1; foreach($slides as $slide){ if($i == 1){ echo '<div class="item active"><img src="'.$slide['image'].'"></div>'; } else { echo '<div class="item"><img src="'.$slide['image'].'"></div>'; } $i++; } ?> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="row" style="background-color:<?php the_field('color'); ?>"> <?php if(have_posts()) : while (have_posts()) : the_post(); ?> <div class="col-xs-3"> <h2><?php the_title(); ?></h2> </div> <div class="col-xs-9" > <img src="<?php the_field('main_image'); ?>" alt=""> <?php the_field('company_info'); ?> </div> <?php endwhile; else: ?> <p>Sorry, no pages matched your criteria.</p> <?php endif; ?> </div> <?php get_footer(); ?>
trevorgreenleaf/zoom
wp-content/themes/basic/page-about.php
PHP
gpl-2.0
3,390
#include <cmath> #include <iostream> using namespace std; int main() { int num = 4.4; cout << ceil(num) << endl; return 0; }
songpengwei/Algorithms
math/ceil.cc
C++
gpl-2.0
140
module.exports = { user : 'Your Github Username', cal : 'Google calendar id to update' };
mike-audi/gh-gcal
example.config.js
JavaScript
gpl-2.0
92
/* This source file is a part of the GePhex Project. Copyright (C) 2001-2004 Georg Seidel <georg@gephex.org> Martin Bayer <martin@gephex.org> Phillip Promesberger <coma@gephex.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.*/ //TODO Unterschied zwischen string::size() und string::length() nachschauen #include "structscanner.h" #include "stringtokenizer.h" StructScanner::StructScanner(IStructTokenListener& listener) : m_listener(listener) { } static std::string trim(const std::string& s, const std::string& delim) { std::string::size_type pos = s.find_first_not_of(delim); if (pos == std::string::npos) return std::string(); std::string::size_type pos2 = s.find_first_of(delim,pos); if (pos2 == std::string::npos) return s.substr(pos,s.length()); return s.substr(pos,pos2); } void StructScanner::divideNameFromContent(const std::string& text, std::string& name,std::string& content) const { std::string::size_type pos = text.find('{'); if (pos == std::string::npos) { throw std::runtime_error("Fehler beim scannen: { nicht vorhanden!"); } name = trim(text.substr(0,pos)," \n\t"); std::string::size_type pos2 = text.rfind('}'); if (pos2 == std::string::npos) { throw std::runtime_error("Fehler beim scannen: } nicht vorhanden!"); } content = text.substr(pos+1,pos2); } void StructScanner::processName(const std::string& name) const { m_listener.scannedStructName(name); } void StructScanner::processContent(const std::string& content) const { StringTokenizer st(content); std::string var = st.next(";="); while (var != "") { std::string value = st.next("';"); m_listener.scannedPair(trim(var,"\n\t "),value); var = trim(st.next("=")," \n\t"); } /*std::string::size_type pos = content.find("="); if (content[pos+1] == '\'') { } else { StringTokenizer st(content,pos+1); value = st.next(" \n\t"); }*/ } void StructScanner::scan(const std::string& text) const throw (std::runtime_error) { std::string name; std::string content; divideNameFromContent(text,name,content); processName(name); processContent(content); }
ChristianFrisson/gephex
base/src/utils/structscannerOLD.cpp
C++
gpl-2.0
2,760
<script type="text/template" id="ae-report-loop"> <div class="form-group-work-place"> <div class="info-avatar-report"> <a href="#" class="avatar-employer-report"> {{=avatar}} </a> <div class="info-report"> <span class="name-report">{{= display_name }}</span> <div class="date-chat-report"> {{= message_time }} </div> </div> </div> <div class="clearfix"></div> <div class="content-report-wrapper"> <div class="content-report"> {{= comment_content }} </div> <# if(file_list){ #> <div class="title-attachment"><?php _e("Attachment", ET_DOMAIN); ?></div> {{= file_list }} <# } #> </div> </div> </script> <div class="modal fade" id="acceptance_project" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <i class="fa fa-times"></i> </button> <h4 class="modal-title"> <?php _e("Bid acceptance", ET_DOMAIN) ?> </h4> </div> <div class="modal-body"> <form role="form" id="escrow_bid" class=""> <div class="escrow-info"> <!-- bid info content here --> </div> <?php do_action('fre_after_accept_bid_infor'); ?> <div class="form-group"> <button type="submit" class="btn-submit btn btn-primary btn-sumary btn-sub-create"> <?php _e('Accept Bid', ET_DOMAIN) ?> </button> </div> </form> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog login --> </div><!-- /.modal --> <!-- MODAL BID acceptance PROJECT--> <script type="text/template" id="bid-info-template"> <label style="line-height:2.5;"><?php _e( 'You are about to accept this bid for' , ET_DOMAIN ); ?></label> <p><strong class="color-green">{{=budget}}</strong><strong class="color-green"><i class="fa fa-check"></i></strong></p> <br> <label style="line-height:2.5;"><?php _e( 'You have to pay' , ET_DOMAIN ); ?><br></label> <p class="text-credit-small"> <?php _e( 'Budget' , ET_DOMAIN ); ?> &nbsp; <strong>{{= budget }}</strong> </p> <# if(commission){ #> <p class="text-credit-small"><?php _e( 'Commission' , ET_DOMAIN ); ?> &nbsp; <strong style="color: #1faf67;">{{= commission }}</strong> </p> <# } #> <p class="text-credit-small"><?php _e( 'Total' , ET_DOMAIN ); ?> &nbsp; <strong style="color:#e74c3c;">{{=total}}</strong> </p> <br> </script>
BestWebTech/creativefreelanceprofessionals
wp-content/themes/freelanceengine/mobile/template-js/report-item.php
PHP
gpl-2.0
3,031
#include <iostream> #include "DVB.hh" int main(int argc, char **argv) { ifstream con(argv[1]); DVB dvbd(-1); con >> dvbd; // dvbd.set_outtype(VDR_OUT); cout << dvbd; }
esurharun/libdvb
sample_progs/conv.cc
C++
gpl-2.0
183
/* * Copyright (c) 2006 Sean C. Rhea (srhea@srhea.net) * Copyright (c) 2010 Mark Liversedge (liversedge@gmail.com) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "AllPlot.h" #include "Context.h" #include "Athlete.h" #include "AllPlotWindow.h" #include "AllPlotSlopeCurve.h" #include "ReferenceLineDialog.h" #include "RideFile.h" #include "RideItem.h" #include "IntervalItem.h" #include "IntervalTreeView.h" #include "Settings.h" #include "Units.h" #include "Zones.h" #include "Colors.h" #include "WPrime.h" #include "IndendPlotMarker.h" #include <qwt_plot_curve.h> #include <qwt_plot_canvas.h> #include <qwt_plot_intervalcurve.h> #include <qwt_plot_grid.h> #include <qwt_plot_layout.h> #include <qwt_plot_marker.h> #include <qwt_scale_div.h> #include <qwt_scale_widget.h> #include <qwt_compat.h> #include <qwt_text.h> #include <qwt_legend.h> #include <qwt_series_data.h> #include <QMultiMap> #include <string.h> // for memcpy class IntervalPlotData : public QwtSeriesData<QPointF> { public: IntervalPlotData(AllPlot *allPlot, Context *context, AllPlotWindow *window) : allPlot(allPlot), context(context), window(window) {} double x(size_t i) const ; double y(size_t i) const ; size_t size() const ; //virtual QwtData *copy() const ; void init() ; IntervalItem *intervalNum(int n) const; int intervalCount() const; AllPlot *allPlot; Context *context; AllPlotWindow *window; virtual QPointF sample(size_t i) const; virtual QRectF boundingRect() const; }; // define a background class to handle shading of power zones // draws power zone bands IF zones are defined and the option // to draw bonds has been selected class AllPlotBackground: public QwtPlotItem { private: AllPlot *parent; public: AllPlotBackground(AllPlot *_parent) { setZ(-100.0); parent = _parent; } virtual int rtti() const { return QwtPlotItem::Rtti_PlotUserItem; } virtual void draw(QPainter *painter, const QwtScaleMap &, const QwtScaleMap &yMap, const QRectF &rect) const { RideItem *rideItem = parent->rideItem; // get zone data from ride or athlete ... const Zones *zones; int zone_range = -1; if (parent->context->isCompareIntervals) { zones = parent->context->athlete->zones(); if (!zones) return; // use first compare interval date if (parent->context->compareIntervals.count()) zone_range = zones->whichRange(parent->context->compareIntervals[0].data->startTime().date()); // still not set if (zone_range == -1) zone_range = zones->whichRange(QDate::currentDate()); } else if (rideItem && parent->context->athlete->zones()) { zones = parent->context->athlete->zones(); zone_range = parent->context->athlete->zones()->whichRange(rideItem->dateTime.date()); } else { return; // nulls } if (parent->shadeZones() && (zone_range >= 0)) { QList <int> zone_lows = zones->getZoneLows(zone_range); int num_zones = zone_lows.size(); if (num_zones > 0) { for (int z = 0; z < num_zones; z ++) { QRect r = rect.toRect(); QColor shading_color = zoneColor(z, num_zones); shading_color.setHsv( shading_color.hue(), shading_color.saturation() / 4, shading_color.value() ); r.setBottom(yMap.transform(zone_lows[z])); if (z + 1 < num_zones) r.setTop(yMap.transform(zone_lows[z + 1])); if (r.top() <= r.bottom()) painter->fillRect(r, shading_color); } } } else { } } }; // Zone labels are drawn if power zone bands are enabled, automatically // at the center of the plot class AllPlotZoneLabel: public QwtPlotItem { private: AllPlot *parent; int zone_number; double watts; QwtText text; public: AllPlotZoneLabel(AllPlot *_parent, int _zone_number) { parent = _parent; zone_number = _zone_number; RideItem *rideItem = parent->rideItem; // get zone data from ride or athlete ... const Zones *zones; int zone_range = -1; if (parent->context->isCompareIntervals) { zones = parent->context->athlete->zones(); if (!zones) return; // use first compare interval date if (parent->context->compareIntervals.count()) zone_range = zones->whichRange(parent->context->compareIntervals[0].data->startTime().date()); // still not set if (zone_range == -1) zone_range = zones->whichRange(QDate::currentDate()); } else if (rideItem && parent->context->athlete->zones()) { zones = parent->context->athlete->zones(); zone_range = parent->context->athlete->zones()->whichRange(rideItem->dateTime.date()); } else { return; // nulls } // create new zone labels if we're shading if (parent->shadeZones() && (zone_range >= 0)) { QList <int> zone_lows = zones->getZoneLows(zone_range); QList <QString> zone_names = zones->getZoneNames(zone_range); int num_zones = zone_lows.size(); if (zone_names.size() != num_zones) return; if (zone_number < num_zones) { watts = ( (zone_number + 1 < num_zones) ? 0.5 * (zone_lows[zone_number] + zone_lows[zone_number + 1]) : ( (zone_number > 0) ? (1.5 * zone_lows[zone_number] - 0.5 * zone_lows[zone_number - 1]) : 2.0 * zone_lows[zone_number] ) ); text = QwtText(zone_names[zone_number]); if (_parent->referencePlot == NULL) { text.setFont(QFont("Helvetica",24, QFont::Bold)); } else { text.setFont(QFont("Helvetica",12, QFont::Bold)); } QColor text_color = zoneColor(zone_number, num_zones); text_color.setAlpha(64); text.setColor(text_color); } } setZ(-99.00 + zone_number / 100.0); } virtual int rtti() const { return QwtPlotItem::Rtti_PlotUserItem; } void draw(QPainter *painter, const QwtScaleMap &, const QwtScaleMap &yMap, const QRectF &rect) const { if (parent->shadeZones()) { int x = (rect.left() + rect.right()) / 2; int y = yMap.transform(watts); // the following code based on source for QwtPlotMarker::draw() QRect tr(QPoint(0, 0), text.textSize(painter->font()).toSize()); tr.moveCenter(QPoint(x, y)); text.draw(painter, tr); } } }; class TimeScaleDraw: public ScaleScaleDraw { public: TimeScaleDraw(bool *bydist) : ScaleScaleDraw(), bydist(bydist) {} virtual QwtText label(double v) const { if (*bydist) { return QString("%1").arg(v); } else { QTime t = QTime(0,0,0,0).addSecs(v*60.00); if (scaleMap().sDist() > 5) return t.toString("hh:mm"); return t.toString("hh:mm:ss"); } } private: bool *bydist; }; static inline double max(double a, double b) { if (a > b) return a; else return b; } AllPlotObject::AllPlotObject(AllPlot *plot) : plot(plot) { maxKM = maxSECS = 0; wattsCurve = new QwtPlotCurve(tr("Power")); wattsCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); wattsCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); antissCurve = new QwtPlotCurve(tr("anTISS")); antissCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); antissCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 3)); atissCurve = new QwtPlotCurve(tr("aTISS")); atissCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); atissCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 3)); npCurve = new QwtPlotCurve(tr("NP")); npCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); npCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); rvCurve = new QwtPlotCurve(tr("Vertical Oscillation")); rvCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rvCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); rcadCurve = new QwtPlotCurve(tr("Run Cadence")); rcadCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rcadCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); rgctCurve = new QwtPlotCurve(tr("GCT")); rgctCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rgctCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); gearCurve = new QwtPlotCurve(tr("Gear Ratio")); gearCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); gearCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); gearCurve->setStyle(QwtPlotCurve::Steps); gearCurve->setCurveAttribute(QwtPlotCurve::Inverted); smo2Curve = new QwtPlotCurve(tr("SmO2")); smo2Curve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); smo2Curve->setYAxis(QwtAxisId(QwtAxis::yLeft, 1)); thbCurve = new QwtPlotCurve(tr("tHb")); thbCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thbCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); o2hbCurve = new QwtPlotCurve(tr("O2Hb")); o2hbCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); o2hbCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); hhbCurve = new QwtPlotCurve(tr("HHb")); hhbCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); hhbCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); xpCurve = new QwtPlotCurve(tr("xPower")); xpCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); xpCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); apCurve = new QwtPlotCurve(tr("aPower")); apCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); apCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 0)); hrCurve = new QwtPlotCurve(tr("Heart Rate")); hrCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); hrCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 1)); tcoreCurve = new QwtPlotCurve(tr("Core Temp")); tcoreCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); tcoreCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 1)); accelCurve = new QwtPlotCurve(tr("Acceleration")); accelCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); accelCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); wattsDCurve = new QwtPlotCurve(tr("Power Delta")); wattsDCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); wattsDCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); cadDCurve = new QwtPlotCurve(tr("Cadence Delta")); cadDCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); cadDCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); nmDCurve = new QwtPlotCurve(tr("Torque Delta")); nmDCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); nmDCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); hrDCurve = new QwtPlotCurve(tr("Heartrate Delta")); hrDCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); hrDCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); speedCurve = new QwtPlotCurve(tr("Speed")); speedCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); speedCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); cadCurve = new QwtPlotCurve(tr("Cadence")); cadCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); cadCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 1)); altCurve = new QwtPlotCurve(tr("Altitude")); altCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); // standard->altCurve->setRenderHint(QwtPlotItem::RenderAntialiased); altCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 1)); altCurve->setZ(-10); // always at the back. altSlopeCurve = new AllPlotSlopeCurve(tr("Alt/Slope")); altSlopeCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); altSlopeCurve->setStyle(AllPlotSlopeCurve::SlopeDist1); altSlopeCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 1)); altSlopeCurve->setZ(-5); // always at the back. slopeCurve = new QwtPlotCurve(tr("Slope")); slopeCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); slopeCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); tempCurve = new QwtPlotCurve(tr("Temperature")); tempCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); if (plot->context->athlete->useMetricUnits) tempCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); else tempCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 1)); // with cadence windCurve = new QwtPlotIntervalCurve(tr("Wind")); windCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); torqueCurve = new QwtPlotCurve(tr("Torque")); torqueCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); torqueCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 0)); balanceLCurve = new QwtPlotCurve(tr("Left Balance")); balanceLCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); balanceLCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); balanceRCurve = new QwtPlotCurve(tr("Right Balance")); balanceRCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); balanceRCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); lteCurve = new QwtPlotCurve(tr("Left Torque Efficiency")); lteCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); lteCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); rteCurve = new QwtPlotCurve(tr("Right Torque Efficiency")); rteCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rteCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); lpsCurve = new QwtPlotCurve(tr("Left Pedal Smoothness")); lpsCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); lpsCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); rpsCurve = new QwtPlotCurve(tr("Right Pedal Smoothness")); rpsCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rpsCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); lpcoCurve = new QwtPlotCurve(tr("Left Pedal Center Offset")); lpcoCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); lpcoCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); rpcoCurve = new QwtPlotCurve(tr("Right Pedal Center Offset")); rpcoCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); rpcoCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); lppCurve = new QwtPlotIntervalCurve(tr("Left Pedal Power Phase")); lppCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); rppCurve = new QwtPlotIntervalCurve(tr("Right Pedal Power Phase")); rppCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); lpppCurve = new QwtPlotIntervalCurve(tr("Left Peak Pedal Power Phase")); lpppCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); rpppCurve = new QwtPlotIntervalCurve(tr("Right Peak Pedal Power Phase")); rpppCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 3)); wCurve = new QwtPlotCurve(tr("W' Balance (kJ)")); wCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); wCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 2)); mCurve = new QwtPlotCurve(tr("Matches")); mCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); mCurve->setStyle(QwtPlotCurve::Dots); mCurve->setYAxis(QwtAxisId(QwtAxis::yRight, 2)); curveTitle.attach(plot); curveTitle.setLabelAlignment(Qt::AlignRight); intervalHighlighterCurve = new QwtPlotCurve(); intervalHighlighterCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 2)); intervalHighlighterCurve->setBaseline(-20); // go below axis intervalHighlighterCurve->setZ(-20); // behind alt but infront of zones intervalHighlighterCurve->attach(plot); intervalHoverCurve = new QwtPlotCurve(); intervalHoverCurve->setYAxis(QwtAxisId(QwtAxis::yLeft, 2)); intervalHoverCurve->setBaseline(-20); // go below axis intervalHoverCurve->setZ(-20); // behind alt but infront of zones intervalHoverCurve->attach(plot); // setup that standard->grid grid = new QwtPlotGrid(); grid->enableX(false); // not needed grid->enableY(true); grid->attach(plot); } // we tend to only do this for the compare objects void AllPlotObject::setColor(QColor color) { QList<QwtPlotCurve*> worklist; worklist << mCurve << wCurve << wattsCurve << atissCurve << antissCurve << npCurve << xpCurve << speedCurve << accelCurve << wattsDCurve << cadDCurve << nmDCurve << hrDCurve << apCurve << cadCurve << tempCurve << hrCurve << tcoreCurve << torqueCurve << balanceLCurve << balanceRCurve << lteCurve << rteCurve << lpsCurve << rpsCurve << lpcoCurve << rpcoCurve << altCurve << slopeCurve << altSlopeCurve << rvCurve << rcadCurve << rgctCurve << gearCurve << smo2Curve << thbCurve << o2hbCurve << hhbCurve; // work through getting progressively lighter QPen pen; pen.setWidth(1.0); int alpha = 200; bool antialias = appsettings->value(this, GC_ANTIALIAS, true).toBool(); foreach(QwtPlotCurve *c, worklist) { pen.setColor(color); color.setAlpha(alpha); c->setPen(pen); if (antialias) c->setRenderHint(QwtPlotItem::RenderAntialiased); // lighten up for the next guy color = color.darker(110); if (alpha > 10) alpha -= 10; } // has to be different... windCurve->setPen(pen); if (antialias)windCurve->setRenderHint(QwtPlotItem::RenderAntialiased); lppCurve->setPen(pen); if (antialias)lppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); rppCurve->setPen(pen); if (antialias)rppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); lpppCurve->setPen(pen); if (antialias)lpppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); rpppCurve->setPen(pen); if (antialias)rpppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); // and alt needs a feint brush altCurve->setBrush(QBrush(altCurve->pen().color().lighter(150))); } // wipe those curves AllPlotObject::~AllPlotObject() { grid->detach(); delete grid; mCurve->detach(); delete mCurve; wCurve->detach(); delete wCurve; wattsCurve->detach(); delete wattsCurve; atissCurve->detach(); delete atissCurve; antissCurve->detach(); delete antissCurve; npCurve->detach(); delete npCurve; rcadCurve->detach(); delete rcadCurve; rvCurve->detach(); delete rvCurve; rgctCurve->detach(); delete rgctCurve; gearCurve->detach(); delete gearCurve; smo2Curve->detach(); delete smo2Curve; thbCurve->detach(); delete thbCurve; o2hbCurve->detach(); delete o2hbCurve; hhbCurve->detach(); delete hhbCurve; xpCurve->detach(); delete xpCurve; apCurve->detach(); delete apCurve; hrCurve->detach(); delete hrCurve; tcoreCurve->detach(); delete tcoreCurve; speedCurve->detach(); delete speedCurve; accelCurve->detach(); delete accelCurve; wattsDCurve->detach(); delete wattsDCurve; cadDCurve->detach(); delete cadDCurve; nmDCurve->detach(); delete nmDCurve; hrDCurve->detach(); delete hrDCurve; cadCurve->detach(); delete cadCurve; altCurve->detach(); delete altCurve; slopeCurve->detach(); delete slopeCurve; altSlopeCurve->detach(); delete altSlopeCurve; tempCurve->detach(); delete tempCurve; windCurve->detach(); delete windCurve; torqueCurve->detach(); delete torqueCurve; balanceLCurve->detach(); delete balanceLCurve; balanceRCurve->detach(); delete balanceRCurve; lteCurve->detach(); delete lteCurve; rteCurve->detach(); delete rteCurve; lpsCurve->detach(); delete lpsCurve; rpsCurve->detach(); delete rpsCurve; lpcoCurve->detach(); delete lpcoCurve; rpcoCurve->detach(); delete rpcoCurve; lppCurve->detach(); delete lppCurve; rppCurve->detach(); delete rppCurve; lpppCurve->detach(); delete lpppCurve; rpppCurve->detach(); delete rpppCurve; } void AllPlotObject::setVisible(bool show) { if (show == false) { grid->detach(); mCurve->detach(); wCurve->detach(); wattsCurve->detach(); npCurve->detach(); rcadCurve->detach(); rvCurve->detach(); rgctCurve->detach(); gearCurve->detach(); smo2Curve->detach(); thbCurve->detach(); o2hbCurve->detach(); hhbCurve->detach(); atissCurve->detach(); antissCurve->detach(); xpCurve->detach(); apCurve->detach(); hrCurve->detach(); tcoreCurve->detach(); speedCurve->detach(); accelCurve->detach(); wattsDCurve->detach(); cadDCurve->detach(); nmDCurve->detach(); hrDCurve->detach(); cadCurve->detach(); altCurve->detach(); slopeCurve->detach(); altSlopeCurve->detach(); tempCurve->detach(); windCurve->detach(); torqueCurve->detach(); lteCurve->detach(); rteCurve->detach(); lpsCurve->detach(); rpsCurve->detach(); lpcoCurve->detach(); rpcoCurve->detach(); lppCurve->detach(); rppCurve->detach(); lpppCurve->detach(); rpppCurve->detach(); balanceLCurve->detach(); balanceRCurve->detach(); intervalHighlighterCurve->detach(); intervalHoverCurve->detach(); // marks, calibrations and reference lines foreach(QwtPlotMarker *mrk, d_mrk) { mrk->detach(); } foreach(QwtPlotCurve *referenceLine, referenceLines) { referenceLine->detach(); } } else { altCurve->attach(plot); // always do first as it hasa brush grid->attach(plot); mCurve->attach(plot); wCurve->attach(plot); wattsCurve->attach(plot); slopeCurve->attach(plot); altSlopeCurve->attach(plot); npCurve->attach(plot); rvCurve->attach(plot); rcadCurve->attach(plot); rgctCurve->attach(plot); gearCurve->attach(plot); smo2Curve->attach(plot); thbCurve->attach(plot); o2hbCurve->attach(plot); hhbCurve->attach(plot); atissCurve->attach(plot); antissCurve->attach(plot); xpCurve->attach(plot); apCurve->attach(plot); hrCurve->attach(plot); tcoreCurve->attach(plot); speedCurve->attach(plot); accelCurve->attach(plot); wattsDCurve->attach(plot); cadDCurve->attach(plot); nmDCurve->attach(plot); hrDCurve->attach(plot); cadCurve->attach(plot); tempCurve->attach(plot); windCurve->attach(plot); torqueCurve->attach(plot); lteCurve->attach(plot); rteCurve->attach(plot); lpsCurve->attach(plot); rpsCurve->attach(plot); lpcoCurve->attach(plot); rpcoCurve->attach(plot); lppCurve->attach(plot); rppCurve->attach(plot); lpppCurve->attach(plot); rpppCurve->attach(plot); balanceLCurve->attach(plot); balanceRCurve->attach(plot); intervalHighlighterCurve->attach(plot); intervalHoverCurve->attach(plot); // marks, calibrations and reference lines foreach(QwtPlotMarker *mrk, d_mrk) { mrk->attach(plot); } foreach(QwtPlotCurve *referenceLine, referenceLines) { referenceLine->attach(plot); } } } void AllPlotObject::hideUnwanted() { if (plot->showPowerState>1) wattsCurve->detach(); if (!plot->showNP) npCurve->detach(); if (!plot->showRV) rvCurve->detach(); if (!plot->showRCad) rcadCurve->detach(); if (!plot->showRGCT) rgctCurve->detach(); if (!plot->showGear) gearCurve->detach(); if (!plot->showSmO2) smo2Curve->detach(); if (!plot->showtHb) thbCurve->detach(); if (!plot->showO2Hb) o2hbCurve->detach(); if (!plot->showHHb) hhbCurve->detach(); if (!plot->showATISS) atissCurve->detach(); if (!plot->showANTISS) antissCurve->detach(); if (!plot->showXP) xpCurve->detach(); if (!plot->showAP) apCurve->detach(); if (!plot->showW) wCurve->detach(); if (!plot->showW) mCurve->detach(); if (!plot->showHr) hrCurve->detach(); if (!plot->showTcore) tcoreCurve->detach(); if (!plot->showSpeed) speedCurve->detach(); if (!plot->showAccel) accelCurve->detach(); if (!plot->showPowerD) wattsDCurve->detach(); if (!plot->showCadD) cadDCurve->detach(); if (!plot->showTorqueD) nmDCurve->detach(); if (!plot->showHrD) hrDCurve->detach(); if (!plot->showCad) cadCurve->detach(); if (!plot->showAlt) altCurve->detach(); if (!plot->showSlope) slopeCurve->detach(); if (plot->showAltSlopeState == 0) altSlopeCurve->detach(); if (!plot->showTemp) tempCurve->detach(); if (!plot->showWind) windCurve->detach(); if (!plot->showTorque) torqueCurve->detach(); if (!plot->showTE) { lteCurve->detach(); rteCurve->detach(); } if (!plot->showPS) { lpsCurve->detach(); rpsCurve->detach(); } if (!plot->showPCO) { lpcoCurve->detach(); rpcoCurve->detach(); } if (!plot->showDC) { lppCurve->detach(); rppCurve->detach(); } if (!plot->showPPP) { lpppCurve->detach(); rpppCurve->detach(); } if (!plot->showBalance) { balanceLCurve->detach(); balanceRCurve->detach(); } } AllPlot::AllPlot(QWidget *parent, AllPlotWindow *window, Context *context, RideFile::SeriesType scope, RideFile::SeriesType secScope, bool wanttext): QwtPlot(parent), rideItem(NULL), shade_zones(true), showPowerState(3), showAltSlopeState(0), showATISS(false), showANTISS(false), showNP(false), showXP(false), showAP(false), showHr(true), showTcore(true), showSpeed(true), showAccel(false), showPowerD(false), showCadD(false), showTorqueD(false), showHrD(false), showCad(true), showAlt(true), showSlope(false), showTemp(true), showWind(true), showTorque(true), showBalance(true), showRV(true), showRGCT(true), showRCad(true), showSmO2(true), showtHb(true), showO2Hb(true), showHHb(true), showGear(true), bydist(false), scope(scope), secondaryScope(secScope), context(context), parent(parent), window(window), wanttext(wanttext), isolation(false) { if (appsettings->value(this, GC_SHADEZONES, true).toBool()==false) shade_zones = false; smooth = 1; wantxaxis = wantaxis = true; setAutoDelete(false); // no - we are managing it via the AllPlotObjects now referencePlot = NULL; tooltip = NULL; _canvasPicker = NULL; // curve color object curveColors = new CurveColors(this, true); // create a background object for shading bg = new AllPlotBackground(this); bg->attach(this); //insertLegend(new QwtLegend(), QwtPlot::BottomLegend); setCanvasBackground(GColor(CRIDEPLOTBACKGROUND)); static_cast<QwtPlotCanvas*>(canvas())->setFrameStyle(QFrame::NoFrame); // set the axes that we use.. yLeft 3 is ALWAYS the highlighter axes and never visible // yLeft 4 is balance stuff setAxesCount(QwtAxis::yLeft, 4); setAxesCount(QwtAxis::yRight, 4); setAxesCount(QwtAxis::xBottom, 1); setXTitle(); standard = new AllPlotObject(this); standard->intervalHighlighterCurve->setSamples(new IntervalPlotData(this, context, window)); setAxisMaxMinor(xBottom, 0); enableAxis(xBottom, true); setAxisVisible(xBottom, true); // highlighter ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 2); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); setAxisScaleDraw(QwtAxisId(QwtAxis::yLeft, 2), sd); QPalette pal = palette(); pal.setBrush(QPalette::Background, QBrush(GColor(CRIDEPLOTBACKGROUND))); pal.setColor(QPalette::WindowText, QColor(Qt::gray)); pal.setColor(QPalette::Text, QColor(Qt::gray)); axisWidget(QwtAxisId(QwtAxis::yLeft, 2))->setPalette(pal); setAxisScale(QwtAxisId(QwtAxis::yLeft, 2), 0, 100); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 2), false); // hide interval axis setAxisMaxMinor(yLeft, 0); setAxisMaxMinor(QwtAxisId(QwtAxis::yLeft, 1), 0); setAxisMaxMinor(QwtAxisId(QwtAxis::yLeft, 3), 0); setAxisMaxMinor(yRight, 0); setAxisMaxMinor(QwtAxisId(QwtAxis::yRight, 1), 0); setAxisMaxMinor(QwtAxisId(QwtAxis::yRight, 2), 0); setAxisMaxMinor(QwtAxisId(QwtAxis::yRight, 3), 0); axisWidget(QwtPlot::yLeft)->installEventFilter(this); axisWidget(QwtPlot::yRight)->installEventFilter(this); axisWidget(QwtAxisId(QwtAxis::yLeft, 1))->installEventFilter(this); axisWidget(QwtAxisId(QwtAxis::yLeft, 3))->installEventFilter(this); axisWidget(QwtAxisId(QwtAxis::yRight, 1))->installEventFilter(this); axisWidget(QwtAxisId(QwtAxis::yRight, 2))->installEventFilter(this); axisWidget(QwtAxisId(QwtAxis::yRight, 3))->installEventFilter(this); configChanged(CONFIG_APPEARANCE); // set colors } AllPlot::~AllPlot() { // wipe compare curves if there are any foreach(QwtPlotCurve *compare, compares) { compare->detach(); delete compare; } compares.clear(); // wipe the standard stuff delete standard; if (tooltip) delete tooltip; if (_canvasPicker) delete _canvasPicker; } void AllPlot::configChanged(qint32) { double width = appsettings->value(this, GC_LINEWIDTH, 0.5).toDouble(); labelFont.fromString(appsettings->value(this, GC_FONT_CHARTLABELS, QFont().toString()).toString()); labelFont.setPointSize(appsettings->value(NULL, GC_FONT_CHARTLABELS_SIZE, 8).toInt()); if (appsettings->value(this, GC_ANTIALIAS, true).toBool() == true) { standard->wattsCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->atissCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->antissCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->npCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rvCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rcadCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rgctCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->gearCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->smo2Curve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->thbCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->o2hbCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->hhbCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->xpCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->apCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->wCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->mCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->hrCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->tcoreCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->speedCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->accelCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->wattsDCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->cadDCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->nmDCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->hrDCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->cadCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->altCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->slopeCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->altSlopeCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->tempCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->windCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->torqueCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->lteCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rteCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->lpsCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rpsCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->lpcoCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rpcoCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->lppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->lpppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->rpppCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->balanceLCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->balanceRCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->intervalHighlighterCurve->setRenderHint(QwtPlotItem::RenderAntialiased); standard->intervalHoverCurve->setRenderHint(QwtPlotItem::RenderAntialiased); } setAltSlopePlotStyle(standard->altSlopeCurve); setCanvasBackground(GColor(CRIDEPLOTBACKGROUND)); QPen wattsPen = QPen(GColor(CPOWER)); wattsPen.setWidth(width); standard->wattsCurve->setPen(wattsPen); standard->wattsDCurve->setPen(wattsPen); QPen npPen = QPen(GColor(CNPOWER)); npPen.setWidth(width); standard->npCurve->setPen(npPen); QPen rvPen = QPen(GColor(CRV)); rvPen.setWidth(width); standard->rvCurve->setPen(rvPen); QPen rcadPen = QPen(GColor(CRCAD)); rcadPen.setWidth(width); standard->rcadCurve->setPen(rcadPen); QPen rgctPen = QPen(GColor(CRGCT)); rgctPen.setWidth(width); standard->rgctCurve->setPen(rgctPen); QPen gearPen = QPen(GColor(CGEAR)); gearPen.setWidth(width); standard->gearCurve->setPen(gearPen); QPen smo2Pen = QPen(GColor(CSMO2)); smo2Pen.setWidth(width); standard->smo2Curve->setPen(smo2Pen); QPen thbPen = QPen(GColor(CTHB)); thbPen.setWidth(width); standard->thbCurve->setPen(thbPen); QPen o2hbPen = QPen(GColor(CO2HB)); o2hbPen.setWidth(width); standard->o2hbCurve->setPen(o2hbPen); QPen hhbPen = QPen(GColor(CHHB)); hhbPen.setWidth(width); standard->hhbCurve->setPen(hhbPen); QPen antissPen = QPen(GColor(CANTISS)); antissPen.setWidth(width); standard->antissCurve->setPen(antissPen); QPen atissPen = QPen(GColor(CATISS)); atissPen.setWidth(width); standard->atissCurve->setPen(atissPen); QPen xpPen = QPen(GColor(CXPOWER)); xpPen.setWidth(width); standard->xpCurve->setPen(xpPen); QPen apPen = QPen(GColor(CAPOWER)); apPen.setWidth(width); standard->apCurve->setPen(apPen); QPen hrPen = QPen(GColor(CHEARTRATE)); hrPen.setWidth(width); standard->hrCurve->setPen(hrPen); QPen tcorePen = QPen(GColor(CCORETEMP)); tcorePen.setWidth(width); standard->tcoreCurve->setPen(tcorePen); standard->hrDCurve->setPen(hrPen); QPen speedPen = QPen(GColor(CSPEED)); speedPen.setWidth(width); standard->speedCurve->setPen(speedPen); QPen accelPen = QPen(GColor(CACCELERATION)); accelPen.setWidth(width); standard->accelCurve->setPen(accelPen); QPen cadPen = QPen(GColor(CCADENCE)); cadPen.setWidth(width); standard->cadCurve->setPen(cadPen); standard->cadDCurve->setPen(cadPen); QPen slopePen(GColor(CSLOPE)); slopePen.setWidth(width); standard->slopeCurve->setPen(slopePen); QPen altPen(GColor(CALTITUDE)); altPen.setWidth(width); standard->altCurve->setPen(altPen); QColor brush_color = GColor(CALTITUDEBRUSH); brush_color.setAlpha(200); standard->altCurve->setBrush(brush_color); // fill below the line QPen altSlopePen(GCColor::invertColor(GColor(CPLOTBACKGROUND))); altSlopePen.setWidth(width); standard->altSlopeCurve->setPen(altSlopePen); QPen tempPen = QPen(GColor(CTEMP)); tempPen.setWidth(width); standard->tempCurve->setPen(tempPen); //QPen windPen = QPen(GColor(CWINDSPEED)); //windPen.setWidth(width); standard->windCurve->setPen(QPen(Qt::NoPen)); QColor wbrush_color = GColor(CWINDSPEED); wbrush_color.setAlpha(200); standard->windCurve->setBrush(wbrush_color); // fill below the line QPen torquePen = QPen(GColor(CTORQUE)); torquePen.setWidth(width); standard->torqueCurve->setPen(torquePen); standard->nmDCurve->setPen(torquePen); QPen balanceLPen = QPen(GColor(CBALANCERIGHT)); balanceLPen.setWidth(width); standard->balanceLCurve->setPen(balanceLPen); QColor brbrush_color = GColor(CBALANCERIGHT); brbrush_color.setAlpha(200); standard->balanceLCurve->setBrush(brbrush_color); // fill below the line QPen balanceRPen = QPen(GColor(CBALANCELEFT)); balanceRPen.setWidth(width); standard->balanceRCurve->setPen(balanceRPen); QColor blbrush_color = GColor(CBALANCELEFT); blbrush_color.setAlpha(200); standard->balanceRCurve->setBrush(blbrush_color); // fill below the line QPen ltePen = QPen(GColor(CLTE)); ltePen.setWidth(width); standard->lteCurve->setPen(ltePen); QPen rtePen = QPen(GColor(CRTE)); rtePen.setWidth(width); standard->rteCurve->setPen(rtePen); QPen lpsPen = QPen(GColor(CLPS)); lpsPen.setWidth(width); standard->lpsCurve->setPen(lpsPen); QPen rpsPen = QPen(GColor(CRPS)); rpsPen.setWidth(width); standard->rpsCurve->setPen(rpsPen); QPen lpcoPen = QPen(GColor(CLPS)); lpcoPen.setWidth(width); standard->lpcoCurve->setPen(lpcoPen); QPen rpcoPen = QPen(GColor(CRPS)); rpcoPen.setWidth(width); standard->rpcoCurve->setPen(rpcoPen); QPen ldcPen = QPen(GColor(CLPS)); ldcPen.setWidth(width); standard->lppCurve->setPen(ldcPen); QPen rdcPen = QPen(GColor(CRPS)); rdcPen.setWidth(width); standard->rppCurve->setPen(rdcPen); QPen lpppPen = QPen(GColor(CLPS)); lpppPen.setWidth(width); standard->lpppCurve->setPen(lpppPen); QPen rpppPen = QPen(GColor(CRPS)); rpppPen.setWidth(width); standard->rpppCurve->setPen(rpppPen); QPen wPen = QPen(GColor(CWBAL)); wPen.setWidth(width); // don't thicken standard->wCurve->setPen(wPen); QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::Rect); sym->setPen(QPen(QColor(255,127,0))); // orange like a match, will make configurable later sym->setSize(4); standard->mCurve->setSymbol(sym); QPen ihlPen = QPen(GColor(CINTERVALHIGHLIGHTER)); ihlPen.setWidth(width); standard->intervalHighlighterCurve->setPen(QPen(Qt::NoPen)); standard->intervalHoverCurve->setPen(QPen(Qt::NoPen)); QColor ihlbrush = QColor(GColor(CINTERVALHIGHLIGHTER)); ihlbrush.setAlpha(128); standard->intervalHighlighterCurve->setBrush(ihlbrush); // fill below the line QColor hbrush = QColor(Qt::lightGray); hbrush.setAlpha(64); standard->intervalHoverCurve->setBrush(hbrush); // fill below the line //this->legend()->remove(intervalHighlighterCurve); // don't show in legend QPen gridPen(GColor(CPLOTGRID)); //gridPen.setStyle(Qt::DotLine); // solid line is nicer standard->grid->setPen(gridPen); // curve brushes if (fill) { QColor p; p = standard->wattsCurve->pen().color(); p.setAlpha(64); standard->wattsCurve->setBrush(QBrush(p)); p = standard->atissCurve->pen().color(); p.setAlpha(64); standard->atissCurve->setBrush(QBrush(p)); p = standard->antissCurve->pen().color(); p.setAlpha(64); standard->antissCurve->setBrush(QBrush(p)); p = standard->npCurve->pen().color(); p.setAlpha(64); standard->npCurve->setBrush(QBrush(p)); p = standard->rvCurve->pen().color(); p.setAlpha(64); standard->rvCurve->setBrush(QBrush(p)); p = standard->rcadCurve->pen().color(); p.setAlpha(64); standard->rcadCurve->setBrush(QBrush(p)); p = standard->rgctCurve->pen().color(); p.setAlpha(64); standard->rgctCurve->setBrush(QBrush(p)); p = standard->gearCurve->pen().color(); p.setAlpha(64); standard->gearCurve->setBrush(QBrush(p)); p = standard->smo2Curve->pen().color(); p.setAlpha(64); standard->smo2Curve->setBrush(QBrush(p)); p = standard->thbCurve->pen().color(); p.setAlpha(64); standard->thbCurve->setBrush(QBrush(p)); p = standard->o2hbCurve->pen().color(); p.setAlpha(64); standard->o2hbCurve->setBrush(QBrush(p)); p = standard->hhbCurve->pen().color(); p.setAlpha(64); standard->hhbCurve->setBrush(QBrush(p)); p = standard->xpCurve->pen().color(); p.setAlpha(64); standard->xpCurve->setBrush(QBrush(p)); p = standard->apCurve->pen().color(); p.setAlpha(64); standard->apCurve->setBrush(QBrush(p)); p = standard->wCurve->pen().color(); p.setAlpha(64); standard->wCurve->setBrush(QBrush(p)); p = standard->tcoreCurve->pen().color(); p.setAlpha(64); standard->tcoreCurve->setBrush(QBrush(p)); p = standard->hrCurve->pen().color(); p.setAlpha(64); standard->hrCurve->setBrush(QBrush(p)); p = standard->accelCurve->pen().color(); p.setAlpha(64); standard->accelCurve->setBrush(QBrush(p)); p = standard->wattsDCurve->pen().color(); p.setAlpha(64); standard->wattsDCurve->setBrush(QBrush(p)); p = standard->cadDCurve->pen().color(); p.setAlpha(64); standard->cadDCurve->setBrush(QBrush(p)); p = standard->nmDCurve->pen().color(); p.setAlpha(64); standard->nmDCurve->setBrush(QBrush(p)); p = standard->hrDCurve->pen().color(); p.setAlpha(64); standard->hrDCurve->setBrush(QBrush(p)); p = standard->speedCurve->pen().color(); p.setAlpha(64); standard->speedCurve->setBrush(QBrush(p)); p = standard->cadCurve->pen().color(); p.setAlpha(64); standard->cadCurve->setBrush(QBrush(p)); p = standard->torqueCurve->pen().color(); p.setAlpha(64); standard->torqueCurve->setBrush(QBrush(p)); p = standard->tempCurve->pen().color(); p.setAlpha(64); standard->tempCurve->setBrush(QBrush(p)); p = standard->lteCurve->pen().color(); p.setAlpha(64); standard->lteCurve->setBrush(QBrush(p)); p = standard->rteCurve->pen().color(); p.setAlpha(64); standard->rteCurve->setBrush(QBrush(p)); p = standard->lpsCurve->pen().color(); p.setAlpha(64); standard->lpsCurve->setBrush(QBrush(p)); p = standard->rpsCurve->pen().color(); p.setAlpha(64); standard->rpsCurve->setBrush(QBrush(p)); p = standard->lpcoCurve->pen().color(); p.setAlpha(64); standard->lpcoCurve->setBrush(QBrush(p)); p = standard->rpcoCurve->pen().color(); p.setAlpha(64); standard->rpcoCurve->setBrush(QBrush(p)); p = standard->lppCurve->pen().color(); p.setAlpha(64); standard->lppCurve->setBrush(QBrush(p)); p = standard->rppCurve->pen().color(); p.setAlpha(64); standard->rppCurve->setBrush(QBrush(p)); p = standard->lpppCurve->pen().color(); p.setAlpha(64); standard->lpppCurve->setBrush(QBrush(p)); p = standard->rpppCurve->pen().color(); p.setAlpha(64); standard->rpppCurve->setBrush(QBrush(p)); p = standard->slopeCurve->pen().color(); p.setAlpha(64); standard->slopeCurve->setBrush(QBrush(p)); /*p = standard->altSlopeCurve->pen().color(); p.setAlpha(64); standard->altSlopeCurve->setBrush(QBrush(p)); p = standard->balanceLCurve->pen().color(); p.setAlpha(64); standard->balanceLCurve->setBrush(QBrush(p)); p = standard->balanceRCurve->pen().color(); p.setAlpha(64); standard->balanceRCurve->setBrush(QBrush(p));*/ } else { standard->wattsCurve->setBrush(Qt::NoBrush); standard->atissCurve->setBrush(Qt::NoBrush); standard->antissCurve->setBrush(Qt::NoBrush); standard->rvCurve->setBrush(Qt::NoBrush); standard->rcadCurve->setBrush(Qt::NoBrush); standard->rgctCurve->setBrush(Qt::NoBrush); standard->gearCurve->setBrush(Qt::NoBrush); standard->smo2Curve->setBrush(Qt::NoBrush); standard->thbCurve->setBrush(Qt::NoBrush); standard->o2hbCurve->setBrush(Qt::NoBrush); standard->hhbCurve->setBrush(Qt::NoBrush); standard->npCurve->setBrush(Qt::NoBrush); standard->xpCurve->setBrush(Qt::NoBrush); standard->apCurve->setBrush(Qt::NoBrush); standard->wCurve->setBrush(Qt::NoBrush); standard->hrCurve->setBrush(Qt::NoBrush); standard->tcoreCurve->setBrush(Qt::NoBrush); standard->speedCurve->setBrush(Qt::NoBrush); standard->accelCurve->setBrush(Qt::NoBrush); standard->wattsDCurve->setBrush(Qt::NoBrush); standard->cadDCurve->setBrush(Qt::NoBrush); standard->nmDCurve->setBrush(Qt::NoBrush); standard->hrDCurve->setBrush(Qt::NoBrush); standard->cadCurve->setBrush(Qt::NoBrush); standard->torqueCurve->setBrush(Qt::NoBrush); standard->tempCurve->setBrush(Qt::NoBrush); standard->lteCurve->setBrush(Qt::NoBrush); standard->rteCurve->setBrush(Qt::NoBrush); standard->lpsCurve->setBrush(Qt::NoBrush); standard->rpsCurve->setBrush(Qt::NoBrush); standard->lpcoCurve->setBrush(Qt::NoBrush); standard->rpcoCurve->setBrush(Qt::NoBrush); standard->lppCurve->setBrush(Qt::NoBrush); standard->rppCurve->setBrush(Qt::NoBrush); standard->lpppCurve->setBrush(Qt::NoBrush); standard->rpppCurve->setBrush(Qt::NoBrush); standard->slopeCurve->setBrush(Qt::NoBrush); //standard->altSlopeCurve->setBrush((Qt::NoBrush)); //standard->balanceLCurve->setBrush(Qt::NoBrush); //standard->balanceRCurve->setBrush(Qt::NoBrush); } QPalette pal = palette(); pal.setBrush(QPalette::Background, QBrush(GColor(CRIDEPLOTBACKGROUND))); setPalette(pal); // tick draw TimeScaleDraw *tsd = new TimeScaleDraw(&this->bydist) ; tsd->setTickLength(QwtScaleDiv::MajorTick, 3); setAxisScaleDraw(QwtPlot::xBottom, tsd); pal.setColor(QPalette::WindowText, GColor(CPLOTMARKER)); pal.setColor(QPalette::Text, GColor(CPLOTMARKER)); axisWidget(QwtPlot::xBottom)->setPalette(pal); enableAxis(xBottom, true); setAxisVisible(xBottom, true); ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); setAxisScaleDraw(QwtPlot::yLeft, sd); pal.setColor(QPalette::WindowText, GColor(CPOWER)); pal.setColor(QPalette::Text, GColor(CPOWER)); axisWidget(QwtPlot::yLeft)->setPalette(pal); // some axis show multiple things so color them // to match up if only one curve is selected; // e.g. left, 1 typically has HR, Cadence // on the same curve but can also have SmO2 and Temp // since it gets set a few places we do it with // a special method setLeftOnePalette(); setRightPalette(); sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); setAxisScaleDraw(QwtAxisId(QwtAxis::yLeft, 3), sd); pal.setColor(QPalette::WindowText, GColor(CPLOTMARKER)); pal.setColor(QPalette::Text, GColor(CPLOTMARKER)); axisWidget(QwtAxisId(QwtAxis::yLeft, 3))->setPalette(pal); sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); setAxisScaleDraw(QwtAxisId(QwtAxis::yRight, 1), sd); pal.setColor(QPalette::WindowText, GColor(CALTITUDE)); pal.setColor(QPalette::Text, GColor(CALTITUDE)); axisWidget(QwtAxisId(QwtAxis::yRight, 1))->setPalette(pal); sd = new ScaleScaleDraw; sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->setFactor(0.001f); // in kJ setAxisScaleDraw(QwtAxisId(QwtAxis::yRight, 2), sd); pal.setColor(QPalette::WindowText, GColor(CWBAL)); pal.setColor(QPalette::Text, GColor(CWBAL)); axisWidget(QwtAxisId(QwtAxis::yRight, 2))->setPalette(pal); sd = new ScaleScaleDraw; sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); sd->setTickLength(QwtScaleDiv::MajorTick, 3); setAxisScaleDraw(QwtAxisId(QwtAxis::yRight, 3), sd); pal.setColor(QPalette::WindowText, GColor(CATISS)); pal.setColor(QPalette::Text, GColor(CATISS)); axisWidget(QwtAxisId(QwtAxis::yRight, 3))->setPalette(pal); curveColors->saveState(); } void AllPlot::setLeftOnePalette() { // always use the last, so BPM overrides // Cadence then Temp then SmO2 ... QColor single = QColor(Qt::red); if (standard->smo2Curve->isVisible()) { single = GColor(CSMO2); } if (standard->tempCurve->isVisible() && !context->athlete->useMetricUnits) { single = GColor(CTEMP); } if (standard->cadCurve->isVisible()) { single = GColor(CCADENCE); } if (standard->hrCurve->isVisible()) { single = GColor(CHEARTRATE); } if (standard->tcoreCurve->isVisible()) { single = GColor(CCORETEMP); } // lets go ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); setAxisScaleDraw(QwtAxisId(QwtAxis::yLeft, 1), sd); QPalette pal = palette(); pal.setBrush(QPalette::Background, QBrush(GColor(CRIDEPLOTBACKGROUND))); pal.setColor(QPalette::WindowText, single); pal.setColor(QPalette::Text, single); // now work it out .... axisWidget(QwtAxisId(QwtAxis::yLeft, 1))->setPalette(pal); } void AllPlot::setRightPalette() { // always use the last, so BPM overrides // Cadence then Temp then SmO2 ... QColor single = QColor(Qt::green); if (standard->speedCurve->isVisible()) { single = GColor(CSPEED); } if (standard->tempCurve->isVisible() && context->athlete->useMetricUnits) { single = GColor(CTEMP); } if (standard->o2hbCurve->isVisible()) { single = GColor(CO2HB); } if (standard->hhbCurve->isVisible()) { single = GColor(CHHB); } if (standard->thbCurve->isVisible()) { single = GColor(CTHB); } if (standard->torqueCurve->isVisible()) { single = GColor(CTORQUE); } // lets go ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); sd->setDecimals(2); setAxisScaleDraw(QwtAxisId(QwtAxis::yRight, 0), sd); QPalette pal = palette(); pal.setBrush(QPalette::Background, QBrush(GColor(CRIDEPLOTBACKGROUND))); pal.setColor(QPalette::WindowText, single); pal.setColor(QPalette::Text, single); // now work it out .... axisWidget(QwtAxisId(QwtAxis::yRight, 0))->setPalette(pal); } void AllPlot::setHighlightIntervals(bool state) { if (state) { standard->intervalHighlighterCurve->attach(this); standard->intervalHoverCurve->attach(this); } else { standard->intervalHighlighterCurve->detach(); standard->intervalHoverCurve->detach(); } } struct DataPoint { double time, hr, watts, atiss, antiss, np, rv, rcad, rgct, smo2, thb, o2hb, hhb, ap, xp, speed, cad, alt, temp, wind, torque, lrbalance, lte, rte, lps, rps, lpco, rpco, lppb, rppb, lppe, rppe, lpppb, rpppb, lpppe, rpppe, kphd, wattsd, cadd, nmd, hrd, slope, tcore; DataPoint(double t, double h, double w, double at, double an, double n, double rv, double rcad, double rgct, double smo2, double thb, double o2hb, double hhb, double l, double x, double s, double c, double a, double te, double wi, double tq, double lrb, double lte, double rte, double lps, double rps, double lpco, double rpco, double lppb, double rppb, double lppe, double rppe, double lpppb, double rpppb, double lpppe, double rpppe, double kphd, double wattsd, double cadd, double nmd, double hrd, double sl, double tcore) : time(t), hr(h), watts(w), atiss(at), antiss(an), np(n), rv(rv), rcad(rcad), rgct(rgct), smo2(smo2), thb(thb), o2hb(o2hb), hhb(hhb), ap(l), xp(x), speed(s), cad(c), alt(a), temp(te), wind(wi), torque(tq), lrbalance(lrb), lte(lte), rte(rte), lps(lps), rps(rps), lpco(lpco), rpco(rpco), lppb(lppb), rppb(rppb), lppe(lppe), rppe(rppe), lpppb(lpppb), rpppb(rpppb), lpppe(lpppe), rpppe(rpppe), kphd(kphd), wattsd(wattsd), cadd(cadd), nmd(nmd), hrd(hrd), slope(sl), tcore(tcore) {} }; bool AllPlot::shadeZones() const { return shade_zones; } void AllPlot::setAxisTitle(QwtAxisId axis, QString label) { // setup the default fonts QFont stGiles; // hoho - Chart Font St. Giles ... ok you have to be British to get this joke stGiles.fromString(appsettings->value(this, GC_FONT_CHARTLABELS, QFont().toString()).toString()); stGiles.setPointSize(appsettings->value(NULL, GC_FONT_CHARTLABELS_SIZE, 8).toInt()); QwtText title(label); title.setFont(stGiles); QwtPlot::setAxisFont(axis, stGiles); QwtPlot::setAxisTitle(axis, title); } void AllPlot::refreshZoneLabels() { foreach(AllPlotZoneLabel *label, zoneLabels) { label->detach(); delete label; } zoneLabels.clear(); if (rideItem && context->athlete->zones()) { int zone_range = context->athlete->zones()->whichRange(rideItem->dateTime.date()); // generate labels for existing zones if (zone_range >= 0) { int num_zones = context->athlete->zones()->numZones(zone_range); for (int z = 0; z < num_zones; z ++) { AllPlotZoneLabel *label = new AllPlotZoneLabel(this, z); label->attach(this); zoneLabels.append(label); } } } } void AllPlot::setMatchLabels(AllPlotObject *objects) { // clear anyway foreach(QwtPlotMarker *p, objects->matchLabels) { p->detach(); delete p; } objects->matchLabels.clear(); // add new ones, but only if showW if (showW && objects->mCurve) { bool below = false; // zip through the matches and add a label for (size_t i=0; i<objects->mCurve->data()->size(); i++) { // mCurve->data()->sample(i); // Qwt uses its own text objects QwtText text(QString("%1").arg(objects->mCurve->data()->sample(i).y()/1000.00f, 4, 'f', 1)); text.setFont(labelFont); text.setColor(QColor(255,127,0)); // supposed to be configurable ! // make that mark -- always above with topN QwtPlotMarker *label = new QwtPlotMarker(); label->setLabel(text); label->setValue(objects->mCurve->data()->sample(i).x(), objects->mCurve->data()->sample(i).y()); label->setYAxis(objects->mCurve->yAxis()); label->setSpacing(6); // not px but by yaxis value !? mad. label->setLabelAlignment(below ? (Qt::AlignBottom | Qt::AlignCenter) : (Qt::AlignTop | Qt::AlignCenter)); // and attach label->attach(this); objects->matchLabels << label; // toggle top / bottom below = !below; } } } void AllPlot::recalc(AllPlotObject *objects) { if (referencePlot !=NULL){ return; } if (objects->timeArray.empty()) return; // skip null rides if (!rideItem || !rideItem->ride()) return; int rideTimeSecs = (int) ceil(objects->timeArray[objects->timeArray.count()-1]); if (rideTimeSecs > 7*24*60*60) { // clear all the curves QwtArray<double> data; QVector<QwtIntervalSample> intData; objects->wCurve->setSamples(data,data); objects->mCurve->setSamples(data,data); setMatchLabels(objects); if (!objects->atissArray.empty()) objects->atissCurve->setSamples(data, data); if (!objects->antissArray.empty()) objects->antissCurve->setSamples(data, data); if (!objects->npArray.empty()) objects->npCurve->setSamples(data, data); if (!objects->rvArray.empty()) objects->rvCurve->setSamples(data, data); if (!objects->rcadArray.empty()) objects->rcadCurve->setSamples(data, data); if (!objects->rgctArray.empty()) objects->rgctCurve->setSamples(data, data); if (!objects->gearArray.empty()) objects->gearCurve->setSamples(data, data); if (!objects->smo2Array.empty()) objects->smo2Curve->setSamples(data, data); if (!objects->thbArray.empty()) objects->thbCurve->setSamples(data, data); if (!objects->o2hbArray.empty()) objects->o2hbCurve->setSamples(data, data); if (!objects->hhbArray.empty()) objects->hhbCurve->setSamples(data, data); if (!objects->xpArray.empty()) objects->xpCurve->setSamples(data, data); if (!objects->apArray.empty()) objects->apCurve->setSamples(data, data); if (!objects->wattsArray.empty()) objects->wattsCurve->setSamples(data, data); if (!objects->hrArray.empty()) objects->hrCurve->setSamples(data, data); if (!objects->tcoreArray.empty()) objects->tcoreCurve->setSamples(data, data); if (!objects->speedArray.empty()) objects->speedCurve->setSamples(data, data); // deltas if (!objects->accelArray.empty()) objects->accelCurve->setSamples(data, data); if (!objects->wattsDArray.empty()) objects->wattsDCurve->setSamples(data, data); if (!objects->cadDArray.empty()) objects->cadDCurve->setSamples(data, data); if (!objects->nmDArray.empty()) objects->nmDCurve->setSamples(data, data); if (!objects->hrDArray.empty()) objects->hrDCurve->setSamples(data, data); if (!objects->cadArray.empty()) objects->cadCurve->setSamples(data, data); if (!objects->altArray.empty()) { objects->altCurve->setSamples(data, data); objects->altSlopeCurve->setSamples(data, data); } if (!objects->slopeArray.empty()) objects->slopeCurve->setSamples(data, data); if (!objects->tempArray.empty()) objects->tempCurve->setSamples(data, data); if (!objects->windArray.empty()) objects->windCurve->setSamples(new QwtIntervalSeriesData(intData)); if (!objects->torqueArray.empty()) objects->torqueCurve->setSamples(data, data); // left/right data if (!objects->balanceArray.empty()) { objects->balanceLCurve->setSamples(data, data); objects->balanceRCurve->setSamples(data, data); } if (!objects->lteArray.empty()) objects->lteCurve->setSamples(data, data); if (!objects->rteArray.empty()) objects->rteCurve->setSamples(data, data); if (!objects->lpsArray.empty()) objects->lpsCurve->setSamples(data, data); if (!objects->rpsArray.empty()) objects->rpsCurve->setSamples(data, data); if (!objects->lpcoArray.empty()) objects->lpcoCurve->setSamples(data, data); if (!objects->rpcoArray.empty()) objects->rpcoCurve->setSamples(data, data); if (!objects->lppbArray.empty()) objects->lppCurve->setSamples(new QwtIntervalSeriesData(intData)); if (!objects->rppbArray.empty()) objects->rppCurve->setSamples(new QwtIntervalSeriesData(intData));; if (!objects->lpppbArray.empty()) objects->lpppCurve->setSamples(new QwtIntervalSeriesData(intData)); if (!objects->rpppbArray.empty()) objects->rpppCurve->setSamples(new QwtIntervalSeriesData(intData)); return; } // if recintsecs is longer than the smoothing, or equal to the smoothing there is no point in even trying int applysmooth = smooth <= rideItem->ride()->recIntSecs() ? 0 : smooth; // compare mode breaks if (context->isCompareIntervals && applysmooth == 0) applysmooth = 1; // we should only smooth the curves if objects->smoothed rate is greater than sample rate if (applysmooth > 0) { double totalWatts = 0.0; double totalNP = 0.0; double totalRCad = 0.0; double totalRV = 0.0; double totalRGCT = 0.0; double totalSmO2 = 0.0; double totaltHb = 0.0; double totalO2Hb = 0.0; double totalHHb = 0.0; double totalATISS = 0.0; double totalANTISS = 0.0; double totalXP = 0.0; double totalAP = 0.0; double totalHr = 0.0; double totalTcore = 0.0; double totalSpeed = 0.0; double totalAccel = 0.0; double totalWattsD = 0.0; double totalCadD = 0.0; double totalNmD = 0.0; double totalHrD = 0.0; double totalCad = 0.0; double totalDist = 0.0; double totalAlt = 0.0; double totalSlope = 0.0; double totalTemp = 0.0; double totalWind = 0.0; double totalTorque = 0.0; double totalBalance = 0.0; double totalLTE = 0.0; double totalRTE = 0.0; double totalLPS = 0.0; double totalRPS = 0.0; double totalLPCO = 0.0; double totalRPCO = 0.0; double totalLPPB = 0.0; double totalRPPB = 0.0; double totalLPPE = 0.0; double totalRPPE = 0.0; double totalLPPPB = 0.0; double totalRPPPB = 0.0; double totalLPPPE = 0.0; double totalRPPPE = 0.0; QList<DataPoint> list; objects->smoothWatts.resize(rideTimeSecs + 1); objects->smoothNP.resize(rideTimeSecs + 1); objects->smoothGear.resize(rideTimeSecs + 1); objects->smoothRV.resize(rideTimeSecs + 1); objects->smoothRCad.resize(rideTimeSecs + 1); objects->smoothRGCT.resize(rideTimeSecs + 1); objects->smoothSmO2.resize(rideTimeSecs + 1); objects->smoothtHb.resize(rideTimeSecs + 1); objects->smoothO2Hb.resize(rideTimeSecs + 1); objects->smoothHHb.resize(rideTimeSecs + 1); objects->smoothAT.resize(rideTimeSecs + 1); objects->smoothANT.resize(rideTimeSecs + 1); objects->smoothXP.resize(rideTimeSecs + 1); objects->smoothAP.resize(rideTimeSecs + 1); objects->smoothHr.resize(rideTimeSecs + 1); objects->smoothTcore.resize(rideTimeSecs + 1); objects->smoothSpeed.resize(rideTimeSecs + 1); objects->smoothAccel.resize(rideTimeSecs + 1); objects->smoothWattsD.resize(rideTimeSecs + 1); objects->smoothCadD.resize(rideTimeSecs + 1); objects->smoothNmD.resize(rideTimeSecs + 1); objects->smoothHrD.resize(rideTimeSecs + 1); objects->smoothCad.resize(rideTimeSecs + 1); objects->smoothTime.resize(rideTimeSecs + 1); objects->smoothDistance.resize(rideTimeSecs + 1); objects->smoothAltitude.resize(rideTimeSecs + 1); objects->smoothSlope.resize(rideTimeSecs + 1); objects->smoothTemp.resize(rideTimeSecs + 1); objects->smoothWind.resize(rideTimeSecs + 1); objects->smoothRelSpeed.resize(rideTimeSecs + 1); objects->smoothTorque.resize(rideTimeSecs + 1); objects->smoothBalanceL.resize(rideTimeSecs + 1); objects->smoothBalanceR.resize(rideTimeSecs + 1); objects->smoothLTE.resize(rideTimeSecs + 1); objects->smoothRTE.resize(rideTimeSecs + 1); objects->smoothLPS.resize(rideTimeSecs + 1); objects->smoothRPS.resize(rideTimeSecs + 1); objects->smoothLPCO.resize(rideTimeSecs + 1); objects->smoothRPCO.resize(rideTimeSecs + 1); objects->smoothLPP.resize(rideTimeSecs + 1); objects->smoothRPP.resize(rideTimeSecs + 1); objects->smoothLPPP.resize(rideTimeSecs + 1); objects->smoothRPPP.resize(rideTimeSecs + 1); // do the smoothing by calculating the average of the "applysmooth" values left // of the current data point - for points in time smaller than "applysmooth" // only the available datapoints left are used to build the average int i = 0; for (int secs = 0; secs <= rideTimeSecs; ++secs) { while ((i < objects->timeArray.count()) && (objects->timeArray[i] <= secs)) { DataPoint dp(objects->timeArray[i], (!objects->hrArray.empty() ? objects->hrArray[i] : 0), (!objects->wattsArray.empty() ? objects->wattsArray[i] : 0), (!objects->atissArray.empty() ? objects->atissArray[i] : 0), (!objects->antissArray.empty() ? objects->antissArray[i] : 0), (!objects->npArray.empty() ? objects->npArray[i] : 0), (!objects->rvArray.empty() ? objects->rvArray[i] : 0), (!objects->rcadArray.empty() ? objects->rcadArray[i] : 0), (!objects->rgctArray.empty() ? objects->rgctArray[i] : 0), (!objects->smo2Array.empty() ? objects->smo2Array[i] : 0), (!objects->thbArray.empty() ? objects->thbArray[i] : 0), (!objects->o2hbArray.empty() ? objects->o2hbArray[i] : 0), (!objects->hhbArray.empty() ? objects->hhbArray[i] : 0), (!objects->apArray.empty() ? objects->apArray[i] : 0), (!objects->xpArray.empty() ? objects->xpArray[i] : 0), (!objects->speedArray.empty() ? objects->speedArray[i] : 0), (!objects->cadArray.empty() ? objects->cadArray[i] : 0), (!objects->altArray.empty() ? objects->altArray[i] : 0), (!objects->tempArray.empty() ? objects->tempArray[i] : 0), (!objects->windArray.empty() ? objects->windArray[i] : 0), (!objects->torqueArray.empty() ? objects->torqueArray[i] : 0), (!objects->balanceArray.empty() ? objects->balanceArray[i] : 0), (!objects->lteArray.empty() ? objects->lteArray[i] : 0), (!objects->rteArray.empty() ? objects->rteArray[i] : 0), (!objects->lpsArray.empty() ? objects->lpsArray[i] : 0), (!objects->rpsArray.empty() ? objects->rpsArray[i] : 0), (!objects->lpcoArray.empty() ? objects->lpcoArray[i] : 0), (!objects->rpcoArray.empty() ? objects->rpcoArray[i] : 0), (!objects->lppbArray.empty() ? objects->lppbArray[i] : 0), (!objects->rppbArray.empty() ? objects->rppbArray[i] : 0), (!objects->lppeArray.empty() ? objects->lppeArray[i] : 0), (!objects->rppeArray.empty() ? objects->rppeArray[i] : 0), (!objects->lpppbArray.empty() ? objects->lpppbArray[i] : 0), (!objects->rpppbArray.empty() ? objects->rpppbArray[i] : 0), (!objects->lpppeArray.empty() ? objects->lpppeArray[i] : 0), (!objects->rpppeArray.empty() ? objects->rpppeArray[i] : 0), (!objects->accelArray.empty() ? objects->accelArray[i] : 0), (!objects->wattsDArray.empty() ? objects->wattsDArray[i] : 0), (!objects->cadDArray.empty() ? objects->cadDArray[i] : 0), (!objects->nmDArray.empty() ? objects->nmDArray[i] : 0), (!objects->hrDArray.empty() ? objects->hrDArray[i] : 0), (!objects->slopeArray.empty() ? objects->slopeArray[i] : 0), (!objects->tcoreArray.empty() ? objects->tcoreArray[i] : 0)); if (!objects->wattsArray.empty()) totalWatts += objects->wattsArray[i]; if (!objects->npArray.empty()) totalNP += objects->npArray[i]; if (!objects->rvArray.empty()) totalRV += objects->rvArray[i]; if (!objects->rcadArray.empty()) totalRCad += objects->rcadArray[i]; if (!objects->rgctArray.empty()) totalRGCT += objects->rgctArray[i]; if (!objects->smo2Array.empty()) totalSmO2 += objects->smo2Array[i]; if (!objects->thbArray.empty()) totaltHb += objects->thbArray[i]; if (!objects->o2hbArray.empty()) totalO2Hb += objects->o2hbArray[i]; if (!objects->hhbArray.empty()) totalHHb += objects->hhbArray[i]; if (!objects->atissArray.empty()) totalATISS += objects->atissArray[i]; if (!objects->antissArray.empty()) totalANTISS += objects->antissArray[i]; if (!objects->xpArray.empty()) totalXP += objects->xpArray[i]; if (!objects->apArray.empty()) totalAP += objects->apArray[i]; if (!objects->tcoreArray.empty()) totalTcore += objects->tcoreArray[i]; if (!objects->hrArray.empty()) totalHr += objects->hrArray[i]; if (!objects->accelArray.empty()) totalAccel += objects->accelArray[i]; if (!objects->wattsDArray.empty()) totalWattsD += objects->wattsDArray[i]; if (!objects->cadDArray.empty()) totalCadD += objects->cadDArray[i]; if (!objects->nmDArray.empty()) totalNmD += objects->nmDArray[i]; if (!objects->hrDArray.empty()) totalHrD += objects->hrDArray[i]; if (!objects->speedArray.empty()) totalSpeed += objects->speedArray[i]; if (!objects->cadArray.empty()) totalCad += objects->cadArray[i]; if (!objects->altArray.empty()) totalAlt += objects->altArray[i]; if (!objects->slopeArray.empty()) totalSlope += objects->slopeArray[i]; if (!objects->windArray.empty()) totalWind += objects->windArray[i]; if (!objects->torqueArray.empty()) totalTorque += objects->torqueArray[i]; if (!objects->tempArray.empty() ) { if (objects->tempArray[i] == RideFile::NoTemp) { dp.temp = (i>0 && !list.empty()?list.back().temp:0.0); totalTemp += dp.temp; } else { totalTemp += objects->tempArray[i]; } } // left/right pedal data if (!objects->balanceArray.empty()) totalBalance += (objects->balanceArray[i]>0?objects->balanceArray[i]:50); if (!objects->lteArray.empty()) totalLTE += (objects->lteArray[i]>0?objects->lteArray[i]:0); if (!objects->rteArray.empty()) totalRTE += (objects->rteArray[i]>0?objects->rteArray[i]:0); if (!objects->lpsArray.empty()) totalLPS += (objects->lpsArray[i]>0?objects->lpsArray[i]:0); if (!objects->rpsArray.empty()) totalRPS += (objects->rpsArray[i]>0?objects->rpsArray[i]:0); if (!objects->lpcoArray.empty()) totalLPCO += objects->lpcoArray[i]; if (!objects->rpcoArray.empty()) totalRPCO += objects->rpcoArray[i]; if (!objects->lppbArray.empty()) totalLPPB += (objects->lppbArray[i]>0?objects->lppbArray[i]:0); if (!objects->rppbArray.empty()) totalRPPB += (objects->rppbArray[i]>0?objects->rppbArray[i]:0); if (!objects->lppeArray.empty()) totalLPPE += (objects->lppeArray[i]>0?objects->lppeArray[i]:0); if (!objects->rppeArray.empty()) totalRPPE += (objects->rppeArray[i]>0?objects->rppeArray[i]:0); if (!objects->lpppbArray.empty()) totalLPPPB += (objects->lpppbArray[i]>0?objects->lpppbArray[i]:0); if (!objects->rpppbArray.empty()) totalRPPPB += (objects->rpppbArray[i]>0?objects->rpppbArray[i]:0); if (!objects->lpppeArray.empty()) totalLPPPE += (objects->lpppeArray[i]>0?objects->lpppeArray[i]:0); if (!objects->rpppeArray.empty()) totalRPPPE += (objects->rpppeArray[i]>0?objects->rpppeArray[i]:0); totalDist = objects->distanceArray[i]; list.append(dp); ++i; } while (!list.empty() && (list.front().time < secs - applysmooth)) { DataPoint &dp = list.front(); totalWatts -= dp.watts; totalNP -= dp.np; totalRV -= dp.rv; totalRCad -= dp.rcad; totalRGCT -= dp.rgct; totalSmO2 -= dp.smo2; totaltHb -= dp.thb; totalO2Hb -= dp.o2hb; totalHHb -= dp.hhb; totalATISS -= dp.atiss; totalANTISS -= dp.antiss; totalAP -= dp.ap; totalXP -= dp.xp; totalHr -= dp.hr; totalTcore -= dp.tcore; totalSpeed -= dp.speed; totalAccel -= dp.kphd; totalWattsD -= dp.wattsd; totalCadD -= dp.cadd; totalNmD -= dp.nmd; totalHrD -= dp.hrd; totalCad -= dp.cad; totalAlt -= dp.alt; totalSlope -= dp.slope; totalTemp -= dp.temp; totalWind -= dp.wind; totalTorque -= dp.torque; totalLTE -= dp.lte; totalRTE -= dp.rte; totalLPS -= dp.lps; totalRPS -= dp.rps; totalLPCO -= dp.lpco; totalRPCO -= dp.rpco; totalLPPB -= dp.lppb; totalRPPB -= dp.rppb; totalLPPE -= dp.lppe; totalRPPE -= dp.rppe; totalLPPPB -= dp.lpppb; totalRPPPB -= dp.rpppb; totalLPPPE -= dp.lpppe; totalRPPPE -= dp.rpppe; totalBalance -= (dp.lrbalance>0?dp.lrbalance:50); list.removeFirst(); } // TODO: this is wrong. We should do a weighted average over the // seconds represented by each point... if (list.empty()) { objects->smoothWatts[secs] = 0.0; objects->smoothNP[secs] = 0.0; objects->smoothRV[secs] = 0.0; objects->smoothRCad[secs] = 0.0; objects->smoothRGCT[secs] = 0.0; objects->smoothSmO2[secs] = 0.0; objects->smoothtHb[secs] = 0.0; objects->smoothO2Hb[secs] = 0.0; objects->smoothHHb[secs] = 0.0; objects->smoothAT[secs] = 0.0; objects->smoothANT[secs] = 0.0; objects->smoothXP[secs] = 0.0; objects->smoothAP[secs] = 0.0; objects->smoothHr[secs] = 0.0; objects->smoothTcore[secs] = 0.0; objects->smoothSpeed[secs] = 0.0; objects->smoothAccel[secs] = 0.0; objects->smoothWattsD[secs] = 0.0; objects->smoothCadD[secs] = 0.0; objects->smoothNmD[secs] = 0.0; objects->smoothHrD[secs] = 0.0; objects->smoothCad[secs] = 0.0; objects->smoothAltitude[secs] = ((secs > 0) ? objects->smoothAltitude[secs - 1] : objects->altArray[secs] ) ; objects->smoothSlope[secs] = 0.0; objects->smoothTemp[secs] = 0.0; objects->smoothWind[secs] = 0.0; objects->smoothRelSpeed[secs] = QwtIntervalSample(); objects->smoothTorque[secs] = 0.0; objects->smoothLTE[secs] = 0.0; objects->smoothRTE[secs] = 0.0; objects->smoothLPS[secs] = 0.0; objects->smoothRPS[secs] = 0.0; objects->smoothLPCO[secs] = 0.0; objects->smoothRPCO[secs] = 0.0; objects->smoothLPP[secs] = QwtIntervalSample(); objects->smoothRPP[secs] = QwtIntervalSample(); objects->smoothLPPP[secs] = QwtIntervalSample(); objects->smoothRPPP[secs] = QwtIntervalSample(); objects->smoothBalanceL[secs] = 50; objects->smoothBalanceR[secs] = 50; } else { objects->smoothWatts[secs] = totalWatts / list.size(); objects->smoothNP[secs] = totalNP / list.size(); objects->smoothRV[secs] = totalRV / list.size(); objects->smoothRCad[secs] = totalRCad / list.size(); objects->smoothRGCT[secs] = totalRGCT / list.size(); objects->smoothSmO2[secs] = totalSmO2 / list.size(); objects->smoothtHb[secs] = totaltHb / list.size(); objects->smoothO2Hb[secs] = totalO2Hb / list.size(); objects->smoothHHb[secs] = totalHHb / list.size(); objects->smoothAT[secs] = totalATISS / list.size(); objects->smoothANT[secs] = totalANTISS / list.size(); objects->smoothXP[secs] = totalXP / list.size(); objects->smoothAP[secs] = totalAP / list.size(); objects->smoothHr[secs] = totalHr / list.size(); objects->smoothTcore[secs] = totalTcore / list.size(); objects->smoothSpeed[secs] = totalSpeed / list.size(); objects->smoothAccel[secs] = totalAccel / double(list.size()); objects->smoothWattsD[secs] = totalWattsD / double(list.size()); objects->smoothCadD[secs] = totalCadD / double(list.size()); objects->smoothNmD[secs] = totalNmD / double(list.size()); objects->smoothHrD[secs] = totalHrD / double(list.size()); objects->smoothCad[secs] = totalCad / list.size(); objects->smoothAltitude[secs] = totalAlt / list.size(); objects->smoothSlope[secs] = totalSlope / double(list.size()); objects->smoothTemp[secs] = totalTemp / list.size(); objects->smoothWind[secs] = totalWind / list.size(); objects->smoothRelSpeed[secs] = QwtIntervalSample( bydist ? totalDist : secs / 60.0, QwtInterval(qMin(totalWind / list.size(), totalSpeed / list.size()), qMax(totalWind / list.size(), totalSpeed / list.size()) ) ); objects->smoothTorque[secs] = totalTorque / list.size(); // left /right pedal data double balance = totalBalance / list.size(); if (balance == 0) { objects->smoothBalanceL[secs] = 50; objects->smoothBalanceR[secs] = 50; } else if (balance >= 50) { objects->smoothBalanceL[secs] = balance; objects->smoothBalanceR[secs] = 50; } else { objects->smoothBalanceL[secs] = 50; objects->smoothBalanceR[secs] = balance; } objects->smoothLTE[secs] = totalLTE / list.size(); objects->smoothRTE[secs] = totalRTE / list.size(); objects->smoothLPS[secs] = totalLPS / list.size(); objects->smoothRPS[secs] = totalRPS / list.size(); objects->smoothLPCO[secs] = totalLPCO / list.size(); objects->smoothRPCO[secs] = totalRPCO / list.size(); objects->smoothLPP[secs] = QwtIntervalSample( bydist ? totalDist : secs / 60.0, QwtInterval(totalLPPB / list.size(), totalLPPE / list.size() ) ); objects->smoothRPP[secs] = QwtIntervalSample( bydist ? totalDist : secs / 60.0, QwtInterval(totalRPPB / list.size(), totalRPPE / list.size() ) ); objects->smoothLPPP[secs] = QwtIntervalSample( bydist ? totalDist : secs / 60.0, QwtInterval(totalLPPPB / list.size(), totalLPPPE / list.size() ) ); objects->smoothRPPP[secs] = QwtIntervalSample( bydist ? totalDist : secs / 60.0, QwtInterval(totalRPPPB / list.size(), totalRPPPE / list.size() ) ); } objects->smoothDistance[secs] = totalDist; objects->smoothTime[secs] = secs / 60.0; // set data series (gearRatio) which are not smoothed at all if (objects->gearArray.empty() || secs >= objects->gearArray.count()) { objects->smoothGear[secs] = 0.0f; } else { objects->smoothGear[secs] = objects->gearArray[secs]; } } } else { // no standard->smoothing .. just raw data objects->smoothWatts.resize(0); objects->smoothNP.resize(0); objects->smoothGear.resize(0); objects->smoothRV.resize(0); objects->smoothRCad.resize(0); objects->smoothRGCT.resize(0); objects->smoothSmO2.resize(0); objects->smoothtHb.resize(0); objects->smoothO2Hb.resize(0); objects->smoothHHb.resize(0); objects->smoothAT.resize(0); objects->smoothANT.resize(0); objects->smoothXP.resize(0); objects->smoothAP.resize(0); objects->smoothHr.resize(0); objects->smoothTcore.resize(0); objects->smoothSpeed.resize(0); objects->smoothAccel.resize(0); objects->smoothWattsD.resize(0); objects->smoothCadD.resize(0); objects->smoothNmD.resize(0); objects->smoothHrD.resize(0); objects->smoothCad.resize(0); objects->smoothTime.resize(0); objects->smoothDistance.resize(0); objects->smoothAltitude.resize(0); objects->smoothSlope.resize(0); objects->smoothTemp.resize(0); objects->smoothWind.resize(0); objects->smoothRelSpeed.resize(0); objects->smoothTorque.resize(0); objects->smoothLTE.resize(0); objects->smoothRTE.resize(0); objects->smoothLPS.resize(0); objects->smoothRPS.resize(0); objects->smoothLPCO.resize(0); objects->smoothRPCO.resize(0); objects->smoothLPP.resize(0); objects->smoothRPP.resize(0); objects->smoothLPPP.resize(0); objects->smoothRPPP.resize(0); objects->smoothBalanceL.resize(0); objects->smoothBalanceR.resize(0); foreach (RideFilePoint *dp, rideItem->ride()->dataPoints()) { objects->smoothWatts.append(dp->watts); objects->smoothNP.append(dp->np); objects->smoothRV.append(dp->rvert); objects->smoothRCad.append(dp->rcad); objects->smoothRGCT.append(dp->rcontact); objects->smoothGear.append(dp->gear); objects->smoothSmO2.append(dp->smo2); objects->smoothtHb.append(dp->thb); objects->smoothO2Hb.append(dp->o2hb); objects->smoothHHb.append(dp->hhb); objects->smoothAT.append(dp->atiss); objects->smoothANT.append(dp->antiss); objects->smoothXP.append(dp->xp); objects->smoothAP.append(dp->apower); objects->smoothHr.append(dp->hr); objects->smoothTcore.append(dp->tcore); objects->smoothSpeed.append(context->athlete->useMetricUnits ? dp->kph : dp->kph * MILES_PER_KM); objects->smoothAccel.append(dp->kphd); objects->smoothWattsD.append(dp->wattsd); objects->smoothCadD.append(dp->cadd); objects->smoothNmD.append(dp->nmd); objects->smoothHrD.append(dp->hrd); objects->smoothCad.append(dp->cad); objects->smoothTime.append(dp->secs/60); objects->smoothDistance.append(context->athlete->useMetricUnits ? dp->km : dp->km * MILES_PER_KM); objects->smoothAltitude.append(context->athlete->useMetricUnits ? dp->alt : dp->alt * FEET_PER_METER); objects->smoothSlope.append(dp->slope); if (dp->temp == RideFile::NoTemp && !objects->smoothTemp.empty()) dp->temp = objects->smoothTemp.last(); objects->smoothTemp.append(context->athlete->useMetricUnits ? dp->temp : dp->temp * FAHRENHEIT_PER_CENTIGRADE + FAHRENHEIT_ADD_CENTIGRADE); objects->smoothWind.append(context->athlete->useMetricUnits ? dp->headwind : dp->headwind * MILES_PER_KM); objects->smoothTorque.append(dp->nm); if (dp->lrbalance == 0) { objects->smoothBalanceL.append(50); objects->smoothBalanceR.append(50); } else if (dp->lrbalance >= 50) { objects->smoothBalanceL.append(dp->lrbalance); objects->smoothBalanceR.append(50); } else { objects->smoothBalanceL.append(50); objects->smoothBalanceR.append(dp->lrbalance); } objects->smoothLTE.append(dp->lte); objects->smoothRTE.append(dp->rte); objects->smoothLPS.append(dp->lps); objects->smoothRPS.append(dp->rps); objects->smoothLPCO.append(dp->lpco); objects->smoothRPCO.append(dp->rpco); objects->smoothLPP.append(QwtIntervalSample( bydist ? objects->smoothDistance.last() : objects->smoothTime.last(), QwtInterval(dp->lppb , dp->rppe ) )); objects->smoothRPP.append(QwtIntervalSample( bydist ? objects->smoothDistance.last() : objects->smoothTime.last(), QwtInterval(dp->rppb , dp->rppe ) )); objects->smoothLPPP.append(QwtIntervalSample( bydist ? objects->smoothDistance.last() : objects->smoothTime.last(), QwtInterval(dp->lpppb , dp->lpppe ) )); objects->smoothRPPP.append(QwtIntervalSample( bydist ? objects->smoothDistance.last() : objects->smoothTime.last(), QwtInterval(dp->rpppb , dp->rpppe ) )); double head = dp->headwind * (context->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); double speed = dp->kph * (context->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); objects->smoothRelSpeed.append(QwtIntervalSample( bydist ? objects->smoothDistance.last() : objects->smoothTime.last(), QwtInterval(qMin(head, speed) , qMax(head, speed) ) )); } } QVector<double> &xaxis = bydist ? objects->smoothDistance : objects->smoothTime; int startingIndex = qMin(smooth, xaxis.count()); int totalPoints = xaxis.count() - startingIndex; // set curves - we set the intervalHighlighter to whichver is available //W' curve set to whatever data we have if (!objects->wprime.empty()) { objects->wCurve->setSamples(bydist ? objects->wprimeDist.data() : objects->wprimeTime.data(), objects->wprime.data(), objects->wprime.count()); objects->mCurve->setSamples(bydist ? objects->matchDist.data() : objects->matchTime.data(), objects->match.data(), objects->match.count()); setMatchLabels(objects); } if (!objects->wattsArray.empty()) { objects->wattsCurve->setSamples(xaxis.data() + startingIndex, objects->smoothWatts.data() + startingIndex, totalPoints); } if (!objects->antissArray.empty()) { objects->antissCurve->setSamples(xaxis.data() + startingIndex, objects->smoothANT.data() + startingIndex, totalPoints); } if (!objects->atissArray.empty()) { objects->atissCurve->setSamples(xaxis.data() + startingIndex, objects->smoothAT.data() + startingIndex, totalPoints); } if (!objects->rvArray.empty()) { objects->rvCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRV.data() + startingIndex, totalPoints); } if (!objects->rcadArray.empty()) { objects->rcadCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRCad.data() + startingIndex, totalPoints); } if (!objects->rgctArray.empty()) { objects->rgctCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRGCT.data() + startingIndex, totalPoints); } if (!objects->gearArray.empty()) { objects->gearCurve->setSamples(xaxis.data() + startingIndex, objects->smoothGear.data() + startingIndex, totalPoints); } if (!objects->smo2Array.empty()) { objects->smo2Curve->setSamples(xaxis.data() + startingIndex, objects->smoothSmO2.data() + startingIndex, totalPoints); } if (!objects->thbArray.empty()) { objects->thbCurve->setSamples(xaxis.data() + startingIndex, objects->smoothtHb.data() + startingIndex, totalPoints); } if (!objects->o2hbArray.empty()) { objects->o2hbCurve->setSamples(xaxis.data() + startingIndex, objects->smoothO2Hb.data() + startingIndex, totalPoints); } if (!objects->hhbArray.empty()) { objects->hhbCurve->setSamples(xaxis.data() + startingIndex, objects->smoothHHb.data() + startingIndex, totalPoints); } if (!objects->npArray.empty()) { objects->npCurve->setSamples(xaxis.data() + startingIndex, objects->smoothNP.data() + startingIndex, totalPoints); } if (!objects->xpArray.empty()) { objects->xpCurve->setSamples(xaxis.data() + startingIndex, objects->smoothXP.data() + startingIndex, totalPoints); } if (!objects->apArray.empty()) { objects->apCurve->setSamples(xaxis.data() + startingIndex, objects->smoothAP.data() + startingIndex, totalPoints); } if (!objects->hrArray.empty()) { objects->hrCurve->setSamples(xaxis.data() + startingIndex, objects->smoothHr.data() + startingIndex, totalPoints); } if (!objects->tcoreArray.empty()) { objects->tcoreCurve->setSamples(xaxis.data() + startingIndex, objects->smoothTcore.data() + startingIndex, totalPoints); } if (!objects->speedArray.empty()) { objects->speedCurve->setSamples(xaxis.data() + startingIndex, objects->smoothSpeed.data() + startingIndex, totalPoints); } if (!objects->accelArray.empty()) { objects->accelCurve->setSamples(xaxis.data() + startingIndex, objects->smoothAccel.data() + startingIndex, totalPoints); } if (!objects->wattsDArray.empty()) { objects->wattsDCurve->setSamples(xaxis.data() + startingIndex, objects->smoothWattsD.data() + startingIndex, totalPoints); } if (!objects->cadDArray.empty()) { objects->cadDCurve->setSamples(xaxis.data() + startingIndex, objects->smoothCadD.data() + startingIndex, totalPoints); } if (!objects->nmDArray.empty()) { objects->nmDCurve->setSamples(xaxis.data() + startingIndex, objects->smoothNmD.data() + startingIndex, totalPoints); } if (!objects->hrDArray.empty()) { objects->hrDCurve->setSamples(xaxis.data() + startingIndex, objects->smoothHrD.data() + startingIndex, totalPoints); } if (!objects->cadArray.empty()) { objects->cadCurve->setSamples(xaxis.data() + startingIndex, objects->smoothCad.data() + startingIndex, totalPoints); } if (!objects->altArray.empty()) { objects->altCurve->setSamples(xaxis.data() + startingIndex, objects->smoothAltitude.data() + startingIndex, totalPoints); objects->altSlopeCurve->setSamples(xaxis.data() + startingIndex, objects->smoothAltitude.data() + startingIndex, totalPoints); } if (!objects->slopeArray.empty()) { objects->slopeCurve->setSamples(xaxis.data() + startingIndex, objects->smoothSlope.data() + startingIndex, totalPoints); } if (!objects->tempArray.empty()) { objects->tempCurve->setSamples(xaxis.data() + startingIndex, objects->smoothTemp.data() + startingIndex, totalPoints); } if (!objects->windArray.empty()) { objects->windCurve->setSamples(new QwtIntervalSeriesData(objects->smoothRelSpeed)); } if (!objects->torqueArray.empty()) { objects->torqueCurve->setSamples(xaxis.data() + startingIndex, objects->smoothTorque.data() + startingIndex, totalPoints); } // left/right pedals if (!objects->balanceArray.empty()) { objects->balanceLCurve->setSamples(xaxis.data() + startingIndex, objects->smoothBalanceL.data() + startingIndex, totalPoints); objects->balanceRCurve->setSamples(xaxis.data() + startingIndex, objects->smoothBalanceR.data() + startingIndex, totalPoints); } if (!objects->lteArray.empty()) objects->lteCurve->setSamples(xaxis.data() + startingIndex, objects->smoothLTE.data() + startingIndex, totalPoints); if (!objects->rteArray.empty()) objects->rteCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRTE.data() + startingIndex, totalPoints); if (!objects->lpsArray.empty()) objects->lpsCurve->setSamples(xaxis.data() + startingIndex, objects->smoothLPS.data() + startingIndex, totalPoints); if (!objects->rpsArray.empty()) objects->rpsCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRPS.data() + startingIndex, totalPoints); if (!objects->lpcoArray.empty()) objects->lpcoCurve->setSamples(xaxis.data() + startingIndex, objects->smoothLPCO.data() + startingIndex, totalPoints); if (!objects->rpcoArray.empty()) objects->rpcoCurve->setSamples(xaxis.data() + startingIndex, objects->smoothRPCO.data() + startingIndex, totalPoints); if (!objects->lppbArray.empty()) { objects->lppCurve->setSamples(new QwtIntervalSeriesData(objects->smoothLPP)); } if (!objects->rppbArray.empty()) { objects->rppCurve->setSamples(new QwtIntervalSeriesData(objects->smoothRPP)); } if (!objects->lpppbArray.empty()) { objects->lpppCurve->setSamples(new QwtIntervalSeriesData(objects->smoothLPPP)); } if (!objects->rpppbArray.empty()) { objects->rpppCurve->setSamples(new QwtIntervalSeriesData(objects->smoothRPPP)); } setAltSlopePlotStyle(objects->altSlopeCurve); setYMax(); if (!context->isCompareIntervals) { refreshReferenceLines(); refreshIntervalMarkers(); refreshCalibrationMarkers(); refreshZoneLabels(); } // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::refreshIntervalMarkers() { QwtIndPlotMarker::resetDrawnLabels(); foreach(QwtPlotMarker *mrk, standard->d_mrk) { mrk->detach(); delete mrk; } standard->d_mrk.clear(); if (rideItem && rideItem->ride()) { foreach(IntervalItem *interval, rideItem->intervals()) { bool nolabel = false; // no label, but do add if (interval->type != RideFileInterval::USER) nolabel = true; QwtPlotMarker *mrk = new QwtIndPlotMarker; standard->d_mrk.append(mrk); mrk->attach(this); mrk->setLineStyle(QwtPlotMarker::VLine); mrk->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); if (nolabel) mrk->setLinePen(QPen(QColor(127,127,127,64), 0, Qt::DashLine)); else mrk->setLinePen(QPen(GColor(CPLOTMARKER), 0, Qt::DashLine)); // put matches on second line down QString name(interval->name); if (interval->name.startsWith(tr("Match"))) name = QString("\n%1").arg(interval->name); QwtText text(wanttext && !nolabel ? name : ""); if (!nolabel) { text.setFont(QFont("Helvetica", 10, QFont::Bold)); if (interval->name.startsWith(tr("Match"))) text.setColor(GColor(CWBAL)); else text.setColor(GColor(CPLOTMARKER)); } if (!bydist) mrk->setValue(interval->start / 60.0, 0.0); else mrk->setValue((context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * interval->startKM, 0.0); mrk->setLabel(text); } } } void AllPlot::refreshCalibrationMarkers() { foreach(QwtPlotMarker *mrk, standard->cal_mrk) { mrk->detach(); delete mrk; } standard->cal_mrk.clear(); // only on power based charts if (scope != RideFile::none && scope != RideFile::watts && scope != RideFile::aTISS && scope != RideFile::anTISS && scope != RideFile::NP && scope != RideFile::aPower && scope != RideFile::xPower) return; QColor color = GColor(CPOWER); color.setAlpha(15); // almost invisible ! if (rideItem && rideItem->ride()) { foreach(const RideFileCalibration *calibration, rideItem->ride()->calibrations()) { QwtPlotMarker *mrk = new QwtPlotMarker; standard->cal_mrk.append(mrk); mrk->attach(this); mrk->setLineStyle(QwtPlotMarker::VLine); mrk->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); mrk->setLinePen(QPen(color, 0, Qt::SolidLine)); if (!bydist) mrk->setValue(calibration->start / 60.0, 0.0); else mrk->setValue((context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * rideItem->ride()->timeToDistance(calibration->start), 0.0); //Lots of markers can clutter things, so avoid texts for now //QwtText text(false ? ("\n\n"+calibration.name) : ""); //text.setFont(QFont("Helvetica", 9, QFont::Bold)); //text.setColor(Qt::gray); //mrk->setLabel(text); } } } void AllPlot::refreshReferenceLines() { // not supported in compare mode if (context->isCompareIntervals) return; // only on power based charts if (scope != RideFile::none && scope != RideFile::watts && scope != RideFile::aTISS && scope != RideFile::anTISS && scope != RideFile::NP && scope != RideFile::aPower && scope != RideFile::xPower) return; foreach(QwtPlotCurve *referenceLine, standard->referenceLines) { curveColors->remove(referenceLine); referenceLine->detach(); delete referenceLine; } standard->referenceLines.clear(); if (rideItem && rideItem->ride()) { foreach(const RideFilePoint *referencePoint, rideItem->ride()->referencePoints()) { QwtPlotCurve *referenceLine = plotReferenceLine(referencePoint); if (referenceLine) standard->referenceLines.append(referenceLine); } } } QwtPlotCurve* AllPlot::plotReferenceLine(const RideFilePoint *referencePoint) { // not supported in compare mode if (context->isCompareIntervals) return NULL; // only on power based charts if (scope != RideFile::none && scope != RideFile::watts && scope != RideFile::aTISS && scope != RideFile::anTISS && scope != RideFile::NP && scope != RideFile::aPower && scope != RideFile::xPower) return NULL; QwtPlotCurve *referenceLine = NULL; QVector<double> xaxis; QVector<double> yaxis; xaxis << axisScaleDiv(QwtPlot::xBottom).lowerBound(); xaxis << axisScaleDiv(QwtPlot::xBottom).upperBound(); if (referencePoint->watts != 0) { referenceLine = new QwtPlotCurve(tr("Power Ref")); referenceLine->setYAxis(yLeft); QPen wattsPen = QPen(GColor(CPOWER)); wattsPen.setWidth(1); wattsPen.setStyle(Qt::DashLine); referenceLine->setPen(wattsPen); yaxis.append(referencePoint->watts); yaxis.append(referencePoint->watts); } else if (referencePoint->hr != 0) { referenceLine = new QwtPlotCurve(tr("Heart Rate Ref")); referenceLine->setYAxis(yLeft); QPen hrPen = QPen(GColor(CHEARTRATE)); hrPen.setWidth(1); hrPen.setStyle(Qt::DashLine); referenceLine->setPen(hrPen); yaxis.append(referencePoint->hr); yaxis.append(referencePoint->hr); } else if (referencePoint->cad != 0) { referenceLine = new QwtPlotCurve(tr("Cadence Ref")); referenceLine->setYAxis(yLeft); QPen cadPen = QPen(GColor(CCADENCE)); cadPen.setWidth(1); cadPen.setStyle(Qt::DashLine); referenceLine->setPen(cadPen); yaxis.append(referencePoint->cad); yaxis.append(referencePoint->cad); } if (referenceLine) { curveColors->insert(referenceLine); referenceLine->setSamples(xaxis,yaxis); referenceLine->attach(this); referenceLine->setVisible(true); } return referenceLine; } void AllPlot::replot() { QwtIndPlotMarker::resetDrawnLabels(); QwtPlot::replot(); } void AllPlot::setYMax() { // first lets show or hide, otherwise all the efforts to set scales // etc are ignored because the axis is not visible if (wantaxis) { setAxisVisible(yLeft, standard->wattsCurve->isVisible() || standard->atissCurve->isVisible() || standard->antissCurve->isVisible() || standard->npCurve->isVisible() || standard->rvCurve->isVisible() || standard->rcadCurve->isVisible() || standard->rgctCurve->isVisible() || standard->gearCurve->isVisible() || standard->xpCurve->isVisible() || standard->apCurve->isVisible()); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 1), standard->hrCurve->isVisible() || standard->tcoreCurve->isVisible() || standard->cadCurve->isVisible() || standard->smo2Curve->isVisible()); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 2), false); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 3), standard->balanceLCurve->isVisible() || standard->lteCurve->isVisible() || standard->lpsCurve->isVisible() || standard->slopeCurve->isVisible() ); setAxisVisible(yRight, standard->speedCurve->isVisible() || standard->torqueCurve->isVisible() || standard->thbCurve->isVisible() || standard->o2hbCurve->isVisible() || standard->hhbCurve->isVisible()); setAxisVisible(QwtAxisId(QwtAxis::yRight, 1), standard->altCurve->isVisible() || standard->altSlopeCurve->isVisible()); setAxisVisible(QwtAxisId(QwtAxis::yRight, 2), standard->wCurve->isVisible()); setAxisVisible(QwtAxisId(QwtAxis::yRight, 3), standard->atissCurve->isVisible() || standard->antissCurve->isVisible()); } else { setAxisVisible(yLeft, false); setAxisVisible(QwtAxisId(QwtAxis::yLeft,1), false); setAxisVisible(QwtAxisId(QwtAxis::yLeft,2), false); setAxisVisible(QwtAxisId(QwtAxis::yLeft,3), false); setAxisVisible(yRight, false); setAxisVisible(QwtAxisId(QwtPlot::yRight,1), false); setAxisVisible(QwtAxisId(QwtAxis::yRight,2), false); setAxisVisible(QwtAxisId(QwtAxis::yRight,3), false); } // might want xaxis if (wantxaxis) setAxisVisible(xBottom, true); else setAxisVisible(xBottom, false); // set axis scales // QwtAxis::yRight, 3 if (((showATISS && standard->atissCurve->isVisible()) || (showANTISS && standard->antissCurve->isVisible())) && rideItem && rideItem->ride()) { setAxisTitle(QwtAxisId(QwtAxis::yRight, 3), tr("TISS")); setAxisScale(QwtAxisId(QwtAxis::yRight, 3),0, qMax(standard->atissCurve->maxYValue(), standard->atissCurve->maxYValue()) * 1.05); setAxisLabelAlignment(QwtAxisId(QwtAxis::yRight, 3),Qt::AlignVCenter); } // QwtAxis::yRight, 2 if (showW && standard->wCurve->isVisible() && rideItem && rideItem->ride()) { setAxisTitle(QwtAxisId(QwtAxis::yRight, 2), tr("W' Balance (kJ)")); setAxisScale(QwtAxisId(QwtAxis::yRight, 2), qMin(int(standard->wCurve->minYValue()-1000), 0), qMax(int(standard->wCurve->maxYValue()+1000), 0)); setAxisLabelAlignment(QwtAxisId(QwtAxis::yRight, 2),Qt::AlignVCenter); } // QwtAxis::yLeft if (standard->wattsCurve->isVisible()) { double maxY = (referencePlot == NULL) ? (1.05 * standard->wattsCurve->maxYValue()) : (1.05 * referencePlot->standard->wattsCurve->maxYValue()); int axisHeight = qRound( plotLayout()->canvasRect().height() ); int step = 100; // axisHeight will be zero before first show, so only do this if its non-zero! if (axisHeight) { QFontMetrics labelWidthMetric = QFontMetrics( QwtPlot::axisFont(yLeft) ); int labelWidth = labelWidthMetric.width( (maxY > 1000) ? " 8,888 " : " 888 " ); while( ( qCeil(maxY / step) * labelWidth ) > axisHeight ) nextStep(step); } QwtValueList xytick[QwtScaleDiv::NTickTypes]; for (int i=0;i<maxY && i<2000;i+=step) xytick[QwtScaleDiv::MajorTick]<<i; setAxisTitle(yLeft, tr("Watts")); setAxisScaleDiv(QwtPlot::yLeft,QwtScaleDiv(0.0,maxY,xytick)); axisWidget(yLeft)->update(); } // QwtAxis::yLeft, 1 if (standard->hrCurve->isVisible() || standard->tcoreCurve->isVisible() || standard->cadCurve->isVisible() || standard->smo2Curve->isVisible() || (!context->athlete->useMetricUnits && standard->tempCurve->isVisible())) { double ymin = 0; double ymax = 0; QStringList labels; if (standard->hrCurve->isVisible()) { labels << tr("BPM"); if (referencePlot == NULL) ymax = standard->hrCurve->maxYValue(); else ymax = referencePlot->standard->hrCurve->maxYValue(); } if (standard->tcoreCurve->isVisible()) { labels << tr("Core Temperature"); if (referencePlot == NULL) ymax = qMax(ymax, standard->tcoreCurve->maxYValue()); else ymax = qMax(ymax, referencePlot->standard->tcoreCurve->maxYValue()); } if (standard->smo2Curve->isVisible()) { labels << tr("SmO2"); if (referencePlot == NULL) ymax = qMax(ymax, standard->smo2Curve->maxYValue()); else ymax = qMax(ymax, referencePlot->standard->smo2Curve->maxYValue()); } if (standard->cadCurve->isVisible()) { labels << tr("RPM"); if (referencePlot == NULL) ymax = qMax(ymax, standard->cadCurve->maxYValue()); else ymax = qMax(ymax, referencePlot->standard->cadCurve->maxYValue()); } if (standard->tempCurve->isVisible() && !context->athlete->useMetricUnits) { labels << QString::fromUtf8("°F"); if (referencePlot == NULL) { ymin = qMin(ymin, standard->tempCurve->minYValue()); ymax = qMax(ymax, standard->tempCurve->maxYValue()); } else { ymin = qMin(ymin, referencePlot->standard->tempCurve->minYValue()); ymax = qMax(ymax, referencePlot->standard->tempCurve->maxYValue()); } } int axisHeight = qRound( plotLayout()->canvasRect().height() ); int step = 10; if (axisHeight) { QFontMetrics labelWidthMetric = QFontMetrics( QwtPlot::axisFont(yLeft) ); int labelWidth = labelWidthMetric.width( "888 " ); ymax *= 1.05; while((qCeil(ymax / step) * labelWidth) > axisHeight) nextStep(step); } QwtValueList xytick[QwtScaleDiv::NTickTypes]; for (int i=0;i<ymax;i+=step) xytick[QwtScaleDiv::MajorTick]<<i; setAxisTitle(QwtAxisId(QwtAxis::yLeft, 1), labels.join(" / ")); if (labels.count() == 1 && labels[0] == tr("Core Temperature")) { double ymin=36.5f; if (ymax < 39.0f) ymax = 39.0f; if (standard->tcoreCurve->isVisible() && standard->tcoreCurve->minYValue() < ymin) ymin = standard->tcoreCurve->minYValue(); double step = 0.00f; if (ymin < 100.00f) step = (ymax - ymin) / 4; // we just have Core Temp ... setAxisScale(QwtAxisId(QwtAxis::yLeft, 1),ymin<100.0f?ymin:0, ymax, step); } else { setAxisScaleDiv(QwtAxisId(QwtAxis::yLeft, 1),QwtScaleDiv(ymin, ymax, xytick)); } } // QwtAxis::yLeft, 3 if ((standard->balanceLCurve->isVisible() || standard->lteCurve->isVisible() || standard->lpsCurve->isVisible()) || standard->slopeCurve->isVisible()){ QStringList labels; double ymin = 0; double ymax = 0; if (standard->balanceLCurve->isVisible() || standard->lteCurve->isVisible() || standard->lpsCurve->isVisible()) { labels << tr("Percent"); ymin = 0; ymax = 100; }; if (standard->slopeCurve->isVisible()) { labels << tr("Slope"); ymin = qMin(standard->slopeCurve->minYValue() * 1.1, ymin); ymax = qMax(standard->slopeCurve->maxYValue() * 1.1, ymax); }; // Set range from the curves setAxisTitle(QwtAxisId(QwtAxis::yLeft, 3), labels.join(" / ")); setAxisScale(QwtAxisId(QwtAxis::yLeft, 3), ymin, ymax); // not sure about this .. should be done on creation (?) standard->balanceLCurve->setBaseline(50); standard->balanceRCurve->setBaseline(50); } // QwtAxis::yRight, 0 if (standard->speedCurve->isVisible() || standard->thbCurve->isVisible() || standard->o2hbCurve->isVisible() || standard->hhbCurve->isVisible() || (context->athlete->useMetricUnits && standard->tempCurve->isVisible()) || standard->torqueCurve->isVisible()) { double ymin = -10; double ymax = 0; QStringList labels; // axis scale draw precision static_cast<ScaleScaleDraw*>(axisScaleDraw(QwtAxisId(QwtAxis::yRight, 0)))->setDecimals(2); if (standard->speedCurve->isVisible()) { labels << (context->athlete->useMetricUnits ? tr("KPH") : tr("MPH")); if (referencePlot == NULL) ymax = standard->speedCurve->maxYValue(); else ymax = referencePlot->standard->speedCurve->maxYValue(); } if (standard->tempCurve->isVisible() && context->athlete->useMetricUnits) { labels << QString::fromUtf8("°C"); if (referencePlot == NULL) { ymin = qMin(ymin, standard->tempCurve->minYValue()); ymax = qMax(ymax, standard->tempCurve->maxYValue()); } else { ymin = qMin(ymin, referencePlot->standard->tempCurve->minYValue()); ymax = qMax(ymax, referencePlot->standard->tempCurve->maxYValue()); } } if (standard->thbCurve->isVisible() || standard->o2hbCurve->isVisible() || standard->hhbCurve->isVisible()) { labels << tr("Hb"); if (referencePlot == NULL) ymax = qMax(ymax, standard->thbCurve->maxYValue()); else ymax = qMax(ymax, referencePlot->standard->thbCurve->maxYValue()); } if (standard->torqueCurve->isVisible()) { labels << (context->athlete->useMetricUnits ? tr("Nm") : tr("ftLb")); if (referencePlot == NULL) ymax = qMax(ymax, standard->torqueCurve->maxYValue()); else ymax = qMax(ymax, referencePlot->standard->torqueCurve->maxYValue()); } int axisHeight = qRound( plotLayout()->canvasRect().height() ); int step = 10; if (axisHeight) { QFontMetrics labelWidthMetric = QFontMetrics( QwtPlot::axisFont(yRight) ); int labelWidth = labelWidthMetric.width( "888 " ); ymax *= 1.05; while((qCeil(ymax / step) * labelWidth) > axisHeight) nextStep(step); } QwtValueList xytick[QwtScaleDiv::NTickTypes]; for (int i=0;i<ymax;i+=step) xytick[QwtScaleDiv::MajorTick]<<i; setAxisTitle(QwtAxisId(QwtAxis::yRight, 0), labels.join(" / ")); // we just have Hb ? if (labels.count() == 1 && labels[0] == tr("Hb")) { double ymin=100; ymax /= 1.05; ymax += .10f; if (standard->thbCurve->isVisible() && standard->thbCurve->minYValue() < ymin) ymin = standard->thbCurve->minYValue(); if (standard->o2hbCurve->isVisible() && standard->o2hbCurve->minYValue() < ymin) ymin = standard->o2hbCurve->minYValue(); if (standard->hhbCurve->isVisible() && standard->hhbCurve->minYValue() < ymin) ymin = standard->hhbCurve->minYValue(); double step = 0.00f; if (ymin < 100.00f) step = (ymax - ymin) / 5; // we just have Hb ... setAxisScale(QwtAxisId(QwtAxis::yRight, 0),ymin<100.0f?ymin:0, ymax, step); } else setAxisScaleDiv(QwtAxisId(QwtAxis::yRight, 0),QwtScaleDiv(0, ymax, xytick)); } // QwtAxis::yRight, 1 if (standard->altCurve->isVisible() || standard->altSlopeCurve->isVisible()) { setAxisTitle(QwtAxisId(QwtAxis::yRight, 1), context->athlete->useMetricUnits ? tr("Meters") : tr("Feet")); double ymin,ymax; if (referencePlot == NULL) { ymin = standard->altCurve->minYValue(); ymax = qMax(500.000, 1.05 * standard->altCurve->maxYValue()); } else { ymin = referencePlot->standard->altCurve->minYValue(); ymax = qMax(500.000, 1.05 * referencePlot->standard->altCurve->maxYValue()); } ymin = (ymin < 0 ? -100 : 0) + ( qRound(ymin) / 100 ) * 100; int axisHeight = qRound( plotLayout()->canvasRect().height() ); int step = 100; if (axisHeight) { QFontMetrics labelWidthMetric = QFontMetrics( QwtPlot::axisFont(yLeft) ); int labelWidth = labelWidthMetric.width( (ymax > 1000) ? " 8888 " : " 888 " ); while( ( qCeil( (ymax - ymin ) / step) * labelWidth ) > axisHeight ) nextStep(step); } QwtValueList xytick[QwtScaleDiv::NTickTypes]; for (int i=ymin;i<ymax;i+=step) xytick[QwtScaleDiv::MajorTick]<<i; setAxisScaleDiv(QwtAxisId(QwtAxis::yRight, 1),QwtScaleDiv(ymin,ymax,xytick)); standard->altCurve->setBaseline(ymin); } } void AllPlot::setXTitle() { if (bydist) setAxisTitle(xBottom, context->athlete->useMetricUnits ? "KM" : "Miles"); else setAxisTitle(xBottom, tr("")); // time is bloody obvious, less noise enableAxis(xBottom, true); setAxisVisible(xBottom, true); } // we do this a lot so trying to save a bit of cut and paste woe static void setSymbol(QwtPlotCurve *curve, int points) { QwtSymbol *sym = new QwtSymbol; sym->setPen(QPen(GColor(CPLOTMARKER))); if (points < 150) { sym->setStyle(QwtSymbol::Ellipse); sym->setSize(3); } else { sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); } curve->setSymbol(sym); } void AllPlot::setDataFromPlot(AllPlot *plot, int startidx, int stopidx) { if (plot == NULL) { rideItem = NULL; return; } referencePlot = plot; isolation = false; curveColors->saveState(); // You got to give me some data first! if (!plot->standard->distanceArray.count() || !plot->standard->timeArray.count()) return; // reference the plot for data and state rideItem = plot->rideItem; bydist = plot->bydist; //arrayLength = stopidx-startidx; if (bydist) { startidx = plot->distanceIndex(plot->standard->distanceArray[startidx]); stopidx = plot->distanceIndex(plot->standard->distanceArray[(stopidx>=plot->standard->distanceArray.size()?plot->standard->distanceArray.size()-1:stopidx)]); } else { startidx = plot->timeIndex(plot->standard->timeArray[startidx]/60); stopidx = plot->timeIndex(plot->standard->timeArray[(stopidx>=plot->standard->timeArray.size()?plot->standard->timeArray.size()-1:stopidx)]/60); } // center the curve title standard->curveTitle.setYValue(30); standard->curveTitle.setXValue(2); // make sure indexes are still valid if (startidx > stopidx || startidx < 0 || stopidx < 0) return; double *smoothW = &plot->standard->smoothWatts[startidx]; double *smoothN = &plot->standard->smoothNP[startidx]; double *smoothRV = &plot->standard->smoothRV[startidx]; double *smoothRCad = &plot->standard->smoothRCad[startidx]; double *smoothRGCT = &plot->standard->smoothRGCT[startidx]; double *smoothGear = &plot->standard->smoothGear[startidx]; double *smoothSmO2 = &plot->standard->smoothSmO2[startidx]; double *smoothtHb = &plot->standard->smoothtHb[startidx]; double *smoothO2Hb = &plot->standard->smoothO2Hb[startidx]; double *smoothHHb = &plot->standard->smoothHHb[startidx]; double *smoothAT = &plot->standard->smoothAT[startidx]; double *smoothANT = &plot->standard->smoothANT[startidx]; double *smoothX = &plot->standard->smoothXP[startidx]; double *smoothL = &plot->standard->smoothAP[startidx]; double *smoothT = &plot->standard->smoothTime[startidx]; double *smoothHR = &plot->standard->smoothHr[startidx]; double *smoothTCORE = &plot->standard->smoothTcore[startidx]; double *smoothS = &plot->standard->smoothSpeed[startidx]; double *smoothC = &plot->standard->smoothCad[startidx]; double *smoothA = &plot->standard->smoothAltitude[startidx]; double *smoothSL = &plot->standard->smoothSlope[startidx]; double *smoothD = &plot->standard->smoothDistance[startidx]; double *smoothTE = &plot->standard->smoothTemp[startidx]; //double *standard->smoothWND = &plot->standard->smoothWind[startidx]; double *smoothNM = &plot->standard->smoothTorque[startidx]; // left/right double *smoothBALL = &plot->standard->smoothBalanceL[startidx]; double *smoothBALR = &plot->standard->smoothBalanceR[startidx]; double *smoothLTE = &plot->standard->smoothLTE[startidx]; double *smoothRTE = &plot->standard->smoothRTE[startidx]; double *smoothLPS = &plot->standard->smoothLPS[startidx]; double *smoothRPS = &plot->standard->smoothRPS[startidx]; double *smoothLPCO = &plot->standard->smoothLPCO[startidx]; double *smoothRPCO = &plot->standard->smoothRPCO[startidx]; QwtIntervalSample *smoothLPP = &plot->standard->smoothLPP[startidx]; QwtIntervalSample *smoothRPP = &plot->standard->smoothRPP[startidx]; QwtIntervalSample *smoothLPPP = &plot->standard->smoothLPPP[startidx]; QwtIntervalSample *smoothRPPP = &plot->standard->smoothRPPP[startidx]; // deltas double *smoothAC = &plot->standard->smoothAccel[startidx]; double *smoothWD = &plot->standard->smoothWattsD[startidx]; double *smoothCD = &plot->standard->smoothCadD[startidx]; double *smoothND = &plot->standard->smoothNmD[startidx]; double *smoothHD = &plot->standard->smoothHrD[startidx]; QwtIntervalSample *smoothRS = &plot->standard->smoothRelSpeed[startidx]; double *xaxis = bydist ? smoothD : smoothT; // attach appropriate curves //if (this->legend()) this->legend()->hide(); if (showW && rideItem->ride()->wprimeData()->TAU > 0) { // matches cost double burnt=0; int count=0; foreach(struct Match match, rideItem->ride()->wprimeData()->matches) if (match.cost > 2000) { //XXX how to decide the threshold for a match? burnt += match.cost; count++; } QString warn; if (rideItem->ride()->wprimeData()->minY < 0) { int minCP = rideItem->ride()->wprimeData()->PCP(); if (minCP) warn = QString(tr("** Minimum CP=%1 **")).arg(rideItem->ride()->wprimeData()->PCP()); else warn = QString(tr("** Check W' is set correctly **")); } QString matchesText; // consider Singular/Plural in Text / Zero is in most languages handled like Plural if (count == 1) { matchesText = tr("Tau=%1, CP=%2, W'=%3, %4 match >2kJ (%5 kJ) %6"); } else { matchesText = tr("Tau=%1, CP=%2, W'=%3, %4 matches >2kJ (%5 kJ) %6"); } QwtText text(matchesText.arg(rideItem->ride()->wprimeData()->TAU) .arg(rideItem->ride()->wprimeData()->CP) .arg(rideItem->ride()->wprimeData()->WPRIME) .arg(count) .arg(burnt/1000.00, 0, 'f', 1) .arg(warn)); text.setFont(QFont("Helvetica", 10, QFont::Bold)); text.setColor(GColor(CWBAL)); standard->curveTitle.setLabel(text); } else { standard->curveTitle.setLabel(QwtText("")); } standard->wCurve->detach(); standard->mCurve->detach(); standard->wattsCurve->detach(); standard->atissCurve->detach(); standard->antissCurve->detach(); standard->npCurve->detach(); standard->rvCurve->detach(); standard->rcadCurve->detach(); standard->rgctCurve->detach(); standard->gearCurve->detach(); standard->smo2Curve->detach(); standard->thbCurve->detach(); standard->o2hbCurve->detach(); standard->hhbCurve->detach(); standard->xpCurve->detach(); standard->apCurve->detach(); standard->hrCurve->detach(); standard->tcoreCurve->detach(); standard->speedCurve->detach(); standard->accelCurve->detach(); standard->wattsDCurve->detach(); standard->cadDCurve->detach(); standard->nmDCurve->detach(); standard->hrDCurve->detach(); standard->cadCurve->detach(); standard->altCurve->detach(); standard->altSlopeCurve->detach(); standard->slopeCurve->detach(); standard->tempCurve->detach(); standard->windCurve->detach(); standard->torqueCurve->detach(); standard->lteCurve->detach(); standard->rteCurve->detach(); standard->lpsCurve->detach(); standard->rpsCurve->detach(); standard->balanceLCurve->detach(); standard->balanceRCurve->detach(); standard->lpcoCurve->detach(); standard->rpcoCurve->detach(); standard->lppCurve->detach(); standard->rppCurve->detach(); standard->lpppCurve->detach(); standard->rpppCurve->detach(); standard->wattsCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showPowerState < 2); standard->atissCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showATISS); standard->antissCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showANTISS); standard->npCurve->setVisible(rideItem->ride()->areDataPresent()->np && showNP); standard->rvCurve->setVisible(rideItem->ride()->areDataPresent()->rvert && showRV); standard->rcadCurve->setVisible(rideItem->ride()->areDataPresent()->rcad && showRCad); standard->gearCurve->setVisible(rideItem->ride()->areDataPresent()->gear && showGear); standard->smo2Curve->setVisible(rideItem->ride()->areDataPresent()->smo2 && showSmO2); standard->thbCurve->setVisible(rideItem->ride()->areDataPresent()->thb && showtHb); standard->o2hbCurve->setVisible(rideItem->ride()->areDataPresent()->o2hb && showO2Hb); standard->hhbCurve->setVisible(rideItem->ride()->areDataPresent()->hhb && showHHb); standard->rgctCurve->setVisible(rideItem->ride()->areDataPresent()->rcontact && showRGCT); standard->xpCurve->setVisible(rideItem->ride()->areDataPresent()->xp && showXP); standard->apCurve->setVisible(rideItem->ride()->areDataPresent()->apower && showAP); standard->wCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showW); standard->mCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showW); standard->hrCurve->setVisible(rideItem->ride()->areDataPresent()->hr && showHr); standard->tcoreCurve->setVisible(rideItem->ride()->areDataPresent()->hr && showTcore); standard->speedCurve->setVisible(rideItem->ride()->areDataPresent()->kph && showSpeed); standard->accelCurve->setVisible(rideItem->ride()->areDataPresent()->kph && showAccel); standard->wattsDCurve->setVisible(rideItem->ride()->areDataPresent()->watts && showPowerD); standard->cadDCurve->setVisible(rideItem->ride()->areDataPresent()->cad && showCadD); standard->nmDCurve->setVisible(rideItem->ride()->areDataPresent()->nm && showTorqueD); standard->hrDCurve->setVisible(rideItem->ride()->areDataPresent()->hr && showHrD); standard->cadCurve->setVisible(rideItem->ride()->areDataPresent()->cad && showCad); standard->altCurve->setVisible(rideItem->ride()->areDataPresent()->alt && showAlt); standard->altSlopeCurve->setVisible(rideItem->ride()->areDataPresent()->alt && showAltSlopeState > 0); standard->slopeCurve->setVisible(rideItem->ride()->areDataPresent()->slope && showSlope); standard->tempCurve->setVisible(rideItem->ride()->areDataPresent()->temp && showTemp); standard->windCurve->setVisible(rideItem->ride()->areDataPresent()->headwind && showWind); standard->torqueCurve->setVisible(rideItem->ride()->areDataPresent()->nm && showTorque); standard->lteCurve->setVisible(rideItem->ride()->areDataPresent()->lte && showTE); standard->rteCurve->setVisible(rideItem->ride()->areDataPresent()->rte && showTE); standard->lpsCurve->setVisible(rideItem->ride()->areDataPresent()->lps && showPS); standard->rpsCurve->setVisible(rideItem->ride()->areDataPresent()->rps && showPS); standard->balanceLCurve->setVisible(rideItem->ride()->areDataPresent()->lrbalance && showBalance); standard->balanceRCurve->setVisible(rideItem->ride()->areDataPresent()->lrbalance && showBalance); standard->lpcoCurve->setVisible(rideItem->ride()->areDataPresent()->lpco && showPCO); standard->rpcoCurve->setVisible(rideItem->ride()->areDataPresent()->rpco && showPCO); standard->lppCurve->setVisible(rideItem->ride()->areDataPresent()->lppb && showDC); standard->rppCurve->setVisible(rideItem->ride()->areDataPresent()->rppb && showDC); standard->lpppCurve->setVisible(rideItem->ride()->areDataPresent()->lpppb && showPPP); standard->rpppCurve->setVisible(rideItem->ride()->areDataPresent()->rpppb && showPPP); if (showW) { standard->wCurve->setSamples(bydist ? plot->standard->wprimeDist.data() : plot->standard->wprimeTime.data(), plot->standard->wprime.data(), plot->standard->wprime.count()); standard->mCurve->setSamples(bydist ? plot->standard->matchDist.data() : plot->standard->matchTime.data(), plot->standard->match.data(), plot->standard->match.count()); setMatchLabels(standard); } int points = stopidx - startidx + 1; // e.g. 10 to 12 is 3 points 10,11,12, so not 12-10 ! standard->wattsCurve->setSamples(xaxis,smoothW,points); standard->atissCurve->setSamples(xaxis,smoothAT,points); standard->antissCurve->setSamples(xaxis,smoothANT,points); standard->npCurve->setSamples(xaxis,smoothN,points); standard->rvCurve->setSamples(xaxis,smoothRV,points); standard->rcadCurve->setSamples(xaxis,smoothRCad,points); standard->rgctCurve->setSamples(xaxis,smoothRGCT,points); standard->gearCurve->setSamples(xaxis,smoothGear,points); standard->smo2Curve->setSamples(xaxis,smoothSmO2,points); standard->thbCurve->setSamples(xaxis,smoothtHb,points); standard->o2hbCurve->setSamples(xaxis,smoothO2Hb,points); standard->hhbCurve->setSamples(xaxis,smoothHHb,points); standard->xpCurve->setSamples(xaxis,smoothX,points); standard->apCurve->setSamples(xaxis,smoothL,points); standard->hrCurve->setSamples(xaxis, smoothHR,points); standard->tcoreCurve->setSamples(xaxis, smoothTCORE,points); standard->speedCurve->setSamples(xaxis, smoothS, points); standard->accelCurve->setSamples(xaxis, smoothAC, points); standard->wattsDCurve->setSamples(xaxis, smoothWD, points); standard->cadDCurve->setSamples(xaxis, smoothCD, points); standard->nmDCurve->setSamples(xaxis, smoothND, points); standard->hrDCurve->setSamples(xaxis, smoothHD, points); standard->cadCurve->setSamples(xaxis, smoothC, points); standard->altCurve->setSamples(xaxis, smoothA, points); standard->altSlopeCurve->setSamples(xaxis, smoothA, points); standard->slopeCurve->setSamples(xaxis, smoothSL, points); standard->tempCurve->setSamples(xaxis, smoothTE, points); QVector<QwtIntervalSample> tmpWND(points); memcpy(tmpWND.data(), smoothRS, (points) * sizeof(QwtIntervalSample)); standard->windCurve->setSamples(new QwtIntervalSeriesData(tmpWND)); standard->torqueCurve->setSamples(xaxis, smoothNM, points); standard->balanceLCurve->setSamples(xaxis, smoothBALL, points); standard->balanceRCurve->setSamples(xaxis, smoothBALR, points); standard->lteCurve->setSamples(xaxis, smoothLTE, points); standard->rteCurve->setSamples(xaxis, smoothRTE, points); standard->lpsCurve->setSamples(xaxis, smoothLPS, points); standard->rpsCurve->setSamples(xaxis, smoothRPS, points); standard->lpcoCurve->setSamples(xaxis, smoothLPCO, points); standard->rpcoCurve->setSamples(xaxis, smoothRPCO, points); QVector<QwtIntervalSample> tmpLDC(points); memcpy(tmpLDC.data(), smoothLPP, (points) * sizeof(QwtIntervalSample)); standard->lppCurve->setSamples(new QwtIntervalSeriesData(tmpLDC)); QVector<QwtIntervalSample> tmpRDC(points); memcpy(tmpRDC.data(), smoothRPP, (points) * sizeof(QwtIntervalSample)); standard->rppCurve->setSamples(new QwtIntervalSeriesData(tmpRDC)); QVector<QwtIntervalSample> tmpLPPP(points); memcpy(tmpLPPP.data(), smoothLPPP, (points) * sizeof(QwtIntervalSample)); standard->lpppCurve->setSamples(new QwtIntervalSeriesData(tmpLPPP)); QVector<QwtIntervalSample> tmpRPPP(points); memcpy(tmpRPPP.data(), smoothRPPP, (points) * sizeof(QwtIntervalSample)); standard->rpppCurve->setSamples(new QwtIntervalSeriesData(tmpRPPP)); /*QVector<double> _time(stopidx-startidx); qMemCopy( _time.data(), xaxis, (stopidx-startidx) * sizeof( double ) ); QVector<QwtIntervalSample> tmpWND(stopidx-startidx); for (int i=0;i<_time.count();i++) { QwtIntervalSample inter = QwtIntervalSample(_time.at(i), 20,50); tmpWND.append(inter); // plot->standard->smoothRelSpeed.at(i) }*/ setSymbol(standard->wCurve, points); setSymbol(standard->wattsCurve, points); setSymbol(standard->antissCurve, points); setSymbol(standard->atissCurve, points); setSymbol(standard->npCurve, points); setSymbol(standard->rvCurve, points); setSymbol(standard->rcadCurve, points); setSymbol(standard->rgctCurve, points); setSymbol(standard->gearCurve, points); setSymbol(standard->smo2Curve, points); setSymbol(standard->thbCurve, points); setSymbol(standard->o2hbCurve, points); setSymbol(standard->hhbCurve, points); setSymbol(standard->xpCurve, points); setSymbol(standard->apCurve, points); setSymbol(standard->hrCurve, points); setSymbol(standard->tcoreCurve, points); setSymbol(standard->speedCurve, points); setSymbol(standard->accelCurve, points); setSymbol(standard->wattsDCurve, points); setSymbol(standard->cadDCurve, points); setSymbol(standard->nmDCurve, points); setSymbol(standard->hrDCurve, points); setSymbol(standard->cadCurve, points); setSymbol(standard->altCurve, points); setSymbol(standard->altSlopeCurve, points); setSymbol(standard->slopeCurve, points); setSymbol(standard->tempCurve, points); setSymbol(standard->torqueCurve, points); setSymbol(standard->balanceLCurve, points); setSymbol(standard->balanceRCurve, points); setSymbol(standard->lteCurve, points); setSymbol(standard->rteCurve, points); setSymbol(standard->lpsCurve, points); setSymbol(standard->rpsCurve, points); setSymbol(standard->lpcoCurve, points); setSymbol(standard->rpcoCurve, points); if (!plot->standard->smoothAltitude.empty()) { standard->altCurve->attach(this); standard->altSlopeCurve->attach(this); } if (!plot->standard->smoothSlope.empty()) { standard->slopeCurve->attach(this); } if (showW && plot->standard->wprime.count()) { standard->wCurve->attach(this); standard->mCurve->attach(this); } if (!plot->standard->smoothWatts.empty()) { standard->wattsCurve->attach(this); } if (!plot->standard->smoothANT.empty()) { standard->antissCurve->attach(this); } if (!plot->standard->smoothAT.empty()) { standard->atissCurve->attach(this); } if (!plot->standard->smoothNP.empty()) { standard->npCurve->attach(this); } if (!plot->standard->smoothRV.empty()) { standard->rvCurve->attach(this); } if (!plot->standard->smoothRCad.empty()) { standard->rcadCurve->attach(this); } if (!plot->standard->smoothRGCT.empty()) { standard->rgctCurve->attach(this); } if (!plot->standard->smoothGear.empty()) { standard->gearCurve->attach(this); } if (!plot->standard->smoothSmO2.empty()) { standard->smo2Curve->attach(this); } if (!plot->standard->smoothtHb.empty()) { standard->thbCurve->attach(this); } if (!plot->standard->smoothO2Hb.empty()) { standard->o2hbCurve->attach(this); } if (!plot->standard->smoothHHb.empty()) { standard->hhbCurve->attach(this); } if (!plot->standard->smoothXP.empty()) { standard->xpCurve->attach(this); } if (!plot->standard->smoothAP.empty()) { standard->apCurve->attach(this); } if (!plot->standard->smoothTcore.empty()) { standard->tcoreCurve->attach(this); } if (!plot->standard->smoothHr.empty()) { standard->hrCurve->attach(this); } if (!plot->standard->smoothAccel.empty()) { standard->accelCurve->attach(this); } if (!plot->standard->smoothWattsD.empty()) { standard->wattsDCurve->attach(this); } if (!plot->standard->smoothCadD.empty()) { standard->cadDCurve->attach(this); } if (!plot->standard->smoothNmD.empty()) { standard->nmDCurve->attach(this); } if (!plot->standard->smoothHrD.empty()) { standard->hrDCurve->attach(this); } if (!plot->standard->smoothSpeed.empty()) { standard->speedCurve->attach(this); } if (!plot->standard->smoothCad.empty()) { standard->cadCurve->attach(this); } if (!plot->standard->smoothTemp.empty()) { standard->tempCurve->attach(this); } if (!plot->standard->smoothWind.empty()) { standard->windCurve->attach(this); } if (!plot->standard->smoothTorque.empty()) { standard->torqueCurve->attach(this); } if (!plot->standard->smoothBalanceL.empty()) { standard->balanceLCurve->attach(this); standard->balanceRCurve->attach(this); } if (!plot->standard->smoothLTE.empty()) { standard->lteCurve->attach(this); standard->rteCurve->attach(this); } if (!plot->standard->smoothLPS.empty()) { standard->lpsCurve->attach(this); standard->rpsCurve->attach(this); } if (!plot->standard->smoothLPCO.empty()) { standard->lpcoCurve->attach(this); standard->rpcoCurve->attach(this); } if (!plot->standard->smoothLPP.empty()) { standard->lppCurve->attach(this); standard->rppCurve->attach(this); } if (!plot->standard->smoothLPPP.empty()) { standard->lpppCurve->attach(this); standard->rpppCurve->attach(this); } setAltSlopePlotStyle(standard->altSlopeCurve); setYMax(); setAxisScale(xBottom, xaxis[0], xaxis[stopidx-startidx]); enableAxis(xBottom, true); setAxisVisible(xBottom, true); refreshReferenceLines(); refreshIntervalMarkers(); refreshCalibrationMarkers(); refreshZoneLabels(); // set all the colors ? configChanged(CONFIG_APPEARANCE); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setDataFromPlot(AllPlot *plot) { if (plot == NULL) { rideItem = NULL; return; } referencePlot = plot; isolation = false; curveColors->saveState(); // reference the plot for data and state rideItem = plot->rideItem; bydist = plot->bydist; // remove all curves from the plot standard->wCurve->detach(); standard->mCurve->detach(); standard->wattsCurve->detach(); standard->atissCurve->detach(); standard->antissCurve->detach(); standard->npCurve->detach(); standard->rvCurve->detach(); standard->rcadCurve->detach(); standard->rgctCurve->detach(); standard->gearCurve->detach(); standard->smo2Curve->detach(); standard->thbCurve->detach(); standard->o2hbCurve->detach(); standard->hhbCurve->detach(); standard->xpCurve->detach(); standard->apCurve->detach(); standard->hrCurve->detach(); standard->tcoreCurve->detach(); standard->speedCurve->detach(); standard->accelCurve->detach(); standard->wattsDCurve->detach(); standard->cadDCurve->detach(); standard->nmDCurve->detach(); standard->hrDCurve->detach(); standard->cadCurve->detach(); standard->altCurve->detach(); standard->altSlopeCurve->detach(); standard->slopeCurve->detach(); standard->tempCurve->detach(); standard->windCurve->detach(); standard->torqueCurve->detach(); standard->balanceLCurve->detach(); standard->balanceRCurve->detach(); standard->lteCurve->detach(); standard->rteCurve->detach(); standard->lpsCurve->detach(); standard->rpsCurve->detach(); standard->lpcoCurve->detach(); standard->rpcoCurve->detach(); standard->lppCurve->detach(); standard->rppCurve->detach(); standard->lpppCurve->detach(); standard->rpppCurve->detach(); standard->wCurve->setVisible(false); standard->mCurve->setVisible(false); standard->wattsCurve->setVisible(false); standard->atissCurve->setVisible(false); standard->antissCurve->setVisible(false); standard->npCurve->setVisible(false); standard->rvCurve->setVisible(false); standard->rcadCurve->setVisible(false); standard->rgctCurve->setVisible(false); standard->gearCurve->setVisible(false); standard->smo2Curve->setVisible(false); standard->thbCurve->setVisible(false); standard->o2hbCurve->setVisible(false); standard->hhbCurve->setVisible(false); standard->xpCurve->setVisible(false); standard->apCurve->setVisible(false); standard->hrCurve->setVisible(false); standard->tcoreCurve->setVisible(false); standard->speedCurve->setVisible(false); standard->accelCurve->setVisible(false); standard->wattsDCurve->setVisible(false); standard->cadDCurve->setVisible(false); standard->nmDCurve->setVisible(false); standard->hrDCurve->setVisible(false); standard->cadCurve->setVisible(false); standard->altCurve->setVisible(false); standard->altSlopeCurve->setVisible(false); standard->slopeCurve->setVisible(false); standard->tempCurve->setVisible(false); standard->windCurve->setVisible(false); standard->torqueCurve->setVisible(false); standard->balanceLCurve->setVisible(false); standard->balanceRCurve->setVisible(false); standard->lteCurve->setVisible(false); standard->rteCurve->setVisible(false); standard->lpsCurve->setVisible(false); standard->rpsCurve->setVisible(false); standard->lpcoCurve->setVisible(false); standard->rpcoCurve->setVisible(false); standard->lppCurve->setVisible(false); standard->rppCurve->setVisible(false); standard->lpppCurve->setVisible(false); standard->rpppCurve->setVisible(false); QwtPlotCurve *ourCurve = NULL, *thereCurve = NULL; QwtPlotCurve *ourCurve2 = NULL, *thereCurve2 = NULL; AllPlotSlopeCurve *ourASCurve = NULL, *thereASCurve = NULL; QwtPlotIntervalCurve *ourICurve = NULL, *thereICurve = NULL; QString title; // which curve are we interested in ? switch (scope) { case RideFile::cad: { ourCurve = standard->cadCurve; thereCurve = referencePlot->standard->cadCurve; title = tr("Cadence"); } break; case RideFile::tcore: { ourCurve = standard->tcoreCurve; thereCurve = referencePlot->standard->tcoreCurve; title = tr("Core Temp"); } break; case RideFile::hr: { ourCurve = standard->hrCurve; thereCurve = referencePlot->standard->hrCurve; title = tr("Heartrate"); } break; case RideFile::kphd: { ourCurve = standard->accelCurve; thereCurve = referencePlot->standard->accelCurve; title = tr("Acceleration"); } break; case RideFile::wattsd: { ourCurve = standard->wattsDCurve; thereCurve = referencePlot->standard->wattsDCurve; title = tr("Power Delta"); } break; case RideFile::cadd: { ourCurve = standard->cadDCurve; thereCurve = referencePlot->standard->cadDCurve; title = tr("Cadence Delta"); } break; case RideFile::nmd: { ourCurve = standard->nmDCurve; thereCurve = referencePlot->standard->nmDCurve; title = tr("Torque Delta"); } break; case RideFile::hrd: { ourCurve = standard->hrDCurve; thereCurve = referencePlot->standard->hrDCurve; title = tr("Heartrate Delta"); } break; case RideFile::kph: { ourCurve = standard->speedCurve; thereCurve = referencePlot->standard->speedCurve; if (secondaryScope == RideFile::headwind) { ourICurve = standard->windCurve; thereICurve = referencePlot->standard->windCurve; } title = tr("Speed"); } break; case RideFile::nm: { ourCurve = standard->torqueCurve; thereCurve = referencePlot->standard->torqueCurve; title = tr("Torque"); } break; case RideFile::watts: { ourCurve = standard->wattsCurve; thereCurve = referencePlot->standard->wattsCurve; title = tr("Power"); } break; case RideFile::wprime: { ourCurve = standard->wCurve; ourCurve2 = standard->mCurve; thereCurve = referencePlot->standard->wCurve; thereCurve2 = referencePlot->standard->mCurve; title = tr("W'bal"); } break; case RideFile::alt: { if (secondaryScope == RideFile::none) { ourCurve = standard->altCurve; thereCurve = referencePlot->standard->altCurve; title = tr("Altitude"); } else { ourASCurve = standard->altSlopeCurve; thereASCurve = referencePlot->standard->altSlopeCurve; title = tr("Alt/Slope"); } } break; case RideFile::slope: { ourCurve = standard->slopeCurve; thereCurve = referencePlot->standard->slopeCurve; title = tr("Slope"); } break; case RideFile::headwind: { ourICurve = standard->windCurve; thereICurve = referencePlot->standard->windCurve; title = tr("Headwind"); } break; case RideFile::temp: { ourCurve = standard->tempCurve; thereCurve = referencePlot->standard->tempCurve; title = tr("Temperature"); } break; case RideFile::anTISS: { ourCurve = standard->antissCurve; thereCurve = referencePlot->standard->antissCurve; title = tr("Anaerobic TISS"); } break; case RideFile::aTISS: { ourCurve = standard->atissCurve; thereCurve = referencePlot->standard->atissCurve; title = tr("Aerobic TISS"); } break; case RideFile::NP: { ourCurve = standard->npCurve; thereCurve = referencePlot->standard->npCurve; title = tr("NP"); } break; case RideFile::rvert: { ourCurve = standard->rvCurve; thereCurve = referencePlot->standard->rvCurve; title = tr("Vertical Oscillation"); } break; case RideFile::rcad: { ourCurve = standard->rcadCurve; thereCurve = referencePlot->standard->rcadCurve; title = tr("Run Cadence"); } break; case RideFile::rcontact: { ourCurve = standard->rgctCurve; thereCurve = referencePlot->standard->rgctCurve; title = tr("GCT"); } break; case RideFile::gear: { ourCurve = standard->gearCurve; thereCurve = referencePlot->standard->gearCurve; title = tr("Gear Ratio"); } break; case RideFile::smo2: { ourCurve = standard->smo2Curve; thereCurve = referencePlot->standard->smo2Curve; title = tr("SmO2"); } break; case RideFile::thb: { ourCurve = standard->thbCurve; thereCurve = referencePlot->standard->thbCurve; title = tr("tHb"); } break; case RideFile::o2hb: { ourCurve = standard->o2hbCurve; thereCurve = referencePlot->standard->o2hbCurve; title = tr("O2Hb"); } break; case RideFile::hhb: { ourCurve = standard->hhbCurve; thereCurve = referencePlot->standard->hhbCurve; title = tr("HHb"); } break; case RideFile::xPower: { ourCurve = standard->xpCurve; thereCurve = referencePlot->standard->xpCurve; title = tr("xPower"); } break; case RideFile::lps: { ourCurve = standard->lpsCurve; thereCurve = referencePlot->standard->lpsCurve; title = tr("Left Pedal Smoothness"); } break; case RideFile::rps: { ourCurve = standard->rpsCurve; thereCurve = referencePlot->standard->rpsCurve; title = tr("Right Pedal Smoothness"); } break; case RideFile::lte: { ourCurve = standard->lteCurve; thereCurve = referencePlot->standard->lteCurve; title = tr("Left Torque Efficiency"); } break; case RideFile::rte: { ourCurve = standard->rteCurve; thereCurve = referencePlot->standard->rteCurve; title = tr("Right Torque Efficiency"); } break; case RideFile::lpco: case RideFile::rpco: { ourCurve = standard->lpcoCurve; ourCurve2 = standard->rpcoCurve; thereCurve = referencePlot->standard->lpcoCurve; thereCurve2 = referencePlot->standard->rpcoCurve; title = tr("Left/Right Pedal Center Offset"); } break; case RideFile::lppb: { ourICurve = standard->lppCurve; thereICurve = referencePlot->standard->lppCurve; title = tr("Left Power Phase"); } break; case RideFile::rppb: { ourICurve = standard->rppCurve; thereICurve = referencePlot->standard->rppCurve; title = tr("Right Power Phase"); } break; case RideFile::lpppb: { ourICurve = standard->lpppCurve; thereICurve = referencePlot->standard->lpppCurve; title = tr("Left Peak Power Phase"); } break; case RideFile::rpppb: { ourICurve = standard->rpppCurve; thereICurve = referencePlot->standard->rpppCurve; title = tr("Right Peak Power Phase"); } break; case RideFile::lrbalance: { ourCurve = standard->balanceLCurve; ourCurve2 = standard->balanceRCurve; thereCurve = referencePlot->standard->balanceLCurve; thereCurve2 = referencePlot->standard->balanceRCurve; title = tr("L/R Balance"); } break; case RideFile::aPower: { ourCurve = standard->apCurve; thereCurve = referencePlot->standard->apCurve; title = tr("aPower"); } break; default: case RideFile::interval: case RideFile::vam: case RideFile::wattsKg: case RideFile::km: case RideFile::lon: case RideFile::lat: case RideFile::none: break; } // lets clone ! if ((ourCurve && thereCurve) || (ourICurve && thereICurve) || (ourASCurve && thereASCurve)) { if (ourCurve && thereCurve) { // no way to get values, so we run through them ourCurve->setVisible(true); ourCurve->attach(this); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereCurve->data()->size(); i++) array << thereCurve->data()->sample(i); ourCurve->setSamples(array); ourCurve->setYAxis(yLeft); ourCurve->setBaseline(thereCurve->baseline()); ourCurve->setStyle(thereCurve->style()); // symbol when zoomed in super close if (array.size() < 150) { QwtSymbol *sym = new QwtSymbol; sym->setPen(QPen(GColor(CPLOTMARKER))); sym->setStyle(QwtSymbol::Ellipse); sym->setSize(3); ourCurve->setSymbol(sym); } else { QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourCurve->setSymbol(sym); } } if (ourCurve2 && thereCurve2) { ourCurve2->setVisible(true); ourCurve2->attach(this); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereCurve2->data()->size(); i++) array << thereCurve2->data()->sample(i); ourCurve2->setSamples(array); ourCurve2->setYAxis(yLeft); ourCurve2->setBaseline(thereCurve2->baseline()); // symbol when zoomed in super close if (array.size() < 150) { QwtSymbol *sym = new QwtSymbol; sym->setPen(QPen(GColor(CPLOTMARKER))); sym->setStyle(QwtSymbol::Ellipse); sym->setSize(3); ourCurve2->setSymbol(sym); } else { QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourCurve2->setSymbol(sym); } } if (ourICurve && thereICurve) { ourICurve->setVisible(true); ourICurve->attach(this); // lets clone the data QVector<QwtIntervalSample> array; for (size_t i=0; i<thereICurve->data()->size(); i++) array << thereICurve->data()->sample(i); ourICurve->setSamples(array); ourICurve->setYAxis(yLeft); } if (ourASCurve && thereASCurve) { // no way to get values, so we run through them ourASCurve->setVisible(true); ourASCurve->attach(this); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereASCurve->data()->size(); i++) array << thereASCurve->data()->sample(i); ourASCurve->setSamples(array); ourASCurve->setYAxis(yLeft); ourASCurve->setBaseline(thereASCurve->baseline()); ourASCurve->setStyle(thereASCurve->style()); QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourASCurve->setSymbol(sym); } // x-axis if (thereCurve || thereASCurve) setAxisScale(QwtPlot::xBottom, referencePlot->axisScaleDiv(xBottom).lowerBound(), referencePlot->axisScaleDiv(xBottom).upperBound()); else if (thereICurve) setAxisScale(QwtPlot::xBottom, thereICurve->boundingRect().left(), thereICurve->boundingRect().right()); enableAxis(QwtPlot::xBottom, true); setAxisVisible(QwtPlot::xBottom, true); setXTitle(); // y-axis yLeft setAxisVisible(yLeft, true); if (scope == RideFile::thb && thereCurve) { // minimum non-zero value... worst case its zero ! double minNZ = 0.00f; for (size_t i=0; i<thereCurve->data()->size(); i++) { if (!minNZ) minNZ = thereCurve->data()->sample(i).y(); else if (thereCurve->data()->sample(i).y()<minNZ) minNZ = thereCurve->data()->sample(i).y(); } setAxisScale(QwtPlot::yLeft, minNZ, thereCurve->maxYValue() + 0.10f); } else if (scope == RideFile::wprime) { // always zero or lower (don't truncate) double min = thereCurve->minYValue(); setAxisScale(QwtPlot::yLeft, min > 0 ? 0 : min * 1.1f, 1.1f * thereCurve->maxYValue()); } else if (scope == RideFile::tcore) { // always zero or lower (don't truncate) double min = qMin(36.5f, float(thereCurve->minYValue())); double max = qMax(39.0f, float(thereCurve->maxYValue()+0.5f)); setAxisScale(QwtPlot::yLeft, min, max); } else if (scope != RideFile::lrbalance) { if (thereCurve) setAxisScale(QwtPlot::yLeft, thereCurve->minYValue(), 1.1f * thereCurve->maxYValue()); if (thereICurve) setAxisScale(QwtPlot::yLeft, thereICurve->boundingRect().top(), 1.1f * thereICurve->boundingRect().bottom()); if (thereASCurve) setAxisScale(QwtPlot::yLeft, thereASCurve->minYValue(), 1.1f * thereASCurve->maxYValue()); } else { setAxisScale(QwtPlot::yLeft, 0, 100); // 100 % } ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); sd->setMinimumExtent(24); sd->setSpacing(0); if (scope == RideFile::wprime) sd->setFactor(0.001f); // Kj if (scope == RideFile::thb || scope == RideFile::smo2 || scope == RideFile::o2hb || scope == RideFile::hhb) // Hb sd->setDecimals(2); if (scope == RideFile::tcore) sd->setDecimals(1); setAxisScaleDraw(QwtPlot::yLeft, sd); // title and colour setAxisTitle(yLeft, title); QPalette pal = palette(); if (thereCurve) { pal.setColor(QPalette::WindowText, thereCurve->pen().color()); pal.setColor(QPalette::Text, thereCurve->pen().color()); } else if (thereICurve) { pal.setColor(QPalette::WindowText, thereICurve->pen().color()); pal.setColor(QPalette::Text, thereICurve->pen().color()); } else if (thereASCurve) { pal.setColor(QPalette::WindowText, thereASCurve->pen().color()); pal.setColor(QPalette::Text, thereASCurve->pen().color()); } axisWidget(QwtPlot::yLeft)->setPalette(pal); // hide other y axes setAxisVisible(QwtAxisId(QwtAxis::yLeft, 1), false); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 3), false); setAxisVisible(yRight, false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 1), false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 2), false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 3), false); // plot standard->grid standard->grid->setVisible(referencePlot->standard->grid->isVisible()); // plot markers etc refreshIntervalMarkers(); refreshCalibrationMarkers(); refreshReferenceLines(); #if 0 refreshZoneLabels(); #endif } // remember the curves and colors isolation = false; curveColors->saveState(); } void AllPlot::setDataFromPlots(QList<AllPlot *> plots) { isolation = false; curveColors->saveState(); // remove all curves from the plot standard->wCurve->detach(); standard->mCurve->detach(); standard->wattsCurve->detach(); standard->atissCurve->detach(); standard->antissCurve->detach(); standard->npCurve->detach(); standard->rvCurve->detach(); standard->rcadCurve->detach(); standard->rgctCurve->detach(); standard->gearCurve->detach(); standard->smo2Curve->detach(); standard->thbCurve->detach(); standard->o2hbCurve->detach(); standard->hhbCurve->detach(); standard->xpCurve->detach(); standard->apCurve->detach(); standard->hrCurve->detach(); standard->tcoreCurve->detach(); standard->speedCurve->detach(); standard->accelCurve->detach(); standard->wattsDCurve->detach(); standard->cadDCurve->detach(); standard->nmDCurve->detach(); standard->hrDCurve->detach(); standard->cadCurve->detach(); standard->altCurve->detach(); standard->altSlopeCurve->detach(); standard->slopeCurve->detach(); standard->tempCurve->detach(); standard->windCurve->detach(); standard->torqueCurve->detach(); standard->balanceLCurve->detach(); standard->balanceRCurve->detach(); standard->lteCurve->detach(); standard->rteCurve->detach(); standard->lpsCurve->detach(); standard->rpsCurve->detach(); standard->lpcoCurve->detach(); standard->rpcoCurve->detach(); standard->lppCurve->detach(); standard->rppCurve->detach(); standard->lpppCurve->detach(); standard->rpppCurve->detach(); standard->wCurve->setVisible(false); standard->mCurve->setVisible(false); standard->wattsCurve->setVisible(false); standard->atissCurve->setVisible(false); standard->antissCurve->setVisible(false); standard->npCurve->setVisible(false); standard->rvCurve->setVisible(false); standard->rcadCurve->setVisible(false); standard->rgctCurve->setVisible(false); standard->gearCurve->setVisible(false); standard->smo2Curve->setVisible(false); standard->thbCurve->setVisible(false); standard->o2hbCurve->setVisible(false); standard->hhbCurve->setVisible(false); standard->xpCurve->setVisible(false); standard->apCurve->setVisible(false); standard->hrCurve->setVisible(false); standard->tcoreCurve->setVisible(false); standard->speedCurve->setVisible(false); standard->accelCurve->setVisible(false); standard->wattsDCurve->setVisible(false); standard->cadDCurve->setVisible(false); standard->nmDCurve->setVisible(false); standard->hrDCurve->setVisible(false); standard->cadCurve->setVisible(false); standard->altCurve->setVisible(false); standard->altSlopeCurve->setVisible(false); standard->slopeCurve->setVisible(false); standard->tempCurve->setVisible(false); standard->windCurve->setVisible(false); standard->torqueCurve->setVisible(false); standard->balanceLCurve->setVisible(false); standard->balanceRCurve->setVisible(false); standard->lteCurve->setVisible(false); standard->rteCurve->setVisible(false); standard->lpsCurve->setVisible(false); standard->rpsCurve->setVisible(false); standard->lpcoCurve->setVisible(false); standard->rpcoCurve->setVisible(false); standard->lppCurve->setVisible(false); standard->rppCurve->setVisible(false); standard->lpppCurve->setVisible(false); standard->rpppCurve->setVisible(false); // clear previous curves foreach(QwtPlotCurve *prior, compares) { prior->detach(); delete prior; } compares.clear(); double MAXY = -100; double MINY = 0; // add all the curves int index=0; foreach (AllPlot *plot, plots) { if (context->compareIntervals[index].isChecked() == false) { index++; continue; // ignore if not shown } referencePlot = plot; QwtPlotCurve *ourCurve = NULL, *thereCurve = NULL; QwtPlotCurve *ourCurve2 = NULL, *thereCurve2 = NULL; AllPlotSlopeCurve *ourASCurve = NULL, *thereASCurve = NULL; QwtPlotIntervalCurve *ourICurve = NULL, *thereICurve = NULL; QString title; // which curve are we interested in ? switch (scope) { case RideFile::cad: { ourCurve = new QwtPlotCurve(tr("Cadence")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->cadCurve; title = tr("Cadence"); } break; case RideFile::tcore: { ourCurve = new QwtPlotCurve(tr("Core Temp")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->tcoreCurve; title = tr("Core Temp"); } break; case RideFile::hr: { ourCurve = new QwtPlotCurve(tr("Heart Rate")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->hrCurve; title = tr("Heartrate"); } break; case RideFile::kphd: { ourCurve = new QwtPlotCurve(tr("Acceleration")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->accelCurve; title = tr("Acceleration"); } break; case RideFile::wattsd: { ourCurve = new QwtPlotCurve(tr("Power Delta")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->wattsDCurve; title = tr("Power Delta"); } break; case RideFile::cadd: { ourCurve = new QwtPlotCurve(tr("Cadence Delta")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->cadDCurve; title = tr("Cadence Delta"); } break; case RideFile::nmd: { ourCurve = new QwtPlotCurve(tr("Torque Delta")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->nmDCurve; title = tr("Torque Delta"); } break; case RideFile::hrd: { ourCurve = new QwtPlotCurve(tr("Heartrate Delta")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->hrDCurve; title = tr("Heartrate Delta"); } break; case RideFile::kph: { ourCurve = new QwtPlotCurve(tr("Speed")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->speedCurve; if (secondaryScope == RideFile::headwind) { ourICurve = standard->windCurve; thereICurve = referencePlot->standard->windCurve; } title = tr("Speed"); } break; case RideFile::nm: { ourCurve = new QwtPlotCurve(tr("Torque")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->torqueCurve; title = tr("Torque"); } break; case RideFile::watts: { ourCurve = new QwtPlotCurve(tr("Power")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->wattsCurve; title = tr("Power"); } break; case RideFile::wprime: { ourCurve = new QwtPlotCurve(tr("W' Balance (kJ)")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); ourCurve2 = new QwtPlotCurve(tr("Matches")); ourCurve2->setPaintAttribute(QwtPlotCurve::FilterPoints, true); ourCurve2->setStyle(QwtPlotCurve::Dots); ourCurve2->setYAxis(QwtAxisId(QwtAxis::yRight, 2)); thereCurve = referencePlot->standard->wCurve; thereCurve2 = referencePlot->standard->mCurve; title = tr("W'bal"); } break; case RideFile::alt: { if (secondaryScope != RideFile::slope) { ourCurve = new QwtPlotCurve(tr("Altitude")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); ourCurve->setZ(-10); // always at the back. thereCurve = referencePlot->standard->altCurve; title = tr("Altitude"); } else { ourASCurve = new AllPlotSlopeCurve(tr("Alt/Slope")); ourASCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); ourASCurve->setZ(-5); // thereASCurve = referencePlot->standard->altSlopeCurve; title = tr("Alt/Slope"); } } break; case RideFile::slope: { ourCurve = new QwtPlotCurve(tr("Slope")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->slopeCurve; title = tr("Slope"); } break; case RideFile::headwind: { ourICurve = new QwtPlotIntervalCurve(tr("Headwind")); thereICurve = referencePlot->standard->windCurve; title = tr("Headwind"); } break; case RideFile::temp: { ourCurve = new QwtPlotCurve(tr("Temperature")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->tempCurve; title = tr("Temperature"); } break; case RideFile::anTISS: { ourCurve = new QwtPlotCurve(tr("Anaerobic TISS")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->antissCurve; title = tr("Anaerobic TISS"); } break; case RideFile::aTISS: { ourCurve = new QwtPlotCurve(tr("Aerobic TISS")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->atissCurve; title = tr("Aerobic TISS"); } break; case RideFile::NP: { ourCurve = new QwtPlotCurve(tr("NP")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->npCurve; title = tr("NP"); } break; case RideFile::rvert: { ourCurve = new QwtPlotCurve(tr("Vertical Oscillation")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->rvCurve; title = tr("Vertical Oscillation"); } break; case RideFile::rcad: { ourCurve = new QwtPlotCurve(tr("Run Cadence")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->rcadCurve; title = tr("Run Cadence"); } break; case RideFile::rcontact: { ourCurve = new QwtPlotCurve(tr("GCT")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->rgctCurve; title = tr("GCT"); } break; case RideFile::gear: { ourCurve = new QwtPlotCurve(tr("Gear Ratio")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->gearCurve; title = tr("Gear Ratio"); } break; case RideFile::smo2: { ourCurve = new QwtPlotCurve(tr("SmO2")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->smo2Curve; title = tr("SmO2"); } break; case RideFile::thb: { ourCurve = new QwtPlotCurve(tr("tHb")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->thbCurve; title = tr("tHb"); } break; case RideFile::o2hb: { ourCurve = new QwtPlotCurve(tr("O2Hb")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->o2hbCurve; title = tr("O2Hb"); } break; case RideFile::hhb: { ourCurve = new QwtPlotCurve(tr("HHb")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->hhbCurve; title = tr("HHb"); } break; case RideFile::xPower: { ourCurve = new QwtPlotCurve(tr("xPower")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->xpCurve; title = tr("xPower"); } break; case RideFile::lps: { ourCurve = new QwtPlotCurve(tr("Left Pedal Smoothness")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->lpsCurve; title = tr("Left Pedal Smoothness"); } break; case RideFile::rps: { ourCurve = new QwtPlotCurve(tr("Right Pedal Smoothness")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->rpsCurve; title = tr("Right Pedal Smoothness"); } break; case RideFile::lte: { ourCurve = new QwtPlotCurve(tr("Left Torque Efficiency")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->lteCurve; title = tr("Left Torque Efficiency"); } break; case RideFile::rte: { ourCurve = new QwtPlotCurve(tr("Right Torque Efficiency")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->rteCurve; title = tr("Right Torque Efficiency"); } break; case RideFile::rpco: case RideFile::lpco: { ourCurve = new QwtPlotCurve(tr("Left Pedal Center Offset")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->lpcoCurve; ourCurve2 = new QwtPlotCurve(tr("Right Pedal Center Offset")); ourCurve2->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve2 = referencePlot->standard->rpcoCurve; title = tr("Left/Right Pedal Center Offset"); } break; case RideFile::lppb: case RideFile::lppe: { ourICurve = new QwtPlotIntervalCurve(tr("Left Power Phase")); thereICurve = referencePlot->standard->lppCurve; title = tr("Left Power Phase"); } break; case RideFile::rppb: case RideFile::rppe: { ourICurve = new QwtPlotIntervalCurve(tr("Right Power Phase")); thereICurve = referencePlot->standard->rppCurve; title = tr("Right Power Phase"); } break; case RideFile::lpppb: case RideFile::lpppe: { ourICurve = new QwtPlotIntervalCurve(tr("Left Peak Power Phase")); thereICurve = referencePlot->standard->lpppCurve; title = tr("Left Peak Power Phase"); } break; case RideFile::rpppb: case RideFile::rpppe: { ourICurve = new QwtPlotIntervalCurve(tr("Right Peak Power Phase")); thereICurve = referencePlot->standard->rpppCurve; title = tr("Right Peak Power Phase"); } break; case RideFile::lrbalance: { ourCurve = new QwtPlotCurve(tr("Left Balance")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); ourCurve2 = new QwtPlotCurve(tr("Right Balance")); ourCurve2->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->balanceLCurve; thereCurve2 = referencePlot->standard->balanceRCurve; title = tr("L/R Balance"); } break; case RideFile::aPower: { ourCurve = new QwtPlotCurve(tr("aPower")); ourCurve->setPaintAttribute(QwtPlotCurve::FilterPoints, true); thereCurve = referencePlot->standard->apCurve; title = tr("aPower"); } break; default: case RideFile::interval: case RideFile::vam: case RideFile::wattsKg: case RideFile::km: case RideFile::lon: case RideFile::lat: case RideFile::none: break; } bool antialias = appsettings->value(this, GC_ANTIALIAS, true).toBool(); // lets clone ! if ((ourCurve && thereCurve) || (ourICurve && thereICurve) || (ourASCurve && thereASCurve)) { if (ourCurve && thereCurve) { // remember for next time... compares << ourCurve; // colours etc if (antialias) ourCurve->setRenderHint(QwtPlotItem::RenderAntialiased); QPen pen = thereCurve->pen(); pen.setColor(context->compareIntervals[index].color); ourCurve->setPen(pen); ourCurve->setVisible(true); ourCurve->attach(this); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereCurve->data()->size(); i++) array << thereCurve->data()->sample(i); ourCurve->setSamples(array); ourCurve->setYAxis(yLeft); ourCurve->setBaseline(thereCurve->baseline()); if (ourCurve->maxYValue() > MAXY) MAXY = ourCurve->maxYValue(); if (ourCurve->minYValue() < MINY) MINY = ourCurve->minYValue(); // symbol when zoomed in super close if (array.size() < 150) { QwtSymbol *sym = new QwtSymbol; sym->setPen(QPen(GColor(CPLOTMARKER))); sym->setStyle(QwtSymbol::Ellipse); sym->setSize(3); ourCurve->setSymbol(sym); } else { QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourCurve->setSymbol(sym); } } if (ourCurve2 && thereCurve2) { // remember for next time... compares << ourCurve2; ourCurve2->setVisible(true); ourCurve2->attach(this); if (antialias) ourCurve2->setRenderHint(QwtPlotItem::RenderAntialiased); QPen pen = thereCurve2->pen(); pen.setColor(context->compareIntervals[index].color); ourCurve2->setPen(pen); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereCurve2->data()->size(); i++) array << thereCurve2->data()->sample(i); ourCurve2->setSamples(array); ourCurve2->setYAxis(yLeft); ourCurve2->setBaseline(thereCurve2->baseline()); if (ourCurve2->maxYValue() > MAXY) MAXY = ourCurve2->maxYValue(); if (ourCurve2->minYValue() < MINY) MINY = ourCurve2->minYValue(); // symbol when zoomed in super close if (array.size() < 150) { QwtSymbol *sym = new QwtSymbol; sym->setPen(QPen(GColor(CPLOTMARKER))); sym->setStyle(QwtSymbol::Ellipse); sym->setSize(3); ourCurve2->setSymbol(sym); } else { QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourCurve2->setSymbol(sym); } } if (ourICurve && thereICurve) { ourICurve->setVisible(true); ourICurve->attach(this); QPen pen = thereICurve->pen(); pen.setColor(context->compareIntervals[index].color); ourICurve->setPen(pen); if (antialias) ourICurve->setRenderHint(QwtPlotItem::RenderAntialiased); // lets clone the data QVector<QwtIntervalSample> array; for (size_t i=0; i<thereICurve->data()->size(); i++) array << thereICurve->data()->sample(i); ourICurve->setSamples(array); ourICurve->setYAxis(yLeft); //XXXX ???? DUNNO ????? //XXXX FIX LATER XXXX if (ourICurve->maxYValue() > MAXY) MAXY = ourICurve->maxYValue(); } if (ourASCurve && thereASCurve) { // remember for next time... compares << ourASCurve; // colours etc if (antialias) ourASCurve->setRenderHint(QwtPlotItem::RenderAntialiased); QPen pen = thereASCurve->pen(); pen.setColor(context->compareIntervals[index].color); ourASCurve->setPen(pen); ourASCurve->setVisible(true); ourASCurve->attach(this); // lets clone the data QVector<QPointF> array; for (size_t i=0; i<thereASCurve->data()->size(); i++) array << thereASCurve->data()->sample(i); ourASCurve->setSamples(array); ourASCurve->setYAxis(yLeft); ourASCurve->setBaseline(thereASCurve->baseline()); setAltSlopePlotStyle (ourASCurve); if (ourASCurve->maxYValue() > MAXY) MAXY = ourASCurve->maxYValue(); if (ourASCurve->minYValue() < MINY) MINY = ourASCurve->minYValue(); QwtSymbol *sym = new QwtSymbol; sym->setStyle(QwtSymbol::NoSymbol); sym->setSize(0); ourASCurve->setSymbol(sym); } } // move on -- this is used to reference into the compareIntervals // array to get the colors predominantly! index++; } // x-axis enableAxis(QwtPlot::xBottom, true); setAxisVisible(QwtPlot::xBottom, true); setAxisVisible(yLeft, true); // prettify the chart at the end ScaleScaleDraw *sd = new ScaleScaleDraw; sd->setTickLength(QwtScaleDiv::MajorTick, 3); sd->enableComponent(ScaleScaleDraw::Ticks, false); sd->enableComponent(ScaleScaleDraw::Backbone, false); if (scope == RideFile::wprime) sd->setFactor(0.001f); // Kj setAxisScaleDraw(QwtPlot::yLeft, sd); // set the y-axis for largest value we saw +10% setAxisScale(QwtPlot::yLeft, MINY * 1.10f , MAXY * 1.10f); // hide other y axes setAxisVisible(QwtAxisId(QwtAxis::yLeft, 1), false); setAxisVisible(QwtAxisId(QwtAxis::yLeft, 3), false); setAxisVisible(yRight, false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 1), false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 2), false); setAxisVisible(QwtAxisId(QwtAxis::yRight, 3), false); // refresh zone background (if needed) if (shade_zones) { bg->attach(this); refreshZoneLabels(); } else bg->detach(); #if 0 // plot standard->grid standard->grid->setVisible(referencePlot->standard->grid->isVisible()); // plot markers etc refreshIntervalMarkers(); refreshCalibrationMarkers(); refreshReferenceLines(); // always draw against yLeft in series mode intervalHighlighterCurve->setYAxis(yLeft); if (thereCurve) intervalHighlighterCurve->setBaseline(thereCurve->minYValue()); else if (thereICurve) intervalHighlighterCurve->setBaseline(thereICurve->boundingRect().top()); #if 0 #endif #endif // remember the curves and colors isolation = false; curveColors->saveState(); } // used to setup array of allplots where there is one for // each interval in compare mode void AllPlot::setDataFromObject(AllPlotObject *object, AllPlot *reference) { referencePlot = reference; bydist = reference->bydist; // remove all curves from the plot standard->wCurve->detach(); standard->mCurve->detach(); standard->wattsCurve->detach(); standard->atissCurve->detach(); standard->antissCurve->detach(); standard->npCurve->detach(); standard->rvCurve->detach(); standard->rcadCurve->detach(); standard->rgctCurve->detach(); standard->gearCurve->detach(); standard->smo2Curve->detach(); standard->thbCurve->detach(); standard->o2hbCurve->detach(); standard->hhbCurve->detach(); standard->xpCurve->detach(); standard->apCurve->detach(); standard->hrCurve->detach(); standard->tcoreCurve->detach(); standard->speedCurve->detach(); standard->accelCurve->detach(); standard->wattsDCurve->detach(); standard->cadDCurve->detach(); standard->nmDCurve->detach(); standard->hrDCurve->detach(); standard->cadCurve->detach(); standard->altCurve->detach(); standard->altSlopeCurve->detach(); standard->slopeCurve->detach(); standard->tempCurve->detach(); standard->windCurve->detach(); standard->torqueCurve->detach(); standard->balanceLCurve->detach(); standard->balanceRCurve->detach(); standard->lteCurve->detach(); standard->rteCurve->detach(); standard->lpsCurve->detach(); standard->rpsCurve->detach(); standard->intervalHighlighterCurve->detach(); standard->intervalHoverCurve->detach(); standard->wCurve->setVisible(false); standard->mCurve->setVisible(false); standard->wattsCurve->setVisible(false); standard->atissCurve->setVisible(false); standard->antissCurve->setVisible(false); standard->npCurve->setVisible(false); standard->rvCurve->setVisible(false); standard->rcadCurve->setVisible(false); standard->rgctCurve->setVisible(false); standard->gearCurve->setVisible(false); standard->smo2Curve->setVisible(false); standard->thbCurve->setVisible(false); standard->o2hbCurve->setVisible(false); standard->hhbCurve->setVisible(false); standard->xpCurve->setVisible(false); standard->apCurve->setVisible(false); standard->hrCurve->setVisible(false); standard->tcoreCurve->setVisible(false); standard->speedCurve->setVisible(false); standard->accelCurve->setVisible(false); standard->wattsDCurve->setVisible(false); standard->cadDCurve->setVisible(false); standard->nmDCurve->setVisible(false); standard->hrDCurve->setVisible(false); standard->cadCurve->setVisible(false); standard->altCurve->setVisible(false); standard->altSlopeCurve->setVisible(false); standard->slopeCurve->setVisible(false); standard->tempCurve->setVisible(false); standard->windCurve->setVisible(false); standard->torqueCurve->setVisible(false); standard->balanceLCurve->setVisible(false); standard->balanceRCurve->setVisible(false); standard->lteCurve->setVisible(false); standard->rteCurve->setVisible(false); standard->lpsCurve->setVisible(false); standard->rpsCurve->setVisible(false); standard->intervalHighlighterCurve->setVisible(false); standard->intervalHoverCurve->setVisible(false); // NOW SET OUR CURVES USING THEIR DATA ... QVector<double> &xaxis = referencePlot->bydist ? object->smoothDistance : object->smoothTime; int totalPoints = xaxis.count(); //W' curve set to whatever data we have if (!object->wprime.empty()) { standard->wCurve->setSamples(bydist ? object->wprimeDist.data() : object->wprimeTime.data(), object->wprime.data(), object->wprime.count()); standard->mCurve->setSamples(bydist ? object->matchDist.data() : object->matchTime.data(), object->match.data(), object->match.count()); setMatchLabels(standard); } if (!object->wattsArray.empty()) { standard->wattsCurve->setSamples(xaxis.data(), object->smoothWatts.data(), totalPoints); standard->wattsCurve->attach(this); standard->wattsCurve->setVisible(true); } if (!object->antissArray.empty()) { standard->antissCurve->setSamples(xaxis.data(), object->smoothANT.data(), totalPoints); standard->antissCurve->attach(this); standard->antissCurve->setVisible(true); } if (!object->atissArray.empty()) { standard->atissCurve->setSamples(xaxis.data(), object->smoothAT.data(), totalPoints); standard->atissCurve->attach(this); standard->atissCurve->setVisible(true); } if (!object->npArray.empty()) { standard->npCurve->setSamples(xaxis.data(), object->smoothNP.data(), totalPoints); standard->npCurve->attach(this); standard->npCurve->setVisible(true); } if (!object->rvArray.empty()) { standard->rvCurve->setSamples(xaxis.data(), object->smoothRV.data(), totalPoints); standard->rvCurve->attach(this); standard->rvCurve->setVisible(true); } if (!object->rcadArray.empty()) { standard->rcadCurve->setSamples(xaxis.data(), object->smoothRCad.data(), totalPoints); standard->rcadCurve->attach(this); standard->rcadCurve->setVisible(true); } if (!object->rgctArray.empty()) { standard->rgctCurve->setSamples(xaxis.data(), object->smoothRGCT.data(), totalPoints); standard->rgctCurve->attach(this); standard->rgctCurve->setVisible(true); } if (!object->gearArray.empty()) { standard->gearCurve->setSamples(xaxis.data(), object->smoothGear.data(), totalPoints); standard->gearCurve->attach(this); standard->gearCurve->setVisible(true); } if (!object->smo2Array.empty()) { standard->smo2Curve->setSamples(xaxis.data(), object->smoothSmO2.data(), totalPoints); standard->smo2Curve->attach(this); standard->smo2Curve->setVisible(true); } if (!object->thbArray.empty()) { standard->thbCurve->setSamples(xaxis.data(), object->smoothtHb.data(), totalPoints); standard->thbCurve->attach(this); standard->thbCurve->setVisible(true); } if (!object->o2hbArray.empty()) { standard->o2hbCurve->setSamples(xaxis.data(), object->smoothO2Hb.data(), totalPoints); standard->o2hbCurve->attach(this); standard->o2hbCurve->setVisible(true); } if (!object->hhbArray.empty()) { standard->hhbCurve->setSamples(xaxis.data(), object->smoothHHb.data(), totalPoints); standard->hhbCurve->attach(this); standard->hhbCurve->setVisible(true); } if (!object->xpArray.empty()) { standard->xpCurve->setSamples(xaxis.data(), object->smoothXP.data(), totalPoints); standard->xpCurve->attach(this); standard->xpCurve->setVisible(true); } if (!object->apArray.empty()) { standard->apCurve->setSamples(xaxis.data(), object->smoothAP.data(), totalPoints); standard->apCurve->attach(this); standard->apCurve->setVisible(true); } if (!object->tcoreArray.empty()) { standard->tcoreCurve->setSamples(xaxis.data(), object->smoothTcore.data(), totalPoints); standard->tcoreCurve->attach(this); standard->tcoreCurve->setVisible(true); } if (!object->hrArray.empty()) { standard->hrCurve->setSamples(xaxis.data(), object->smoothHr.data(), totalPoints); standard->hrCurve->attach(this); standard->hrCurve->setVisible(true); } if (!object->speedArray.empty()) { standard->speedCurve->setSamples(xaxis.data(), object->smoothSpeed.data(), totalPoints); standard->speedCurve->attach(this); standard->speedCurve->setVisible(true); } if (!object->accelArray.empty()) { standard->accelCurve->setSamples(xaxis.data(), object->smoothAccel.data(), totalPoints); standard->accelCurve->attach(this); standard->accelCurve->setVisible(true); } if (!object->wattsDArray.empty()) { standard->wattsDCurve->setSamples(xaxis.data(), object->smoothWattsD.data(), totalPoints); standard->wattsDCurve->attach(this); standard->wattsDCurve->setVisible(true); } if (!object->cadDArray.empty()) { standard->cadDCurve->setSamples(xaxis.data(), object->smoothCadD.data(), totalPoints); standard->cadDCurve->attach(this); standard->cadDCurve->setVisible(true); } if (!object->nmDArray.empty()) { standard->nmDCurve->setSamples(xaxis.data(), object->smoothNmD.data(), totalPoints); standard->nmDCurve->attach(this); standard->nmDCurve->setVisible(true); } if (!object->hrDArray.empty()) { standard->hrDCurve->setSamples(xaxis.data(), object->smoothHrD.data(), totalPoints); standard->hrDCurve->attach(this); standard->hrDCurve->setVisible(true); } if (!object->cadArray.empty()) { standard->cadCurve->setSamples(xaxis.data(), object->smoothCad.data(), totalPoints); standard->cadCurve->attach(this); standard->cadCurve->setVisible(true); } if (!object->altArray.empty()) { standard->altCurve->setSamples(xaxis.data(), object->smoothAltitude.data(), totalPoints); standard->altCurve->attach(this); standard->altCurve->setVisible(true); standard->altSlopeCurve->setSamples(xaxis.data(), object->smoothAltitude.data(), totalPoints); standard->altSlopeCurve->attach(this); standard->altSlopeCurve->setVisible(true); } if (!object->slopeArray.empty()) { standard->slopeCurve->setSamples(xaxis.data(), object->smoothSlope.data(), totalPoints); standard->slopeCurve->attach(this); standard->slopeCurve->setVisible(true); } if (!object->tempArray.empty()) { standard->tempCurve->setSamples(xaxis.data(), object->smoothTemp.data(), totalPoints); standard->tempCurve->attach(this); standard->tempCurve->setVisible(true); } if (!object->windArray.empty()) { standard->windCurve->setSamples(new QwtIntervalSeriesData(object->smoothRelSpeed)); standard->windCurve->attach(this); standard->windCurve->setVisible(true); } if (!object->torqueArray.empty()) { standard->torqueCurve->setSamples(xaxis.data(), object->smoothTorque.data(), totalPoints); standard->torqueCurve->attach(this); standard->torqueCurve->setVisible(true); } if (!object->balanceArray.empty()) { standard->balanceLCurve->setSamples(xaxis.data(), object->smoothBalanceL.data(), totalPoints); standard->balanceRCurve->setSamples(xaxis.data(), object->smoothBalanceR.data(), totalPoints); standard->balanceLCurve->attach(this); standard->balanceLCurve->setVisible(true); standard->balanceRCurve->attach(this); standard->balanceRCurve->setVisible(true); } if (!object->lteArray.empty()) { standard->lteCurve->setSamples(xaxis.data(), object->smoothLTE.data(), totalPoints); standard->rteCurve->setSamples(xaxis.data(), object->smoothRTE.data(), totalPoints); standard->lteCurve->attach(this); standard->lteCurve->setVisible(true); standard->rteCurve->attach(this); standard->rteCurve->setVisible(true); } if (!object->lpsArray.empty()) { standard->lpsCurve->setSamples(xaxis.data(), object->smoothLPS.data(), totalPoints); standard->rpsCurve->setSamples(xaxis.data(), object->smoothRPS.data(), totalPoints); standard->lpsCurve->attach(this); standard->lpsCurve->setVisible(true); standard->rpsCurve->attach(this); standard->rpsCurve->setVisible(true); } if (!object->lpcoArray.empty()) { standard->lpcoCurve->setSamples(xaxis.data(), object->smoothLPCO.data(), totalPoints); standard->rpcoCurve->setSamples(xaxis.data(), object->smoothRPCO.data(), totalPoints); standard->lpcoCurve->attach(this); standard->lpcoCurve->setVisible(true); standard->rpcoCurve->attach(this); standard->rpcoCurve->setVisible(true); } if (!object->lppbArray.empty()) { standard->lppCurve->setSamples(new QwtIntervalSeriesData(object->smoothLPP)); standard->lppCurve->attach(this); standard->lppCurve->setVisible(true); } if (!object->rppbArray.empty()) { standard->rppCurve->setSamples(new QwtIntervalSeriesData(object->smoothRPP)); standard->rppCurve->attach(this); standard->rppCurve->setVisible(true); } if (!object->lpppbArray.empty()) { standard->lpppCurve->setSamples(new QwtIntervalSeriesData(object->smoothLPPP)); standard->lpppCurve->attach(this); standard->lpppCurve->setVisible(true); } if (!object->rpppbArray.empty()) { standard->rpppCurve->setSamples(new QwtIntervalSeriesData(object->smoothRPPP)); standard->rpppCurve->attach(this); standard->rpppCurve->setVisible(true); } // to the max / min standard->grid->detach(); // honour user preferences standard->wCurve->setVisible(referencePlot->showW); standard->mCurve->setVisible(referencePlot->showW); standard->wattsCurve->setVisible(referencePlot->showPowerState < 2); standard->npCurve->setVisible(referencePlot->showNP); standard->rvCurve->setVisible(referencePlot->showRV); standard->rcadCurve->setVisible(referencePlot->showRCad); standard->rgctCurve->setVisible(referencePlot->showRGCT); standard->gearCurve->setVisible(referencePlot->showGear); standard->smo2Curve->setVisible(referencePlot->showSmO2); standard->thbCurve->setVisible(referencePlot->showtHb); standard->o2hbCurve->setVisible(referencePlot->showO2Hb); standard->hhbCurve->setVisible(referencePlot->showHHb); standard->atissCurve->setVisible(referencePlot->showATISS); standard->antissCurve->setVisible(referencePlot->showANTISS); standard->xpCurve->setVisible(referencePlot->showXP); standard->apCurve->setVisible(referencePlot->showAP); standard->hrCurve->setVisible(referencePlot->showHr); standard->tcoreCurve->setVisible(referencePlot->showTcore); standard->speedCurve->setVisible(referencePlot->showSpeed); standard->accelCurve->setVisible(referencePlot->showAccel); standard->wattsDCurve->setVisible(referencePlot->showPowerD); standard->cadDCurve->setVisible(referencePlot->showCadD); standard->nmDCurve->setVisible(referencePlot->showTorqueD); standard->hrDCurve->setVisible(referencePlot->showHrD); standard->cadCurve->setVisible(referencePlot->showCad); standard->altCurve->setVisible(referencePlot->showAlt); standard->altSlopeCurve->setVisible(referencePlot->showAltSlopeState > 0); standard->slopeCurve->setVisible(referencePlot->showSlope); standard->tempCurve->setVisible(referencePlot->showTemp); standard->windCurve->setVisible(referencePlot->showWind); standard->torqueCurve->setVisible(referencePlot->showWind); standard->balanceLCurve->setVisible(referencePlot->showBalance); standard->balanceRCurve->setVisible(referencePlot->showBalance); standard->lteCurve->setVisible(referencePlot->showTE); standard->rteCurve->setVisible(referencePlot->showTE); standard->lpsCurve->setVisible(referencePlot->showPS); standard->rpsCurve->setVisible(referencePlot->showPS); standard->lpcoCurve->setVisible(referencePlot->showPCO); standard->rpcoCurve->setVisible(referencePlot->showPCO); standard->lppCurve->setVisible(referencePlot->showDC); standard->rppCurve->setVisible(referencePlot->showDC); standard->lpppCurve->setVisible(referencePlot->showPPP); standard->rpppCurve->setVisible(referencePlot->showPPP); // set xaxis -- but not min/max as we get called during smoothing // and massively quicker to reuse data and replot setXTitle(); enableAxis(xBottom, true); setAxisVisible(xBottom, true); // set the y-axis scales now referencePlot = NULL; setAltSlopePlotStyle(standard->altSlopeCurve); setYMax(); // refresh zone background (if needed) if (shade_zones) { bg->attach(this); refreshZoneLabels(); } else bg->detach(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setDataFromRide(RideItem *_rideItem) { rideItem = _rideItem; if (_rideItem == NULL) return; // we don't have a reference plot referencePlot = NULL; // basically clear out //standard->wattsArray.clear(); //standard->curveTitle.setLabel(QwtText(QString(""), QwtText::PlainText)); // default to no title setDataFromRideFile(rideItem->ride(), standard); // remember the curves and colors isolation = false; curveColors->saveState(); } void AllPlot::setDataFromRideFile(RideFile *ride, AllPlotObject *here) { if (ride && ride->dataPoints().size()) { const RideFileDataPresent *dataPresent = ride->areDataPresent(); int npoints = ride->dataPoints().size(); // fetch w' bal data here->match = ride->wprimeData()->mydata(); here->matchTime = ride->wprimeData()->mxdata(false); here->matchDist = ride->wprimeData()->mxdata(true); here->wprime = ride->wprimeData()->ydata(); here->wprimeTime = ride->wprimeData()->xdata(false); here->wprimeDist = ride->wprimeData()->xdata(true); here->wattsArray.resize(dataPresent->watts ? npoints : 0); here->atissArray.resize(dataPresent->watts ? npoints : 0); here->antissArray.resize(dataPresent->watts ? npoints : 0); here->npArray.resize(dataPresent->np ? npoints : 0); here->rcadArray.resize(dataPresent->rcad ? npoints : 0); here->rvArray.resize(dataPresent->rvert ? npoints : 0); here->rgctArray.resize(dataPresent->rcontact ? npoints : 0); here->smo2Array.resize(dataPresent->smo2 ? npoints : 0); here->thbArray.resize(dataPresent->thb ? npoints : 0); here->o2hbArray.resize(dataPresent->o2hb ? npoints : 0); here->hhbArray.resize(dataPresent->hhb ? npoints : 0); here->gearArray.resize(dataPresent->gear ? npoints : 0); here->xpArray.resize(dataPresent->xp ? npoints : 0); here->apArray.resize(dataPresent->apower ? npoints : 0); here->hrArray.resize(dataPresent->hr ? npoints : 0); here->tcoreArray.resize(dataPresent->hr ? npoints : 0); here->speedArray.resize(dataPresent->kph ? npoints : 0); here->accelArray.resize(dataPresent->kph ? npoints : 0); here->wattsDArray.resize(dataPresent->watts ? npoints : 0); here->cadDArray.resize(dataPresent->cad ? npoints : 0); here->nmDArray.resize(dataPresent->nm ? npoints : 0); here->hrDArray.resize(dataPresent->hr ? npoints : 0); here->cadArray.resize(dataPresent->cad ? npoints : 0); here->altArray.resize(dataPresent->alt ? npoints : 0); here->slopeArray.resize(dataPresent->slope ? npoints : 0); here->tempArray.resize(dataPresent->temp ? npoints : 0); here->windArray.resize(dataPresent->headwind ? npoints : 0); here->torqueArray.resize(dataPresent->nm ? npoints : 0); here->balanceArray.resize(dataPresent->lrbalance ? npoints : 0); here->lteArray.resize(dataPresent->lte ? npoints : 0); here->rteArray.resize(dataPresent->rte ? npoints : 0); here->lpsArray.resize(dataPresent->lps ? npoints : 0); here->rpsArray.resize(dataPresent->rps ? npoints : 0); here->lpcoArray.resize(dataPresent->lpco ? npoints : 0); here->rpcoArray.resize(dataPresent->rpco ? npoints : 0); here->lppbArray.resize(dataPresent->lppb ? npoints : 0); here->rppbArray.resize(dataPresent->rppb ? npoints : 0); here->lppeArray.resize(dataPresent->lppe ? npoints : 0); here->rppeArray.resize(dataPresent->rppe ? npoints : 0); here->lpppbArray.resize(dataPresent->lpppb ? npoints : 0); here->rpppbArray.resize(dataPresent->rpppb ? npoints : 0); here->lpppeArray.resize(dataPresent->lpppe ? npoints : 0); here->rpppeArray.resize(dataPresent->rpppe ? npoints : 0); here->timeArray.resize(npoints); here->distanceArray.resize(npoints); // attach appropriate curves here->wCurve->detach(); here->mCurve->detach(); here->wattsCurve->detach(); here->atissCurve->detach(); here->antissCurve->detach(); here->npCurve->detach(); here->rcadCurve->detach(); here->rvCurve->detach(); here->rgctCurve->detach(); here->gearCurve->detach(); here->smo2Curve->detach(); here->thbCurve->detach(); here->o2hbCurve->detach(); here->hhbCurve->detach(); here->xpCurve->detach(); here->apCurve->detach(); here->hrCurve->detach(); here->tcoreCurve->detach(); here->speedCurve->detach(); here->accelCurve->detach(); here->wattsDCurve->detach(); here->cadDCurve->detach(); here->nmDCurve->detach(); here->hrDCurve->detach(); here->cadCurve->detach(); here->altCurve->detach(); here->altSlopeCurve->detach(); here->slopeCurve->detach(); here->tempCurve->detach(); here->windCurve->detach(); here->torqueCurve->detach(); here->balanceLCurve->detach(); here->balanceRCurve->detach(); here->lteCurve->detach(); here->rteCurve->detach(); here->lpsCurve->detach(); here->rpsCurve->detach(); here->lpcoCurve->detach(); here->rpcoCurve->detach(); here->lppCurve->detach(); here->rppCurve->detach(); here->lpppCurve->detach(); here->rpppCurve->detach(); if (!here->altArray.empty()) { here->altCurve->attach(this); here->altSlopeCurve->attach(this); } if (!here->slopeArray.empty()) here->slopeCurve->attach(this); if (!here->wattsArray.empty()) here->wattsCurve->attach(this); if (!here->atissArray.empty()) here->atissCurve->attach(this); if (!here->antissArray.empty()) here->antissCurve->attach(this); if (!here->npArray.empty()) here->npCurve->attach(this); if (!here->rvArray.empty()) here->rvCurve->attach(this); if (!here->rcadArray.empty()) here->rcadCurve->attach(this); if (!here->rgctArray.empty()) here->rgctCurve->attach(this); if (!here->gearArray.empty()) here->gearCurve->attach(this); if (!here->smo2Array.empty()) here->smo2Curve->attach(this); if (!here->thbArray.empty()) here->thbCurve->attach(this); if (!here->o2hbArray.empty()) here->o2hbCurve->attach(this); if (!here->hhbArray.empty()) here->hhbCurve->attach(this); if (!here->xpArray.empty()) here->xpCurve->attach(this); if (!here->apArray.empty()) here->apCurve->attach(this); if (showW && ride && !here->wprime.empty()) { here->wCurve->attach(this); here->mCurve->attach(this); } if (!here->hrArray.empty()) here->hrCurve->attach(this); if (!here->tcoreArray.empty()) here->tcoreCurve->attach(this); if (!here->speedArray.empty()) here->speedCurve->attach(this); // deltas if (!here->accelArray.empty()) here->accelCurve->attach(this); if (!here->wattsDArray.empty()) here->wattsDCurve->attach(this); if (!here->cadDArray.empty()) here->cadDCurve->attach(this); if (!here->nmDArray.empty()) here->nmDCurve->attach(this); if (!here->hrDArray.empty()) here->hrDCurve->attach(this); if (!here->cadArray.empty()) here->cadCurve->attach(this); if (!here->tempArray.empty()) here->tempCurve->attach(this); if (!here->windArray.empty()) here->windCurve->attach(this); if (!here->torqueArray.empty()) here->torqueCurve->attach(this); if (!here->lteArray.empty()) { here->lteCurve->attach(this); here->rteCurve->attach(this); } if (!here->lpsArray.empty()) { here->lpsCurve->attach(this); here->rpsCurve->attach(this); } if (!here->balanceArray.empty()) { here->balanceLCurve->attach(this); here->balanceRCurve->attach(this); } if (!here->lpcoArray.empty()) { here->lpcoCurve->attach(this); here->rpcoCurve->attach(this); } if (!here->lppbArray.empty()) { here->lppCurve->attach(this); here->rppCurve->attach(this); } if (!here->lpppbArray.empty()) { here->lpppCurve->attach(this); here->rpppCurve->attach(this); } here->wCurve->setVisible(dataPresent->watts && showW); here->mCurve->setVisible(dataPresent->watts && showW); here->wattsCurve->setVisible(dataPresent->watts && showPowerState < 2); here->atissCurve->setVisible(dataPresent->watts && showATISS); here->antissCurve->setVisible(dataPresent->watts && showANTISS); here->npCurve->setVisible(dataPresent->np && showNP); here->rcadCurve->setVisible(dataPresent->rcad && showRCad); here->rvCurve->setVisible(dataPresent->rvert && showRV); here->rgctCurve->setVisible(dataPresent->rcontact && showRGCT); here->gearCurve->setVisible(dataPresent->gear && showGear); here->smo2Curve->setVisible(dataPresent->smo2 && showSmO2); here->thbCurve->setVisible(dataPresent->thb && showtHb); here->o2hbCurve->setVisible(dataPresent->o2hb && showO2Hb); here->hhbCurve->setVisible(dataPresent->hhb && showHHb); here->xpCurve->setVisible(dataPresent->xp && showXP); here->apCurve->setVisible(dataPresent->apower && showAP); here->hrCurve->setVisible(dataPresent->hr && showHr); here->tcoreCurve->setVisible(dataPresent->hr && showTcore); here->speedCurve->setVisible(dataPresent->kph && showSpeed); here->cadCurve->setVisible(dataPresent->cad && showCad); here->altCurve->setVisible(dataPresent->alt && showAlt); here->altSlopeCurve->setVisible(dataPresent->alt && showAltSlopeState > 0); here->slopeCurve->setVisible(dataPresent->slope && showSlope); here->tempCurve->setVisible(dataPresent->temp && showTemp); here->windCurve->setVisible(dataPresent->headwind && showWind); here->torqueCurve->setVisible(dataPresent->nm && showWind); here->lteCurve->setVisible(dataPresent->lte && showTE); here->rteCurve->setVisible(dataPresent->rte && showTE); here->lpsCurve->setVisible(dataPresent->lps && showPS); here->rpsCurve->setVisible(dataPresent->rps && showPS); here->balanceLCurve->setVisible(dataPresent->lrbalance && showBalance); here->balanceRCurve->setVisible(dataPresent->lrbalance && showBalance); here->lpcoCurve->setVisible(dataPresent->lpco && showPCO); here->rpcoCurve->setVisible(dataPresent->rpco && showPCO); here->lppCurve->setVisible(dataPresent->lppb && showDC); here->rppCurve->setVisible(dataPresent->rppb && showDC); here->lpppCurve->setVisible(dataPresent->lpppb && showPPP); here->rpppCurve->setVisible(dataPresent->rpppb && showPPP); // deltas here->accelCurve->setVisible(dataPresent->kph && showAccel); here->wattsDCurve->setVisible(dataPresent->watts && showPowerD); here->cadDCurve->setVisible(dataPresent->cad && showCadD); here->nmDCurve->setVisible(dataPresent->nm && showTorqueD); here->hrDCurve->setVisible(dataPresent->hr && showHrD); int arrayLength = 0; foreach (const RideFilePoint *point, ride->dataPoints()) { // we round the time to nearest 100th of a second // before adding to the array, to avoid situation // where 'high precision' time slice is an artefact // of double precision or slight timing anomalies // e.g. where realtime gives timestamps like // 940.002 followed by 940.998 and were previously // both rounded to 940s // // NOTE: this rounding mechanism is identical to that // used by the Ride Editor. double secs = floor(point->secs); double msecs = round((point->secs - secs) * 100) * 10; here->timeArray[arrayLength] = secs + msecs/1000; if (!here->wattsArray.empty()) here->wattsArray[arrayLength] = max(0, point->watts); if (!here->atissArray.empty()) here->atissArray[arrayLength] = max(0, point->atiss); if (!here->antissArray.empty()) here->antissArray[arrayLength] = max(0, point->antiss); if (!here->npArray.empty()) here->npArray[arrayLength] = max(0, point->np); if (!here->rvArray.empty()) here->rvArray[arrayLength] = max(0, point->rvert); if (!here->rcadArray.empty()) here->rcadArray[arrayLength] = max(0, point->rcad); if (!here->rgctArray.empty()) here->rgctArray[arrayLength] = max(0, point->rcontact); if (!here->gearArray.empty()) here->gearArray[arrayLength] = max(0, point->gear); if (!here->smo2Array.empty()) here->smo2Array[arrayLength] = max(0, point->smo2); if (!here->thbArray.empty()) here->thbArray[arrayLength] = max(0, point->thb); if (!here->o2hbArray.empty()) here->o2hbArray[arrayLength] = max(0, point->o2hb); if (!here->hhbArray.empty()) here->hhbArray[arrayLength] = max(0, point->hhb); if (!here->xpArray.empty()) here->xpArray[arrayLength] = max(0, point->xp); if (!here->apArray.empty()) here->apArray[arrayLength] = max(0, point->apower); if (!here->hrArray.empty()) here->hrArray[arrayLength] = max(0, point->hr); if (!here->tcoreArray.empty()) here->tcoreArray[arrayLength] = max(0, point->tcore); // delta series if (!here->accelArray.empty()) here->accelArray[arrayLength] = point->kphd; if (!here->wattsDArray.empty()) here->wattsDArray[arrayLength] = point->wattsd; if (!here->cadDArray.empty()) here->cadDArray[arrayLength] = point->cadd; if (!here->nmDArray.empty()) here->nmDArray[arrayLength] = point->nmd; if (!here->hrDArray.empty()) here->hrDArray[arrayLength] = point->hrd; if (!here->speedArray.empty()) here->speedArray[arrayLength] = max(0, (context->athlete->useMetricUnits ? point->kph : point->kph * MILES_PER_KM)); if (!here->cadArray.empty()) here->cadArray[arrayLength] = max(0, point->cad); if (!here->altArray.empty()) here->altArray[arrayLength] = (context->athlete->useMetricUnits ? point->alt : point->alt * FEET_PER_METER); if (!here->slopeArray.empty()) here->slopeArray[arrayLength] = point->slope; if (!here->tempArray.empty()) here->tempArray[arrayLength] = point->temp; if (!here->windArray.empty()) here->windArray[arrayLength] = max(0, (context->athlete->useMetricUnits ? point->headwind : point->headwind * MILES_PER_KM)); // pedal data if (!here->balanceArray.empty()) here->balanceArray[arrayLength] = point->lrbalance; if (!here->lteArray.empty()) here->lteArray[arrayLength] = point->lte; if (!here->rteArray.empty()) here->rteArray[arrayLength] = point->rte; if (!here->lpsArray.empty()) here->lpsArray[arrayLength] = point->lps; if (!here->rpsArray.empty()) here->rpsArray[arrayLength] = point->rps; if (!here->lpcoArray.empty()) here->lpcoArray[arrayLength] = point->lpco; if (!here->rpcoArray.empty()) here->rpcoArray[arrayLength] = point->rpco; if (!here->lppbArray.empty()) here->lppbArray[arrayLength] = point->lppb; if (!here->rppbArray.empty()) here->rppbArray[arrayLength] = point->rppb; if (!here->lppeArray.empty()) here->lppeArray[arrayLength] = point->lppe; if (!here->rppeArray.empty()) here->rppeArray[arrayLength] = point->rppe; if (!here->lpppbArray.empty()) here->lpppbArray[arrayLength] = point->lpppb; if (!here->rpppbArray.empty()) here->rpppbArray[arrayLength] = point->rpppb; if (!here->lpppeArray.empty()) here->lpppeArray[arrayLength] = point->lpppe; if (!here->rpppeArray.empty()) here->rpppeArray[arrayLength] = point->rpppe; here->distanceArray[arrayLength] = max(0, (context->athlete->useMetricUnits ? point->km : point->km * MILES_PER_KM)); if (!here->torqueArray.empty()) here->torqueArray[arrayLength] = max(0, (context->athlete->useMetricUnits ? point->nm : point->nm * FEET_LB_PER_NM)); ++arrayLength; } recalc(here); } else { //setTitle("no data"); here->wCurve->detach(); here->mCurve->detach(); here->wattsCurve->detach(); here->atissCurve->detach(); here->antissCurve->detach(); here->npCurve->detach(); here->rvCurve->detach(); here->rcadCurve->detach(); here->rgctCurve->detach(); here->gearCurve->detach(); here->smo2Curve->detach(); here->thbCurve->detach(); here->o2hbCurve->detach(); here->hhbCurve->detach(); here->xpCurve->detach(); here->apCurve->detach(); here->hrCurve->detach(); here->tcoreCurve->detach(); here->speedCurve->detach(); here->accelCurve->detach(); here->wattsDCurve->detach(); here->cadDCurve->detach(); here->nmDCurve->detach(); here->hrDCurve->detach(); here->cadCurve->detach(); here->altCurve->detach(); here->altSlopeCurve->detach(); here->slopeCurve->detach(); here->tempCurve->detach(); here->windCurve->detach(); here->torqueCurve->detach(); here->lteCurve->detach(); here->rteCurve->detach(); here->lpsCurve->detach(); here->rpsCurve->detach(); here->balanceLCurve->detach(); here->balanceRCurve->detach(); here->lpcoCurve->detach(); here->rpcoCurve->detach(); here->lppCurve->detach(); here->rppCurve->detach(); here->lpppCurve->detach(); here->rpppCurve->detach(); foreach(QwtPlotMarker *mrk, here->d_mrk) delete mrk; here->d_mrk.clear(); foreach(QwtPlotMarker *mrk, here->cal_mrk) delete mrk; here->cal_mrk.clear(); foreach(QwtPlotCurve *referenceLine, here->referenceLines) { curveColors->remove(referenceLine); referenceLine->detach(); delete referenceLine; } here->referenceLines.clear(); } // record the max x value if (here->timeArray.count() && here->distanceArray.count()) { int maxSECS = here->timeArray[here->timeArray.count()-1]; int maxKM = here->distanceArray[here->distanceArray.count()-1]; if (maxKM > here->maxKM) here->maxKM = maxKM; if (maxSECS > here->maxSECS) here->maxSECS = maxSECS; } setAltSlopePlotStyle(here->altSlopeCurve); // set the axis setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); } void AllPlot::setShow(RideFile::SeriesType type, bool state) { switch(type) { case RideFile::none: setShowAccel(false); setShowPowerD(false); setShowCadD(false); setShowTorqueD(false); setShowHrD(false); setShowPower(0); setShowAltSlope(0); setShowSlope(false); setShowNP(false); setShowATISS(false); setShowANTISS(false); setShowXP(false); setShowAP(false); setShowHr(false); setShowTcore(false); setShowSpeed(false); setShowCad(false); setShowAlt(false); setShowTemp(false); setShowWind(false); setShowRV(false); setShowRGCT(false); setShowRCad(false); setShowSmO2(false); setShowtHb(false); setShowO2Hb(false); setShowHHb(false); setShowGear(false); setShowW(false); setShowTorque(false); setShowBalance(false); setShowTE(false); setShowPS(false); setShowPCO(false); setShowDC(false); setShowPPP(false); break; case RideFile::secs: break; case RideFile::cad: setShowCad(state); break; case RideFile::tcore: setShowTcore(state); break; case RideFile::hr: setShowHr(state); break; case RideFile::km: break; case RideFile::kph: setShowSpeed(state); break; case RideFile::kphd: setShowAccel(state); break; case RideFile::wattsd: setShowPowerD(state); break; case RideFile::cadd: setShowCadD(state); break; case RideFile::nmd: setShowTorqueD(state); break; case RideFile::hrd: setShowHrD(state); break; case RideFile::nm: setShowTorque(state); break; case RideFile::watts: setShowPower(state ? 0 : 2); break; case RideFile::xPower: setShowXP(state); break; case RideFile::aPower: setShowAP(state); break; case RideFile::aTISS: setShowATISS(state); break; case RideFile::anTISS: setShowANTISS(state); break; case RideFile::NP: setShowNP(state); break; case RideFile::alt: setShowAlt(state); break; case RideFile::lon: break; case RideFile::lat: break; case RideFile::headwind: setShowWind(state); break; case RideFile::slope: setShowSlope(state); break; case RideFile::temp: setShowTemp(state); break; case RideFile::lrbalance: setShowBalance(state); break; case RideFile::lte: case RideFile::rte: setShowTE(state); break; case RideFile::lps: case RideFile::rps: setShowPS(state); break; case RideFile::lpco: case RideFile::rpco: setShowPCO(state); break; case RideFile::lppb: case RideFile::rppb: case RideFile::lppe: case RideFile::rppe: setShowDC(state); break; case RideFile::lpppb: case RideFile::rpppb: case RideFile::lpppe: case RideFile::rpppe: setShowPPP(state); break; case RideFile::interval: break; case RideFile::vam: break; case RideFile::wattsKg: break; case RideFile::wprime: setShowW(state); break; case RideFile::smo2: setShowSmO2(state); break; case RideFile::thb: setShowtHb(state); break; case RideFile::o2hb: setShowO2Hb(state); break; case RideFile::hhb: setShowHHb(state); break; case RideFile::rvert: setShowRV(state); break; case RideFile::rcad: setShowRCad(state); break; case RideFile::rcontact: setShowRGCT(state); break; case RideFile::gear: setShowGear(state); break; case RideFile::wbal: break; } } void AllPlot::setShowPower(int id) { if (showPowerState == id) return; showPowerState = id; standard->wattsCurve->setVisible(id < 2); shade_zones = (id == 0); setYMax(); if (shade_zones) { bg->attach(this); refreshZoneLabels(); } else bg->detach(); // remember the curves and colors isolation = false; curveColors->saveState(); } void AllPlot::setShowNP(bool show) { showNP = show; standard->npCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowRV(bool show) { showRV = show; standard->rvCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowRCad(bool show) { showRCad = show; standard->rcadCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowRGCT(bool show) { showRGCT = show; standard->rgctCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowGear(bool show) { showGear = show; standard->gearCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowSmO2(bool show) { showSmO2 = show; standard->smo2Curve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowtHb(bool show) { showtHb = show; standard->thbCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowO2Hb(bool show) { showO2Hb = show; standard->o2hbCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowHHb(bool show) { showHHb = show; standard->hhbCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowANTISS(bool show) { showANTISS = show; standard->antissCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowATISS(bool show) { showATISS = show; standard->atissCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowXP(bool show) { showXP = show; standard->xpCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowAP(bool show) { showAP = show; standard->apCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowTcore(bool show) { showTcore = show; standard->tcoreCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowHr(bool show) { showHr = show; standard->hrCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowSpeed(bool show) { showSpeed = show; standard->speedCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowAccel(bool show) { showAccel = show; standard->accelCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowPowerD(bool show) { showPowerD = show; standard->wattsDCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowCadD(bool show) { showCadD = show; standard->cadDCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowTorqueD(bool show) { showTorqueD = show; standard->nmDCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowHrD(bool show) { showHrD = show; standard->hrDCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowCad(bool show) { showCad = show; standard->cadCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowAlt(bool show) { showAlt = show; standard->altCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowSlope(bool show) { showSlope = show; standard->slopeCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowAltSlope(int id) { if (showAltSlopeState == id) return; showAltSlopeState = id; standard->altSlopeCurve->setVisible(id > 0); setAltSlopePlotStyle(standard->altSlopeCurve); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowTemp(bool show) { showTemp = show; standard->tempCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowWind(bool show) { showWind = show; standard->windCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowW(bool show) { showW = show; standard->wCurve->setVisible(show); standard->mCurve->setVisible(show); if (!showW || (rideItem && rideItem->ride() && rideItem->ride()->wprimeData()->TAU <= 0)) { standard->curveTitle.setLabel(QwtText("")); } setYMax(); // clear labels ? if (show == false) { foreach(QwtPlotMarker *p, standard->matchLabels) { p->detach(); delete p; } standard->matchLabels.clear(); } // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowTorque(bool show) { showTorque = show; standard->torqueCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowBalance(bool show) { showBalance = show; standard->balanceLCurve->setVisible(show); standard->balanceRCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowTE(bool show) { showTE = show; standard->lteCurve->setVisible(show); standard->rteCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowPS(bool show) { showPS = show; standard->lpsCurve->setVisible(show); standard->rpsCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowDC(bool show) { showDC = show; standard->lppCurve->setVisible(show); standard->rppCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowPPP(bool show) { showPPP = show; standard->lpppCurve->setVisible(show); standard->rpppCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowPCO(bool show) { showPCO = show; standard->lpcoCurve->setVisible(show); standard->rpcoCurve->setVisible(show); setYMax(); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setShowGrid(bool show) { standard->grid->setVisible(show); // remember the curves and colors isolation = false; curveColors->saveState(); replot(); } void AllPlot::setPaintBrush(int state) { fill = state; if (state) { QColor p; p = standard->wCurve->pen().color(); p.setAlpha(64); standard->wCurve->setBrush(QBrush(p)); p = standard->wattsCurve->pen().color(); p.setAlpha(64); standard->wattsCurve->setBrush(QBrush(p)); p = standard->npCurve->pen().color(); p.setAlpha(64); standard->npCurve->setBrush(QBrush(p)); standard->atissCurve->setBrush(QBrush(p)); standard->antissCurve->setBrush(QBrush(p)); p = standard->rvCurve->pen().color(); p.setAlpha(64); standard->rvCurve->setBrush(QBrush(p)); p = standard->rgctCurve->pen().color(); p.setAlpha(64); standard->rgctCurve->setBrush(QBrush(p)); p = standard->rcadCurve->pen().color(); p.setAlpha(64); standard->rcadCurve->setBrush(QBrush(p)); p = standard->gearCurve->pen().color(); p.setAlpha(64); standard->gearCurve->setBrush(QBrush(p)); p = standard->smo2Curve->pen().color(); p.setAlpha(64); standard->smo2Curve->setBrush(QBrush(p)); p = standard->thbCurve->pen().color(); p.setAlpha(64); standard->thbCurve->setBrush(QBrush(p)); p = standard->o2hbCurve->pen().color(); p.setAlpha(64); standard->o2hbCurve->setBrush(QBrush(p)); p = standard->hhbCurve->pen().color(); p.setAlpha(64); standard->hhbCurve->setBrush(QBrush(p)); p = standard->xpCurve->pen().color(); p.setAlpha(64); standard->xpCurve->setBrush(QBrush(p)); p = standard->apCurve->pen().color(); p.setAlpha(64); standard->apCurve->setBrush(QBrush(p)); p = standard->tcoreCurve->pen().color(); p.setAlpha(64); standard->tcoreCurve->setBrush(QBrush(p)); p = standard->hrCurve->pen().color(); p.setAlpha(64); standard->hrCurve->setBrush(QBrush(p)); p = standard->accelCurve->pen().color(); p.setAlpha(64); standard->accelCurve->setBrush(QBrush(p)); p = standard->wattsDCurve->pen().color(); p.setAlpha(64); standard->wattsDCurve->setBrush(QBrush(p)); p = standard->cadDCurve->pen().color(); p.setAlpha(64); standard->cadDCurve->setBrush(QBrush(p)); p = standard->nmDCurve->pen().color(); p.setAlpha(64); standard->nmDCurve->setBrush(QBrush(p)); p = standard->hrDCurve->pen().color(); p.setAlpha(64); standard->hrDCurve->setBrush(QBrush(p)); p = standard->speedCurve->pen().color(); p.setAlpha(64); standard->speedCurve->setBrush(QBrush(p)); p = standard->cadCurve->pen().color(); p.setAlpha(64); standard->cadCurve->setBrush(QBrush(p)); p = standard->tempCurve->pen().color(); p.setAlpha(64); standard->tempCurve->setBrush(QBrush(p)); p = standard->torqueCurve->pen().color(); p.setAlpha(64); standard->torqueCurve->setBrush(QBrush(p)); p = standard->lteCurve->pen().color(); p.setAlpha(64); standard->lteCurve->setBrush(QBrush(p)); p = standard->rteCurve->pen().color(); p.setAlpha(64); standard->rteCurve->setBrush(QBrush(p)); p = standard->lpsCurve->pen().color(); p.setAlpha(64); standard->lpsCurve->setBrush(QBrush(p)); p = standard->rpsCurve->pen().color(); p.setAlpha(64); standard->rpsCurve->setBrush(QBrush(p)); p = standard->lpcoCurve->pen().color(); p.setAlpha(64); standard->lpcoCurve->setBrush(QBrush(p)); p = standard->rpcoCurve->pen().color(); p.setAlpha(64); standard->rpcoCurve->setBrush(QBrush(p)); p = standard->lppCurve->pen().color(); p.setAlpha(64); standard->lppCurve->setBrush(QBrush(p)); p = standard->rppCurve->pen().color(); p.setAlpha(64); standard->rppCurve->setBrush(QBrush(p)); p = standard->lpppCurve->pen().color(); p.setAlpha(64); standard->lpppCurve->setBrush(QBrush(p)); p = standard->rpppCurve->pen().color(); p.setAlpha(64); standard->rpppCurve->setBrush(QBrush(p)); p = standard->slopeCurve->pen().color(); p.setAlpha(64); standard->slopeCurve->setBrush(QBrush(p)); /*p = standard->altSlopeCurve->pen().color(); p.setAlpha(64); standard->altSlopeCurve->setBrush(QBrush(p)); p = standard->balanceLCurve->pen().color(); p.setAlpha(64); standard->balanceLCurve->setBrush(QBrush(p)); p = standard->balanceRCurve->pen().color(); p.setAlpha(64); standard->balanceRCurve->setBrush(QBrush(p));*/ } else { standard->wCurve->setBrush(Qt::NoBrush); standard->wattsCurve->setBrush(Qt::NoBrush); standard->npCurve->setBrush(Qt::NoBrush); standard->rvCurve->setBrush(Qt::NoBrush); standard->rgctCurve->setBrush(Qt::NoBrush); standard->rcadCurve->setBrush(Qt::NoBrush); standard->gearCurve->setBrush(Qt::NoBrush); standard->smo2Curve->setBrush(Qt::NoBrush); standard->thbCurve->setBrush(Qt::NoBrush); standard->o2hbCurve->setBrush(Qt::NoBrush); standard->hhbCurve->setBrush(Qt::NoBrush); standard->atissCurve->setBrush(Qt::NoBrush); standard->antissCurve->setBrush(Qt::NoBrush); standard->xpCurve->setBrush(Qt::NoBrush); standard->apCurve->setBrush(Qt::NoBrush); standard->hrCurve->setBrush(Qt::NoBrush); standard->tcoreCurve->setBrush(Qt::NoBrush); standard->speedCurve->setBrush(Qt::NoBrush); standard->accelCurve->setBrush(Qt::NoBrush); standard->wattsDCurve->setBrush(Qt::NoBrush); standard->cadDCurve->setBrush(Qt::NoBrush); standard->hrDCurve->setBrush(Qt::NoBrush); standard->nmDCurve->setBrush(Qt::NoBrush); standard->cadCurve->setBrush(Qt::NoBrush); standard->tempCurve->setBrush(Qt::NoBrush); standard->torqueCurve->setBrush(Qt::NoBrush); standard->lteCurve->setBrush(Qt::NoBrush); standard->rteCurve->setBrush(Qt::NoBrush); standard->lpsCurve->setBrush(Qt::NoBrush); standard->rpsCurve->setBrush(Qt::NoBrush); standard->lpcoCurve->setBrush(Qt::NoBrush); standard->rpcoCurve->setBrush(Qt::NoBrush); standard->lppCurve->setBrush(Qt::NoBrush); standard->rppCurve->setBrush(Qt::NoBrush); standard->lpppCurve->setBrush(Qt::NoBrush); standard->rpppCurve->setBrush(Qt::NoBrush); standard->slopeCurve->setBrush(Qt::NoBrush); //standard->altSlopeCurve->setBrush(Qt::NoBrush); //standard->balanceLCurve->setBrush(Qt::NoBrush); //standard->balanceRCurve->setBrush(Qt::NoBrush); } replot(); } void AllPlot::setSmoothing(int value) { smooth = value; // if anything is going on, lets stop it now! // ACTUALLY its quite handy to play with smooting! isolation = false; curveColors->restoreState(); recalc(standard); } void AllPlot::setByDistance(int id) { bydist = (id == 1); setXTitle(); // if anything is going on, lets stop it now! isolation = false; curveColors->restoreState(); recalc(standard); } struct ComparePoints { bool operator()(const double p1, const double p2) { return p1 < p2; } }; int AllPlot::timeIndex(double min) const { // return index offset for specified time QVector<double>::const_iterator i = std::lower_bound( standard->smoothTime.begin(), standard->smoothTime.end(), min, ComparePoints()); if (i == standard->smoothTime.end()) return standard->smoothTime.size(); return i - standard->smoothTime.begin(); } int AllPlot::distanceIndex(double km) const { // return index offset for specified distance in km QVector<double>::const_iterator i = std::lower_bound( standard->smoothDistance.begin(), standard->smoothDistance.end(), km, ComparePoints()); if (i == standard->smoothDistance.end()) return standard->smoothDistance.size(); return i - standard->smoothDistance.begin(); } /*---------------------------------------------------------------------- * Interval plotting *--------------------------------------------------------------------*/ /* * HELPER FUNCTIONS: * intervalNum - returns a pointer to the nth selected interval * intervalCount - returns the number of highlighted intervals */ // note this is operating on the children of allIntervals and not the // intervalWidget (QTreeWidget) -- this is why we do not use the // selectedItems() member. N starts a one not zero. IntervalItem *IntervalPlotData::intervalNum(int n) const { RideItem *rideItem = window->current; if (!rideItem) return NULL; int highlighted=0; foreach(IntervalItem *p, rideItem->intervals()) { if (p->selected) highlighted++; if (highlighted == n) return p; } return NULL; } // how many intervals selected? int IntervalPlotData::intervalCount() const { RideItem *rideItem = window->current; if (!rideItem) return 0; int highlighted=0; foreach(IntervalItem *p, rideItem->intervals()) if (p->selected) highlighted++; return highlighted; } /* * INTERVAL HIGHLIGHTING CURVE * IntervalPlotData - implements the qwtdata interface where * x,y return point co-ordinates and * size returns the number of points */ // The interval curve data is derived from the intervals that have // been selected in the Context leftlayout for each selected // interval we return 4 data points; bottomleft, topleft, topright // and bottom right. // // the points correspond to: // bottom left = interval start, 0 watts // top left = interval start, maxwatts // top right = interval stop, maxwatts // bottom right = interval stop, 0 watts // double IntervalPlotData::x(size_t i) const { // for each interval there are four points, which interval is this for? int interval = i ? i/4 : 0; interval += 1; // interval numbers start at 1 not ZERO in the utility functions double multiplier = context->athlete->useMetricUnits ? 1 : MILES_PER_KM; // get the interval IntervalItem *current = intervalNum(interval); if (current == NULL) return 0; // out of bounds !? // overlap at right ? double right = allPlot->bydist ? multiplier * current->stopKM : current->stop/60; if (i%4 == 2 || i%4 == 3) { for (int n=1; n<=intervalCount(); n++) { IntervalItem *other = intervalNum(n); if (other != current) { if (other->start < current->stop && other->stop > current->stop) { if (other->start < current->start) { double _right = allPlot->bydist ? multiplier * current->startKM : current->start/60; if (_right<right) right = _right; } else { double _right = allPlot->bydist ? multiplier * other->startKM : other->start/60; if (_right<right) right = _right; } } } } } // which point are we returning? switch (i%4) { case 0 : return allPlot->bydist ? multiplier * current->startKM : current->start/60; // bottom left case 1 : return allPlot->bydist ? multiplier * current->startKM : current->start/60; // top left case 2 : return right; // top right case 3 : return right; // bottom right } return 0; // shouldn't get here, but keeps compiler happy } double IntervalPlotData::y(size_t i) const { // which point are we returning? switch (i%4) { case 0 : return -20; // bottom left case 1 : return 100; // top left - set to out of bound value case 2 : return 100; // top right - set to out of bound value case 3 : return -20; // bottom right } return 0; } size_t IntervalPlotData::size() const { return intervalCount()*4; } QPointF IntervalPlotData::sample(size_t i) const { return QPointF(x(i), y(i)); } QRectF IntervalPlotData::boundingRect() const { return QRectF(0, 5000, 5100, 5100); } void AllPlot::pointHover(QwtPlotCurve *curve, int index) { double X=0.0f; if (index >= 0 && curve != standard->intervalHighlighterCurve && curve != standard->intervalHoverCurve && curve->isVisible()) { double yvalue = curve->sample(index).y(); double xvalue = curve->sample(index).x(); X = xvalue; QString xstring; if (bydist) { xstring = QString("%1").arg(xvalue); } else { QTime t = QTime(0,0,0).addSecs(xvalue*60.00); xstring = t.toString("hh:mm:ss"); } // for speed curve add pace with units according to settings // only when the activity is a run. QString paceStr; if (curve->title() == tr("Speed") && rideItem && rideItem->isRun) { bool metricPace = appsettings->value(this, GC_PACE, true).toBool(); QString paceunit = metricPace ? tr("min/km") : tr("min/mile"); paceStr = tr("\n%1 %2").arg(context->athlete->useMetricUnits ? kphToPace(yvalue, metricPace, false) : mphToPace(yvalue, metricPace, false)).arg(paceunit); } if (curve->title() == tr("Speed") && rideItem && rideItem->isSwim) { bool metricPace = appsettings->value(this, GC_SWIMPACE, true).toBool(); QString paceunit = metricPace ? tr("min/100m") : tr("min/100yd"); paceStr = tr("\n%1 %2").arg(context->athlete->useMetricUnits ? kphToPace(yvalue, metricPace, true) : mphToPace(yvalue, metricPace, true)).arg(paceunit); } bool isHB= curve->title().text().contains("Hb"); // need to scale for W' bal if (curve->title().text().contains("W'")) yvalue /= 1000.0f; // output the tooltip QString text = QString("%1 %2%5\n%3 %4") .arg(yvalue, 0, 'f', isHB ? 2 : 1) .arg(this->axisTitle(curve->yAxis()).text()) .arg(xstring) .arg(this->axisTitle(curve->xAxis()).text()) .arg(paceStr); // set that text up tooltip->setText(text); // isolate me -- maybe do this via the legend ? //curveColors->isolate(curve); //replot(); } else { // no point tooltip->setText(""); // ok now we highlight intervals QPoint cursor = QCursor::pos(); X = tooltip->invTransform(canvas()->mapFromGlobal(cursor)).x(); // get colors back -- maybe do this via the legend? //curveColors->restoreState(); //replot(); } // we don't want hoveing or we have intervals selected so no need to mouse over if (!window->showHover->isChecked() || (rideItem && rideItem->intervalsSelected().count())) return; if (!context->isCompareIntervals && rideItem && rideItem->ride()) { // convert from distance to time if (bydist) X = rideItem->ride()->distanceToTime(X) / 60.00f; QVector<double>xdata, ydata; IntervalItem *chosen = NULL; if (rideItem->ride()->dataPoints().count() > 1) { // set duration to length of ride, and keep the value to compare int rideduration = rideItem->ride()->dataPoints().last()->secs - rideItem->ride()->dataPoints().first()->secs; int duration = rideduration; // loop through intervals and select FIRST we are in foreach(IntervalItem *i, rideItem->intervals()) { // ignore peaks and all, they are really distracting if (i->type == RideFileInterval::ALL || i->type == RideFileInterval::PEAKPOWER) continue; if (i->start < (X*60.00f) && i->stop > (X*60.00f)) { if ((i->stop-i->start) < duration) { duration = i->stop - i->start; chosen = i; } } } // we already chose it! if (chosen == NULL || chosen == hovered) return; if (duration < rideduration) { // hover curve color aligns to the type of interval we are highlighting QColor hbrush = chosen->color; hbrush.setAlpha(64); standard->intervalHoverCurve->setBrush(hbrush); // fill below the line // we chose one? if (bydist) { double multiplier = context->athlete->useMetricUnits ? 1 : MILES_PER_KM; double start = multiplier * chosen->startKM; double stop = multiplier * chosen->stopKM; xdata << start; ydata << -20; xdata << start; ydata << 100; xdata << stop; ydata << 100; xdata << stop; ydata << -20; } else { xdata << chosen->start / 60.00f; ydata << -20; xdata << chosen->start / 60.00f; ydata << 100; xdata << chosen->stop / 60.00f; ydata << 100; xdata << chosen->stop / 60.00f; ydata << -20; } } } standard->intervalHoverCurve->setSamples(xdata,ydata); replot(); // remember for next time! hovered = chosen; // tell the charts -- and block signals whilst they occur blockSignals(true); context->notifyIntervalHover(hovered); blockSignals(false); } } void AllPlot::intervalHover(IntervalItem *chosen) { // no point! if (!isVisible() || chosen == hovered) return; // don't highlight the all or all the peak intervals if (chosen && chosen->type == RideFileInterval::ALL) return; QVector<double>xdata, ydata; if (chosen) { // hover curve color aligns to the type of interval we are highlighting QColor hbrush = chosen->color; hbrush.setAlpha(64); standard->intervalHoverCurve->setBrush(hbrush); // fill below the line if (bydist) { double multiplier = context->athlete->useMetricUnits ? 1 : MILES_PER_KM; double start = multiplier * chosen->startKM; double stop = multiplier * chosen->stopKM; xdata << start; ydata << -20; xdata << start; ydata << 100; xdata << stop; ydata << 100; xdata << stop; ydata << -20; } else { xdata << chosen->start / 60.00f; ydata << -20; xdata << chosen->start / 60.00f; ydata << 100; xdata << chosen->stop / 60.00f; ydata << 100; xdata << chosen->stop / 60.00f; ydata << -20; } } // update state hovered = chosen; standard->intervalHoverCurve->setSamples(xdata,ydata); replot(); } void AllPlot::nextStep( int& step ) { if( step < 50 ) { step += 10; } else if( step == 50 ) { step = 100; } else if( step >= 100 && step < 1000 ) { step += 100; } else if( step >= 1000 && step < 5000) { step += 500; } else { step += 1000; } } bool AllPlot::eventFilter(QObject *obj, QEvent *event) { // if power is going on we worry about reference lines // otherwise not so much .. if ((showPowerState<2 && scope == RideFile::none) || scope == RideFile::watts || scope == RideFile::aTISS || scope == RideFile::anTISS || scope == RideFile::NP || scope == RideFile::aPower || scope == RideFile::xPower) { int axis = -1; if (obj == axisWidget(QwtPlot::yLeft)) axis=QwtPlot::yLeft; if (axis>-1 && event->type() == QEvent::MouseButtonDblClick) { QMouseEvent *m = static_cast<QMouseEvent*>(event); confirmTmpReference(invTransform(axis, m->y()),axis, true); // do show delete stuff return false; } if (axis>-1 && event->type() == QEvent::MouseMove) { QMouseEvent *m = static_cast<QMouseEvent*>(event); plotTmpReference(axis, m->x()-axisWidget(axis)->width(), m->y()); return false; } if (axis>-1 && event->type() == QEvent::MouseButtonRelease) { QMouseEvent *m = static_cast<QMouseEvent*>(event); if (m->x()>axisWidget(axis)->width()) { confirmTmpReference(invTransform(axis, m->y()),axis,false); // don't show delete stuff return false; } else if (standard->tmpReferenceLines.count()) { plotTmpReference(axis, 0, 0); //unplot return true; } } } // is it for other objects ? QList<QObject*> axes; QList<QwtAxisId> axesId; axes << axisWidget(QwtPlot::yLeft); axesId << QwtPlot::yLeft; axes << axisWidget(QwtAxisId(QwtAxis::yLeft, 1)); axesId << QwtAxisId(QwtAxis::yLeft, 1); axes << axisWidget(QwtAxisId(QwtAxis::yLeft, 3)); axesId << QwtAxisId(QwtAxis::yLeft, 3); axes << axisWidget(QwtPlot::yRight); axesId << QwtPlot::yRight; axes << axisWidget(QwtAxisId(QwtAxis::yRight, 1)); axesId << QwtAxisId(QwtAxis::yRight, 1); axes << axisWidget(QwtAxisId(QwtAxis::yRight, 2)); axesId << QwtAxisId(QwtAxis::yRight, 2); axes << axisWidget(QwtAxisId(QwtAxis::yRight, 3)); axesId << QwtAxisId(QwtAxis::yRight, 3); if (axes.contains(obj)) { QwtAxisId id = axesId.at(axes.indexOf(obj)); // this is an axes widget //qDebug()<<this<<"event on="<<id<< static_cast<QwtScaleWidget*>(obj)->title().text() <<"event="<<event->type(); // isolate / restore on mouse enter leave if (!isolation && event->type() == QEvent::Enter) { // isolate curve on hover curveColors->isolateAxis(id); replot(); } else if (!isolation && event->type() == QEvent::Leave) { // return to normal when leave curveColors->restoreState(); replot(); } else if (event->type() == QEvent::MouseButtonRelease) { // click on any axis to toggle isolation // if isolation is on, just turns it off // if isolation is off, turns it on for the axis clicked if (isolation) { isolation = false; curveColors->restoreState(); replot(); } else { isolation = true; curveColors->isolateAxis(id, true); // with scale adjust replot(); } } } // turn off hover when mouse leaves if (event->type() == QEvent::Leave) context->notifyIntervalHover(NULL); return false; } void AllPlot::plotTmpReference(int axis, int x, int y) { // only if on allplotwindow if (window==NULL) return; // not supported in compare mode if (context->isCompareIntervals) return; // only on power based charts if (scope != RideFile::none && scope != RideFile::watts && scope != RideFile::aTISS && scope != RideFile::anTISS && scope != RideFile::NP && scope != RideFile::aPower && scope != RideFile::xPower) return; if (x>0) { RideFilePoint *referencePoint = new RideFilePoint(); referencePoint->watts = invTransform(axis, y); foreach(QwtPlotCurve *curve, standard->tmpReferenceLines) { if (curve) { curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } } standard->tmpReferenceLines.clear(); // only plot if they are relevant to the plot. QwtPlotCurve *referenceLine = window->allPlot->plotReferenceLine(referencePoint); if (referenceLine) { standard->tmpReferenceLines.append(referenceLine); window->allPlot->replot(); } // now do the series plots foreach(AllPlot *plot, window->seriesPlots) { plot->replot(); foreach(QwtPlotCurve *curve, plot->standard->tmpReferenceLines) { if (curve) { plot->curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } } plot->standard->tmpReferenceLines.clear(); } foreach(AllPlot *plot, window->seriesPlots) { QwtPlotCurve *referenceLine = plot->plotReferenceLine(referencePoint); if (referenceLine) { plot->standard->tmpReferenceLines.append(referenceLine); plot->replot(); } } // now the stack plots foreach(AllPlot *plot, window->allPlots) { plot->replot(); foreach(QwtPlotCurve *curve, plot->standard->tmpReferenceLines) { if (curve) { plot->curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } } plot->standard->tmpReferenceLines.clear(); } foreach(AllPlot *plot, window->allPlots) { QwtPlotCurve *referenceLine = plot->plotReferenceLine(referencePoint); if (referenceLine) { plot->standard->tmpReferenceLines.append(referenceLine); plot->replot(); } } } else { // wipe any we don't want foreach(QwtPlotCurve *curve, standard->tmpReferenceLines) { if (curve) { curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } } standard->tmpReferenceLines.clear(); window->allPlot->replot(); foreach(AllPlot *plot, window->seriesPlots) { plot->replot(); foreach(QwtPlotCurve *curve, plot->standard->tmpReferenceLines) { if (curve) { plot->curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } plot->standard->tmpReferenceLines.clear(); } } window->allPlot->replot(); foreach(AllPlot *plot, window->allPlots) { plot->replot(); foreach(QwtPlotCurve *curve, plot->standard->tmpReferenceLines) { if (curve) { plot->curveColors->remove(curve); // ignored if not already there curve->detach(); delete curve; } } plot->standard->tmpReferenceLines.clear(); } } } void AllPlot::refreshReferenceLinesForAllPlots() { // not supported in compare mode if (window == NULL || context->isCompareIntervals) return; window->allPlot->refreshReferenceLines(); foreach(AllPlot *plot, window->allPlots) { plot->refreshReferenceLines(); } foreach(AllPlot *plot, window->seriesPlots) { plot->refreshReferenceLines(); } } void AllPlot::confirmTmpReference(double value, int axis, bool allowDelete) { // not supported in compare mode if (window == NULL || context->isCompareIntervals) return; ReferenceLineDialog *p = new ReferenceLineDialog(this, context, allowDelete); p->setWindowModality(Qt::ApplicationModal); // don't allow select other ride or it all goes wrong! p->setValueForAxis(value, axis); p->move(QCursor::pos()-QPoint(40,40)); p->exec(); } void AllPlot::setAltSlopePlotStyle (AllPlotSlopeCurve *curve){ if (bydist) { switch (showAltSlopeState) { case 0: {curve->setStyle(AllPlotSlopeCurve::SlopeDist1); break;} case 1: {curve->setStyle(AllPlotSlopeCurve::SlopeDist1); break;} case 2: {curve->setStyle(AllPlotSlopeCurve::SlopeDist2); break;} case 3: {curve->setStyle(AllPlotSlopeCurve::SlopeDist3); break;} } } else { switch (showAltSlopeState) { case 0: {curve->setStyle(AllPlotSlopeCurve::SlopeTime1); break;} case 1: {curve->setStyle(AllPlotSlopeCurve::SlopeTime1); break;} case 2: {curve->setStyle(AllPlotSlopeCurve::SlopeTime2); break;} case 3: {curve->setStyle(AllPlotSlopeCurve::SlopeTime3); break;} } } }
stigbd/GoldenCheetah
src/AllPlot.cpp
C++
gpl-2.0
266,861
<?php /** * @version $Id$ * @package Joomla.Site * @subpackage com_users * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; JHtml::_('behavior.mootools'); JHtml::_('behavior.formvalidation'); ?> <form action="<?php echo JRoute::_('index.php?option=com_users&task=reset.request'); ?>" method="post" class="form-validate"> <?php foreach ($this->form->getGroups() as $group): ?> <fieldset> <dl> <?php foreach ($this->form->getFields($group, $group) as $name => $field): ?> <dt><?php echo $field->label; ?></dt> <dd><?php echo $field->input; ?></dd> <?php endforeach; ?> </dl> </fieldset> <?php endforeach; ?> <button type="submit"><?php echo JText::_('BUTTON_SUBMIT'); ?></button> <input type="hidden" name="option" value="com_users" /> <input type="hidden" name="task" value="reset.request" /> <?php echo JHtml::_('form.token'); ?> </form>
joebushi/joomla
components/com_users/views/reset/tmpl/default.php
PHP
gpl-2.0
1,009
<?php if (substr($_SERVER['HTTP_HOST'], 0, 4) != 'www.') { header('Location: http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 's':'').'://' . "www.".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); exit; } include('config.php'); if (!class_exists('Database')) { include('lib/database.class.php'); } //Config Vars $database = new Database(); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'ambulance'); $row_ambulance = $database->single(); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'apiKey'); $row = $database->single(); define("KEY", htmlentities($row['settings_value'])); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'title'); $row = $database->single(); define("TITLE", htmlentities($row['settings_value'])); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'url'); $row = $database->single(); define("INIT_DIR", $row['settings_value']); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'desc'); $row = $database->single(); define("DESCRIPTION", strip_tags(utf8_encode(html_entity_decode($row['settings_value'])))); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'keywords'); $row = $database->single(); define("KEYWORDS", strip_tags(utf8_encode(html_entity_decode($row['settings_value'])))); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'cms_title'); $row = $database->single(); define("CMS_TITLE", $row['settings_value']); $database->query('SELECT * FROM settings WHERE settings_desc= :settings_desc'); $database->bind(':settings_desc', 'cms_subtitle'); $row = $database->single(); define("CMS_SUBTITLE", $row['settings_value']); define("COPY",'Desarrollo de: <a target="_blank" href="http://www.loop.mx">Loop Media</a> &copy; '.date("Y")); define("AUTHOR",'Oscar Azpeitia'); //frontend constants define("CSS_DIR", INIT_DIR."/css"); define("JS_DIR", INIT_DIR."/js"); define("IMG_DIR", INIT_DIR."/images"); // Admin globals if(SYSTEM_TYPE==1) { define("ADMIN_DIR", INIT_DIR."/admin"); define("GALERIA_DIR", "../images/galeria"); define("UPLOAD_DIR", "../images/uploads"); } else { define("ADMIN_DIR", INIT_DIR); define("GALERIA_DIR", "images/galeria"); define("UPLOAD_DIR", "images/uploads"); } define("ADMIN_CSS", ADMIN_DIR."/css"); define("ADMIN_JS", ADMIN_DIR."/js"); define("ADMIN_IMG", ADMIN_DIR."/images"); //Extras define("AVATAR_DIR", "images/avatar"); define("UPLOADS_REL", INIT_DIR."/images/uploads/"); define("UPLOADS_ABS", $_SERVER['DOCUMENT_ROOT'].'/images/uploads/'); define("ITEMSPP", 10); define("CMS_TITULO", CMS_TITLE.' <small>'.CMS_SUBTITLE.'</small>'); ?>
Zilus/cms
includes/globals.php
PHP
gpl-2.0
3,007
package com.vk.libs.appcommontest.gankio.mvp.data.requestbody; /** * Created by VK on 2017/2/8.<br/> * - 登录 */ public class LoginInfoReqParam { /* URL: /user/login.action param: { account: ‘admin’, password: ‘admin123’ } */ // {"j_mobile_mid":"864895022552002","j_pic_code":"4725", // "j_password":"841e5c1f5a8a9ebc34a723f66affb38787b9364f", // "j_app_version":"2.4.1_52_20170810","j_os_name":"samsung", // "j_mobile_type":"ZTE U795","j_os_sdk":"17", // "j_os_version":"Android4.2.2_JDQ39E","j_username":"leileima","salt":"b208cb62a85edb65d30f99ec3d08c434"} private String j_mobile_mid = "864895022552002"; private String j_pic_code ; private String j_password = "841e5c1f5a8a9ebc34a723f66affb38787b9364f"; private String j_app_version ="2.4.1_52_20170810"; private String j_os_name = "samsung"; private String j_mobile_type = "ZTE U795"; private String j_os_sdk = "17"; private String j_os_version = "Android4.2.2_JDQ39E"; private String j_username; private String salt; public LoginInfoReqParam(String account,String pwd,String picCode,String salt){ j_username = account; this.salt = salt; j_pic_code = picCode; } public String getJ_mobile_mid() { return j_mobile_mid; } public void setJ_mobile_mid(String j_mobile_mid) { this.j_mobile_mid = j_mobile_mid; } public String getJ_pic_code() { return j_pic_code; } public void setJ_pic_code(String j_pic_code) { this.j_pic_code = j_pic_code; } public String getJ_password() { return j_password; } public void setJ_password(String j_password) { this.j_password = j_password; } public String getJ_app_version() { return j_app_version; } public void setJ_app_version(String j_app_version) { this.j_app_version = j_app_version; } public String getJ_os_name() { return j_os_name; } public void setJ_os_name(String j_os_name) { this.j_os_name = j_os_name; } public String getJ_mobile_type() { return j_mobile_type; } public void setJ_mobile_type(String j_mobile_type) { this.j_mobile_type = j_mobile_type; } public String getJ_os_sdk() { return j_os_sdk; } public void setJ_os_sdk(String j_os_sdk) { this.j_os_sdk = j_os_sdk; } public String getJ_os_version() { return j_os_version; } public void setJ_os_version(String j_os_version) { this.j_os_version = j_os_version; } public String getJ_username() { return j_username; } public void setJ_username(String j_username) { this.j_username = j_username; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } }
VK2012/AppCommonFrame
app/src/main/java/com/vk/libs/appcommontest/gankio/mvp/data/requestbody/LoginInfoReqParam.java
Java
gpl-2.0
2,960
package com.tincent.demo.adapter; import java.util.ArrayList; import java.util.List; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.tincent.demo.R; import com.tincent.demo.activity.ImageDisplayActivity; import com.tincent.demo.activity.ImagePreviewActivity; import com.tincent.demo.model.AdBean; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; /** * 广告条适配器 * * @author hui.wang * @date 2015.3.25 * */ public class AdBannerAdapter extends PagerAdapter { private DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.banner_stub).showImageOnFail(R.drawable.banner_stub) .showImageOnLoading(R.drawable.banner_stub).resetViewBeforeLoading(true).cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565) .considerExifParams(true).displayer(new FadeInBitmapDisplayer(300)).build(); private List<AdBean> adList; private LayoutInflater inflater; private Context context; private ImageLoader imageLoader = ImageLoader.getInstance(); public AdBannerAdapter(Context ctx) { context = ctx; inflater = LayoutInflater.from(ctx); adList = new ArrayList<AdBean>(); AdBean bean = new AdBean(); bean.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201407291041466579.jpg"; //bean.httpurl = "http://mhospital.yihu.com/hospital/default.aspx?hospitalid=734&platformType=0&sourceType=1&sourceId=734"; AdBean bean1 = new AdBean(); bean1.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201401271110367821.jpg"; //bean1.httpurl = "http://88.88.88.197:8010/Summery/index.html?PatientId=108"; AdBean bean2 = new AdBean(); bean2.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201404090916310760.jpg"; //bean2.httpurl = "http://88.88.88.197:8010/ForTestRecover/index.html"; adList.add(bean); adList.add(bean1); adList.add(bean2); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = inflater.inflate(R.layout.image_pager_item, view, false); ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image); final int pos = position; imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ImagePreviewActivity.class); intent.putExtra("position", pos); intent.putStringArrayListExtra("uriList", (ArrayList<String>) getUriList()); context.startActivity(intent); } }); final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading); imageLoader.displayImage(adList.get(position).imgul, imageView, options, new SimpleImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { spinner.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { spinner.setVisibility(View.GONE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { spinner.setVisibility(View.GONE); } }); view.addView(imageLayout, 0); return imageLayout; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { if (adList != null) { return adList.size(); } return 0; } public String getItem(int position) { if (adList != null) { return adList.get(position).httpurl; } return null; } public List<String> getUriList() { if(adList != null) { List<String> uriList = new ArrayList<String>(); for(AdBean bean : adList) { uriList.add(bean.imgul); } return uriList; } return null; } public void updateDate(List<AdBean> list) { adList = list; notifyDataSetChanged(); } }
tincent/libtincent
appdemo/src/com/tincent/demo/adapter/AdBannerAdapter.java
Java
gpl-2.0
4,595
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "Config.h" #include "DatabaseEnv.h" #include "DBCStores.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "ScriptLoader.h" #include "ScriptSystem.h" #include "Transport.h" #include "Vehicle.h" #include "SpellInfo.h" #include "SpellScript.h" #include "GossipDef.h" #include "CreatureAI.h" #include "sc_npc_teleport.h" // This is the global static registry of scripts. template<class TScript> class ScriptRegistry { public: typedef std::map<uint32, TScript*> ScriptMap; typedef typename ScriptMap::iterator ScriptMapIterator; // The actual list of scripts. This will be accessed concurrently, so it must not be modified // after server startup. static ScriptMap ScriptPointerList; static void AddScript(TScript* const script) { ASSERT(script); // See if the script is using the same memory as another script. If this happens, it means that // someone forgot to allocate new memory for a script. for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) { if (it->second == script) { sLog->outError(LOG_FILTER_TSCR, "Script '%s' has same memory pointer as '%s'.", script->GetName().c_str(), it->second->GetName().c_str()); return; } } if (script->IsDatabaseBound()) { // Get an ID for the script. An ID only exists if it's a script that is assigned in the database // through a script name (or similar). uint32 id = sObjectMgr->GetScriptId(script->GetName().c_str()); if (id) { // Try to find an existing script. bool existing = false; for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) { // If the script names match... if (it->second->GetName() == script->GetName()) { // ... It exists. existing = true; break; } } // If the script isn't assigned -> assign it! if (!existing) { ScriptPointerList[id] = script; sScriptMgr->IncrementScriptCount(); } else { // If the script is already assigned -> delete it! sLog->outError(LOG_FILTER_TSCR, "Script '%s' already assigned with the same script name, so the script can't work.", script->GetName().c_str()); ASSERT(false); // Error that should be fixed ASAP. } } else { // The script uses a script name from database, but isn't assigned to anything. if (script->GetName().find("example") == std::string::npos && script->GetName().find("Smart") == std::string::npos) sLog->outError(LOG_FILTER_SQL, "Script named '%s' does not have a script name assigned in database.", script->GetName().c_str()); } } else { // We're dealing with a code-only script; just add it. ScriptPointerList[_scriptIdCounter++] = script; sScriptMgr->IncrementScriptCount(); } } // Gets a script by its ID (assigned by ObjectMgr). static TScript* GetScriptById(uint32 id) { ScriptMapIterator it = ScriptPointerList.find(id); if (it != ScriptPointerList.end()) return it->second; return NULL; } private: // Counter used for code-only scripts. static uint32 _scriptIdCounter; }; // Utility macros to refer to the script registry. #define SCR_REG_MAP(T) ScriptRegistry<T>::ScriptMap #define SCR_REG_ITR(T) ScriptRegistry<T>::ScriptMapIterator #define SCR_REG_LST(T) ScriptRegistry<T>::ScriptPointerList // Utility macros for looping over scripts. #define FOR_SCRIPTS(T, C, E) \ if (SCR_REG_LST(T).empty()) \ return; \ for (SCR_REG_ITR(T) C = SCR_REG_LST(T).begin(); \ C != SCR_REG_LST(T).end(); ++C) #define FOR_SCRIPTS_RET(T, C, E, R) \ if (SCR_REG_LST(T).empty()) \ return R; \ for (SCR_REG_ITR(T) C = SCR_REG_LST(T).begin(); \ C != SCR_REG_LST(T).end(); ++C) #define FOREACH_SCRIPT(T) \ FOR_SCRIPTS(T, itr, end) \ itr->second // Utility macros for finding specific scripts. #define GET_SCRIPT(T, I, V) \ T* V = ScriptRegistry<T>::GetScriptById(I); \ if (!V) \ return; #define GET_SCRIPT_RET(T, I, V, R) \ T* V = ScriptRegistry<T>::GetScriptById(I); \ if (!V) \ return R; void DoScriptText(int32 iTextEntry, WorldObject* pSource, Unit* target) { if (!pSource) { sLog->outError(LOG_FILTER_TSCR, "DoScriptText entry %i, invalid Source pointer.", iTextEntry); return; } if (iTextEntry >= 0) { sLog->outError(LOG_FILTER_TSCR, "DoScriptText with source entry %u (TypeId=%u, guid=%u) attempts to process text entry %i, but text entry must be negative.", pSource->GetEntry(), pSource->GetTypeId(), pSource->GetGUIDLow(), iTextEntry); return; } const StringTextData* pData = sScriptSystemMgr->GetTextData(iTextEntry); if (!pData) { sLog->outError(LOG_FILTER_TSCR, "DoScriptText with source entry %u (TypeId=%u, guid=%u) could not find text entry %i.", pSource->GetEntry(), pSource->GetTypeId(), pSource->GetGUIDLow(), iTextEntry); return; } sLog->outDebug(LOG_FILTER_TSCR, "DoScriptText: text entry=%i, Sound=%u, Type=%u, Language=%u, Emote=%u", iTextEntry, pData->uiSoundId, pData->uiType, pData->uiLanguage, pData->uiEmote); if (pData->uiSoundId) { if (sSoundEntriesStore.LookupEntry(pData->uiSoundId)) pSource->SendPlaySound(pData->uiSoundId, false); else sLog->outError(LOG_FILTER_TSCR, "DoScriptText entry %i tried to process invalid sound id %u.", iTextEntry, pData->uiSoundId); } if (pData->uiEmote) { if (pSource->GetTypeId() == TYPEID_UNIT || pSource->GetTypeId() == TYPEID_PLAYER) ((Unit*)pSource)->HandleEmoteCommand(pData->uiEmote); else sLog->outError(LOG_FILTER_TSCR, "DoScriptText entry %i tried to process emote for invalid TypeId (%u).", iTextEntry, pSource->GetTypeId()); } switch (pData->uiType) { case CHAT_TYPE_SAY: pSource->MonsterSay(iTextEntry, pData->uiLanguage, target ? target->GetGUID() : 0); break; case CHAT_TYPE_YELL: pSource->MonsterYell(iTextEntry, pData->uiLanguage, target ? target->GetGUID() : 0); break; case CHAT_TYPE_TEXT_EMOTE: pSource->MonsterTextEmote(iTextEntry, target ? target->GetGUID() : 0); break; case CHAT_TYPE_BOSS_EMOTE: pSource->MonsterTextEmote(iTextEntry, target ? target->GetGUID() : 0, true); break; case CHAT_TYPE_WHISPER: { if (target && target->GetTypeId() == TYPEID_PLAYER) pSource->MonsterWhisper(iTextEntry, target->GetGUID()); else sLog->outError(LOG_FILTER_TSCR, "DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", iTextEntry); break; } case CHAT_TYPE_BOSS_WHISPER: { if (target && target->GetTypeId() == TYPEID_PLAYER) pSource->MonsterWhisper(iTextEntry, target->GetGUID(), true); else sLog->outError(LOG_FILTER_TSCR, "DoScriptText entry %i cannot whisper without target unit (TYPEID_PLAYER).", iTextEntry); break; } case CHAT_TYPE_ZONE_YELL: pSource->MonsterYellToZone(iTextEntry, pData->uiLanguage, target ? target->GetGUID() : 0); break; } } ScriptMgr::ScriptMgr() : _scriptCount(0), _scheduledScripts(0) { } ScriptMgr::~ScriptMgr() { } void ScriptMgr::Initialize() { uint32 oldMSTime = getMSTime(); LoadDatabase(); // Load TeleNPC2 - maybe not the best place to load it ... LoadNpcTele(); sLog->outInfo(LOG_FILTER_SERVER_LOADING, "Loading C++ scripts"); FillSpellSummary(); AddScripts(); sLog->outInfo(LOG_FILTER_SERVER_LOADING, ">> Loaded %u C++ scripts in %u ms", GetScriptCount(), GetMSTimeDiffToNow(oldMSTime)); } void ScriptMgr::Unload() { #define SCR_CLEAR(T) \ for (SCR_REG_ITR(T) itr = SCR_REG_LST(T).begin(); itr != SCR_REG_LST(T).end(); ++itr) \ delete itr->second; \ SCR_REG_LST(T).clear(); // Clear scripts for every script type. SCR_CLEAR(SpellScriptLoader); SCR_CLEAR(ServerScript); SCR_CLEAR(WorldScript); SCR_CLEAR(FormulaScript); SCR_CLEAR(WorldMapScript); SCR_CLEAR(InstanceMapScript); SCR_CLEAR(BattlegroundMapScript); SCR_CLEAR(ItemScript); SCR_CLEAR(CreatureScript); SCR_CLEAR(GameObjectScript); SCR_CLEAR(AreaTriggerScript); SCR_CLEAR(BattlegroundScript); SCR_CLEAR(OutdoorPvPScript); SCR_CLEAR(CommandScript); SCR_CLEAR(WeatherScript); SCR_CLEAR(AuctionHouseScript); SCR_CLEAR(ConditionScript); SCR_CLEAR(VehicleScript); SCR_CLEAR(DynamicObjectScript); SCR_CLEAR(TransportScript); SCR_CLEAR(AchievementCriteriaScript); SCR_CLEAR(PlayerScript); SCR_CLEAR(GuildScript); SCR_CLEAR(GroupScript); #undef SCR_CLEAR } void ScriptMgr::LoadDatabase() { sScriptSystemMgr->LoadScriptTexts(); sScriptSystemMgr->LoadScriptTextsCustom(); sScriptSystemMgr->LoadScriptWaypoints(); } struct TSpellSummary { uint8 Targets; // set of enum SelectTarget uint8 Effects; // set of enum SelectEffect } *SpellSummary; void ScriptMgr::FillSpellSummary() { SpellSummary = new TSpellSummary[sSpellMgr->GetSpellInfoStoreSize()]; SpellInfo const* pTempSpell; for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i) { SpellSummary[i].Effects = 0; SpellSummary[i].Targets = 0; pTempSpell = sSpellMgr->GetSpellInfo(i); // This spell doesn't exist. if (!pTempSpell) continue; for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { // Spell targets self. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SELF-1); // Spell targets a single enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_ENEMY-1); // Spell targets AoE at enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_ENEMY-1); // Spell targets an enemy. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_TARGET_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_SRC_AREA_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_DEST_AREA_ENEMY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_DEST_DYNOBJ_ENEMY) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_ENEMY-1); // Spell targets a single friend (or self). if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_SINGLE_FRIEND-1); // Spell targets AoE friends. if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER_AREA_PARTY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_AOE_FRIEND-1); // Spell targets any friend (or self). if (pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_ALLY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_TARGET_PARTY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_CASTER_AREA_PARTY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_UNIT_LASTTARGET_AREA_PARTY || pTempSpell->Effects[j].TargetA.GetTarget() == TARGET_SRC_CASTER) SpellSummary[i].Targets |= 1 << (SELECT_TARGET_ANY_FRIEND-1); // Make sure that this spell includes a damage effect. if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_SCHOOL_DAMAGE || pTempSpell->Effects[j].Effect == SPELL_EFFECT_INSTAKILL || pTempSpell->Effects[j].Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE || pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEALTH_LEECH) SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_DAMAGE-1); // Make sure that this spell includes a healing effect (or an apply aura with a periodic heal). if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL || pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MAX_HEALTH || pTempSpell->Effects[j].Effect == SPELL_EFFECT_HEAL_MECHANICAL || (pTempSpell->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA && pTempSpell->Effects[j].ApplyAuraName == 8)) SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_HEALING-1); // Make sure that this spell applies an aura. if (pTempSpell->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) SpellSummary[i].Effects |= 1 << (SELECT_EFFECT_AURA-1); } } } void ScriptMgr::CreateSpellScripts(uint32 spellId, std::list<SpellScript*>& scriptVector) { SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) { SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); if (!tmpscript) continue; SpellScript* script = tmpscript->GetSpellScript(); if (!script) continue; script->_Init(&tmpscript->GetName(), spellId); scriptVector.push_back(script); } } void ScriptMgr::CreateAuraScripts(uint32 spellId, std::list<AuraScript*>& scriptVector) { SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) { SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); if (!tmpscript) continue; AuraScript* script = tmpscript->GetAuraScript(); if (!script) continue; script->_Init(&tmpscript->GetName(), spellId); scriptVector.push_back(script); } } void ScriptMgr::CreateSpellScriptLoaders(uint32 spellId, std::vector<std::pair<SpellScriptLoader*, SpellScriptsContainer::iterator> >& scriptVector) { SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); scriptVector.reserve(std::distance(bounds.first, bounds.second)); for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) { SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); if (!tmpscript) continue; scriptVector.push_back(std::make_pair(tmpscript, itr)); } } void ScriptMgr::OnNetworkStart() { FOREACH_SCRIPT(ServerScript)->OnNetworkStart(); } void ScriptMgr::OnNetworkStop() { FOREACH_SCRIPT(ServerScript)->OnNetworkStop(); } void ScriptMgr::OnSocketOpen(WorldSocket* socket) { ASSERT(socket); FOREACH_SCRIPT(ServerScript)->OnSocketOpen(socket); } void ScriptMgr::OnSocketClose(WorldSocket* socket, bool wasNew) { ASSERT(socket); FOREACH_SCRIPT(ServerScript)->OnSocketClose(socket, wasNew); } void ScriptMgr::OnPacketReceive(WorldSocket* socket, WorldPacket packet) { ASSERT(socket); FOREACH_SCRIPT(ServerScript)->OnPacketReceive(socket, packet); } void ScriptMgr::OnPacketSend(WorldSocket* socket, WorldPacket packet) { ASSERT(socket); FOREACH_SCRIPT(ServerScript)->OnPacketSend(socket, packet); } void ScriptMgr::OnUnknownPacketReceive(WorldSocket* socket, WorldPacket packet) { ASSERT(socket); FOREACH_SCRIPT(ServerScript)->OnUnknownPacketReceive(socket, packet); } void ScriptMgr::OnOpenStateChange(bool open) { FOREACH_SCRIPT(WorldScript)->OnOpenStateChange(open); } void ScriptMgr::OnConfigLoad(bool reload) { FOREACH_SCRIPT(WorldScript)->OnConfigLoad(reload); } void ScriptMgr::OnMotdChange(std::string& newMotd) { FOREACH_SCRIPT(WorldScript)->OnMotdChange(newMotd); } void ScriptMgr::OnShutdownInitiate(ShutdownExitCode code, ShutdownMask mask) { FOREACH_SCRIPT(WorldScript)->OnShutdownInitiate(code, mask); } void ScriptMgr::OnShutdownCancel() { FOREACH_SCRIPT(WorldScript)->OnShutdownCancel(); } void ScriptMgr::OnWorldUpdate(uint32 diff) { FOREACH_SCRIPT(WorldScript)->OnUpdate(diff); } void ScriptMgr::OnHonorCalculation(float& honor, uint8 level, float multiplier) { FOREACH_SCRIPT(FormulaScript)->OnHonorCalculation(honor, level, multiplier); } void ScriptMgr::OnGrayLevelCalculation(uint8& grayLevel, uint8 playerLevel) { FOREACH_SCRIPT(FormulaScript)->OnGrayLevelCalculation(grayLevel, playerLevel); } void ScriptMgr::OnColorCodeCalculation(XPColorChar& color, uint8 playerLevel, uint8 mobLevel) { FOREACH_SCRIPT(FormulaScript)->OnColorCodeCalculation(color, playerLevel, mobLevel); } void ScriptMgr::OnZeroDifferenceCalculation(uint8& diff, uint8 playerLevel) { FOREACH_SCRIPT(FormulaScript)->OnZeroDifferenceCalculation(diff, playerLevel); } void ScriptMgr::OnBaseGainCalculation(uint32& gain, uint8 playerLevel, uint8 mobLevel, ContentLevels content) { FOREACH_SCRIPT(FormulaScript)->OnBaseGainCalculation(gain, playerLevel, mobLevel, content); } void ScriptMgr::OnGainCalculation(uint32& gain, Player* player, Unit* unit) { ASSERT(player); ASSERT(unit); FOREACH_SCRIPT(FormulaScript)->OnGainCalculation(gain, player, unit); } void ScriptMgr::OnGroupRateCalculation(float& rate, uint32 count, bool isRaid) { FOREACH_SCRIPT(FormulaScript)->OnGroupRateCalculation(rate, count, isRaid); } #define SCR_MAP_BGN(M, V, I, E, C, T) \ if (V->GetEntry()->T()) \ { \ FOR_SCRIPTS(M, I, E) \ { \ MapEntry const* C = I->second->GetEntry(); \ if (!C) \ continue; \ if (entry->MapID == V->GetId()) \ { #define SCR_MAP_END \ return; \ } \ } \ } void ScriptMgr::OnCreateMap(Map* map) { ASSERT(map); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnCreate(map); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnCreate((InstanceMap*)map); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnCreate((BattlegroundMap*)map); SCR_MAP_END; } void ScriptMgr::OnDestroyMap(Map* map) { ASSERT(map); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnDestroy(map); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnDestroy((InstanceMap*)map); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnDestroy((BattlegroundMap*)map); SCR_MAP_END; } void ScriptMgr::OnLoadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy) { ASSERT(map); ASSERT(gmap); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnLoadGridMap(map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnLoadGridMap((InstanceMap*)map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnLoadGridMap((BattlegroundMap*)map, gmap, gx, gy); SCR_MAP_END; } void ScriptMgr::OnUnloadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy) { ASSERT(map); ASSERT(gmap); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnUnloadGridMap(map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnUnloadGridMap((InstanceMap*)map, gmap, gx, gy); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnUnloadGridMap((BattlegroundMap*)map, gmap, gx, gy); SCR_MAP_END; } void ScriptMgr::OnPlayerEnterMap(Map* map, Player* player) { ASSERT(map); ASSERT(player); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnPlayerEnter(map, player); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnPlayerEnter((InstanceMap*)map, player); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnPlayerEnter((BattlegroundMap*)map, player); SCR_MAP_END; } void ScriptMgr::OnPlayerLeaveMap(Map* map, Player* player) { ASSERT(map); ASSERT(player); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnPlayerLeave(map, player); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnPlayerLeave((InstanceMap*)map, player); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnPlayerLeave((BattlegroundMap*)map, player); SCR_MAP_END; } void ScriptMgr::OnMapUpdate(Map* map, uint32 diff) { ASSERT(map); SCR_MAP_BGN(WorldMapScript, map, itr, end, entry, IsWorldMap); itr->second->OnUpdate(map, diff); SCR_MAP_END; SCR_MAP_BGN(InstanceMapScript, map, itr, end, entry, IsDungeon); itr->second->OnUpdate((InstanceMap*)map, diff); SCR_MAP_END; SCR_MAP_BGN(BattlegroundMapScript, map, itr, end, entry, IsBattleground); itr->second->OnUpdate((BattlegroundMap*)map, diff); SCR_MAP_END; } #undef SCR_MAP_BGN #undef SCR_MAP_END InstanceScript* ScriptMgr::CreateInstanceData(InstanceMap* map) { ASSERT(map); GET_SCRIPT_RET(InstanceMapScript, map->GetScriptId(), tmpscript, NULL); return tmpscript->GetInstanceScript(map); } bool ScriptMgr::OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, Item* target) { ASSERT(caster); ASSERT(target); GET_SCRIPT_RET(ItemScript, target->GetScriptId(), tmpscript, false); return tmpscript->OnDummyEffect(caster, spellId, effIndex, target); } bool ScriptMgr::OnQuestAccept(Player* player, Item* item, Quest const* quest) { ASSERT(player); ASSERT(item); ASSERT(quest); GET_SCRIPT_RET(ItemScript, item->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestAccept(player, item, quest); } bool ScriptMgr::OnItemUse(Player* player, Item* item, SpellCastTargets const& targets) { ASSERT(player); ASSERT(item); GET_SCRIPT_RET(ItemScript, item->GetScriptId(), tmpscript, false); return tmpscript->OnUse(player, item, targets); } bool ScriptMgr::OnItemExpire(Player* player, ItemTemplate const* proto) { ASSERT(player); ASSERT(proto); GET_SCRIPT_RET(ItemScript, proto->ScriptId, tmpscript, false); return tmpscript->OnExpire(player, proto); } bool ScriptMgr::OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, Creature* target) { ASSERT(caster); ASSERT(target); GET_SCRIPT_RET(CreatureScript, target->GetScriptId(), tmpscript, false); return tmpscript->OnDummyEffect(caster, spellId, effIndex, target); } bool ScriptMgr::OnGossipHello(Player* player, Creature* creature) { ASSERT(player); ASSERT(creature); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnGossipHello(player, creature); } bool ScriptMgr::OnGossipSelect(Player* player, Creature* creature, uint32 sender, uint32 action) { ASSERT(player); ASSERT(creature); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); return tmpscript->OnGossipSelect(player, creature, sender, action); } bool ScriptMgr::OnGossipSelectCode(Player* player, Creature* creature, uint32 sender, uint32 action, const char* code) { ASSERT(player); ASSERT(creature); ASSERT(code); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); return tmpscript->OnGossipSelectCode(player, creature, sender, action, code); } bool ScriptMgr::OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { ASSERT(player); ASSERT(creature); ASSERT(quest); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestAccept(player, creature, quest); } bool ScriptMgr::OnQuestSelect(Player* player, Creature* creature, Quest const* quest) { ASSERT(player); ASSERT(creature); ASSERT(quest); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestSelect(player, creature, quest); } bool ScriptMgr::OnQuestComplete(Player* player, Creature* creature, Quest const* quest) { ASSERT(player); ASSERT(creature); ASSERT(quest); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestComplete(player, creature, quest); } bool ScriptMgr::OnQuestReward(Player* player, Creature* creature, Quest const* quest, uint32 opt) { ASSERT(player); ASSERT(creature); ASSERT(quest); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestReward(player, creature, quest, opt); } uint32 ScriptMgr::GetDialogStatus(Player* player, Creature* creature) { ASSERT(player); ASSERT(creature); // TODO: 100 is a funny magic number to have hanging around here... GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, 100); player->PlayerTalkClass->ClearMenus(); return tmpscript->GetDialogStatus(player, creature); } CreatureAI* ScriptMgr::GetCreatureAI(Creature* creature) { ASSERT(creature); GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, NULL); return tmpscript->GetAI(creature); } GameObjectAI* ScriptMgr::GetGameObjectAI(GameObject* gameobject) { ASSERT(gameobject); GET_SCRIPT_RET(GameObjectScript, gameobject->GetScriptId(), tmpscript, NULL); return tmpscript->GetAI(gameobject); } void ScriptMgr::OnCreatureUpdate(Creature* creature, uint32 diff) { ASSERT(creature); GET_SCRIPT(CreatureScript, creature->GetScriptId(), tmpscript); tmpscript->OnUpdate(creature, diff); } bool ScriptMgr::OnGossipHello(Player* player, GameObject* go) { ASSERT(player); ASSERT(go); GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnGossipHello(player, go); } bool ScriptMgr::OnGossipSelect(Player* player, GameObject* go, uint32 sender, uint32 action) { ASSERT(player); ASSERT(go); GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, false); return tmpscript->OnGossipSelect(player, go, sender, action); } bool ScriptMgr::OnGossipSelectCode(Player* player, GameObject* go, uint32 sender, uint32 action, const char* code) { ASSERT(player); ASSERT(go); ASSERT(code); GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, false); return tmpscript->OnGossipSelectCode(player, go, sender, action, code); } bool ScriptMgr::OnQuestAccept(Player* player, GameObject* go, Quest const* quest) { ASSERT(player); ASSERT(go); ASSERT(quest); GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestAccept(player, go, quest); } bool ScriptMgr::OnQuestReward(Player* player, GameObject* go, Quest const* quest, uint32 opt) { ASSERT(player); ASSERT(go); ASSERT(quest); GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, false); player->PlayerTalkClass->ClearMenus(); return tmpscript->OnQuestReward(player, go, quest, opt); } uint32 ScriptMgr::GetDialogStatus(Player* player, GameObject* go) { ASSERT(player); ASSERT(go); // TODO: 100 is a funny magic number to have hanging around here... GET_SCRIPT_RET(GameObjectScript, go->GetScriptId(), tmpscript, 100); player->PlayerTalkClass->ClearMenus(); return tmpscript->GetDialogStatus(player, go); } void ScriptMgr::OnGameObjectDestroyed(GameObject* go, Player* player) { ASSERT(go); GET_SCRIPT(GameObjectScript, go->GetScriptId(), tmpscript); tmpscript->OnDestroyed(go, player); } void ScriptMgr::OnGameObjectDamaged(GameObject* go, Player* player) { ASSERT(go); GET_SCRIPT(GameObjectScript, go->GetScriptId(), tmpscript); tmpscript->OnDamaged(go, player); } void ScriptMgr::OnGameObjectLootStateChanged(GameObject* go, uint32 state, Unit* unit) { ASSERT(go); GET_SCRIPT(GameObjectScript, go->GetScriptId(), tmpscript); tmpscript->OnLootStateChanged(go, state, unit); } void ScriptMgr::OnGameObjectStateChanged(GameObject* go, uint32 state) { ASSERT(go); GET_SCRIPT(GameObjectScript, go->GetScriptId(), tmpscript); tmpscript->OnGameObjectStateChanged(go, state); } void ScriptMgr::OnGameObjectUpdate(GameObject* go, uint32 diff) { ASSERT(go); GET_SCRIPT(GameObjectScript, go->GetScriptId(), tmpscript); tmpscript->OnUpdate(go, diff); } bool ScriptMgr::OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, GameObject* target) { ASSERT(caster); ASSERT(target); GET_SCRIPT_RET(GameObjectScript, target->GetScriptId(), tmpscript, false); return tmpscript->OnDummyEffect(caster, spellId, effIndex, target); } bool ScriptMgr::OnAreaTrigger(Player* player, AreaTriggerEntry const* trigger) { ASSERT(player); ASSERT(trigger); GET_SCRIPT_RET(AreaTriggerScript, sObjectMgr->GetAreaTriggerScriptId(trigger->id), tmpscript, false); return tmpscript->OnTrigger(player, trigger); } Battleground* ScriptMgr::CreateBattleground(BattlegroundTypeId /*typeId*/) { // TODO: Implement script-side battlegrounds. ASSERT(false); return NULL; } OutdoorPvP* ScriptMgr::CreateOutdoorPvP(OutdoorPvPData const* data) { ASSERT(data); GET_SCRIPT_RET(OutdoorPvPScript, data->ScriptId, tmpscript, NULL); return tmpscript->GetOutdoorPvP(); } std::vector<ChatCommand*> ScriptMgr::GetChatCommands() { std::vector<ChatCommand*> table; FOR_SCRIPTS_RET(CommandScript, itr, end, table) table.push_back(itr->second->GetCommands()); return table; } void ScriptMgr::OnWeatherChange(Weather* weather, WeatherState state, float grade) { ASSERT(weather); GET_SCRIPT(WeatherScript, weather->GetScriptId(), tmpscript); tmpscript->OnChange(weather, state, grade); } void ScriptMgr::OnWeatherUpdate(Weather* weather, uint32 diff) { ASSERT(weather); GET_SCRIPT(WeatherScript, weather->GetScriptId(), tmpscript); tmpscript->OnUpdate(weather, diff); } void ScriptMgr::OnAuctionAdd(AuctionHouseObject* ah, AuctionEntry* entry) { ASSERT(ah); ASSERT(entry); FOREACH_SCRIPT(AuctionHouseScript)->OnAuctionAdd(ah, entry); } void ScriptMgr::OnAuctionRemove(AuctionHouseObject* ah, AuctionEntry* entry) { ASSERT(ah); ASSERT(entry); FOREACH_SCRIPT(AuctionHouseScript)->OnAuctionRemove(ah, entry); } void ScriptMgr::OnAuctionSuccessful(AuctionHouseObject* ah, AuctionEntry* entry) { ASSERT(ah); ASSERT(entry); FOREACH_SCRIPT(AuctionHouseScript)->OnAuctionSuccessful(ah, entry); } void ScriptMgr::OnAuctionExpire(AuctionHouseObject* ah, AuctionEntry* entry) { ASSERT(ah); ASSERT(entry); FOREACH_SCRIPT(AuctionHouseScript)->OnAuctionExpire(ah, entry); } bool ScriptMgr::OnConditionCheck(Condition* condition, ConditionSourceInfo& sourceInfo) { ASSERT(condition); GET_SCRIPT_RET(ConditionScript, condition->ScriptId, tmpscript, true); return tmpscript->OnConditionCheck(condition, sourceInfo); } void ScriptMgr::OnInstall(Vehicle* veh) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnInstall(veh); } void ScriptMgr::OnUninstall(Vehicle* veh) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnUninstall(veh); } void ScriptMgr::OnReset(Vehicle* veh) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnReset(veh); } void ScriptMgr::OnInstallAccessory(Vehicle* veh, Creature* accessory) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); ASSERT(accessory); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnInstallAccessory(veh, accessory); } void ScriptMgr::OnAddPassenger(Vehicle* veh, Unit* passenger, int8 seatId) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); ASSERT(passenger); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnAddPassenger(veh, passenger, seatId); } void ScriptMgr::OnRemovePassenger(Vehicle* veh, Unit* passenger) { ASSERT(veh); ASSERT(veh->GetBase()->GetTypeId() == TYPEID_UNIT); ASSERT(passenger); GET_SCRIPT(VehicleScript, veh->GetBase()->ToCreature()->GetScriptId(), tmpscript); tmpscript->OnRemovePassenger(veh, passenger); } void ScriptMgr::OnDynamicObjectUpdate(DynamicObject* dynobj, uint32 diff) { ASSERT(dynobj); FOR_SCRIPTS(DynamicObjectScript, itr, end) itr->second->OnUpdate(dynobj, diff); } void ScriptMgr::OnAddPassenger(Transport* transport, Player* player) { ASSERT(transport); ASSERT(player); GET_SCRIPT(TransportScript, transport->GetScriptId(), tmpscript); tmpscript->OnAddPassenger(transport, player); } void ScriptMgr::OnAddCreaturePassenger(Transport* transport, Creature* creature) { ASSERT(transport); ASSERT(creature); GET_SCRIPT(TransportScript, transport->GetScriptId(), tmpscript); tmpscript->OnAddCreaturePassenger(transport, creature); } void ScriptMgr::OnRemovePassenger(Transport* transport, Player* player) { ASSERT(transport); ASSERT(player); GET_SCRIPT(TransportScript, transport->GetScriptId(), tmpscript); tmpscript->OnRemovePassenger(transport, player); } void ScriptMgr::OnTransportUpdate(Transport* transport, uint32 diff) { ASSERT(transport); GET_SCRIPT(TransportScript, transport->GetScriptId(), tmpscript); tmpscript->OnUpdate(transport, diff); } void ScriptMgr::OnRelocate(Transport* transport, uint32 waypointId, uint32 mapId, float x, float y, float z) { GET_SCRIPT(TransportScript, transport->GetScriptId(), tmpscript); tmpscript->OnRelocate(transport, waypointId, mapId, x, y, z); } void ScriptMgr::OnStartup() { FOREACH_SCRIPT(WorldScript)->OnStartup(); } void ScriptMgr::OnShutdown() { FOREACH_SCRIPT(WorldScript)->OnShutdown(); } bool ScriptMgr::OnCriteriaCheck(AchievementCriteriaData const* data, Player* source, Unit* target) { ASSERT(source); // target can be NULL. GET_SCRIPT_RET(AchievementCriteriaScript, data->ScriptId, tmpscript, false); return tmpscript->OnCheck(source, target); } // Player void ScriptMgr::OnPVPKill(Player* killer, Player* killed) { FOREACH_SCRIPT(PlayerScript)->OnPVPKill(killer, killed); } void ScriptMgr::OnCreatureKill(Player* killer, Creature* killed) { FOREACH_SCRIPT(PlayerScript)->OnCreatureKill(killer, killed); } void ScriptMgr::OnPlayerKilledByCreature(Creature* killer, Player* killed) { FOREACH_SCRIPT(PlayerScript)->OnPlayerKilledByCreature(killer, killed); } void ScriptMgr::OnPlayerLevelChanged(Player* player, uint8 oldLevel) { FOREACH_SCRIPT(PlayerScript)->OnLevelChanged(player, oldLevel); } void ScriptMgr::OnPlayerFreeTalentPointsChanged(Player* player, uint32 points) { FOREACH_SCRIPT(PlayerScript)->OnFreeTalentPointsChanged(player, points); } void ScriptMgr::OnPlayerTalentsReset(Player* player, bool noCost) { FOREACH_SCRIPT(PlayerScript)->OnTalentsReset(player, noCost); } void ScriptMgr::OnPlayerMoneyChanged(Player* player, int32& amount) { FOREACH_SCRIPT(PlayerScript)->OnMoneyChanged(player, amount); } void ScriptMgr::OnGivePlayerXP(Player* player, uint32& amount, Unit* victim) { FOREACH_SCRIPT(PlayerScript)->OnGiveXP(player, amount, victim); } void ScriptMgr::OnPlayerReputationChange(Player* player, uint32 factionID, int32& standing, bool incremental) { FOREACH_SCRIPT(PlayerScript)->OnReputationChange(player, factionID, standing, incremental); } void ScriptMgr::OnPlayerDuelRequest(Player* target, Player* challenger) { FOREACH_SCRIPT(PlayerScript)->OnDuelRequest(target, challenger); } void ScriptMgr::OnPlayerDuelStart(Player* player1, Player* player2) { FOREACH_SCRIPT(PlayerScript)->OnDuelStart(player1, player2); } void ScriptMgr::OnPlayerDuelEnd(Player* winner, Player* loser, DuelCompleteType type) { FOREACH_SCRIPT(PlayerScript)->OnDuelEnd(winner, loser, type); } void ScriptMgr::OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg) { FOREACH_SCRIPT(PlayerScript)->OnChat(player, type, lang, msg); } void ScriptMgr::OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Player* receiver) { FOREACH_SCRIPT(PlayerScript)->OnChat(player, type, lang, msg, receiver); } void ScriptMgr::OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Group* group) { FOREACH_SCRIPT(PlayerScript)->OnChat(player, type, lang, msg, group); } void ScriptMgr::OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Guild* guild) { FOREACH_SCRIPT(PlayerScript)->OnChat(player, type, lang, msg, guild); } void ScriptMgr::OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string& msg, Channel* channel) { FOREACH_SCRIPT(PlayerScript)->OnChat(player, type, lang, msg, channel); } void ScriptMgr::OnPlayerEmote(Player* player, uint32 emote) { FOREACH_SCRIPT(PlayerScript)->OnEmote(player, emote); } void ScriptMgr::OnPlayerTextEmote(Player* player, uint32 textEmote, uint32 emoteNum, uint64 guid) { FOREACH_SCRIPT(PlayerScript)->OnTextEmote(player, textEmote, emoteNum, guid); } void ScriptMgr::OnPlayerSpellCast(Player* player, Spell* spell, bool skipCheck) { FOREACH_SCRIPT(PlayerScript)->OnSpellCast(player, spell, skipCheck); } void ScriptMgr::OnPlayerLogin(Player* player) { FOREACH_SCRIPT(PlayerScript)->OnLogin(player); } void ScriptMgr::OnPlayerLogout(Player* player) { FOREACH_SCRIPT(PlayerScript)->OnLogout(player); } void ScriptMgr::OnPlayerCreate(Player* player) { FOREACH_SCRIPT(PlayerScript)->OnCreate(player); } void ScriptMgr::OnPlayerDelete(uint64 guid) { FOREACH_SCRIPT(PlayerScript)->OnDelete(guid); } void ScriptMgr::OnPlayerBindToInstance(Player* player, Difficulty difficulty, uint32 mapid, bool permanent) { FOREACH_SCRIPT(PlayerScript)->OnBindToInstance(player, difficulty, mapid, permanent); } void ScriptMgr::OnPlayerUpdateZone(Player* player, uint32 newZone, uint32 newArea) { FOREACH_SCRIPT(PlayerScript)->OnUpdateZone(player, newZone, newArea); } // Guild void ScriptMgr::OnGuildAddMember(Guild* guild, Player* player, uint8& plRank) { FOREACH_SCRIPT(GuildScript)->OnAddMember(guild, player, plRank); } void ScriptMgr::OnGuildRemoveMember(Guild* guild, Player* player, bool isDisbanding, bool isKicked) { FOREACH_SCRIPT(GuildScript)->OnRemoveMember(guild, player, isDisbanding, isKicked); } void ScriptMgr::OnGuildMOTDChanged(Guild* guild, const std::string& newMotd) { FOREACH_SCRIPT(GuildScript)->OnMOTDChanged(guild, newMotd); } void ScriptMgr::OnGuildInfoChanged(Guild* guild, const std::string& newInfo) { FOREACH_SCRIPT(GuildScript)->OnInfoChanged(guild, newInfo); } void ScriptMgr::OnGuildCreate(Guild* guild, Player* leader, const std::string& name) { FOREACH_SCRIPT(GuildScript)->OnCreate(guild, leader, name); } void ScriptMgr::OnGuildDisband(Guild* guild) { FOREACH_SCRIPT(GuildScript)->OnDisband(guild); } void ScriptMgr::OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32 &amount, bool isRepair) { FOREACH_SCRIPT(GuildScript)->OnMemberWitdrawMoney(guild, player, amount, isRepair); } void ScriptMgr::OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32 &amount) { FOREACH_SCRIPT(GuildScript)->OnMemberDepositMoney(guild, player, amount); } void ScriptMgr::OnGuildItemMove(Guild* guild, Player* player, Item* pItem, bool isSrcBank, uint8 srcContainer, uint8 srcSlotId, bool isDestBank, uint8 destContainer, uint8 destSlotId) { FOREACH_SCRIPT(GuildScript)->OnItemMove(guild, player, pItem, isSrcBank, srcContainer, srcSlotId, isDestBank, destContainer, destSlotId); } void ScriptMgr::OnGuildEvent(Guild* guild, uint8 eventType, uint32 playerGuid1, uint32 playerGuid2, uint8 newRank) { FOREACH_SCRIPT(GuildScript)->OnEvent(guild, eventType, playerGuid1, playerGuid2, newRank); } void ScriptMgr::OnGuildBankEvent(Guild* guild, uint8 eventType, uint8 tabId, uint32 playerGuid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId) { FOREACH_SCRIPT(GuildScript)->OnBankEvent(guild, eventType, tabId, playerGuid, itemOrMoney, itemStackCount, destTabId); } // Group void ScriptMgr::OnGroupAddMember(Group* group, uint64 guid) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnAddMember(group, guid); } void ScriptMgr::OnGroupInviteMember(Group* group, uint64 guid) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnInviteMember(group, guid); } void ScriptMgr::OnGroupRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, const char* reason) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnRemoveMember(group, guid, method, kicker, reason); } void ScriptMgr::OnGroupChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnChangeLeader(group, newLeaderGuid, oldLeaderGuid); } void ScriptMgr::OnGroupDisband(Group* group) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnDisband(group); } SpellScriptLoader::SpellScriptLoader(const char* name) : ScriptObject(name) { ScriptRegistry<SpellScriptLoader>::AddScript(this); } ServerScript::ServerScript(const char* name) : ScriptObject(name) { ScriptRegistry<ServerScript>::AddScript(this); } WorldScript::WorldScript(const char* name) : ScriptObject(name) { ScriptRegistry<WorldScript>::AddScript(this); } FormulaScript::FormulaScript(const char* name) : ScriptObject(name) { ScriptRegistry<FormulaScript>::AddScript(this); } WorldMapScript::WorldMapScript(const char* name, uint32 mapId) : ScriptObject(name), MapScript<Map>(mapId) { if (GetEntry() && !GetEntry()->IsWorldMap()) sLog->outError(LOG_FILTER_TSCR, "WorldMapScript for map %u is invalid.", mapId); ScriptRegistry<WorldMapScript>::AddScript(this); } InstanceMapScript::InstanceMapScript(const char* name, uint32 mapId) : ScriptObject(name), MapScript<InstanceMap>(mapId) { if (GetEntry() && !GetEntry()->IsDungeon()) sLog->outError(LOG_FILTER_TSCR, "InstanceMapScript for map %u is invalid.", mapId); ScriptRegistry<InstanceMapScript>::AddScript(this); } BattlegroundMapScript::BattlegroundMapScript(const char* name, uint32 mapId) : ScriptObject(name), MapScript<BattlegroundMap>(mapId) { if (GetEntry() && !GetEntry()->IsBattleground()) sLog->outError(LOG_FILTER_TSCR, "BattlegroundMapScript for map %u is invalid.", mapId); ScriptRegistry<BattlegroundMapScript>::AddScript(this); } ItemScript::ItemScript(const char* name) : ScriptObject(name) { ScriptRegistry<ItemScript>::AddScript(this); } CreatureScript::CreatureScript(const char* name) : ScriptObject(name) { ScriptRegistry<CreatureScript>::AddScript(this); } GameObjectScript::GameObjectScript(const char* name) : ScriptObject(name) { ScriptRegistry<GameObjectScript>::AddScript(this); } AreaTriggerScript::AreaTriggerScript(const char* name) : ScriptObject(name) { ScriptRegistry<AreaTriggerScript>::AddScript(this); } BattlegroundScript::BattlegroundScript(const char* name) : ScriptObject(name) { ScriptRegistry<BattlegroundScript>::AddScript(this); } OutdoorPvPScript::OutdoorPvPScript(const char* name) : ScriptObject(name) { ScriptRegistry<OutdoorPvPScript>::AddScript(this); } CommandScript::CommandScript(const char* name) : ScriptObject(name) { ScriptRegistry<CommandScript>::AddScript(this); } WeatherScript::WeatherScript(const char* name) : ScriptObject(name) { ScriptRegistry<WeatherScript>::AddScript(this); } AuctionHouseScript::AuctionHouseScript(const char* name) : ScriptObject(name) { ScriptRegistry<AuctionHouseScript>::AddScript(this); } ConditionScript::ConditionScript(const char* name) : ScriptObject(name) { ScriptRegistry<ConditionScript>::AddScript(this); } VehicleScript::VehicleScript(const char* name) : ScriptObject(name) { ScriptRegistry<VehicleScript>::AddScript(this); } DynamicObjectScript::DynamicObjectScript(const char* name) : ScriptObject(name) { ScriptRegistry<DynamicObjectScript>::AddScript(this); } TransportScript::TransportScript(const char* name) : ScriptObject(name) { ScriptRegistry<TransportScript>::AddScript(this); } AchievementCriteriaScript::AchievementCriteriaScript(const char* name) : ScriptObject(name) { ScriptRegistry<AchievementCriteriaScript>::AddScript(this); } PlayerScript::PlayerScript(const char* name) : ScriptObject(name) { ScriptRegistry<PlayerScript>::AddScript(this); } GuildScript::GuildScript(const char* name) : ScriptObject(name) { ScriptRegistry<GuildScript>::AddScript(this); } GroupScript::GroupScript(const char* name) : ScriptObject(name) { ScriptRegistry<GroupScript>::AddScript(this); } // Instantiate static members of ScriptRegistry. template<class TScript> std::map<uint32, TScript*> ScriptRegistry<TScript>::ScriptPointerList; template<class TScript> uint32 ScriptRegistry<TScript>::_scriptIdCounter = 0; // Specialize for each script type class like so: template class ScriptRegistry<SpellScriptLoader>; template class ScriptRegistry<ServerScript>; template class ScriptRegistry<WorldScript>; template class ScriptRegistry<FormulaScript>; template class ScriptRegistry<WorldMapScript>; template class ScriptRegistry<InstanceMapScript>; template class ScriptRegistry<BattlegroundMapScript>; template class ScriptRegistry<ItemScript>; template class ScriptRegistry<CreatureScript>; template class ScriptRegistry<GameObjectScript>; template class ScriptRegistry<AreaTriggerScript>; template class ScriptRegistry<BattlegroundScript>; template class ScriptRegistry<OutdoorPvPScript>; template class ScriptRegistry<CommandScript>; template class ScriptRegistry<WeatherScript>; template class ScriptRegistry<AuctionHouseScript>; template class ScriptRegistry<ConditionScript>; template class ScriptRegistry<VehicleScript>; template class ScriptRegistry<DynamicObjectScript>; template class ScriptRegistry<TransportScript>; template class ScriptRegistry<AchievementCriteriaScript>; template class ScriptRegistry<PlayerScript>; template class ScriptRegistry<GuildScript>; template class ScriptRegistry<GroupScript>; // Undefine utility macros. #undef GET_SCRIPT_RET #undef GET_SCRIPT #undef FOREACH_SCRIPT #undef FOR_SCRIPTS_RET #undef FOR_SCRIPTS #undef SCR_REG_LST #undef SCR_REG_ITR #undef SCR_REG_MAP
lasoto/Arena_TC
src/server/game/Scripting/ScriptMgr.cpp
C++
gpl-2.0
50,973
/* sec_auth.cc: NT authentication functions Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Red Hat, Inc. This file is part of Cygwin. This software is a copyrighted work licensed under the terms of the Cygwin license. Please consult the file "CYGWIN_LICENSE" for details. */ #include "winsup.h" #include <stdlib.h> #include <wchar.h> #include <wininet.h> #include <ntsecapi.h> #include <dsgetdc.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include "ntdll.h" #include "tls_pbuf.h" #include <lm.h> #include <iptypes.h> #include "pwdgrp.h" #include "cyglsa.h" #include "cygserver_setpwd.h" #include <cygwin/version.h> /* Starting with Windows Vista, the token returned by system functions is a restricted token. The full admin token is linked to it and can be fetched with NtQueryInformationToken. This function returns the original token on pre-Vista, and the elevated token on Vista++ if it's available, the original token otherwise. The token handle is also made inheritable since that's necessary anyway. */ static HANDLE get_full_privileged_inheritable_token (HANDLE token) { if (wincap.has_mandatory_integrity_control ()) { TOKEN_LINKED_TOKEN linked; ULONG size; /* When fetching the linked token without TCB privs, then the linked token is not a primary token, only an impersonation token, which is not suitable for CreateProcessAsUser. Converting it to a primary token using DuplicateTokenEx does NOT work for the linked token in this case. So we have to switch on TCB privs to get a primary token. This is generally performed in the calling functions. */ if (NT_SUCCESS (NtQueryInformationToken (token, TokenLinkedToken, (PVOID) &linked, sizeof linked, &size))) { debug_printf ("Linked Token: %p", linked.LinkedToken); if (linked.LinkedToken) { TOKEN_TYPE type; /* At this point we don't know if the user actually had TCB privileges. Check if the linked token is a primary token. If not, just return the original token. */ if (NT_SUCCESS (NtQueryInformationToken (linked.LinkedToken, TokenType, (PVOID) &type, sizeof type, &size)) && type != TokenPrimary) debug_printf ("Linked Token is not a primary token!"); else { CloseHandle (token); token = linked.LinkedToken; } } } } if (!SetHandleInformation (token, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { __seterrno (); CloseHandle (token); token = NULL; } return token; } void set_imp_token (HANDLE token, int type) { debug_printf ("set_imp_token (%d, %d)", token, type); cygheap->user.external_token = (token == INVALID_HANDLE_VALUE ? NO_IMPERSONATION : token); cygheap->user.ext_token_is_restricted = (type == CW_TOKEN_RESTRICTED); } extern "C" void cygwin_set_impersonation_token (const HANDLE hToken) { set_imp_token (hToken, CW_TOKEN_IMPERSONATION); } void extract_nt_dom_user (const struct passwd *pw, PWCHAR domain, PWCHAR user) { cygsid psid; DWORD ulen = UNLEN + 1; DWORD dlen = MAX_DOMAIN_NAME_LEN + 1; SID_NAME_USE use; debug_printf ("pw_gecos %x (%s)", pw->pw_gecos, pw->pw_gecos); if (psid.getfrompw (pw) && LookupAccountSidW (NULL, psid, user, &ulen, domain, &dlen, &use)) return; char *d, *u, *c; domain[0] = L'\0'; sys_mbstowcs (user, UNLEN + 1, pw->pw_name); if ((d = strstr (pw->pw_gecos, "U-")) != NULL && (d == pw->pw_gecos || d[-1] == ',')) { c = strchrnul (d + 2, ','); if ((u = strchrnul (d + 2, '\\')) >= c) u = d + 1; else if (u - d <= MAX_DOMAIN_NAME_LEN + 2) sys_mbstowcs (domain, MAX_DOMAIN_NAME_LEN + 1, d + 2, u - d - 1); if (c - u <= UNLEN + 1) sys_mbstowcs (user, UNLEN + 1, u + 1, c - u); } } extern "C" HANDLE cygwin_logon_user (const struct passwd *pw, const char *password) { if (!pw || !password) { set_errno (EINVAL); return INVALID_HANDLE_VALUE; } WCHAR nt_domain[MAX_DOMAIN_NAME_LEN + 1]; WCHAR nt_user[UNLEN + 1]; PWCHAR passwd; HANDLE hToken; tmp_pathbuf tp; extract_nt_dom_user (pw, nt_domain, nt_user); debug_printf ("LogonUserW (%W, %W, ...)", nt_user, nt_domain); sys_mbstowcs (passwd = tp.w_get (), NT_MAX_PATH, password); /* CV 2005-06-08: LogonUser should run under the primary process token, otherwise it returns with ERROR_ACCESS_DENIED. */ cygheap->user.deimpersonate (); if (!LogonUserW (nt_user, *nt_domain ? nt_domain : NULL, passwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken)) { __seterrno (); hToken = INVALID_HANDLE_VALUE; } else { /* See the comment in get_full_privileged_inheritable_token for a description why we enable TCB privileges here. */ push_self_privilege (SE_TCB_PRIVILEGE, true); hToken = get_full_privileged_inheritable_token (hToken); pop_self_privilege (); if (!hToken) hToken = INVALID_HANDLE_VALUE; } cygheap->user.reimpersonate (); debug_printf ("%R = logon_user(%s,...)", hToken, pw->pw_name); return hToken; } static void str2lsa (LSA_STRING &tgt, const char *srcstr) { tgt.Length = strlen (srcstr); tgt.MaximumLength = tgt.Length + 1; tgt.Buffer = (PCHAR) srcstr; } static void str2buf2lsa (LSA_STRING &tgt, char *buf, const char *srcstr) { tgt.Length = strlen (srcstr); tgt.MaximumLength = tgt.Length + 1; tgt.Buffer = (PCHAR) buf; memcpy (buf, srcstr, tgt.MaximumLength); } HANDLE open_local_policy (ACCESS_MASK access) { LSA_OBJECT_ATTRIBUTES oa = { 0, 0, 0, 0, 0, 0 }; HANDLE lsa = INVALID_HANDLE_VALUE; NTSTATUS status = LsaOpenPolicy (NULL, &oa, access, &lsa); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); /* Some versions of Windows set the lsa handle to NULL when LsaOpenPolicy fails. */ lsa = INVALID_HANDLE_VALUE; } return lsa; } static void close_local_policy (LSA_HANDLE &lsa) { if (lsa != INVALID_HANDLE_VALUE) LsaClose (lsa); lsa = INVALID_HANDLE_VALUE; } bool get_logon_server (PWCHAR domain, WCHAR *server, bool rediscovery) { DWORD ret; PDOMAIN_CONTROLLER_INFOW pci; DWORD size = MAX_COMPUTERNAME_LENGTH + 1; /* Empty domain is interpreted as local system */ if ((GetComputerNameW (server + 2, &size)) && (!wcscasecmp (domain, server + 2) || !domain[0])) { server[0] = server[1] = L'\\'; return true; } /* Try to get any available domain controller for this domain */ ret = DsGetDcNameW (NULL, domain, NULL, NULL, rediscovery ? DS_FORCE_REDISCOVERY : 0, &pci); if (ret == ERROR_SUCCESS) { wcscpy (server, pci->DomainControllerName); NetApiBufferFree (pci); debug_printf ("DC: rediscovery: %d, server: %W", rediscovery, server); return true; } __seterrno_from_win_error (ret); return false; } static bool get_user_groups (WCHAR *logonserver, cygsidlist &grp_list, PWCHAR user, PWCHAR domain) { WCHAR dgroup[MAX_DOMAIN_NAME_LEN + GNLEN + 2]; LPGROUP_USERS_INFO_0 buf; DWORD cnt, tot, len; NET_API_STATUS ret; /* Look only on logonserver */ ret = NetUserGetGroups (logonserver, user, 0, (LPBYTE *) &buf, MAX_PREFERRED_LENGTH, &cnt, &tot); if (ret) { __seterrno_from_win_error (ret); /* It's no error when the user name can't be found. */ return ret == NERR_UserNotFound; } len = wcslen (domain); wcscpy (dgroup, domain); dgroup[len++] = L'\\'; for (DWORD i = 0; i < cnt; ++i) { cygsid gsid; DWORD glen = MAX_SID_LEN; WCHAR dom[MAX_DOMAIN_NAME_LEN + 1]; DWORD dlen = sizeof (dom); SID_NAME_USE use = SidTypeInvalid; wcscpy (dgroup + len, buf[i].grui0_name); if (!LookupAccountNameW (NULL, dgroup, gsid, &glen, dom, &dlen, &use)) debug_printf ("LookupAccountName(%W), %E", dgroup); else if (well_known_sid_type (use)) grp_list *= gsid; else if (legal_sid_type (use)) grp_list += gsid; else debug_printf ("Global group %W invalid. Use: %d", dgroup, use); } NetApiBufferFree (buf); return true; } static bool get_user_local_groups (PWCHAR logonserver, PWCHAR domain, cygsidlist &grp_list, PWCHAR user) { LPLOCALGROUP_INFO_0 buf; DWORD cnt, tot; NET_API_STATUS ret; ret = NetUserGetLocalGroups (logonserver, user, 0, LG_INCLUDE_INDIRECT, (LPBYTE *) &buf, MAX_PREFERRED_LENGTH, &cnt, &tot); if (ret) { __seterrno_from_win_error (ret); return false; } WCHAR domlocal_grp[MAX_DOMAIN_NAME_LEN + GNLEN + 2]; WCHAR builtin_grp[2 * GNLEN + 2]; PWCHAR dg_ptr, bg_ptr = NULL; SID_NAME_USE use; dg_ptr = wcpcpy (domlocal_grp, domain); *dg_ptr++ = L'\\'; for (DWORD i = 0; i < cnt; ++i) { cygsid gsid; DWORD glen = MAX_SID_LEN; WCHAR dom[MAX_DOMAIN_NAME_LEN + 1]; DWORD domlen = MAX_DOMAIN_NAME_LEN + 1; use = SidTypeInvalid; wcscpy (dg_ptr, buf[i].lgrpi0_name); if (LookupAccountNameW (NULL, domlocal_grp, gsid, &glen, dom, &domlen, &use)) { if (well_known_sid_type (use)) grp_list *= gsid; else if (legal_sid_type (use)) grp_list += gsid; else debug_printf ("Rejecting local %W. use: %d", dg_ptr, use); } else if (GetLastError () == ERROR_NONE_MAPPED) { /* Check if it's a builtin group. */ if (!bg_ptr) { /* Retrieve name of builtin group from system since it's localized. */ glen = 2 * GNLEN + 2; if (!LookupAccountSidW (NULL, well_known_builtin_sid, builtin_grp, &glen, domain, &domlen, &use)) debug_printf ("LookupAccountSid(BUILTIN), %E"); else { bg_ptr = builtin_grp + wcslen (builtin_grp); bg_ptr = wcpcpy (builtin_grp, L"\\"); } } if (bg_ptr) { wcscpy (bg_ptr, dg_ptr); glen = MAX_SID_LEN; domlen = MAX_DOMAIN_NAME_LEN + 1; if (LookupAccountNameW (NULL, builtin_grp, gsid, &glen, dom, &domlen, &use)) { if (!legal_sid_type (use)) debug_printf ("Rejecting local %W. use: %d", dg_ptr, use); else grp_list *= gsid; } else debug_printf ("LookupAccountName(%W), %E", builtin_grp); } } else debug_printf ("LookupAccountName(%W), %E", domlocal_grp); } NetApiBufferFree (buf); return true; } static bool sid_in_token_groups (PTOKEN_GROUPS grps, cygpsid sid) { if (!grps) return false; for (DWORD i = 0; i < grps->GroupCount; ++i) if (sid == grps->Groups[i].Sid) return true; return false; } static void get_unix_group_sidlist (struct passwd *pw, cygsidlist &grp_list) { struct __group32 *gr; cygsid gsid; for (int gidx = 0; (gr = internal_getgrent (gidx)); ++gidx) { if (gr->gr_gid == (__gid32_t) pw->pw_gid) goto found; else if (gr->gr_mem) for (int gi = 0; gr->gr_mem[gi]; ++gi) if (strcasematch (pw->pw_name, gr->gr_mem[gi])) goto found; continue; found: if (gsid.getfromgr (gr)) grp_list += gsid; } } static void get_token_group_sidlist (cygsidlist &grp_list, PTOKEN_GROUPS my_grps, LUID auth_luid, int &auth_pos) { auth_pos = -1; if (my_grps) { grp_list += well_known_local_sid; if (wincap.has_console_logon_sid ()) grp_list += well_known_console_logon_sid; if (sid_in_token_groups (my_grps, well_known_dialup_sid)) grp_list *= well_known_dialup_sid; if (sid_in_token_groups (my_grps, well_known_network_sid)) grp_list *= well_known_network_sid; if (sid_in_token_groups (my_grps, well_known_batch_sid)) grp_list *= well_known_batch_sid; grp_list *= well_known_interactive_sid; #if 0 /* Don't add the SERVICE group when switching the user context. That's much too dangerous, since the service group adds the SE_IMPERSONATE_NAME privilege to the user. After all, the process started with this token is not the service process anymore anyway. */ if (sid_in_token_groups (my_grps, well_known_service_sid)) grp_list *= well_known_service_sid; #endif if (sid_in_token_groups (my_grps, well_known_this_org_sid)) grp_list *= well_known_this_org_sid; grp_list *= well_known_users_sid; } else { grp_list += well_known_local_sid; grp_list *= well_known_interactive_sid; grp_list *= well_known_users_sid; } if (get_ll (auth_luid) != 999LL) /* != SYSTEM_LUID */ { for (DWORD i = 0; i < my_grps->GroupCount; ++i) if (my_grps->Groups[i].Attributes & SE_GROUP_LOGON_ID) { grp_list += my_grps->Groups[i].Sid; auth_pos = grp_list.count () - 1; break; } } } bool get_server_groups (cygsidlist &grp_list, PSID usersid, struct passwd *pw) { WCHAR user[UNLEN + 1]; WCHAR domain[MAX_DOMAIN_NAME_LEN + 1]; WCHAR server[INTERNET_MAX_HOST_NAME_LENGTH + 3]; DWORD ulen = UNLEN + 1; DWORD dlen = MAX_DOMAIN_NAME_LEN + 1; SID_NAME_USE use; if (well_known_system_sid == usersid) { grp_list *= well_known_admins_sid; get_unix_group_sidlist (pw, grp_list); return true; } grp_list *= well_known_world_sid; grp_list *= well_known_authenticated_users_sid; if (!LookupAccountSidW (NULL, usersid, user, &ulen, domain, &dlen, &use)) { __seterrno (); return false; } if (get_logon_server (domain, server, false) && !get_user_groups (server, grp_list, user, domain) && get_logon_server (domain, server, true)) get_user_groups (server, grp_list, user, domain); get_user_local_groups (server, domain, grp_list, user); get_unix_group_sidlist (pw, grp_list); return true; } static bool get_initgroups_sidlist (cygsidlist &grp_list, PSID usersid, PSID pgrpsid, struct passwd *pw, PTOKEN_GROUPS my_grps, LUID auth_luid, int &auth_pos) { grp_list *= well_known_world_sid; grp_list *= well_known_authenticated_users_sid; if (well_known_system_sid == usersid) auth_pos = -1; else get_token_group_sidlist (grp_list, my_grps, auth_luid, auth_pos); if (!get_server_groups (grp_list, usersid, pw)) return false; /* special_pgrp true if pgrpsid is not in normal groups */ grp_list += pgrpsid; return true; } static void get_setgroups_sidlist (cygsidlist &tmp_list, PSID usersid, struct passwd *pw, PTOKEN_GROUPS my_grps, user_groups &groups, LUID auth_luid, int &auth_pos) { tmp_list *= well_known_world_sid; tmp_list *= well_known_authenticated_users_sid; get_token_group_sidlist (tmp_list, my_grps, auth_luid, auth_pos); get_server_groups (tmp_list, usersid, pw); for (int gidx = 0; gidx < groups.sgsids.count (); gidx++) tmp_list += groups.sgsids.sids[gidx]; tmp_list += groups.pgsid; } static ULONG sys_privs[] = { SE_CREATE_TOKEN_PRIVILEGE, SE_ASSIGNPRIMARYTOKEN_PRIVILEGE, SE_LOCK_MEMORY_PRIVILEGE, SE_INCREASE_QUOTA_PRIVILEGE, SE_TCB_PRIVILEGE, SE_SECURITY_PRIVILEGE, SE_TAKE_OWNERSHIP_PRIVILEGE, SE_LOAD_DRIVER_PRIVILEGE, SE_SYSTEM_PROFILE_PRIVILEGE, /* Vista ONLY */ SE_SYSTEMTIME_PRIVILEGE, SE_PROF_SINGLE_PROCESS_PRIVILEGE, SE_INC_BASE_PRIORITY_PRIVILEGE, SE_CREATE_PAGEFILE_PRIVILEGE, SE_CREATE_PERMANENT_PRIVILEGE, SE_BACKUP_PRIVILEGE, SE_RESTORE_PRIVILEGE, SE_SHUTDOWN_PRIVILEGE, SE_DEBUG_PRIVILEGE, SE_AUDIT_PRIVILEGE, SE_SYSTEM_ENVIRONMENT_PRIVILEGE, SE_CHANGE_NOTIFY_PRIVILEGE, SE_UNDOCK_PRIVILEGE, SE_MANAGE_VOLUME_PRIVILEGE, SE_IMPERSONATE_PRIVILEGE, SE_CREATE_GLOBAL_PRIVILEGE, SE_INCREASE_WORKING_SET_PRIVILEGE, SE_TIME_ZONE_PRIVILEGE, SE_CREATE_SYMBOLIC_LINK_PRIVILEGE }; #define SYSTEM_PRIVILEGES_COUNT (sizeof sys_privs / sizeof *sys_privs) static PTOKEN_PRIVILEGES get_system_priv_list (size_t &size) { ULONG max_idx = 0; while (max_idx < SYSTEM_PRIVILEGES_COUNT && sys_privs[max_idx] != wincap.max_sys_priv ()) ++max_idx; if (max_idx >= SYSTEM_PRIVILEGES_COUNT) api_fatal ("Coding error: wincap privilege %u doesn't exist in sys_privs", wincap.max_sys_priv ()); size = sizeof (ULONG) + (max_idx + 1) * sizeof (LUID_AND_ATTRIBUTES); PTOKEN_PRIVILEGES privs = (PTOKEN_PRIVILEGES) malloc (size); if (!privs) { debug_printf ("malloc (system_privs) failed."); return NULL; } privs->PrivilegeCount = 0; for (ULONG i = 0; i <= max_idx; ++i) { privs->Privileges[privs->PrivilegeCount].Luid.HighPart = 0L; privs->Privileges[privs->PrivilegeCount].Luid.LowPart = sys_privs[i]; privs->Privileges[privs->PrivilegeCount].Attributes = SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_ENABLED_BY_DEFAULT; ++privs->PrivilegeCount; } return privs; } static PTOKEN_PRIVILEGES get_priv_list (LSA_HANDLE lsa, cygsid &usersid, cygsidlist &grp_list, size_t &size, cygpsid *mandatory_integrity_sid) { PLSA_UNICODE_STRING privstrs; ULONG cnt; PTOKEN_PRIVILEGES privs = NULL; if (usersid == well_known_system_sid) { if (mandatory_integrity_sid) *mandatory_integrity_sid = mandatory_system_integrity_sid; return get_system_priv_list (size); } if (mandatory_integrity_sid) *mandatory_integrity_sid = mandatory_medium_integrity_sid; for (int grp = -1; grp < grp_list.count (); ++grp) { if (grp == -1) { if (LsaEnumerateAccountRights (lsa, usersid, &privstrs, &cnt) != STATUS_SUCCESS) continue; } else if (LsaEnumerateAccountRights (lsa, grp_list.sids[grp], &privstrs, &cnt) != STATUS_SUCCESS) continue; for (ULONG i = 0; i < cnt; ++i) { LUID priv; PTOKEN_PRIVILEGES tmp; DWORD tmp_count; bool high_integrity; if (!privilege_luid (privstrs[i].Buffer, priv, high_integrity)) continue; if (privs) { DWORD pcnt = privs->PrivilegeCount; LUID_AND_ATTRIBUTES *p = privs->Privileges; for (; pcnt > 0; --pcnt, ++p) if (priv.HighPart == p->Luid.HighPart && priv.LowPart == p->Luid.LowPart) goto next_account_right; } tmp_count = privs ? privs->PrivilegeCount : 0; size = sizeof (DWORD) + (tmp_count + 1) * sizeof (LUID_AND_ATTRIBUTES); tmp = (PTOKEN_PRIVILEGES) realloc (privs, size); if (!tmp) { if (privs) free (privs); LsaFreeMemory (privstrs); debug_printf ("realloc (privs) failed."); return NULL; } tmp->PrivilegeCount = tmp_count; privs = tmp; privs->Privileges[privs->PrivilegeCount].Luid = priv; privs->Privileges[privs->PrivilegeCount].Attributes = SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_ENABLED_BY_DEFAULT; ++privs->PrivilegeCount; if (mandatory_integrity_sid && high_integrity) *mandatory_integrity_sid = mandatory_high_integrity_sid; next_account_right: ; } LsaFreeMemory (privstrs); } return privs; } /* Accept a token if - the requested usersid matches the TokenUser and - if setgroups has been called: the token groups that are listed in /etc/group match the union of the requested primary and supplementary groups in gsids. - else the (unknown) implicitly requested supplementary groups and those in the token are the groups associated with the usersid. We assume they match and verify only the primary groups. The requested primary group must appear in the token. The primary group in the token is a group associated with the usersid, except if the token is internal and the group is in the token SD (see create_token). In that latter case that group must match the requested primary group. */ bool verify_token (HANDLE token, cygsid &usersid, user_groups &groups, bool *pintern) { NTSTATUS status; ULONG size; bool intern = false; if (pintern) { TOKEN_SOURCE ts; status = NtQueryInformationToken (token, TokenSource, &ts, sizeof ts, &size); if (!NT_SUCCESS (status)) debug_printf ("NtQueryInformationToken(), %p", status); else *pintern = intern = !memcmp (ts.SourceName, "Cygwin.1", 8); } /* Verify usersid */ cygsid tok_usersid = NO_SID; status = NtQueryInformationToken (token, TokenUser, &tok_usersid, sizeof tok_usersid, &size); if (!NT_SUCCESS (status)) debug_printf ("NtQueryInformationToken(), %p", status); if (usersid != tok_usersid) return false; /* For an internal token, if setgroups was not called and if the sd group is not well_known_null_sid, it must match pgrpsid */ if (intern && !groups.issetgroups ()) { const DWORD sd_buf_siz = MAX_SID_LEN + sizeof (SECURITY_DESCRIPTOR); PSECURITY_DESCRIPTOR sd_buf = (PSECURITY_DESCRIPTOR) alloca (sd_buf_siz); cygpsid gsid (NO_SID); NTSTATUS status; status = NtQuerySecurityObject (token, GROUP_SECURITY_INFORMATION, sd_buf, sd_buf_siz, &size); if (!NT_SUCCESS (status)) debug_printf ("NtQuerySecurityObject(), %p", status); else { BOOLEAN dummy; status = RtlGetGroupSecurityDescriptor (sd_buf, (PSID *) &gsid, &dummy); if (!NT_SUCCESS (status)) debug_printf ("RtlGetGroupSecurityDescriptor(), %p", status); } if (well_known_null_sid != gsid) return gsid == groups.pgsid; } PTOKEN_GROUPS my_grps; status = NtQueryInformationToken (token, TokenGroups, NULL, 0, &size); if (!NT_SUCCESS (status) && status != STATUS_BUFFER_TOO_SMALL) { debug_printf ("NtQueryInformationToken(token, TokenGroups), %p", status); return false; } my_grps = (PTOKEN_GROUPS) alloca (size); status = NtQueryInformationToken (token, TokenGroups, my_grps, size, &size); if (!NT_SUCCESS (status)) { debug_printf ("NtQueryInformationToken(my_token, TokenGroups), %p", status); return false; } bool sawpg = false; if (groups.issetgroups ()) /* setgroups was called */ { cygsid gsid; struct __group32 *gr; bool saw[groups.sgsids.count ()]; memset (saw, 0, sizeof(saw)); /* token groups found in /etc/group match the user.gsids ? */ for (int gidx = 0; (gr = internal_getgrent (gidx)); ++gidx) if (gsid.getfromgr (gr) && sid_in_token_groups (my_grps, gsid)) { int pos = groups.sgsids.position (gsid); if (pos >= 0) saw[pos] = true; else if (groups.pgsid == gsid) sawpg = true; #if 0 /* With this `else', verify_token returns false if we find groups in the token, which are not in the group list set with setgroups(). That's rather dangerous. What we're really interested in is that all groups in the setgroups() list are in the token. A token created through ADVAPI should be allowed to contain more groups than requested through setgroups(), esecially since Vista and the addition of integrity groups. So we disable this statement for now. */ else if (gsid != well_known_world_sid && gsid != usersid) goto done; #endif } /* user.sgsids groups must be in the token, except for builtin groups. These can be different on domain member machines compared to domain controllers, so these builtin groups may be validly missing from a token created through password or lsaauth logon. */ for (int gidx = 0; gidx < groups.sgsids.count (); gidx++) if (!saw[gidx] && !groups.sgsids.sids[gidx].is_well_known_sid () && !sid_in_token_groups (my_grps, groups.sgsids.sids[gidx])) return false; } /* The primary group must be in the token */ return sawpg || sid_in_token_groups (my_grps, groups.pgsid) || groups.pgsid == usersid; } HANDLE create_token (cygsid &usersid, user_groups &new_groups, struct passwd *pw) { NTSTATUS status; LSA_HANDLE lsa = INVALID_HANDLE_VALUE; cygsidlist tmp_gsids (cygsidlist_auto, 12); SECURITY_QUALITY_OF_SERVICE sqos = { sizeof sqos, SecurityImpersonation, SECURITY_STATIC_TRACKING, FALSE }; OBJECT_ATTRIBUTES oa = { sizeof oa, 0, 0, 0, 0, &sqos }; LUID auth_luid = SYSTEM_LUID; LARGE_INTEGER exp = { QuadPart:INT64_MAX }; TOKEN_USER user; PTOKEN_GROUPS new_tok_gsids = NULL; PTOKEN_PRIVILEGES privs = NULL; TOKEN_OWNER owner; TOKEN_PRIMARY_GROUP pgrp; TOKEN_DEFAULT_DACL dacl = {}; TOKEN_SOURCE source; TOKEN_STATISTICS stats; memcpy (source.SourceName, "Cygwin.1", 8); source.SourceIdentifier.HighPart = 0; source.SourceIdentifier.LowPart = 0x0101; HANDLE token = INVALID_HANDLE_VALUE; HANDLE primary_token = INVALID_HANDLE_VALUE; PTOKEN_GROUPS my_tok_gsids = NULL; cygpsid mandatory_integrity_sid; ULONG size; size_t psize = 0; /* SE_CREATE_TOKEN_NAME privilege needed to call NtCreateToken. */ push_self_privilege (SE_CREATE_TOKEN_PRIVILEGE, true); /* Open policy object. */ if ((lsa = open_local_policy (POLICY_EXECUTE)) == INVALID_HANDLE_VALUE) goto out; /* User, owner, primary group. */ user.User.Sid = usersid; user.User.Attributes = 0; owner.Owner = usersid; /* Retrieve authentication id and group list from own process. */ if (hProcToken) { /* Switching user context to SYSTEM doesn't inherit the authentication id of the user account running current process. */ if (usersid == well_known_system_sid) /* nothing to do */; else { status = NtQueryInformationToken (hProcToken, TokenStatistics, &stats, sizeof stats, &size); if (!NT_SUCCESS (status)) debug_printf ("NtQueryInformationToken(hProcToken, " "TokenStatistics), %p", status); else auth_luid = stats.AuthenticationId; } /* Retrieving current processes group list to be able to inherit some important well known group sids. */ status = NtQueryInformationToken (hProcToken, TokenGroups, NULL, 0, &size); if (!NT_SUCCESS (status) && status != STATUS_BUFFER_TOO_SMALL) debug_printf ("NtQueryInformationToken(hProcToken, TokenGroups), %p", status); else if (!(my_tok_gsids = (PTOKEN_GROUPS) malloc (size))) debug_printf ("malloc (my_tok_gsids) failed."); else { status = NtQueryInformationToken (hProcToken, TokenGroups, my_tok_gsids, size, &size); if (!NT_SUCCESS (status)) { debug_printf ("NtQueryInformationToken(hProcToken, TokenGroups), " "%p", status); free (my_tok_gsids); my_tok_gsids = NULL; } } } /* Create list of groups, the user is member in. */ int auth_pos; if (new_groups.issetgroups ()) get_setgroups_sidlist (tmp_gsids, usersid, pw, my_tok_gsids, new_groups, auth_luid, auth_pos); else if (!get_initgroups_sidlist (tmp_gsids, usersid, new_groups.pgsid, pw, my_tok_gsids, auth_luid, auth_pos)) goto out; /* Primary group. */ pgrp.PrimaryGroup = new_groups.pgsid; /* Create a TOKEN_GROUPS list from the above retrieved list of sids. */ new_tok_gsids = (PTOKEN_GROUPS) alloca (sizeof (DWORD) + (tmp_gsids.count () + 1) * sizeof (SID_AND_ATTRIBUTES)); new_tok_gsids->GroupCount = tmp_gsids.count (); for (DWORD i = 0; i < new_tok_gsids->GroupCount; ++i) { new_tok_gsids->Groups[i].Sid = tmp_gsids.sids[i]; new_tok_gsids->Groups[i].Attributes = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED; } if (auth_pos >= 0) new_tok_gsids->Groups[auth_pos].Attributes |= SE_GROUP_LOGON_ID; /* Retrieve list of privileges of that user. Based on the usersid and the returned privileges, get_priv_list sets the mandatory_integrity_sid pointer to the correct MIC SID for UAC. */ if (!(privs = get_priv_list (lsa, usersid, tmp_gsids, psize, &mandatory_integrity_sid))) goto out; /* On systems supporting Mandatory Integrity Control, add the MIC SID. */ if (wincap.has_mandatory_integrity_control ()) { new_tok_gsids->Groups[new_tok_gsids->GroupCount].Attributes = SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED; new_tok_gsids->Groups[new_tok_gsids->GroupCount++].Sid = mandatory_integrity_sid; } /* Let's be heroic... */ status = NtCreateToken (&token, TOKEN_ALL_ACCESS, &oa, TokenImpersonation, &auth_luid, &exp, &user, new_tok_gsids, privs, &owner, &pgrp, &dacl, &source); if (status) __seterrno_from_nt_status (status); else { /* Convert to primary token. */ if (!DuplicateTokenEx (token, MAXIMUM_ALLOWED, &sec_none, SecurityImpersonation, TokenPrimary, &primary_token)) { __seterrno (); debug_printf ("DuplicateTokenEx %E"); } } out: pop_self_privilege (); if (token != INVALID_HANDLE_VALUE) CloseHandle (token); if (privs) free (privs); if (my_tok_gsids) free (my_tok_gsids); close_local_policy (lsa); debug_printf ("%p = create_token ()", primary_token); return primary_token; } HANDLE lsaauth (cygsid &usersid, user_groups &new_groups, struct passwd *pw) { cygsidlist tmp_gsids (cygsidlist_auto, 12); cygpsid pgrpsid; LSA_STRING name; HANDLE lsa_hdl = NULL, lsa = INVALID_HANDLE_VALUE; LSA_OPERATIONAL_MODE sec_mode; NTSTATUS status, sub_status; ULONG package_id, size; LUID auth_luid = SYSTEM_LUID; struct { LSA_STRING str; CHAR buf[16]; } origin; DWORD ulen = UNLEN + 1; DWORD dlen = MAX_DOMAIN_NAME_LEN + 1; SID_NAME_USE use; cyglsa_t *authinf = NULL; ULONG authinf_size; TOKEN_SOURCE ts; PCYG_TOKEN_GROUPS gsids = NULL; PTOKEN_PRIVILEGES privs = NULL; PACL dacl = NULL; PVOID profile = NULL; LUID luid; QUOTA_LIMITS quota; size_t psize = 0, gsize = 0, dsize = 0; OFFSET offset, sids_offset; int tmpidx, non_well_known_cnt; HANDLE user_token = NULL; push_self_privilege (SE_TCB_PRIVILEGE, true); /* Register as logon process. */ str2lsa (name, "Cygwin"); SetLastError (0); status = LsaRegisterLogonProcess (&name, &lsa_hdl, &sec_mode); if (status != STATUS_SUCCESS) { debug_printf ("LsaRegisterLogonProcess: %p", status); __seterrno_from_nt_status (status); goto out; } else if (GetLastError () == ERROR_PROC_NOT_FOUND) { debug_printf ("Couldn't load Secur32.dll"); goto out; } /* Get handle to our own LSA package. */ str2lsa (name, CYG_LSA_PKGNAME); status = LsaLookupAuthenticationPackage (lsa_hdl, &name, &package_id); if (status != STATUS_SUCCESS) { debug_printf ("LsaLookupAuthenticationPackage: %p", status); __seterrno_from_nt_status (status); goto out; } /* Open policy object. */ if ((lsa = open_local_policy (POLICY_EXECUTE)) == INVALID_HANDLE_VALUE) goto out; /* Create origin. */ str2buf2lsa (origin.str, origin.buf, "Cygwin"); /* Create token source. */ memcpy (ts.SourceName, "Cygwin.1", 8); ts.SourceIdentifier.HighPart = 0; ts.SourceIdentifier.LowPart = 0x0103; /* Create list of groups, the user is member in. */ int auth_pos; if (new_groups.issetgroups ()) get_setgroups_sidlist (tmp_gsids, usersid, pw, NULL, new_groups, auth_luid, auth_pos); else if (!get_initgroups_sidlist (tmp_gsids, usersid, new_groups.pgsid, pw, NULL, auth_luid, auth_pos)) goto out; /* The logon SID entry is not generated automatically on Windows 2000 and earlier for some reason. So add fake logon sid here, which is filled with logon id values in the authentication package. */ if (wincap.needs_logon_sid_in_sid_list ()) tmp_gsids += fake_logon_sid; tmp_gsids.debug_print ("tmp_gsids"); /* Evaluate size of TOKEN_GROUPS list */ non_well_known_cnt = tmp_gsids.non_well_known_count (); gsize = sizeof (DWORD) + non_well_known_cnt * sizeof (SID_AND_ATTRIBUTES); tmpidx = -1; for (int i = 0; i < non_well_known_cnt; ++i) if ((tmpidx = tmp_gsids.next_non_well_known_sid (tmpidx)) >= 0) gsize += RtlLengthSid (tmp_gsids.sids[tmpidx]); /* Retrieve list of privileges of that user. The MIC SID is created by the LSA here. */ if (!(privs = get_priv_list (lsa, usersid, tmp_gsids, psize, NULL))) goto out; /* Create DefaultDacl. */ dsize = sizeof (ACL) + 3 * sizeof (ACCESS_ALLOWED_ACE) + RtlLengthSid (usersid) + RtlLengthSid (well_known_admins_sid) + RtlLengthSid (well_known_system_sid); dacl = (PACL) alloca (dsize); if (!NT_SUCCESS (RtlCreateAcl (dacl, dsize, ACL_REVISION))) goto out; if (!NT_SUCCESS (RtlAddAccessAllowedAce (dacl, ACL_REVISION, GENERIC_ALL, usersid))) goto out; if (!NT_SUCCESS (RtlAddAccessAllowedAce (dacl, ACL_REVISION, GENERIC_ALL, well_known_admins_sid))) goto out; if (!NT_SUCCESS (RtlAddAccessAllowedAce (dacl, ACL_REVISION, GENERIC_ALL, well_known_system_sid))) goto out; /* Evaluate authinf size and allocate authinf. */ authinf_size = (authinf->data - (PBYTE) authinf); authinf_size += RtlLengthSid (usersid); /* User SID */ authinf_size += gsize; /* Groups + Group SIDs */ /* When trying to define the admins group as primary group on Vista, LsaLogonUser fails with error STATUS_INVALID_OWNER. As workaround we define "Local" as primary group here. Seteuid32 sets the primary group to the group set in /etc/passwd anyway. */ if (new_groups.pgsid == well_known_admins_sid) pgrpsid = well_known_local_sid; else pgrpsid = new_groups.pgsid; authinf_size += RtlLengthSid (pgrpsid); /* Primary Group SID */ authinf_size += psize; /* Privileges */ authinf_size += 0; /* Owner SID */ authinf_size += dsize; /* Default DACL */ authinf = (cyglsa_t *) alloca (authinf_size); authinf->inf_size = authinf_size - ((PBYTE) &authinf->inf - (PBYTE) authinf); authinf->magic = CYG_LSA_MAGIC; if (!LookupAccountSidW (NULL, usersid, authinf->username, &ulen, authinf->domain, &dlen, &use)) { __seterrno (); goto out; } /* Store stuff in authinf with offset relative to start of "inf" member, instead of using pointers. */ offset = authinf->data - (PBYTE) &authinf->inf; authinf->inf.ExpirationTime.LowPart = 0xffffffffL; authinf->inf.ExpirationTime.HighPart = 0x7fffffffL; /* User SID */ authinf->inf.User.User.Sid = offset; authinf->inf.User.User.Attributes = 0; RtlCopySid (RtlLengthSid (usersid), (PSID) ((PBYTE) &authinf->inf + offset), usersid); offset += RtlLengthSid (usersid); /* Groups */ authinf->inf.Groups = offset; gsids = (PCYG_TOKEN_GROUPS) ((PBYTE) &authinf->inf + offset); sids_offset = offset + sizeof (ULONG) + non_well_known_cnt * sizeof (SID_AND_ATTRIBUTES); gsids->GroupCount = non_well_known_cnt; /* Group SIDs */ tmpidx = -1; for (int i = 0; i < non_well_known_cnt; ++i) { if ((tmpidx = tmp_gsids.next_non_well_known_sid (tmpidx)) < 0) break; gsids->Groups[i].Sid = sids_offset; gsids->Groups[i].Attributes = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED; /* Mark logon SID as logon SID :) */ if (wincap.needs_logon_sid_in_sid_list () && tmp_gsids.sids[tmpidx] == fake_logon_sid) gsids->Groups[i].Attributes += SE_GROUP_LOGON_ID; RtlCopySid (RtlLengthSid (tmp_gsids.sids[tmpidx]), (PSID) ((PBYTE) &authinf->inf + sids_offset), tmp_gsids.sids[tmpidx]); sids_offset += RtlLengthSid (tmp_gsids.sids[tmpidx]); } offset += gsize; /* Primary Group SID */ authinf->inf.PrimaryGroup.PrimaryGroup = offset; RtlCopySid (RtlLengthSid (pgrpsid), (PSID) ((PBYTE) &authinf->inf + offset), pgrpsid); offset += RtlLengthSid (pgrpsid); /* Privileges */ authinf->inf.Privileges = offset; memcpy ((PBYTE) &authinf->inf + offset, privs, psize); offset += psize; /* Owner */ authinf->inf.Owner.Owner = 0; /* Default DACL */ authinf->inf.DefaultDacl.DefaultDacl = offset; memcpy ((PBYTE) &authinf->inf + offset, dacl, dsize); authinf->checksum = CYG_LSA_MAGIC; PDWORD csp; PDWORD csp_end; csp = (PDWORD) &authinf->username; csp_end = (PDWORD) ((PBYTE) authinf + authinf_size); while (csp < csp_end) authinf->checksum += *csp++; /* Try to logon... */ status = LsaLogonUser (lsa_hdl, (PLSA_STRING) &origin, Interactive, package_id, authinf, authinf_size, NULL, &ts, &profile, &size, &luid, &user_token, &quota, &sub_status); if (status != STATUS_SUCCESS) { debug_printf ("LsaLogonUser: %p (sub-status %p)", status, sub_status); __seterrno_from_nt_status (status); goto out; } if (profile) { #ifdef JUST_ANOTHER_NONWORKING_SOLUTION /* See ../lsaauth/cyglsa.c. */ cygprf_t *prf = (cygprf_t *) profile; if (prf->magic_pre == MAGIC_PRE && prf->magic_post == MAGIC_POST && prf->token) { CloseHandle (user_token); user_token = prf->token; system_printf ("Got token through profile: %p", user_token); } #endif /* JUST_ANOTHER_NONWORKING_SOLUTION */ LsaFreeReturnBuffer (profile); } user_token = get_full_privileged_inheritable_token (user_token); out: if (privs) free (privs); close_local_policy (lsa); if (lsa_hdl) LsaDeregisterLogonProcess (lsa_hdl); pop_self_privilege (); debug_printf ("%p = lsaauth ()", user_token); return user_token; } #define SFU_LSA_KEY_SUFFIX L"_microsoft_sfu_utility" HANDLE lsaprivkeyauth (struct passwd *pw) { NTSTATUS status; HANDLE lsa = INVALID_HANDLE_VALUE; HANDLE token = NULL; WCHAR sid[256]; WCHAR domain[MAX_DOMAIN_NAME_LEN + 1]; WCHAR user[UNLEN + 1]; WCHAR key_name[MAX_DOMAIN_NAME_LEN + UNLEN + wcslen (SFU_LSA_KEY_SUFFIX) + 2]; UNICODE_STRING key; PUNICODE_STRING data; cygsid psid; push_self_privilege (SE_TCB_PRIVILEGE, true); /* Open policy object. */ if ((lsa = open_local_policy (POLICY_GET_PRIVATE_INFORMATION)) == INVALID_HANDLE_VALUE) goto out; /* Needed for Interix key and LogonUser. */ extract_nt_dom_user (pw, domain, user); /* First test for a Cygwin entry. */ if (psid.getfrompw (pw) && psid.string (sid)) { wcpcpy (wcpcpy (key_name, CYGWIN_LSA_KEY_PREFIX), sid); RtlInitUnicodeString (&key, key_name); status = LsaRetrievePrivateData (lsa, &key, &data); if (!NT_SUCCESS (status)) { /* No Cygwin key, try Interix key. */ if (!*domain) goto out; __small_swprintf (key_name, L"%W_%W%W", domain, user, SFU_LSA_KEY_SUFFIX); RtlInitUnicodeString (&key, key_name); status = LsaRetrievePrivateData (lsa, &key, &data); if (!NT_SUCCESS (status)) goto out; } } /* The key is not 0-terminated. */ PWCHAR passwd; passwd = (PWCHAR) alloca (data->Length + sizeof (WCHAR)); *wcpncpy (passwd, data->Buffer, data->Length / sizeof (WCHAR)) = L'\0'; LsaFreeMemory (data); debug_printf ("Try logon for %W\\%W", domain, user); if (!LogonUserW (user, domain, passwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &token)) { __seterrno (); token = NULL; } else token = get_full_privileged_inheritable_token (token); out: close_local_policy (lsa); pop_self_privilege (); return token; }
pgavin/or1k-src
winsup/cygwin/sec_auth.cc
C++
gpl-2.0
38,957
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.enterprise.inject.spi; /** * {@link javax.enterprise.inject.spi.Extension} callback while processing * a managed bean. * * <code><pre> * public class MyExtension implements Extension * { * &lt;X> public void * processManagedBean(@Observes ProcessManagedBean&lt;X> event) * { * ... * } * } * </pre></code> */ public interface ProcessManagedBean<X> extends ProcessBean<X> { public AnnotatedType<X> getAnnotatedBeanClass(); }
christianchristensen/resin
modules/webbeans/src/javax/enterprise/inject/spi/ProcessManagedBean.java
Java
gpl-2.0
1,495
<?php /** * @package WordPress * @subpackage Agrofields * @version 1.0.0 * * Blog Page Timeline Gallery Post Format Template * Created by CMSMasters * */ global $cmsms_metadata; $cmsms_post_metadata = explode(',', $cmsms_metadata); $date = (in_array('date', $cmsms_post_metadata) || is_home()) ? true : false; $categories = (get_the_category() && (in_array('categories', $cmsms_post_metadata) || is_home())) ? true : false; $author = (in_array('author', $cmsms_post_metadata) || is_home()) ? true : false; $comments = (comments_open() && (in_array('comments', $cmsms_post_metadata) || is_home())) ? true : false; $likes = (in_array('likes', $cmsms_post_metadata) || is_home()) ? true : false; $tags = (get_the_tags() && (in_array('tags', $cmsms_post_metadata) || is_home())) ? true : false; $more = (in_array('more', $cmsms_post_metadata) || is_home()) ? true : false; $cmsms_post_images = explode(',', str_replace(' ', '', str_replace('img_', '', get_post_meta(get_the_ID(), 'cmsms_post_images', true)))); $uniqid = uniqid(); ?> <!--_________________________ Start Gallery Article _________________________ --> <article id="post-<?php the_ID(); ?>" <?php post_class('cmsms_timeline_type'); ?>> <?php cmsms_post_highlight(get_the_ID(), get_post_format(), 'timeline'); $date ? cmsms_post_date('page', 'timeline') : ''; ?> <div class="cmsms_post_cont"> <?php if (!post_password_required()) { if (sizeof($cmsms_post_images) > 1) { ?> <script type="text/javascript"> jQuery(document).ready(function () { jQuery('.cmsms_slider_<?php echo $uniqid; ?>').owlCarousel( { singleItem : true, transitionStyle : false, rewindNav : true, slideSpeed : 200, paginationSpeed : 800, rewindSpeed : 1000, autoPlay : false, stopOnHover : false, pagination : true, navigation : false, navigationText : [ '<span></span>', '<span></span>' ] } ); } ); </script> <div id="cmsms_owl_carousel_<?php the_ID(); ?>" class="cmsms_slider_<?php echo $uniqid; ?> cmsms_owl_slider"> <?php foreach ($cmsms_post_images as $cmsms_post_image) { echo '<div>' . '<figure>' . wp_get_attachment_image($cmsms_post_image, 'post-thumbnail', false, array( 'class' => 'full-width', 'alt' => cmsms_title(get_the_ID(), false), 'title' => cmsms_title(get_the_ID(), false) )) . '</figure>' . '</div>'; } ?> </div> <?php } elseif (sizeof($cmsms_post_images) == 1 && $cmsms_post_images[0] != '') { cmsms_thumb(get_the_ID(), 'post-thumbnail', false, 'img_' . get_the_ID(), true, true, true, true, $cmsms_post_images[0]); } elseif (has_post_thumbnail()) { cmsms_thumb(get_the_ID(), 'post-thumbnail', false, 'img_' . get_the_ID(), true, true, true, true, false); } } echo '<div class="cmsms_post_cont_inner">' . '<span class="cmsms_post_format_img cmsms_theme_icon_camera"></span>' . '<div class="cmsms_post_cont_info_wrap">'; cmsms_post_heading(get_the_ID(), 'h4'); if ($author || $categories || $tags) { echo '<div class="cmsms_post_cont_info entry-meta">'; $author ? cmsms_post_author('page') : ''; $categories ? cmsms_post_category('page') : ''; $tags ? cmsms_post_tags('page') : ''; echo '</div>'; } echo '</div>' . '<div class="cl"></div>'; cmsms_post_exc_cont(); echo '</div>'; if ($likes || $comments || $more) { echo '<footer class="cmsms_post_footer entry-meta">'; $comments ? cmsms_post_comments('page') : ''; $likes ? cmsms_post_like('page') : ''; $more ? cmsms_post_more(get_the_ID()) : ''; echo '</footer>'; } ?> </div> </article> <!--_________________________ Finish Gallery Article _________________________ -->
arturoceballos/Qualified-Applicator-Specialist
wp-content/themes/agrofields/framework/postType/blog/page/timeline/gallery.php
PHP
gpl-2.0
4,108
<?php /** * Your Inspiration Themes * * @package WordPress * @subpackage Your Inspiration Themes * @author Your Inspiration Themes Team <info@yithemes.com> * * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-3.0.txt */ /** * Extends classic WP_Nav_Menu_Edit * * @since 1.0.0 */ class YIT_Walker_Nav_Menu_Div extends YIT_Walker_Nav_Menu { function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "\n<div class=\"submenu clearfix\">\n"; $output .= "\n$indent<ul class=\"sub-menu clearfix\">\n"; } function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n".($depth ? "$indent\n" : ""); $output .= "\n</div>\n"; } function start_el(&$output, $item, $depth = 0, $args = array(), $current_object_id = 0) { $item_output = ''; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $this->_load_custom_fields( $item ); $class_names = $value = ''; $children_number = isset($args->children_number) ? $args->children_number : '0'; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names .= ' menu-item-children-' . $children_number; if($depth == 1 && $this->_is_custom_item( $item ) ) { $class_names .= ' menu-item-custom-content'; } $class_names = ' class="'. esc_attr( $class_names ) . '"'; $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $prepend = ''; $append = ''; // $description = ! empty( $item->description ) ? $item->description : ''; $icon = ''; $image = ''; if( ! empty( $item->description ) ){ $description = $item->description; if( preg_match('/\[icon ([a-zA-Z0-9-:]+)\]/', $description, $matches) ){ $icon = do_shortcode('[icon icon_theme="'.$matches[1].'" color="inherit"]'); } if( preg_match('/\[background ([a-zA-Z0-9\-\_\/\:\~\.\s\%]*\.(jpg|jpeg|png|gif))\]/', $description, $matches) ){ $image_id = yit_get_attachment_id( $matches[1] ); list( $matches[1], $thumbnail_width, $thumbnail_height ) = wp_get_attachment_image_src( $image_id, "full" ); $image = "<a class='custom-item-{$item->ID} custom-item-yitimage custom-item-image' href='". esc_attr( $item->url ) ."'><img src='". $matches[1] ."' alt='". apply_filters( 'the_title', $item->title, $item->ID ) ."' width='". $thumbnail_width ."' height='". $thumbnail_height ."' /></a>"; } } $item_output = $args->before; if($depth == 1 && $this->_is_custom_item( $item ) ) { $item_output .= '<a'. $attributes .'>'.$icon; $item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $this->_parse_string($item->title), $item->ID ).$append; $item_output .= $args->link_after; $item_output .= '</a>'.$image; } else { $item_output .= '<a'. $attributes .'>'.$icon; $item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $this->_parse_string($item->title), $item->ID ).$append; $item_output .= $args->link_after; $item_output .= '</a>'.$image; } $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } }
lieison/IndustriasFenix
wp-content/themes/bishop/theme/assets/lib/Walker_Nav_Menu_Div.php
PHP
gpl-2.0
4,536
#ifndef QGOOGLEAUTHENTICATOR_H #define QGOOGLEAUTHENTICATOR_H #include "qgoogleauthenticator_global.h" #include <QDateTime> #include <QtEndian> #include "base32.h" #include "hmac.h" #define SECRET_LENGTH 16 #define VERIFICATION_CODE_MODULUS (1000*1000) // Six digits class QGOOGLEAUTHENTICATORSHARED_EXPORT QGoogleAuthenticator { public: static QString getCode(QByteArray secret, quint64 time = 0); static bool checkCode(QString code, QByteArray secret); static QByteArray generate_secret(); }; #endif // QGOOGLEAUTHENTICATOR_H
iMoritz/QGoogleAuthenticator
qgoogleauthenticator.hpp
C++
gpl-2.0
545
<?php /** * @name Geocode Factory * @package geoFactory * @copyright Copyright © 2013 - All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Cédric Pelloquin aka Rick <info@myJoom.com> * @website www.myJoom.com */ defined('_JEXEC') or die; JLoader::register('GeofactoryHelper', JPATH_COMPONENT.'/helpers/geofactory.php'); class GeofactoryViewMarkerset extends JViewLegacy{ protected $form; protected $item; protected $state; /** * Display the view */ public function display($tpl = null){ // Initialise variables. $this->form = $this->get('Form'); $this->item = $this->get('Item'); $this->state= $this->get('State'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } $this->addToolbar(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 1.6 */ protected function addToolbar() { JFactory::getApplication()->input->set('hidemainmenu', true); $user = JFactory::getUser(); $isNew = ($this->item->id == 0); $checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('id')); $canDo = GeofactoryHelperAdm::getActions(); JToolbarHelper::title($isNew ? JText::_('COM_GEOFACTORY_MARKERSETS_NEW_MARKERSET') : JText::_('COM_GEOFACTORY_MARKERSETS_EDIT_MARKERSET')); // If not checked out, can save the item. if (!$checkedOut && ($canDo->get('core.edit')||$canDo->get('core.create'))) { JToolbarHelper::apply('markerset.apply'); JToolbarHelper::save('markerset.save'); } if (!$checkedOut && $canDo->get('core.create')) { JToolbarHelper::save2new('markerset.save2new'); } // If an existing item, can save to a copy. if (!$isNew && $canDo->get('core.create')) { JToolbarHelper::save2copy('markerset.save2copy'); } if (empty($this->item->id)) { JToolbarHelper::cancel('markerset.cancel'); } else { JToolbarHelper::cancel('markerset.cancel', 'JTOOLBAR_CLOSE'); } // JToolbarHelper::divider(); // JToolbarHelper::help('COM_GEOFACTORY_HELP_XXX'); } }
naka211/daekcenter
administrator/components/com_geofactory/views/markerset/view.html.php
PHP
gpl-2.0
2,149
package de.tkprog.MiSeLoR; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.tkprog.log.Logger; public class MiSeLoR { private Database currentDatabase; public static MiSeLoR THIS; public static Logger log; public static void main(String[] args){ (new File("log/")).mkdir(); log = new Logger("log/MiSeLoR_"+System.currentTimeMillis()+".log"); log.setLogToCLI(true); log.setLogToFile(true); log.logAll(true); new MiSeLoR(); } public MiSeLoR(){ try { THIS = this; currentDatabase = new Database("MiSeLoR_current.db"); Message.initialise(cD()); SimpleMessage.initialise(cD()); ChatMessage.initialise(cD()); LoginMessage.initialise(cD()); LeftGameMessage.initialise(cD()); ServerOverloadMessage.initialise(cD()); DeathMessage.initialise(cD()); EarnedAchievementMessage.initialise(cD()); JoinMessage.initialise(cD()); LostConnectionMessage.initialise(cD()); MovedWronglyMessage.initialise(cD()); PlayerOnlineMessage.initialise(cD()); SavingWorldDataMessage.initialise(cD()); ServerChatMessage.initialise(cD()); UUIDofPlayerIsMessage.initialise(cD()); cmd(); } catch (Exception e) { e.printStackTrace(); } } private void cmd() { boolean running = true; BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println(); do{ try { System.out.print("> "); String input = bf.readLine(); if(input != null){ if(Pattern.matches("help|\\?|\\\\\\?|\\\\help", input)){ System.out.println("Commands:\r\n"+ "\thelp|?|\\?|\\help - Shows this help\r\n"+ "\tparse <dd> <mm> <yyyy> <file name> - parses the given file for the given day // file name can use Regex\r\n"+ "\tparses <file name> - parses the given file (\"yyyy-mm-dd-x.log\") for the given day // file name can use Regex\r\n"+ "\tuptime <player name> - shows the uptime for the player\r\n"+ "\tall - shows a summary\r\n"+ "\tgetAllPlayer - shows all saved player\r\n"+ "\tleaderboard - Shows some leaderboard\r\n"+ "\texit - exits the program"); } else if(Pattern.matches("parse\\s\\d{2}\\s\\d{2}\\s\\d{4}\\s(\\S*)", input)){ Pattern p = Pattern.compile("parse\\s(\\d{2})\\s(\\d{2})\\s(\\d{4})\\s(\\S*)"); Matcher mm = p.matcher(input); mm.find(); File[] f = getFiles(mm.group(4)); for(File ff : f){ Commands.parse(Integer.parseInt(mm.group(1)), Integer.parseInt(mm.group(2)), Integer.parseInt(mm.group(3)), ff.getAbsolutePath()); } } else if(Pattern.matches("parses\\s(\\S*)", input)){ Pattern p = Pattern.compile("parses\\s(\\S*)"); Matcher mm = p.matcher(input); mm.find(); String filename = mm.group(1); File[] f = getFiles(filename); for(File ff : f){ p = Pattern.compile("(\\d{4})\\-(\\d{2})\\-(\\d{2})\\-\\d*\\.log"); mm = p.matcher(ff.getName()); mm.find(); Commands.parse(Integer.parseInt(mm.group(3)), Integer.parseInt(mm.group(2)), Integer.parseInt(mm.group(1)), ff.getAbsolutePath()); } } else if(Pattern.matches("uptime\\s(\\S*)", input)){ Pattern p = Pattern.compile("uptime\\s(\\S*)"); Matcher mm = p.matcher(input); mm.find(); Commands.uptime(mm.group(1)); } else if(Pattern.matches("all", input)){ Commands.all(); } else if(Pattern.matches("exit", input)){ Commands.exit(); } else if(Pattern.matches("getAllPlayer", input)){ String[] s = Commands.getAllPlayers(); for(String ss : s){ System.out.println(ss); } } else if(Pattern.matches("leaderboard", input)){ Commands.showLeaderboard(cD()); } else{ System.out.println("The command \""+input+"\" wasn't recognized. Type in \"help\"."); } } } catch (Exception e) { e.printStackTrace(); } } while(running); } private File[] getFiles(String fileregex) { File f = new File("."); if(!f.isDirectory()){ f = f.getParentFile(); } if(!f.isDirectory()){ System.err.println("Sollte ned passieren..."); } File[] ff = f.listFiles(); ArrayList<File> o = new ArrayList<File>(); for(File fff : ff){ if(Pattern.matches(fileregex, fff.getName())){ o.add(fff); } else{ System.out.println("\""+fileregex+"\" does not match \""+fff.getName()+"\""); } } File[] ffff = new File[o.size()]; int i = 0; for(File fff : o){ ffff[i] = fff; i++; } return ffff; } public Database cD() { return getCurrentDatabase(); } public Database getCurrentDatabase() { return currentDatabase; } public void setCurrentDatabase(Database currentDatabase) { this.currentDatabase = currentDatabase; } }
TKPROG/MiSeLoR
src/de/tkprog/MiSeLoR/MiSeLoR.java
Java
gpl-2.0
5,164
//Copyright (c) 2008-2010 Emil Dotchevski and Reverge Studios, Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/qvm/q_access.hpp> #include <boost/qvm/v_access.hpp> struct my_quat { }; namespace boost { namespace qvm { template <> struct q_traits<my_quat> { typedef int scalar_type; template <int I> static int r( my_quat const & ); template <int I> static int & w( my_quat & ); }; } } int main() { using namespace boost::qvm; my_quat const q=my_quat(); q%V%A<3>(); return 1; }
ducis/cuda-brute-force-vision
cuda_vision/libs/qvm/test/access_q_fail.cpp
C++
gpl-2.0
780
<?php die("Access Denied"); ?>#x#s:4974:" 1449928439 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw"> <head> <script type="text/javascript"> var siteurl='/'; var tmplurl='/templates/ja_mendozite/'; var isRTL = false; </script> <base href="http://zon-com-tw.sensetop.com/zh/component/mailto/" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="榮憶橡膠工業股份有限公司" /> <title>榮憶橡膠工業股份有限公司 | 榮憶橡膠工業股份有限公司</title> <link href="http://zon-com-tw.sensetop.com/zh/component/mailto/?tmpl=component&amp;template=ja_mendozite&amp;link=e1f4f626a47fd15186a91af8f9e1fb73f9256db5" rel="canonical" /> <link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" /> <link rel="stylesheet" href="/t3-assets/css_f383c.css" type="text/css" /> <script src="/en/?jat3action=gzip&amp;jat3type=js&amp;jat3file=t3-assets%2Fjs_46b57.js" type="text/javascript"></script> <script type="text/javascript"> function keepAlive() { var myAjax = new Request({method: "get", url: "index.php"}).send();} window.addEvent("domready", function(){ keepAlive.periodical(840000); }); </script> <script type="text/javascript"> var akoption = { "colorTable" : true , "opacityEffect" : true , "foldContent" : true , "fixingElement" : true , "smoothScroll" : false } ; var akconfig = new Object(); akconfig.root = 'http://zon-com-tw.sensetop.com/' ; akconfig.host = 'http://'+location.host+'/' ; AsikartEasySet.init( akoption , akconfig ); </script> <!--[if ie]><link href="/plugins/system/jat3/jat3/base-themes/default/css/template-ie.css" type="text/css" rel="stylesheet" /><![endif]--> <!--[if ie 7]><link href="/plugins/system/jat3/jat3/base-themes/default/css/template-ie7.css" type="text/css" rel="stylesheet" /><![endif]--> <!--[if ie 7]><link href="/templates/ja_mendozite/css/template-ie7.css" type="text/css" rel="stylesheet" /><![endif]--> <link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-60602086-1', 'auto'); ga('send', 'pageview'); </script> <link rel="stylesheet" href="http://zon-com-tw.sensetop.com/easyset/css/custom-typo.css" type="text/css" /> <link rel="stylesheet" href="http://zon-com-tw.sensetop.com/easyset/css/custom.css" type="text/css" /> </head> <body id="bd" class="fs3 com_mailto contentpane"> <div id="system-message-container"> <div id="system-message"> </div> </div> <script type="text/javascript"> Joomla.submitbutton = function(pressbutton) { var form = document.getElementById('mailtoForm'); // do field validation if (form.mailto.value == "" || form.from.value == "") { alert('請提供正確的電子郵件。'); return false; } form.submit(); } </script> <div id="mailto-window"> <h2> 推薦此連結給朋友。 </h2> <div class="mailto-close"> <a href="javascript: void window.close()" title="關閉視窗"> <span>關閉視窗 </span></a> </div> <form action="http://zon-com-tw.sensetop.com/index.php" id="mailtoForm" method="post"> <div class="formelm"> <label for="mailto_field">寄信給</label> <input type="text" id="mailto_field" name="mailto" class="inputbox" size="25" value=""/> </div> <div class="formelm"> <label for="sender_field"> 寄件者</label> <input type="text" id="sender_field" name="sender" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="from_field"> 您的郵件</label> <input type="text" id="from_field" name="from" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="subject_field"> 主旨</label> <input type="text" id="subject_field" name="subject" class="inputbox" value="" size="25" /> </div> <p> <button class="button" onclick="return Joomla.submitbutton('send');"> 送出 </button> <button class="button" onclick="window.close();return false;"> 取消 </button> </p> <input type="hidden" name="layout" value="default" /> <input type="hidden" name="option" value="com_mailto" /> <input type="hidden" name="task" value="send" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="link" value="e1f4f626a47fd15186a91af8f9e1fb73f9256db5" /> <input type="hidden" name="86ceffa305434e25a4582b7d307b089d" value="1" /> </form> </div> </body> </html>";
ForAEdesWeb/AEW32
cache/t3_pages/e8efe7956197beb28b5e158ad88f292e-cache-t3_pages-eda25a734db4561a48963667955ba148.php
PHP
gpl-2.0
4,982
/** * This file is part of the Goobi viewer - a content presentation and management application for digitized objects. * * Visit these websites for more information. * - http://www.intranda.com * - http://digiverso.com * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.goobi.viewer.model.cms; import java.util.Locale; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.goobi.viewer.model.cms.CMSStaticPage; public class CMSStaticPageTest { private CMSStaticPage page = new CMSStaticPage("test"); @Before public void setUp() { } @Test public void testGetPageName() { Assert.assertEquals("test", page.getPageName()); } @Test public void testIsLanguageComplete() { Assert.assertFalse(page.isLanguageComplete(Locale.GERMANY)); } @Test public void testHasCmsPage() { Assert.assertFalse(page.isHasCmsPage()); } }
intranda/goobi-viewer-core
goobi-viewer-core/src/test/java/io/goobi/viewer/model/cms/CMSStaticPageTest.java
Java
gpl-2.0
1,546
/** * Util of json ajax. * author: firstboy * require: jquery */ function Jsoncallback(url, callback, method, data, loadid) { if (loadid) $('#'+loadid).fadeIn(200); $.ajax({ type: method, data: data, scriptCharset: 'UTF-8', dataType: 'json', url: url, success: function(json) { if (loadid) $('#'+loadid).fadeOut(200); callback(json); }, error: function(json, textStatus, errorThrown) { if (loadid) $('#'+loadid).fadeOut(200); alert('[ERROR] -- JSON CALLBACK:\n' + '[ERROR:textStatus]: ' + textStatus + '[ERROR:errorThrown]: ' + errorThrown + '[ERROR:json.responseText]: ' + json.responseText); } }); } function getURLParameter(name) { return decodeURI( (RegExp(name + "=" + "(.+?)(&|$)").exec(location.search)||[,null])[1] ); } function addslashes(string) { return string.replace(/\\/g, '\\\\'). replace(/\u0008/g, '\\b'). replace(/\t/g, '\\t'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/'/g, '\\\''). replace(/"/g, '\\"'); } function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); } function ltrim(str){ return str.replace(/(^\s*)/g,""); } function rtrim(str){ return str.replace(/(\s*$)/g,""); }
firstboy0513/lexstat
cgi/js/util.js
JavaScript
gpl-2.0
1,281
TESTS = { "Level_1": [ { "input": [1, 2, 3], "answer": 2, "explanation": "3-1=2" }, { "input": [5, -5], "answer": 10, "explanation": "5-(-5)=10" }, { "input": [10.2, -2.2, 0, 1.1, 0.5], "answer": 12.4, "explanation": "10.2-(-2.2)=12.4" }, { "input": [], "answer": 0, "explanation": "Empty" }, {"input": [-99.9, 99.9], "answer": 199.8, "explanation": "99.9-(-99.9)"}, {"input": [1, 1], "answer": 0, "explanation": "1-1"}, {"input": [0, 0, 0, 0], "answer": 0, "explanation": "0-0"}, {"input": [36.0, -26.0, -7.5, 0.9, 0.53, -6.6, -71.0, 0.53, -48.0, 57.0, 69.0, 0.063, -4.7, 0.01, 9.2], "answer": 140.0, "explanation": "69.0-(-71.0)"}, {"input": [-0.035, 0.0, -0.1, 83.0, 0.28, 60.0], "answer": 83.1, "explanation": "83.0-(-0.1)"}, {"input": [0.02, 0.93, 0.066, -94.0, -0.91, -21.0, -7.2, -0.018, 26.0], "answer": 120.0, "explanation": "26.0-(-94.0)"}, {"input": [89.0, 0.014, 2.9, -1.2, 5.8], "answer": 90.2, "explanation": "89.0-(-1.2)"}, {"input": [-69.0, 0.0, 0.0, -0.051, -0.021, -0.81], "answer": 69.0, "explanation": "0.0-(-69.0)"}, {"input": [-0.07], "answer": 0.0, "explanation": "-0.07-(-0.07)"}, {"input": [0.074, 0.12, -0.4, 4.0, -1.7, 3.0, -5.1, 0.57, -54.0, -41.0, -5.2, -5.6, 3.8, 0.054, -35.0, -5.0, -0.005, 0.034], "answer": 58.0, "explanation": "4.0-(-54.0)"}, {"input": [29.0, 0.47, -4.5, -6.7, -0.051, -0.82, -0.074, -4.0, -0.015, -0.015, -8.0, -0.43], "answer": 37.0, "explanation": "29.0-(-8.0)"}, {"input": [-0.036, -0.11, -0.55, -64.0], "answer": 63.964, "explanation": "-0.036-(-64.0)"}, {"input": [-0.092, -0.079, -0.31, -0.87, -28.0, -6.2, -0.097, -5.8, -0.025, -28.0, -4.7, -2.9, -8.0, -0.093, -13.0, -73.0], "answer": 72.975, "explanation": "-0.025-(-73.0)"}, {"input": [-0.015, 7.6], "answer": 7.615, "explanation": "7.6-(-0.015)"}, {"input": [-46.0, 0.19, -0.08, -4.0, 4.4, 0.071, -0.029, -0.034, 28.0, 0.043, -97.0], "answer": 125.0, "explanation": "28.0-(-97.0)"}, {"input": [32.0, -0.07, -0.056, -6.4, 0.084], "answer": 38.4, "explanation": "32.0-(-6.4)"}, {"input": [0.017, 0.015, 0.69, 0.78], "answer": 0.765, "explanation": "0.78-0.015"}, ] }
Empire-of-Code-Puzzles/checkio-empire-most-numbers
verification/src/tests.py
Python
gpl-2.0
2,790
/* * This file is part of the OpenNos Emulator Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ using System.ComponentModel.DataAnnotations; using OpenNos.Domain; namespace OpenNos.Data { public class CharacterRelationDTO : MappingBaseDTO { #region Properties public long CharacterId { get; set; } [Key] public long CharacterRelationId { get; set; } public long RelatedCharacterId { get; set; } public CharacterRelationType RelationType { get; set; } #endregion } }
OpenNos/OpenNos
OpenNos.Data/CharacterRelationDTO.cs
C#
gpl-2.0
1,055
#include <iostream> #include <fstream> #include <sstream> #include <cstdint> #include <stdexcept> #include <math.h> #include <opennfs/cloud.h> #include <opennfs/opengl.h> #include <opennfs/billboard.h> namespace visualizer { void CloudLayer::enable_light_shafts() { _light_shafts_enabled = true; } void CloudLayer::disable_light_shafts() { _light_shafts_enabled = false; } float CloudLayer::rayleigh(float a) { return 0.75f * (1 + cos(a)*cos(a)); } float CloudLayer::henyey_greenstein(float a, float g) { return (1-g*g)/pow(1+g*g-2*g*cos(a), 1.5f); } float CloudLayer::color(float a, float Ik) { return albedo * extinction * rayleigh(a) * Ik / (4*M_PI); } void CloudLayer::position(float x, float y, float z) { m->position(x, y, z); cloud_x = x; cloud_y = y; cloud_z = z; } void CloudLayer::set_observer_position(float x, float y, float z) { eye_x = x; eye_y = y; eye_z = z; } void CloudLayer::set_sun_position(float x, float y, float z) { sun_x = x; sun_y = y; sun_z = z; } void CloudLayer::set_sun_position(float azimuth, float elevation) { sun_azimuth = azimuth; sun_elevation = elevation; } float CloudLayer::phase_function(types::XYZ p, types::XYZ *delta) { static int cnt=0; cnt++; p.x+=cloud_x; p.y+=cloud_y; p.z+=cloud_z; float o[3] = { p.x-eye_x, p.y-eye_y, p.z-eye_z }; float l[3] = { sun_x-eye_x, sun_y-eye_y, sun_z-eye_z }; float Oxz = o[0]*o[0] + o[2]*o[2]; float Oyz = o[1]*o[1] + o[2]*o[2]; float os = sqrt(Oxz + o[1]*o[1]); float ls = sqrt(l[0]*l[0] + l[1]*l[1] + l[2]*l[2]); float phi = asinf(o[1] / os); // float theta = asinf(o[0] / (os*sin(phi))); float Ux = 1.0f; float Uy = 1.0f; float Uz = 0.0f; float Vx = 1.0f; float Vy = Uz * sin(phi) + Uy * cos(phi); float Vz = Uz * cos(phi) - Uy * sin(phi); //Ux = Vx; //Uz = Vz; //Vz = Uz * cos(theta) + Ux * sin(theta); //Vx = -Uz * sin(theta) + Ux * cos(theta); o[0]/=os; o[1]/=os; o[2]/=os; l[0]/=ls; l[1]/=ls; l[2]/=ls; delta->x = Vx; delta->y = Vy; delta->z = -Vz; float cos_Phi = (o[0]*l[0] + o[1]*l[1] + o[2]*l[2]); phi = acos(cos_Phi); #if 0 if(0==(cnt&511)) { std::cout << "P: " << p.x << ", " << p.y << ", " << p.z << std::endl; std::cout << "L: " << sun_x << ", " << sun_y << ", " << sun_z << std::endl; std::cout << "O: " << eye_x << ", " << eye_y << ", " << eye_z << std::endl; std::cout << "O-P: " << o[0] << ", " << o[1] << ", " << o[2] << std::endl; std::cout << "P-L: " << l[0] << ", " << l[1] << ", " << l[2] << std::endl; std::cout << "COS_PHI: " << cos_Phi << std::endl; std::cout << "PHI: " << phi << std::endl; } #endif // the phase function should just say the probability of scattering in certain direction // however we don't compute that yet. // we use the function bellow for glowing the angles close to sun directions and decaling the other // ones. That's obviously not scattering and this method is not doing what phase function should do. float k = henyey_greenstein(0.99f, phi); float sol_elevation_ratio = fabs(2 * sun_elevation / M_PI); k=std::max(k, 0.7f + 0.2f*sol_elevation_ratio); return k; } void CloudLayer::drawVoxel(types::voxel_t *v, Billboard *billboard) { float red = sun_red * v->c; float green = sun_green * v->c; float blue = sun_blue * v->c; float alpha = blend_factor_from_vapor(v->vapor, dissipation); //alpha = 0.01f; types::XYZ p = v->p; #ifdef _CLOUD_PHASE_FUNCTION /* shade the clouds based on phase function */ float k = phase_function(p, &(v->delta)); red *= k; green *= k; blue *= k; red = std::min(1.0f, red); green=std::min(1.0f, green); blue=std::min(1.0f, blue); #endif glColor4f( red, green, blue, alpha); //glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //billboard.billboardSphericalBegin(p.x, p.y, p.z); float dx = v->delta.x; float dy = v->delta.y; float dz = v->delta.z; //dx=dy=1.0f; //dz=0.0f; #if 1 float r = v->r ; //Billboard billboard(position); billboard->draw(p.x, p.y, p.z, r, r); //billboard.billboardEnd(); #else //dx = 1500.0f / os; float r = v->r * dx; glPointSize(r); glBegin(GL_POINTS); glVertex3f(p.x, p.y, p.z); glEnd(); #endif } void CloudLayer::draw(float position[3]) { //std::cout << "VOXELS SZ: " << voxels.size() << std::endl; sort_voxels cmp_voxels(this); glPushMatrix(); glMultMatrixf(m->get()); glPointSize(3.0f); glEnable(GL_POINT_SMOOTH) ; glBegin(GL_POINTS); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(sun_x-cloud_x, sun_y-cloud_y, sun_z-cloud_z); glEnd(); std::sort(voxels.begin(), voxels.end(), cmp_voxels); //std::sort(basement.begin(), basement.end(), cmp_voxels); Billboard billboard(position); billboard.position(cloud_x, cloud_y, cloud_z); material->draw(); float c=1.0f; glBegin(GL_QUADS); for(size_t idx=0; idx<voxels.size(); idx++) { //for(size_t idx=0; idx<500; idx++) { types::voxel_t *v = voxels.at(idx); //billboard.cheatSphericalBegin(); drawVoxel(v, &billboard); //billboard.end(); } glEnd(); #if 0 base->draw(); for(size_t idx=0; idx<basement.size(); idx++) { types::voxel_t *v = basement.at(idx); //billboard.cheatSphericalBegin(); drawVoxel(v, &billboard); //billboard.end(); } #endif //exit(0); glPopMatrix(); light_shafts(); } void CloudLayer::set_dissipation(float a) { dissipation = a; } void CloudLayer::read_cloud_map(std::string pathname) { std::fstream cloud_map_file(pathname, std::ios::in); if( !cloud_map_file.is_open() ) { std::cerr << "Error opening file: " << pathname << std::endl; throw std::runtime_error("can't open file!"); } std::string rgb_component; while (cloud_map_file >> rgb_component) { std::stringstream ss; ss << std::hex << rgb_component; unsigned int rgb; ss >> rgb; unsigned char mass = rgb&0x0ff; cloud_mass.push_back(mass); } cloud_map_file.close(); size_t mass_no = cloud_mass.size(); size_t w = sqrt(mass_no) ; std::cout << "SIZE: " << mass_no << " SQRT= " << w << std::endl; if(w*w != mass_no) { throw std::runtime_error("cloud definition file must be power of two!"); } // initialize cloud mass storage cloud_map_width = w; cloud3d = new types::voxel_t**[w]; for(size_t i=0; i<w; i++) { cloud3d[i] = new types::voxel_t*[w]; } for(size_t i=0; i<w; i++) for(size_t j=0; j<w; j++) { cloud3d[i][j] = new types::voxel_t[CLOUD_MAX_LAYER_HEIGHT]; } Uint32 *lightmap_pixels = new Uint32[mass_no]; for(int i=0; i<mass_no; i++) { unsigned char mass = cloud_mass.at(i); unsigned char R, G, B, A; R=G=B=0xff; if(mass>0x80) A=0; else { A=0x80 - mass; } Uint32 color = (A<<24) | (B << 16) | (G << 8) | R; lightmap_pixels[i]=color; } std::cout << "LIGHT MAP Texture " << std::endl; lightmap->texture_from_data(w, w, lightmap_pixels); std::cout << "LIGHT MAP Texture Done" << std::endl; } void CloudLayer::generate() { float cx=1.0; float cy=0.0; float cz=0.0; double dx=2.0/128; double dy=4.0/128; double ra; double h; int k,t; types::XYZ p = { cx, cy, cz }; int cl_cnt=0; for(size_t j=0;j<cloud_map_width;j++) { cx=0.0; for(size_t i=0;i<cloud_map_width;i++) { ra=0.03; p.x=cx * scale; p.y=cy * scale; p.z=cz * scale; k=0; h = get_mass(i,j); cloud3d[i][j][k].p=p; cloud3d[i][j][k].r=10.95; cloud3d[i][j][k].h=h; cloud3d[i][j][0].top=0; cloud3d[i][j][k].draw=0; cloud3d[i][j][k].vapor=0; //fprintf(stderr,"[%d %d %d]: h=%4f t=%d\n",i,j,k,h,t); t= (int)(h*h*10); //t=(int)(h*10); for( cy=0,k=0; k < t ; k++, cy+=dx ) { struct { float x,y,z; } random_shift = { -0.5f + random()/(float)(RAND_MAX), -0.5f + random()/(float)(RAND_MAX), -0.5f + random()/(float)(RAND_MAX) }; p.x=cx * scale; p.y=cy * scale; p.z=cz * scale; #ifndef _CLOUD_PARTICLE_RADIUS # warning "Please define the _CLOUD_PARTICLE_RADIUS in Makefile." # define _CLOUD_PARTICLE_RADIUS 2.5f #endif //double r=0.06f * scale; double r = _CLOUD_PARTICLE_RADIUS*scale * 2.0/256 ; if(k==0) r*=2; else if(k==1) r*=1.75f; else r*=1.5f; p.x += 0.5f * r * random_shift.x; p.y += 0.5f * r * random_shift.y; p.z += 0.5f * r * random_shift.z; cloud3d[i][j][k].p=p; cloud3d[i][j][k].r=r; cloud3d[i][j][k].h=h; cloud3d[i][j][0].top=t; cloud3d[i][j][k].draw=1; cloud3d[i][j][k].vapor= t-k; if( cloud3d[i][j][k].vapor > max_vapor ) max_vapor=t-k; // fprintf(stderr,"[%d %d %d]: h=%4f t=%d\n",i,j,k,h,t); } cl_cnt+=t; cx+=dx; } cz+=dy; } } void CloudLayer::optimize() { int cl_removed=0; types::XYZ p; for(size_t i=0;i<cloud_map_width;i++) { for(size_t j=0;j<cloud_map_width;j++) { for(int k=cloud3d[i][j][0].top;k>=0;k--){ if( !cloud3d[i][j][k].draw ) continue; cloud3d[i][j][k].surf=CLOUD_SURF_NORMAL; cloud3d[i][j][k].c=1.0; cloud3d[i][j][k].a=cloud3d[i][j][k].vapor; //std::cout << "cloud H: " << cloud3d[i][j][k].h << "TOP: " << cloud3d[i][j][k].top << std::endl; if(k==1) { cloud3d[i][j][k].c=1.0-cloud3d[i][j][k].h/3; } if( !k ) { cloud3d[i][j][k].c=1.0-cloud3d[i][j][k].h/2; } #if 0 if( remove_cloud_cell(i-1,j,k) && remove_cloud_cell(i+1,j,k) && remove_cloud_cell(i,j-1,k) && remove_cloud_cell(i,j+1,k) && remove_cloud_cell(i,j,k-1) && remove_cloud_cell(i,j,k+1) ) { cloud3d[i][j][k].draw=0; cl_removed++; } #endif if( !cloud3d[i][j][k].draw ) continue; if( !k) { cloud3d[i][j][k].surf=CLOUD_SURF_BOTTOM_LAYER; } cloud3d[i][j][k].r+=(rand()&0xff)/(double)0xff/50; if(k==0) { voxels.push_back(&cloud3d[i][j][k]); } else { voxels.push_back(&cloud3d[i][j][k]); } } } } } float CloudLayer::get_mass(size_t i, size_t j) { return cloud_mass.at(i + j*cloud_map_width) / 256.0f; } bool CloudLayer::remove_cloud_cell(ssize_t i, ssize_t j, ssize_t k) { if( i<0 ) return false; if( i>=cloud_map_width-1 ) return false; if( j<0 ) return false; if( j>=cloud_map_width-1 ) return false; if( k<0 ) return false; if( k>=cloud3d[i][j][0].top ) return false; if( cloud3d[i][j][0].top <= k) return false; return true; } float CloudLayer::blend_factor_from_vapor(float vapor, float a) { float v = vapor/max_vapor; // return 3*v*v*a; return a*vapor*vapor; } void CloudLayer::set_sun_color(float color[3]) { sun_red = color[0]; sun_green = color[1]; sun_blue = color[2]; } void CloudLayer::evolve(int hour, int minute) { float min_dissipation = 0.0001f; float max_dissipation = 1.0f; float d = max_dissipation - min_dissipation; int start_hour = 8; int peak_hour = 14; int end_hour = 19; int ps = peak_hour - start_hour; int pe = end_hour - peak_hour; if(hour<start_hour || hour>end_hour) dissipation = min_dissipation; if(hour<peak_hour) { float t = (hour-start_hour) + minute/60.0f; dissipation = min_dissipation + t*d/ps; } else { float t = (hour-peak_hour) + minute/60.0f; dissipation = max_dissipation - t*d/pe; } } // Project the point x, cloud_y, z into point with y==0.0f types::XYZ CloudLayer::project(float x, float y, float z) { types::XYZ v = { .x = x - sun_x, .y = y - sun_y, .z = z - sun_z }; float t = - sun_y / v.y; types::XYZ T = { .x = sun_x + v.x*t, .y = 0.0f, .z = sun_z + v.z*t }; return T; } types::UV CloudLayer::uv(types::XYZ P) { types::UV texture; float range_x = 2/128.0f * scale * cloud_map_width ; float range_z = 4/128.0f * scale * cloud_map_width ; if(P.y == cloud_y) { texture.u = (P.x - cloud_x) / range_x; texture.v = (P.z - cloud_z) / range_z; return texture; } types::XYZ v = { .x = P.x - sun_x, .y = P.y - sun_y, .z = P.z - sun_z }; float t = (cloud_y - sun_y) / v.y; float x = sun_x + v.x*t; float z = sun_z + v.z*t; texture.u = (x - cloud_x) / range_x; texture.v = (z - cloud_z) / range_z; return texture; } void CloudLayer::render_plate(types::XYZ A, types::XYZ B, types::XYZ C, types::XYZ D, float v) { float dx1 = A.x - B.x; float dy1 = A.y - B.y; float dz1 = A.z - B.z; float dx2 = C.x - D.x; float dy2 = C.y - D.y; float dz2 = C.z - D.z; float top = sqrt(dx1*dx1 + dy1*dy1 + dz1*dz1); float bottom = sqrt(dx2*dx2 + dy2*dy2 + dz2*dz2); float w = top / bottom; glTexCoord4f(0.0f, v*w, 0.0f, w); glVertex3f(A.x, A.y, A.z); glTexCoord4f(w, v*w, 0.0f, w); glVertex3f(B.x, B.y, B.z); glTexCoord2f(1.0f, v); glVertex3f(C.x, C.y, C.z); glTexCoord2f(0.0f, v); glVertex3f(D.x, D.y, D.z); } void CloudLayer::set_air_humidity(float humidity) { air_hum_alpha = humidity; } void CloudLayer::light_shafts() { if(!_light_shafts_enabled) { return; } // render light shafts only when we are under the cloud layer if(eye_y > cloud_y) return; if(sun_y < 2*cloud_y) return; lightmap->draw(); glDisable(GL_LIGHTING); //glDisable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBegin(GL_QUADS); glColor4f(1.0f, 1.0f, 1.0f, air_hum_alpha); float range_x = 2/128.0f * scale * cloud_map_width ; float range_z = 4/128.0f * scale * cloud_map_width ; for(float z=cloud_z; z<cloud_z+range_z; z+=100.0f) { types::XYZ A = {cloud_x, cloud_y, z}; types::XYZ B = {cloud_x+range_x, cloud_y, z}; types::XYZ C = project(cloud_x+range_x, cloud_y, z); types::XYZ D = project(cloud_x, cloud_y, z); render_plate(A, B, C, D, (z-cloud_z)/range_z); } glEnd(); glEnable(GL_LIGHTING); } }
mixaal/opennfs
src/cloud.cc
C++
gpl-2.0
13,419
#include "commands.h" Commands* Commands::Instance () { static Commands t; return &t; } Commands::Commands() { settings = Settings::Instance(); critterselection = Critterselection::Instance(); registerCmd("quit", &Commands::quit); registerCmd("decreaseenergy", &Commands::decreaseenergy); registerCmd("increaseenergy", &Commands::increaseenergy); registerCmd("dec_foodmaxenergy", &Commands::decreasefoodmaxenergy); registerCmd("inc_foodmaxenergy", &Commands::increasefoodmaxenergy); registerCmd("dec_worldsizex", &Commands::dec_worldsizex); registerCmd("inc_worldsizex", &Commands::inc_worldsizex); registerCmd("dec_worldsizey", &Commands::dec_worldsizey); registerCmd("inc_worldsizey", &Commands::inc_worldsizey); registerCmd("dec_worldsizez", &Commands::dec_worldsizez); registerCmd("inc_worldsizez", &Commands::inc_worldsizez); registerCmd("loadallcritters", &WorldB::loadAllCritters); registerCmd("saveallcritters", &WorldB::saveAllCritters); registerCmd("insertcritter", &WorldB::insertCritter); registerCmd("killhalfofcritters", &WorldB::killHalfOfCritters); registerCmd("camera_resetposition", &WorldB::resetCamera); registerCmd("toggle_pause", &WorldB::togglePause); registerCmd("toggle_sleeper", &WorldB::toggleSleeper); registerCmd("toggle_mouselook", &WorldB::toggleMouselook); registerCmd("critter_select", &WorldB::selectBody); registerCmd("critter_deselect", &WorldB::deselectBody); registerCmd("critter_pick", &WorldB::pickBody); registerCmd("critter_unpick", &WorldB::unpickBody); registerCmd("camera_moveup", &Commands::camera_moveup); registerCmd("camera_movedown", &Commands::camera_movedown); registerCmd("camera_moveforward", &Commands::camera_moveforward); registerCmd("camera_movebackward", &Commands::camera_movebackward); registerCmd("camera_moveleft", &Commands::camera_moveleft); registerCmd("camera_moveright", &Commands::camera_moveright); registerCmd("camera_lookup", &Commands::camera_lookup); registerCmd("camera_lookdown", &Commands::camera_lookdown); registerCmd("camera_lookleft", &Commands::camera_lookleft); registerCmd("camera_lookright", &Commands::camera_lookright); registerCmd("camera_rollleft", &Commands::camera_rollleft); registerCmd("camera_rollright", &Commands::camera_rollright); registerCmd("camera_lookhorizontal", &Commands::camera_lookhorizontal); registerCmd("camera_lookvertical", &Commands::camera_lookvertical); registerCmd("camera_movehorizontal", &Commands::camera_movehorizontal); registerCmd("camera_movevertical", &Commands::camera_movevertical); registerCmd("gui_togglepanel", &Maincanvas::swapChild); registerCmd("gui_toggle", &Maincanvas::swap); registerCmd("settings_saveprofile", &Settings::saveProfile); registerCmd("settings_increase", &Settings::increaseCVar); registerCmd("settings_decrease", &Settings::decreaseCVar); registerCmd("cs_unregister", &Critterselection::unregisterCritterVID); // registerCmd("cs_select", &Critterselection::selectCritterVID); registerCmd("cs_select", &Commands::selectCritter); registerCmd("cs_selectall", &Commands::selectCritterAll); registerCmd("cs_clear", &Critterselection::clear); registerCmd("cs_kill", &WorldB::removeSelectedCritter); registerCmd("cs_killall", &WorldB::removeAllSelectedCritters); registerCmd("cs_duplicate", &WorldB::duplicateSelectedCritter); registerCmd("cs_spawnbrainmutant", &WorldB::spawnBrainMutantSelectedCritter); registerCmd("cs_spawnbodymutant", &WorldB::spawnBodyMutantSelectedCritter); registerCmd("cs_spawnbrainbodymutant", &WorldB::spawnBrainBodyMutantSelectedCritter); registerCmd("cs_duplicateall", &WorldB::duplicateAllSelectedCritters); registerCmd("cs_spawnbrainmutantall", &WorldB::spawnBrainMutantAllSelectedCritters); registerCmd("cs_spawnbodymutantall", &WorldB::spawnBodyMutantAllSelectedCritters); registerCmd("cs_spawnbrainbodymutantall", &WorldB::spawnBrainBodyMutantAllSelectedCritters); registerCmd("cs_feed", &WorldB::feedSelectedCritter); registerCmd("cs_resetage", &WorldB::resetageSelectedCritter); } void Commands::registerCmd(string name, void (Commands::*pt2Func)()) { cmd* c = new cmd(); c->commandtype = T_COMMAND; c->argtype = A_NOARG; c->commandsMember = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Commands::*pt2Func)(const unsigned int&)) { cmd* c = new cmd(); c->commandtype = T_COMMAND; c->argtype = A_UINT; c->commandsMember_uint = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (WorldB::*pt2Func)()) { cmd* c = new cmd(); c->commandtype = T_WORLD; c->argtype = A_NOARG; c->worldMember = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Maincanvas::*pt2Func)()) { cmd* c = new cmd(); c->commandtype = T_CANVAS; c->argtype = A_NOARG; c->canvasMember = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Maincanvas::*pt2Func)(const string&)) { cmd* c = new cmd(); c->commandtype = T_CANVAS; c->argtype = A_STRING; c->canvasMember_string = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Settings::*pt2Func)()) { cmd* c = new cmd(); c->commandtype = T_SETTINGS; c->argtype = A_NOARG; c->settingsMember = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Settings::*pt2Func)(const string&)) { cmd* c = new cmd(); c->commandtype = T_SETTINGS; c->argtype = A_STRING; c->settingsMember_string= pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Critterselection::*pt2Func)()) { cmd* c = new cmd(); c->commandtype = T_CS; c->argtype = A_NOARG; c->critterselectionMember = pt2Func; cmdlist[name] = c; } void Commands::registerCmd(string name, void (Critterselection::*pt2Func)(const unsigned int&)) { cmd* c = new cmd(); c->commandtype = T_CS; c->argtype = A_UINT; c->critterselectionMember_uint= pt2Func; cmdlist[name] = c; } // fixme private void Commands::execCmd(const string& name) { if ( cmdlist[name]->commandtype == T_COMMAND ) (this->*cmdlist[name]->commandsMember)(); else if ( cmdlist[name]->commandtype == T_WORLD ) (world->*cmdlist[name]->worldMember)(); else if ( cmdlist[name]->commandtype == T_CS ) (critterselection->*cmdlist[name]->critterselectionMember)(); else if ( cmdlist[name]->commandtype == T_CANVAS ) (canvas->*cmdlist[name]->canvasMember)(); else if ( cmdlist[name]->commandtype == T_SETTINGS ) (settings->*cmdlist[name]->settingsMember)(); } void Commands::execCmd(const string& name, const string& str) { if ( cmdlist[name]->commandtype == T_CANVAS ) (canvas->*cmdlist[name]->canvasMember_string)(str); else if ( cmdlist[name]->commandtype == T_SETTINGS ) (settings->*cmdlist[name]->settingsMember_string)(str); } void Commands::execCmd(const string& name, const unsigned int& ui) { if ( cmdlist[name]->commandtype == T_CS ) (critterselection->*cmdlist[name]->critterselectionMember_uint)(ui); else if ( cmdlist[name]->commandtype == T_COMMAND ) (this->*cmdlist[name]->commandsMember_uint)(ui); } // fixme public void Commands::execCmd(const cmdsettings& cmds) { // first check if called function exists if ( cmdlist[cmds.name] ) { // check if expected types match if ( cmdlist[cmds.name]->argtype == cmds.argtype ) { if ( cmds.argtype == A_NOARG ) execCmd(cmds.name); else if ( cmds.argtype == A_STRING ) execCmd(cmds.name, cmds.args); else if ( cmds.argtype == A_UINT ) execCmd(cmds.name, cmds.argui); } else cerr << "command '" << cmds.name << "'s args do not match: got " << cmds.argtype << " but expected " << cmdlist[cmds.name]->argtype << endl; } // else // cerr << "command '" << cmds.name << "' does not exist" << endl; } void Commands::quit() { SDL_Quit(); exit(0); } void Commands::selectCritterAll() { critterselection->clear(); for ( unsigned int i=0; i < world->critters.size(); i++ ) critterselection->registerCritter(world->critters[i]); } void Commands::selectCritter(const unsigned int& c) { canvas->swapChild("critterview"); critterselection->selectCritterVID(c); } void Commands::decreaseenergy() { if ( ( (int)settings->getCVar("energy") - 1 ) >= 0 ) { settings->setCVar("energy", settings->getCVar("energy")-1 ); world->freeEnergy -= settings->getCVar("food_maxenergy"); stringstream buf; buf << "energy: " << settings->getCVar("energy"); Logbuffer::Instance()->add(buf); } } void Commands::increaseenergy() { settings->setCVar("energy", settings->getCVar("energy")+1 ); world->freeEnergy += settings->getCVar("food_maxenergy"); stringstream buf; buf << "energy: " << settings->getCVar("energy"); Logbuffer::Instance()->add(buf); } void Commands::decreasefoodmaxenergy() { if ( ( (int)settings->getCVar("food_maxenergy") - 1 ) >= 0 ) { world->freeEnergy -= settings->getCVar("energy"); settings->setCVar("food_maxenergy", settings->getCVar("food_maxenergy")-1 ); } } void Commands::increasefoodmaxenergy() { world->freeEnergy += settings->getCVar("energy"); settings->setCVar("food_maxenergy", settings->getCVar("food_maxenergy")+1 ); } void Commands::dec_worldsizex() { settings->decreaseCVar("worldsizeX"); world->makeFloor(); } void Commands::inc_worldsizex() { settings->increaseCVar("worldsizeX"); world->makeFloor(); } void Commands::dec_worldsizey() { settings->decreaseCVar("worldsizeY"); world->makeFloor(); } void Commands::inc_worldsizey() { settings->increaseCVar("worldsizeY"); world->makeFloor(); } void Commands::dec_worldsizez() { settings->decreaseCVar("worldsizeZ"); world->makeFloor(); } void Commands::inc_worldsizez() { settings->increaseCVar("worldsizeZ"); world->makeFloor(); } // camera ops void Commands::camera_moveup() { world->camera.moveUp(0.01f); world->movePickedBodyFrom(); } void Commands::camera_movedown() { world->camera.moveDown(0.01f); world->movePickedBodyFrom(); } void Commands::camera_moveforward() { world->camera.moveForward(0.01f); world->movePickedBodyFrom(); } void Commands::camera_movebackward() { world->camera.moveBackward(0.01f); world->movePickedBodyFrom(); } void Commands::camera_moveleft() { world->camera.moveLeft(0.01f); world->movePickedBodyFrom(); } void Commands::camera_moveright() { world->camera.moveRight(0.01f); world->movePickedBodyFrom(); } void Commands::camera_lookup() { world->camera.lookUp(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_lookdown() { world->camera.lookDown(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_lookleft() { world->camera.lookLeft(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_lookright() { world->camera.lookRight(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_rollleft() { world->camera.rollLeft(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_rollright() { world->camera.rollRight(0.001f); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_lookhorizontal() { world->camera.lookRight((float)world->relx/3000); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_lookvertical() { world->camera.lookDown((float)world->rely/3000); world->calcMouseDirection(); world->movePickedBodyTo(); } void Commands::camera_movehorizontal() { world->camera.moveRight((float)world->relx/300); world->movePickedBodyFrom(); } void Commands::camera_movevertical() { world->camera.moveDown((float)world->rely/300); world->movePickedBodyFrom(); } Commands::~Commands() { for( cmdit = cmdlist.begin(); cmdit != cmdlist.end(); cmdit++ ) delete cmdit->second; }
bobke/Critterding
src/utils/commands.cpp
C++
gpl-2.0
11,700
# _*_ coding:utf-8 _*_ # Filename:ClientUI.py # Python在线聊天客户端 from socket import * from ftplib import FTP import ftplib import socket import thread import time import sys import codecs import os reload(sys) sys.setdefaultencoding( "utf-8" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): self.usr=usr self.pwd=pwd #设置目标用户 def setToUsr(self,toUsr): self.toUsr=toUsr self.ChatFormTitle=toUsr #设置ip地址和端口号 def setLocalANDPort(self,local,port): self.local = local self.port = port def check_info(self): self.buffer = 1024 self.ADDR=(self.local,self.port) self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM) self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR) self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer) s=self.serverMsg.split('##') if s[0]=='Y': return True elif s[0]== 'N': return False #接收消息 def receiveMessage(self): self.buffer = 1024 self.ADDR=(self.local,self.port) self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM) self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR) while True: #连接建立,接收服务器端消息 self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer) s=self.serverMsg.split('##') if s[0]=='Y': #self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......') return True elif s[0]== 'N': #self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......') return False elif s[0]=='CLOSE': i=5 while i>0: self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......') time.sleep(1) i=i-1 self.chatText.delete(Tkinter.END) os._exit(0) #好友列表 elif s[0]=='F': for eachFriend in s[1:len(s)]: print eachFriend #好友上线 elif s[0]=='0': theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了') #好友下线 elif s[0]=='1': theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了') #好友传来消息 elif s[0]=='2': theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n') self.chatText.insert(Tkinter.END, ' ' + s[3]) #好友传来文件 elif s[0]=='3': filename=s[2] f=FTP('192.168.1.105') f.login('Coder', 'xianjian') f.cwd(self.usr) filenameD=filename[:-1].encode("cp936") try: f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write) except ftplib.error_perm: print 'ERROR:cannot read file "%s"' %file self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成') elif s[0]=='4': agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)') if agreement=='Y': self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR) elif agreement=='N': self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR) elif s[0]=='5': if s[3]=='Y': print s[2]+'接受了你的好友请求' elif s[3]=='N': print s[2]+'拒绝了你的好友请求' #发送消息 def sendMessage(self): #得到用户在Text中输入的消息 message = self.inputText.get('1.0',Tkinter.END) #格式化当前的时间 theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.chatText.insert(Tkinter.END, theTime +' 我 说:\n') self.chatText.insert(Tkinter.END,' ' + message + '\n') self.udpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR); #清空用户在Text中输入的消息 self.inputText.delete(0.0,message.__len__()-1.0) #传文件 def sendFile(self): filename = self.inputText.get('1.0',Tkinter.END) theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n') self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n') f=FTP('192.168.1.105') f.login('Coder', 'xianjian') f.cwd(self.toUsr) filenameU=filename[:-1].encode("cp936") try: #f.retrbinary('RETR '+filename,open(filename,'wb').write) #将文件上传到服务器对方文件夹中 f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb')) except ftplib.error_perm: print 'ERROR:cannot read file "%s"' %file self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR); #加好友 def addFriends(self): message= self.inputText.get('1.0',Tkinter.END) s=message.split('##') self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR); #关闭消息窗口并退出 def close(self): self.udpCliSock.sendto('1##'+self.usr,self.ADDR); sys.exit() #启动线程接收服务器端的消息 def startNewThread(self): thread.start_new_thread(self.receiveMessage,()) def main(): client = ClientMessage() client.setLocalANDPort('192.168.1.105', 8808) client.setUsrANDPwd('12073127', '12073127') client.setToUsr('12073128') client.startNewThread() if __name__=='__main__': main()
gzxultra/IM_programming
class_ClientMessage.py
Python
gpl-2.0
6,373
/*! Responsive JS Library v1.2.2 */ /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ window.matchMedia = window.matchMedia || (function(doc, undefined){ var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement('body'), div = doc.createElement('div'); div.id = 'mq-test-1'; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = '&shy;<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>'; docElem.insertBefore(fakeBody, refNode); bool = div.offsetWidth == 42; docElem.removeChild(fakeBody); return { matches: bool, media: q }; }; })(document); /*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ (function( win ){ //exposed namespace win.respond = {}; //define update even in native-mq-supporting browsers, to avoid errors respond.update = function(){}; //expose media query support flag for external use respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches; //if media queries are supported, exit here if( respond.mediaQueriesSupported ){ return; } //define vars var doc = win.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName( "head" )[0] || docElem, base = doc.getElementsByTagName( "base" )[0], links = head.getElementsByTagName( "link" ), requestQueue = [], //loop stylesheets, send text content to translate ripCSS = function(){ var sheets = links, sl = sheets.length, i = 0, //vars for loop: sheet, href, media, isCSS; for( ; i < sl; i++ ){ sheet = sheets[ i ], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; //only links plz and prevent re-parsing if( !!href && isCSS && !parsedSheets[ href ] ){ // selectivizr exposes css through the rawCssText expando if (sheet.styleSheet && sheet.styleSheet.rawCssText) { translate( sheet.styleSheet.rawCssText, href, media ); parsedSheets[ href ] = true; } else { if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) || href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){ requestQueue.push( { href: href, media: media } ); } } } } makeRequests(); }, //recurse through request queue, get css text makeRequests = function(){ if( requestQueue.length ){ var thisRequest = requestQueue.shift(); ajax( thisRequest.href, function( styles ){ translate( styles, thisRequest.href, thisRequest.media ); parsedSheets[ thisRequest.href ] = true; makeRequests(); } ); } }, //find media blocks in css text, convert to style blocks translate = function( styles, href, media ){ var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ), ql = qs && qs.length || 0, //try to get CSS path href = href.substring( 0, href.lastIndexOf( "/" )), repUrls = function( css ){ return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" ); }, useMedia = !ql && media, //vars used in loop i = 0, j, fullq, thisq, eachq, eql; //if path exists, tack on trailing slash if( href.length ){ href += "/"; } //if no internal queries exist, but media attr does, use that //note: this currently lacks support for situations where a media attr is specified on a link AND //its associated stylesheet has internal CSS media queries. //In those cases, the media attribute will currently be ignored. if( useMedia ){ ql = 1; } for( ; i < ql; i++ ){ j = 0; //media attr if( useMedia ){ fullq = media; rules.push( repUrls( styles ) ); } //parse for styles else{ fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1; rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); } eachq = fullq.split( "," ); eql = eachq.length; for( ; j < eql; j++ ){ thisq = eachq[ j ]; mediastyles.push( { media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all", rules : rules.length - 1, hasquery: thisq.indexOf("(") > -1, minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) } ); } } applyMedia(); }, lastCall, resizeDefer, // returns the value of 1em in pixels getEmValue = function() { var ret, div = doc.createElement('div'), body = doc.body, fakeUsed = false; div.style.cssText = "position:absolute;font-size:1em;width:1em"; if( !body ){ body = fakeUsed = doc.createElement( "body" ); body.style.background = "none"; } body.appendChild( div ); docElem.insertBefore( body, docElem.firstChild ); ret = div.offsetWidth; if( fakeUsed ){ docElem.removeChild( body ); } else { body.removeChild( div ); } //also update eminpx before returning ret = eminpx = parseFloat(ret); return ret; }, //cached container for 1em value, populated the first time it's needed eminpx, //enable/disable styles applyMedia = function( fromResize ){ var name = "clientWidth", docElemProp = docElem[ name ], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, styleBlocks = {}, lastLink = links[ links.length-1 ], now = (new Date()).getTime(); //throttle resize calls if( fromResize && lastCall && now - lastCall < resizeThrottle ){ clearTimeout( resizeDefer ); resizeDefer = setTimeout( applyMedia, resizeThrottle ); return; } else { lastCall = now; } for( var i in mediastyles ){ var thisstyle = mediastyles[ i ], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em"; if( !!min ){ min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } if( !!max ){ max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ if( !styleBlocks[ thisstyle.media ] ){ styleBlocks[ thisstyle.media ] = []; } styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); } } //remove any existing respond style element(s) for( var i in appendedEls ){ if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){ head.removeChild( appendedEls[ i ] ); } } //inject active styles, grouped by media type for( var i in styleBlocks ){ var ss = doc.createElement( "style" ), css = styleBlocks[ i ].join( "\n" ); ss.type = "text/css"; ss.media = i; //originally, ss was appended to a documentFragment and sheets were appended in bulk. //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! head.insertBefore( ss, lastLink.nextSibling ); if ( ss.styleSheet ){ ss.styleSheet.cssText = css; } else { ss.appendChild( doc.createTextNode( css ) ); } //push to appendedEls to track for later removal appendedEls.push( ss ); } }, //tweaked Ajax functions from Quirksmode ajax = function( url, callback ) { var req = xmlHttp(); if (!req){ return; } req.open( "GET", url, true ); req.onreadystatechange = function () { if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){ return; } callback( req.responseText ); } if ( req.readyState == 4 ){ return; } req.send( null ); }, //define ajax obj xmlHttp = (function() { var xmlhttpmethod = false; try { xmlhttpmethod = new XMLHttpRequest(); } catch( e ){ xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" ); } return function(){ return xmlhttpmethod; }; })(); //translate CSS ripCSS(); //expose update for re-running respond later on respond.update = ripCSS; //adjust on resize function callMedia(){ applyMedia( true ); } if( win.addEventListener ){ win.addEventListener( "resize", callMedia, false ); } else if( win.attachEvent ){ win.attachEvent( "onresize", callMedia ); } })(this); /** * jQuery Scroll Top Plugin 1.0.0 */ jQuery(document).ready(function ($) { $('a[href=#scroll-top]').click(function () { $('html, body').animate({ scrollTop: 0 }, 'slow'); return false; }); }); /*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery)); /*global jQuery */ /*jshint multistr:true browser:true */ /*! * FitVids 1.0 * * Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ * * Date: Thu Sept 01 18:00:00 2011 -0500 */ (function( $ ){ "use strict"; $.fn.fitVids = function( options ) { var settings = { customSelector: null }; var div = document.createElement('div'), ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0]; div.className = 'fit-vids-style'; div.innerHTML = '&shy;<style> \ .fluid-width-video-wrapper { \ width: 100%; \ position: relative; \ padding: 0; \ } \ \ .fluid-width-video-wrapper iframe, \ .fluid-width-video-wrapper object, \ .fluid-width-video-wrapper embed { \ position: absolute; \ top: 0; \ left: 0; \ width: 100%; \ height: 100%; \ } \ </style>'; ref.parentNode.insertBefore(div,ref); if ( options ) { $.extend( settings, options ); } return this.each(function(){ var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='www.youtube.com']", "iframe[src*='www.youtube-nocookie.com']", "iframe[src*='fast.wistia.com']", "embed" ]; if (settings.customSelector) { selectors.push(settings.customSelector); } var $allVideos = $(this).find(selectors.join(',')); $allVideos.each(function(){ var $this = $(this); if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(), width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(), aspectRatio = height / width; if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%"); $this.removeAttr('height').removeAttr('width'); }); }); }; })( jQuery ); /*! * Mobile Menu */ (function($) { var current = $('.main-nav li.current-menu-item a').html(); current = $('.main-nav li.current_page_item a').html(); if( $('span').hasClass('custom-mobile-menu-title') ) { current = $('span.custom-mobile-menu-title').html(); } else if( typeof current == 'undefined' || current === null ) { if( $('body').hasClass('home') ) { if( $('#logo span').hasClass('site-name') ) { current = $('#logo .site-name a').html(); } else { current = $('#logo img').attr('alt'); } } else { if( $('body').hasClass('woocommerce') ) { current = $('h1.page-title').html(); } else if( $('body').hasClass('archive') ) { current = $('h6.title-archive').html(); } else if( $('body').hasClass('search-results') ) { current = $('h6.title-search-results').html(); } else if( $('body').hasClass('page-template-blog-excerpt-php') ) { current = $('.current_page_item').text(); } else if( $('body').hasClass('page-template-blog-php') ) { current = $('.current_page_item').text(); } else { current = $('h1.post-title').html(); } } }; $('.main-nav').append('<a id="responsive_menu_button"></a>'); $('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>'); $('a#responsive_menu_button, #responsive_current_menu_item').click(function(){ $('.js .main-nav .menu').slideToggle( function() { if( $(this).is(':visible') ) { $('a#responsive_menu_button').addClass('responsive-toggle-open'); } else { $('a#responsive_menu_button').removeClass('responsive-toggle-open'); $('.js .main-nav .menu').removeAttr('style'); } }); }); })(jQuery); // Close the mobile menu when clicked outside of it. (function($) { $('html').click(function() { // Check if the menu is open, close in that case. if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){ $('.js .main-nav .menu').slideToggle( function() { $('a#responsive_menu_button').removeClass('responsive-toggle-open'); $('.js .main-nav .menu').removeAttr('style'); }); } }) })(jQuery); // Stop propagation on click on menu. jQuery('.main-nav').click(function(event){ var pathname = window.location.pathname; if( pathname != '/wp-admin/customize.php' ){ event.stopPropagation(); } }); // Placeholder jQuery(function(){ jQuery('input[placeholder], textarea[placeholder]').placeholder(); }); // FitVids jQuery(document).ready(function(){ // Target your #container, #wrapper etc. jQuery("#wrapper").fitVids(); }); // Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player): // jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"}); // Selectors are comma separated, just like CSS // Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids.
kevinreilly/ivsn-wp
wp-content/themes/responsive/core/js-dev/responsive-scripts.js
JavaScript
gpl-2.0
21,660
/* * aTunes * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors * * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package net.sourceforge.atunes.kernel.modules.context.audioobject; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.SwingConstants; import net.sourceforge.atunes.kernel.modules.context.AbstractContextPanelContent; import net.sourceforge.atunes.model.ILocalAudioObject; import net.sourceforge.atunes.model.IStateContext; import net.sourceforge.atunes.utils.I18nUtils; /** * Basic information about an audio object * @author alex * */ public class AudioObjectBasicInfoContent extends AbstractContextPanelContent<AudioObjectBasicInfoDataSource> { private static final long serialVersionUID = 996227362636450601L; /** * Image for Audio Object */ private JLabel audioObjectImage; /** * Title of audio object */ private JLabel audioObjectTitle; /** * Artist of audio object */ private JLabel audioObjectArtist; /** * Last date played this audio object */ private JLabel audioObjectLastPlayDate; private IStateContext stateContext; private AbstractAction addLovedSongInLastFMAction; private AbstractAction addBannedSongInLastFMAction; /** * @param addBannedSongInLastFMAction */ public void setAddBannedSongInLastFMAction(AbstractAction addBannedSongInLastFMAction) { this.addBannedSongInLastFMAction = addBannedSongInLastFMAction; } /** * @param addLovedSongInLastFMAction */ public void setAddLovedSongInLastFMAction(AbstractAction addLovedSongInLastFMAction) { this.addLovedSongInLastFMAction = addLovedSongInLastFMAction; } /** * @param stateContext */ public void setStateContext(IStateContext stateContext) { this.stateContext = stateContext; } @Override public void clearContextPanelContent() { super.clearContextPanelContent(); audioObjectImage.setIcon(null); audioObjectImage.setBorder(null); audioObjectTitle.setText(null); audioObjectArtist.setText(null); audioObjectLastPlayDate.setText(null); addLovedSongInLastFMAction.setEnabled(false); addBannedSongInLastFMAction.setEnabled(false); } @Override public void updateContentFromDataSource(AudioObjectBasicInfoDataSource source) { ImageIcon image = source.getImage(); if (image != null) { audioObjectImage.setIcon(image); } audioObjectTitle.setText(source.getTitle()); audioObjectArtist.setText(source.getArtist()); audioObjectLastPlayDate.setText(source.getLastPlayDate()); // TODO: Allow these options for radios where song information is available addLovedSongInLastFMAction.setEnabled(stateContext.isLastFmEnabled() && source.getAudioObject() instanceof ILocalAudioObject); addBannedSongInLastFMAction.setEnabled(stateContext.isLastFmEnabled() && source.getAudioObject() instanceof ILocalAudioObject); } @Override public String getContentName() { return I18nUtils.getString("INFO"); } @Override public Component getComponent() { // Create components audioObjectImage = new JLabel(); audioObjectTitle = new JLabel(); audioObjectTitle.setHorizontalAlignment(SwingConstants.CENTER); audioObjectTitle.setFont(getLookAndFeelManager().getCurrentLookAndFeel().getContextInformationBigFont()); audioObjectArtist = new JLabel(); audioObjectArtist.setHorizontalAlignment(SwingConstants.CENTER); audioObjectLastPlayDate = new JLabel(); audioObjectLastPlayDate.setHorizontalAlignment(SwingConstants.CENTER); // Add components JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(15, 0, 0, 0); panel.add(audioObjectImage, c); c.gridx = 0; c.gridy = 1; c.weightx = 1; c.weighty = 0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 10, 0, 10); panel.add(audioObjectTitle, c); c.gridy = 2; c.insets = new Insets(5, 10, 10, 10); panel.add(audioObjectArtist, c); c.gridy = 3; panel.add(audioObjectLastPlayDate, c); return panel; } @Override public List<Component> getOptions() { List<Component> options = new ArrayList<Component>(); options.add(new JMenuItem(addLovedSongInLastFMAction)); options.add(new JMenuItem(addBannedSongInLastFMAction)); return options; } }
PDavid/aTunes
aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/context/audioobject/AudioObjectBasicInfoContent.java
Java
gpl-2.0
5,655
/* * aTunes * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors * * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package net.sourceforge.atunes.gui.views.dialogs; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import net.sourceforge.atunes.Constants; import net.sourceforge.atunes.gui.views.controls.AbstractCustomWindow; import net.sourceforge.atunes.gui.views.controls.FadeInPanel; import net.sourceforge.atunes.model.IControlsBuilder; import net.sourceforge.atunes.utils.ImageUtils; /** * The Class ExtendedToolTip. This is a special window shown as tooltip for * navigator tree objects */ public final class ExtendedToolTip extends AbstractCustomWindow { private static final long serialVersionUID = -5041702404982493070L; private final FadeInPanel imagePanel; private final JLabel image; private final JLabel line1; private final JLabel line2; private final JLabel line3; /** * Instantiates a new extended tool tip. * * @param controlsBuilder * @param width * @param height */ public ExtendedToolTip(final IControlsBuilder controlsBuilder, final int width, final int height) { super(null, width, height, controlsBuilder); setFocusableWindowState(false); JPanel container = new JPanel(new GridBagLayout()); this.image = new JLabel(); this.imagePanel = new FadeInPanel(); this.imagePanel.setLayout(new GridLayout(1, 1)); this.imagePanel.add(this.image); this.line1 = new JLabel(); this.line2 = new JLabel(); this.line3 = new JLabel(); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridheight = 3; c.insets = new Insets(0, 5, 0, 0); container.add(this.imagePanel, c); c.gridx = 1; c.gridheight = 1; c.weightx = 1; c.anchor = GridBagConstraints.WEST; // c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(10, 10, 0, 10); container.add(this.line1, c); c.gridx = 1; c.gridy = 1; c.insets = new Insets(0, 10, 0, 10); container.add(this.line2, c); c.gridx = 1; c.gridy = 2; c.weighty = 1; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(0, 10, 0, 10); container.add(this.line3, c); // Use scroll pane to draw a border consistent with look and feel JScrollPane scrollPane = controlsBuilder.createScrollPane(container); scrollPane .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); add(scrollPane); } /** * Sets the text of line 1 * * @param text * */ public void setLine1(final String text) { this.line1.setText(text); } /** * Sets the text of line 2 * * @param text * */ public void setLine2(final String text) { this.line2.setText(text); } /** * Sets the image * * @param img * the new image */ public void setImage(final ImageIcon img) { if (img != null) { // Add 50 to width to force images to fit height of tool tip as much // as possible this.image.setIcon(ImageUtils.scaleImageBicubic(img.getImage(), Constants.TOOLTIP_IMAGE_WIDTH + 50, Constants.TOOLTIP_IMAGE_HEIGHT)); this.imagePanel.setVisible(true); } else { this.image.setIcon(null); this.imagePanel.setVisible(false); } } /** * Sets the text of line 3 * * @param text * */ public void setLine3(final String text) { this.line3.setText(text); } }
PDavid/aTunes
aTunes/src/main/java/net/sourceforge/atunes/gui/views/dialogs/ExtendedToolTip.java
Java
gpl-2.0
4,283
<?php namespace TYPO3\CMS\Backend\Toolbar; /*************************************************************** * Copyright notice * * (c) 2007-2013 Ingo Renner <ingo@typo3.org> * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * A copy is found in the textfile GPL.txt and important notices to the license * from the author is found in LICENSE.txt distributed with these scripts. * * * This script 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. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Interface for classes which extend the backend by adding items to the top toolbar * * @author Ingo Renner <ingo@typo3.org> */ interface ToolbarItemHookInterface { /** * Constructor that receives a back reference to the backend * * @param \TYPO3\CMS\Backend\Controller\BackendController $backendReference TYPO3 backend object reference */ public function __construct(\TYPO3\CMS\Backend\Controller\BackendController &$backendReference = NULL); /** * Checks whether the user has access to this toolbar item * * @return boolean TRUE if user has access, FALSE if not */ public function checkAccess(); /** * Renders the toolbar item * * @return string The toolbar item rendered as HTML string */ public function render(); /** * Returns additional attributes for the list item in the toolbar * * @return string List item HTML attibutes */ public function getAdditionalAttributes(); } ?>
tonglin/pdPm
public_html/typo3_src-6.1.7/typo3/sysext/backend/Classes/Toolbar/ToolbarItemHookInterface.php
PHP
gpl-2.0
2,092
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.env; import com.caucho.quercus.program.JavaClassDef; import java.util.Calendar; import java.util.logging.Logger; /** * Represents a Quercus java Calendar value. */ public class JavaCalendarValue extends JavaValue { private static final Logger log = Logger.getLogger(JavaCalendarValue.class.getName()); private final Calendar _calendar; public JavaCalendarValue(Env env, Calendar calendar, JavaClassDef def) { super(env, calendar, def); _calendar = calendar; } /** * Converts to a long. */ @Override public long toLong() { return _calendar.getTimeInMillis(); } /** * Converts to a Java Calendar. */ @Override public Calendar toJavaCalendar() { return _calendar; } @Override public String toString() { return _calendar.getTime().toString(); } }
CleverCloud/Quercus
quercus/src/main/java/com/caucho/quercus/env/JavaCalendarValue.java
Java
gpl-2.0
1,904
<?php /** * 文件读写 * * @copyright JDphp框架 * @version 1.0.8 * @author yy */ defined('JDPHP_MAKER') || exit('Forbidden'); class cfile { /** * 写文件 * * @param string $filename * @param string $data * @param string $method * @param int $iflock * @param int $check * @param int $chmod * @return boolean */ public static function write($filename, $data, $method = 'wb+', $iflock = 1, $check = 1, $chmod = 1) { if (empty($filename)) { return false; } if ($check && strpos($filename, '..') !== false) { return false; } if (!is_dir(dirname($filename)) && !self::mkdir_recursive(dirname($filename), 0700)) { return false; } if (false == ($handle = fopen($filename, $method))) { return false; } if($iflock) { flock($handle, LOCK_EX); } fwrite($handle, $data); touch($filename); if($method == "wb+") { ftruncate($handle, strlen($data)); } fclose($handle); $chmod && @chmod($filename,0777); return true; } /** * 读文件 * * @param string $filename * @param string $method * @return string */ public static function read( $filename, $method = "rb" ) { if (strpos( $filename, '..' ) !== false) { return false; } if( $handle = @fopen( $filename, $method ) ) { flock( $handle, LOCK_SH ); $filedata = @fread( $handle, filesize( $filename ) ); fclose( $handle ); return $filedata; } else { return false; } } /** * 删除文件 * * @param string $filename * @return boolean */ public static function rm($filename) { if (strpos($filename, '..') !== false) { return false; } return @unlink($filename); } /** * 用递归方式创建目录 * * @param string $pathname * @param $mode * @return boolean */ public static function mkdir_recursive($pathname, $mode = 0700) { $pathname .= 'xx.log'; //byy1.08 if (DEBUG_LEVEL) { error_log("mkdir_recursive, $pathname, $mode\n", 3, 'debug.log'); } $pathname = rtrim(preg_replace(array('/\\{1,}/', '/\/{2,}/'), '/', $pathname), '/'); $dotpos = strrpos($pathname, '/'); //如果是路径中带文件名 if ($dotpos !== false && strpos(substr($pathname, $dotpos), '.') !== false) { $pathname = dirname($pathname); } if (is_dir($pathname)) { return true; } return mkdir($pathname, $mode, $recursive = 1); } /** * 用递归方式删除目录 * * @param string $file * @return boolean */ public static function rm_recurse($file) { if (strpos( $file, '..' ) !== false && strpos( $file, '/../' )===false ) { return false; } if (is_dir($file) && !is_link($file)) { foreach(scandir($file) as $sf) { if($sf === '..' || $sf === '.') { continue; } if (!self::rm_recurse($file . '/' . $sf)) { return false; } } return @rmdir($file); } else { return unlink($file); } } /** * 引用文件安全检查 * * @param string $filename * @param int $ifcheck * @return boolean */ public static function check_security($filename, $ifcheck=1) { if (strpos($filename, 'http://') !== false) return false; if (strpos($filename, 'https://') !== false) return false; if (strpos($filename, 'ftp://') !== false) return false; if (strpos($filename, 'ftps://') !== false) return false; if (strpos($filename, 'php://') !== false) return false; if (strpos($filename, '..') !== false) return false; return $filename; } /** * 文件列表 * * @param string $path //路径 * @param string $type[optional] //类型:file 文件,dir 目录, 缺省 file+dir * @return array */ public static function ls($path, $type = '') { if(!is_dir($path)) { return false; } if(!empty($type) && in_array($type, array('file', 'dir'))) { $func = "is_" . $type; } $files = scandir($path); foreach($files as $k => $cur_file) { if ($cur_file=="." || $cur_file==".." || $cur_file == '.svn' || ($func && !$func($path . '/' . $cur_file))) { unset($files[$k]); } } return $files; } /** * 计算目录大小 */ public static function dirsize($dir) { $dh = opendir($dir); $size = 0; while($file = readdir($dh)) { if($file != '.' and $file != '..') { $path = $dir."/".$file; if (is_dir($path)) { $size += dirsize($path); } else { $size += filesize($path); } } } closedir($dh); return $size; } /** * 获取文件大小(包含远程文件) */ public static function get_file_size($url) { $url = parse_url($url); if ($fp = @fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)) { fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])." HTTP/1.1\r\n"); fputs($fp,"Host:$url[host]\r\n\r\n"); while(!feof($fp)) { $tmp = fgets($fp); if(trim($tmp) == '') { break; } else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)) { return trim($arr[1]); } } return null; } else { return null; } } }
zy73122/jdphp
system/tool/cfile.php
PHP
gpl-2.0
5,313
vti_encoding:SR|utf8-nl vti_timelastmodified:TR|11 May 2015 07:09:03 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|jafnote1\\jafnote vti_modifiedby:SR|jafnote1\\jafnote vti_timecreated:TR|11 May 2015 07:09:03 -0000 vti_cacheddtm:TX|11 May 2015 07:09:03 -0000 vti_filesize:IR|10146 vti_cachedlinkinfo:VX|A|options-permalink.php A|options-permalink.php A|options-permalink.php I|./admin-footer.php vti_cachedsvcrellinks:VX|FAUS|jafnet.co.jp/wordpress/wp-admin/options-permalink.php FAUS|jafnet.co.jp/wordpress/wp-admin/options-permalink.php FAUS|jafnet.co.jp/wordpress/wp-admin/options-permalink.php FIUS|jafnet.co.jp/wordpress/wp-admin/admin-footer.php vti_cachedneedsrewrite:BR|true vti_cachedhasbots:BR|true vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_backlinkinfo:VX|jafnet.co.jp/wordpress/wp-admin/options-permalink.php
Siguana/square
wp-admin/_vti_cnf/options-permalink.php
PHP
gpl-2.0
867
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Crypto.Parameters { public class ECPrivateKeyParameters : ECKeyParameters { private readonly BigInteger d; public ECPrivateKeyParameters( BigInteger d, ECDomainParameters parameters) : this("EC", d, parameters) { } [Obsolete("Use version with explicit 'algorithm' parameter")] public ECPrivateKeyParameters( BigInteger d, DerObjectIdentifier publicKeyParamSet) : base("ECGOST3410", true, publicKeyParamSet) { if (d == null) throw new ArgumentNullException("d"); this.d = d; } public ECPrivateKeyParameters( string algorithm, BigInteger d, ECDomainParameters parameters) : base(algorithm, true, parameters) { if (d == null) throw new ArgumentNullException("d"); this.d = d; } public ECPrivateKeyParameters( string algorithm, BigInteger d, DerObjectIdentifier publicKeyParamSet) : base(algorithm, true, publicKeyParamSet) { if (d == null) throw new ArgumentNullException("d"); this.d = d; } public BigInteger D { get { return d; } } public override bool Equals( object obj) { if (obj == this) return true; ECPrivateKeyParameters other = obj as ECPrivateKeyParameters; if (other == null) return false; return Equals(other); } protected bool Equals( ECPrivateKeyParameters other) { return d.Equals(other.d) && base.Equals(other); } public override int GetHashCode() { return d.GetHashCode() ^ base.GetHashCode(); } } } #endif
JohnMalmsteen/mobile-apps-tower-defense
Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs
C#
gpl-2.0
2,207
package in.shabhushan.cp_trials.bits; /** * Leetcode solution for * https://leetcode.com/problems/counting-bits/submissions/ */ class CountBits { public static int[] countBits(int num) { int[] n = new int[num + 1]; for (int i = 1; i < num + 1; i++) { if (i % 2 == 0) { n[i] = n[i / 2]; } else { n[i] = n[i/2] + 1; } } return n; } }
Shashi-Bhushan/General
cp-trials/src/main/java/in/shabhushan/cp_trials/bits/CountBits.java
Java
gpl-2.0
392
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), DS = "/"; var settings = { port: 8080, indexFile: "index.html", folder: { serverside: "serverside", clientside: "clientside", static: "static_server", admin: "admin" } }; var paths = {}; paths.origin = process.cwd(); paths.base = paths.origin.slice(0, -1 * settings.folder.serverside.length - 1); paths.clientside = paths.base + DS + settings.folder.clientside; paths.serverside = paths.base + DS + settings.folder.serverside; paths.static = paths.base + DS + settings.folder.serverside + DS + settings.folder.static; clientside_exists = false; path.exists(paths.clientside, function(exists) { clientside_exists = exists; }); var static_server = http.createServer(function(request, response) { var uri = url.parse(request.url).pathname, filename; var DS_admin = DS + settings.folder.admin + DS; if (uri.slice(0, DS_admin.length) === DS_admin) { filename = path.join(paths.static, uri); } else if (clientside_exists) { filename = path.join(paths.clientside, uri); } else { filename = path.join(paths.origin, uri); } fs.exists(filename, function(exists) { if (!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } if (fs.statSync(filename).isDirectory()) { var indexFound = false; var rawlist = fs.readdirSync(filename); var filelist = []; rawlist.forEach(function(element) { if (!fs.statSync(path.join(filename, element)).isDirectory() && !indexFound) { if (element === settings.indexFile) { indexFound = true; } else { filelist.push(element); } } }); if (filelist.length > 0 && !indexFound) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(JSON.stringify(filelist)); response.end(); return; } filename = path.join(filename, settings.indexFile); } fs.readFile(filename, "binary", function(err, file) { if (err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file, "binary"); response.end(); }); }); }); static_server.listen(parseInt(settings.port, 10)); module.exports = static_server;
ninjinx/nadeplanet
serverside/static_server/static_server.js
JavaScript
gpl-2.0
2,872