diff --git a/.editorconfig b/.editorconfig index 0055396..3eba5d1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -50,7 +50,7 @@ dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion dotnet_style_predefined_type_for_member_access = true:suggestion # methods -dotnet_naming_rule.methods_must_be_capitalized.severity = error #suggestion +dotnet_naming_rule.methods_must_be_capitalized.severity = suggestion dotnet_naming_rule.methods_must_be_capitalized.symbols = methods_symbols dotnet_naming_rule.methods_must_be_capitalized.style = methods_case_style dotnet_naming_symbols.methods_symbols.applicable_kinds = method @@ -58,7 +58,7 @@ dotnet_naming_symbols.methods_symbols.applicable_accessibilities = public, priva dotnet_naming_style.methods_case_style.capitalization = pascal_case # public fields -dotnet_naming_rule.public_members_must_be_capitalized.severity = error #suggestion +dotnet_naming_rule.public_members_must_be_capitalized.severity = suggestion dotnet_naming_rule.public_members_must_be_capitalized.symbols = public_symbols dotnet_naming_rule.public_members_must_be_capitalized.style = public_case_style dotnet_naming_symbols.public_symbols.applicable_kinds = property,field,event,delegate @@ -66,7 +66,7 @@ dotnet_naming_symbols.public_symbols.applicable_accessibilities = public dotnet_naming_style.public_case_style.capitalization = pascal_case # name all constant fields using PascalCase -dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error #suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style dotnet_naming_symbols.constant_fields.applicable_kinds = field @@ -74,7 +74,7 @@ dotnet_naming_symbols.constant_fields.required_modifiers = const dotnet_naming_style.pascal_case_style.capitalization = pascal_case # internal and private fields should be _camelCase -dotnet_naming_rule.camel_case_for_private_internal_fields.severity = error #suggestion +dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style dotnet_naming_symbols.private_internal_fields.applicable_kinds = field diff --git a/External/Aga.Controls/Aga.Controls.csproj b/Aga.Controls/Aga.Controls.csproj similarity index 97% rename from External/Aga.Controls/Aga.Controls.csproj rename to Aga.Controls/Aga.Controls.csproj index 5bcfd8d..7eeadb5 100644 --- a/External/Aga.Controls/Aga.Controls.csproj +++ b/Aga.Controls/Aga.Controls.csproj @@ -1,264 +1,264 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {E73BB233-D88B-44A7-A98F-D71EE158381D} - Library - Properties - Aga.Controls - Aga.Controls - - - - - - - - - false - - - - - 3.5 - - - v4.5.2 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - Bin\Debug\ - TRACE;DEBUG;PERF_TEST - prompt - 4 - - - true - AllRules.ruleset - false - - - pdbonly - true - Bin\Release\ - TRACE - prompt - 4 - true - AllRules.ruleset - false - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - - - - - - Component - - - Component - - - Component - - - Component - - - Component - - - - - - - - - - Component - - - Component - - - Component - - - - - - - Component - - - - - Component - - - - - - Component - - - Component - - - Component - - - - - - - Component - - - - - - - - - - - - - - - Component - - - - Component - - - Component - - - Component - - - - - Component - - - Component - - - - Component - - - - - - Component - - - TreeViewAdv.cs - - - - - - - - - - - - - - - - - Designer - ResXFileCodeGenerator - Resources.Designer.cs - - - TreeViewAdv.cs - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {E73BB233-D88B-44A7-A98F-D71EE158381D} + Library + Properties + Aga.Controls + Aga.Controls + + + + + + + + + false + + + + + 3.5 + + + v4.5.2 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + Bin\Debug\ + TRACE;DEBUG;PERF_TEST + prompt + 4 + + + true + AllRules.ruleset + false + + + pdbonly + true + Bin\Release\ + TRACE + prompt + 4 + true + AllRules.ruleset + false + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + + + + + + + Component + + + Component + + + Component + + + Component + + + Component + + + + + + + + + + Component + + + Component + + + Component + + + + + + + Component + + + + + Component + + + + + + Component + + + Component + + + Component + + + + + + + Component + + + + + + + + + + + + + + + Component + + + + Component + + + Component + + + Component + + + + + Component + + + Component + + + + Component + + + + + + Component + + + TreeViewAdv.cs + + + + + + + + + + + + + + + + + Designer + ResXFileCodeGenerator + Resources.Designer.cs + + + TreeViewAdv.cs + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + \ No newline at end of file diff --git a/External/Aga.Controls/Aga.Controls.sln b/Aga.Controls/Aga.Controls.sln similarity index 97% rename from External/Aga.Controls/Aga.Controls.sln rename to Aga.Controls/Aga.Controls.sln index 72815db..9c7ba8c 100644 --- a/External/Aga.Controls/Aga.Controls.sln +++ b/Aga.Controls/Aga.Controls.sln @@ -1,20 +1,20 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E73BB233-D88B-44A7-A98F-D71EE158381D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E73BB233-D88B-44A7-A98F-D71EE158381D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/External/Aga.Controls/BitmapHelper.cs b/Aga.Controls/BitmapHelper.cs similarity index 96% rename from External/Aga.Controls/BitmapHelper.cs rename to Aga.Controls/BitmapHelper.cs index 3237db2..a29b1c2 100644 --- a/External/Aga.Controls/BitmapHelper.cs +++ b/Aga.Controls/BitmapHelper.cs @@ -1,46 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Runtime.InteropServices; -using System.Drawing.Imaging; - -namespace Aga.Controls -{ - public static class BitmapHelper - { - [StructLayout(LayoutKind.Sequential)] - private struct PixelData - { - public byte B; - public byte G; - public byte R; - public byte A; - } - - public static void SetAlphaChanelValue(Bitmap image, byte value) - { - if (image == null) - throw new ArgumentNullException("image"); - if (image.PixelFormat != PixelFormat.Format32bppArgb) - throw new ArgumentException("Wrong PixelFormat"); - - BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), - ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); - unsafe - { - PixelData* pPixel = (PixelData*)bitmapData.Scan0; - for (int i = 0; i < bitmapData.Height; i++) - { - for (int j = 0; j < bitmapData.Width; j++) - { - pPixel->A = value; - pPixel++; - } - pPixel += bitmapData.Stride - (bitmapData.Width * 4); - } - } - image.UnlockBits(bitmapData); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Drawing.Imaging; + +namespace Aga.Controls +{ + public static class BitmapHelper + { + [StructLayout(LayoutKind.Sequential)] + private struct PixelData + { + public byte B; + public byte G; + public byte R; + public byte A; + } + + public static void SetAlphaChanelValue(Bitmap image, byte value) + { + if (image == null) + throw new ArgumentNullException("image"); + if (image.PixelFormat != PixelFormat.Format32bppArgb) + throw new ArgumentException("Wrong PixelFormat"); + + BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), + ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + unsafe + { + PixelData* pPixel = (PixelData*)bitmapData.Scan0; + for (int i = 0; i < bitmapData.Height; i++) + { + for (int j = 0; j < bitmapData.Width; j++) + { + pPixel->A = value; + pPixel++; + } + pPixel += bitmapData.Stride - (bitmapData.Width * 4); + } + } + image.UnlockBits(bitmapData); + } + } +} diff --git a/External/Aga.Controls/GifDecoder.cs b/Aga.Controls/GifDecoder.cs similarity index 95% rename from External/Aga.Controls/GifDecoder.cs rename to Aga.Controls/GifDecoder.cs index fbbaffd..e611155 100644 --- a/External/Aga.Controls/GifDecoder.cs +++ b/Aga.Controls/GifDecoder.cs @@ -1,864 +1,864 @@ -#pragma warning disable 675 // Bitwise-or operator used on a sign-extended operand - -#region Java Info -/** - * Class GifDecoder - Decodes a GIF file into one or more frames. - *
- * Example:
- *    GifDecoder d = new GifDecoder();
- *    d.read("sample.gif");
- *    int n = d.getFrameCount();
- *    for (int i = 0; i < n; i++) {
- *       BufferedImage frame = d.getFrame(i);  // frame i
- *       int t = d.getDelay(i);  // display duration of frame in milliseconds
- *       // do something with frame
- *    }
- * 
- * No copyright asserted on the source code of this class. May be used for - * any purpose, however, refer to the Unisys LZW patent for any additional - * restrictions. Please forward any corrections to kweiner@fmsware.com. - * - * @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's ImageMagick. - * @version 1.03 November 2003 - * - */ -#endregion - -using System; -using System.Collections; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; - -namespace Aga.Controls -{ - public class GifFrame - { - private Image _image; - public Image Image - { - get { return _image; } - } - - private int _delay; - public int Delay - { - get { return _delay; } - } - - public GifFrame(Image im, int del) - { - _image = im; - _delay = del; - } - } - - public class GifDecoder - { - public const int StatusOK = 0;//File read status: No errors. - public const int StatusFormatError = 1; //File read status: Error decoding file (may be partially decoded) - public const int StatusOpenError = 2; //Unable to open source. - - private Stream inStream; - private int status; - - private int width; // full image width - private int height; // full image height - private bool gctFlag; // global color table used - private int gctSize; // size of global color table - private int loopCount = 1; // iterations; 0 = repeat forever - - private int[] gct; // global color table - private int[] lct; // local color table - private int[] act; // active color table - - private int bgIndex; // background color index - private int bgColor; // background color - private int lastBgColor; // previous bg color - private int pixelAspect; // pixel aspect ratio - - private bool lctFlag; // local color table flag - private bool interlace; // interlace flag - private int lctSize; // local color table size - - private int ix, iy, iw, ih; // current image rectangle - private Rectangle lastRect; // last image rect - private Image image; // current frame - private Bitmap bitmap; - private Image lastImage; // previous frame - - private byte[] block = new byte[256]; // current data block - private int blockSize = 0; // block size - - // last graphic control extension info - private int dispose = 0; - // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev - private int lastDispose = 0; - private bool transparency = false; // use transparent color - private int delay = 0; // delay in milliseconds - private int transIndex; // transparent color index - - private const int MaxStackSize = 4096; - // max decoder pixel stack size - - // LZW decoder working arrays - private short[] prefix; - private byte[] suffix; - private byte[] pixelStack; - private byte[] pixels; - - private ArrayList frames; // frames read from current file - private int frameCount; - private bool _makeTransparent; - - /** - * Gets the number of frames read from file. - * @return frame count - */ - public int FrameCount - { - get - { - return frameCount; - } - } - - /** - * Gets the first (or only) image read. - * - * @return BufferedImage containing first frame, or null if none. - */ - public Image Image - { - get - { - return GetFrame(0).Image; - } - } - - /** - * Gets the "Netscape" iteration count, if any. - * A count of 0 means repeat indefinitiely. - * - * @return iteration count if one was specified, else 1. - */ - public int LoopCount - { - get - { - return loopCount; - } - } - - public GifDecoder(Stream stream, bool makeTransparent) - { - _makeTransparent = makeTransparent; - if (Read(stream) != 0) - throw new InvalidOperationException(); - } - - /** - * Creates new frame image from current data (and previous - * frames as specified by their disposition codes). - */ - private int[] GetPixels(Bitmap bitmap) - { - int [] pixels = new int [ 3 * image.Width * image.Height ]; - int count = 0; - for (int th = 0; th < image.Height; th++) - { - for (int tw = 0; tw < image.Width; tw++) - { - Color color = bitmap.GetPixel(tw, th); - pixels[count] = color.R; - count++; - pixels[count] = color.G; - count++; - pixels[count] = color.B; - count++; - } - } - return pixels; - } - - private void SetPixels(int[] pixels) - { - int count = 0; - for (int th = 0; th < image.Height; th++) - { - for (int tw = 0; tw < image.Width; tw++) - { - Color color = Color.FromArgb( pixels[count++] ); - bitmap.SetPixel( tw, th, color ); - } - } - if (_makeTransparent) - bitmap.MakeTransparent(bitmap.GetPixel(0, 0)); - } - - private void SetPixels() - { - // expose destination image's pixels as int array - // int[] dest = - // (( int ) image.getRaster().getDataBuffer()).getData(); - int[] dest = GetPixels( bitmap ); - - // fill in starting image contents based on last image's dispose code - if (lastDispose > 0) - { - if (lastDispose == 3) - { - // use image before last - int n = frameCount - 2; - if (n > 0) - { - lastImage = GetFrame(n - 1).Image; - } - else - { - lastImage = null; - } - } - - if (lastImage != null) - { - // int[] prev = - // ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); - int[] prev = GetPixels( new Bitmap( lastImage ) ); - Array.Copy(prev, 0, dest, 0, width * height); - // copy pixels - - if (lastDispose == 2) - { - // fill last image rect area with background color - Graphics g = Graphics.FromImage( image ); - Color c = Color.Empty; - if (transparency) - { - c = Color.FromArgb( 0, 0, 0, 0 ); // assume background is transparent - } - else - { - c = Color.FromArgb( lastBgColor ) ; - // c = new Color(lastBgColor); // use given background color - } - Brush brush = new SolidBrush( c ); - g.FillRectangle( brush, lastRect ); - brush.Dispose(); - g.Dispose(); - } - } - } - - // copy each source line to the appropriate place in the destination - int pass = 1; - int inc = 8; - int iline = 0; - for (int i = 0; i < ih; i++) - { - int line = i; - if (interlace) - { - if (iline >= ih) - { - pass++; - switch (pass) - { - case 2 : - iline = 4; - break; - case 3 : - iline = 2; - inc = 4; - break; - case 4 : - iline = 1; - inc = 2; - break; - } - } - line = iline; - iline += inc; - } - line += iy; - if (line < height) - { - int k = line * width; - int dx = k + ix; // start of line in dest - int dlim = dx + iw; // end of dest line - if ((k + width) < dlim) - { - dlim = k + width; // past dest edge - } - int sx = i * iw; // start of line in source - while (dx < dlim) - { - // map color and insert in destination - int index = ((int) pixels[sx++]) & 0xff; - int c = act[index]; - if (c != 0) - { - dest[dx] = c; - } - dx++; - } - } - } - SetPixels( dest ); - } - - /** - * Gets the image contents of frame n. - * - * @return BufferedImage representation of frame. - */ - public GifFrame GetFrame(int n) - { - if ((n >= 0) && (n < frameCount)) - return (GifFrame)frames[n]; - else - throw new ArgumentOutOfRangeException(); - } - - /** - * Gets image size. - * - * @return GIF image dimensions - */ - public Size FrameSize - { - get - { - return new Size(width, height); - } - } - - /** - * Reads GIF image from stream - * - * @param BufferedInputStream containing GIF file. - * @return read status code (0 = no errors) - */ - private int Read( Stream inStream ) - { - Init(); - if ( inStream != null) - { - this.inStream = inStream; - ReadHeader(); - if (!Error()) - { - ReadContents(); - if (frameCount < 0) - { - status = StatusFormatError; - } - } - inStream.Close(); - } - else - { - status = StatusOpenError; - } - return status; - } - - - /** - * Decodes LZW image data into pixel array. - * Adapted from John Cristy's ImageMagick. - */ - private void DecodeImageData() - { - int NullCode = -1; - int npix = iw * ih; - int available, - clear, - code_mask, - code_size, - end_of_information, - in_code, - old_code, - bits, - code, - count, - i, - datum, - data_size, - first, - top, - bi, - pi; - - if ((pixels == null) || (pixels.Length < npix)) - { - pixels = new byte[npix]; // allocate new pixel array - } - if (prefix == null) prefix = new short[MaxStackSize]; - if (suffix == null) suffix = new byte[MaxStackSize]; - if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1]; - - // Initialize GIF data stream decoder. - - data_size = Read(); - clear = 1 << data_size; - end_of_information = clear + 1; - available = clear + 2; - old_code = NullCode; - code_size = data_size + 1; - code_mask = (1 << code_size) - 1; - for (code = 0; code < clear; code++) - { - prefix[code] = 0; - suffix[code] = (byte) code; - } - - // Decode GIF pixel stream. - - datum = bits = count = first = top = pi = bi = 0; - - for (i = 0; i < npix;) - { - if (top == 0) - { - if (bits < code_size) - { - // Load bytes until there are enough bits for a code. - if (count == 0) - { - // Read a new data block. - count = ReadBlock(); - if (count <= 0) - break; - bi = 0; - } - datum += (((int) block[bi]) & 0xff) << bits; - bits += 8; - bi++; - count--; - continue; - } - - // Get the next code. - - code = datum & code_mask; - datum >>= code_size; - bits -= code_size; - - // Interpret the code - - if ((code > available) || (code == end_of_information)) - break; - if (code == clear) - { - // Reset decoder. - code_size = data_size + 1; - code_mask = (1 << code_size) - 1; - available = clear + 2; - old_code = NullCode; - continue; - } - if (old_code == NullCode) - { - pixelStack[top++] = suffix[code]; - old_code = code; - first = code; - continue; - } - in_code = code; - if (code == available) - { - pixelStack[top++] = (byte) first; - code = old_code; - } - while (code > clear) - { - pixelStack[top++] = suffix[code]; - code = prefix[code]; - } - first = ((int) suffix[code]) & 0xff; - - // Add a new string to the string table, - - if (available >= MaxStackSize) - break; - pixelStack[top++] = (byte) first; - prefix[available] = (short) old_code; - suffix[available] = (byte) first; - available++; - if (((available & code_mask) == 0) - && (available < MaxStackSize)) - { - code_size++; - code_mask += available; - } - old_code = in_code; - } - - // Pop a pixel off the pixel stack. - - top--; - pixels[pi++] = pixelStack[top]; - i++; - } - - for (i = pi; i < npix; i++) - { - pixels[i] = 0; // clear missing pixels - } - - } - - /** - * Returns true if an error was encountered during reading/decoding - */ - private bool Error() - { - return status != StatusOK; - } - - /** - * Initializes or re-initializes reader - */ - private void Init() - { - status = StatusOK; - frameCount = 0; - frames = new ArrayList(); - gct = null; - lct = null; - } - - /** - * Reads a single byte from the input stream. - */ - private int Read() - { - int curByte = 0; - try - { - curByte = inStream.ReadByte(); - } - catch (IOException) - { - status = StatusFormatError; - } - return curByte; - } - - /** - * Reads next variable length block from input. - * - * @return number of bytes stored in "buffer" - */ - private int ReadBlock() - { - blockSize = Read(); - int n = 0; - if (blockSize > 0) - { - try - { - int count = 0; - while (n < blockSize) - { - count = inStream.Read(block, n, blockSize - n); - if (count == -1) - break; - n += count; - } - } - catch (IOException) - { - } - - if (n < blockSize) - { - status = StatusFormatError; - } - } - return n; - } - - /** - * Reads color table as 256 RGB integer values - * - * @param ncolors int number of colors to read - * @return int array containing 256 colors (packed ARGB with full alpha) - */ - private int[] ReadColorTable(int ncolors) - { - int nbytes = 3 * ncolors; - int[] tab = null; - byte[] c = new byte[nbytes]; - int n = 0; - try - { - n = inStream.Read(c, 0, c.Length ); - } - catch (IOException) - { - } - if (n < nbytes) - { - status = StatusFormatError; - } - else - { - tab = new int[256]; // max size to avoid bounds checks - int i = 0; - int j = 0; - while (i < ncolors) - { - int r = ((int) c[j++]) & 0xff; - int g = ((int) c[j++]) & 0xff; - int b = ((int) c[j++]) & 0xff; - tab[i++] = ( int ) ( 0xff000000 | (r << 16) | (g << 8) | b ); - } - } - return tab; - } - - /** - * Main file parser. Reads GIF content blocks. - */ - private void ReadContents() - { - // read GIF file content blocks - bool done = false; - while (!(done || Error())) - { - int code = Read(); - switch (code) - { - - case 0x2C : // image separator - ReadImage(); - break; - - case 0x21 : // extension - code = Read(); - switch (code) - { - case 0xf9 : // graphics control extension - ReadGraphicControlExt(); - break; - - case 0xff : // application extension - ReadBlock(); - String app = ""; - for (int i = 0; i < 11; i++) - { - app += (char) block[i]; - } - if (app.Equals("NETSCAPE2.0")) - { - ReadNetscapeExt(); - } - else - Skip(); // don't care - break; - - default : // uninteresting extension - Skip(); - break; - } - break; - - case 0x3b : // terminator - done = true; - break; - - case 0x00 : // bad byte, but keep going and see what happens - break; - - default : - status = StatusFormatError; - break; - } - } - } - - /** - * Reads Graphics Control Extension values - */ - private void ReadGraphicControlExt() - { - Read(); // block size - int packed = Read(); // packed fields - dispose = (packed & 0x1c) >> 2; // disposal method - if (dispose == 0) - { - dispose = 1; // elect to keep old image if discretionary - } - transparency = (packed & 1) != 0; - delay = ReadShort() * 10; // delay in milliseconds - transIndex = Read(); // transparent color index - Read(); // block terminator - } - - /** - * Reads GIF file header information. - */ - private void ReadHeader() - { - String id = ""; - for (int i = 0; i < 6; i++) - { - id += (char) Read(); - } - if (!id.StartsWith("GIF")) - { - status = StatusFormatError; - return; - } - - ReadLSD(); - if (gctFlag && !Error()) - { - gct = ReadColorTable(gctSize); - bgColor = gct[bgIndex]; - } - } - - /** - * Reads next frame image - */ - private void ReadImage() - { - ix = ReadShort(); // (sub)image position & size - iy = ReadShort(); - iw = ReadShort(); - ih = ReadShort(); - - int packed = Read(); - lctFlag = (packed & 0x80) != 0; // 1 - local color table flag - interlace = (packed & 0x40) != 0; // 2 - interlace flag - // 3 - sort flag - // 4-5 - reserved - lctSize = 2 << (packed & 7); // 6-8 - local color table size - - if (lctFlag) - { - lct = ReadColorTable(lctSize); // read table - act = lct; // make local table active - } - else - { - act = gct; // make global table active - if (bgIndex == transIndex) - bgColor = 0; - } - int save = 0; - if (transparency) - { - save = act[transIndex]; - act[transIndex] = 0; // set transparent color if specified - } - - if (act == null) - { - status = StatusFormatError; // no color table defined - } - - if (Error()) return; - - DecodeImageData(); // decode pixel data - Skip(); - - if (Error()) return; - - frameCount++; - - // create new image to receive frame data - // image = - // new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); - - bitmap = new Bitmap( width, height ); - image = bitmap; - SetPixels(); // transfer pixel data to image - - frames.Add(new GifFrame(bitmap, delay)); // add image to frame list - - if (transparency) - { - act[transIndex] = save; - } - ResetFrame(); - - } - - /** - * Reads Logical Screen Descriptor - */ - private void ReadLSD() - { - - // logical screen size - width = ReadShort(); - height = ReadShort(); - - // packed fields - int packed = Read(); - gctFlag = (packed & 0x80) != 0; // 1 : global color table flag - // 2-4 : color resolution - // 5 : gct sort flag - gctSize = 2 << (packed & 7); // 6-8 : gct size - - bgIndex = Read(); // background color index - pixelAspect = Read(); // pixel aspect ratio - } - - /** - * Reads Netscape extenstion to obtain iteration count - */ - private void ReadNetscapeExt() - { - do - { - ReadBlock(); - if (block[0] == 1) - { - // loop count sub-block - int b1 = ((int) block[1]) & 0xff; - int b2 = ((int) block[2]) & 0xff; - loopCount = (b2 << 8) | b1; - } - } while ((blockSize > 0) && !Error()); - } - - /** - * Reads next 16-bit value, LSB first - */ - private int ReadShort() - { - // read 16-bit value, LSB first - return Read() | (Read() << 8); - } - - /** - * Resets frame state for reading next image. - */ - private void ResetFrame() - { - lastDispose = dispose; - lastRect = new Rectangle(ix, iy, iw, ih); - lastImage = image; - lastBgColor = bgColor; - // int dispose = 0; - lct = null; - } - - /** - * Skips variable length blocks up to and including - * next zero length block. - */ - private void Skip() - { - do - { - ReadBlock(); - } while ((blockSize > 0) && !Error()); - } - } -} +#pragma warning disable 675 // Bitwise-or operator used on a sign-extended operand + +#region Java Info +/** + * Class GifDecoder - Decodes a GIF file into one or more frames. + *
+ * Example:
+ *    GifDecoder d = new GifDecoder();
+ *    d.read("sample.gif");
+ *    int n = d.getFrameCount();
+ *    for (int i = 0; i < n; i++) {
+ *       BufferedImage frame = d.getFrame(i);  // frame i
+ *       int t = d.getDelay(i);  // display duration of frame in milliseconds
+ *       // do something with frame
+ *    }
+ * 
+ * No copyright asserted on the source code of this class. May be used for + * any purpose, however, refer to the Unisys LZW patent for any additional + * restrictions. Please forward any corrections to kweiner@fmsware.com. + * + * @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's ImageMagick. + * @version 1.03 November 2003 + * + */ +#endregion + +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; + +namespace Aga.Controls +{ + public class GifFrame + { + private Image _image; + public Image Image + { + get { return _image; } + } + + private int _delay; + public int Delay + { + get { return _delay; } + } + + public GifFrame(Image im, int del) + { + _image = im; + _delay = del; + } + } + + public class GifDecoder + { + public const int StatusOK = 0;//File read status: No errors. + public const int StatusFormatError = 1; //File read status: Error decoding file (may be partially decoded) + public const int StatusOpenError = 2; //Unable to open source. + + private Stream inStream; + private int status; + + private int width; // full image width + private int height; // full image height + private bool gctFlag; // global color table used + private int gctSize; // size of global color table + private int loopCount = 1; // iterations; 0 = repeat forever + + private int[] gct; // global color table + private int[] lct; // local color table + private int[] act; // active color table + + private int bgIndex; // background color index + private int bgColor; // background color + private int lastBgColor; // previous bg color + private int pixelAspect; // pixel aspect ratio + + private bool lctFlag; // local color table flag + private bool interlace; // interlace flag + private int lctSize; // local color table size + + private int ix, iy, iw, ih; // current image rectangle + private Rectangle lastRect; // last image rect + private Image image; // current frame + private Bitmap bitmap; + private Image lastImage; // previous frame + + private byte[] block = new byte[256]; // current data block + private int blockSize = 0; // block size + + // last graphic control extension info + private int dispose = 0; + // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev + private int lastDispose = 0; + private bool transparency = false; // use transparent color + private int delay = 0; // delay in milliseconds + private int transIndex; // transparent color index + + private const int MaxStackSize = 4096; + // max decoder pixel stack size + + // LZW decoder working arrays + private short[] prefix; + private byte[] suffix; + private byte[] pixelStack; + private byte[] pixels; + + private ArrayList frames; // frames read from current file + private int frameCount; + private bool _makeTransparent; + + /** + * Gets the number of frames read from file. + * @return frame count + */ + public int FrameCount + { + get + { + return frameCount; + } + } + + /** + * Gets the first (or only) image read. + * + * @return BufferedImage containing first frame, or null if none. + */ + public Image Image + { + get + { + return GetFrame(0).Image; + } + } + + /** + * Gets the "Netscape" iteration count, if any. + * A count of 0 means repeat indefinitiely. + * + * @return iteration count if one was specified, else 1. + */ + public int LoopCount + { + get + { + return loopCount; + } + } + + public GifDecoder(Stream stream, bool makeTransparent) + { + _makeTransparent = makeTransparent; + if (Read(stream) != 0) + throw new InvalidOperationException(); + } + + /** + * Creates new frame image from current data (and previous + * frames as specified by their disposition codes). + */ + private int[] GetPixels(Bitmap bitmap) + { + int [] pixels = new int [ 3 * image.Width * image.Height ]; + int count = 0; + for (int th = 0; th < image.Height; th++) + { + for (int tw = 0; tw < image.Width; tw++) + { + Color color = bitmap.GetPixel(tw, th); + pixels[count] = color.R; + count++; + pixels[count] = color.G; + count++; + pixels[count] = color.B; + count++; + } + } + return pixels; + } + + private void SetPixels(int[] pixels) + { + int count = 0; + for (int th = 0; th < image.Height; th++) + { + for (int tw = 0; tw < image.Width; tw++) + { + Color color = Color.FromArgb( pixels[count++] ); + bitmap.SetPixel( tw, th, color ); + } + } + if (_makeTransparent) + bitmap.MakeTransparent(bitmap.GetPixel(0, 0)); + } + + private void SetPixels() + { + // expose destination image's pixels as int array + // int[] dest = + // (( int ) image.getRaster().getDataBuffer()).getData(); + int[] dest = GetPixels( bitmap ); + + // fill in starting image contents based on last image's dispose code + if (lastDispose > 0) + { + if (lastDispose == 3) + { + // use image before last + int n = frameCount - 2; + if (n > 0) + { + lastImage = GetFrame(n - 1).Image; + } + else + { + lastImage = null; + } + } + + if (lastImage != null) + { + // int[] prev = + // ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); + int[] prev = GetPixels( new Bitmap( lastImage ) ); + Array.Copy(prev, 0, dest, 0, width * height); + // copy pixels + + if (lastDispose == 2) + { + // fill last image rect area with background color + Graphics g = Graphics.FromImage( image ); + Color c = Color.Empty; + if (transparency) + { + c = Color.FromArgb( 0, 0, 0, 0 ); // assume background is transparent + } + else + { + c = Color.FromArgb( lastBgColor ) ; + // c = new Color(lastBgColor); // use given background color + } + Brush brush = new SolidBrush( c ); + g.FillRectangle( brush, lastRect ); + brush.Dispose(); + g.Dispose(); + } + } + } + + // copy each source line to the appropriate place in the destination + int pass = 1; + int inc = 8; + int iline = 0; + for (int i = 0; i < ih; i++) + { + int line = i; + if (interlace) + { + if (iline >= ih) + { + pass++; + switch (pass) + { + case 2 : + iline = 4; + break; + case 3 : + iline = 2; + inc = 4; + break; + case 4 : + iline = 1; + inc = 2; + break; + } + } + line = iline; + iline += inc; + } + line += iy; + if (line < height) + { + int k = line * width; + int dx = k + ix; // start of line in dest + int dlim = dx + iw; // end of dest line + if ((k + width) < dlim) + { + dlim = k + width; // past dest edge + } + int sx = i * iw; // start of line in source + while (dx < dlim) + { + // map color and insert in destination + int index = ((int) pixels[sx++]) & 0xff; + int c = act[index]; + if (c != 0) + { + dest[dx] = c; + } + dx++; + } + } + } + SetPixels( dest ); + } + + /** + * Gets the image contents of frame n. + * + * @return BufferedImage representation of frame. + */ + public GifFrame GetFrame(int n) + { + if ((n >= 0) && (n < frameCount)) + return (GifFrame)frames[n]; + else + throw new ArgumentOutOfRangeException(); + } + + /** + * Gets image size. + * + * @return GIF image dimensions + */ + public Size FrameSize + { + get + { + return new Size(width, height); + } + } + + /** + * Reads GIF image from stream + * + * @param BufferedInputStream containing GIF file. + * @return read status code (0 = no errors) + */ + private int Read( Stream inStream ) + { + Init(); + if ( inStream != null) + { + this.inStream = inStream; + ReadHeader(); + if (!Error()) + { + ReadContents(); + if (frameCount < 0) + { + status = StatusFormatError; + } + } + inStream.Close(); + } + else + { + status = StatusOpenError; + } + return status; + } + + + /** + * Decodes LZW image data into pixel array. + * Adapted from John Cristy's ImageMagick. + */ + private void DecodeImageData() + { + int NullCode = -1; + int npix = iw * ih; + int available, + clear, + code_mask, + code_size, + end_of_information, + in_code, + old_code, + bits, + code, + count, + i, + datum, + data_size, + first, + top, + bi, + pi; + + if ((pixels == null) || (pixels.Length < npix)) + { + pixels = new byte[npix]; // allocate new pixel array + } + if (prefix == null) prefix = new short[MaxStackSize]; + if (suffix == null) suffix = new byte[MaxStackSize]; + if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1]; + + // Initialize GIF data stream decoder. + + data_size = Read(); + clear = 1 << data_size; + end_of_information = clear + 1; + available = clear + 2; + old_code = NullCode; + code_size = data_size + 1; + code_mask = (1 << code_size) - 1; + for (code = 0; code < clear; code++) + { + prefix[code] = 0; + suffix[code] = (byte) code; + } + + // Decode GIF pixel stream. + + datum = bits = count = first = top = pi = bi = 0; + + for (i = 0; i < npix;) + { + if (top == 0) + { + if (bits < code_size) + { + // Load bytes until there are enough bits for a code. + if (count == 0) + { + // Read a new data block. + count = ReadBlock(); + if (count <= 0) + break; + bi = 0; + } + datum += (((int) block[bi]) & 0xff) << bits; + bits += 8; + bi++; + count--; + continue; + } + + // Get the next code. + + code = datum & code_mask; + datum >>= code_size; + bits -= code_size; + + // Interpret the code + + if ((code > available) || (code == end_of_information)) + break; + if (code == clear) + { + // Reset decoder. + code_size = data_size + 1; + code_mask = (1 << code_size) - 1; + available = clear + 2; + old_code = NullCode; + continue; + } + if (old_code == NullCode) + { + pixelStack[top++] = suffix[code]; + old_code = code; + first = code; + continue; + } + in_code = code; + if (code == available) + { + pixelStack[top++] = (byte) first; + code = old_code; + } + while (code > clear) + { + pixelStack[top++] = suffix[code]; + code = prefix[code]; + } + first = ((int) suffix[code]) & 0xff; + + // Add a new string to the string table, + + if (available >= MaxStackSize) + break; + pixelStack[top++] = (byte) first; + prefix[available] = (short) old_code; + suffix[available] = (byte) first; + available++; + if (((available & code_mask) == 0) + && (available < MaxStackSize)) + { + code_size++; + code_mask += available; + } + old_code = in_code; + } + + // Pop a pixel off the pixel stack. + + top--; + pixels[pi++] = pixelStack[top]; + i++; + } + + for (i = pi; i < npix; i++) + { + pixels[i] = 0; // clear missing pixels + } + + } + + /** + * Returns true if an error was encountered during reading/decoding + */ + private bool Error() + { + return status != StatusOK; + } + + /** + * Initializes or re-initializes reader + */ + private void Init() + { + status = StatusOK; + frameCount = 0; + frames = new ArrayList(); + gct = null; + lct = null; + } + + /** + * Reads a single byte from the input stream. + */ + private int Read() + { + int curByte = 0; + try + { + curByte = inStream.ReadByte(); + } + catch (IOException) + { + status = StatusFormatError; + } + return curByte; + } + + /** + * Reads next variable length block from input. + * + * @return number of bytes stored in "buffer" + */ + private int ReadBlock() + { + blockSize = Read(); + int n = 0; + if (blockSize > 0) + { + try + { + int count = 0; + while (n < blockSize) + { + count = inStream.Read(block, n, blockSize - n); + if (count == -1) + break; + n += count; + } + } + catch (IOException) + { + } + + if (n < blockSize) + { + status = StatusFormatError; + } + } + return n; + } + + /** + * Reads color table as 256 RGB integer values + * + * @param ncolors int number of colors to read + * @return int array containing 256 colors (packed ARGB with full alpha) + */ + private int[] ReadColorTable(int ncolors) + { + int nbytes = 3 * ncolors; + int[] tab = null; + byte[] c = new byte[nbytes]; + int n = 0; + try + { + n = inStream.Read(c, 0, c.Length ); + } + catch (IOException) + { + } + if (n < nbytes) + { + status = StatusFormatError; + } + else + { + tab = new int[256]; // max size to avoid bounds checks + int i = 0; + int j = 0; + while (i < ncolors) + { + int r = ((int) c[j++]) & 0xff; + int g = ((int) c[j++]) & 0xff; + int b = ((int) c[j++]) & 0xff; + tab[i++] = ( int ) ( 0xff000000 | (r << 16) | (g << 8) | b ); + } + } + return tab; + } + + /** + * Main file parser. Reads GIF content blocks. + */ + private void ReadContents() + { + // read GIF file content blocks + bool done = false; + while (!(done || Error())) + { + int code = Read(); + switch (code) + { + + case 0x2C : // image separator + ReadImage(); + break; + + case 0x21 : // extension + code = Read(); + switch (code) + { + case 0xf9 : // graphics control extension + ReadGraphicControlExt(); + break; + + case 0xff : // application extension + ReadBlock(); + String app = ""; + for (int i = 0; i < 11; i++) + { + app += (char) block[i]; + } + if (app.Equals("NETSCAPE2.0")) + { + ReadNetscapeExt(); + } + else + Skip(); // don't care + break; + + default : // uninteresting extension + Skip(); + break; + } + break; + + case 0x3b : // terminator + done = true; + break; + + case 0x00 : // bad byte, but keep going and see what happens + break; + + default : + status = StatusFormatError; + break; + } + } + } + + /** + * Reads Graphics Control Extension values + */ + private void ReadGraphicControlExt() + { + Read(); // block size + int packed = Read(); // packed fields + dispose = (packed & 0x1c) >> 2; // disposal method + if (dispose == 0) + { + dispose = 1; // elect to keep old image if discretionary + } + transparency = (packed & 1) != 0; + delay = ReadShort() * 10; // delay in milliseconds + transIndex = Read(); // transparent color index + Read(); // block terminator + } + + /** + * Reads GIF file header information. + */ + private void ReadHeader() + { + String id = ""; + for (int i = 0; i < 6; i++) + { + id += (char) Read(); + } + if (!id.StartsWith("GIF")) + { + status = StatusFormatError; + return; + } + + ReadLSD(); + if (gctFlag && !Error()) + { + gct = ReadColorTable(gctSize); + bgColor = gct[bgIndex]; + } + } + + /** + * Reads next frame image + */ + private void ReadImage() + { + ix = ReadShort(); // (sub)image position & size + iy = ReadShort(); + iw = ReadShort(); + ih = ReadShort(); + + int packed = Read(); + lctFlag = (packed & 0x80) != 0; // 1 - local color table flag + interlace = (packed & 0x40) != 0; // 2 - interlace flag + // 3 - sort flag + // 4-5 - reserved + lctSize = 2 << (packed & 7); // 6-8 - local color table size + + if (lctFlag) + { + lct = ReadColorTable(lctSize); // read table + act = lct; // make local table active + } + else + { + act = gct; // make global table active + if (bgIndex == transIndex) + bgColor = 0; + } + int save = 0; + if (transparency) + { + save = act[transIndex]; + act[transIndex] = 0; // set transparent color if specified + } + + if (act == null) + { + status = StatusFormatError; // no color table defined + } + + if (Error()) return; + + DecodeImageData(); // decode pixel data + Skip(); + + if (Error()) return; + + frameCount++; + + // create new image to receive frame data + // image = + // new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); + + bitmap = new Bitmap( width, height ); + image = bitmap; + SetPixels(); // transfer pixel data to image + + frames.Add(new GifFrame(bitmap, delay)); // add image to frame list + + if (transparency) + { + act[transIndex] = save; + } + ResetFrame(); + + } + + /** + * Reads Logical Screen Descriptor + */ + private void ReadLSD() + { + + // logical screen size + width = ReadShort(); + height = ReadShort(); + + // packed fields + int packed = Read(); + gctFlag = (packed & 0x80) != 0; // 1 : global color table flag + // 2-4 : color resolution + // 5 : gct sort flag + gctSize = 2 << (packed & 7); // 6-8 : gct size + + bgIndex = Read(); // background color index + pixelAspect = Read(); // pixel aspect ratio + } + + /** + * Reads Netscape extenstion to obtain iteration count + */ + private void ReadNetscapeExt() + { + do + { + ReadBlock(); + if (block[0] == 1) + { + // loop count sub-block + int b1 = ((int) block[1]) & 0xff; + int b2 = ((int) block[2]) & 0xff; + loopCount = (b2 << 8) | b1; + } + } while ((blockSize > 0) && !Error()); + } + + /** + * Reads next 16-bit value, LSB first + */ + private int ReadShort() + { + // read 16-bit value, LSB first + return Read() | (Read() << 8); + } + + /** + * Resets frame state for reading next image. + */ + private void ResetFrame() + { + lastDispose = dispose; + lastRect = new Rectangle(ix, iy, iw, ih); + lastImage = image; + lastBgColor = bgColor; + // int dispose = 0; + lct = null; + } + + /** + * Skips variable length blocks up to and including + * next zero length block. + */ + private void Skip() + { + do + { + ReadBlock(); + } while ((blockSize > 0) && !Error()); + } + } +} diff --git a/External/Aga.Controls/NumericTextBox.cs b/Aga.Controls/NumericTextBox.cs similarity index 96% rename from External/Aga.Controls/NumericTextBox.cs rename to Aga.Controls/NumericTextBox.cs index bed0910..0dcef4a 100644 --- a/External/Aga.Controls/NumericTextBox.cs +++ b/Aga.Controls/NumericTextBox.cs @@ -1,189 +1,189 @@ -using System; -using System.ComponentModel; -using System.Windows.Forms; -using System.Globalization; - - -namespace Aga.Controls -{ - /// - /// Restricts the entry of characters to digits, the negative sign, - /// the decimal point, and editing keystrokes (backspace). - /// It does not handle the AltGr key so any keys that can be created in any - /// combination with AltGr these are not filtered - /// - public class NumericTextBox : TextBox - { - private const int WM_PASTE = 0x302; - private NumberStyles numberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign; - - /// - /// Restricts the entry of characters to digits, the negative sign, - /// the decimal point, and editing keystrokes (backspace). - /// It does not handle the AltGr key - /// - /// - protected override void OnKeyPress(KeyPressEventArgs e) - { - base.OnKeyPress(e); - - e.Handled = invalidNumeric(e.KeyChar); - } - - - /// - /// Main method for verifying allowed keypresses. - /// This does not catch cut paste copy ... operations. - /// - /// - /// - private bool invalidNumeric(char key) - { - bool handled = false; - - NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat; - string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; - string negativeSign = numberFormatInfo.NegativeSign; - - string keyString = key.ToString(); - - if (Char.IsDigit(key)) - { - // Digits are OK - } - else if (AllowDecimalSeparator && keyString.Equals(decimalSeparator)) - { - if (Text.IndexOf(decimalSeparator) >= 0) - { - handled = true; - } - } - else if (AllowNegativeSign && keyString.Equals(negativeSign)) - { - if (Text.IndexOf(negativeSign) >= 0) - { - handled = true; - } - } - else if (key == '\b') - { - // Backspace key is OK - } - else if ((ModifierKeys & (Keys.Control)) != 0) - { - // Let the edit control handle control and alt key combinations - } - else - { - // Swallow this invalid key and beep - handled = true; - } - return handled; - } - - - /// - /// Method invoked when Windows sends a message. - /// - /// Message from Windows. - /// - /// This is over-ridden so that the user can not use - /// cut or paste operations to bypass the TextChanging event. - /// This catches ContextMenu Paste, Shift+Insert, Ctrl+V, - /// While it is generally frowned upon to override WndProc, no - /// other simple mechanism was apparent to simultaneously and - /// transparently intercept so many different operations. - /// - protected override void WndProc(ref Message m) - { - // Switch to handle message... - switch (m.Msg) - { - case WM_PASTE: - { - // Get clipboard object to paste - IDataObject clipboardData = Clipboard.GetDataObject(); - - // Get text from clipboard data - string pasteText = (string)clipboardData.GetData( - DataFormats.UnicodeText); - - // Get the number of characters to replace - int selectionLength = SelectionLength; - - // If no replacement or insertion, we are done - if (pasteText.Length == 0) - { - break; - } - else if (selectionLength != 0) - { - base.Text = base.Text.Remove(SelectionStart, selectionLength); - } - - bool containsInvalidChars = false; - foreach (char c in pasteText) - { - if (containsInvalidChars) - { - break; - } - else if (invalidNumeric(c)) - { - containsInvalidChars = true; - } - } - - if (!containsInvalidChars) - { - base.Text = base.Text.Insert(SelectionStart, pasteText); - } - - return; - } - - } - base.WndProc(ref m); - } - - - public int IntValue - { - get - { - int intValue; - Int32.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out intValue); - return intValue; - } - } - - public decimal DecimalValue - { - get - { - decimal decimalValue; - Decimal.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out decimalValue); - return decimalValue; - } - } - - - private bool allowNegativeSign; - [DefaultValue(true)] - public bool AllowNegativeSign - { - get { return allowNegativeSign; } - set { allowNegativeSign = value; } - } - - private bool allowDecimalSeparator; - [DefaultValue(true)] - public bool AllowDecimalSeparator - { - get { return allowDecimalSeparator; } - set { allowDecimalSeparator = value; } - } - - } - -} +using System; +using System.ComponentModel; +using System.Windows.Forms; +using System.Globalization; + + +namespace Aga.Controls +{ + /// + /// Restricts the entry of characters to digits, the negative sign, + /// the decimal point, and editing keystrokes (backspace). + /// It does not handle the AltGr key so any keys that can be created in any + /// combination with AltGr these are not filtered + /// + public class NumericTextBox : TextBox + { + private const int WM_PASTE = 0x302; + private NumberStyles numberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign; + + /// + /// Restricts the entry of characters to digits, the negative sign, + /// the decimal point, and editing keystrokes (backspace). + /// It does not handle the AltGr key + /// + /// + protected override void OnKeyPress(KeyPressEventArgs e) + { + base.OnKeyPress(e); + + e.Handled = invalidNumeric(e.KeyChar); + } + + + /// + /// Main method for verifying allowed keypresses. + /// This does not catch cut paste copy ... operations. + /// + /// + /// + private bool invalidNumeric(char key) + { + bool handled = false; + + NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat; + string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; + string negativeSign = numberFormatInfo.NegativeSign; + + string keyString = key.ToString(); + + if (Char.IsDigit(key)) + { + // Digits are OK + } + else if (AllowDecimalSeparator && keyString.Equals(decimalSeparator)) + { + if (Text.IndexOf(decimalSeparator) >= 0) + { + handled = true; + } + } + else if (AllowNegativeSign && keyString.Equals(negativeSign)) + { + if (Text.IndexOf(negativeSign) >= 0) + { + handled = true; + } + } + else if (key == '\b') + { + // Backspace key is OK + } + else if ((ModifierKeys & (Keys.Control)) != 0) + { + // Let the edit control handle control and alt key combinations + } + else + { + // Swallow this invalid key and beep + handled = true; + } + return handled; + } + + + /// + /// Method invoked when Windows sends a message. + /// + /// Message from Windows. + /// + /// This is over-ridden so that the user can not use + /// cut or paste operations to bypass the TextChanging event. + /// This catches ContextMenu Paste, Shift+Insert, Ctrl+V, + /// While it is generally frowned upon to override WndProc, no + /// other simple mechanism was apparent to simultaneously and + /// transparently intercept so many different operations. + /// + protected override void WndProc(ref Message m) + { + // Switch to handle message... + switch (m.Msg) + { + case WM_PASTE: + { + // Get clipboard object to paste + IDataObject clipboardData = Clipboard.GetDataObject(); + + // Get text from clipboard data + string pasteText = (string)clipboardData.GetData( + DataFormats.UnicodeText); + + // Get the number of characters to replace + int selectionLength = SelectionLength; + + // If no replacement or insertion, we are done + if (pasteText.Length == 0) + { + break; + } + else if (selectionLength != 0) + { + base.Text = base.Text.Remove(SelectionStart, selectionLength); + } + + bool containsInvalidChars = false; + foreach (char c in pasteText) + { + if (containsInvalidChars) + { + break; + } + else if (invalidNumeric(c)) + { + containsInvalidChars = true; + } + } + + if (!containsInvalidChars) + { + base.Text = base.Text.Insert(SelectionStart, pasteText); + } + + return; + } + + } + base.WndProc(ref m); + } + + + public int IntValue + { + get + { + int intValue; + Int32.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out intValue); + return intValue; + } + } + + public decimal DecimalValue + { + get + { + decimal decimalValue; + Decimal.TryParse(this.Text, numberStyle, CultureInfo.CurrentCulture.NumberFormat, out decimalValue); + return decimalValue; + } + } + + + private bool allowNegativeSign; + [DefaultValue(true)] + public bool AllowNegativeSign + { + get { return allowNegativeSign; } + set { allowNegativeSign = value; } + } + + private bool allowDecimalSeparator; + [DefaultValue(true)] + public bool AllowDecimalSeparator + { + get { return allowDecimalSeparator; } + set { allowDecimalSeparator = value; } + } + + } + +} diff --git a/External/Aga.Controls/PerformanceAnalyzer.cs b/Aga.Controls/PerformanceAnalyzer.cs similarity index 95% rename from External/Aga.Controls/PerformanceAnalyzer.cs rename to Aga.Controls/PerformanceAnalyzer.cs index c55bc9e..94fdd6e 100644 --- a/External/Aga.Controls/PerformanceAnalyzer.cs +++ b/Aga.Controls/PerformanceAnalyzer.cs @@ -1,136 +1,136 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; - -namespace Aga.Controls -{ - /// - /// Is used to analyze code performance - /// - public static class PerformanceAnalyzer - { - public class PerformanceInfo - { - private string _name; - public string Name - { - get { return _name; } - } - - private int _count = 0; - public int Count - { - get { return _count; } - set { _count = value; } - } - - private double _totalTime = 0; - public double TotalTime - { - get { return _totalTime; } - set { _totalTime = value; } - } - - private Int64 _start; - public Int64 Start - { - get { return _start; } - set { _start = value; } - } - - public PerformanceInfo(string name) - { - _name = name; - } - } - - private static Dictionary _performances = new Dictionary(); - - public static IEnumerable Performances - { - get - { - return _performances.Values; - } - } - - [Conditional("DEBUG")] - public static void Start(string pieceOfCode) - { - PerformanceInfo info = null; - lock(_performances) - { - if (_performances.ContainsKey(pieceOfCode)) - info = _performances[pieceOfCode]; - else - { - info = new PerformanceInfo(pieceOfCode); - _performances.Add(pieceOfCode, info); - } - - info.Count++; - info.Start = TimeCounter.GetStartValue(); - } - } - - [Conditional("DEBUG")] - public static void Finish(string pieceOfCode) - { - lock (_performances) - { - if (_performances.ContainsKey(pieceOfCode)) - { - PerformanceInfo info = _performances[pieceOfCode]; - info.Count++; - info.TotalTime += TimeCounter.Finish(info.Start); - } - } - } - - public static void Reset() - { - _performances.Clear(); - } - - public static string GenerateReport() - { - return GenerateReport(0); - } - - public static string GenerateReport(string mainPieceOfCode) - { - if (_performances.ContainsKey(mainPieceOfCode)) - return GenerateReport(_performances[mainPieceOfCode].TotalTime); - else - return GenerateReport(0); - } - - public static string GenerateReport(double totalTime) - { - StringBuilder sb = new StringBuilder(); - int len = 0; - foreach (PerformanceInfo info in Performances) - len = Math.Max(info.Name.Length, len); - - sb.AppendLine("Name".PadRight(len) + " Count Total Time, ms Avg. Time, ms Percentage, %"); - sb.AppendLine("----------------------------------------------------------------------------------------------"); - foreach (PerformanceInfo info in Performances) - { - sb.Append(info.Name.PadRight(len)); - double p = 0; - double avgt = 0; - if (totalTime != 0) - p = info.TotalTime / totalTime; - if (info.Count > 0) - avgt = info.TotalTime * 1000 / info.Count; - string c = info.Count.ToString("0,0").PadRight(20); - string tt = (info.TotalTime * 1000).ToString("0,0.00").PadRight(20); - string t = avgt.ToString("0.0000").PadRight(20); - string sp = (p * 100).ToString("###").PadRight(20); - sb.AppendFormat(" " + c + tt + t + sp + "\n"); - } - return sb.ToString(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Diagnostics; + +namespace Aga.Controls +{ + /// + /// Is used to analyze code performance + /// + public static class PerformanceAnalyzer + { + public class PerformanceInfo + { + private string _name; + public string Name + { + get { return _name; } + } + + private int _count = 0; + public int Count + { + get { return _count; } + set { _count = value; } + } + + private double _totalTime = 0; + public double TotalTime + { + get { return _totalTime; } + set { _totalTime = value; } + } + + private Int64 _start; + public Int64 Start + { + get { return _start; } + set { _start = value; } + } + + public PerformanceInfo(string name) + { + _name = name; + } + } + + private static Dictionary _performances = new Dictionary(); + + public static IEnumerable Performances + { + get + { + return _performances.Values; + } + } + + [Conditional("DEBUG")] + public static void Start(string pieceOfCode) + { + PerformanceInfo info = null; + lock(_performances) + { + if (_performances.ContainsKey(pieceOfCode)) + info = _performances[pieceOfCode]; + else + { + info = new PerformanceInfo(pieceOfCode); + _performances.Add(pieceOfCode, info); + } + + info.Count++; + info.Start = TimeCounter.GetStartValue(); + } + } + + [Conditional("DEBUG")] + public static void Finish(string pieceOfCode) + { + lock (_performances) + { + if (_performances.ContainsKey(pieceOfCode)) + { + PerformanceInfo info = _performances[pieceOfCode]; + info.Count++; + info.TotalTime += TimeCounter.Finish(info.Start); + } + } + } + + public static void Reset() + { + _performances.Clear(); + } + + public static string GenerateReport() + { + return GenerateReport(0); + } + + public static string GenerateReport(string mainPieceOfCode) + { + if (_performances.ContainsKey(mainPieceOfCode)) + return GenerateReport(_performances[mainPieceOfCode].TotalTime); + else + return GenerateReport(0); + } + + public static string GenerateReport(double totalTime) + { + StringBuilder sb = new StringBuilder(); + int len = 0; + foreach (PerformanceInfo info in Performances) + len = Math.Max(info.Name.Length, len); + + sb.AppendLine("Name".PadRight(len) + " Count Total Time, ms Avg. Time, ms Percentage, %"); + sb.AppendLine("----------------------------------------------------------------------------------------------"); + foreach (PerformanceInfo info in Performances) + { + sb.Append(info.Name.PadRight(len)); + double p = 0; + double avgt = 0; + if (totalTime != 0) + p = info.TotalTime / totalTime; + if (info.Count > 0) + avgt = info.TotalTime * 1000 / info.Count; + string c = info.Count.ToString("0,0").PadRight(20); + string tt = (info.TotalTime * 1000).ToString("0,0.00").PadRight(20); + string t = avgt.ToString("0.0000").PadRight(20); + string sp = (p * 100).ToString("###").PadRight(20); + sb.AppendFormat(" " + c + tt + t + sp + "\n"); + } + return sb.ToString(); + } + } +} diff --git a/External/Aga.Controls/Properties/AssemblyInfo.cs b/Aga.Controls/Properties/AssemblyInfo.cs similarity index 97% rename from External/Aga.Controls/Properties/AssemblyInfo.cs rename to Aga.Controls/Properties/AssemblyInfo.cs index b65b76c..a55abae 100644 --- a/External/Aga.Controls/Properties/AssemblyInfo.cs +++ b/Aga.Controls/Properties/AssemblyInfo.cs @@ -1,14 +1,14 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System; -using System.Security.Permissions; - -[assembly: ComVisible(false)] -[assembly: CLSCompliant(false)] - -[assembly: AssemblyTitle("Aga.Controls")] -[assembly: AssemblyCopyright("Copyright © Andrey Gliznetsov 2006 - 2009")] -[assembly: AssemblyDescription("http://sourceforge.net/projects/treeviewadv/")] - -[assembly: AssemblyVersion("1.7.0.0")] +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System; +using System.Security.Permissions; + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] + +[assembly: AssemblyTitle("Aga.Controls")] +[assembly: AssemblyCopyright("Copyright © Andrey Gliznetsov 2006 - 2009")] +[assembly: AssemblyDescription("http://sourceforge.net/projects/treeviewadv/")] + +[assembly: AssemblyVersion("1.7.0.0")] diff --git a/External/Aga.Controls/Properties/Resources.Designer.cs b/Aga.Controls/Properties/Resources.Designer.cs similarity index 97% rename from External/Aga.Controls/Properties/Resources.Designer.cs rename to Aga.Controls/Properties/Resources.Designer.cs index c2139b5..a1aaf8c 100644 --- a/External/Aga.Controls/Properties/Resources.Designer.cs +++ b/Aga.Controls/Properties/Resources.Designer.cs @@ -1,133 +1,133 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.235 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Aga.Controls.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Aga.Controls.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - internal static System.Drawing.Bitmap check { - get { - object obj = ResourceManager.GetObject("check", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static byte[] DVSplit { - get { - object obj = ResourceManager.GetObject("DVSplit", resourceCulture); - return ((byte[])(obj)); - } - } - - internal static System.Drawing.Bitmap Folder { - get { - object obj = ResourceManager.GetObject("Folder", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static System.Drawing.Bitmap FolderClosed { - get { - object obj = ResourceManager.GetObject("FolderClosed", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static System.Drawing.Bitmap Leaf { - get { - object obj = ResourceManager.GetObject("Leaf", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static byte[] loading_icon { - get { - object obj = ResourceManager.GetObject("loading_icon", resourceCulture); - return ((byte[])(obj)); - } - } - - internal static System.Drawing.Bitmap minus { - get { - object obj = ResourceManager.GetObject("minus", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static System.Drawing.Bitmap plus { - get { - object obj = ResourceManager.GetObject("plus", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static System.Drawing.Bitmap uncheck { - get { - object obj = ResourceManager.GetObject("uncheck", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - internal static System.Drawing.Bitmap unknown { - get { - object obj = ResourceManager.GetObject("unknown", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.235 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Aga.Controls.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Aga.Controls.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + internal static System.Drawing.Bitmap check { + get { + object obj = ResourceManager.GetObject("check", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static byte[] DVSplit { + get { + object obj = ResourceManager.GetObject("DVSplit", resourceCulture); + return ((byte[])(obj)); + } + } + + internal static System.Drawing.Bitmap Folder { + get { + object obj = ResourceManager.GetObject("Folder", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap FolderClosed { + get { + object obj = ResourceManager.GetObject("FolderClosed", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap Leaf { + get { + object obj = ResourceManager.GetObject("Leaf", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static byte[] loading_icon { + get { + object obj = ResourceManager.GetObject("loading_icon", resourceCulture); + return ((byte[])(obj)); + } + } + + internal static System.Drawing.Bitmap minus { + get { + object obj = ResourceManager.GetObject("minus", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap plus { + get { + object obj = ResourceManager.GetObject("plus", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap uncheck { + get { + object obj = ResourceManager.GetObject("uncheck", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + internal static System.Drawing.Bitmap unknown { + get { + object obj = ResourceManager.GetObject("unknown", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/External/Aga.Controls/Properties/Resources.resx b/Aga.Controls/Properties/Resources.resx similarity index 98% rename from External/Aga.Controls/Properties/Resources.resx rename to Aga.Controls/Properties/Resources.resx index 09ea802..a23f6cc 100644 --- a/External/Aga.Controls/Properties/Resources.resx +++ b/Aga.Controls/Properties/Resources.resx @@ -1,151 +1,151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Resources\check.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\DVSplit.cur;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Resources\Folder.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\FolderClosed.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Leaf.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\loading_icon;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Resources\minus.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\plus.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\uncheck.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\unknown.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\check.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\DVSplit.cur;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + ..\Resources\Folder.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\FolderClosed.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\Leaf.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\loading_icon;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + ..\Resources\minus.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\plus.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\uncheck.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\unknown.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + \ No newline at end of file diff --git a/External/Aga.Controls/ResourceHelper.cs b/Aga.Controls/ResourceHelper.cs similarity index 96% rename from External/Aga.Controls/ResourceHelper.cs rename to Aga.Controls/ResourceHelper.cs index 99176f2..6f865e0 100644 --- a/External/Aga.Controls/ResourceHelper.cs +++ b/Aga.Controls/ResourceHelper.cs @@ -1,48 +1,48 @@ -using System; -using System.IO; -using System.Reflection; -using System.Windows.Forms; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls -{ - public static class ResourceHelper - { - // VSpilt Cursor with Innerline (symbolisize hidden column) - private static Cursor _dVSplitCursor = GetCursor(Properties.Resources.DVSplit); - public static Cursor DVSplitCursor - { - get { return _dVSplitCursor; } - } - - private static GifDecoder _loadingIcon = GetGifDecoder(Properties.Resources.loading_icon); - public static GifDecoder LoadingIcon - { - get { return _loadingIcon; } - } - - /// - /// Help function to convert byte[] from resource into Cursor Type - /// - /// - /// - private static Cursor GetCursor(byte[] data) - { - using (MemoryStream s = new MemoryStream(data)) - return new Cursor(s); - } - - /// - /// Help function to convert byte[] from resource into GifDecoder Type - /// - /// - /// - private static GifDecoder GetGifDecoder(byte[] data) - { - using(MemoryStream ms = new MemoryStream(data)) - return new GifDecoder(ms, true); - } - - } -} +using System; +using System.IO; +using System.Reflection; +using System.Windows.Forms; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls +{ + public static class ResourceHelper + { + // VSpilt Cursor with Innerline (symbolisize hidden column) + private static Cursor _dVSplitCursor = GetCursor(Properties.Resources.DVSplit); + public static Cursor DVSplitCursor + { + get { return _dVSplitCursor; } + } + + private static GifDecoder _loadingIcon = GetGifDecoder(Properties.Resources.loading_icon); + public static GifDecoder LoadingIcon + { + get { return _loadingIcon; } + } + + /// + /// Help function to convert byte[] from resource into Cursor Type + /// + /// + /// + private static Cursor GetCursor(byte[] data) + { + using (MemoryStream s = new MemoryStream(data)) + return new Cursor(s); + } + + /// + /// Help function to convert byte[] from resource into GifDecoder Type + /// + /// + /// + private static GifDecoder GetGifDecoder(byte[] data) + { + using(MemoryStream ms = new MemoryStream(data)) + return new GifDecoder(ms, true); + } + + } +} diff --git a/External/Aga.Controls/Resources/DVSplit.cur b/Aga.Controls/Resources/DVSplit.cur similarity index 100% rename from External/Aga.Controls/Resources/DVSplit.cur rename to Aga.Controls/Resources/DVSplit.cur diff --git a/External/Aga.Controls/Resources/Folder.bmp b/Aga.Controls/Resources/Folder.bmp similarity index 100% rename from External/Aga.Controls/Resources/Folder.bmp rename to Aga.Controls/Resources/Folder.bmp diff --git a/External/Aga.Controls/Resources/FolderClosed.bmp b/Aga.Controls/Resources/FolderClosed.bmp similarity index 100% rename from External/Aga.Controls/Resources/FolderClosed.bmp rename to Aga.Controls/Resources/FolderClosed.bmp diff --git a/External/Aga.Controls/Resources/Leaf.bmp b/Aga.Controls/Resources/Leaf.bmp similarity index 100% rename from External/Aga.Controls/Resources/Leaf.bmp rename to Aga.Controls/Resources/Leaf.bmp diff --git a/External/Aga.Controls/Resources/check.bmp b/Aga.Controls/Resources/check.bmp similarity index 100% rename from External/Aga.Controls/Resources/check.bmp rename to Aga.Controls/Resources/check.bmp diff --git a/External/Aga.Controls/Resources/loading_icon b/Aga.Controls/Resources/loading_icon similarity index 100% rename from External/Aga.Controls/Resources/loading_icon rename to Aga.Controls/Resources/loading_icon diff --git a/External/Aga.Controls/Resources/minus.bmp b/Aga.Controls/Resources/minus.bmp similarity index 100% rename from External/Aga.Controls/Resources/minus.bmp rename to Aga.Controls/Resources/minus.bmp diff --git a/External/Aga.Controls/Resources/plus.bmp b/Aga.Controls/Resources/plus.bmp similarity index 100% rename from External/Aga.Controls/Resources/plus.bmp rename to Aga.Controls/Resources/plus.bmp diff --git a/External/Aga.Controls/Resources/uncheck.bmp b/Aga.Controls/Resources/uncheck.bmp similarity index 100% rename from External/Aga.Controls/Resources/uncheck.bmp rename to Aga.Controls/Resources/uncheck.bmp diff --git a/External/Aga.Controls/Resources/unknown.bmp b/Aga.Controls/Resources/unknown.bmp similarity index 100% rename from External/Aga.Controls/Resources/unknown.bmp rename to Aga.Controls/Resources/unknown.bmp diff --git a/External/Aga.Controls/StringCollectionEditor.cs b/Aga.Controls/StringCollectionEditor.cs similarity index 94% rename from External/Aga.Controls/StringCollectionEditor.cs rename to Aga.Controls/StringCollectionEditor.cs index 1bc5816..411fa49 100644 --- a/External/Aga.Controls/StringCollectionEditor.cs +++ b/Aga.Controls/StringCollectionEditor.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel.Design; - -namespace Aga.Controls -{ - public class StringCollectionEditor : CollectionEditor - { - public StringCollectionEditor(Type type): base(type) - { - } - - protected override Type CreateCollectionItemType() - { - return typeof(string); - } - - protected override object CreateInstance(Type itemType) - { - return ""; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel.Design; + +namespace Aga.Controls +{ + public class StringCollectionEditor : CollectionEditor + { + public StringCollectionEditor(Type type): base(type) + { + } + + protected override Type CreateCollectionItemType() + { + return typeof(string); + } + + protected override object CreateInstance(Type itemType) + { + return ""; + } + } +} diff --git a/External/Aga.Controls/TextHelper.cs b/Aga.Controls/TextHelper.cs similarity index 96% rename from External/Aga.Controls/TextHelper.cs rename to Aga.Controls/TextHelper.cs index cd8e38e..10b7475 100644 --- a/External/Aga.Controls/TextHelper.cs +++ b/Aga.Controls/TextHelper.cs @@ -1,45 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; - -namespace Aga.Controls -{ - public static class TextHelper - { - public static StringAlignment TranslateAligment(HorizontalAlignment alignment) - { - if (alignment == HorizontalAlignment.Left) - return StringAlignment.Near; - else if (alignment == HorizontalAlignment.Right) - return StringAlignment.Far; - else - return StringAlignment.Center; - } - - public static TextFormatFlags TranslateAligmentToFlag(HorizontalAlignment alignment) - { - if (alignment == HorizontalAlignment.Left) - return TextFormatFlags.Left; - else if (alignment == HorizontalAlignment.Right) - return TextFormatFlags.Right; - else - return TextFormatFlags.HorizontalCenter; - } - - public static TextFormatFlags TranslateTrimmingToFlag(StringTrimming trimming) - { - if (trimming == StringTrimming.EllipsisCharacter) - return TextFormatFlags.EndEllipsis; - else if (trimming == StringTrimming.EllipsisPath) - return TextFormatFlags.PathEllipsis; - if (trimming == StringTrimming.EllipsisWord) - return TextFormatFlags.WordEllipsis; - if (trimming == StringTrimming.Word) - return TextFormatFlags.WordBreak; - else - return TextFormatFlags.Default; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace Aga.Controls +{ + public static class TextHelper + { + public static StringAlignment TranslateAligment(HorizontalAlignment alignment) + { + if (alignment == HorizontalAlignment.Left) + return StringAlignment.Near; + else if (alignment == HorizontalAlignment.Right) + return StringAlignment.Far; + else + return StringAlignment.Center; + } + + public static TextFormatFlags TranslateAligmentToFlag(HorizontalAlignment alignment) + { + if (alignment == HorizontalAlignment.Left) + return TextFormatFlags.Left; + else if (alignment == HorizontalAlignment.Right) + return TextFormatFlags.Right; + else + return TextFormatFlags.HorizontalCenter; + } + + public static TextFormatFlags TranslateTrimmingToFlag(StringTrimming trimming) + { + if (trimming == StringTrimming.EllipsisCharacter) + return TextFormatFlags.EndEllipsis; + else if (trimming == StringTrimming.EllipsisPath) + return TextFormatFlags.PathEllipsis; + if (trimming == StringTrimming.EllipsisWord) + return TextFormatFlags.WordEllipsis; + if (trimming == StringTrimming.Word) + return TextFormatFlags.WordBreak; + else + return TextFormatFlags.Default; + } + } +} diff --git a/External/Aga.Controls/Threading/AbortableThreadPool.cs b/Aga.Controls/Threading/AbortableThreadPool.cs similarity index 95% rename from External/Aga.Controls/Threading/AbortableThreadPool.cs rename to Aga.Controls/Threading/AbortableThreadPool.cs index 9b390aa..5424e89 100644 --- a/External/Aga.Controls/Threading/AbortableThreadPool.cs +++ b/Aga.Controls/Threading/AbortableThreadPool.cs @@ -1,118 +1,118 @@ -// Stephen Toub -// stoub@microsoft.com - -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace Aga.Controls.Threading -{ - public class AbortableThreadPool - { - private LinkedList _callbacks = new LinkedList(); - private Dictionary _threads = new Dictionary(); - - public WorkItem QueueUserWorkItem(WaitCallback callback) - { - return QueueUserWorkItem(callback, null); - } - - public WorkItem QueueUserWorkItem(WaitCallback callback, object state) - { - if (callback == null) throw new ArgumentNullException("callback"); - - WorkItem item = new WorkItem(callback, state, ExecutionContext.Capture()); - lock (_callbacks) - { - _callbacks.AddLast(item); - } - ThreadPool.QueueUserWorkItem(new WaitCallback(HandleItem)); - return item; - } - - private void HandleItem(object ignored) - { - WorkItem item = null; - try - { - lock (_callbacks) - { - if (_callbacks.Count > 0) - { - item = _callbacks.First.Value; - _callbacks.RemoveFirst(); - } - if (item == null) - return; - _threads.Add(item, Thread.CurrentThread); - - } - ExecutionContext.Run(item.Context, - delegate { item.Callback(item.State); }, null); - } - finally - { - lock (_callbacks) - { - if (item != null) - _threads.Remove(item); - } - } - } - - public bool IsMyThread(Thread thread) - { - lock (_callbacks) - { - foreach (Thread t in _threads.Values) - { - if (t == thread) - return true; - } - return false; - } - } - - public WorkItemStatus Cancel(WorkItem item, bool allowAbort) - { - if (item == null) - throw new ArgumentNullException("item"); - lock (_callbacks) - { - LinkedListNode node = _callbacks.Find(item); - if (node != null) - { - _callbacks.Remove(node); - return WorkItemStatus.Queued; - } - else if (_threads.ContainsKey(item)) - { - if (allowAbort) - { - _threads[item].Abort(); - _threads.Remove(item); - return WorkItemStatus.Aborted; - } - else - return WorkItemStatus.Executing; - } - else - return WorkItemStatus.Completed; - } - } - - public void CancelAll(bool allowAbort) - { - lock (_callbacks) - { - _callbacks.Clear(); - if (allowAbort) - { - foreach (Thread t in _threads.Values) - t.Abort(); - } - } - } - } -} +// Stephen Toub +// stoub@microsoft.com + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +namespace Aga.Controls.Threading +{ + public class AbortableThreadPool + { + private LinkedList _callbacks = new LinkedList(); + private Dictionary _threads = new Dictionary(); + + public WorkItem QueueUserWorkItem(WaitCallback callback) + { + return QueueUserWorkItem(callback, null); + } + + public WorkItem QueueUserWorkItem(WaitCallback callback, object state) + { + if (callback == null) throw new ArgumentNullException("callback"); + + WorkItem item = new WorkItem(callback, state, ExecutionContext.Capture()); + lock (_callbacks) + { + _callbacks.AddLast(item); + } + ThreadPool.QueueUserWorkItem(new WaitCallback(HandleItem)); + return item; + } + + private void HandleItem(object ignored) + { + WorkItem item = null; + try + { + lock (_callbacks) + { + if (_callbacks.Count > 0) + { + item = _callbacks.First.Value; + _callbacks.RemoveFirst(); + } + if (item == null) + return; + _threads.Add(item, Thread.CurrentThread); + + } + ExecutionContext.Run(item.Context, + delegate { item.Callback(item.State); }, null); + } + finally + { + lock (_callbacks) + { + if (item != null) + _threads.Remove(item); + } + } + } + + public bool IsMyThread(Thread thread) + { + lock (_callbacks) + { + foreach (Thread t in _threads.Values) + { + if (t == thread) + return true; + } + return false; + } + } + + public WorkItemStatus Cancel(WorkItem item, bool allowAbort) + { + if (item == null) + throw new ArgumentNullException("item"); + lock (_callbacks) + { + LinkedListNode node = _callbacks.Find(item); + if (node != null) + { + _callbacks.Remove(node); + return WorkItemStatus.Queued; + } + else if (_threads.ContainsKey(item)) + { + if (allowAbort) + { + _threads[item].Abort(); + _threads.Remove(item); + return WorkItemStatus.Aborted; + } + else + return WorkItemStatus.Executing; + } + else + return WorkItemStatus.Completed; + } + } + + public void CancelAll(bool allowAbort) + { + lock (_callbacks) + { + _callbacks.Clear(); + if (allowAbort) + { + foreach (Thread t in _threads.Values) + t.Abort(); + } + } + } + } +} diff --git a/External/Aga.Controls/Threading/WorkItem.cs b/Aga.Controls/Threading/WorkItem.cs similarity index 93% rename from External/Aga.Controls/Threading/WorkItem.cs rename to Aga.Controls/Threading/WorkItem.cs index c422a72..0bcaf4c 100644 --- a/External/Aga.Controls/Threading/WorkItem.cs +++ b/Aga.Controls/Threading/WorkItem.cs @@ -1,45 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace Aga.Controls.Threading -{ - public sealed class WorkItem - { - private WaitCallback _callback; - private object _state; - private ExecutionContext _ctx; - - internal WorkItem(WaitCallback wc, object state, ExecutionContext ctx) - { - _callback = wc; - _state = state; - _ctx = ctx; - } - - internal WaitCallback Callback - { - get - { - return _callback; - } - } - - internal object State - { - get - { - return _state; - } - } - - internal ExecutionContext Context - { - get - { - return _ctx; - } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +namespace Aga.Controls.Threading +{ + public sealed class WorkItem + { + private WaitCallback _callback; + private object _state; + private ExecutionContext _ctx; + + internal WorkItem(WaitCallback wc, object state, ExecutionContext ctx) + { + _callback = wc; + _state = state; + _ctx = ctx; + } + + internal WaitCallback Callback + { + get + { + return _callback; + } + } + + internal object State + { + get + { + return _state; + } + } + + internal ExecutionContext Context + { + get + { + return _ctx; + } + } + } +} diff --git a/External/Aga.Controls/Threading/WorkItemStatus.cs b/Aga.Controls/Threading/WorkItemStatus.cs similarity index 93% rename from External/Aga.Controls/Threading/WorkItemStatus.cs rename to Aga.Controls/Threading/WorkItemStatus.cs index 71e16fa..ec4becb 100644 --- a/External/Aga.Controls/Threading/WorkItemStatus.cs +++ b/Aga.Controls/Threading/WorkItemStatus.cs @@ -1,14 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Threading -{ - public enum WorkItemStatus - { - Completed, - Queued, - Executing, - Aborted - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Threading +{ + public enum WorkItemStatus + { + Completed, + Queued, + Executing, + Aborted + } +} diff --git a/External/Aga.Controls/TimeCounter.cs b/Aga.Controls/TimeCounter.cs similarity index 95% rename from External/Aga.Controls/TimeCounter.cs rename to Aga.Controls/TimeCounter.cs index e7afc3a..e06c180 100644 --- a/External/Aga.Controls/TimeCounter.cs +++ b/Aga.Controls/TimeCounter.cs @@ -1,59 +1,59 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; -using System.Diagnostics.CodeAnalysis; - -namespace Aga.Controls -{ - /// - /// High resolution timer, used to test performance - /// - public static class TimeCounter - { - private static Int64 _start; - - /// - /// Start time counting - /// - public static void Start() - { - _start = 0; - QueryPerformanceCounter(ref _start); - } - - public static Int64 GetStartValue() - { - Int64 t = 0; - QueryPerformanceCounter(ref t); - return t; - } - - /// - /// Finish time counting - /// - /// time in seconds elapsed from Start till Finish - public static double Finish() - { - return Finish(_start); - } - - public static double Finish(Int64 start) - { - Int64 finish = 0; - QueryPerformanceCounter(ref finish); - - Int64 freq = 0; - QueryPerformanceFrequency(ref freq); - return (finish - start) / (double)freq; - } - - [DllImport("Kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool QueryPerformanceCounter(ref Int64 performanceCount); - - [DllImport("Kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool QueryPerformanceFrequency(ref Int64 frequency); - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Runtime.InteropServices; +using System.Diagnostics.CodeAnalysis; + +namespace Aga.Controls +{ + /// + /// High resolution timer, used to test performance + /// + public static class TimeCounter + { + private static Int64 _start; + + /// + /// Start time counting + /// + public static void Start() + { + _start = 0; + QueryPerformanceCounter(ref _start); + } + + public static Int64 GetStartValue() + { + Int64 t = 0; + QueryPerformanceCounter(ref t); + return t; + } + + /// + /// Finish time counting + /// + /// time in seconds elapsed from Start till Finish + public static double Finish() + { + return Finish(_start); + } + + public static double Finish(Int64 start) + { + Int64 finish = 0; + QueryPerformanceCounter(ref finish); + + Int64 freq = 0; + QueryPerformanceFrequency(ref freq); + return (finish - start) / (double)freq; + } + + [DllImport("Kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + static extern bool QueryPerformanceCounter(ref Int64 performanceCount); + + [DllImport("Kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + static extern bool QueryPerformanceFrequency(ref Int64 frequency); + } +} diff --git a/External/Aga.Controls/Tree/AutoRowHeightLayout.cs b/Aga.Controls/Tree/AutoRowHeightLayout.cs similarity index 95% rename from External/Aga.Controls/Tree/AutoRowHeightLayout.cs rename to Aga.Controls/Tree/AutoRowHeightLayout.cs index 8b89a98..953df02 100644 --- a/External/Aga.Controls/Tree/AutoRowHeightLayout.cs +++ b/Aga.Controls/Tree/AutoRowHeightLayout.cs @@ -1,151 +1,151 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public class AutoRowHeightLayout: IRowLayout - { - private DrawContext _measureContext; - private TreeViewAdv _treeView; - private List _rowCache; - - public AutoRowHeightLayout(TreeViewAdv treeView, int rowHeight) - { - _rowCache = new List(); - _treeView = treeView; - PreferredRowHeight = rowHeight; - _measureContext = new DrawContext(); - _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); - } - - private int _rowHeight; - public int PreferredRowHeight - { - get { return _rowHeight; } - set { _rowHeight = value; } - } - - - public int PageRowCount - { - get - { - if (_treeView.RowCount == 0) - return 0; - else - { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; - int y = 0; - for (int i = _treeView.RowCount - 1; i >= 0; i--) - { - y += GetRowHeight(i); - if (y > pageHeight) - return Math.Max(0, _treeView.RowCount - 1 - i); - } - return _treeView.RowCount; - } - } - } - - public int CurrentPageSize - { - get - { - if (_treeView.RowCount == 0) - return 0; - else - { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; - int y = 0; - for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) - { - y += GetRowHeight(i); - if (y > pageHeight) - return Math.Max(0, i - _treeView.FirstVisibleRow); - } - return Math.Max(0, _treeView.RowCount - _treeView.FirstVisibleRow); - } - } - } - - public Rectangle GetRowBounds(int rowNo) - { - if (rowNo >= _rowCache.Count) - { - int count = _rowCache.Count; - int y = count > 0 ? _rowCache[count - 1].Bottom : 0; - for (int i = count; i <= rowNo; i++) - { - int height = GetRowHeight(i); - _rowCache.Add(new Rectangle(0, y, 0, height)); - y += height; - } - if (rowNo < _rowCache.Count - 1) - return Rectangle.Empty; - } - if (rowNo >= 0 && rowNo < _rowCache.Count) - return _rowCache[rowNo]; - else - return Rectangle.Empty; - } - - private int GetRowHeight(int rowNo) - { - if (rowNo < _treeView.RowMap.Count) - { - TreeNodeAdv node = _treeView.RowMap[rowNo]; - if (node.Height == null) - { - int res = 0; - _measureContext.Font = _treeView.Font; - foreach (NodeControl nc in _treeView.NodeControls) - { - int h = nc.GetActualSize(node, _measureContext).Height; - if (h > res) - res = h; - } - node.Height = res; - } - return node.Height.Value; - } - else - return 0; - } - - public int GetRowAt(Point point) - { - int py = point.Y - _treeView.ColumnHeaderHeight; - int y = 0; - for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) - { - int h = GetRowHeight(i); - if (py >= y && py < y + h) - return i; - else - y += h; - } - return -1; - } - - public int GetFirstRow(int lastPageRow) - { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; - int y = 0; - for (int i = lastPageRow; i >= 0; i--) - { - y += GetRowHeight(i); - if (y > pageHeight) - return Math.Max(0, i + 1); - } - return 0; - } - - public void ClearCache() - { - _rowCache.Clear(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public class AutoRowHeightLayout: IRowLayout + { + private DrawContext _measureContext; + private TreeViewAdv _treeView; + private List _rowCache; + + public AutoRowHeightLayout(TreeViewAdv treeView, int rowHeight) + { + _rowCache = new List(); + _treeView = treeView; + PreferredRowHeight = rowHeight; + _measureContext = new DrawContext(); + _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); + } + + private int _rowHeight; + public int PreferredRowHeight + { + get { return _rowHeight; } + set { _rowHeight = value; } + } + + + public int PageRowCount + { + get + { + if (_treeView.RowCount == 0) + return 0; + else + { + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int y = 0; + for (int i = _treeView.RowCount - 1; i >= 0; i--) + { + y += GetRowHeight(i); + if (y > pageHeight) + return Math.Max(0, _treeView.RowCount - 1 - i); + } + return _treeView.RowCount; + } + } + } + + public int CurrentPageSize + { + get + { + if (_treeView.RowCount == 0) + return 0; + else + { + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int y = 0; + for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) + { + y += GetRowHeight(i); + if (y > pageHeight) + return Math.Max(0, i - _treeView.FirstVisibleRow); + } + return Math.Max(0, _treeView.RowCount - _treeView.FirstVisibleRow); + } + } + } + + public Rectangle GetRowBounds(int rowNo) + { + if (rowNo >= _rowCache.Count) + { + int count = _rowCache.Count; + int y = count > 0 ? _rowCache[count - 1].Bottom : 0; + for (int i = count; i <= rowNo; i++) + { + int height = GetRowHeight(i); + _rowCache.Add(new Rectangle(0, y, 0, height)); + y += height; + } + if (rowNo < _rowCache.Count - 1) + return Rectangle.Empty; + } + if (rowNo >= 0 && rowNo < _rowCache.Count) + return _rowCache[rowNo]; + else + return Rectangle.Empty; + } + + private int GetRowHeight(int rowNo) + { + if (rowNo < _treeView.RowMap.Count) + { + TreeNodeAdv node = _treeView.RowMap[rowNo]; + if (node.Height == null) + { + int res = 0; + _measureContext.Font = _treeView.Font; + foreach (NodeControl nc in _treeView.NodeControls) + { + int h = nc.GetActualSize(node, _measureContext).Height; + if (h > res) + res = h; + } + node.Height = res; + } + return node.Height.Value; + } + else + return 0; + } + + public int GetRowAt(Point point) + { + int py = point.Y - _treeView.ColumnHeaderHeight; + int y = 0; + for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) + { + int h = GetRowHeight(i); + if (py >= y && py < y + h) + return i; + else + y += h; + } + return -1; + } + + public int GetFirstRow(int lastPageRow) + { + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int y = 0; + for (int i = lastPageRow; i >= 0; i--) + { + y += GetRowHeight(i); + if (y > pageHeight) + return Math.Max(0, i + 1); + } + return 0; + } + + public void ClearCache() + { + _rowCache.Clear(); + } + } +} diff --git a/External/Aga.Controls/Tree/ClassDiagram.cd b/Aga.Controls/Tree/ClassDiagram.cd similarity index 97% rename from External/Aga.Controls/Tree/ClassDiagram.cd rename to Aga.Controls/Tree/ClassDiagram.cd index 0bd16ef..1a44c01 100644 --- a/External/Aga.Controls/Tree/ClassDiagram.cd +++ b/Aga.Controls/Tree/ClassDiagram.cd @@ -1,84 +1,84 @@ - - - - - - - Tree\TreeModel.cs - AAAkgAAAAAAQAGQAAAAAEAAAEAACQAAAUAAAAAAAAQE= - - - - - - - - - - - - Tree\TreePath.cs - GABAAAAAAAACAAAAAAIAAAAAAAAACAAAAAAAAAAAAAA= - - - - - - - - - - - Tree\Node.cs - AAAgABAAgCAAAAAAAgAEVAAQAAAQAAAIAAsgCAAAAAA= - - - - - - - - - - Tree\Node.cs - - - - - - - - Tree\NodeControls\NodeControl.cs - AAAAAAAAgAAAgsIAAAhAQAAwAAAAEAAAAEAIAAAAAAA= - - - - - - - - Tree\ITreeModel.cs - AAAEAAAAAAAAAEQAAAAAEAAAEAAAQAAAAAAAAAAAAAA= - - - - - - Tree\IToolTipProvider.cs - AAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - + + + + + + + Tree\TreeModel.cs + AAAkgAAAAAAQAGQAAAAAEAAAEAACQAAAUAAAAAAAAQE= + + + + + + + + + + + + Tree\TreePath.cs + GABAAAAAAAACAAAAAAIAAAAAAAAACAAAAAAAAAAAAAA= + + + + + + + + + + + Tree\Node.cs + AAAgABAAgCAAAAAAAgAEVAAQAAAQAAAIAAsgCAAAAAA= + + + + + + + + + + Tree\Node.cs + + + + + + + + Tree\NodeControls\NodeControl.cs + AAAAAAAAgAAAgsIAAAhAQAAwAAAAEAAAAEAIAAAAAAA= + + + + + + + + Tree\ITreeModel.cs + AAAEAAAAAAAAAEQAAAAAEAAAEAAAQAAAAAAAAAAAAAA= + + + + + + Tree\IToolTipProvider.cs + AAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + \ No newline at end of file diff --git a/External/Aga.Controls/Tree/ColumnCollection.cs b/Aga.Controls/Tree/ColumnCollection.cs similarity index 94% rename from External/Aga.Controls/Tree/ColumnCollection.cs rename to Aga.Controls/Tree/ColumnCollection.cs index 522c37a..b5c6aff 100644 --- a/External/Aga.Controls/Tree/ColumnCollection.cs +++ b/Aga.Controls/Tree/ColumnCollection.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections.ObjectModel; - -namespace Aga.Controls.Tree -{ - /*internal class ColumnCollection: Collection - { - public int TotalWidth - { - get - { - int res = 0; - foreach (Column c in Items) - res += c.Width; - return res; - } - } - }*/ -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; + +namespace Aga.Controls.Tree +{ + /*internal class ColumnCollection: Collection + { + public int TotalWidth + { + get + { + int res = 0; + foreach (Column c in Items) + res += c.Width; + return res; + } + } + }*/ +} diff --git a/External/Aga.Controls/Tree/DrawContext.cs b/Aga.Controls/Tree/DrawContext.cs similarity index 94% rename from External/Aga.Controls/Tree/DrawContext.cs rename to Aga.Controls/Tree/DrawContext.cs index 88a9748..4fe8b1d 100644 --- a/External/Aga.Controls/Tree/DrawContext.cs +++ b/Aga.Controls/Tree/DrawContext.cs @@ -1,60 +1,60 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public struct DrawContext - { - private Graphics _graphics; - public Graphics Graphics - { - get { return _graphics; } - set { _graphics = value; } - } - - private Rectangle _bounds; - public Rectangle Bounds - { - get { return _bounds; } - set { _bounds = value; } - } - - private Font _font; - public Font Font - { - get { return _font; } - set { _font = value; } - } - - private DrawSelectionMode _drawSelection; - public DrawSelectionMode DrawSelection - { - get { return _drawSelection; } - set { _drawSelection = value; } - } - - private bool _drawFocus; - public bool DrawFocus - { - get { return _drawFocus; } - set { _drawFocus = value; } - } - - private NodeControl _currentEditorOwner; - public NodeControl CurrentEditorOwner - { - get { return _currentEditorOwner; } - set { _currentEditorOwner = value; } - } - - private bool _enabled; - public bool Enabled - { - get { return _enabled; } - set { _enabled = value; } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public struct DrawContext + { + private Graphics _graphics; + public Graphics Graphics + { + get { return _graphics; } + set { _graphics = value; } + } + + private Rectangle _bounds; + public Rectangle Bounds + { + get { return _bounds; } + set { _bounds = value; } + } + + private Font _font; + public Font Font + { + get { return _font; } + set { _font = value; } + } + + private DrawSelectionMode _drawSelection; + public DrawSelectionMode DrawSelection + { + get { return _drawSelection; } + set { _drawSelection = value; } + } + + private bool _drawFocus; + public bool DrawFocus + { + get { return _drawFocus; } + set { _drawFocus = value; } + } + + private NodeControl _currentEditorOwner; + public NodeControl CurrentEditorOwner + { + get { return _currentEditorOwner; } + set { _currentEditorOwner = value; } + } + + private bool _enabled; + public bool Enabled + { + get { return _enabled; } + set { _enabled = value; } + } + } +} diff --git a/External/Aga.Controls/Tree/DropNodeValidatingEventArgs.cs b/Aga.Controls/Tree/DropNodeValidatingEventArgs.cs similarity index 93% rename from External/Aga.Controls/Tree/DropNodeValidatingEventArgs.cs rename to Aga.Controls/Tree/DropNodeValidatingEventArgs.cs index f301c18..fb7ef00 100644 --- a/External/Aga.Controls/Tree/DropNodeValidatingEventArgs.cs +++ b/Aga.Controls/Tree/DropNodeValidatingEventArgs.cs @@ -1,28 +1,28 @@ -using System; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - public class DropNodeValidatingEventArgs: EventArgs - { - Point _point; - TreeNodeAdv _node; - - public DropNodeValidatingEventArgs(Point point, TreeNodeAdv node) - { - _point = point; - _node = node; - } - - public Point Point - { - get { return _point; } - } - - public TreeNodeAdv Node - { - get { return _node; } - set { _node = value; } - } - } -} +using System; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + public class DropNodeValidatingEventArgs: EventArgs + { + Point _point; + TreeNodeAdv _node; + + public DropNodeValidatingEventArgs(Point point, TreeNodeAdv node) + { + _point = point; + _node = node; + } + + public Point Point + { + get { return _point; } + } + + public TreeNodeAdv Node + { + get { return _node; } + set { _node = value; } + } + } +} diff --git a/External/Aga.Controls/Tree/DropPosition.cs b/Aga.Controls/Tree/DropPosition.cs similarity index 94% rename from External/Aga.Controls/Tree/DropPosition.cs rename to Aga.Controls/Tree/DropPosition.cs index 1bb800e..7356326 100644 --- a/External/Aga.Controls/Tree/DropPosition.cs +++ b/Aga.Controls/Tree/DropPosition.cs @@ -1,23 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public struct DropPosition - { - private TreeNodeAdv _node; - public TreeNodeAdv Node - { - get { return _node; } - set { _node = value; } - } - - private NodePosition _position; - public NodePosition Position - { - get { return _position; } - set { _position = value; } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public struct DropPosition + { + private TreeNodeAdv _node; + public TreeNodeAdv Node + { + get { return _node; } + set { _node = value; } + } + + private NodePosition _position; + public NodePosition Position + { + get { return _position; } + set { _position = value; } + } + } +} diff --git a/External/Aga.Controls/Tree/EditorContext.cs b/Aga.Controls/Tree/EditorContext.cs similarity index 94% rename from External/Aga.Controls/Tree/EditorContext.cs rename to Aga.Controls/Tree/EditorContext.cs index 3906ccc..ffea2fa 100644 --- a/External/Aga.Controls/Tree/EditorContext.cs +++ b/Aga.Controls/Tree/EditorContext.cs @@ -1,47 +1,47 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public struct EditorContext - { - private TreeNodeAdv _currentNode; - public TreeNodeAdv CurrentNode - { - get { return _currentNode; } - set { _currentNode = value; } - } - - private Control _editor; - public Control Editor - { - get { return _editor; } - set { _editor = value; } - } - - private NodeControl _owner; - public NodeControl Owner - { - get { return _owner; } - set { _owner = value; } - } - - private Rectangle _bounds; - public Rectangle Bounds - { - get { return _bounds; } - set { _bounds = value; } - } - - private DrawContext _drawContext; - public DrawContext DrawContext - { - get { return _drawContext; } - set { _drawContext = value; } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public struct EditorContext + { + private TreeNodeAdv _currentNode; + public TreeNodeAdv CurrentNode + { + get { return _currentNode; } + set { _currentNode = value; } + } + + private Control _editor; + public Control Editor + { + get { return _editor; } + set { _editor = value; } + } + + private NodeControl _owner; + public NodeControl Owner + { + get { return _owner; } + set { _owner = value; } + } + + private Rectangle _bounds; + public Rectangle Bounds + { + get { return _bounds; } + set { _bounds = value; } + } + + private DrawContext _drawContext; + public DrawContext DrawContext + { + get { return _drawContext; } + set { _drawContext = value; } + } + } +} diff --git a/External/Aga.Controls/Tree/Enums.cs b/Aga.Controls/Tree/Enums.cs similarity index 94% rename from External/Aga.Controls/Tree/Enums.cs rename to Aga.Controls/Tree/Enums.cs index 1e6342f..3a83e9a 100644 --- a/External/Aga.Controls/Tree/Enums.cs +++ b/Aga.Controls/Tree/Enums.cs @@ -1,65 +1,65 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public enum DrawSelectionMode - { - None, Active, Inactive, FullRowSelect - } - - public enum TreeSelectionMode - { - Single, Multi, MultiSameParent - } - - public enum NodePosition - { - Inside, Before, After - } - - public enum VerticalAlignment - { - Top, Bottom, Center - } - - public enum IncrementalSearchMode - { - None, Standard, Continuous - } - - [Flags] - public enum GridLineStyle - { - None = 0, - Horizontal = 1, - Vertical = 2, - HorizontalAndVertical = 3 - } - - public enum ImageScaleMode - { - /// - /// Don't scale - /// - Clip, - /// - /// Scales image to fit the display rectangle, aspect ratio is not fixed. - /// - Fit, - /// - /// Scales image down if it is larger than display rectangle, taking aspect ratio into account - /// - ScaleDown, - /// - /// Scales image up if it is smaller than display rectangle, taking aspect ratio into account - /// - ScaleUp, - /// - /// Scales image to match the display rectangle, taking aspect ratio into account - /// - AlwaysScale, - - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public enum DrawSelectionMode + { + None, Active, Inactive, FullRowSelect + } + + public enum TreeSelectionMode + { + Single, Multi, MultiSameParent + } + + public enum NodePosition + { + Inside, Before, After + } + + public enum VerticalAlignment + { + Top, Bottom, Center + } + + public enum IncrementalSearchMode + { + None, Standard, Continuous + } + + [Flags] + public enum GridLineStyle + { + None = 0, + Horizontal = 1, + Vertical = 2, + HorizontalAndVertical = 3 + } + + public enum ImageScaleMode + { + /// + /// Don't scale + /// + Clip, + /// + /// Scales image to fit the display rectangle, aspect ratio is not fixed. + /// + Fit, + /// + /// Scales image down if it is larger than display rectangle, taking aspect ratio into account + /// + ScaleDown, + /// + /// Scales image up if it is smaller than display rectangle, taking aspect ratio into account + /// + ScaleUp, + /// + /// Scales image to match the display rectangle, taking aspect ratio into account + /// + AlwaysScale, + + } +} diff --git a/External/Aga.Controls/Tree/FixedRowHeightLayout.cs b/Aga.Controls/Tree/FixedRowHeightLayout.cs similarity index 95% rename from External/Aga.Controls/Tree/FixedRowHeightLayout.cs rename to Aga.Controls/Tree/FixedRowHeightLayout.cs index b43df66..316b3dc 100644 --- a/External/Aga.Controls/Tree/FixedRowHeightLayout.cs +++ b/Aga.Controls/Tree/FixedRowHeightLayout.cs @@ -1,61 +1,61 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - internal class FixedRowHeightLayout : IRowLayout - { - private TreeViewAdv _treeView; - - public FixedRowHeightLayout(TreeViewAdv treeView, int rowHeight) - { - _treeView = treeView; - PreferredRowHeight = rowHeight; - } - - private int _rowHeight; - public int PreferredRowHeight - { - get { return _rowHeight; } - set { _rowHeight = value; } - } - - public Rectangle GetRowBounds(int rowNo) - { - return new Rectangle(0, rowNo * _rowHeight, 0, _rowHeight); - } - - public int PageRowCount - { - get - { - return Math.Max((_treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight) / _rowHeight, 0); - } - } - - public int CurrentPageSize - { - get - { - return PageRowCount; - } - } - - public int GetRowAt(Point point) - { - point = new Point(point.X, point.Y + (_treeView.FirstVisibleRow * _rowHeight) - _treeView.ColumnHeaderHeight); - return point.Y / _rowHeight; - } - - public int GetFirstRow(int lastPageRow) - { - return Math.Max(0, lastPageRow - PageRowCount + 1); - } - - public void ClearCache() - { - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + internal class FixedRowHeightLayout : IRowLayout + { + private TreeViewAdv _treeView; + + public FixedRowHeightLayout(TreeViewAdv treeView, int rowHeight) + { + _treeView = treeView; + PreferredRowHeight = rowHeight; + } + + private int _rowHeight; + public int PreferredRowHeight + { + get { return _rowHeight; } + set { _rowHeight = value; } + } + + public Rectangle GetRowBounds(int rowNo) + { + return new Rectangle(0, rowNo * _rowHeight, 0, _rowHeight); + } + + public int PageRowCount + { + get + { + return Math.Max((_treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight) / _rowHeight, 0); + } + } + + public int CurrentPageSize + { + get + { + return PageRowCount; + } + } + + public int GetRowAt(Point point) + { + point = new Point(point.X, point.Y + (_treeView.FirstVisibleRow * _rowHeight) - _treeView.ColumnHeaderHeight); + return point.Y / _rowHeight; + } + + public int GetFirstRow(int lastPageRow) + { + return Math.Max(0, lastPageRow - PageRowCount + 1); + } + + public void ClearCache() + { + } + } +} diff --git a/External/Aga.Controls/Tree/IRowLayout.cs b/Aga.Controls/Tree/IRowLayout.cs similarity index 92% rename from External/Aga.Controls/Tree/IRowLayout.cs rename to Aga.Controls/Tree/IRowLayout.cs index 30825b6..9a9018f 100644 --- a/External/Aga.Controls/Tree/IRowLayout.cs +++ b/Aga.Controls/Tree/IRowLayout.cs @@ -1,34 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - internal interface IRowLayout - { - int PreferredRowHeight - { - get; - set; - } - - int PageRowCount - { - get; - } - - int CurrentPageSize - { - get; - } - - Rectangle GetRowBounds(int rowNo); - - int GetRowAt(Point point); - - int GetFirstRow(int lastPageRow); - - void ClearCache(); - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + internal interface IRowLayout + { + int PreferredRowHeight + { + get; + set; + } + + int PageRowCount + { + get; + } + + int CurrentPageSize + { + get; + } + + Rectangle GetRowBounds(int rowNo); + + int GetRowAt(Point point); + + int GetFirstRow(int lastPageRow); + + void ClearCache(); + } +} diff --git a/External/Aga.Controls/Tree/IToolTipProvider.cs b/Aga.Controls/Tree/IToolTipProvider.cs similarity index 95% rename from External/Aga.Controls/Tree/IToolTipProvider.cs rename to Aga.Controls/Tree/IToolTipProvider.cs index 7356e30..3f3e086 100644 --- a/External/Aga.Controls/Tree/IToolTipProvider.cs +++ b/Aga.Controls/Tree/IToolTipProvider.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public interface IToolTipProvider - { - string GetToolTip(TreeNodeAdv node, NodeControl nodeControl); - } -} +using System; +using System.Collections.Generic; +using System.Text; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public interface IToolTipProvider + { + string GetToolTip(TreeNodeAdv node, NodeControl nodeControl); + } +} diff --git a/External/Aga.Controls/Tree/ITreeModel.cs b/Aga.Controls/Tree/ITreeModel.cs similarity index 96% rename from External/Aga.Controls/Tree/ITreeModel.cs rename to Aga.Controls/Tree/ITreeModel.cs index 7880253..680d255 100644 --- a/External/Aga.Controls/Tree/ITreeModel.cs +++ b/Aga.Controls/Tree/ITreeModel.cs @@ -1,18 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections; - -namespace Aga.Controls.Tree -{ - public interface ITreeModel - { - IEnumerable GetChildren(TreePath treePath); - bool IsLeaf(TreePath treePath); - - event EventHandler NodesChanged; - event EventHandler NodesInserted; - event EventHandler NodesRemoved; - event EventHandler StructureChanged; - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace Aga.Controls.Tree +{ + public interface ITreeModel + { + IEnumerable GetChildren(TreePath treePath); + bool IsLeaf(TreePath treePath); + + event EventHandler NodesChanged; + event EventHandler NodesInserted; + event EventHandler NodesRemoved; + event EventHandler StructureChanged; + } +} diff --git a/External/Aga.Controls/Tree/IncrementalSearch.cs b/Aga.Controls/Tree/IncrementalSearch.cs similarity index 95% rename from External/Aga.Controls/Tree/IncrementalSearch.cs rename to Aga.Controls/Tree/IncrementalSearch.cs index 0573631..1390562 100644 --- a/External/Aga.Controls/Tree/IncrementalSearch.cs +++ b/Aga.Controls/Tree/IncrementalSearch.cs @@ -1,144 +1,144 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Aga.Controls.Tree.NodeControls; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; - -namespace Aga.Controls.Tree -{ - internal class IncrementalSearch - { - private const int SearchTimeout = 300; //end of incremental search timeot in msec - - private TreeViewAdv _tree; - private TreeNodeAdv _currentNode; - private string _searchString = ""; - private DateTime _lastKeyPressed = DateTime.Now; - - public IncrementalSearch(TreeViewAdv tree) - { - _tree = tree; - } - - public void Search(Char value) - { - if (!Char.IsControl(value)) - { - Char ch = Char.ToLowerInvariant(value); - DateTime dt = DateTime.Now; - TimeSpan ts = dt - _lastKeyPressed; - _lastKeyPressed = dt; - if (ts.TotalMilliseconds < SearchTimeout) - { - if (_searchString == value.ToString()) - FirstCharSearch(ch); - else - ContinuousSearch(ch); - } - else - { - FirstCharSearch(ch); - } - } - } - - private void ContinuousSearch(Char value) - { - if (value == ' ' && String.IsNullOrEmpty(_searchString)) - return; //Ingnore leading space - - _searchString += value; - DoContinuousSearch(); - } - - private void FirstCharSearch(Char value) - { - if (value == ' ') - return; - - _searchString = value.ToString(); - TreeNodeAdv node = null; - if (_tree.SelectedNode != null) - node = _tree.SelectedNode.NextVisibleNode; - if (node == null) - node = _tree.Root.NextVisibleNode; - - if (node != null) - foreach (string label in IterateNodeLabels(node)) - { - if (label.StartsWith(_searchString)) - { - _tree.SelectedNode = _currentNode; - return; - } - } - } - - public virtual void EndSearch() - { - _currentNode = null; - _searchString = ""; - } - - protected IEnumerable IterateNodeLabels(TreeNodeAdv start) - { - _currentNode = start; - while(_currentNode != null) - { - foreach (string label in GetNodeLabels(_currentNode)) - yield return label; - - _currentNode = _currentNode.NextVisibleNode; - if (_currentNode == null) - _currentNode = _tree.Root; - - if (start == _currentNode) - break; - } - } - - private IEnumerable GetNodeLabels(TreeNodeAdv node) - { - foreach (NodeControl nc in _tree.NodeControls) - { - BindableControl bc = nc as BindableControl; - if (bc != null && bc.IncrementalSearchEnabled) - { - object obj = bc.GetValue(node); - if (obj != null) - yield return obj.ToString().ToLowerInvariant(); - } - } - } - - private bool DoContinuousSearch() - { - bool found = false; - if (!String.IsNullOrEmpty(_searchString)) - { - TreeNodeAdv node = null; - if (_tree.SelectedNode != null) - node = _tree.SelectedNode; - if (node == null) - node = _tree.Root.NextVisibleNode; - - if (!String.IsNullOrEmpty(_searchString)) - { - foreach (string label in IterateNodeLabels(node)) - { - if (label.StartsWith(_searchString)) - { - found = true; - _tree.SelectedNode = _currentNode; - break; - } - } - } - } - return found; - } - - } -} +using System; +using System.Collections.Generic; +using System.Text; +using Aga.Controls.Tree.NodeControls; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + internal class IncrementalSearch + { + private const int SearchTimeout = 300; //end of incremental search timeot in msec + + private TreeViewAdv _tree; + private TreeNodeAdv _currentNode; + private string _searchString = ""; + private DateTime _lastKeyPressed = DateTime.Now; + + public IncrementalSearch(TreeViewAdv tree) + { + _tree = tree; + } + + public void Search(Char value) + { + if (!Char.IsControl(value)) + { + Char ch = Char.ToLowerInvariant(value); + DateTime dt = DateTime.Now; + TimeSpan ts = dt - _lastKeyPressed; + _lastKeyPressed = dt; + if (ts.TotalMilliseconds < SearchTimeout) + { + if (_searchString == value.ToString()) + FirstCharSearch(ch); + else + ContinuousSearch(ch); + } + else + { + FirstCharSearch(ch); + } + } + } + + private void ContinuousSearch(Char value) + { + if (value == ' ' && String.IsNullOrEmpty(_searchString)) + return; //Ingnore leading space + + _searchString += value; + DoContinuousSearch(); + } + + private void FirstCharSearch(Char value) + { + if (value == ' ') + return; + + _searchString = value.ToString(); + TreeNodeAdv node = null; + if (_tree.SelectedNode != null) + node = _tree.SelectedNode.NextVisibleNode; + if (node == null) + node = _tree.Root.NextVisibleNode; + + if (node != null) + foreach (string label in IterateNodeLabels(node)) + { + if (label.StartsWith(_searchString)) + { + _tree.SelectedNode = _currentNode; + return; + } + } + } + + public virtual void EndSearch() + { + _currentNode = null; + _searchString = ""; + } + + protected IEnumerable IterateNodeLabels(TreeNodeAdv start) + { + _currentNode = start; + while(_currentNode != null) + { + foreach (string label in GetNodeLabels(_currentNode)) + yield return label; + + _currentNode = _currentNode.NextVisibleNode; + if (_currentNode == null) + _currentNode = _tree.Root; + + if (start == _currentNode) + break; + } + } + + private IEnumerable GetNodeLabels(TreeNodeAdv node) + { + foreach (NodeControl nc in _tree.NodeControls) + { + BindableControl bc = nc as BindableControl; + if (bc != null && bc.IncrementalSearchEnabled) + { + object obj = bc.GetValue(node); + if (obj != null) + yield return obj.ToString().ToLowerInvariant(); + } + } + } + + private bool DoContinuousSearch() + { + bool found = false; + if (!String.IsNullOrEmpty(_searchString)) + { + TreeNodeAdv node = null; + if (_tree.SelectedNode != null) + node = _tree.SelectedNode; + if (node == null) + node = _tree.Root.NextVisibleNode; + + if (!String.IsNullOrEmpty(_searchString)) + { + foreach (string label in IterateNodeLabels(node)) + { + if (label.StartsWith(_searchString)) + { + found = true; + _tree.SelectedNode = _currentNode; + break; + } + } + } + } + return found; + } + + } +} diff --git a/External/Aga.Controls/Tree/Input/ClickColumnState.cs b/Aga.Controls/Tree/Input/ClickColumnState.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/ClickColumnState.cs rename to Aga.Controls/Tree/Input/ClickColumnState.cs index 9fa1923..12146c9 100644 --- a/External/Aga.Controls/Tree/Input/ClickColumnState.cs +++ b/Aga.Controls/Tree/Input/ClickColumnState.cs @@ -1,45 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - internal class ClickColumnState : ColumnState - { - private Point _location; - - public ClickColumnState(TreeViewAdv tree, TreeColumn column, Point location) - : base(tree, column) - { - _location = location; - } - - public override void KeyDown(KeyEventArgs args) - { - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - } - - public override bool MouseMove(MouseEventArgs args) - { - if (TreeViewAdv.Dist(_location, args.Location) > TreeViewAdv.ItemDragSensivity - && Tree.AllowColumnReorder) - { - Tree.Input = new ReorderColumnState(Tree, Column, args.Location); - Tree.UpdateView(); - } - return true; - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - Tree.ChangeInput(); - Tree.UpdateView(); - Tree.OnColumnClicked(Column); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + internal class ClickColumnState : ColumnState + { + private Point _location; + + public ClickColumnState(TreeViewAdv tree, TreeColumn column, Point location) + : base(tree, column) + { + _location = location; + } + + public override void KeyDown(KeyEventArgs args) + { + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + } + + public override bool MouseMove(MouseEventArgs args) + { + if (TreeViewAdv.Dist(_location, args.Location) > TreeViewAdv.ItemDragSensivity + && Tree.AllowColumnReorder) + { + Tree.Input = new ReorderColumnState(Tree, Column, args.Location); + Tree.UpdateView(); + } + return true; + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + Tree.ChangeInput(); + Tree.UpdateView(); + Tree.OnColumnClicked(Column); + } + } +} diff --git a/External/Aga.Controls/Tree/Input/ColumnState.cs b/Aga.Controls/Tree/Input/ColumnState.cs similarity index 94% rename from External/Aga.Controls/Tree/Input/ColumnState.cs rename to Aga.Controls/Tree/Input/ColumnState.cs index 10e064f..2b8fc7d 100644 --- a/External/Aga.Controls/Tree/Input/ColumnState.cs +++ b/Aga.Controls/Tree/Input/ColumnState.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - internal abstract class ColumnState : InputState - { - private TreeColumn _column; - public TreeColumn Column - { - get { return _column; } - } - - public ColumnState(TreeViewAdv tree, TreeColumn column) - : base(tree) - { - _column = column; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + internal abstract class ColumnState : InputState + { + private TreeColumn _column; + public TreeColumn Column + { + get { return _column; } + } + + public ColumnState(TreeViewAdv tree, TreeColumn column) + : base(tree) + { + _column = column; + } + } +} diff --git a/External/Aga.Controls/Tree/Input/InputState.cs b/Aga.Controls/Tree/Input/InputState.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/InputState.cs rename to Aga.Controls/Tree/Input/InputState.cs index 65f07f9..b347d4f 100644 --- a/External/Aga.Controls/Tree/Input/InputState.cs +++ b/Aga.Controls/Tree/Input/InputState.cs @@ -1,37 +1,37 @@ -using System; -using System.Windows.Forms; -namespace Aga.Controls.Tree -{ - internal abstract class InputState - { - private TreeViewAdv _tree; - - public TreeViewAdv Tree - { - get { return _tree; } - } - - public InputState(TreeViewAdv tree) - { - _tree = tree; - } - - public abstract void KeyDown(System.Windows.Forms.KeyEventArgs args); - public abstract void MouseDown(TreeNodeAdvMouseEventArgs args); - public abstract void MouseUp(TreeNodeAdvMouseEventArgs args); - - /// - /// handle OnMouseMove event - /// - /// - /// true if event was handled and should be dispatched - public virtual bool MouseMove(MouseEventArgs args) - { - return false; - } - - public virtual void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - } - } -} +using System; +using System.Windows.Forms; +namespace Aga.Controls.Tree +{ + internal abstract class InputState + { + private TreeViewAdv _tree; + + public TreeViewAdv Tree + { + get { return _tree; } + } + + public InputState(TreeViewAdv tree) + { + _tree = tree; + } + + public abstract void KeyDown(System.Windows.Forms.KeyEventArgs args); + public abstract void MouseDown(TreeNodeAdvMouseEventArgs args); + public abstract void MouseUp(TreeNodeAdvMouseEventArgs args); + + /// + /// handle OnMouseMove event + /// + /// + /// true if event was handled and should be dispatched + public virtual bool MouseMove(MouseEventArgs args) + { + return false; + } + + public virtual void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + } + } +} diff --git a/External/Aga.Controls/Tree/Input/InputWithControl.cs b/Aga.Controls/Tree/Input/InputWithControl.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/InputWithControl.cs rename to Aga.Controls/Tree/Input/InputWithControl.cs index 94bd857..6559b67 100644 --- a/External/Aga.Controls/Tree/Input/InputWithControl.cs +++ b/Aga.Controls/Tree/Input/InputWithControl.cs @@ -1,30 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - internal class InputWithControl: NormalInputState - { - public InputWithControl(TreeViewAdv tree): base(tree) - { - } - - protected override void DoMouseOperation(TreeNodeAdvMouseEventArgs args) - { - if (Tree.SelectionMode == TreeSelectionMode.Single) - { - base.DoMouseOperation(args); - } - else if (CanSelect(args.Node)) - { - args.Node.IsSelected = !args.Node.IsSelected; - Tree.SelectionStart = args.Node; - } - } - - protected override void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) - { - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + internal class InputWithControl: NormalInputState + { + public InputWithControl(TreeViewAdv tree): base(tree) + { + } + + protected override void DoMouseOperation(TreeNodeAdvMouseEventArgs args) + { + if (Tree.SelectionMode == TreeSelectionMode.Single) + { + base.DoMouseOperation(args); + } + else if (CanSelect(args.Node)) + { + args.Node.IsSelected = !args.Node.IsSelected; + Tree.SelectionStart = args.Node; + } + } + + protected override void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) + { + } + } +} diff --git a/External/Aga.Controls/Tree/Input/InputWithShift.cs b/Aga.Controls/Tree/Input/InputWithShift.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/InputWithShift.cs rename to Aga.Controls/Tree/Input/InputWithShift.cs index a5a7aa0..777fc7a 100644 --- a/External/Aga.Controls/Tree/Input/InputWithShift.cs +++ b/Aga.Controls/Tree/Input/InputWithShift.cs @@ -1,69 +1,69 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - internal class InputWithShift: NormalInputState - { - public InputWithShift(TreeViewAdv tree): base(tree) - { - } - - protected override void FocusRow(TreeNodeAdv node) - { - Tree.SuspendSelectionEvent = true; - try - { - if (Tree.SelectionMode == TreeSelectionMode.Single || Tree.SelectionStart == null) - base.FocusRow(node); - else if (CanSelect(node)) - { - SelectAllFromStart(node); - Tree.CurrentNode = node; - Tree.ScrollTo(node); - } - } - finally - { - Tree.SuspendSelectionEvent = false; - } - } - - protected override void DoMouseOperation(TreeNodeAdvMouseEventArgs args) - { - if (Tree.SelectionMode == TreeSelectionMode.Single || Tree.SelectionStart == null) - { - base.DoMouseOperation(args); - } - else if (CanSelect(args.Node)) - { - Tree.SuspendSelectionEvent = true; - try - { - SelectAllFromStart(args.Node); - } - finally - { - Tree.SuspendSelectionEvent = false; - } - } - } - - protected override void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) - { - } - - private void SelectAllFromStart(TreeNodeAdv node) - { - Tree.ClearSelectionInternal(); - int a = node.Row; - int b = Tree.SelectionStart.Row; - for (int i = Math.Min(a, b); i <= Math.Max(a, b); i++) - { - if (Tree.SelectionMode == TreeSelectionMode.Multi || Tree.RowMap[i].Parent == node.Parent) - Tree.RowMap[i].IsSelected = true; - } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + internal class InputWithShift: NormalInputState + { + public InputWithShift(TreeViewAdv tree): base(tree) + { + } + + protected override void FocusRow(TreeNodeAdv node) + { + Tree.SuspendSelectionEvent = true; + try + { + if (Tree.SelectionMode == TreeSelectionMode.Single || Tree.SelectionStart == null) + base.FocusRow(node); + else if (CanSelect(node)) + { + SelectAllFromStart(node); + Tree.CurrentNode = node; + Tree.ScrollTo(node); + } + } + finally + { + Tree.SuspendSelectionEvent = false; + } + } + + protected override void DoMouseOperation(TreeNodeAdvMouseEventArgs args) + { + if (Tree.SelectionMode == TreeSelectionMode.Single || Tree.SelectionStart == null) + { + base.DoMouseOperation(args); + } + else if (CanSelect(args.Node)) + { + Tree.SuspendSelectionEvent = true; + try + { + SelectAllFromStart(args.Node); + } + finally + { + Tree.SuspendSelectionEvent = false; + } + } + } + + protected override void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) + { + } + + private void SelectAllFromStart(TreeNodeAdv node) + { + Tree.ClearSelectionInternal(); + int a = node.Row; + int b = Tree.SelectionStart.Row; + for (int i = Math.Min(a, b); i <= Math.Max(a, b); i++) + { + if (Tree.SelectionMode == TreeSelectionMode.Multi || Tree.RowMap[i].Parent == node.Parent) + Tree.RowMap[i].IsSelected = true; + } + } + } +} diff --git a/External/Aga.Controls/Tree/Input/NormalInputState.cs b/Aga.Controls/Tree/Input/NormalInputState.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/NormalInputState.cs rename to Aga.Controls/Tree/Input/NormalInputState.cs index 360973e..7a66be9 100644 --- a/External/Aga.Controls/Tree/Input/NormalInputState.cs +++ b/Aga.Controls/Tree/Input/NormalInputState.cs @@ -1,202 +1,202 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; - -namespace Aga.Controls.Tree -{ - internal class NormalInputState : InputState - { - private bool _mouseDownFlag = false; - - public NormalInputState(TreeViewAdv tree) : base(tree) - { - } - - public override void KeyDown(KeyEventArgs args) - { - if (Tree.CurrentNode == null && Tree.Root.Nodes.Count > 0) - Tree.CurrentNode = Tree.Root.Nodes[0]; - - if (Tree.CurrentNode != null) - { - switch (args.KeyCode) - { - case Keys.Right: - if (!Tree.CurrentNode.IsExpanded) - Tree.CurrentNode.IsExpanded = true; - else if (Tree.CurrentNode.Nodes.Count > 0) - Tree.SelectedNode = Tree.CurrentNode.Nodes[0]; - args.Handled = true; - break; - case Keys.Left: - if (Tree.CurrentNode.IsExpanded) - Tree.CurrentNode.IsExpanded = false; - else if (Tree.CurrentNode.Parent != Tree.Root) - Tree.SelectedNode = Tree.CurrentNode.Parent; - args.Handled = true; - break; - case Keys.Down: - NavigateForward(1); - args.Handled = true; - break; - case Keys.Up: - NavigateBackward(1); - args.Handled = true; - break; - case Keys.PageDown: - NavigateForward(Math.Max(1, Tree.CurrentPageSize - 1)); - args.Handled = true; - break; - case Keys.PageUp: - NavigateBackward(Math.Max(1, Tree.CurrentPageSize - 1)); - args.Handled = true; - break; - case Keys.Home: - if (Tree.RowMap.Count > 0) - FocusRow(Tree.RowMap[0]); - args.Handled = true; - break; - case Keys.End: - if (Tree.RowMap.Count > 0) - FocusRow(Tree.RowMap[Tree.RowMap.Count-1]); - args.Handled = true; - break; - case Keys.Subtract: - Tree.CurrentNode.Collapse(); - args.Handled = true; - args.SuppressKeyPress = true; - break; - case Keys.Add: - Tree.CurrentNode.Expand(); - args.Handled = true; - args.SuppressKeyPress = true; - break; - case Keys.Multiply: - Tree.CurrentNode.ExpandAll(); - args.Handled = true; - args.SuppressKeyPress = true; - break; - case Keys.A: - if (args.Modifiers == Keys.Control) - Tree.SelectAllNodes(); - break; - } - } - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - if (args.Node != null) - { - Tree.ItemDragMode = true; - Tree.ItemDragStart = args.Location; - - if (args.Button == MouseButtons.Left || args.Button == MouseButtons.Right) - { - Tree.BeginUpdate(); - try - { - Tree.CurrentNode = args.Node; - if (args.Node.IsSelected) - _mouseDownFlag = true; - else - { - _mouseDownFlag = false; - DoMouseOperation(args); - } - } - finally - { - Tree.EndUpdate(); - } - } - - } - else - { - Tree.ItemDragMode = false; - MouseDownAtEmptySpace(args); - } - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - Tree.ItemDragMode = false; - if (_mouseDownFlag && args.Node != null) - { - if (args.Button == MouseButtons.Left) - DoMouseOperation(args); - else if (args.Button == MouseButtons.Right) - Tree.CurrentNode = args.Node; - } - _mouseDownFlag = false; - } - - - private void NavigateBackward(int n) - { - int row = Math.Max(Tree.CurrentNode.Row - n, 0); - if (row != Tree.CurrentNode.Row) - FocusRow(Tree.RowMap[row]); - } - - private void NavigateForward(int n) - { - int row = Math.Min(Tree.CurrentNode.Row + n, Tree.RowCount - 1); - if (row != Tree.CurrentNode.Row) - FocusRow(Tree.RowMap[row]); - } - - protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) - { - Tree.ClearSelection(); - } - - protected virtual void FocusRow(TreeNodeAdv node) - { - Tree.SuspendSelectionEvent = true; - try - { - Tree.ClearSelectionInternal(); - Tree.CurrentNode = node; - Tree.SelectionStart = node; - node.IsSelected = true; - Tree.ScrollTo(node); - } - finally - { - Tree.SuspendSelectionEvent = false; - } - } - - protected bool CanSelect(TreeNodeAdv node) - { - if (Tree.SelectionMode == TreeSelectionMode.MultiSameParent) - { - return (Tree.SelectionStart == null || node.Parent == Tree.SelectionStart.Parent); - } - else - return true; - } - - protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args) - { - if (Tree.SelectedNodes.Count == 1 && args.Node != null && args.Node.IsSelected) - return; - - Tree.SuspendSelectionEvent = true; - try - { - Tree.ClearSelectionInternal(); - if (args.Node != null) - args.Node.IsSelected = true; - Tree.SelectionStart = args.Node; - } - finally - { - Tree.SuspendSelectionEvent = false; - } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + internal class NormalInputState : InputState + { + private bool _mouseDownFlag = false; + + public NormalInputState(TreeViewAdv tree) : base(tree) + { + } + + public override void KeyDown(KeyEventArgs args) + { + if (Tree.CurrentNode == null && Tree.Root.Nodes.Count > 0) + Tree.CurrentNode = Tree.Root.Nodes[0]; + + if (Tree.CurrentNode != null) + { + switch (args.KeyCode) + { + case Keys.Right: + if (!Tree.CurrentNode.IsExpanded) + Tree.CurrentNode.IsExpanded = true; + else if (Tree.CurrentNode.Nodes.Count > 0) + Tree.SelectedNode = Tree.CurrentNode.Nodes[0]; + args.Handled = true; + break; + case Keys.Left: + if (Tree.CurrentNode.IsExpanded) + Tree.CurrentNode.IsExpanded = false; + else if (Tree.CurrentNode.Parent != Tree.Root) + Tree.SelectedNode = Tree.CurrentNode.Parent; + args.Handled = true; + break; + case Keys.Down: + NavigateForward(1); + args.Handled = true; + break; + case Keys.Up: + NavigateBackward(1); + args.Handled = true; + break; + case Keys.PageDown: + NavigateForward(Math.Max(1, Tree.CurrentPageSize - 1)); + args.Handled = true; + break; + case Keys.PageUp: + NavigateBackward(Math.Max(1, Tree.CurrentPageSize - 1)); + args.Handled = true; + break; + case Keys.Home: + if (Tree.RowMap.Count > 0) + FocusRow(Tree.RowMap[0]); + args.Handled = true; + break; + case Keys.End: + if (Tree.RowMap.Count > 0) + FocusRow(Tree.RowMap[Tree.RowMap.Count-1]); + args.Handled = true; + break; + case Keys.Subtract: + Tree.CurrentNode.Collapse(); + args.Handled = true; + args.SuppressKeyPress = true; + break; + case Keys.Add: + Tree.CurrentNode.Expand(); + args.Handled = true; + args.SuppressKeyPress = true; + break; + case Keys.Multiply: + Tree.CurrentNode.ExpandAll(); + args.Handled = true; + args.SuppressKeyPress = true; + break; + case Keys.A: + if (args.Modifiers == Keys.Control) + Tree.SelectAllNodes(); + break; + } + } + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + if (args.Node != null) + { + Tree.ItemDragMode = true; + Tree.ItemDragStart = args.Location; + + if (args.Button == MouseButtons.Left || args.Button == MouseButtons.Right) + { + Tree.BeginUpdate(); + try + { + Tree.CurrentNode = args.Node; + if (args.Node.IsSelected) + _mouseDownFlag = true; + else + { + _mouseDownFlag = false; + DoMouseOperation(args); + } + } + finally + { + Tree.EndUpdate(); + } + } + + } + else + { + Tree.ItemDragMode = false; + MouseDownAtEmptySpace(args); + } + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + Tree.ItemDragMode = false; + if (_mouseDownFlag && args.Node != null) + { + if (args.Button == MouseButtons.Left) + DoMouseOperation(args); + else if (args.Button == MouseButtons.Right) + Tree.CurrentNode = args.Node; + } + _mouseDownFlag = false; + } + + + private void NavigateBackward(int n) + { + int row = Math.Max(Tree.CurrentNode.Row - n, 0); + if (row != Tree.CurrentNode.Row) + FocusRow(Tree.RowMap[row]); + } + + private void NavigateForward(int n) + { + int row = Math.Min(Tree.CurrentNode.Row + n, Tree.RowCount - 1); + if (row != Tree.CurrentNode.Row) + FocusRow(Tree.RowMap[row]); + } + + protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) + { + Tree.ClearSelection(); + } + + protected virtual void FocusRow(TreeNodeAdv node) + { + Tree.SuspendSelectionEvent = true; + try + { + Tree.ClearSelectionInternal(); + Tree.CurrentNode = node; + Tree.SelectionStart = node; + node.IsSelected = true; + Tree.ScrollTo(node); + } + finally + { + Tree.SuspendSelectionEvent = false; + } + } + + protected bool CanSelect(TreeNodeAdv node) + { + if (Tree.SelectionMode == TreeSelectionMode.MultiSameParent) + { + return (Tree.SelectionStart == null || node.Parent == Tree.SelectionStart.Parent); + } + else + return true; + } + + protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args) + { + if (Tree.SelectedNodes.Count == 1 && args.Node != null && args.Node.IsSelected) + return; + + Tree.SuspendSelectionEvent = true; + try + { + Tree.ClearSelectionInternal(); + if (args.Node != null) + args.Node.IsSelected = true; + Tree.SelectionStart = args.Node; + } + finally + { + Tree.SuspendSelectionEvent = false; + } + } + } +} diff --git a/External/Aga.Controls/Tree/Input/ReorderColumnState.cs b/Aga.Controls/Tree/Input/ReorderColumnState.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/ReorderColumnState.cs rename to Aga.Controls/Tree/Input/ReorderColumnState.cs index 2fe445f..181cca5 100644 --- a/External/Aga.Controls/Tree/Input/ReorderColumnState.cs +++ b/Aga.Controls/Tree/Input/ReorderColumnState.cs @@ -1,101 +1,101 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; - -namespace Aga.Controls.Tree -{ - internal class ReorderColumnState : ColumnState - { - #region Properties - - private Point _location; - public Point Location - { - get { return _location; } - } - - private Bitmap _ghostImage; - public Bitmap GhostImage - { - get { return _ghostImage; } - } - - private TreeColumn _dropColumn; - public TreeColumn DropColumn - { - get { return _dropColumn; } - } - - private int _dragOffset; - public int DragOffset - { - get { return _dragOffset; } - } - - #endregion - - public ReorderColumnState(TreeViewAdv tree, TreeColumn column, Point initialMouseLocation) - : base(tree, column) - { - _location = new Point(initialMouseLocation.X + Tree.OffsetX, 0); - _dragOffset = tree.GetColumnX(column) - initialMouseLocation.X; - _ghostImage = column.CreateGhostImage(new Rectangle(0, 0, column.Width, tree.ColumnHeaderHeight), tree.Font); - } - - public override void KeyDown(KeyEventArgs args) - { - args.Handled = true; - if (args.KeyCode == Keys.Escape) - FinishResize(); - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - FinishResize(); - } - - public override bool MouseMove(MouseEventArgs args) - { - _dropColumn = null; - _location = new Point(args.X + Tree.OffsetX, 0); - int x = 0; - foreach (TreeColumn c in Tree.Columns) - { - if (c.IsVisible) - { - if (_location.X < x + c.Width / 2) - { - _dropColumn = c; - break; - } - x += c.Width; - } - } - Tree.UpdateHeaders(); - return true; - } - - private void FinishResize() - { - Tree.ChangeInput(); - if (Column == DropColumn) - Tree.UpdateView(); - else - { - Tree.Columns.Remove(Column); - if (DropColumn == null) - Tree.Columns.Add(Column); - else - Tree.Columns.Insert(Tree.Columns.IndexOf(DropColumn), Column); - - Tree.OnColumnReordered(Column); - } - } - } +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + internal class ReorderColumnState : ColumnState + { + #region Properties + + private Point _location; + public Point Location + { + get { return _location; } + } + + private Bitmap _ghostImage; + public Bitmap GhostImage + { + get { return _ghostImage; } + } + + private TreeColumn _dropColumn; + public TreeColumn DropColumn + { + get { return _dropColumn; } + } + + private int _dragOffset; + public int DragOffset + { + get { return _dragOffset; } + } + + #endregion + + public ReorderColumnState(TreeViewAdv tree, TreeColumn column, Point initialMouseLocation) + : base(tree, column) + { + _location = new Point(initialMouseLocation.X + Tree.OffsetX, 0); + _dragOffset = tree.GetColumnX(column) - initialMouseLocation.X; + _ghostImage = column.CreateGhostImage(new Rectangle(0, 0, column.Width, tree.ColumnHeaderHeight), tree.Font); + } + + public override void KeyDown(KeyEventArgs args) + { + args.Handled = true; + if (args.KeyCode == Keys.Escape) + FinishResize(); + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + FinishResize(); + } + + public override bool MouseMove(MouseEventArgs args) + { + _dropColumn = null; + _location = new Point(args.X + Tree.OffsetX, 0); + int x = 0; + foreach (TreeColumn c in Tree.Columns) + { + if (c.IsVisible) + { + if (_location.X < x + c.Width / 2) + { + _dropColumn = c; + break; + } + x += c.Width; + } + } + Tree.UpdateHeaders(); + return true; + } + + private void FinishResize() + { + Tree.ChangeInput(); + if (Column == DropColumn) + Tree.UpdateView(); + else + { + Tree.Columns.Remove(Column); + if (DropColumn == null) + Tree.Columns.Add(Column); + else + Tree.Columns.Insert(Tree.Columns.IndexOf(DropColumn), Column); + + Tree.OnColumnReordered(Column); + } + } + } } \ No newline at end of file diff --git a/External/Aga.Controls/Tree/Input/ResizeColumnState.cs b/Aga.Controls/Tree/Input/ResizeColumnState.cs similarity index 95% rename from External/Aga.Controls/Tree/Input/ResizeColumnState.cs rename to Aga.Controls/Tree/Input/ResizeColumnState.cs index 6a01038..e4d8653 100644 --- a/External/Aga.Controls/Tree/Input/ResizeColumnState.cs +++ b/Aga.Controls/Tree/Input/ResizeColumnState.cs @@ -1,57 +1,57 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Security.Permissions; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - internal class ResizeColumnState: ColumnState - { - private Point _initLocation; - private int _initWidth; - - public ResizeColumnState(TreeViewAdv tree, TreeColumn column, Point p) - : base(tree, column) - { - _initLocation = p; - _initWidth = column.Width; - } - - public override void KeyDown(KeyEventArgs args) - { - args.Handled = true; - if (args.KeyCode == Keys.Escape) - FinishResize(); - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - FinishResize(); - } - - private void FinishResize() - { - Tree.ChangeInput(); - Tree.FullUpdate(); - Tree.OnColumnWidthChanged(Column); - } - - public override bool MouseMove(MouseEventArgs args) - { - Column.Width = _initWidth + args.Location.X - _initLocation.X; - Tree.UpdateView(); - return true; - } - - public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - Tree.AutoSizeColumn(Column); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Security.Permissions; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + internal class ResizeColumnState: ColumnState + { + private Point _initLocation; + private int _initWidth; + + public ResizeColumnState(TreeViewAdv tree, TreeColumn column, Point p) + : base(tree, column) + { + _initLocation = p; + _initWidth = column.Width; + } + + public override void KeyDown(KeyEventArgs args) + { + args.Handled = true; + if (args.KeyCode == Keys.Escape) + FinishResize(); + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + FinishResize(); + } + + private void FinishResize() + { + Tree.ChangeInput(); + Tree.FullUpdate(); + Tree.OnColumnWidthChanged(Column); + } + + public override bool MouseMove(MouseEventArgs args) + { + Column.Width = _initWidth + args.Location.X - _initLocation.X; + Tree.UpdateView(); + return true; + } + + public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + Tree.AutoSizeColumn(Column); + } + } +} diff --git a/External/Aga.Controls/Tree/ListModel.cs b/Aga.Controls/Tree/ListModel.cs similarity index 94% rename from External/Aga.Controls/Tree/ListModel.cs rename to Aga.Controls/Tree/ListModel.cs index 1aacfc1..4d833e2 100644 --- a/External/Aga.Controls/Tree/ListModel.cs +++ b/Aga.Controls/Tree/ListModel.cs @@ -1,56 +1,56 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections; - -namespace Aga.Controls.Tree -{ - public class ListModel : TreeModelBase - { - private IList _list; - - public int Count - { - get { return _list.Count; } - } - - public ListModel() - { - _list = new List(); - } - - public ListModel(IList list) - { - _list = list; - } - - public override IEnumerable GetChildren(TreePath treePath) - { - return _list; - } - - public override bool IsLeaf(TreePath treePath) - { - return true; - } - - public void AddRange(IEnumerable items) - { - foreach (object obj in items) - _list.Add(obj); - OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); - } - - public void Add(object item) - { - _list.Add(item); - OnNodesInserted(new TreeModelEventArgs(TreePath.Empty, new int[] { _list.Count - 1 }, new object[] { item })); - } - - public void Clear() - { - _list.Clear(); - OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace Aga.Controls.Tree +{ + public class ListModel : TreeModelBase + { + private IList _list; + + public int Count + { + get { return _list.Count; } + } + + public ListModel() + { + _list = new List(); + } + + public ListModel(IList list) + { + _list = list; + } + + public override IEnumerable GetChildren(TreePath treePath) + { + return _list; + } + + public override bool IsLeaf(TreePath treePath) + { + return true; + } + + public void AddRange(IEnumerable items) + { + foreach (object obj in items) + _list.Add(obj); + OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); + } + + public void Add(object item) + { + _list.Add(item); + OnNodesInserted(new TreeModelEventArgs(TreePath.Empty, new int[] { _list.Count - 1 }, new object[] { item })); + } + + public void Clear() + { + _list.Clear(); + OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); + } + } +} diff --git a/External/Aga.Controls/Tree/NativeMethods.cs b/Aga.Controls/Tree/NativeMethods.cs similarity index 97% rename from External/Aga.Controls/Tree/NativeMethods.cs rename to Aga.Controls/Tree/NativeMethods.cs index 7dafc7a..81e2635 100644 --- a/External/Aga.Controls/Tree/NativeMethods.cs +++ b/Aga.Controls/Tree/NativeMethods.cs @@ -1,74 +1,74 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; - - -namespace Aga.Controls.Tree -{ - internal static class NativeMethods - { - public const int DCX_WINDOW = 0x01; - public const int DCX_CACHE = 0x02; - public const int DCX_NORESETATTRS = 0x04; - public const int DCX_CLIPCHILDREN = 0x08; - public const int DCX_CLIPSIBLINGS = 0x10; - public const int DCX_PARENTCLIP = 0x20; - public const int DCX_EXCLUDERGN = 0x40; - public const int DCX_INTERSECTRGN = 0x80; - public const int DCX_EXCLUDEUPDATE = 0x100; - public const int DCX_INTERSECTUPDATE = 0x200; - public const int DCX_LOCKWINDOWUPDATE = 0x400; - public const int DCX_VALIDATE = 0x200000; - - public const int WM_THEMECHANGED = 0x031A; - public const int WM_NCPAINT = 0x85; - public const int WM_NCCALCSIZE = 0x83; - - public const int WS_BORDER = 0x800000; - public const int WS_EX_CLIENTEDGE = 0x200; - - public const int WVR_HREDRAW = 0x100; - public const int WVR_VREDRAW = 0x200; - public const int WVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW); - - [StructLayout(LayoutKind.Sequential)] - public struct NCCALCSIZE_PARAMS - { - public RECT rgrc0, rgrc1, rgrc2; - public IntPtr lppos; - } - - [StructLayout(LayoutKind.Sequential)] - public struct RECT - { - public int Left; - public int Top; - public int Right; - public int Bottom; - - public static RECT FromRectangle(Rectangle rectangle) - { - RECT result = new RECT(); - result.Left = rectangle.Left; - result.Top = rectangle.Top; - result.Right = rectangle.Right; - result.Bottom = rectangle.Bottom; - return result; - } - - public Rectangle ToRectangle() - { - return new Rectangle(Left, Top, Right - Left, Bottom - Top); - } - } - - [DllImport("user32.dll", SetLastError = true)] - public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags); - - [DllImport("user32.dll")] - public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); - - [DllImport("user32.dll")] - public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); - } -} +using System; +using System.Drawing; +using System.Runtime.InteropServices; + + +namespace Aga.Controls.Tree +{ + internal static class NativeMethods + { + public const int DCX_WINDOW = 0x01; + public const int DCX_CACHE = 0x02; + public const int DCX_NORESETATTRS = 0x04; + public const int DCX_CLIPCHILDREN = 0x08; + public const int DCX_CLIPSIBLINGS = 0x10; + public const int DCX_PARENTCLIP = 0x20; + public const int DCX_EXCLUDERGN = 0x40; + public const int DCX_INTERSECTRGN = 0x80; + public const int DCX_EXCLUDEUPDATE = 0x100; + public const int DCX_INTERSECTUPDATE = 0x200; + public const int DCX_LOCKWINDOWUPDATE = 0x400; + public const int DCX_VALIDATE = 0x200000; + + public const int WM_THEMECHANGED = 0x031A; + public const int WM_NCPAINT = 0x85; + public const int WM_NCCALCSIZE = 0x83; + + public const int WS_BORDER = 0x800000; + public const int WS_EX_CLIENTEDGE = 0x200; + + public const int WVR_HREDRAW = 0x100; + public const int WVR_VREDRAW = 0x200; + public const int WVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW); + + [StructLayout(LayoutKind.Sequential)] + public struct NCCALCSIZE_PARAMS + { + public RECT rgrc0, rgrc1, rgrc2; + public IntPtr lppos; + } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int Left; + public int Top; + public int Right; + public int Bottom; + + public static RECT FromRectangle(Rectangle rectangle) + { + RECT result = new RECT(); + result.Left = rectangle.Left; + result.Top = rectangle.Top; + result.Right = rectangle.Right; + result.Bottom = rectangle.Bottom; + return result; + } + + public Rectangle ToRectangle() + { + return new Rectangle(Left, Top, Right - Left, Bottom - Top); + } + } + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags); + + [DllImport("user32.dll")] + public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); + + [DllImport("user32.dll")] + public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); + } +} diff --git a/External/Aga.Controls/Tree/Node.cs b/Aga.Controls/Tree/Node.cs similarity index 94% rename from External/Aga.Controls/Tree/Node.cs rename to Aga.Controls/Tree/Node.cs index 1389714..733c089 100644 --- a/External/Aga.Controls/Tree/Node.cs +++ b/Aga.Controls/Tree/Node.cs @@ -1,257 +1,257 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections.ObjectModel; -using System.Windows.Forms; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - public class Node - { - #region NodeCollection - - private class NodeCollection : Collection - { - private Node _owner; - - public NodeCollection(Node owner) - { - _owner = owner; - } - - protected override void ClearItems() - { - while (this.Count != 0) - this.RemoveAt(this.Count - 1); - } - - protected override void InsertItem(int index, Node item) - { - if (item == null) - throw new ArgumentNullException("item"); - - if (item.Parent != _owner) - { - if (item.Parent != null) - item.Parent.Nodes.Remove(item); - item._parent = _owner; - item._index = index; - for (int i = index; i < Count; i++) - this[i]._index++; - base.InsertItem(index, item); - - TreeModel model = _owner.FindModel(); - if (model != null) - model.OnNodeInserted(_owner, index, item); - } - } - - protected override void RemoveItem(int index) - { - Node item = this[index]; - item._parent = null; - item._index = -1; - for (int i = index + 1; i < Count; i++) - this[i]._index--; - base.RemoveItem(index); - - TreeModel model = _owner.FindModel(); - if (model != null) - model.OnNodeRemoved(_owner, index, item); - } - - protected override void SetItem(int index, Node item) - { - if (item == null) - throw new ArgumentNullException("item"); - - RemoveAt(index); - InsertItem(index, item); - } - } - - #endregion - - #region Properties - - private TreeModel _model; - internal TreeModel Model - { - get { return _model; } - set { _model = value; } - } - - private NodeCollection _nodes; - public Collection Nodes - { - get { return _nodes; } - } - - private Node _parent; - public Node Parent - { - get { return _parent; } - set - { - if (value != _parent) - { - if (_parent != null) - _parent.Nodes.Remove(this); - - if (value != null) - value.Nodes.Add(this); - } - } - } - - private int _index = -1; - public int Index - { - get - { - return _index; - } - } - - public Node PreviousNode - { - get - { - int index = Index; - if (index > 0) - return _parent.Nodes[index - 1]; - else - return null; - } - } - - public Node NextNode - { - get - { - int index = Index; - if (index >= 0 && index < _parent.Nodes.Count - 1) - return _parent.Nodes[index + 1]; - else - return null; - } - } - - private string _text; - public virtual string Text - { - get { return _text; } - set - { - if (_text != value) - { - _text = value; - NotifyModel(); - } - } - } - - private CheckState _checkState; - public virtual CheckState CheckState - { - get { return _checkState; } - set - { - if (_checkState != value) - { - _checkState = value; - NotifyModel(); - } - } - } - - private Image _image; - public Image Image - { - get { return _image; } - set - { - if (_image != value) - { - _image = value; - NotifyModel(); - } - } - } - - private object _tag; - public object Tag - { - get { return _tag; } - set { _tag = value; } - } - - public bool IsChecked - { - get - { - return CheckState != CheckState.Unchecked; - } - set - { - if (value) - CheckState = CheckState.Checked; - else - CheckState = CheckState.Unchecked; - } - } - - public virtual bool IsLeaf - { - get - { - return false; - } - } - - #endregion - - public Node() - : this(string.Empty) - { - } - - public Node(string text) - { - _text = text; - _nodes = new NodeCollection(this); - } - - public override string ToString() - { - return Text; - } - - private TreeModel FindModel() - { - Node node = this; - while (node != null) - { - if (node.Model != null) - return node.Model; - node = node.Parent; - } - return null; - } - - protected void NotifyModel() - { - TreeModel model = FindModel(); - if (model != null && Parent != null) - { - TreePath path = model.GetPath(Parent); - if (path != null) - { - TreeModelEventArgs args = new TreeModelEventArgs(path, new int[] { Index }, new object[] { this }); - model.OnNodesChanged(args); - } - } - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; +using System.Windows.Forms; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + public class Node + { + #region NodeCollection + + private class NodeCollection : Collection + { + private Node _owner; + + public NodeCollection(Node owner) + { + _owner = owner; + } + + protected override void ClearItems() + { + while (this.Count != 0) + this.RemoveAt(this.Count - 1); + } + + protected override void InsertItem(int index, Node item) + { + if (item == null) + throw new ArgumentNullException("item"); + + if (item.Parent != _owner) + { + if (item.Parent != null) + item.Parent.Nodes.Remove(item); + item._parent = _owner; + item._index = index; + for (int i = index; i < Count; i++) + this[i]._index++; + base.InsertItem(index, item); + + TreeModel model = _owner.FindModel(); + if (model != null) + model.OnNodeInserted(_owner, index, item); + } + } + + protected override void RemoveItem(int index) + { + Node item = this[index]; + item._parent = null; + item._index = -1; + for (int i = index + 1; i < Count; i++) + this[i]._index--; + base.RemoveItem(index); + + TreeModel model = _owner.FindModel(); + if (model != null) + model.OnNodeRemoved(_owner, index, item); + } + + protected override void SetItem(int index, Node item) + { + if (item == null) + throw new ArgumentNullException("item"); + + RemoveAt(index); + InsertItem(index, item); + } + } + + #endregion + + #region Properties + + private TreeModel _model; + internal TreeModel Model + { + get { return _model; } + set { _model = value; } + } + + private NodeCollection _nodes; + public Collection Nodes + { + get { return _nodes; } + } + + private Node _parent; + public Node Parent + { + get { return _parent; } + set + { + if (value != _parent) + { + if (_parent != null) + _parent.Nodes.Remove(this); + + if (value != null) + value.Nodes.Add(this); + } + } + } + + private int _index = -1; + public int Index + { + get + { + return _index; + } + } + + public Node PreviousNode + { + get + { + int index = Index; + if (index > 0) + return _parent.Nodes[index - 1]; + else + return null; + } + } + + public Node NextNode + { + get + { + int index = Index; + if (index >= 0 && index < _parent.Nodes.Count - 1) + return _parent.Nodes[index + 1]; + else + return null; + } + } + + private string _text; + public virtual string Text + { + get { return _text; } + set + { + if (_text != value) + { + _text = value; + NotifyModel(); + } + } + } + + private CheckState _checkState; + public virtual CheckState CheckState + { + get { return _checkState; } + set + { + if (_checkState != value) + { + _checkState = value; + NotifyModel(); + } + } + } + + private Image _image; + public Image Image + { + get { return _image; } + set + { + if (_image != value) + { + _image = value; + NotifyModel(); + } + } + } + + private object _tag; + public object Tag + { + get { return _tag; } + set { _tag = value; } + } + + public bool IsChecked + { + get + { + return CheckState != CheckState.Unchecked; + } + set + { + if (value) + CheckState = CheckState.Checked; + else + CheckState = CheckState.Unchecked; + } + } + + public virtual bool IsLeaf + { + get + { + return false; + } + } + + #endregion + + public Node() + : this(string.Empty) + { + } + + public Node(string text) + { + _text = text; + _nodes = new NodeCollection(this); + } + + public override string ToString() + { + return Text; + } + + private TreeModel FindModel() + { + Node node = this; + while (node != null) + { + if (node.Model != null) + return node.Model; + node = node.Parent; + } + return null; + } + + protected void NotifyModel() + { + TreeModel model = FindModel(); + if (model != null && Parent != null) + { + TreePath path = model.GetPath(Parent); + if (path != null) + { + TreeModelEventArgs args = new TreeModelEventArgs(path, new int[] { Index }, new object[] { this }); + model.OnNodesChanged(args); + } + } + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControlInfo.cs b/Aga.Controls/Tree/NodeControlInfo.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControlInfo.cs rename to Aga.Controls/Tree/NodeControlInfo.cs index db9d684..c884a26 100644 --- a/External/Aga.Controls/Tree/NodeControlInfo.cs +++ b/Aga.Controls/Tree/NodeControlInfo.cs @@ -1,38 +1,38 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Aga.Controls.Tree.NodeControls; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - public struct NodeControlInfo - { - public static readonly NodeControlInfo Empty = new NodeControlInfo(null, Rectangle.Empty, null); - - private NodeControl _control; - public NodeControl Control - { - get { return _control; } - } - - private Rectangle _bounds; - public Rectangle Bounds - { - get { return _bounds; } - } - - private TreeNodeAdv _node; - public TreeNodeAdv Node - { - get { return _node; } - } - - public NodeControlInfo(NodeControl control, Rectangle bounds, TreeNodeAdv node) - { - _control = control; - _bounds = bounds; - _node = node; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using Aga.Controls.Tree.NodeControls; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + public struct NodeControlInfo + { + public static readonly NodeControlInfo Empty = new NodeControlInfo(null, Rectangle.Empty, null); + + private NodeControl _control; + public NodeControl Control + { + get { return _control; } + } + + private Rectangle _bounds; + public Rectangle Bounds + { + get { return _bounds; } + } + + private TreeNodeAdv _node; + public TreeNodeAdv Node + { + get { return _node; } + } + + public NodeControlInfo(NodeControl control, Rectangle bounds, TreeNodeAdv node) + { + _control = control; + _bounds = bounds; + _node = node; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/BaseTextControl.cs b/Aga.Controls/Tree/NodeControls/BaseTextControl.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/BaseTextControl.cs rename to Aga.Controls/Tree/NodeControls/BaseTextControl.cs index 10b9def..016c7b0 100644 --- a/External/Aga.Controls/Tree/NodeControls/BaseTextControl.cs +++ b/Aga.Controls/Tree/NodeControls/BaseTextControl.cs @@ -1,314 +1,314 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using System.Reflection; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public abstract class BaseTextControl : EditableControl - { - private TextFormatFlags _baseFormatFlags; - private TextFormatFlags _formatFlags; - private Pen _focusPen; - private StringFormat _format; - - #region Properties - - private Font _font = null; - public Font Font - { - get - { - if (_font == null) - return Control.DefaultFont; - else - return _font; - } - set - { - if (value == Control.DefaultFont) - _font = null; - else - _font = value; - } - } - - protected bool ShouldSerializeFont() - { - return (_font != null); - } - - private HorizontalAlignment _textAlign = HorizontalAlignment.Left; - [DefaultValue(HorizontalAlignment.Left)] - public HorizontalAlignment TextAlign - { - get { return _textAlign; } - set - { - _textAlign = value; - SetFormatFlags(); - } - } - - private StringTrimming _trimming = StringTrimming.None; - [DefaultValue(StringTrimming.None)] - public StringTrimming Trimming - { - get { return _trimming; } - set - { - _trimming = value; - SetFormatFlags(); - } - } - - private bool _displayHiddenContentInToolTip = true; - [DefaultValue(true)] - public bool DisplayHiddenContentInToolTip - { - get { return _displayHiddenContentInToolTip; } - set { _displayHiddenContentInToolTip = value; } - } - - private bool _useCompatibleTextRendering = false; - [DefaultValue(false)] - public bool UseCompatibleTextRendering - { - get { return _useCompatibleTextRendering; } - set { _useCompatibleTextRendering = value; } - } - - [DefaultValue(false)] - public bool TrimMultiLine - { - get; - set; - } - - #endregion - - protected BaseTextControl() - { - IncrementalSearchEnabled = true; - _focusPen = new Pen(Color.Black); - _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; - - _format = new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces); - _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | - TextFormatFlags.PreserveGraphicsTranslateTransform; - SetFormatFlags(); - LeftMargin = 3; - } - - private void SetFormatFlags() - { - _format.Alignment = TextHelper.TranslateAligment(TextAlign); - _format.Trimming = Trimming; - - _formatFlags = _baseFormatFlags | TextHelper.TranslateAligmentToFlag(TextAlign) - | TextHelper.TranslateTrimmingToFlag(Trimming); - } - - public override Size MeasureSize(TreeNodeAdv node, DrawContext context) - { - return GetLabelSize(node, context); - } - - protected Size GetLabelSize(TreeNodeAdv node, DrawContext context) - { - return GetLabelSize(node, context, GetLabel(node)); - } - - protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label) - { - PerformanceAnalyzer.Start("GetLabelSize"); - CheckThread(); - Font font = GetDrawingFont(node, context, label); - Size s = Size.Empty; - if (UseCompatibleTextRendering) - s = TextRenderer.MeasureText(label, font); - else - { - SizeF sf = context.Graphics.MeasureString(label, font); - s = new Size((int)Math.Ceiling(sf.Width), (int)Math.Ceiling(sf.Height)); - } - PerformanceAnalyzer.Finish("GetLabelSize"); - - if (!s.IsEmpty) - return s; - else - return new Size(10, Font.Height); - } - - protected Font GetDrawingFont(TreeNodeAdv node, DrawContext context, string label) - { - Font font = context.Font; - if (DrawTextMustBeFired(node)) - { - DrawEventArgs args = new DrawEventArgs(node, this, context, label); - args.Font = context.Font; - OnDrawText(args); - font = args.Font; - } - return font; - } - - protected void SetEditControlProperties(Control control, TreeNodeAdv node) - { - string label = GetLabel(node); - DrawContext context = new DrawContext(); - context.Font = control.Font; - control.Font = GetDrawingFont(node, context, label); - } - - public override void Draw(TreeNodeAdv node, DrawContext context) - { - if (context.CurrentEditorOwner == this && node == Parent.CurrentNode) - return; - - PerformanceAnalyzer.Start("BaseTextControl.Draw"); - string label = GetLabel(node); - Rectangle bounds = GetBounds(node, context); - Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y, - bounds.Width, context.Bounds.Height); - - Brush backgroundBrush; - Color textColor; - Font font; - CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label); - - if (backgroundBrush != null) - context.Graphics.FillRectangle(backgroundBrush, focusRect); - if (context.DrawFocus) - { - focusRect.Width--; - focusRect.Height--; - if (context.DrawSelection == DrawSelectionMode.None) - _focusPen.Color = SystemColors.ControlText; - else - _focusPen.Color = SystemColors.InactiveCaption; - context.Graphics.DrawRectangle(_focusPen, focusRect); - } - - PerformanceAnalyzer.Start("BaseTextControl.DrawText"); - if (UseCompatibleTextRendering) - TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags); - else - context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format); - PerformanceAnalyzer.Finish("BaseTextControl.DrawText"); - - PerformanceAnalyzer.Finish("BaseTextControl.Draw"); - } - - private static Dictionary _brushes = new Dictionary(); - private static Brush GetFrush(Color color) - { - Brush br; - if (_brushes.ContainsKey(color)) - br = _brushes[color]; - else - { - br = new SolidBrush(color); - _brushes.Add(color, br); - } - return br; - } - - private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label) - { - textColor = SystemColors.ControlText; - backgroundBrush = null; - font = context.Font; - if (context.DrawSelection == DrawSelectionMode.Active) - { - textColor = SystemColors.HighlightText; - backgroundBrush = SystemBrushes.Highlight; - } - else if (context.DrawSelection == DrawSelectionMode.Inactive) - { - textColor = SystemColors.ControlText; - backgroundBrush = SystemBrushes.InactiveBorder; - } - else if (context.DrawSelection == DrawSelectionMode.FullRowSelect) - textColor = SystemColors.ControlText; - - if (!context.Enabled) - textColor = SystemColors.GrayText; - - if (DrawTextMustBeFired(node)) - { - DrawEventArgs args = new DrawEventArgs(node, this, context, text); - args.Text = label; - args.TextColor = textColor; - args.BackgroundBrush = backgroundBrush; - args.Font = font; - - OnDrawText(args); - - textColor = args.TextColor; - backgroundBrush = args.BackgroundBrush; - font = args.Font; - label = args.Text; - } - } - - public string GetLabel(TreeNodeAdv node) - { - if (node != null && node.Tag != null) - { - object obj = GetValue(node); - if (obj != null) - return FormatLabel(obj); - } - return string.Empty; - } - - protected virtual string FormatLabel(object obj) - { - var res = obj.ToString(); - if (TrimMultiLine && res != null) - { - string[] parts = res.Split('\n'); - if (parts.Length > 1) - return parts[0] + "..."; - } - return res; - } - - public void SetLabel(TreeNodeAdv node, string value) - { - SetValue(node, value); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (disposing) - { - _focusPen.Dispose(); - _format.Dispose(); - } - } - - /// - /// Fires when control is going to draw a text. Can be used to change text or back color - /// - public event EventHandler DrawText; - protected virtual void OnDrawText(DrawEventArgs args) - { - TreeViewAdv tree = args.Node.Tree; - if (tree != null) - tree.FireDrawControl(args); - if (DrawText != null) - DrawText(this, args); - } - - protected virtual bool DrawTextMustBeFired(TreeNodeAdv node) - { - return DrawText != null || (node.Tree != null && node.Tree.DrawControlMustBeFired()); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Reflection; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public abstract class BaseTextControl : EditableControl + { + private TextFormatFlags _baseFormatFlags; + private TextFormatFlags _formatFlags; + private Pen _focusPen; + private StringFormat _format; + + #region Properties + + private Font _font = null; + public Font Font + { + get + { + if (_font == null) + return Control.DefaultFont; + else + return _font; + } + set + { + if (value == Control.DefaultFont) + _font = null; + else + _font = value; + } + } + + protected bool ShouldSerializeFont() + { + return (_font != null); + } + + private HorizontalAlignment _textAlign = HorizontalAlignment.Left; + [DefaultValue(HorizontalAlignment.Left)] + public HorizontalAlignment TextAlign + { + get { return _textAlign; } + set + { + _textAlign = value; + SetFormatFlags(); + } + } + + private StringTrimming _trimming = StringTrimming.None; + [DefaultValue(StringTrimming.None)] + public StringTrimming Trimming + { + get { return _trimming; } + set + { + _trimming = value; + SetFormatFlags(); + } + } + + private bool _displayHiddenContentInToolTip = true; + [DefaultValue(true)] + public bool DisplayHiddenContentInToolTip + { + get { return _displayHiddenContentInToolTip; } + set { _displayHiddenContentInToolTip = value; } + } + + private bool _useCompatibleTextRendering = false; + [DefaultValue(false)] + public bool UseCompatibleTextRendering + { + get { return _useCompatibleTextRendering; } + set { _useCompatibleTextRendering = value; } + } + + [DefaultValue(false)] + public bool TrimMultiLine + { + get; + set; + } + + #endregion + + protected BaseTextControl() + { + IncrementalSearchEnabled = true; + _focusPen = new Pen(Color.Black); + _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; + + _format = new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces); + _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | + TextFormatFlags.PreserveGraphicsTranslateTransform; + SetFormatFlags(); + LeftMargin = 3; + } + + private void SetFormatFlags() + { + _format.Alignment = TextHelper.TranslateAligment(TextAlign); + _format.Trimming = Trimming; + + _formatFlags = _baseFormatFlags | TextHelper.TranslateAligmentToFlag(TextAlign) + | TextHelper.TranslateTrimmingToFlag(Trimming); + } + + public override Size MeasureSize(TreeNodeAdv node, DrawContext context) + { + return GetLabelSize(node, context); + } + + protected Size GetLabelSize(TreeNodeAdv node, DrawContext context) + { + return GetLabelSize(node, context, GetLabel(node)); + } + + protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label) + { + PerformanceAnalyzer.Start("GetLabelSize"); + CheckThread(); + Font font = GetDrawingFont(node, context, label); + Size s = Size.Empty; + if (UseCompatibleTextRendering) + s = TextRenderer.MeasureText(label, font); + else + { + SizeF sf = context.Graphics.MeasureString(label, font); + s = new Size((int)Math.Ceiling(sf.Width), (int)Math.Ceiling(sf.Height)); + } + PerformanceAnalyzer.Finish("GetLabelSize"); + + if (!s.IsEmpty) + return s; + else + return new Size(10, Font.Height); + } + + protected Font GetDrawingFont(TreeNodeAdv node, DrawContext context, string label) + { + Font font = context.Font; + if (DrawTextMustBeFired(node)) + { + DrawEventArgs args = new DrawEventArgs(node, this, context, label); + args.Font = context.Font; + OnDrawText(args); + font = args.Font; + } + return font; + } + + protected void SetEditControlProperties(Control control, TreeNodeAdv node) + { + string label = GetLabel(node); + DrawContext context = new DrawContext(); + context.Font = control.Font; + control.Font = GetDrawingFont(node, context, label); + } + + public override void Draw(TreeNodeAdv node, DrawContext context) + { + if (context.CurrentEditorOwner == this && node == Parent.CurrentNode) + return; + + PerformanceAnalyzer.Start("BaseTextControl.Draw"); + string label = GetLabel(node); + Rectangle bounds = GetBounds(node, context); + Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y, + bounds.Width, context.Bounds.Height); + + Brush backgroundBrush; + Color textColor; + Font font; + CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label); + + if (backgroundBrush != null) + context.Graphics.FillRectangle(backgroundBrush, focusRect); + if (context.DrawFocus) + { + focusRect.Width--; + focusRect.Height--; + if (context.DrawSelection == DrawSelectionMode.None) + _focusPen.Color = SystemColors.ControlText; + else + _focusPen.Color = SystemColors.InactiveCaption; + context.Graphics.DrawRectangle(_focusPen, focusRect); + } + + PerformanceAnalyzer.Start("BaseTextControl.DrawText"); + if (UseCompatibleTextRendering) + TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags); + else + context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format); + PerformanceAnalyzer.Finish("BaseTextControl.DrawText"); + + PerformanceAnalyzer.Finish("BaseTextControl.Draw"); + } + + private static Dictionary _brushes = new Dictionary(); + private static Brush GetFrush(Color color) + { + Brush br; + if (_brushes.ContainsKey(color)) + br = _brushes[color]; + else + { + br = new SolidBrush(color); + _brushes.Add(color, br); + } + return br; + } + + private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label) + { + textColor = SystemColors.ControlText; + backgroundBrush = null; + font = context.Font; + if (context.DrawSelection == DrawSelectionMode.Active) + { + textColor = SystemColors.HighlightText; + backgroundBrush = SystemBrushes.Highlight; + } + else if (context.DrawSelection == DrawSelectionMode.Inactive) + { + textColor = SystemColors.ControlText; + backgroundBrush = SystemBrushes.InactiveBorder; + } + else if (context.DrawSelection == DrawSelectionMode.FullRowSelect) + textColor = SystemColors.ControlText; + + if (!context.Enabled) + textColor = SystemColors.GrayText; + + if (DrawTextMustBeFired(node)) + { + DrawEventArgs args = new DrawEventArgs(node, this, context, text); + args.Text = label; + args.TextColor = textColor; + args.BackgroundBrush = backgroundBrush; + args.Font = font; + + OnDrawText(args); + + textColor = args.TextColor; + backgroundBrush = args.BackgroundBrush; + font = args.Font; + label = args.Text; + } + } + + public string GetLabel(TreeNodeAdv node) + { + if (node != null && node.Tag != null) + { + object obj = GetValue(node); + if (obj != null) + return FormatLabel(obj); + } + return string.Empty; + } + + protected virtual string FormatLabel(object obj) + { + var res = obj.ToString(); + if (TrimMultiLine && res != null) + { + string[] parts = res.Split('\n'); + if (parts.Length > 1) + return parts[0] + "..."; + } + return res; + } + + public void SetLabel(TreeNodeAdv node, string value) + { + SetValue(node, value); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + _focusPen.Dispose(); + _format.Dispose(); + } + } + + /// + /// Fires when control is going to draw a text. Can be used to change text or back color + /// + public event EventHandler DrawText; + protected virtual void OnDrawText(DrawEventArgs args) + { + TreeViewAdv tree = args.Node.Tree; + if (tree != null) + tree.FireDrawControl(args); + if (DrawText != null) + DrawText(this, args); + } + + protected virtual bool DrawTextMustBeFired(TreeNodeAdv node) + { + return DrawText != null || (node.Tree != null && node.Tree.DrawControlMustBeFired()); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/BindableControl.cs b/Aga.Controls/Tree/NodeControls/BindableControl.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/BindableControl.cs rename to Aga.Controls/Tree/NodeControls/BindableControl.cs index 5ce2c1e..673d8fc 100644 --- a/External/Aga.Controls/Tree/NodeControls/BindableControl.cs +++ b/Aga.Controls/Tree/NodeControls/BindableControl.cs @@ -1,194 +1,194 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Reflection; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public abstract class BindableControl : NodeControl - { - private struct MemberAdapter - { - private object _obj; - private PropertyInfo _pi; - private FieldInfo _fi; - - public static readonly MemberAdapter Empty = new MemberAdapter(); - - public Type MemberType - { - get - { - if (_pi != null) - return _pi.PropertyType; - else if (_fi != null) - return _fi.FieldType; - else - return null; - } - } - - public object Value - { - get - { - if (_pi != null && _pi.CanRead) - return _pi.GetValue(_obj, null); - else if (_fi != null) - return _fi.GetValue(_obj); - else - return null; - } - set - { - if (_pi != null && _pi.CanWrite) - _pi.SetValue(_obj, value, null); - else if (_fi != null) - _fi.SetValue(_obj, value); - } - } - - public MemberAdapter(object obj, PropertyInfo pi) - { - _obj = obj; - _pi = pi; - _fi = null; - } - - public MemberAdapter(object obj, FieldInfo fi) - { - _obj = obj; - _fi = fi; - _pi = null; - } - } - - #region Properties - - private bool _virtualMode = false; - [DefaultValue(false), Category("Data")] - public bool VirtualMode - { - get { return _virtualMode; } - set { _virtualMode = value; } - } - - private string _propertyName = ""; - [DefaultValue(""), Category("Data")] - public string DataPropertyName - { - get { return _propertyName; } - set - { - if (_propertyName == null) - _propertyName = string.Empty; - _propertyName = value; - } - } - - private bool _incrementalSearchEnabled = false; - [DefaultValue(false)] - public bool IncrementalSearchEnabled - { - get { return _incrementalSearchEnabled; } - set { _incrementalSearchEnabled = value; } - } - - #endregion - - public virtual object GetValue(TreeNodeAdv node) - { - if (VirtualMode) - { - NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); - OnValueNeeded(args); - return args.Value; - } - else - { - try - { - return GetMemberAdapter(node).Value; - } - catch (TargetInvocationException ex) - { - if (ex.InnerException != null) - throw new ArgumentException(ex.InnerException.Message, ex.InnerException); - else - throw new ArgumentException(ex.Message); - } - } - } - - public virtual void SetValue(TreeNodeAdv node, object value) - { - if (VirtualMode) - { - NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); - args.Value = value; - OnValuePushed(args); - } - else - { - try - { - MemberAdapter ma = GetMemberAdapter(node); - ma.Value = value; - } - catch (TargetInvocationException ex) - { - if (ex.InnerException != null) - throw new ArgumentException(ex.InnerException.Message, ex.InnerException); - else - throw new ArgumentException(ex.Message); - } - } - } - - public Type GetPropertyType(TreeNodeAdv node) - { - return GetMemberAdapter(node).MemberType; - } - - private MemberAdapter GetMemberAdapter(TreeNodeAdv node) - { - if (node.Tag != null && !string.IsNullOrEmpty(DataPropertyName)) - { - Type type = node.Tag.GetType(); - PropertyInfo pi = type.GetProperty(DataPropertyName); - if (pi != null) - return new MemberAdapter(node.Tag, pi); - else - { - FieldInfo fi = type.GetField(DataPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (fi != null) - return new MemberAdapter(node.Tag, fi); - } - } - return MemberAdapter.Empty; - } - - public override string ToString() - { - if (string.IsNullOrEmpty(DataPropertyName)) - return GetType().Name; - else - return string.Format("{0} ({1})", GetType().Name, DataPropertyName); - } - - public event EventHandler ValueNeeded; - private void OnValueNeeded(NodeControlValueEventArgs args) - { - if (ValueNeeded != null) - ValueNeeded(this, args); - } - - public event EventHandler ValuePushed; - private void OnValuePushed(NodeControlValueEventArgs args) - { - if (ValuePushed != null) - ValuePushed(this, args); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public abstract class BindableControl : NodeControl + { + private struct MemberAdapter + { + private object _obj; + private PropertyInfo _pi; + private FieldInfo _fi; + + public static readonly MemberAdapter Empty = new MemberAdapter(); + + public Type MemberType + { + get + { + if (_pi != null) + return _pi.PropertyType; + else if (_fi != null) + return _fi.FieldType; + else + return null; + } + } + + public object Value + { + get + { + if (_pi != null && _pi.CanRead) + return _pi.GetValue(_obj, null); + else if (_fi != null) + return _fi.GetValue(_obj); + else + return null; + } + set + { + if (_pi != null && _pi.CanWrite) + _pi.SetValue(_obj, value, null); + else if (_fi != null) + _fi.SetValue(_obj, value); + } + } + + public MemberAdapter(object obj, PropertyInfo pi) + { + _obj = obj; + _pi = pi; + _fi = null; + } + + public MemberAdapter(object obj, FieldInfo fi) + { + _obj = obj; + _fi = fi; + _pi = null; + } + } + + #region Properties + + private bool _virtualMode = false; + [DefaultValue(false), Category("Data")] + public bool VirtualMode + { + get { return _virtualMode; } + set { _virtualMode = value; } + } + + private string _propertyName = ""; + [DefaultValue(""), Category("Data")] + public string DataPropertyName + { + get { return _propertyName; } + set + { + if (_propertyName == null) + _propertyName = string.Empty; + _propertyName = value; + } + } + + private bool _incrementalSearchEnabled = false; + [DefaultValue(false)] + public bool IncrementalSearchEnabled + { + get { return _incrementalSearchEnabled; } + set { _incrementalSearchEnabled = value; } + } + + #endregion + + public virtual object GetValue(TreeNodeAdv node) + { + if (VirtualMode) + { + NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); + OnValueNeeded(args); + return args.Value; + } + else + { + try + { + return GetMemberAdapter(node).Value; + } + catch (TargetInvocationException ex) + { + if (ex.InnerException != null) + throw new ArgumentException(ex.InnerException.Message, ex.InnerException); + else + throw new ArgumentException(ex.Message); + } + } + } + + public virtual void SetValue(TreeNodeAdv node, object value) + { + if (VirtualMode) + { + NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); + args.Value = value; + OnValuePushed(args); + } + else + { + try + { + MemberAdapter ma = GetMemberAdapter(node); + ma.Value = value; + } + catch (TargetInvocationException ex) + { + if (ex.InnerException != null) + throw new ArgumentException(ex.InnerException.Message, ex.InnerException); + else + throw new ArgumentException(ex.Message); + } + } + } + + public Type GetPropertyType(TreeNodeAdv node) + { + return GetMemberAdapter(node).MemberType; + } + + private MemberAdapter GetMemberAdapter(TreeNodeAdv node) + { + if (node.Tag != null && !string.IsNullOrEmpty(DataPropertyName)) + { + Type type = node.Tag.GetType(); + PropertyInfo pi = type.GetProperty(DataPropertyName); + if (pi != null) + return new MemberAdapter(node.Tag, pi); + else + { + FieldInfo fi = type.GetField(DataPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (fi != null) + return new MemberAdapter(node.Tag, fi); + } + } + return MemberAdapter.Empty; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(DataPropertyName)) + return GetType().Name; + else + return string.Format("{0} ({1})", GetType().Name, DataPropertyName); + } + + public event EventHandler ValueNeeded; + private void OnValueNeeded(NodeControlValueEventArgs args) + { + if (ValueNeeded != null) + ValueNeeded(this, args); + } + + public event EventHandler ValuePushed; + private void OnValuePushed(NodeControlValueEventArgs args) + { + if (ValuePushed != null) + ValuePushed(this, args); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/ClassDiagram.cd b/Aga.Controls/Tree/NodeControls/ClassDiagram.cd similarity index 97% rename from External/Aga.Controls/Tree/NodeControls/ClassDiagram.cd rename to Aga.Controls/Tree/NodeControls/ClassDiagram.cd index 437ad6d..733d539 100644 --- a/External/Aga.Controls/Tree/NodeControls/ClassDiagram.cd +++ b/Aga.Controls/Tree/NodeControls/ClassDiagram.cd @@ -1,105 +1,105 @@ - - - - - - - Tree\NodeControls\NodeStateIcon.cs - ABAAAAAAAAQAQAAAAAAAAAAAAAAAAAAAQIAAAAAAAAA= - - - - - - Tree\NodeControls\BindableControl.cs - FAAAAAAQIBAQCgAEAAAAIAAAAAAAAAEMAAACAAAAAAE= - - - - - - Tree\NodeControls\NodeCheckBox.cs - AAEAAAAAAAACgkQCAAAAAAigAgAAEGABAAAIAAAAAAA= - - - - - - Tree\NodeControls\NodeControl.cs - AAAAAJAAgIgBkkoQAAgAQAAwAAABEIQAAEBIAAAAAAA= - - - - - - - - - Tree\NodeControls\NodeIcon.cs - ABAAAAAAAAAAAgAAAAAAAAAgAAAAAAAAAAAAAAAAAAA= - - - - - - Tree\NodeControls\NodePlusMinus.cs - AAAAAAAAAAAAAgAAAAAAAEAgAAAAMCAAAAAIACAAAAA= - - - - - - Tree\NodeControls\BaseTextControl.cs - AAAAICBQACAAIgACBCAEAQA8AgmFoAAwAAAAACACAMA= - - - - - - Tree\NodeControls\NodeTextBox.cs - QQQAhAAAADAMgAAAABAAAAAAAgEAIAAAAAAAAIAAAAA= - - - - - - Tree\NodeControls\EditableControl.cs - QQAgAAAACGgkAMAABAEEkADAEAAUEAAABAGoAAAAAQA= - - - - - - Tree\NodeControls\NodeComboBox.cs - wQACAAAAAAAMAEBAAAAAAABAAAAAAAABAAAAAAAAAAA= - - - - - - Tree\NodeControls\NodeNumericUpDown.cs - wQAAAACAAAAEAABAIAAQIAAAAAAAAAABAAAIAAAAAII= - - - - - - Tree\NodeControls\InteractiveControl.cs - AAAABAAAAAAAAAAACAAAAAAAABAAAQAAAAAAAAIAAAA= - - - - - - Tree\NodeControls\NodeDecimalTextBox.cs - AQAAAAAAAACAAAACAAAAAAQAAAAAIAAAAAgAAAAAAAA= - - - - - - Tree\NodeControls\NodeIntegerTextBox.cs - AQAAAAAAAAAAAAACAAAAAAQAAAAAIAAAAAAAAAAAAAA= - - + + + + + + + Tree\NodeControls\NodeStateIcon.cs + ABAAAAAAAAQAQAAAAAAAAAAAAAAAAAAAQIAAAAAAAAA= + + + + + + Tree\NodeControls\BindableControl.cs + FAAAAAAQIBAQCgAEAAAAIAAAAAAAAAEMAAACAAAAAAE= + + + + + + Tree\NodeControls\NodeCheckBox.cs + AAEAAAAAAAACgkQCAAAAAAigAgAAEGABAAAIAAAAAAA= + + + + + + Tree\NodeControls\NodeControl.cs + AAAAAJAAgIgBkkoQAAgAQAAwAAABEIQAAEBIAAAAAAA= + + + + + + + + + Tree\NodeControls\NodeIcon.cs + ABAAAAAAAAAAAgAAAAAAAAAgAAAAAAAAAAAAAAAAAAA= + + + + + + Tree\NodeControls\NodePlusMinus.cs + AAAAAAAAAAAAAgAAAAAAAEAgAAAAMCAAAAAIACAAAAA= + + + + + + Tree\NodeControls\BaseTextControl.cs + AAAAICBQACAAIgACBCAEAQA8AgmFoAAwAAAAACACAMA= + + + + + + Tree\NodeControls\NodeTextBox.cs + QQQAhAAAADAMgAAAABAAAAAAAgEAIAAAAAAAAIAAAAA= + + + + + + Tree\NodeControls\EditableControl.cs + QQAgAAAACGgkAMAABAEEkADAEAAUEAAABAGoAAAAAQA= + + + + + + Tree\NodeControls\NodeComboBox.cs + wQACAAAAAAAMAEBAAAAAAABAAAAAAAABAAAAAAAAAAA= + + + + + + Tree\NodeControls\NodeNumericUpDown.cs + wQAAAACAAAAEAABAIAAQIAAAAAAAAAABAAAIAAAAAII= + + + + + + Tree\NodeControls\InteractiveControl.cs + AAAABAAAAAAAAAAACAAAAAAAABAAAQAAAAAAAAIAAAA= + + + + + + Tree\NodeControls\NodeDecimalTextBox.cs + AQAAAAAAAACAAAACAAAAAAQAAAAAIAAAAAgAAAAAAAA= + + + + + + Tree\NodeControls\NodeIntegerTextBox.cs + AQAAAAAAAAAAAAACAAAAAAQAAAAAIAAAAAAAAAAAAAA= + + \ No newline at end of file diff --git a/External/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs b/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs rename to Aga.Controls/Tree/NodeControls/DrawEventArgs.cs index c24779b..8333c1f 100644 --- a/External/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs +++ b/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs @@ -1,67 +1,67 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -namespace Aga.Controls.Tree.NodeControls -{ - public class DrawEventArgs : NodeEventArgs - { - private DrawContext _context; - public DrawContext Context - { - get { return _context; } - } - - private Brush _textBrush; - [Obsolete("Use TextColor")] - public Brush TextBrush - { - get { return _textBrush; } - set { _textBrush = value; } - } - - private Brush _backgroundBrush; - public Brush BackgroundBrush - { - get { return _backgroundBrush; } - set { _backgroundBrush = value; } - } - - private Font _font; - public Font Font - { - get { return _font; } - set { _font = value; } - } - - private Color _textColor; - public Color TextColor - { - get { return _textColor; } - set { _textColor = value; } - } - - private string _text; - public string Text - { - get { return _text; } - set { _text = value; } - } - - - private EditableControl _control; - public EditableControl Control - { - get { return _control; } - } - - public DrawEventArgs(TreeNodeAdv node, EditableControl control, DrawContext context, string text) - : base(node) - { - _control = control; - _context = context; - _text = text; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; + +namespace Aga.Controls.Tree.NodeControls +{ + public class DrawEventArgs : NodeEventArgs + { + private DrawContext _context; + public DrawContext Context + { + get { return _context; } + } + + private Brush _textBrush; + [Obsolete("Use TextColor")] + public Brush TextBrush + { + get { return _textBrush; } + set { _textBrush = value; } + } + + private Brush _backgroundBrush; + public Brush BackgroundBrush + { + get { return _backgroundBrush; } + set { _backgroundBrush = value; } + } + + private Font _font; + public Font Font + { + get { return _font; } + set { _font = value; } + } + + private Color _textColor; + public Color TextColor + { + get { return _textColor; } + set { _textColor = value; } + } + + private string _text; + public string Text + { + get { return _text; } + set { _text = value; } + } + + + private EditableControl _control; + public EditableControl Control + { + get { return _control; } + } + + public DrawEventArgs(TreeNodeAdv node, EditableControl control, DrawContext context, string text) + : base(node) + { + _control = control; + _context = context; + _text = text; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/EditEventArgs.cs b/Aga.Controls/Tree/NodeControls/EditEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/EditEventArgs.cs rename to Aga.Controls/Tree/NodeControls/EditEventArgs.cs index f9bc55a..d26033b 100644 --- a/External/Aga.Controls/Tree/NodeControls/EditEventArgs.cs +++ b/Aga.Controls/Tree/NodeControls/EditEventArgs.cs @@ -1,22 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; - -namespace Aga.Controls.Tree.NodeControls -{ - public class EditEventArgs : NodeEventArgs - { - private Control _control; - public Control Control - { - get { return _control; } - } - - public EditEventArgs(TreeNodeAdv node, Control control) - : base(node) - { - _control = control; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; + +namespace Aga.Controls.Tree.NodeControls +{ + public class EditEventArgs : NodeEventArgs + { + private Control _control; + public Control Control + { + get { return _control; } + } + + public EditEventArgs(TreeNodeAdv node, Control control) + : base(node) + { + _control = control; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/EditableControl.cs b/Aga.Controls/Tree/NodeControls/EditableControl.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/EditableControl.cs rename to Aga.Controls/Tree/NodeControls/EditableControl.cs index 99d4ea6..ec2a9d9 100644 --- a/External/Aga.Controls/Tree/NodeControls/EditableControl.cs +++ b/Aga.Controls/Tree/NodeControls/EditableControl.cs @@ -1,175 +1,175 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public abstract class EditableControl : InteractiveControl - { - private Timer _timer; - private bool _editFlag; - - #region Properties - - private bool _editOnClick = false; - [DefaultValue(false)] - public bool EditOnClick - { - get { return _editOnClick; } - set { _editOnClick = value; } - } - - #endregion - - protected EditableControl() - { - _timer = new Timer(); - _timer.Interval = 500; - _timer.Tick += new EventHandler(TimerTick); - } - - private void TimerTick(object sender, EventArgs e) - { - _timer.Stop(); - if (_editFlag) - BeginEdit(); - _editFlag = false; - } - - public void SetEditorBounds(EditorContext context) - { - Size size = CalculateEditorSize(context); - context.Editor.Bounds = new Rectangle(context.Bounds.X, context.Bounds.Y, - Math.Min(size.Width, context.Bounds.Width), - Math.Min(size.Height, Parent.ClientSize.Height - context.Bounds.Y) - ); - } - - protected abstract Size CalculateEditorSize(EditorContext context); - - protected virtual bool CanEdit(TreeNodeAdv node) - { - return (node.Tag != null) && IsEditEnabled(node); - } - - public void BeginEdit() - { - if (Parent != null && Parent.CurrentNode != null && CanEdit(Parent.CurrentNode)) - { - CancelEventArgs args = new CancelEventArgs(); - OnEditorShowing(args); - if (!args.Cancel) - { - var editor = CreateEditor(Parent.CurrentNode); - Parent.DisplayEditor(editor, this); - } - } - } - - public void EndEdit(bool applyChanges) - { - if (Parent != null) - if (Parent.HideEditor(applyChanges)) - OnEditorHided(); - } - - public virtual void UpdateEditor(Control control) - { - } - - internal void ApplyChanges(TreeNodeAdv node, Control editor) - { - DoApplyChanges(node, editor); - OnChangesApplied(); - } - - internal void DoDisposeEditor(Control editor) - { - DisposeEditor(editor); - } - - protected abstract void DoApplyChanges(TreeNodeAdv node, Control editor); - - protected abstract Control CreateEditor(TreeNodeAdv node); - - protected abstract void DisposeEditor(Control editor); - - public virtual void Cut(Control control) - { - } - - public virtual void Copy(Control control) - { - } - - public virtual void Paste(Control control) - { - } - - public virtual void Delete(Control control) - { - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - _editFlag = (!EditOnClick && args.Button == MouseButtons.Left - && args.ModifierKeys == Keys.None && args.Node.IsSelected); - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - if (args.Node.IsSelected) - { - if (EditOnClick && args.Button == MouseButtons.Left && args.ModifierKeys == Keys.None) - { - Parent.ItemDragMode = false; - BeginEdit(); - args.Handled = true; - } - else if (_editFlag)// && args.Node.IsSelected) - _timer.Start(); - } - } - - public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - _editFlag = false; - _timer.Stop(); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (disposing) - _timer.Dispose(); - } - - #region Events - - public event CancelEventHandler EditorShowing; - protected void OnEditorShowing(CancelEventArgs args) - { - if (EditorShowing != null) - EditorShowing(this, args); - } - - public event EventHandler EditorHided; - protected void OnEditorHided() - { - if (EditorHided != null) - EditorHided(this, EventArgs.Empty); - } - - public event EventHandler ChangesApplied; - protected void OnChangesApplied() - { - if (ChangesApplied != null) - ChangesApplied(this, EventArgs.Empty); - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public abstract class EditableControl : InteractiveControl + { + private Timer _timer; + private bool _editFlag; + + #region Properties + + private bool _editOnClick = false; + [DefaultValue(false)] + public bool EditOnClick + { + get { return _editOnClick; } + set { _editOnClick = value; } + } + + #endregion + + protected EditableControl() + { + _timer = new Timer(); + _timer.Interval = 500; + _timer.Tick += new EventHandler(TimerTick); + } + + private void TimerTick(object sender, EventArgs e) + { + _timer.Stop(); + if (_editFlag) + BeginEdit(); + _editFlag = false; + } + + public void SetEditorBounds(EditorContext context) + { + Size size = CalculateEditorSize(context); + context.Editor.Bounds = new Rectangle(context.Bounds.X, context.Bounds.Y, + Math.Min(size.Width, context.Bounds.Width), + Math.Min(size.Height, Parent.ClientSize.Height - context.Bounds.Y) + ); + } + + protected abstract Size CalculateEditorSize(EditorContext context); + + protected virtual bool CanEdit(TreeNodeAdv node) + { + return (node.Tag != null) && IsEditEnabled(node); + } + + public void BeginEdit() + { + if (Parent != null && Parent.CurrentNode != null && CanEdit(Parent.CurrentNode)) + { + CancelEventArgs args = new CancelEventArgs(); + OnEditorShowing(args); + if (!args.Cancel) + { + var editor = CreateEditor(Parent.CurrentNode); + Parent.DisplayEditor(editor, this); + } + } + } + + public void EndEdit(bool applyChanges) + { + if (Parent != null) + if (Parent.HideEditor(applyChanges)) + OnEditorHided(); + } + + public virtual void UpdateEditor(Control control) + { + } + + internal void ApplyChanges(TreeNodeAdv node, Control editor) + { + DoApplyChanges(node, editor); + OnChangesApplied(); + } + + internal void DoDisposeEditor(Control editor) + { + DisposeEditor(editor); + } + + protected abstract void DoApplyChanges(TreeNodeAdv node, Control editor); + + protected abstract Control CreateEditor(TreeNodeAdv node); + + protected abstract void DisposeEditor(Control editor); + + public virtual void Cut(Control control) + { + } + + public virtual void Copy(Control control) + { + } + + public virtual void Paste(Control control) + { + } + + public virtual void Delete(Control control) + { + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + _editFlag = (!EditOnClick && args.Button == MouseButtons.Left + && args.ModifierKeys == Keys.None && args.Node.IsSelected); + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + if (args.Node.IsSelected) + { + if (EditOnClick && args.Button == MouseButtons.Left && args.ModifierKeys == Keys.None) + { + Parent.ItemDragMode = false; + BeginEdit(); + args.Handled = true; + } + else if (_editFlag)// && args.Node.IsSelected) + _timer.Start(); + } + } + + public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + _editFlag = false; + _timer.Stop(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + _timer.Dispose(); + } + + #region Events + + public event CancelEventHandler EditorShowing; + protected void OnEditorShowing(CancelEventArgs args) + { + if (EditorShowing != null) + EditorShowing(this, args); + } + + public event EventHandler EditorHided; + protected void OnEditorHided() + { + if (EditorHided != null) + EditorHided(this, EventArgs.Empty); + } + + public event EventHandler ChangesApplied; + protected void OnChangesApplied() + { + if (ChangesApplied != null) + ChangesApplied(this, EventArgs.Empty); + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs b/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs rename to Aga.Controls/Tree/NodeControls/ExpandingIcon.cs index 513586f..bd2c34c 100644 --- a/External/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs +++ b/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs @@ -1,83 +1,83 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Threading; -using System.Windows.Forms; - -namespace Aga.Controls.Tree.NodeControls -{ - /// - /// Displays an animated icon for those nodes, who are in expanding state. - /// Parent TreeView must have AsyncExpanding property set to true. - /// - public class ExpandingIcon: NodeControl - { - private static GifDecoder _gif = ResourceHelper.LoadingIcon; - private static int _index = 0; - private static volatile Thread _animatingThread; - private static object _lock = new object(); - - public override Size MeasureSize(TreeNodeAdv node, DrawContext context) - { - return ResourceHelper.LoadingIcon.FrameSize; - } - - protected override void OnIsVisibleValueNeeded(NodeControlValueEventArgs args) - { - args.Value = args.Node.IsExpandingNow; - base.OnIsVisibleValueNeeded(args); - } - - public override void Draw(TreeNodeAdv node, DrawContext context) - { - Rectangle rect = GetBounds(node, context); - Image img = _gif.GetFrame(_index).Image; - context.Graphics.DrawImage(img, rect.Location); - } - - public static void Start() - { - lock (_lock) - { - if (_animatingThread == null) - { - _index = 0; - _animatingThread = new Thread(new ThreadStart(IterateIcons)); - _animatingThread.IsBackground = true; - _animatingThread.Priority = ThreadPriority.Lowest; - _animatingThread.Start(); - } - } - } - - public static void Stop() - { - lock (_lock) - { - _index = 0; - _animatingThread = null; - } - } - - private static void IterateIcons() - { - while (_animatingThread != null) - { - if (_index < _gif.FrameCount - 1) - _index++; - else - _index = 0; - - if (IconChanged != null) - IconChanged(null, EventArgs.Empty); - - int delay = _gif.GetFrame(_index).Delay; - Thread.Sleep(delay); - } - System.Diagnostics.Debug.WriteLine("IterateIcons Stopped"); - } - - public static event EventHandler IconChanged; - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; + +namespace Aga.Controls.Tree.NodeControls +{ + /// + /// Displays an animated icon for those nodes, who are in expanding state. + /// Parent TreeView must have AsyncExpanding property set to true. + /// + public class ExpandingIcon: NodeControl + { + private static GifDecoder _gif = ResourceHelper.LoadingIcon; + private static int _index = 0; + private static volatile Thread _animatingThread; + private static object _lock = new object(); + + public override Size MeasureSize(TreeNodeAdv node, DrawContext context) + { + return ResourceHelper.LoadingIcon.FrameSize; + } + + protected override void OnIsVisibleValueNeeded(NodeControlValueEventArgs args) + { + args.Value = args.Node.IsExpandingNow; + base.OnIsVisibleValueNeeded(args); + } + + public override void Draw(TreeNodeAdv node, DrawContext context) + { + Rectangle rect = GetBounds(node, context); + Image img = _gif.GetFrame(_index).Image; + context.Graphics.DrawImage(img, rect.Location); + } + + public static void Start() + { + lock (_lock) + { + if (_animatingThread == null) + { + _index = 0; + _animatingThread = new Thread(new ThreadStart(IterateIcons)); + _animatingThread.IsBackground = true; + _animatingThread.Priority = ThreadPriority.Lowest; + _animatingThread.Start(); + } + } + } + + public static void Stop() + { + lock (_lock) + { + _index = 0; + _animatingThread = null; + } + } + + private static void IterateIcons() + { + while (_animatingThread != null) + { + if (_index < _gif.FrameCount - 1) + _index++; + else + _index = 0; + + if (IconChanged != null) + IconChanged(null, EventArgs.Empty); + + int delay = _gif.GetFrame(_index).Delay; + Thread.Sleep(delay); + } + System.Diagnostics.Debug.WriteLine("IterateIcons Stopped"); + } + + public static event EventHandler IconChanged; + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/InteractiveControl.cs b/Aga.Controls/Tree/NodeControls/InteractiveControl.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/InteractiveControl.cs rename to Aga.Controls/Tree/NodeControls/InteractiveControl.cs index 8f9300b..0a9f803 100644 --- a/External/Aga.Controls/Tree/NodeControls/InteractiveControl.cs +++ b/Aga.Controls/Tree/NodeControls/InteractiveControl.cs @@ -1,38 +1,38 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public abstract class InteractiveControl : BindableControl - { - private bool _editEnabled = false; - [DefaultValue(false)] - public bool EditEnabled - { - get { return _editEnabled; } - set { _editEnabled = value; } - } - - protected bool IsEditEnabled(TreeNodeAdv node) - { - if (EditEnabled) - { - NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); - args.Value = true; - OnIsEditEnabledValueNeeded(args); - return Convert.ToBoolean(args.Value); - } - else - return false; - } - - public event EventHandler IsEditEnabledValueNeeded; - private void OnIsEditEnabledValueNeeded(NodeControlValueEventArgs args) - { - if (IsEditEnabledValueNeeded != null) - IsEditEnabledValueNeeded(this, args); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public abstract class InteractiveControl : BindableControl + { + private bool _editEnabled = false; + [DefaultValue(false)] + public bool EditEnabled + { + get { return _editEnabled; } + set { _editEnabled = value; } + } + + protected bool IsEditEnabled(TreeNodeAdv node) + { + if (EditEnabled) + { + NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); + args.Value = true; + OnIsEditEnabledValueNeeded(args); + return Convert.ToBoolean(args.Value); + } + else + return false; + } + + public event EventHandler IsEditEnabledValueNeeded; + private void OnIsEditEnabledValueNeeded(NodeControlValueEventArgs args) + { + if (IsEditEnabledValueNeeded != null) + IsEditEnabledValueNeeded(this, args); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/LabelEventArgs.cs b/Aga.Controls/Tree/NodeControls/LabelEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/LabelEventArgs.cs rename to Aga.Controls/Tree/NodeControls/LabelEventArgs.cs index 78d913e..d792253 100644 --- a/External/Aga.Controls/Tree/NodeControls/LabelEventArgs.cs +++ b/Aga.Controls/Tree/NodeControls/LabelEventArgs.cs @@ -1,34 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree.NodeControls -{ - public class LabelEventArgs : EventArgs - { - private object _subject; - public object Subject - { - get { return _subject; } - } - - private string _oldLabel; - public string OldLabel - { - get { return _oldLabel; } - } - - private string _newLabel; - public string NewLabel - { - get { return _newLabel; } - } - - public LabelEventArgs(object subject, string oldLabel, string newLabel) - { - _subject = subject; - _oldLabel = oldLabel; - _newLabel = newLabel; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree.NodeControls +{ + public class LabelEventArgs : EventArgs + { + private object _subject; + public object Subject + { + get { return _subject; } + } + + private string _oldLabel; + public string OldLabel + { + get { return _oldLabel; } + } + + private string _newLabel; + public string NewLabel + { + get { return _newLabel; } + } + + public LabelEventArgs(object subject, string oldLabel, string newLabel) + { + _subject = subject; + _oldLabel = oldLabel; + _newLabel = newLabel; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs b/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs rename to Aga.Controls/Tree/NodeControls/NodeCheckBox.cs index f702ef0..d9824f1 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs +++ b/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs @@ -1,188 +1,188 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using Aga.Controls.Properties; -using System.Reflection; -using System.Windows.Forms; -using System.Windows.Forms.VisualStyles; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeCheckBox : InteractiveControl - { - public const int ImageSize = 13; - - private Bitmap _check; - private Bitmap _uncheck; - private Bitmap _unknown; - - #region Properties - - private bool _threeState; - [DefaultValue(false)] - public bool ThreeState - { - get { return _threeState; } - set { _threeState = value; } - } - - #endregion - - public NodeCheckBox() - : this(string.Empty) - { - } - - public NodeCheckBox(string propertyName) - { - _check = Resources.check; - _uncheck = Resources.uncheck; - _unknown = Resources.unknown; - DataPropertyName = propertyName; - LeftMargin = 0; - } - - public override Size MeasureSize(TreeNodeAdv node, DrawContext context) - { - int scaledX = node.Tree.GetScaledSize(ImageSize, false); - int scaledY = node.Tree.GetScaledSize(ImageSize); - return new Size(scaledX, scaledY); - } - - public override void Draw(TreeNodeAdv node, DrawContext context) - { - Rectangle bounds = GetBounds(node, context); - CheckState state = GetCheckState(node); - if (Application.RenderWithVisualStyles) - { - VisualStyleRenderer renderer; - int scaledX = node.Tree.GetScaledSize(ImageSize, false); - int scaledY = node.Tree.GetScaledSize(ImageSize); - if (state == CheckState.Indeterminate) - renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.MixedNormal); - else if (state == CheckState.Checked) - renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.CheckedNormal); - else - renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.UncheckedNormal); - renderer.DrawBackground(context.Graphics, new Rectangle(bounds.X, bounds.Y, scaledX, scaledY)); - } - else - { - Image img; - if (state == CheckState.Indeterminate) - img = _unknown; - else if (state == CheckState.Checked) - img = _check; - else - img = _uncheck; - context.Graphics.DrawImage(img, bounds.Location); - } - } - - protected virtual CheckState GetCheckState(TreeNodeAdv node) - { - object obj = GetValue(node); - if (obj is CheckState) - return (CheckState)obj; - else if (obj is bool) - return (bool)obj ? CheckState.Checked : CheckState.Unchecked; - else - return CheckState.Unchecked; - } - - protected virtual void SetCheckState(TreeNodeAdv node, CheckState value) - { - if (VirtualMode) - { - SetValue(node, value); - OnCheckStateChanged(node); - } - else - { - Type type = GetPropertyType(node); - if (type == typeof(CheckState)) - { - SetValue(node, value); - OnCheckStateChanged(node); - } - else if (type == typeof(bool)) - { - SetValue(node, value != CheckState.Unchecked); - OnCheckStateChanged(node); - } - } - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - if (args.Button == MouseButtons.Left && IsEditEnabled(args.Node)) - { - DrawContext context = new DrawContext(); - context.Bounds = args.ControlBounds; - Rectangle rect = GetBounds(args.Node, context); - if (rect.Contains(args.ViewLocation)) - { - CheckState state = GetCheckState(args.Node); - state = GetNewState(state); - SetCheckState(args.Node, state); - Parent.UpdateView(); - args.Handled = true; - } - } - } - - public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - args.Handled = true; - } - - private CheckState GetNewState(CheckState state) - { - if (state == CheckState.Indeterminate) - return CheckState.Unchecked; - else if(state == CheckState.Unchecked) - return CheckState.Checked; - else - return ThreeState ? CheckState.Indeterminate : CheckState.Unchecked; - } - - public override void KeyDown(KeyEventArgs args) - { - if (args.KeyCode == Keys.Space && EditEnabled) - { - Parent.BeginUpdate(); - try - { - if (Parent.CurrentNode != null) - { - CheckState value = GetNewState(GetCheckState(Parent.CurrentNode)); - foreach (TreeNodeAdv node in Parent.Selection) - if (IsEditEnabled(node)) - SetCheckState(node, value); - } - } - finally - { - Parent.EndUpdate(); - } - args.Handled = true; - } - } - - public event EventHandler CheckStateChanged; - protected void OnCheckStateChanged(TreePathEventArgs args) - { - if (CheckStateChanged != null) - CheckStateChanged(this, args); - } - - protected void OnCheckStateChanged(TreeNodeAdv node) - { - TreePath path = this.Parent.GetPath(node); - OnCheckStateChanged(new TreePathEventArgs(path)); - } - - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using Aga.Controls.Properties; +using System.Reflection; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeCheckBox : InteractiveControl + { + public const int ImageSize = 13; + + private Bitmap _check; + private Bitmap _uncheck; + private Bitmap _unknown; + + #region Properties + + private bool _threeState; + [DefaultValue(false)] + public bool ThreeState + { + get { return _threeState; } + set { _threeState = value; } + } + + #endregion + + public NodeCheckBox() + : this(string.Empty) + { + } + + public NodeCheckBox(string propertyName) + { + _check = Resources.check; + _uncheck = Resources.uncheck; + _unknown = Resources.unknown; + DataPropertyName = propertyName; + LeftMargin = 0; + } + + public override Size MeasureSize(TreeNodeAdv node, DrawContext context) + { + int scaledX = node.Tree.GetScaledSize(ImageSize, false); + int scaledY = node.Tree.GetScaledSize(ImageSize); + return new Size(scaledX, scaledY); + } + + public override void Draw(TreeNodeAdv node, DrawContext context) + { + Rectangle bounds = GetBounds(node, context); + CheckState state = GetCheckState(node); + if (Application.RenderWithVisualStyles) + { + VisualStyleRenderer renderer; + int scaledX = node.Tree.GetScaledSize(ImageSize, false); + int scaledY = node.Tree.GetScaledSize(ImageSize); + if (state == CheckState.Indeterminate) + renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.MixedNormal); + else if (state == CheckState.Checked) + renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.CheckedNormal); + else + renderer = new VisualStyleRenderer(VisualStyleElement.Button.CheckBox.UncheckedNormal); + renderer.DrawBackground(context.Graphics, new Rectangle(bounds.X, bounds.Y, scaledX, scaledY)); + } + else + { + Image img; + if (state == CheckState.Indeterminate) + img = _unknown; + else if (state == CheckState.Checked) + img = _check; + else + img = _uncheck; + context.Graphics.DrawImage(img, bounds.Location); + } + } + + protected virtual CheckState GetCheckState(TreeNodeAdv node) + { + object obj = GetValue(node); + if (obj is CheckState) + return (CheckState)obj; + else if (obj is bool) + return (bool)obj ? CheckState.Checked : CheckState.Unchecked; + else + return CheckState.Unchecked; + } + + protected virtual void SetCheckState(TreeNodeAdv node, CheckState value) + { + if (VirtualMode) + { + SetValue(node, value); + OnCheckStateChanged(node); + } + else + { + Type type = GetPropertyType(node); + if (type == typeof(CheckState)) + { + SetValue(node, value); + OnCheckStateChanged(node); + } + else if (type == typeof(bool)) + { + SetValue(node, value != CheckState.Unchecked); + OnCheckStateChanged(node); + } + } + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + if (args.Button == MouseButtons.Left && IsEditEnabled(args.Node)) + { + DrawContext context = new DrawContext(); + context.Bounds = args.ControlBounds; + Rectangle rect = GetBounds(args.Node, context); + if (rect.Contains(args.ViewLocation)) + { + CheckState state = GetCheckState(args.Node); + state = GetNewState(state); + SetCheckState(args.Node, state); + Parent.UpdateView(); + args.Handled = true; + } + } + } + + public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + args.Handled = true; + } + + private CheckState GetNewState(CheckState state) + { + if (state == CheckState.Indeterminate) + return CheckState.Unchecked; + else if(state == CheckState.Unchecked) + return CheckState.Checked; + else + return ThreeState ? CheckState.Indeterminate : CheckState.Unchecked; + } + + public override void KeyDown(KeyEventArgs args) + { + if (args.KeyCode == Keys.Space && EditEnabled) + { + Parent.BeginUpdate(); + try + { + if (Parent.CurrentNode != null) + { + CheckState value = GetNewState(GetCheckState(Parent.CurrentNode)); + foreach (TreeNodeAdv node in Parent.Selection) + if (IsEditEnabled(node)) + SetCheckState(node, value); + } + } + finally + { + Parent.EndUpdate(); + } + args.Handled = true; + } + } + + public event EventHandler CheckStateChanged; + protected void OnCheckStateChanged(TreePathEventArgs args) + { + if (CheckStateChanged != null) + CheckStateChanged(this, args); + } + + protected void OnCheckStateChanged(TreeNodeAdv node) + { + TreePath path = this.Parent.GetPath(node); + OnCheckStateChanged(new TreePathEventArgs(path)); + } + + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeComboBox.cs b/Aga.Controls/Tree/NodeControls/NodeComboBox.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/NodeComboBox.cs rename to Aga.Controls/Tree/NodeControls/NodeComboBox.cs index 89edc06..8aff375 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeComboBox.cs +++ b/Aga.Controls/Tree/NodeControls/NodeComboBox.cs @@ -1,232 +1,232 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using System.Reflection; -using System.ComponentModel; -using System.Drawing.Design; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeComboBox : BaseTextControl - { - #region Properties - - private int _editorWidth = 100; - [DefaultValue(100)] - public int EditorWidth - { - get { return _editorWidth; } - set { _editorWidth = value; } - } - - private int _editorHeight = 100; - [DefaultValue(100)] - public int EditorHeight - { - get { return _editorHeight; } - set { _editorHeight = value; } - } - - private List _dropDownItems; - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] - [Editor(typeof(StringCollectionEditor), typeof(UITypeEditor)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public List DropDownItems - { - get { return _dropDownItems; } - } - - #endregion - - public event EventHandler CreatingEditor; - - public NodeComboBox() - { - _dropDownItems = new List(); - } - - protected override Size CalculateEditorSize(EditorContext context) - { - if (Parent.UseColumns) - { - if (context.Editor is CheckedListBox) - return new Size(context.Bounds.Size.Width, EditorHeight); - else - return context.Bounds.Size; - } - else - { - if (context.Editor is CheckedListBox) - return new Size(EditorWidth, EditorHeight); - else - return new Size(EditorWidth, context.Bounds.Height); - } - } - - protected override Control CreateEditor(TreeNodeAdv node) - { - Control c; - object value = GetValue(node); - if (IsCheckedListBoxRequired(node)) - c = CreateCheckedListBox(node); - else - c = CreateCombo(node); - OnCreatingEditor(new EditEventArgs(node, c)); - return c; - } - - protected override void DisposeEditor(Control editor) - { - } - - protected virtual void OnCreatingEditor(EditEventArgs args) - { - if (CreatingEditor != null) - CreatingEditor(this, args); - } - - protected virtual bool IsCheckedListBoxRequired(TreeNodeAdv node) - { - object value = GetValue(node); - if (value != null) - { - Type t = value.GetType(); - object[] arr = t.GetCustomAttributes(typeof(FlagsAttribute), false); - return (t.IsEnum && arr.Length == 1); - } - return false; - } - - private Control CreateCombo(TreeNodeAdv node) - { - ComboBox comboBox = new ComboBox(); - if (DropDownItems != null) - comboBox.Items.AddRange(DropDownItems.ToArray()); - comboBox.SelectedItem = GetValue(node); - comboBox.DropDownStyle = ComboBoxStyle.DropDownList; - comboBox.DropDownClosed += new EventHandler(EditorDropDownClosed); - SetEditControlProperties(comboBox, node); - return comboBox; - } - - private Control CreateCheckedListBox(TreeNodeAdv node) - { - CheckedListBox listBox = new CheckedListBox(); - listBox.CheckOnClick = true; - - object value = GetValue(node); - Type enumType = GetEnumType(node); - foreach (object obj in Enum.GetValues(enumType)) - { - object[] attributes = enumType.GetField(obj.ToString()).GetCustomAttributes(typeof(BrowsableAttribute), false); - if (attributes.Length == 0 || ((BrowsableAttribute)attributes[0]).Browsable) - listBox.Items.Add(obj, IsContain(value, obj)); - } - - SetEditControlProperties(listBox, node); - if (CreatingEditor != null) - CreatingEditor(this, new EditEventArgs(node, listBox)); - return listBox; - } - - protected virtual Type GetEnumType(TreeNodeAdv node) - { - object value = GetValue(node); - return value.GetType(); - } - - private bool IsContain(object value, object enumElement) - { - if (value == null || enumElement == null) - return false; - if (value.GetType().IsEnum) - { - int i1 = (int)value; - int i2 = (int)enumElement; - return (i1 & i2) == i2; - } - else - { - var arr = value as object[]; - foreach (object obj in arr) - if ((int)obj == (int)enumElement) - return true; - return false; - } - } - - protected override string FormatLabel(object obj) - { - var arr = obj as object[]; - if (arr != null) - { - StringBuilder sb = new StringBuilder(); - foreach (object t in arr) - { - if (sb.Length > 0) - sb.Append(", "); - sb.Append(t); - } - return sb.ToString(); - } - else - return base.FormatLabel(obj); - } - - void EditorDropDownClosed(object sender, EventArgs e) - { - EndEdit(true); - } - - public override void UpdateEditor(Control control) - { - if (control is ComboBox) - (control as ComboBox).DroppedDown = true; - } - - protected override void DoApplyChanges(TreeNodeAdv node, Control editor) - { - var combo = editor as ComboBox; - if (combo != null) - { - if (combo.DropDownStyle == ComboBoxStyle.DropDown) - SetValue(node, combo.Text); - else - SetValue(node, combo.SelectedItem); - } - else - { - var listBox = editor as CheckedListBox; - Type type = GetEnumType(node); - if (IsFlags(type)) - { - int res = 0; - foreach (object obj in listBox.CheckedItems) - res |= (int)obj; - object val = Enum.ToObject(type, res); - SetValue(node, val); - } - else - { - List list = new List(); - foreach (object obj in listBox.CheckedItems) - list.Add(obj); - SetValue(node, list.ToArray()); - } - } - } - - private bool IsFlags(Type type) - { - object[] atr = type.GetCustomAttributes(typeof(FlagsAttribute), false); - return atr.Length == 1; - } - - public override void MouseUp(TreeNodeAdvMouseEventArgs args) - { - if (args.Node != null && args.Node.IsSelected) //Workaround of specific ComboBox control behavior - base.MouseUp(args); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Reflection; +using System.ComponentModel; +using System.Drawing.Design; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeComboBox : BaseTextControl + { + #region Properties + + private int _editorWidth = 100; + [DefaultValue(100)] + public int EditorWidth + { + get { return _editorWidth; } + set { _editorWidth = value; } + } + + private int _editorHeight = 100; + [DefaultValue(100)] + public int EditorHeight + { + get { return _editorHeight; } + set { _editorHeight = value; } + } + + private List _dropDownItems; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] + [Editor(typeof(StringCollectionEditor), typeof(UITypeEditor)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List DropDownItems + { + get { return _dropDownItems; } + } + + #endregion + + public event EventHandler CreatingEditor; + + public NodeComboBox() + { + _dropDownItems = new List(); + } + + protected override Size CalculateEditorSize(EditorContext context) + { + if (Parent.UseColumns) + { + if (context.Editor is CheckedListBox) + return new Size(context.Bounds.Size.Width, EditorHeight); + else + return context.Bounds.Size; + } + else + { + if (context.Editor is CheckedListBox) + return new Size(EditorWidth, EditorHeight); + else + return new Size(EditorWidth, context.Bounds.Height); + } + } + + protected override Control CreateEditor(TreeNodeAdv node) + { + Control c; + object value = GetValue(node); + if (IsCheckedListBoxRequired(node)) + c = CreateCheckedListBox(node); + else + c = CreateCombo(node); + OnCreatingEditor(new EditEventArgs(node, c)); + return c; + } + + protected override void DisposeEditor(Control editor) + { + } + + protected virtual void OnCreatingEditor(EditEventArgs args) + { + if (CreatingEditor != null) + CreatingEditor(this, args); + } + + protected virtual bool IsCheckedListBoxRequired(TreeNodeAdv node) + { + object value = GetValue(node); + if (value != null) + { + Type t = value.GetType(); + object[] arr = t.GetCustomAttributes(typeof(FlagsAttribute), false); + return (t.IsEnum && arr.Length == 1); + } + return false; + } + + private Control CreateCombo(TreeNodeAdv node) + { + ComboBox comboBox = new ComboBox(); + if (DropDownItems != null) + comboBox.Items.AddRange(DropDownItems.ToArray()); + comboBox.SelectedItem = GetValue(node); + comboBox.DropDownStyle = ComboBoxStyle.DropDownList; + comboBox.DropDownClosed += new EventHandler(EditorDropDownClosed); + SetEditControlProperties(comboBox, node); + return comboBox; + } + + private Control CreateCheckedListBox(TreeNodeAdv node) + { + CheckedListBox listBox = new CheckedListBox(); + listBox.CheckOnClick = true; + + object value = GetValue(node); + Type enumType = GetEnumType(node); + foreach (object obj in Enum.GetValues(enumType)) + { + object[] attributes = enumType.GetField(obj.ToString()).GetCustomAttributes(typeof(BrowsableAttribute), false); + if (attributes.Length == 0 || ((BrowsableAttribute)attributes[0]).Browsable) + listBox.Items.Add(obj, IsContain(value, obj)); + } + + SetEditControlProperties(listBox, node); + if (CreatingEditor != null) + CreatingEditor(this, new EditEventArgs(node, listBox)); + return listBox; + } + + protected virtual Type GetEnumType(TreeNodeAdv node) + { + object value = GetValue(node); + return value.GetType(); + } + + private bool IsContain(object value, object enumElement) + { + if (value == null || enumElement == null) + return false; + if (value.GetType().IsEnum) + { + int i1 = (int)value; + int i2 = (int)enumElement; + return (i1 & i2) == i2; + } + else + { + var arr = value as object[]; + foreach (object obj in arr) + if ((int)obj == (int)enumElement) + return true; + return false; + } + } + + protected override string FormatLabel(object obj) + { + var arr = obj as object[]; + if (arr != null) + { + StringBuilder sb = new StringBuilder(); + foreach (object t in arr) + { + if (sb.Length > 0) + sb.Append(", "); + sb.Append(t); + } + return sb.ToString(); + } + else + return base.FormatLabel(obj); + } + + void EditorDropDownClosed(object sender, EventArgs e) + { + EndEdit(true); + } + + public override void UpdateEditor(Control control) + { + if (control is ComboBox) + (control as ComboBox).DroppedDown = true; + } + + protected override void DoApplyChanges(TreeNodeAdv node, Control editor) + { + var combo = editor as ComboBox; + if (combo != null) + { + if (combo.DropDownStyle == ComboBoxStyle.DropDown) + SetValue(node, combo.Text); + else + SetValue(node, combo.SelectedItem); + } + else + { + var listBox = editor as CheckedListBox; + Type type = GetEnumType(node); + if (IsFlags(type)) + { + int res = 0; + foreach (object obj in listBox.CheckedItems) + res |= (int)obj; + object val = Enum.ToObject(type, res); + SetValue(node, val); + } + else + { + List list = new List(); + foreach (object obj in listBox.CheckedItems) + list.Add(obj); + SetValue(node, list.ToArray()); + } + } + } + + private bool IsFlags(Type type) + { + object[] atr = type.GetCustomAttributes(typeof(FlagsAttribute), false); + return atr.Length == 1; + } + + public override void MouseUp(TreeNodeAdvMouseEventArgs args) + { + if (args.Node != null && args.Node.IsSelected) //Workaround of specific ComboBox control behavior + base.MouseUp(args); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeControl.cs b/Aga.Controls/Tree/NodeControls/NodeControl.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/NodeControl.cs rename to Aga.Controls/Tree/NodeControls/NodeControl.cs index 2d60efa..9243e61 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeControl.cs +++ b/Aga.Controls/Tree/NodeControls/NodeControl.cs @@ -1,169 +1,169 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - [DesignTimeVisible(false), ToolboxItem(false)] - public abstract class NodeControl : Component - { - #region Properties - - private TreeViewAdv _parent; - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public TreeViewAdv Parent - { - get { return _parent; } - set - { - if (value != _parent) - { - if (_parent != null) - _parent.NodeControls.Remove(this); - - if (value != null) - value.NodeControls.Add(this); - } - } - } - - private IToolTipProvider _toolTipProvider; - [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public IToolTipProvider ToolTipProvider - { - get { return _toolTipProvider; } - set { _toolTipProvider = value; } - } - - private TreeColumn _parentColumn; - public TreeColumn ParentColumn - { - get { return _parentColumn; } - set - { - _parentColumn = value; - if (_parent != null) - _parent.FullUpdate(); - } - } - - private VerticalAlignment _verticalAlign = VerticalAlignment.Center; - [DefaultValue(VerticalAlignment.Center)] - public VerticalAlignment VerticalAlign - { - get { return _verticalAlign; } - set - { - _verticalAlign = value; - if (_parent != null) - _parent.FullUpdate(); - } - } - - private int _leftMargin = 0; - public int LeftMargin - { - get { return _leftMargin; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(); - - _leftMargin = value; - if (_parent != null) - _parent.FullUpdate(); - } - } - #endregion - - internal virtual void AssignParent(TreeViewAdv parent) - { - _parent = parent; - } - - protected virtual Rectangle GetBounds(TreeNodeAdv node, DrawContext context) - { - Rectangle r = context.Bounds; - Size s = GetActualSize(node, context); - Size bs = new Size(r.Width - LeftMargin, Math.Min(r.Height, s.Height)); - switch (VerticalAlign) - { - case VerticalAlignment.Top: - return new Rectangle(new Point(r.X + LeftMargin, r.Y), bs); - case VerticalAlignment.Bottom: - return new Rectangle(new Point(r.X + LeftMargin, r.Bottom - s.Height), bs); - default: - return new Rectangle(new Point(r.X + LeftMargin, r.Y + (r.Height - s.Height) / 2), bs); - } - } - - protected void CheckThread() - { - if (Parent != null && Control.CheckForIllegalCrossThreadCalls) - if (Parent.InvokeRequired) - throw new InvalidOperationException("Cross-thread calls are not allowed"); - } - - public bool IsVisible(TreeNodeAdv node) - { - NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); - args.Value = true; - OnIsVisibleValueNeeded(args); - return Convert.ToBoolean(args.Value); - } - - internal Size GetActualSize(TreeNodeAdv node, DrawContext context) - { - if (IsVisible(node)) - { - Size s = MeasureSize(node, context); - return new Size(s.Width + LeftMargin, s.Height); - } - else - return Size.Empty; - } - - public abstract Size MeasureSize(TreeNodeAdv node, DrawContext context); - - public abstract void Draw(TreeNodeAdv node, DrawContext context); - - public virtual string GetToolTip(TreeNodeAdv node) - { - if (ToolTipProvider != null) - return ToolTipProvider.GetToolTip(node, this); - else - return string.Empty; - } - - public virtual void MouseDown(TreeNodeAdvMouseEventArgs args) - { - } - - public virtual void MouseUp(TreeNodeAdvMouseEventArgs args) - { - } - - public virtual void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - } - - public virtual void KeyDown(KeyEventArgs args) - { - } - - public virtual void KeyUp(KeyEventArgs args) - { - } - - public event EventHandler IsVisibleValueNeeded; - protected virtual void OnIsVisibleValueNeeded(NodeControlValueEventArgs args) - { - if (IsVisibleValueNeeded != null) - IsVisibleValueNeeded(this, args); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + [DesignTimeVisible(false), ToolboxItem(false)] + public abstract class NodeControl : Component + { + #region Properties + + private TreeViewAdv _parent; + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public TreeViewAdv Parent + { + get { return _parent; } + set + { + if (value != _parent) + { + if (_parent != null) + _parent.NodeControls.Remove(this); + + if (value != null) + value.NodeControls.Add(this); + } + } + } + + private IToolTipProvider _toolTipProvider; + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IToolTipProvider ToolTipProvider + { + get { return _toolTipProvider; } + set { _toolTipProvider = value; } + } + + private TreeColumn _parentColumn; + public TreeColumn ParentColumn + { + get { return _parentColumn; } + set + { + _parentColumn = value; + if (_parent != null) + _parent.FullUpdate(); + } + } + + private VerticalAlignment _verticalAlign = VerticalAlignment.Center; + [DefaultValue(VerticalAlignment.Center)] + public VerticalAlignment VerticalAlign + { + get { return _verticalAlign; } + set + { + _verticalAlign = value; + if (_parent != null) + _parent.FullUpdate(); + } + } + + private int _leftMargin = 0; + public int LeftMargin + { + get { return _leftMargin; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(); + + _leftMargin = value; + if (_parent != null) + _parent.FullUpdate(); + } + } + #endregion + + internal virtual void AssignParent(TreeViewAdv parent) + { + _parent = parent; + } + + protected virtual Rectangle GetBounds(TreeNodeAdv node, DrawContext context) + { + Rectangle r = context.Bounds; + Size s = GetActualSize(node, context); + Size bs = new Size(r.Width - LeftMargin, Math.Min(r.Height, s.Height)); + switch (VerticalAlign) + { + case VerticalAlignment.Top: + return new Rectangle(new Point(r.X + LeftMargin, r.Y), bs); + case VerticalAlignment.Bottom: + return new Rectangle(new Point(r.X + LeftMargin, r.Bottom - s.Height), bs); + default: + return new Rectangle(new Point(r.X + LeftMargin, r.Y + (r.Height - s.Height) / 2), bs); + } + } + + protected void CheckThread() + { + if (Parent != null && Control.CheckForIllegalCrossThreadCalls) + if (Parent.InvokeRequired) + throw new InvalidOperationException("Cross-thread calls are not allowed"); + } + + public bool IsVisible(TreeNodeAdv node) + { + NodeControlValueEventArgs args = new NodeControlValueEventArgs(node); + args.Value = true; + OnIsVisibleValueNeeded(args); + return Convert.ToBoolean(args.Value); + } + + internal Size GetActualSize(TreeNodeAdv node, DrawContext context) + { + if (IsVisible(node)) + { + Size s = MeasureSize(node, context); + return new Size(s.Width + LeftMargin, s.Height); + } + else + return Size.Empty; + } + + public abstract Size MeasureSize(TreeNodeAdv node, DrawContext context); + + public abstract void Draw(TreeNodeAdv node, DrawContext context); + + public virtual string GetToolTip(TreeNodeAdv node) + { + if (ToolTipProvider != null) + return ToolTipProvider.GetToolTip(node, this); + else + return string.Empty; + } + + public virtual void MouseDown(TreeNodeAdvMouseEventArgs args) + { + } + + public virtual void MouseUp(TreeNodeAdvMouseEventArgs args) + { + } + + public virtual void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + } + + public virtual void KeyDown(KeyEventArgs args) + { + } + + public virtual void KeyUp(KeyEventArgs args) + { + } + + public event EventHandler IsVisibleValueNeeded; + protected virtual void OnIsVisibleValueNeeded(NodeControlValueEventArgs args) + { + if (IsVisibleValueNeeded != null) + IsVisibleValueNeeded(this, args); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs b/Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs rename to Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs index d4f72ec..3686440 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs +++ b/Aga.Controls/Tree/NodeControls/NodeControlValueEventArgs.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeControlValueEventArgs : NodeEventArgs - { - private object _value; - public object Value - { - get { return _value; } - set { _value = value; } - } - - public NodeControlValueEventArgs(TreeNodeAdv node) - :base(node) - { - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeControlValueEventArgs : NodeEventArgs + { + private object _value; + public object Value + { + get { return _value; } + set { _value = value; } + } + + public NodeControlValueEventArgs(TreeNodeAdv node) + :base(node) + { + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs b/Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs rename to Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs index 1177ec4..f31e05e 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs +++ b/Aga.Controls/Tree/NodeControls/NodeControlsCollection.cs @@ -1,94 +1,94 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel.Design; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Drawing.Design; - -namespace Aga.Controls.Tree.NodeControls -{ - internal class NodeControlsCollection : Collection - { - private TreeViewAdv _tree; - - public NodeControlsCollection(TreeViewAdv tree) - { - _tree = tree; - } - - protected override void ClearItems() - { - _tree.BeginUpdate(); - try - { - while (this.Count != 0) - this.RemoveAt(this.Count - 1); - } - finally - { - _tree.EndUpdate(); - } - } - - protected override void InsertItem(int index, NodeControl item) - { - if (item == null) - throw new ArgumentNullException("item"); - - if (item.Parent != _tree) - { - if (item.Parent != null) - { - item.Parent.NodeControls.Remove(item); - } - base.InsertItem(index, item); - item.AssignParent(_tree); - _tree.FullUpdate(); - } - } - - protected override void RemoveItem(int index) - { - NodeControl value = this[index]; - value.AssignParent(null); - base.RemoveItem(index); - _tree.FullUpdate(); - } - - protected override void SetItem(int index, NodeControl item) - { - if (item == null) - throw new ArgumentNullException("item"); - - _tree.BeginUpdate(); - try - { - RemoveAt(index); - InsertItem(index, item); - } - finally - { - _tree.EndUpdate(); - } - } - } - - internal class NodeControlCollectionEditor : CollectionEditor - { - private Type[] _types; - - public NodeControlCollectionEditor(Type type) - : base(type) - { - _types = new Type[] { typeof(NodeTextBox), typeof(NodeIntegerTextBox), typeof(NodeDecimalTextBox), - typeof(NodeComboBox), typeof(NodeCheckBox), - typeof(NodeStateIcon), typeof(NodeIcon), typeof(NodeNumericUpDown), typeof(ExpandingIcon) }; - } - - protected override System.Type[] CreateNewItemTypes() - { - return _types; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel.Design; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Drawing.Design; + +namespace Aga.Controls.Tree.NodeControls +{ + internal class NodeControlsCollection : Collection + { + private TreeViewAdv _tree; + + public NodeControlsCollection(TreeViewAdv tree) + { + _tree = tree; + } + + protected override void ClearItems() + { + _tree.BeginUpdate(); + try + { + while (this.Count != 0) + this.RemoveAt(this.Count - 1); + } + finally + { + _tree.EndUpdate(); + } + } + + protected override void InsertItem(int index, NodeControl item) + { + if (item == null) + throw new ArgumentNullException("item"); + + if (item.Parent != _tree) + { + if (item.Parent != null) + { + item.Parent.NodeControls.Remove(item); + } + base.InsertItem(index, item); + item.AssignParent(_tree); + _tree.FullUpdate(); + } + } + + protected override void RemoveItem(int index) + { + NodeControl value = this[index]; + value.AssignParent(null); + base.RemoveItem(index); + _tree.FullUpdate(); + } + + protected override void SetItem(int index, NodeControl item) + { + if (item == null) + throw new ArgumentNullException("item"); + + _tree.BeginUpdate(); + try + { + RemoveAt(index); + InsertItem(index, item); + } + finally + { + _tree.EndUpdate(); + } + } + } + + internal class NodeControlCollectionEditor : CollectionEditor + { + private Type[] _types; + + public NodeControlCollectionEditor(Type type) + : base(type) + { + _types = new Type[] { typeof(NodeTextBox), typeof(NodeIntegerTextBox), typeof(NodeDecimalTextBox), + typeof(NodeComboBox), typeof(NodeCheckBox), + typeof(NodeStateIcon), typeof(NodeIcon), typeof(NodeNumericUpDown), typeof(ExpandingIcon) }; + } + + protected override System.Type[] CreateNewItemTypes() + { + return _types; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs b/Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs rename to Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs index 6a44d7d..20ada8e 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs +++ b/Aga.Controls/Tree/NodeControls/NodeDecimalTextBox.cs @@ -1,46 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using System.Reflection; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeDecimalTextBox : NodeTextBox - { - private bool _allowDecimalSeparator = true; - [DefaultValue(true)] - public bool AllowDecimalSeparator - { - get { return _allowDecimalSeparator; } - set { _allowDecimalSeparator = value; } - } - - private bool _allowNegativeSign = true; - [DefaultValue(true)] - public bool AllowNegativeSign - { - get { return _allowNegativeSign; } - set { _allowNegativeSign = value; } - } - - protected NodeDecimalTextBox() - { - } - - protected override TextBox CreateTextBox() - { - NumericTextBox textBox = new NumericTextBox(); - textBox.AllowDecimalSeparator = AllowDecimalSeparator; - textBox.AllowNegativeSign = AllowNegativeSign; - return textBox; - } - - protected override void DoApplyChanges(TreeNodeAdv node, Control editor) - { - SetValue(node, (editor as NumericTextBox).DecimalValue); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Reflection; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeDecimalTextBox : NodeTextBox + { + private bool _allowDecimalSeparator = true; + [DefaultValue(true)] + public bool AllowDecimalSeparator + { + get { return _allowDecimalSeparator; } + set { _allowDecimalSeparator = value; } + } + + private bool _allowNegativeSign = true; + [DefaultValue(true)] + public bool AllowNegativeSign + { + get { return _allowNegativeSign; } + set { _allowNegativeSign = value; } + } + + protected NodeDecimalTextBox() + { + } + + protected override TextBox CreateTextBox() + { + NumericTextBox textBox = new NumericTextBox(); + textBox.AllowDecimalSeparator = AllowDecimalSeparator; + textBox.AllowNegativeSign = AllowNegativeSign; + return textBox; + } + + protected override void DoApplyChanges(TreeNodeAdv node, Control editor) + { + SetValue(node, (editor as NumericTextBox).DecimalValue); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeEventArgs.cs b/Aga.Controls/Tree/NodeControls/NodeEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/NodeEventArgs.cs rename to Aga.Controls/Tree/NodeControls/NodeEventArgs.cs index 5ee8e4f..cedccbf 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeEventArgs.cs +++ b/Aga.Controls/Tree/NodeControls/NodeEventArgs.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeEventArgs : EventArgs - { - private TreeNodeAdv _node; - public TreeNodeAdv Node - { - get { return _node; } - } - - public NodeEventArgs(TreeNodeAdv node) - { - _node = node; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeEventArgs : EventArgs + { + private TreeNodeAdv _node; + public TreeNodeAdv Node + { + get { return _node; } + } + + public NodeEventArgs(TreeNodeAdv node) + { + _node = node; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeIcon.cs b/Aga.Controls/Tree/NodeControls/NodeIcon.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/NodeIcon.cs rename to Aga.Controls/Tree/NodeControls/NodeIcon.cs index 65ce972..d86340c 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeIcon.cs +++ b/Aga.Controls/Tree/NodeControls/NodeIcon.cs @@ -1,105 +1,105 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using Aga.Controls.Properties; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeIcon : BindableControl - { - public NodeIcon() - { - LeftMargin = 1; - } - - public override Size MeasureSize(TreeNodeAdv node, DrawContext context) - { - Image image = GetIcon(node); - if (image != null) - { - int scaledX = node.Tree.GetScaledSize(image.Size.Width, false); - int scaledY = node.Tree.GetScaledSize(image.Size.Height); - return new Size(scaledX, scaledY); ; - } - else - { - return Size.Empty; - } - } - - - public override void Draw(TreeNodeAdv node, DrawContext context) - { - Image image = GetIcon(node); - if (image != null) - { - Rectangle r = GetBounds(node, context); - if ( image.Width > 0 && image.Height > 0 ) - { - switch (_scaleMode) - { - case ImageScaleMode.Fit: - context.Graphics.DrawImage(image, r); - break; - case ImageScaleMode.ScaleDown: - { - float factor = Math.Min((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height); - if (factor < 1) - context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); - else - context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); - } break; - case ImageScaleMode.ScaleUp: - { - float factor = Math.Max((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height); - if (factor > 1) - context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); - else - context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); - } break; - case ImageScaleMode.AlwaysScale: - { - float fx = (float)r.Width / (float)image.Width; - float fy = (float)r.Height / (float)image.Height; - if (Math.Min(fx, fy) < 1) - { //scale down - float factor = Math.Min(fx, fy); - context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); - } - else if (Math.Max(fx, fy) > 1) - { - float factor = Math.Max(fx, fy); - context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); - } - else - context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); - } break; - case ImageScaleMode.Clip: - default: - context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); - break; - } - } - - } - } - - protected virtual Image GetIcon(TreeNodeAdv node) - { - return GetValue(node) as Image; - } - - private ImageScaleMode _scaleMode = ImageScaleMode.Clip; - [DefaultValue("Clip"), Category("Appearance")] - public ImageScaleMode ScaleMode - { - get { return _scaleMode; } - set { _scaleMode = value; } - } - - - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using Aga.Controls.Properties; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeIcon : BindableControl + { + public NodeIcon() + { + LeftMargin = 1; + } + + public override Size MeasureSize(TreeNodeAdv node, DrawContext context) + { + Image image = GetIcon(node); + if (image != null) + { + int scaledX = node.Tree.GetScaledSize(image.Size.Width, false); + int scaledY = node.Tree.GetScaledSize(image.Size.Height); + return new Size(scaledX, scaledY); ; + } + else + { + return Size.Empty; + } + } + + + public override void Draw(TreeNodeAdv node, DrawContext context) + { + Image image = GetIcon(node); + if (image != null) + { + Rectangle r = GetBounds(node, context); + if ( image.Width > 0 && image.Height > 0 ) + { + switch (_scaleMode) + { + case ImageScaleMode.Fit: + context.Graphics.DrawImage(image, r); + break; + case ImageScaleMode.ScaleDown: + { + float factor = Math.Min((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height); + if (factor < 1) + context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); + else + context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); + } break; + case ImageScaleMode.ScaleUp: + { + float factor = Math.Max((float)r.Width / (float)image.Width, (float)r.Height / (float)image.Height); + if (factor > 1) + context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); + else + context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); + } break; + case ImageScaleMode.AlwaysScale: + { + float fx = (float)r.Width / (float)image.Width; + float fy = (float)r.Height / (float)image.Height; + if (Math.Min(fx, fy) < 1) + { //scale down + float factor = Math.Min(fx, fy); + context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); + } + else if (Math.Max(fx, fy) > 1) + { + float factor = Math.Max(fx, fy); + context.Graphics.DrawImage(image, r.X, r.Y, image.Width * factor, image.Height * factor); + } + else + context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); + } break; + case ImageScaleMode.Clip: + default: + context.Graphics.DrawImage(image, r.X, r.Y, image.Width, image.Height); + break; + } + } + + } + } + + protected virtual Image GetIcon(TreeNodeAdv node) + { + return GetValue(node) as Image; + } + + private ImageScaleMode _scaleMode = ImageScaleMode.Clip; + [DefaultValue("Clip"), Category("Appearance")] + public ImageScaleMode ScaleMode + { + get { return _scaleMode; } + set { _scaleMode = value; } + } + + + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs b/Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs rename to Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs index 943944e..7e6d075 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs +++ b/Aga.Controls/Tree/NodeControls/NodeIntegerTextBox.cs @@ -1,37 +1,37 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel; -using System.Windows.Forms; - -namespace Aga.Controls.Tree.NodeControls -{ - - public class NodeIntegerTextBox : NodeTextBox - { - private bool _allowNegativeSign = true; - [DefaultValue(true)] - public bool AllowNegativeSign - { - get { return _allowNegativeSign; } - set { _allowNegativeSign = value; } - } - - public NodeIntegerTextBox() - { - } - - protected override TextBox CreateTextBox() - { - NumericTextBox textBox = new NumericTextBox(); - textBox.AllowDecimalSeparator = false; - textBox.AllowNegativeSign = AllowNegativeSign; - return textBox; - } - - protected override void DoApplyChanges(TreeNodeAdv node, Control editor) - { - SetValue(node, (editor as NumericTextBox).IntValue); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; +using System.Windows.Forms; + +namespace Aga.Controls.Tree.NodeControls +{ + + public class NodeIntegerTextBox : NodeTextBox + { + private bool _allowNegativeSign = true; + [DefaultValue(true)] + public bool AllowNegativeSign + { + get { return _allowNegativeSign; } + set { _allowNegativeSign = value; } + } + + public NodeIntegerTextBox() + { + } + + protected override TextBox CreateTextBox() + { + NumericTextBox textBox = new NumericTextBox(); + textBox.AllowDecimalSeparator = false; + textBox.AllowNegativeSign = AllowNegativeSign; + return textBox; + } + + protected override void DoApplyChanges(TreeNodeAdv node, Control editor) + { + SetValue(node, (editor as NumericTextBox).IntValue); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs b/Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs similarity index 94% rename from External/Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs rename to Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs index 692ab81..743e6f7 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs +++ b/Aga.Controls/Tree/NodeControls/NodeNumericUpDown.cs @@ -1,115 +1,115 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using System.Reflection; -using System.ComponentModel; -using System.Drawing.Design; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeNumericUpDown : BaseTextControl - { - #region Properties - - private int _editorWidth = 100; - [DefaultValue(100)] - public int EditorWidth - { - get { return _editorWidth; } - set { _editorWidth = value; } - } - - private int _decimalPlaces = 0; - [Category("Data"), DefaultValue(0)] - public int DecimalPlaces - { - get - { - return this._decimalPlaces; - } - set - { - this._decimalPlaces = value; - } - } - - private decimal _increment = 1; - [Category("Data"), DefaultValue(1)] - public decimal Increment - { - get - { - return this._increment; - } - set - { - this._increment = value; - } - } - - private decimal _minimum = 0; - [Category("Data"), DefaultValue(0)] - public decimal Minimum - { - get - { - return _minimum; - } - set - { - _minimum = value; - } - } - - private decimal _maximum = 100; - [Category("Data"), DefaultValue(100)] - public decimal Maximum - { - get - { - return this._maximum; - } - set - { - this._maximum = value; - } - } - - #endregion - - public NodeNumericUpDown() - { - } - - protected override Size CalculateEditorSize(EditorContext context) - { - if (Parent.UseColumns) - return context.Bounds.Size; - else - return new Size(EditorWidth, context.Bounds.Height); - } - - protected override Control CreateEditor(TreeNodeAdv node) - { - NumericUpDown num = new NumericUpDown(); - num.Increment = Increment; - num.DecimalPlaces = DecimalPlaces; - num.Minimum = Minimum; - num.Maximum = Maximum; - num.Value = (decimal)GetValue(node); - SetEditControlProperties(num, node); - return num; - } - - protected override void DisposeEditor(Control editor) - { - } - - protected override void DoApplyChanges(TreeNodeAdv node, Control editor) - { - SetValue(node, (editor as NumericUpDown).Value); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Reflection; +using System.ComponentModel; +using System.Drawing.Design; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeNumericUpDown : BaseTextControl + { + #region Properties + + private int _editorWidth = 100; + [DefaultValue(100)] + public int EditorWidth + { + get { return _editorWidth; } + set { _editorWidth = value; } + } + + private int _decimalPlaces = 0; + [Category("Data"), DefaultValue(0)] + public int DecimalPlaces + { + get + { + return this._decimalPlaces; + } + set + { + this._decimalPlaces = value; + } + } + + private decimal _increment = 1; + [Category("Data"), DefaultValue(1)] + public decimal Increment + { + get + { + return this._increment; + } + set + { + this._increment = value; + } + } + + private decimal _minimum = 0; + [Category("Data"), DefaultValue(0)] + public decimal Minimum + { + get + { + return _minimum; + } + set + { + _minimum = value; + } + } + + private decimal _maximum = 100; + [Category("Data"), DefaultValue(100)] + public decimal Maximum + { + get + { + return this._maximum; + } + set + { + this._maximum = value; + } + } + + #endregion + + public NodeNumericUpDown() + { + } + + protected override Size CalculateEditorSize(EditorContext context) + { + if (Parent.UseColumns) + return context.Bounds.Size; + else + return new Size(EditorWidth, context.Bounds.Height); + } + + protected override Control CreateEditor(TreeNodeAdv node) + { + NumericUpDown num = new NumericUpDown(); + num.Increment = Increment; + num.DecimalPlaces = DecimalPlaces; + num.Minimum = Minimum; + num.Maximum = Maximum; + num.Value = (decimal)GetValue(node); + SetEditControlProperties(num, node); + return num; + } + + protected override void DisposeEditor(Control editor) + { + } + + protected override void DoApplyChanges(TreeNodeAdv node, Control editor) + { + SetValue(node, (editor as NumericUpDown).Value); + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodePlusMinus.cs b/Aga.Controls/Tree/NodeControls/NodePlusMinus.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/NodePlusMinus.cs rename to Aga.Controls/Tree/NodeControls/NodePlusMinus.cs index 3f16a5d..efde813 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodePlusMinus.cs +++ b/Aga.Controls/Tree/NodeControls/NodePlusMinus.cs @@ -1,98 +1,98 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using Aga.Controls.Properties; -using System.Windows.Forms; -using System.Windows.Forms.VisualStyles; - -namespace Aga.Controls.Tree.NodeControls -{ - internal class NodePlusMinus : NodeControl - { - public const int ImageSize = 9; - public const int Width = 16; - private Bitmap _plus; - private Bitmap _minus; - - private VisualStyleRenderer _openedRenderer; - private VisualStyleRenderer OpenedRenderer - { - get - { - if (_openedRenderer == null) - _openedRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened); - return _openedRenderer; - - } - } - - private VisualStyleRenderer _closedRenderer; - private VisualStyleRenderer ClosedRenderer - { - get - { - if (_closedRenderer == null) - _closedRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed); - return _closedRenderer; - } - } - - public NodePlusMinus() - { - _plus = Resources.plus; - _minus = Resources.minus; - } - - public override Size MeasureSize(TreeNodeAdv node, DrawContext context) - { - int scaledX = node.Tree.GetScaledSize(Width, false); - int scaledY = node.Tree.GetScaledSize(Width); - return new Size(scaledX, scaledY); - } - - public override void Draw(TreeNodeAdv node, DrawContext context) - { - if (node.CanExpand) - { - Rectangle r = context.Bounds; - int scaledX = node.Tree.GetScaledSize(ImageSize, false); - int scaledY = node.Tree.GetScaledSize(ImageSize); - int dy = (int)Math.Round((float)(r.Height - scaledY) / 2); - if (Application.RenderWithVisualStyles) - { - VisualStyleRenderer renderer; - if (node.IsExpanded) - renderer = OpenedRenderer; - else - renderer = ClosedRenderer; - renderer.DrawBackground(context.Graphics, new Rectangle(r.X, r.Y + dy, scaledX, scaledY)); - } - else - { - Image img; - if (node.IsExpanded) - img = _minus; - else - img = _plus; - context.Graphics.DrawImageUnscaled(img, new Point(r.X, r.Y + dy)); - } - } - } - - public override void MouseDown(TreeNodeAdvMouseEventArgs args) - { - if (args.Button == MouseButtons.Left) - { - args.Handled = true; - if (args.Node.CanExpand) - args.Node.IsExpanded = !args.Node.IsExpanded; - } - } - - public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - args.Handled = true; // Supress expand/collapse when double click on plus/minus - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using Aga.Controls.Properties; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace Aga.Controls.Tree.NodeControls +{ + internal class NodePlusMinus : NodeControl + { + public const int ImageSize = 9; + public const int Width = 16; + private Bitmap _plus; + private Bitmap _minus; + + private VisualStyleRenderer _openedRenderer; + private VisualStyleRenderer OpenedRenderer + { + get + { + if (_openedRenderer == null) + _openedRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened); + return _openedRenderer; + + } + } + + private VisualStyleRenderer _closedRenderer; + private VisualStyleRenderer ClosedRenderer + { + get + { + if (_closedRenderer == null) + _closedRenderer = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed); + return _closedRenderer; + } + } + + public NodePlusMinus() + { + _plus = Resources.plus; + _minus = Resources.minus; + } + + public override Size MeasureSize(TreeNodeAdv node, DrawContext context) + { + int scaledX = node.Tree.GetScaledSize(Width, false); + int scaledY = node.Tree.GetScaledSize(Width); + return new Size(scaledX, scaledY); + } + + public override void Draw(TreeNodeAdv node, DrawContext context) + { + if (node.CanExpand) + { + Rectangle r = context.Bounds; + int scaledX = node.Tree.GetScaledSize(ImageSize, false); + int scaledY = node.Tree.GetScaledSize(ImageSize); + int dy = (int)Math.Round((float)(r.Height - scaledY) / 2); + if (Application.RenderWithVisualStyles) + { + VisualStyleRenderer renderer; + if (node.IsExpanded) + renderer = OpenedRenderer; + else + renderer = ClosedRenderer; + renderer.DrawBackground(context.Graphics, new Rectangle(r.X, r.Y + dy, scaledX, scaledY)); + } + else + { + Image img; + if (node.IsExpanded) + img = _minus; + else + img = _plus; + context.Graphics.DrawImageUnscaled(img, new Point(r.X, r.Y + dy)); + } + } + } + + public override void MouseDown(TreeNodeAdvMouseEventArgs args) + { + if (args.Button == MouseButtons.Left) + { + args.Handled = true; + if (args.Node.CanExpand) + args.Node.IsExpanded = !args.Node.IsExpanded; + } + } + + public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + args.Handled = true; // Supress expand/collapse when double click on plus/minus + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeStateIcon.cs b/Aga.Controls/Tree/NodeControls/NodeStateIcon.cs similarity index 95% rename from External/Aga.Controls/Tree/NodeControls/NodeStateIcon.cs rename to Aga.Controls/Tree/NodeControls/NodeStateIcon.cs index 20c751c..bd041e8 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeStateIcon.cs +++ b/Aga.Controls/Tree/NodeControls/NodeStateIcon.cs @@ -1,41 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using Aga.Controls.Properties; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeStateIcon: NodeIcon - { - private Image _leaf; - private Image _opened; - private Image _closed; - - public NodeStateIcon() - { - _leaf = MakeTransparent(Resources.Leaf); - _opened = MakeTransparent(Resources.Folder); - _closed = MakeTransparent(Resources.FolderClosed); - } - - private static Image MakeTransparent(Bitmap bitmap) - { - bitmap.MakeTransparent(bitmap.GetPixel(0,0)); - return bitmap; - } - - protected override Image GetIcon(TreeNodeAdv node) - { - Image icon = base.GetIcon(node); - if (icon != null) - return icon; - else if (node.IsLeaf) - return _leaf; - else if (node.CanExpand && node.IsExpanded) - return _opened; - else - return _closed; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using Aga.Controls.Properties; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeStateIcon: NodeIcon + { + private Image _leaf; + private Image _opened; + private Image _closed; + + public NodeStateIcon() + { + _leaf = MakeTransparent(Resources.Leaf); + _opened = MakeTransparent(Resources.Folder); + _closed = MakeTransparent(Resources.FolderClosed); + } + + private static Image MakeTransparent(Bitmap bitmap) + { + bitmap.MakeTransparent(bitmap.GetPixel(0,0)); + return bitmap; + } + + protected override Image GetIcon(TreeNodeAdv node) + { + Image icon = base.GetIcon(node); + if (icon != null) + return icon; + else if (node.IsLeaf) + return _leaf; + else if (node.CanExpand && node.IsExpanded) + return _opened; + else + return _closed; + } + } +} diff --git a/External/Aga.Controls/Tree/NodeControls/NodeTextBox.cs b/Aga.Controls/Tree/NodeControls/NodeTextBox.cs similarity index 96% rename from External/Aga.Controls/Tree/NodeControls/NodeTextBox.cs rename to Aga.Controls/Tree/NodeControls/NodeTextBox.cs index e8676b3..81065d8 100644 --- a/External/Aga.Controls/Tree/NodeControls/NodeTextBox.cs +++ b/Aga.Controls/Tree/NodeControls/NodeTextBox.cs @@ -1,126 +1,126 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Windows.Forms; -using System.Reflection; -using System.ComponentModel; - -namespace Aga.Controls.Tree.NodeControls -{ - public class NodeTextBox : BaseTextControl - { - private const int MinTextBoxWidth = 30; - - public NodeTextBox() - { - } - - protected override Size CalculateEditorSize(EditorContext context) - { - if (Parent.UseColumns) - return context.Bounds.Size; - else - { - Size size = GetLabelSize(context.CurrentNode, context.DrawContext, _label); - int width = Math.Max(size.Width + Font.Height, MinTextBoxWidth); // reserve a place for new typed character - return new Size(width, size.Height); - } - } - - public override void KeyDown(KeyEventArgs args) - { - if (args.KeyCode == Keys.F2 && Parent.CurrentNode != null && EditEnabled) - { - args.Handled = true; - BeginEdit(); - } - } - - protected override Control CreateEditor(TreeNodeAdv node) - { - TextBox textBox = CreateTextBox(); - textBox.TextAlign = TextAlign; - textBox.Text = GetLabel(node); - textBox.BorderStyle = BorderStyle.FixedSingle; - textBox.TextChanged += EditorTextChanged; - textBox.KeyDown += EditorKeyDown; - _label = textBox.Text; - SetEditControlProperties(textBox, node); - return textBox; - } - - protected virtual TextBox CreateTextBox() - { - return new TextBox(); - } - - protected override void DisposeEditor(Control editor) - { - var textBox = editor as TextBox; - textBox.TextChanged -= EditorTextChanged; - textBox.KeyDown -= EditorKeyDown; - } - - private void EditorKeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Escape) - EndEdit(false); - else if (e.KeyCode == Keys.Enter) - EndEdit(true); - } - - private string _label; - private void EditorTextChanged(object sender, EventArgs e) - { - var textBox = sender as TextBox; - _label = textBox.Text; - Parent.UpdateEditorBounds(); - } - - protected override void DoApplyChanges(TreeNodeAdv node, Control editor) - { - var label = (editor as TextBox).Text; - string oldLabel = GetLabel(node); - if (oldLabel != label) - { - SetLabel(node, label); - OnLabelChanged(node.Tag, oldLabel, label); - } - } - - public override void Cut(Control control) - { - (control as TextBox).Cut(); - } - - public override void Copy(Control control) - { - (control as TextBox).Copy(); - } - - public override void Paste(Control control) - { - (control as TextBox).Paste(); - } - - public override void Delete(Control control) - { - var textBox = control as TextBox; - int len = Math.Max(textBox.SelectionLength, 1); - if (textBox.SelectionStart < textBox.Text.Length) - { - int start = textBox.SelectionStart; - textBox.Text = textBox.Text.Remove(textBox.SelectionStart, len); - textBox.SelectionStart = start; - } - } - - public event EventHandler LabelChanged; - protected void OnLabelChanged(object subject, string oldLabel, string newLabel) - { - if (LabelChanged != null) - LabelChanged(this, new LabelEventArgs(subject, oldLabel, newLabel)); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Windows.Forms; +using System.Reflection; +using System.ComponentModel; + +namespace Aga.Controls.Tree.NodeControls +{ + public class NodeTextBox : BaseTextControl + { + private const int MinTextBoxWidth = 30; + + public NodeTextBox() + { + } + + protected override Size CalculateEditorSize(EditorContext context) + { + if (Parent.UseColumns) + return context.Bounds.Size; + else + { + Size size = GetLabelSize(context.CurrentNode, context.DrawContext, _label); + int width = Math.Max(size.Width + Font.Height, MinTextBoxWidth); // reserve a place for new typed character + return new Size(width, size.Height); + } + } + + public override void KeyDown(KeyEventArgs args) + { + if (args.KeyCode == Keys.F2 && Parent.CurrentNode != null && EditEnabled) + { + args.Handled = true; + BeginEdit(); + } + } + + protected override Control CreateEditor(TreeNodeAdv node) + { + TextBox textBox = CreateTextBox(); + textBox.TextAlign = TextAlign; + textBox.Text = GetLabel(node); + textBox.BorderStyle = BorderStyle.FixedSingle; + textBox.TextChanged += EditorTextChanged; + textBox.KeyDown += EditorKeyDown; + _label = textBox.Text; + SetEditControlProperties(textBox, node); + return textBox; + } + + protected virtual TextBox CreateTextBox() + { + return new TextBox(); + } + + protected override void DisposeEditor(Control editor) + { + var textBox = editor as TextBox; + textBox.TextChanged -= EditorTextChanged; + textBox.KeyDown -= EditorKeyDown; + } + + private void EditorKeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Escape) + EndEdit(false); + else if (e.KeyCode == Keys.Enter) + EndEdit(true); + } + + private string _label; + private void EditorTextChanged(object sender, EventArgs e) + { + var textBox = sender as TextBox; + _label = textBox.Text; + Parent.UpdateEditorBounds(); + } + + protected override void DoApplyChanges(TreeNodeAdv node, Control editor) + { + var label = (editor as TextBox).Text; + string oldLabel = GetLabel(node); + if (oldLabel != label) + { + SetLabel(node, label); + OnLabelChanged(node.Tag, oldLabel, label); + } + } + + public override void Cut(Control control) + { + (control as TextBox).Cut(); + } + + public override void Copy(Control control) + { + (control as TextBox).Copy(); + } + + public override void Paste(Control control) + { + (control as TextBox).Paste(); + } + + public override void Delete(Control control) + { + var textBox = control as TextBox; + int len = Math.Max(textBox.SelectionLength, 1); + if (textBox.SelectionStart < textBox.Text.Length) + { + int start = textBox.SelectionStart; + textBox.Text = textBox.Text.Remove(textBox.SelectionStart, len); + textBox.SelectionStart = start; + } + } + + public event EventHandler LabelChanged; + protected void OnLabelChanged(object subject, string oldLabel, string newLabel) + { + if (LabelChanged != null) + LabelChanged(this, new LabelEventArgs(subject, oldLabel, newLabel)); + } + } +} diff --git a/External/Aga.Controls/Tree/SortedTreeModel.cs b/Aga.Controls/Tree/SortedTreeModel.cs similarity index 96% rename from External/Aga.Controls/Tree/SortedTreeModel.cs rename to Aga.Controls/Tree/SortedTreeModel.cs index d9cb108..96f22c2 100644 --- a/External/Aga.Controls/Tree/SortedTreeModel.cs +++ b/Aga.Controls/Tree/SortedTreeModel.cs @@ -1,81 +1,81 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections; - -namespace Aga.Controls.Tree -{ - public class SortedTreeModel: TreeModelBase - { - private ITreeModel _innerModel; - public ITreeModel InnerModel - { - get { return _innerModel; } - } - - private IComparer _comparer; - public IComparer Comparer - { - get { return _comparer; } - set - { - _comparer = value; - OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); - } - } - - public SortedTreeModel(ITreeModel innerModel) - { - _innerModel = innerModel; - _innerModel.NodesChanged += new EventHandler(_innerModel_NodesChanged); - _innerModel.NodesInserted += new EventHandler(_innerModel_NodesInserted); - _innerModel.NodesRemoved += new EventHandler(_innerModel_NodesRemoved); - _innerModel.StructureChanged += new EventHandler(_innerModel_StructureChanged); - } - - void _innerModel_StructureChanged(object sender, TreePathEventArgs e) - { - OnStructureChanged(e); - } - - void _innerModel_NodesRemoved(object sender, TreeModelEventArgs e) - { - OnStructureChanged(new TreePathEventArgs(e.Path)); - } - - void _innerModel_NodesInserted(object sender, TreeModelEventArgs e) - { - OnStructureChanged(new TreePathEventArgs(e.Path)); - } - - void _innerModel_NodesChanged(object sender, TreeModelEventArgs e) - { - OnStructureChanged(new TreePathEventArgs(e.Path)); - } - - public override IEnumerable GetChildren(TreePath treePath) - { - if (Comparer != null) - { - ArrayList list = new ArrayList(); - IEnumerable res = InnerModel.GetChildren(treePath); - if (res != null) - { - foreach (object obj in res) - list.Add(obj); - list.Sort(Comparer); - return list; - } - else - return null; - } - else - return InnerModel.GetChildren(treePath); - } - - public override bool IsLeaf(TreePath treePath) - { - return InnerModel.IsLeaf(treePath); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace Aga.Controls.Tree +{ + public class SortedTreeModel: TreeModelBase + { + private ITreeModel _innerModel; + public ITreeModel InnerModel + { + get { return _innerModel; } + } + + private IComparer _comparer; + public IComparer Comparer + { + get { return _comparer; } + set + { + _comparer = value; + OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); + } + } + + public SortedTreeModel(ITreeModel innerModel) + { + _innerModel = innerModel; + _innerModel.NodesChanged += new EventHandler(_innerModel_NodesChanged); + _innerModel.NodesInserted += new EventHandler(_innerModel_NodesInserted); + _innerModel.NodesRemoved += new EventHandler(_innerModel_NodesRemoved); + _innerModel.StructureChanged += new EventHandler(_innerModel_StructureChanged); + } + + void _innerModel_StructureChanged(object sender, TreePathEventArgs e) + { + OnStructureChanged(e); + } + + void _innerModel_NodesRemoved(object sender, TreeModelEventArgs e) + { + OnStructureChanged(new TreePathEventArgs(e.Path)); + } + + void _innerModel_NodesInserted(object sender, TreeModelEventArgs e) + { + OnStructureChanged(new TreePathEventArgs(e.Path)); + } + + void _innerModel_NodesChanged(object sender, TreeModelEventArgs e) + { + OnStructureChanged(new TreePathEventArgs(e.Path)); + } + + public override IEnumerable GetChildren(TreePath treePath) + { + if (Comparer != null) + { + ArrayList list = new ArrayList(); + IEnumerable res = InnerModel.GetChildren(treePath); + if (res != null) + { + foreach (object obj in res) + list.Add(obj); + list.Sort(Comparer); + return list; + } + else + return null; + } + else + return InnerModel.GetChildren(treePath); + } + + public override bool IsLeaf(TreePath treePath) + { + return InnerModel.IsLeaf(treePath); + } + } +} diff --git a/External/Aga.Controls/Tree/TreeColumn.cs b/Aga.Controls/Tree/TreeColumn.cs similarity index 96% rename from External/Aga.Controls/Tree/TreeColumn.cs rename to Aga.Controls/Tree/TreeColumn.cs index bfa12c0..fcaf03d 100644 --- a/External/Aga.Controls/Tree/TreeColumn.cs +++ b/Aga.Controls/Tree/TreeColumn.cs @@ -1,371 +1,371 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel; -using System.Windows.Forms; -using System.Drawing; -using System.Windows.Forms.VisualStyles; -using System.Drawing.Imaging; - -namespace Aga.Controls.Tree -{ - [TypeConverter(typeof(TreeColumn.TreeColumnConverter)), DesignTimeVisible(false), ToolboxItem(false)] - public class TreeColumn : Component - { - private class TreeColumnConverter : ComponentConverter - { - public TreeColumnConverter() - : base(typeof(TreeColumn)) - { - } - - public override bool GetPropertiesSupported(ITypeDescriptorContext context) - { - return false; - } - } - - private const int HeaderLeftMargin = 5; - private const int HeaderRightMargin = 5; - private const int SortOrderMarkMargin = 8; - - private TextFormatFlags _headerFlags; - private TextFormatFlags _baseHeaderFlags = TextFormatFlags.NoPadding | - TextFormatFlags.EndEllipsis | - TextFormatFlags.VerticalCenter | - TextFormatFlags.PreserveGraphicsTranslateTransform; - - #region Properties - - private TreeColumnCollection _owner; - internal TreeColumnCollection Owner - { - get { return _owner; } - set { _owner = value; } - } - - [Browsable(false)] - public int Index - { - get - { - if (Owner != null) - return Owner.IndexOf(this); - else - return -1; - } - } - - private string _header; - [Localizable(true)] - public string Header - { - get { return _header; } - set - { - _header = value; - OnHeaderChanged(); - } - } - - private string _tooltipText; - [Localizable(true)] - public string TooltipText - { - get { return _tooltipText; } - set { _tooltipText = value; } - } - - private int _width; - [DefaultValue(50), Localizable(true)] - public int Width - { - get - { - return _width; - } - set - { - if (_width != value) - { - _width = Math.Max(MinColumnWidth, value); - if (_maxColumnWidth > 0) - { - _width = Math.Min(_width, MaxColumnWidth); - } - OnWidthChanged(); - } - } - } - - private int _minColumnWidth; - [DefaultValue(0)] - public int MinColumnWidth - { - get { return _minColumnWidth; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException("value"); - - _minColumnWidth = value; - Width = Math.Max(value, Width); - } - } - - private int _maxColumnWidth; - [DefaultValue(0)] - public int MaxColumnWidth - { - get { return _maxColumnWidth; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException("value"); - - _maxColumnWidth = value; - if (value > 0) - Width = Math.Min(value, _width); - } - } - - private bool _visible = true; - [DefaultValue(true)] - public bool IsVisible - { - get { return _visible; } - set - { - _visible = value; - OnIsVisibleChanged(); - } - } - - private HorizontalAlignment _textAlign = HorizontalAlignment.Left; - [DefaultValue(HorizontalAlignment.Left)] - public HorizontalAlignment TextAlign - { - get { return _textAlign; } - set - { - if (value != _textAlign) - { - _textAlign = value; - _headerFlags = _baseHeaderFlags | TextHelper.TranslateAligmentToFlag(value); - OnHeaderChanged(); - } - } - } - - private bool _sortable = false; - [DefaultValue(false)] - public bool Sortable - { - get { return _sortable; } - set { _sortable = value; } - } - - private SortOrder _sort_order = SortOrder.None; - public SortOrder SortOrder - { - get { return _sort_order; } - set - { - if (value == _sort_order) - return; - _sort_order = value; - OnSortOrderChanged(); - } - } - - public Size SortMarkSize - { - get - { - if (Application.RenderWithVisualStyles) - return new Size(9, 5); - else - return new Size(7, 4); - } - } - #endregion - - public TreeColumn(): - this(string.Empty, 50) - { - } - - public TreeColumn(string header, int width) - { - _header = header; - _width = width; - _headerFlags = _baseHeaderFlags | TextFormatFlags.Left; - } - - public override string ToString() - { - if (string.IsNullOrEmpty(Header)) - return GetType().Name; - else - return Header; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - } - - #region Draw - - private static VisualStyleRenderer _normalRenderer; - private static VisualStyleRenderer _pressedRenderer; - private static VisualStyleRenderer _hotRenderer; - - private static void CreateRenderers() - { - if (Application.RenderWithVisualStyles && _normalRenderer == null) - { - _normalRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Normal); - _pressedRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Pressed); - _hotRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Hot); - } - } - - internal Bitmap CreateGhostImage(Rectangle bounds, Font font) - { - Bitmap b = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); - Graphics gr = Graphics.FromImage(b); - gr.FillRectangle(SystemBrushes.ControlDark, bounds); - DrawContent(gr, bounds, font); - BitmapHelper.SetAlphaChanelValue(b, 150); - return b; - } - - internal void Draw(Graphics gr, Rectangle bounds, Font font, bool pressed, bool hot) - { - DrawBackground(gr, bounds, pressed, hot); - DrawContent(gr, bounds, font); - } - - private void DrawContent(Graphics gr, Rectangle bounds, Font font) - { - Rectangle innerBounds = new Rectangle(bounds.X + HeaderLeftMargin, bounds.Y, - bounds.Width - HeaderLeftMargin - HeaderRightMargin, - bounds.Height); - - if (SortOrder != SortOrder.None) - innerBounds.Width -= (SortMarkSize.Width + SortOrderMarkMargin); - - Size maxTextSize = TextRenderer.MeasureText(gr, Header, font, innerBounds.Size, TextFormatFlags.NoPadding); - Size textSize = TextRenderer.MeasureText(gr, Header, font, innerBounds.Size, _baseHeaderFlags); - - if (SortOrder != SortOrder.None) - { - int tw = Math.Min(textSize.Width, innerBounds.Size.Width); - - int x = 0; - if (TextAlign == HorizontalAlignment.Left) - x = innerBounds.X + tw + SortOrderMarkMargin; - else if (TextAlign == HorizontalAlignment.Right) - x = innerBounds.Right + SortOrderMarkMargin; - else - x = innerBounds.X + tw + (innerBounds.Width - tw) / 2 + SortOrderMarkMargin; - DrawSortMark(gr, bounds, x); - } - - if (textSize.Width < maxTextSize.Width) - TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _baseHeaderFlags | TextFormatFlags.Left); - else - TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _headerFlags); - } - - private void DrawSortMark(Graphics gr, Rectangle bounds, int x) - { - int y = bounds.Y + bounds.Height / 2 - 2; - x = Math.Max(x, bounds.X + SortOrderMarkMargin); - - int w2 = SortMarkSize.Width / 2; - if (SortOrder == SortOrder.Ascending) - { - Point[] points = new Point[] { new Point(x, y), new Point(x + SortMarkSize.Width, y), new Point(x + w2, y + SortMarkSize.Height) }; - gr.FillPolygon(SystemBrushes.ControlDark, points); - } - else if (SortOrder == SortOrder.Descending) - { - Point[] points = new Point[] { new Point(x - 1, y + SortMarkSize.Height), new Point(x + SortMarkSize.Width, y + SortMarkSize.Height), new Point(x + w2, y - 1) }; - gr.FillPolygon(SystemBrushes.ControlDark, points); - } - } - - internal static void DrawDropMark(Graphics gr, Rectangle rect) - { - gr.FillRectangle(SystemBrushes.HotTrack, rect.X-1, rect.Y, 2, rect.Height); - } - - internal static void DrawBackground(Graphics gr, Rectangle bounds, bool pressed, bool hot) - { - if (Application.RenderWithVisualStyles) - { - CreateRenderers(); - if (pressed) - _pressedRenderer.DrawBackground(gr, bounds); - else if (hot) - _hotRenderer.DrawBackground(gr, bounds); - else - _normalRenderer.DrawBackground(gr, bounds); - } - else - { - gr.FillRectangle(SystemBrushes.Control, bounds); - Pen p1 = SystemPens.ControlLightLight; - Pen p2 = SystemPens.ControlDark; - Pen p3 = SystemPens.ControlDarkDark; - if (pressed) - gr.DrawRectangle(p2, bounds.X, bounds.Y, bounds.Width, bounds.Height); - else - { - gr.DrawLine(p1, bounds.X, bounds.Y, bounds.Right, bounds.Y); - gr.DrawLine(p3, bounds.X, bounds.Bottom, bounds.Right, bounds.Bottom); - gr.DrawLine(p3, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1); - gr.DrawLine(p1, bounds.Left, bounds.Y + 1, bounds.Left, bounds.Bottom - 2); - gr.DrawLine(p2, bounds.Right - 2, bounds.Y + 1, bounds.Right - 2, bounds.Bottom - 2); - gr.DrawLine(p2, bounds.X, bounds.Bottom - 1, bounds.Right - 2, bounds.Bottom - 1); - } - } - } - - #endregion - - #region Events - - public event EventHandler HeaderChanged; - private void OnHeaderChanged() - { - if (HeaderChanged != null) - HeaderChanged(this, EventArgs.Empty); - } - - public event EventHandler SortOrderChanged; - private void OnSortOrderChanged() - { - if (SortOrderChanged != null) - SortOrderChanged(this, EventArgs.Empty); - } - - public event EventHandler IsVisibleChanged; - private void OnIsVisibleChanged() - { - if (IsVisibleChanged != null) - IsVisibleChanged(this, EventArgs.Empty); - } - - public event EventHandler WidthChanged; - private void OnWidthChanged() - { - if (WidthChanged != null) - WidthChanged(this, EventArgs.Empty); - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; +using System.Windows.Forms; +using System.Drawing; +using System.Windows.Forms.VisualStyles; +using System.Drawing.Imaging; + +namespace Aga.Controls.Tree +{ + [TypeConverter(typeof(TreeColumn.TreeColumnConverter)), DesignTimeVisible(false), ToolboxItem(false)] + public class TreeColumn : Component + { + private class TreeColumnConverter : ComponentConverter + { + public TreeColumnConverter() + : base(typeof(TreeColumn)) + { + } + + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { + return false; + } + } + + private const int HeaderLeftMargin = 5; + private const int HeaderRightMargin = 5; + private const int SortOrderMarkMargin = 8; + + private TextFormatFlags _headerFlags; + private TextFormatFlags _baseHeaderFlags = TextFormatFlags.NoPadding | + TextFormatFlags.EndEllipsis | + TextFormatFlags.VerticalCenter | + TextFormatFlags.PreserveGraphicsTranslateTransform; + + #region Properties + + private TreeColumnCollection _owner; + internal TreeColumnCollection Owner + { + get { return _owner; } + set { _owner = value; } + } + + [Browsable(false)] + public int Index + { + get + { + if (Owner != null) + return Owner.IndexOf(this); + else + return -1; + } + } + + private string _header; + [Localizable(true)] + public string Header + { + get { return _header; } + set + { + _header = value; + OnHeaderChanged(); + } + } + + private string _tooltipText; + [Localizable(true)] + public string TooltipText + { + get { return _tooltipText; } + set { _tooltipText = value; } + } + + private int _width; + [DefaultValue(50), Localizable(true)] + public int Width + { + get + { + return _width; + } + set + { + if (_width != value) + { + _width = Math.Max(MinColumnWidth, value); + if (_maxColumnWidth > 0) + { + _width = Math.Min(_width, MaxColumnWidth); + } + OnWidthChanged(); + } + } + } + + private int _minColumnWidth; + [DefaultValue(0)] + public int MinColumnWidth + { + get { return _minColumnWidth; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException("value"); + + _minColumnWidth = value; + Width = Math.Max(value, Width); + } + } + + private int _maxColumnWidth; + [DefaultValue(0)] + public int MaxColumnWidth + { + get { return _maxColumnWidth; } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException("value"); + + _maxColumnWidth = value; + if (value > 0) + Width = Math.Min(value, _width); + } + } + + private bool _visible = true; + [DefaultValue(true)] + public bool IsVisible + { + get { return _visible; } + set + { + _visible = value; + OnIsVisibleChanged(); + } + } + + private HorizontalAlignment _textAlign = HorizontalAlignment.Left; + [DefaultValue(HorizontalAlignment.Left)] + public HorizontalAlignment TextAlign + { + get { return _textAlign; } + set + { + if (value != _textAlign) + { + _textAlign = value; + _headerFlags = _baseHeaderFlags | TextHelper.TranslateAligmentToFlag(value); + OnHeaderChanged(); + } + } + } + + private bool _sortable = false; + [DefaultValue(false)] + public bool Sortable + { + get { return _sortable; } + set { _sortable = value; } + } + + private SortOrder _sort_order = SortOrder.None; + public SortOrder SortOrder + { + get { return _sort_order; } + set + { + if (value == _sort_order) + return; + _sort_order = value; + OnSortOrderChanged(); + } + } + + public Size SortMarkSize + { + get + { + if (Application.RenderWithVisualStyles) + return new Size(9, 5); + else + return new Size(7, 4); + } + } + #endregion + + public TreeColumn(): + this(string.Empty, 50) + { + } + + public TreeColumn(string header, int width) + { + _header = header; + _width = width; + _headerFlags = _baseHeaderFlags | TextFormatFlags.Left; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Header)) + return GetType().Name; + else + return Header; + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + } + + #region Draw + + private static VisualStyleRenderer _normalRenderer; + private static VisualStyleRenderer _pressedRenderer; + private static VisualStyleRenderer _hotRenderer; + + private static void CreateRenderers() + { + if (Application.RenderWithVisualStyles && _normalRenderer == null) + { + _normalRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Normal); + _pressedRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Pressed); + _hotRenderer = new VisualStyleRenderer(VisualStyleElement.Header.Item.Hot); + } + } + + internal Bitmap CreateGhostImage(Rectangle bounds, Font font) + { + Bitmap b = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); + Graphics gr = Graphics.FromImage(b); + gr.FillRectangle(SystemBrushes.ControlDark, bounds); + DrawContent(gr, bounds, font); + BitmapHelper.SetAlphaChanelValue(b, 150); + return b; + } + + internal void Draw(Graphics gr, Rectangle bounds, Font font, bool pressed, bool hot) + { + DrawBackground(gr, bounds, pressed, hot); + DrawContent(gr, bounds, font); + } + + private void DrawContent(Graphics gr, Rectangle bounds, Font font) + { + Rectangle innerBounds = new Rectangle(bounds.X + HeaderLeftMargin, bounds.Y, + bounds.Width - HeaderLeftMargin - HeaderRightMargin, + bounds.Height); + + if (SortOrder != SortOrder.None) + innerBounds.Width -= (SortMarkSize.Width + SortOrderMarkMargin); + + Size maxTextSize = TextRenderer.MeasureText(gr, Header, font, innerBounds.Size, TextFormatFlags.NoPadding); + Size textSize = TextRenderer.MeasureText(gr, Header, font, innerBounds.Size, _baseHeaderFlags); + + if (SortOrder != SortOrder.None) + { + int tw = Math.Min(textSize.Width, innerBounds.Size.Width); + + int x = 0; + if (TextAlign == HorizontalAlignment.Left) + x = innerBounds.X + tw + SortOrderMarkMargin; + else if (TextAlign == HorizontalAlignment.Right) + x = innerBounds.Right + SortOrderMarkMargin; + else + x = innerBounds.X + tw + (innerBounds.Width - tw) / 2 + SortOrderMarkMargin; + DrawSortMark(gr, bounds, x); + } + + if (textSize.Width < maxTextSize.Width) + TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _baseHeaderFlags | TextFormatFlags.Left); + else + TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _headerFlags); + } + + private void DrawSortMark(Graphics gr, Rectangle bounds, int x) + { + int y = bounds.Y + bounds.Height / 2 - 2; + x = Math.Max(x, bounds.X + SortOrderMarkMargin); + + int w2 = SortMarkSize.Width / 2; + if (SortOrder == SortOrder.Ascending) + { + Point[] points = new Point[] { new Point(x, y), new Point(x + SortMarkSize.Width, y), new Point(x + w2, y + SortMarkSize.Height) }; + gr.FillPolygon(SystemBrushes.ControlDark, points); + } + else if (SortOrder == SortOrder.Descending) + { + Point[] points = new Point[] { new Point(x - 1, y + SortMarkSize.Height), new Point(x + SortMarkSize.Width, y + SortMarkSize.Height), new Point(x + w2, y - 1) }; + gr.FillPolygon(SystemBrushes.ControlDark, points); + } + } + + internal static void DrawDropMark(Graphics gr, Rectangle rect) + { + gr.FillRectangle(SystemBrushes.HotTrack, rect.X-1, rect.Y, 2, rect.Height); + } + + internal static void DrawBackground(Graphics gr, Rectangle bounds, bool pressed, bool hot) + { + if (Application.RenderWithVisualStyles) + { + CreateRenderers(); + if (pressed) + _pressedRenderer.DrawBackground(gr, bounds); + else if (hot) + _hotRenderer.DrawBackground(gr, bounds); + else + _normalRenderer.DrawBackground(gr, bounds); + } + else + { + gr.FillRectangle(SystemBrushes.Control, bounds); + Pen p1 = SystemPens.ControlLightLight; + Pen p2 = SystemPens.ControlDark; + Pen p3 = SystemPens.ControlDarkDark; + if (pressed) + gr.DrawRectangle(p2, bounds.X, bounds.Y, bounds.Width, bounds.Height); + else + { + gr.DrawLine(p1, bounds.X, bounds.Y, bounds.Right, bounds.Y); + gr.DrawLine(p3, bounds.X, bounds.Bottom, bounds.Right, bounds.Bottom); + gr.DrawLine(p3, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1); + gr.DrawLine(p1, bounds.Left, bounds.Y + 1, bounds.Left, bounds.Bottom - 2); + gr.DrawLine(p2, bounds.Right - 2, bounds.Y + 1, bounds.Right - 2, bounds.Bottom - 2); + gr.DrawLine(p2, bounds.X, bounds.Bottom - 1, bounds.Right - 2, bounds.Bottom - 1); + } + } + } + + #endregion + + #region Events + + public event EventHandler HeaderChanged; + private void OnHeaderChanged() + { + if (HeaderChanged != null) + HeaderChanged(this, EventArgs.Empty); + } + + public event EventHandler SortOrderChanged; + private void OnSortOrderChanged() + { + if (SortOrderChanged != null) + SortOrderChanged(this, EventArgs.Empty); + } + + public event EventHandler IsVisibleChanged; + private void OnIsVisibleChanged() + { + if (IsVisibleChanged != null) + IsVisibleChanged(this, EventArgs.Empty); + } + + public event EventHandler WidthChanged; + private void OnWidthChanged() + { + if (WidthChanged != null) + WidthChanged(this, EventArgs.Empty); + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeColumnCollection.cs b/Aga.Controls/Tree/TreeColumnCollection.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeColumnCollection.cs rename to Aga.Controls/Tree/TreeColumnCollection.cs index e6fab40..2368ec6 100644 --- a/External/Aga.Controls/Tree/TreeColumnCollection.cs +++ b/Aga.Controls/Tree/TreeColumnCollection.cs @@ -1,98 +1,98 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Windows.Forms; - -namespace Aga.Controls.Tree -{ - internal class TreeColumnCollection : Collection - { - private TreeViewAdv _treeView; - - public TreeColumnCollection(TreeViewAdv treeView) - { - _treeView = treeView; - } - - protected override void InsertItem(int index, TreeColumn item) - { - base.InsertItem(index, item); - BindEvents(item); - _treeView.UpdateColumns(); - } - - protected override void RemoveItem(int index) - { - UnbindEvents(this[index]); - base.RemoveItem(index); - _treeView.UpdateColumns(); - } - - protected override void SetItem(int index, TreeColumn item) - { - UnbindEvents(this[index]); - base.SetItem(index, item); - item.Owner = this; - BindEvents(item); - _treeView.UpdateColumns(); - } - - protected override void ClearItems() - { - foreach (TreeColumn c in Items) - UnbindEvents(c); - Items.Clear(); - _treeView.UpdateColumns(); - } - - private void BindEvents(TreeColumn item) - { - item.Owner = this; - item.HeaderChanged += HeaderChanged; - item.IsVisibleChanged += IsVisibleChanged; - item.WidthChanged += WidthChanged; - item.SortOrderChanged += SortOrderChanged; - } - - private void UnbindEvents(TreeColumn item) - { - item.Owner = null; - item.HeaderChanged -= HeaderChanged; - item.IsVisibleChanged -= IsVisibleChanged; - item.WidthChanged -= WidthChanged; - item.SortOrderChanged -= SortOrderChanged; - } - - void SortOrderChanged(object sender, EventArgs e) - { - TreeColumn changed = sender as TreeColumn; - //Only one column at a time can have a sort property set - if (changed.SortOrder != SortOrder.None) - { - foreach (TreeColumn col in this) - { - if (col != changed) - col.SortOrder = SortOrder.None; - } - } - _treeView.UpdateHeaders(); - } - - void WidthChanged(object sender, EventArgs e) - { - _treeView.ChangeColumnWidth(sender as TreeColumn); - } - - void IsVisibleChanged(object sender, EventArgs e) - { - _treeView.FullUpdate(); - } - - void HeaderChanged(object sender, EventArgs e) - { - _treeView.UpdateView(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + internal class TreeColumnCollection : Collection + { + private TreeViewAdv _treeView; + + public TreeColumnCollection(TreeViewAdv treeView) + { + _treeView = treeView; + } + + protected override void InsertItem(int index, TreeColumn item) + { + base.InsertItem(index, item); + BindEvents(item); + _treeView.UpdateColumns(); + } + + protected override void RemoveItem(int index) + { + UnbindEvents(this[index]); + base.RemoveItem(index); + _treeView.UpdateColumns(); + } + + protected override void SetItem(int index, TreeColumn item) + { + UnbindEvents(this[index]); + base.SetItem(index, item); + item.Owner = this; + BindEvents(item); + _treeView.UpdateColumns(); + } + + protected override void ClearItems() + { + foreach (TreeColumn c in Items) + UnbindEvents(c); + Items.Clear(); + _treeView.UpdateColumns(); + } + + private void BindEvents(TreeColumn item) + { + item.Owner = this; + item.HeaderChanged += HeaderChanged; + item.IsVisibleChanged += IsVisibleChanged; + item.WidthChanged += WidthChanged; + item.SortOrderChanged += SortOrderChanged; + } + + private void UnbindEvents(TreeColumn item) + { + item.Owner = null; + item.HeaderChanged -= HeaderChanged; + item.IsVisibleChanged -= IsVisibleChanged; + item.WidthChanged -= WidthChanged; + item.SortOrderChanged -= SortOrderChanged; + } + + void SortOrderChanged(object sender, EventArgs e) + { + TreeColumn changed = sender as TreeColumn; + //Only one column at a time can have a sort property set + if (changed.SortOrder != SortOrder.None) + { + foreach (TreeColumn col in this) + { + if (col != changed) + col.SortOrder = SortOrder.None; + } + } + _treeView.UpdateHeaders(); + } + + void WidthChanged(object sender, EventArgs e) + { + _treeView.ChangeColumnWidth(sender as TreeColumn); + } + + void IsVisibleChanged(object sender, EventArgs e) + { + _treeView.FullUpdate(); + } + + void HeaderChanged(object sender, EventArgs e) + { + _treeView.UpdateView(); + } + } +} diff --git a/External/Aga.Controls/Tree/TreeColumnEventArgs.cs b/Aga.Controls/Tree/TreeColumnEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/TreeColumnEventArgs.cs rename to Aga.Controls/Tree/TreeColumnEventArgs.cs index 0c616a0..405c707 100644 --- a/External/Aga.Controls/Tree/TreeColumnEventArgs.cs +++ b/Aga.Controls/Tree/TreeColumnEventArgs.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public class TreeColumnEventArgs: EventArgs - { - private TreeColumn _column; - public TreeColumn Column - { - get { return _column; } - } - - public TreeColumnEventArgs(TreeColumn column) - { - _column = column; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public class TreeColumnEventArgs: EventArgs + { + private TreeColumn _column; + public TreeColumn Column + { + get { return _column; } + } + + public TreeColumnEventArgs(TreeColumn column) + { + _column = column; + } + } +} diff --git a/External/Aga.Controls/Tree/TreeListAdapter.cs b/Aga.Controls/Tree/TreeListAdapter.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeListAdapter.cs rename to Aga.Controls/Tree/TreeListAdapter.cs index f53a5d3..819e568 100644 --- a/External/Aga.Controls/Tree/TreeListAdapter.cs +++ b/Aga.Controls/Tree/TreeListAdapter.cs @@ -1,65 +1,65 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - /// - /// Converts IEnumerable interface to ITreeModel. - /// Allows to display a plain list in the TreeView - /// - public class TreeListAdapter : ITreeModel - { - private System.Collections.IEnumerable _list; - - public TreeListAdapter(System.Collections.IEnumerable list) - { - _list = list; - } - - #region ITreeModel Members - - public System.Collections.IEnumerable GetChildren(TreePath treePath) - { - if (treePath.IsEmpty()) - return _list; - else - return null; - } - - public bool IsLeaf(TreePath treePath) - { - return true; - } - - public event EventHandler NodesChanged; - public void OnNodesChanged(TreeModelEventArgs args) - { - if (NodesChanged != null) - NodesChanged(this, args); - } - - public event EventHandler StructureChanged; - public void OnStructureChanged(TreePathEventArgs args) - { - if (StructureChanged != null) - StructureChanged(this, args); - } - - public event EventHandler NodesInserted; - public void OnNodeInserted(TreeModelEventArgs args) - { - if (NodesInserted != null) - NodesInserted(this, args); - } - - public event EventHandler NodesRemoved; - public void OnNodeRemoved(TreeModelEventArgs args) - { - if (NodesRemoved != null) - NodesRemoved(this, args); - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + /// + /// Converts IEnumerable interface to ITreeModel. + /// Allows to display a plain list in the TreeView + /// + public class TreeListAdapter : ITreeModel + { + private System.Collections.IEnumerable _list; + + public TreeListAdapter(System.Collections.IEnumerable list) + { + _list = list; + } + + #region ITreeModel Members + + public System.Collections.IEnumerable GetChildren(TreePath treePath) + { + if (treePath.IsEmpty()) + return _list; + else + return null; + } + + public bool IsLeaf(TreePath treePath) + { + return true; + } + + public event EventHandler NodesChanged; + public void OnNodesChanged(TreeModelEventArgs args) + { + if (NodesChanged != null) + NodesChanged(this, args); + } + + public event EventHandler StructureChanged; + public void OnStructureChanged(TreePathEventArgs args) + { + if (StructureChanged != null) + StructureChanged(this, args); + } + + public event EventHandler NodesInserted; + public void OnNodeInserted(TreeModelEventArgs args) + { + if (NodesInserted != null) + NodesInserted(this, args); + } + + public event EventHandler NodesRemoved; + public void OnNodeRemoved(TreeModelEventArgs args) + { + if (NodesRemoved != null) + NodesRemoved(this, args); + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeModel.cs b/Aga.Controls/Tree/TreeModel.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeModel.cs rename to Aga.Controls/Tree/TreeModel.cs index 12a533f..14ef857 100644 --- a/External/Aga.Controls/Tree/TreeModel.cs +++ b/Aga.Controls/Tree/TreeModel.cs @@ -1,127 +1,127 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections.ObjectModel; - -namespace Aga.Controls.Tree -{ - /// - /// Provides a simple ready to use implementation of . Warning: this class is not optimized - /// to work with big amount of data. In this case create you own implementation of ITreeModel, and pay attention - /// on GetChildren and IsLeaf methods. - /// - public class TreeModel : ITreeModel - { - private Node _root; - public Node Root - { - get { return _root; } - } - - public Collection Nodes - { - get { return _root.Nodes; } - } - - public TreeModel() - { - _root = new Node(); - _root.Model = this; - } - - public TreePath GetPath(Node node) - { - if (node == _root) - return TreePath.Empty; - else - { - Stack stack = new Stack(); - while (node != _root) - { - stack.Push(node); - node = node.Parent; - } - return new TreePath(stack.ToArray()); - } - } - - public Node FindNode(TreePath path) - { - if (path.IsEmpty()) - return _root; - else - return FindNode(_root, path, 0); - } - - private Node FindNode(Node root, TreePath path, int level) - { - foreach (Node node in root.Nodes) - if (node == path.FullPath[level]) - { - if (level == path.FullPath.Length - 1) - return node; - else - return FindNode(node, path, level + 1); - } - return null; - } - - #region ITreeModel Members - - public System.Collections.IEnumerable GetChildren(TreePath treePath) - { - Node node = FindNode(treePath); - if (node != null) - foreach (Node n in node.Nodes) - yield return n; - else - yield break; - } - - public bool IsLeaf(TreePath treePath) - { - Node node = FindNode(treePath); - if (node != null) - return node.IsLeaf; - else - throw new ArgumentException("treePath"); - } - - public event EventHandler NodesChanged; - internal void OnNodesChanged(TreeModelEventArgs args) - { - if (NodesChanged != null) - NodesChanged(this, args); - } - - public event EventHandler StructureChanged; - public void OnStructureChanged(TreePathEventArgs args) - { - if (StructureChanged != null) - StructureChanged(this, args); - } - - public event EventHandler NodesInserted; - internal void OnNodeInserted(Node parent, int index, Node node) - { - if (NodesInserted != null) - { - TreeModelEventArgs args = new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node }); - NodesInserted(this, args); - } - - } - - public event EventHandler NodesRemoved; - internal void OnNodeRemoved(Node parent, int index, Node node) - { - if (NodesRemoved != null) - { - TreeModelEventArgs args = new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node }); - NodesRemoved(this, args); - } - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; + +namespace Aga.Controls.Tree +{ + /// + /// Provides a simple ready to use implementation of . Warning: this class is not optimized + /// to work with big amount of data. In this case create you own implementation of ITreeModel, and pay attention + /// on GetChildren and IsLeaf methods. + /// + public class TreeModel : ITreeModel + { + private Node _root; + public Node Root + { + get { return _root; } + } + + public Collection Nodes + { + get { return _root.Nodes; } + } + + public TreeModel() + { + _root = new Node(); + _root.Model = this; + } + + public TreePath GetPath(Node node) + { + if (node == _root) + return TreePath.Empty; + else + { + Stack stack = new Stack(); + while (node != _root) + { + stack.Push(node); + node = node.Parent; + } + return new TreePath(stack.ToArray()); + } + } + + public Node FindNode(TreePath path) + { + if (path.IsEmpty()) + return _root; + else + return FindNode(_root, path, 0); + } + + private Node FindNode(Node root, TreePath path, int level) + { + foreach (Node node in root.Nodes) + if (node == path.FullPath[level]) + { + if (level == path.FullPath.Length - 1) + return node; + else + return FindNode(node, path, level + 1); + } + return null; + } + + #region ITreeModel Members + + public System.Collections.IEnumerable GetChildren(TreePath treePath) + { + Node node = FindNode(treePath); + if (node != null) + foreach (Node n in node.Nodes) + yield return n; + else + yield break; + } + + public bool IsLeaf(TreePath treePath) + { + Node node = FindNode(treePath); + if (node != null) + return node.IsLeaf; + else + throw new ArgumentException("treePath"); + } + + public event EventHandler NodesChanged; + internal void OnNodesChanged(TreeModelEventArgs args) + { + if (NodesChanged != null) + NodesChanged(this, args); + } + + public event EventHandler StructureChanged; + public void OnStructureChanged(TreePathEventArgs args) + { + if (StructureChanged != null) + StructureChanged(this, args); + } + + public event EventHandler NodesInserted; + internal void OnNodeInserted(Node parent, int index, Node node) + { + if (NodesInserted != null) + { + TreeModelEventArgs args = new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node }); + NodesInserted(this, args); + } + + } + + public event EventHandler NodesRemoved; + internal void OnNodeRemoved(Node parent, int index, Node node) + { + if (NodesRemoved != null) + { + TreeModelEventArgs args = new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node }); + NodesRemoved(this, args); + } + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeModelBase.cs b/Aga.Controls/Tree/TreeModelBase.cs similarity index 96% rename from External/Aga.Controls/Tree/TreeModelBase.cs rename to Aga.Controls/Tree/TreeModelBase.cs index bb4a002..a366295 100644 --- a/External/Aga.Controls/Tree/TreeModelBase.cs +++ b/Aga.Controls/Tree/TreeModelBase.cs @@ -1,46 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public abstract class TreeModelBase: ITreeModel - { - public abstract System.Collections.IEnumerable GetChildren(TreePath treePath); - public abstract bool IsLeaf(TreePath treePath); - - - public event EventHandler NodesChanged; - protected void OnNodesChanged(TreeModelEventArgs args) - { - if (NodesChanged != null) - NodesChanged(this, args); - } - - public event EventHandler StructureChanged; - protected void OnStructureChanged(TreePathEventArgs args) - { - if (StructureChanged != null) - StructureChanged(this, args); - } - - public event EventHandler NodesInserted; - protected void OnNodesInserted(TreeModelEventArgs args) - { - if (NodesInserted != null) - NodesInserted(this, args); - } - - public event EventHandler NodesRemoved; - protected void OnNodesRemoved(TreeModelEventArgs args) - { - if (NodesRemoved != null) - NodesRemoved(this, args); - } - - public virtual void Refresh() - { - OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public abstract class TreeModelBase: ITreeModel + { + public abstract System.Collections.IEnumerable GetChildren(TreePath treePath); + public abstract bool IsLeaf(TreePath treePath); + + + public event EventHandler NodesChanged; + protected void OnNodesChanged(TreeModelEventArgs args) + { + if (NodesChanged != null) + NodesChanged(this, args); + } + + public event EventHandler StructureChanged; + protected void OnStructureChanged(TreePathEventArgs args) + { + if (StructureChanged != null) + StructureChanged(this, args); + } + + public event EventHandler NodesInserted; + protected void OnNodesInserted(TreeModelEventArgs args) + { + if (NodesInserted != null) + NodesInserted(this, args); + } + + public event EventHandler NodesRemoved; + protected void OnNodesRemoved(TreeModelEventArgs args) + { + if (NodesRemoved != null) + NodesRemoved(this, args); + } + + public virtual void Refresh() + { + OnStructureChanged(new TreePathEventArgs(TreePath.Empty)); + } + } +} diff --git a/External/Aga.Controls/Tree/TreeModelEventArgs.cs b/Aga.Controls/Tree/TreeModelEventArgs.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeModelEventArgs.cs rename to Aga.Controls/Tree/TreeModelEventArgs.cs index f8abe40..5148e63 100644 --- a/External/Aga.Controls/Tree/TreeModelEventArgs.cs +++ b/Aga.Controls/Tree/TreeModelEventArgs.cs @@ -1,50 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public class TreeModelEventArgs: TreePathEventArgs - { - private object[] _children; - public object[] Children - { - get { return _children; } - } - - private int[] _indices; - public int[] Indices - { - get { return _indices; } - } - - /// - /// - /// - /// Path to a parent node - /// Child nodes - public TreeModelEventArgs(TreePath parent, object[] children) - : this(parent, null, children) - { - } - - /// - /// - /// - /// Path to a parent node - /// Indices of children in parent nodes collection - /// Child nodes - public TreeModelEventArgs(TreePath parent, int[] indices, object[] children) - : base(parent) - { - if (children == null) - throw new ArgumentNullException(); - - if (indices != null && indices.Length != children.Length) - throw new ArgumentException("indices and children arrays must have the same length"); - - _indices = indices; - _children = children; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public class TreeModelEventArgs: TreePathEventArgs + { + private object[] _children; + public object[] Children + { + get { return _children; } + } + + private int[] _indices; + public int[] Indices + { + get { return _indices; } + } + + /// + /// + /// + /// Path to a parent node + /// Child nodes + public TreeModelEventArgs(TreePath parent, object[] children) + : this(parent, null, children) + { + } + + /// + /// + /// + /// Path to a parent node + /// Indices of children in parent nodes collection + /// Child nodes + public TreeModelEventArgs(TreePath parent, int[] indices, object[] children) + : base(parent) + { + if (children == null) + throw new ArgumentNullException(); + + if (indices != null && indices.Length != children.Length) + throw new ArgumentException("indices and children arrays must have the same length"); + + _indices = indices; + _children = children; + } + } +} diff --git a/External/Aga.Controls/Tree/TreeNodeAdv.cs b/Aga.Controls/Tree/TreeNodeAdv.cs similarity index 94% rename from External/Aga.Controls/Tree/TreeNodeAdv.cs rename to Aga.Controls/Tree/TreeNodeAdv.cs index b9dea86..c2c6668 100644 --- a/External/Aga.Controls/Tree/TreeNodeAdv.cs +++ b/Aga.Controls/Tree/TreeNodeAdv.cs @@ -1,443 +1,443 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using System.Security.Permissions; - -namespace Aga.Controls.Tree -{ - [Serializable] - public sealed class TreeNodeAdv : ISerializable - { - #region NodeCollection - private class NodeCollection : Collection - { - private TreeNodeAdv _owner; - - public NodeCollection(TreeNodeAdv owner) - { - _owner = owner; - } - - protected override void ClearItems() - { - while (this.Count != 0) - this.RemoveAt(this.Count - 1); - } - - protected override void InsertItem(int index, TreeNodeAdv item) - { - if (item == null) - throw new ArgumentNullException("item"); - - if (item.Parent != _owner) - { - if (item.Parent != null) - item.Parent.Nodes.Remove(item); - item._parent = _owner; - item._index = index; - for (int i = index; i < Count; i++) - this[i]._index++; - base.InsertItem(index, item); - } - - if (_owner.Tree != null && _owner.Tree.Model == null) - { - _owner.Tree.SmartFullUpdate(); - } - } - - protected override void RemoveItem(int index) - { - TreeNodeAdv item = this[index]; - item._parent = null; - item._index = -1; - for (int i = index + 1; i < Count; i++) - this[i]._index--; - base.RemoveItem(index); - - if (_owner.Tree != null && _owner.Tree.Model == null) - { - _owner.Tree.UpdateSelection(); - _owner.Tree.SmartFullUpdate(); - } - } - - protected override void SetItem(int index, TreeNodeAdv item) - { - if (item == null) - throw new ArgumentNullException("item"); - RemoveAt(index); - InsertItem(index, item); - } - } - #endregion - - #region Events - - public event EventHandler Collapsing; - internal void OnCollapsing() - { - if (Collapsing != null) - Collapsing(this, new TreeViewAdvEventArgs(this)); - } - - public event EventHandler Collapsed; - internal void OnCollapsed() - { - if (Collapsed != null) - Collapsed(this, new TreeViewAdvEventArgs(this)); - } - - public event EventHandler Expanding; - internal void OnExpanding() - { - if (Expanding != null) - Expanding(this, new TreeViewAdvEventArgs(this)); - } - - public event EventHandler Expanded; - internal void OnExpanded() - { - if (Expanded != null) - Expanded(this, new TreeViewAdvEventArgs(this)); - } - - #endregion - - #region Properties - - private TreeViewAdv _tree; - public TreeViewAdv Tree - { - get { return _tree; } - } - - private int _row; - public int Row - { - get { return _row; } - internal set { _row = value; } - } - - private int _index = -1; - public int Index - { - get - { - return _index; - } - } - - private bool _isSelected; - public bool IsSelected - { - get { return _isSelected; } - set - { - if (_isSelected != value) - { - if (Tree.IsMyNode(this)) - { - //_tree.OnSelectionChanging - if (value) - { - if (!_tree.Selection.Contains(this)) - _tree.Selection.Add(this); - - if (_tree.Selection.Count == 1) - _tree.CurrentNode = this; - } - else - _tree.Selection.Remove(this); - _tree.UpdateView(); - _tree.OnSelectionChanged(); - } - _isSelected = value; - } - } - } - - /// - /// Returns true if all parent nodes of this node are expanded. - /// - internal bool IsVisible - { - get - { - TreeNodeAdv node = _parent; - while (node != null) - { - if (!node.IsExpanded) - return false; - node = node.Parent; - } - return true; - } - } - - private bool _isLeaf; - public bool IsLeaf - { - get { return _isLeaf; } - internal set { _isLeaf = value; } - } - - private bool _isExpandedOnce; - public bool IsExpandedOnce - { - get { return _isExpandedOnce; } - internal set { _isExpandedOnce = value; } - } - - private bool _isExpanded; - public bool IsExpanded - { - get { return _isExpanded; } - set - { - if (value) - Expand(); - else - Collapse(); - } - } - - internal void AssignIsExpanded(bool value) - { - _isExpanded = value; - } - - private TreeNodeAdv _parent; - public TreeNodeAdv Parent - { - get { return _parent; } - } - - public int Level - { - get - { - if (_parent == null) - return 0; - else - return _parent.Level + 1; - } - } - - public TreeNodeAdv PreviousNode - { - get - { - if (_parent != null) - { - int index = Index; - if (index > 0) - return _parent.Nodes[index - 1]; - } - return null; - } - } - - public TreeNodeAdv NextNode - { - get - { - if (_parent != null) - { - int index = Index; - if (index < _parent.Nodes.Count - 1) - return _parent.Nodes[index + 1]; - } - return null; - } - } - - internal TreeNodeAdv BottomNode - { - get - { - TreeNodeAdv parent = this.Parent; - if (parent != null) - { - if (parent.NextNode != null) - return parent.NextNode; - else - return parent.BottomNode; - } - return null; - } - } - - internal TreeNodeAdv NextVisibleNode - { - get - { - if (IsExpanded && Nodes.Count > 0) - return Nodes[0]; - else - { - TreeNodeAdv nn = NextNode; - if (nn != null) - return nn; - else - return BottomNode; - } - } - } - - public bool CanExpand - { - get - { - return (Nodes.Count > 0 || (!IsExpandedOnce && !IsLeaf)); - } - } - - private object _tag; - public object Tag - { - get { return _tag; } - } - - private Collection _nodes; - internal Collection Nodes - { - get { return _nodes; } - } - - private ReadOnlyCollection _children; - public ReadOnlyCollection Children - { - get - { - return _children; - } - } - - private int? _rightBounds; - internal int? RightBounds - { - get { return _rightBounds; } - set { _rightBounds = value; } - } - - private int? _height; - internal int? Height - { - get { return _height; } - set { _height = value; } - } - - private bool _isExpandingNow; - internal bool IsExpandingNow - { - get { return _isExpandingNow; } - set { _isExpandingNow = value; } - } - - private bool _autoExpandOnStructureChanged = true; - public bool AutoExpandOnStructureChanged - { - get { return _autoExpandOnStructureChanged; } - set { _autoExpandOnStructureChanged = value; } - } - - #endregion - - public TreeNodeAdv(object tag) - : this(null, tag) - { - } - - internal TreeNodeAdv(TreeViewAdv tree, object tag) - { - _row = -1; - _tree = tree; - _nodes = new NodeCollection(this); - _children = new ReadOnlyCollection(_nodes); - _tag = tag; - } - - public override string ToString() - { - if (Tag != null) - return Tag.ToString(); - else - return base.ToString(); - } - - public void Collapse() - { - if (_isExpanded) - Collapse(true); - } - - public void CollapseAll() - { - Collapse(false); - } - - public void Collapse(bool ignoreChildren) - { - SetIsExpanded(false, ignoreChildren); - } - - public void Expand() - { - if (!_isExpanded) - Expand(true); - } - - public void ExpandAll() - { - Expand(false); - } - - public void Expand(bool ignoreChildren) - { - SetIsExpanded(true, ignoreChildren); - } - - private void SetIsExpanded(bool value, bool ignoreChildren) - { - if (Tree == null) - _isExpanded = value; - else - Tree.SetIsExpanded(this, value, ignoreChildren); - } - - #region ISerializable Members - - private TreeNodeAdv(SerializationInfo info, StreamingContext context) - : this(null, null) - { - int nodesCount = 0; - nodesCount = info.GetInt32("NodesCount"); - _isExpanded = info.GetBoolean("IsExpanded"); - _tag = info.GetValue("Tag", typeof(object)); - - for (int i = 0; i < nodesCount; i++) - { - TreeNodeAdv child = (TreeNodeAdv)info.GetValue("Child" + i, typeof(TreeNodeAdv)); - Nodes.Add(child); - } - - } - - [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("IsExpanded", IsExpanded); - info.AddValue("NodesCount", Nodes.Count); - if ((Tag != null) && Tag.GetType().IsSerializable) - info.AddValue("Tag", Tag, Tag.GetType()); - - for (int i = 0; i < Nodes.Count; i++) - info.AddValue("Child" + i, Nodes[i], typeof(TreeNodeAdv)); - - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using System.Security.Permissions; + +namespace Aga.Controls.Tree +{ + [Serializable] + public sealed class TreeNodeAdv : ISerializable + { + #region NodeCollection + private class NodeCollection : Collection + { + private TreeNodeAdv _owner; + + public NodeCollection(TreeNodeAdv owner) + { + _owner = owner; + } + + protected override void ClearItems() + { + while (this.Count != 0) + this.RemoveAt(this.Count - 1); + } + + protected override void InsertItem(int index, TreeNodeAdv item) + { + if (item == null) + throw new ArgumentNullException("item"); + + if (item.Parent != _owner) + { + if (item.Parent != null) + item.Parent.Nodes.Remove(item); + item._parent = _owner; + item._index = index; + for (int i = index; i < Count; i++) + this[i]._index++; + base.InsertItem(index, item); + } + + if (_owner.Tree != null && _owner.Tree.Model == null) + { + _owner.Tree.SmartFullUpdate(); + } + } + + protected override void RemoveItem(int index) + { + TreeNodeAdv item = this[index]; + item._parent = null; + item._index = -1; + for (int i = index + 1; i < Count; i++) + this[i]._index--; + base.RemoveItem(index); + + if (_owner.Tree != null && _owner.Tree.Model == null) + { + _owner.Tree.UpdateSelection(); + _owner.Tree.SmartFullUpdate(); + } + } + + protected override void SetItem(int index, TreeNodeAdv item) + { + if (item == null) + throw new ArgumentNullException("item"); + RemoveAt(index); + InsertItem(index, item); + } + } + #endregion + + #region Events + + public event EventHandler Collapsing; + internal void OnCollapsing() + { + if (Collapsing != null) + Collapsing(this, new TreeViewAdvEventArgs(this)); + } + + public event EventHandler Collapsed; + internal void OnCollapsed() + { + if (Collapsed != null) + Collapsed(this, new TreeViewAdvEventArgs(this)); + } + + public event EventHandler Expanding; + internal void OnExpanding() + { + if (Expanding != null) + Expanding(this, new TreeViewAdvEventArgs(this)); + } + + public event EventHandler Expanded; + internal void OnExpanded() + { + if (Expanded != null) + Expanded(this, new TreeViewAdvEventArgs(this)); + } + + #endregion + + #region Properties + + private TreeViewAdv _tree; + public TreeViewAdv Tree + { + get { return _tree; } + } + + private int _row; + public int Row + { + get { return _row; } + internal set { _row = value; } + } + + private int _index = -1; + public int Index + { + get + { + return _index; + } + } + + private bool _isSelected; + public bool IsSelected + { + get { return _isSelected; } + set + { + if (_isSelected != value) + { + if (Tree.IsMyNode(this)) + { + //_tree.OnSelectionChanging + if (value) + { + if (!_tree.Selection.Contains(this)) + _tree.Selection.Add(this); + + if (_tree.Selection.Count == 1) + _tree.CurrentNode = this; + } + else + _tree.Selection.Remove(this); + _tree.UpdateView(); + _tree.OnSelectionChanged(); + } + _isSelected = value; + } + } + } + + /// + /// Returns true if all parent nodes of this node are expanded. + /// + internal bool IsVisible + { + get + { + TreeNodeAdv node = _parent; + while (node != null) + { + if (!node.IsExpanded) + return false; + node = node.Parent; + } + return true; + } + } + + private bool _isLeaf; + public bool IsLeaf + { + get { return _isLeaf; } + internal set { _isLeaf = value; } + } + + private bool _isExpandedOnce; + public bool IsExpandedOnce + { + get { return _isExpandedOnce; } + internal set { _isExpandedOnce = value; } + } + + private bool _isExpanded; + public bool IsExpanded + { + get { return _isExpanded; } + set + { + if (value) + Expand(); + else + Collapse(); + } + } + + internal void AssignIsExpanded(bool value) + { + _isExpanded = value; + } + + private TreeNodeAdv _parent; + public TreeNodeAdv Parent + { + get { return _parent; } + } + + public int Level + { + get + { + if (_parent == null) + return 0; + else + return _parent.Level + 1; + } + } + + public TreeNodeAdv PreviousNode + { + get + { + if (_parent != null) + { + int index = Index; + if (index > 0) + return _parent.Nodes[index - 1]; + } + return null; + } + } + + public TreeNodeAdv NextNode + { + get + { + if (_parent != null) + { + int index = Index; + if (index < _parent.Nodes.Count - 1) + return _parent.Nodes[index + 1]; + } + return null; + } + } + + internal TreeNodeAdv BottomNode + { + get + { + TreeNodeAdv parent = this.Parent; + if (parent != null) + { + if (parent.NextNode != null) + return parent.NextNode; + else + return parent.BottomNode; + } + return null; + } + } + + internal TreeNodeAdv NextVisibleNode + { + get + { + if (IsExpanded && Nodes.Count > 0) + return Nodes[0]; + else + { + TreeNodeAdv nn = NextNode; + if (nn != null) + return nn; + else + return BottomNode; + } + } + } + + public bool CanExpand + { + get + { + return (Nodes.Count > 0 || (!IsExpandedOnce && !IsLeaf)); + } + } + + private object _tag; + public object Tag + { + get { return _tag; } + } + + private Collection _nodes; + internal Collection Nodes + { + get { return _nodes; } + } + + private ReadOnlyCollection _children; + public ReadOnlyCollection Children + { + get + { + return _children; + } + } + + private int? _rightBounds; + internal int? RightBounds + { + get { return _rightBounds; } + set { _rightBounds = value; } + } + + private int? _height; + internal int? Height + { + get { return _height; } + set { _height = value; } + } + + private bool _isExpandingNow; + internal bool IsExpandingNow + { + get { return _isExpandingNow; } + set { _isExpandingNow = value; } + } + + private bool _autoExpandOnStructureChanged = true; + public bool AutoExpandOnStructureChanged + { + get { return _autoExpandOnStructureChanged; } + set { _autoExpandOnStructureChanged = value; } + } + + #endregion + + public TreeNodeAdv(object tag) + : this(null, tag) + { + } + + internal TreeNodeAdv(TreeViewAdv tree, object tag) + { + _row = -1; + _tree = tree; + _nodes = new NodeCollection(this); + _children = new ReadOnlyCollection(_nodes); + _tag = tag; + } + + public override string ToString() + { + if (Tag != null) + return Tag.ToString(); + else + return base.ToString(); + } + + public void Collapse() + { + if (_isExpanded) + Collapse(true); + } + + public void CollapseAll() + { + Collapse(false); + } + + public void Collapse(bool ignoreChildren) + { + SetIsExpanded(false, ignoreChildren); + } + + public void Expand() + { + if (!_isExpanded) + Expand(true); + } + + public void ExpandAll() + { + Expand(false); + } + + public void Expand(bool ignoreChildren) + { + SetIsExpanded(true, ignoreChildren); + } + + private void SetIsExpanded(bool value, bool ignoreChildren) + { + if (Tree == null) + _isExpanded = value; + else + Tree.SetIsExpanded(this, value, ignoreChildren); + } + + #region ISerializable Members + + private TreeNodeAdv(SerializationInfo info, StreamingContext context) + : this(null, null) + { + int nodesCount = 0; + nodesCount = info.GetInt32("NodesCount"); + _isExpanded = info.GetBoolean("IsExpanded"); + _tag = info.GetValue("Tag", typeof(object)); + + for (int i = 0; i < nodesCount; i++) + { + TreeNodeAdv child = (TreeNodeAdv)info.GetValue("Child" + i, typeof(TreeNodeAdv)); + Nodes.Add(child); + } + + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("IsExpanded", IsExpanded); + info.AddValue("NodesCount", Nodes.Count); + if ((Tag != null) && Tag.GetType().IsSerializable) + info.AddValue("Tag", Tag, Tag.GetType()); + + for (int i = 0; i < Nodes.Count; i++) + info.AddValue("Child" + i, Nodes[i], typeof(TreeNodeAdv)); + + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs b/Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs rename to Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs index 79d7b20..145c5b8 100644 --- a/External/Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs +++ b/Aga.Controls/Tree/TreeNodeAdvMouseEventArgs.cs @@ -1,59 +1,59 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public class TreeNodeAdvMouseEventArgs : MouseEventArgs - { - private TreeNodeAdv _node; - public TreeNodeAdv Node - { - get { return _node; } - internal set { _node = value; } - } - - private NodeControl _control; - public NodeControl Control - { - get { return _control; } - internal set { _control = value; } - } - - private Point _viewLocation; - public Point ViewLocation - { - get { return _viewLocation; } - internal set { _viewLocation = value; } - } - - private Keys _modifierKeys; - public Keys ModifierKeys - { - get { return _modifierKeys; } - internal set { _modifierKeys = value; } - } - - private bool _handled; - public bool Handled - { - get { return _handled; } - set { _handled = value; } - } - - private Rectangle _controlBounds; - public Rectangle ControlBounds - { - get { return _controlBounds; } - internal set { _controlBounds = value; } - } - - public TreeNodeAdvMouseEventArgs(MouseEventArgs args) - : base(args.Button, args.Clicks, args.X, args.Y, args.Delta) - { - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public class TreeNodeAdvMouseEventArgs : MouseEventArgs + { + private TreeNodeAdv _node; + public TreeNodeAdv Node + { + get { return _node; } + internal set { _node = value; } + } + + private NodeControl _control; + public NodeControl Control + { + get { return _control; } + internal set { _control = value; } + } + + private Point _viewLocation; + public Point ViewLocation + { + get { return _viewLocation; } + internal set { _viewLocation = value; } + } + + private Keys _modifierKeys; + public Keys ModifierKeys + { + get { return _modifierKeys; } + internal set { _modifierKeys = value; } + } + + private bool _handled; + public bool Handled + { + get { return _handled; } + set { _handled = value; } + } + + private Rectangle _controlBounds; + public Rectangle ControlBounds + { + get { return _controlBounds; } + internal set { _controlBounds = value; } + } + + public TreeNodeAdvMouseEventArgs(MouseEventArgs args) + : base(args.Button, args.Clicks, args.X, args.Y, args.Delta) + { + } + } +} diff --git a/External/Aga.Controls/Tree/TreePath.cs b/Aga.Controls/Tree/TreePath.cs similarity index 94% rename from External/Aga.Controls/Tree/TreePath.cs rename to Aga.Controls/Tree/TreePath.cs index bd5b682..4b923ff 100644 --- a/External/Aga.Controls/Tree/TreePath.cs +++ b/Aga.Controls/Tree/TreePath.cs @@ -1,68 +1,68 @@ -using System; -using System.Text; -using System.Collections.ObjectModel; - -namespace Aga.Controls.Tree -{ - public class TreePath - { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - public static readonly TreePath Empty = new TreePath(); - - private object[] _path; - public object[] FullPath - { - get { return _path; } - } - - public object LastNode - { - get - { - if (_path.Length > 0) - return _path[_path.Length - 1]; - else - return null; - } - } - - public object FirstNode - { - get - { - if (_path.Length > 0) - return _path[0]; - else - return null; - } - } - - public TreePath() - { - _path = new object[0]; - } - - public TreePath(object node) - { - _path = new object[] { node }; - } - - public TreePath(object[] path) - { - _path = path; - } - - public TreePath(TreePath parent, object node) - { - _path = new object[parent.FullPath.Length + 1]; - for (int i = 0; i < _path.Length - 1; i++) - _path[i] = parent.FullPath[i]; - _path[_path.Length - 1] = node; - } - - public bool IsEmpty() - { - return (_path.Length == 0); - } - } -} +using System; +using System.Text; +using System.Collections.ObjectModel; + +namespace Aga.Controls.Tree +{ + public class TreePath + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] + public static readonly TreePath Empty = new TreePath(); + + private object[] _path; + public object[] FullPath + { + get { return _path; } + } + + public object LastNode + { + get + { + if (_path.Length > 0) + return _path[_path.Length - 1]; + else + return null; + } + } + + public object FirstNode + { + get + { + if (_path.Length > 0) + return _path[0]; + else + return null; + } + } + + public TreePath() + { + _path = new object[0]; + } + + public TreePath(object node) + { + _path = new object[] { node }; + } + + public TreePath(object[] path) + { + _path = path; + } + + public TreePath(TreePath parent, object node) + { + _path = new object[parent.FullPath.Length + 1]; + for (int i = 0; i < _path.Length - 1; i++) + _path[i] = parent.FullPath[i]; + _path[_path.Length - 1] = node; + } + + public bool IsEmpty() + { + return (_path.Length == 0); + } + } +} diff --git a/External/Aga.Controls/Tree/TreePathEventArgs.cs b/Aga.Controls/Tree/TreePathEventArgs.cs similarity index 93% rename from External/Aga.Controls/Tree/TreePathEventArgs.cs rename to Aga.Controls/Tree/TreePathEventArgs.cs index 70e4ff9..6ee8a4d 100644 --- a/External/Aga.Controls/Tree/TreePathEventArgs.cs +++ b/Aga.Controls/Tree/TreePathEventArgs.cs @@ -1,28 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public class TreePathEventArgs : EventArgs - { - private TreePath _path; - public TreePath Path - { - get { return _path; } - } - - public TreePathEventArgs() - { - _path = new TreePath(); - } - - public TreePathEventArgs(TreePath path) - { - if (path == null) - throw new ArgumentNullException(); - - _path = path; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public class TreePathEventArgs : EventArgs + { + private TreePath _path; + public TreePath Path + { + get { return _path; } + } + + public TreePathEventArgs() + { + _path = new TreePath(); + } + + public TreePathEventArgs(TreePath path) + { + if (path == null) + throw new ArgumentNullException(); + + _path = path; + } + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.Designer.cs b/Aga.Controls/Tree/TreeViewAdv.Designer.cs similarity index 97% rename from External/Aga.Controls/Tree/TreeViewAdv.Designer.cs rename to Aga.Controls/Tree/TreeViewAdv.Designer.cs index a58c509..b08e641 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.Designer.cs +++ b/Aga.Controls/Tree/TreeViewAdv.Designer.cs @@ -1,69 +1,69 @@ -using System.Windows.Forms; - -namespace Aga.Controls.Tree -{ - partial class TreeViewAdv - { - private System.ComponentModel.IContainer components = null; - - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - if (_dragBitmap != null) _dragBitmap.Dispose(); - if (_dragTimer != null) _dragTimer.Dispose(); - if (_linePen != null) _linePen.Dispose(); - if (_markPen != null) _markPen.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this._vScrollBar = new System.Windows.Forms.VScrollBar(); - this._hScrollBar = new System.Windows.Forms.HScrollBar(); - this._errorProvider = new System.Windows.Forms.ErrorProvider(this.components); - ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).BeginInit(); - this.SuspendLayout(); - // - // _vScrollBar - // - this._vScrollBar.LargeChange = 1; - this._vScrollBar.Location = new System.Drawing.Point(0, 0); - this._vScrollBar.Maximum = 0; - this._vScrollBar.Name = "_vScrollBar"; - this._vScrollBar.Size = new System.Drawing.Size(13, 80); - this._vScrollBar.TabIndex = 1; - this._vScrollBar.ValueChanged += new System.EventHandler(this._vScrollBar_ValueChanged); - this._vScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this._vScrollBar_Scroll); - // - // _hScrollBar - // - this._hScrollBar.LargeChange = 1; - this._hScrollBar.Location = new System.Drawing.Point(0, 0); - this._hScrollBar.Maximum = 0; - this._hScrollBar.Name = "_hScrollBar"; - this._hScrollBar.Size = new System.Drawing.Size(80, 13); - this._hScrollBar.TabIndex = 2; - this._hScrollBar.ValueChanged += new System.EventHandler(this._hScrollBar_ValueChanged); - this._hScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this._hScrollBar_Scroll); - // - // TreeViewAdv - // - this.BackColor = System.Drawing.SystemColors.Window; - this.Controls.Add(this._vScrollBar); - this.Controls.Add(this._hScrollBar); - ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).EndInit(); - this.ResumeLayout(false); - - } - #endregion - - private VScrollBar _vScrollBar; - private HScrollBar _hScrollBar; - private ErrorProvider _errorProvider; - } -} +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + partial class TreeViewAdv + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + if (_dragBitmap != null) _dragBitmap.Dispose(); + if (_dragTimer != null) _dragTimer.Dispose(); + if (_linePen != null) _linePen.Dispose(); + if (_markPen != null) _markPen.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this._vScrollBar = new System.Windows.Forms.VScrollBar(); + this._hScrollBar = new System.Windows.Forms.HScrollBar(); + this._errorProvider = new System.Windows.Forms.ErrorProvider(this.components); + ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).BeginInit(); + this.SuspendLayout(); + // + // _vScrollBar + // + this._vScrollBar.LargeChange = 1; + this._vScrollBar.Location = new System.Drawing.Point(0, 0); + this._vScrollBar.Maximum = 0; + this._vScrollBar.Name = "_vScrollBar"; + this._vScrollBar.Size = new System.Drawing.Size(13, 80); + this._vScrollBar.TabIndex = 1; + this._vScrollBar.ValueChanged += new System.EventHandler(this._vScrollBar_ValueChanged); + this._vScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this._vScrollBar_Scroll); + // + // _hScrollBar + // + this._hScrollBar.LargeChange = 1; + this._hScrollBar.Location = new System.Drawing.Point(0, 0); + this._hScrollBar.Maximum = 0; + this._hScrollBar.Name = "_hScrollBar"; + this._hScrollBar.Size = new System.Drawing.Size(80, 13); + this._hScrollBar.TabIndex = 2; + this._hScrollBar.ValueChanged += new System.EventHandler(this._hScrollBar_ValueChanged); + this._hScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this._hScrollBar_Scroll); + // + // TreeViewAdv + // + this.BackColor = System.Drawing.SystemColors.Window; + this.Controls.Add(this._vScrollBar); + this.Controls.Add(this._hScrollBar); + ((System.ComponentModel.ISupportInitialize)(this._errorProvider)).EndInit(); + this.ResumeLayout(false); + + } + #endregion + + private VScrollBar _vScrollBar; + private HScrollBar _hScrollBar; + private ErrorProvider _errorProvider; + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.Draw.cs b/Aga.Controls/Tree/TreeViewAdv.Draw.cs similarity index 96% rename from External/Aga.Controls/Tree/TreeViewAdv.Draw.cs rename to Aga.Controls/Tree/TreeViewAdv.Draw.cs index a512213..f42b9cd 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.Draw.cs +++ b/Aga.Controls/Tree/TreeViewAdv.Draw.cs @@ -1,313 +1,313 @@ -using System; -using System.Drawing; -using System.Diagnostics; -using System.Drawing.Drawing2D; -using System.Windows.Forms; -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public partial class TreeViewAdv - { - public void AutoSizeColumn(TreeColumn column) - { - if (!Columns.Contains(column)) - throw new ArgumentException("column"); - - DrawContext context = new DrawContext(); - context.Graphics = Graphics.FromImage(new Bitmap(1, 1)); - context.Font = this.Font; - int res = 0; - for (int row = 0; row < RowCount; row++) - { - if (row < RowMap.Count) - { - int w = 0; - TreeNodeAdv node = RowMap[row]; - foreach (NodeControl nc in NodeControls) - { - if (nc.ParentColumn == column) - w += nc.GetActualSize(node, _measureContext).Width; - } - res = Math.Max(res, w); - } - } - - if (res > 0) - column.Width = res; - } - - private void CreatePens() - { - CreateLinePen(); - CreateMarkPen(); - } - - private void CreateMarkPen() - { - GraphicsPath path = new GraphicsPath(); - path.AddLines(new Point[] { new Point(0, 0), new Point(1, 1), new Point(-1, 1), new Point(0, 0) }); - CustomLineCap cap = new CustomLineCap(null, path); - cap.WidthScale = 1.0f; - - _markPen = new Pen(_dragDropMarkColor, _dragDropMarkWidth); - _markPen.CustomStartCap = cap; - _markPen.CustomEndCap = cap; - } - - private void CreateLinePen() - { - _linePen = new Pen(_lineColor); - _linePen.DashStyle = DashStyle.Dot; - } - - protected override void OnPaint(PaintEventArgs e) - { - BeginPerformanceCount(); - PerformanceAnalyzer.Start("OnPaint"); - - DrawContext context = new DrawContext(); - context.Graphics = e.Graphics; - context.Font = this.Font; - context.Enabled = Enabled; - - int y = 0; - int gridHeight = 0; - - if (UseColumns) - { - DrawColumnHeaders(e.Graphics); - y += ColumnHeaderHeight; - if (Columns.Count == 0 || e.ClipRectangle.Height <= y) - return; - } - - int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y; - y -= firstRowY; - - e.Graphics.ResetTransform(); - e.Graphics.TranslateTransform(-OffsetX, y); - Rectangle displayRect = DisplayRectangle; - for (int row = FirstVisibleRow; row < RowCount; row++) - { - Rectangle rowRect = _rowLayout.GetRowBounds(row); - gridHeight += rowRect.Height; - if (rowRect.Y + y > displayRect.Bottom) - break; - else - DrawRow(e, ref context, row, rowRect); - } - - if ((GridLineStyle & GridLineStyle.Vertical) == GridLineStyle.Vertical && UseColumns) - DrawVerticalGridLines(e.Graphics, firstRowY); - - if (_dropPosition.Node != null && DragMode && HighlightDropPosition) - DrawDropMark(e.Graphics); - - e.Graphics.ResetTransform(); - DrawScrollBarsBox(e.Graphics); - - if (DragMode && _dragBitmap != null) - e.Graphics.DrawImage(_dragBitmap, PointToClient(MousePosition)); - - PerformanceAnalyzer.Finish("OnPaint"); - EndPerformanceCount(e); - } - - private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectangle rowRect) - { - TreeNodeAdv node = RowMap[row]; - context.DrawSelection = DrawSelectionMode.None; - context.CurrentEditorOwner = CurrentEditorOwner; - if (DragMode) - { - if ((_dropPosition.Node == node) && _dropPosition.Position == NodePosition.Inside && HighlightDropPosition) - context.DrawSelection = DrawSelectionMode.Active; - } - else - { - if (node.IsSelected && Focused) - context.DrawSelection = DrawSelectionMode.Active; - else if (node.IsSelected && !Focused && !HideSelection) - context.DrawSelection = DrawSelectionMode.Inactive; - } - context.DrawFocus = Focused && CurrentNode == node; - - OnRowDraw(e, node, context, row, rowRect); - - if ((GridLineStyle & GridLineStyle.Horizontal) == GridLineStyle.Horizontal) { - e.Graphics.DrawLine(LightGrayPen, 0, rowRect.Bottom, e.Graphics.ClipBounds.Right, rowRect.Bottom); - } - - if (FullRowSelect) - { - context.DrawFocus = false; - if (context.DrawSelection == DrawSelectionMode.Active || context.DrawSelection == DrawSelectionMode.Inactive) - { - Rectangle focusRect = new Rectangle(OffsetX, rowRect.Y, ClientRectangle.Width, rowRect.Height); - if (context.DrawSelection == DrawSelectionMode.Active) - { - e.Graphics.FillRectangle(GrayBrush, focusRect); - context.DrawSelection = DrawSelectionMode.FullRowSelect; - } - else - { - e.Graphics.FillRectangle(GrayBrush, focusRect); - context.DrawSelection = DrawSelectionMode.None; - } - } - } - - if (ShowLines) - DrawLines(e.Graphics, node, rowRect); - - DrawNode(node, context); - } - - private Brush GrayBrush = new SolidBrush(Color.FromArgb(240, 240, 240)); - private Pen LightGrayPen = new Pen(Color.FromArgb(247, 247, 247)); - - private void DrawVerticalGridLines(Graphics gr, int y) - { - int x = 0; - foreach (TreeColumn c in Columns) - { - if (c.IsVisible) - { - x += c.Width; - gr.DrawLine(SystemPens.InactiveBorder, x - 1, y, x - 1, gr.ClipBounds.Bottom); - } - } - } - - private void DrawColumnHeaders(Graphics gr) - { - PerformanceAnalyzer.Start("DrawColumnHeaders"); - ReorderColumnState reorder = Input as ReorderColumnState; - int x = 0; - TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width + 2, ColumnHeaderHeight - 1), false, false); - gr.TranslateTransform(-OffsetX, 0); - foreach (TreeColumn c in Columns) - { - if (c.IsVisible) - { - if (x >= OffsetX && x - OffsetX < this.Bounds.Width)// skip invisible columns - { - Rectangle rect = new Rectangle(x, 0, c.Width, ColumnHeaderHeight - 1); - gr.SetClip(rect); - bool pressed = ((Input is ClickColumnState || reorder != null) && ((Input as ColumnState).Column == c)); - c.Draw(gr, rect, Font, pressed, _hotColumn == c); - gr.ResetClip(); - - if (reorder != null && reorder.DropColumn == c) - TreeColumn.DrawDropMark(gr, rect); - } - x += c.Width; - } - } - - if (reorder != null) - { - if (reorder.DropColumn == null) - TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, ColumnHeaderHeight)); - gr.DrawImage(reorder.GhostImage, new Point(reorder.Location.X + + reorder.DragOffset, reorder.Location.Y)); - } - PerformanceAnalyzer.Finish("DrawColumnHeaders"); - } - - public void DrawNode(TreeNodeAdv node, DrawContext context) - { - foreach (NodeControlInfo item in GetNodeControls(node)) - { - if (item.Bounds.Right >= OffsetX && item.Bounds.X - OffsetX < this.Bounds.Width)// skip invisible nodes - { - context.Bounds = item.Bounds; - context.Graphics.SetClip(context.Bounds); - item.Control.Draw(node, context); - context.Graphics.ResetClip(); - } - } - } - - private void DrawScrollBarsBox(Graphics gr) - { - Rectangle r1 = DisplayRectangle; - Rectangle r2 = ClientRectangle; - gr.FillRectangle(SystemBrushes.Control, - new Rectangle(r1.Right, r1.Bottom, r2.Width - r1.Width, r2.Height - r1.Height)); - } - - private void DrawDropMark(Graphics gr) - { - if (_dropPosition.Position == NodePosition.Inside) - return; - - Rectangle rect = GetNodeBounds(_dropPosition.Node); - int right = DisplayRectangle.Right - LeftMargin + OffsetX; - int y = rect.Y; - if (_dropPosition.Position == NodePosition.After) - y = rect.Bottom; - gr.DrawLine(_markPen, rect.X, y, right, y); - } - - private void DrawLines(Graphics gr, TreeNodeAdv node, Rectangle rowRect) - { - if (UseColumns && Columns.Count > 0) - gr.SetClip(new Rectangle(0, rowRect.Y, Columns[0].Width, rowRect.Bottom)); - - TreeNodeAdv curNode = node; - while (curNode != _root && curNode != null) - { - int level = curNode.Level; - int scaledIndent = node.Tree.GetScaledSize(_indent, false); - int x = (level - 1) * scaledIndent + NodePlusMinus.ImageSize / 2 + LeftMargin; - int width = node.Tree.GetScaledSize(NodePlusMinus.Width - NodePlusMinus.ImageSize / 2, false); - int y = rowRect.Y; - int y2 = y + rowRect.Height; - - if (curNode == node) - { - int midy = y + rowRect.Height / 2; - gr.DrawLine(_linePen, x, midy, x + width, midy); - if (curNode.NextNode == null) - y2 = y + rowRect.Height / 2; - } - - if (node.Row == 0) - y = rowRect.Height / 2; - if (curNode.NextNode != null || curNode == node) - gr.DrawLine(_linePen, x, y, x, y2); - - curNode = curNode.Parent; - } - - gr.ResetClip(); - } - - #region Performance - - private double _totalTime; - private int _paintCount; - - [Conditional("PERF_TEST")] - private void BeginPerformanceCount() - { - _paintCount++; - TimeCounter.Start(); - } - - [Conditional("PERF_TEST")] - private void EndPerformanceCount(PaintEventArgs e) - { - double time = TimeCounter.Finish(); - _totalTime += time; - string debugText = string.Format("FPS {0:0.0}; Avg. FPS {1:0.0}", - 1 / time, 1 / (_totalTime / _paintCount)); - e.Graphics.FillRectangle(Brushes.White, new Rectangle(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20, 150, 20)); - e.Graphics.DrawString(debugText, Control.DefaultFont, Brushes.Gray, - new PointF(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20)); - } - #endregion - - } -} +using System; +using System.Drawing; +using System.Diagnostics; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public partial class TreeViewAdv + { + public void AutoSizeColumn(TreeColumn column) + { + if (!Columns.Contains(column)) + throw new ArgumentException("column"); + + DrawContext context = new DrawContext(); + context.Graphics = Graphics.FromImage(new Bitmap(1, 1)); + context.Font = this.Font; + int res = 0; + for (int row = 0; row < RowCount; row++) + { + if (row < RowMap.Count) + { + int w = 0; + TreeNodeAdv node = RowMap[row]; + foreach (NodeControl nc in NodeControls) + { + if (nc.ParentColumn == column) + w += nc.GetActualSize(node, _measureContext).Width; + } + res = Math.Max(res, w); + } + } + + if (res > 0) + column.Width = res; + } + + private void CreatePens() + { + CreateLinePen(); + CreateMarkPen(); + } + + private void CreateMarkPen() + { + GraphicsPath path = new GraphicsPath(); + path.AddLines(new Point[] { new Point(0, 0), new Point(1, 1), new Point(-1, 1), new Point(0, 0) }); + CustomLineCap cap = new CustomLineCap(null, path); + cap.WidthScale = 1.0f; + + _markPen = new Pen(_dragDropMarkColor, _dragDropMarkWidth); + _markPen.CustomStartCap = cap; + _markPen.CustomEndCap = cap; + } + + private void CreateLinePen() + { + _linePen = new Pen(_lineColor); + _linePen.DashStyle = DashStyle.Dot; + } + + protected override void OnPaint(PaintEventArgs e) + { + BeginPerformanceCount(); + PerformanceAnalyzer.Start("OnPaint"); + + DrawContext context = new DrawContext(); + context.Graphics = e.Graphics; + context.Font = this.Font; + context.Enabled = Enabled; + + int y = 0; + int gridHeight = 0; + + if (UseColumns) + { + DrawColumnHeaders(e.Graphics); + y += ColumnHeaderHeight; + if (Columns.Count == 0 || e.ClipRectangle.Height <= y) + return; + } + + int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y; + y -= firstRowY; + + e.Graphics.ResetTransform(); + e.Graphics.TranslateTransform(-OffsetX, y); + Rectangle displayRect = DisplayRectangle; + for (int row = FirstVisibleRow; row < RowCount; row++) + { + Rectangle rowRect = _rowLayout.GetRowBounds(row); + gridHeight += rowRect.Height; + if (rowRect.Y + y > displayRect.Bottom) + break; + else + DrawRow(e, ref context, row, rowRect); + } + + if ((GridLineStyle & GridLineStyle.Vertical) == GridLineStyle.Vertical && UseColumns) + DrawVerticalGridLines(e.Graphics, firstRowY); + + if (_dropPosition.Node != null && DragMode && HighlightDropPosition) + DrawDropMark(e.Graphics); + + e.Graphics.ResetTransform(); + DrawScrollBarsBox(e.Graphics); + + if (DragMode && _dragBitmap != null) + e.Graphics.DrawImage(_dragBitmap, PointToClient(MousePosition)); + + PerformanceAnalyzer.Finish("OnPaint"); + EndPerformanceCount(e); + } + + private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectangle rowRect) + { + TreeNodeAdv node = RowMap[row]; + context.DrawSelection = DrawSelectionMode.None; + context.CurrentEditorOwner = CurrentEditorOwner; + if (DragMode) + { + if ((_dropPosition.Node == node) && _dropPosition.Position == NodePosition.Inside && HighlightDropPosition) + context.DrawSelection = DrawSelectionMode.Active; + } + else + { + if (node.IsSelected && Focused) + context.DrawSelection = DrawSelectionMode.Active; + else if (node.IsSelected && !Focused && !HideSelection) + context.DrawSelection = DrawSelectionMode.Inactive; + } + context.DrawFocus = Focused && CurrentNode == node; + + OnRowDraw(e, node, context, row, rowRect); + + if ((GridLineStyle & GridLineStyle.Horizontal) == GridLineStyle.Horizontal) { + e.Graphics.DrawLine(LightGrayPen, 0, rowRect.Bottom, e.Graphics.ClipBounds.Right, rowRect.Bottom); + } + + if (FullRowSelect) + { + context.DrawFocus = false; + if (context.DrawSelection == DrawSelectionMode.Active || context.DrawSelection == DrawSelectionMode.Inactive) + { + Rectangle focusRect = new Rectangle(OffsetX, rowRect.Y, ClientRectangle.Width, rowRect.Height); + if (context.DrawSelection == DrawSelectionMode.Active) + { + e.Graphics.FillRectangle(GrayBrush, focusRect); + context.DrawSelection = DrawSelectionMode.FullRowSelect; + } + else + { + e.Graphics.FillRectangle(GrayBrush, focusRect); + context.DrawSelection = DrawSelectionMode.None; + } + } + } + + if (ShowLines) + DrawLines(e.Graphics, node, rowRect); + + DrawNode(node, context); + } + + private Brush GrayBrush = new SolidBrush(Color.FromArgb(240, 240, 240)); + private Pen LightGrayPen = new Pen(Color.FromArgb(247, 247, 247)); + + private void DrawVerticalGridLines(Graphics gr, int y) + { + int x = 0; + foreach (TreeColumn c in Columns) + { + if (c.IsVisible) + { + x += c.Width; + gr.DrawLine(SystemPens.InactiveBorder, x - 1, y, x - 1, gr.ClipBounds.Bottom); + } + } + } + + private void DrawColumnHeaders(Graphics gr) + { + PerformanceAnalyzer.Start("DrawColumnHeaders"); + ReorderColumnState reorder = Input as ReorderColumnState; + int x = 0; + TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width + 2, ColumnHeaderHeight - 1), false, false); + gr.TranslateTransform(-OffsetX, 0); + foreach (TreeColumn c in Columns) + { + if (c.IsVisible) + { + if (x >= OffsetX && x - OffsetX < this.Bounds.Width)// skip invisible columns + { + Rectangle rect = new Rectangle(x, 0, c.Width, ColumnHeaderHeight - 1); + gr.SetClip(rect); + bool pressed = ((Input is ClickColumnState || reorder != null) && ((Input as ColumnState).Column == c)); + c.Draw(gr, rect, Font, pressed, _hotColumn == c); + gr.ResetClip(); + + if (reorder != null && reorder.DropColumn == c) + TreeColumn.DrawDropMark(gr, rect); + } + x += c.Width; + } + } + + if (reorder != null) + { + if (reorder.DropColumn == null) + TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, ColumnHeaderHeight)); + gr.DrawImage(reorder.GhostImage, new Point(reorder.Location.X + + reorder.DragOffset, reorder.Location.Y)); + } + PerformanceAnalyzer.Finish("DrawColumnHeaders"); + } + + public void DrawNode(TreeNodeAdv node, DrawContext context) + { + foreach (NodeControlInfo item in GetNodeControls(node)) + { + if (item.Bounds.Right >= OffsetX && item.Bounds.X - OffsetX < this.Bounds.Width)// skip invisible nodes + { + context.Bounds = item.Bounds; + context.Graphics.SetClip(context.Bounds); + item.Control.Draw(node, context); + context.Graphics.ResetClip(); + } + } + } + + private void DrawScrollBarsBox(Graphics gr) + { + Rectangle r1 = DisplayRectangle; + Rectangle r2 = ClientRectangle; + gr.FillRectangle(SystemBrushes.Control, + new Rectangle(r1.Right, r1.Bottom, r2.Width - r1.Width, r2.Height - r1.Height)); + } + + private void DrawDropMark(Graphics gr) + { + if (_dropPosition.Position == NodePosition.Inside) + return; + + Rectangle rect = GetNodeBounds(_dropPosition.Node); + int right = DisplayRectangle.Right - LeftMargin + OffsetX; + int y = rect.Y; + if (_dropPosition.Position == NodePosition.After) + y = rect.Bottom; + gr.DrawLine(_markPen, rect.X, y, right, y); + } + + private void DrawLines(Graphics gr, TreeNodeAdv node, Rectangle rowRect) + { + if (UseColumns && Columns.Count > 0) + gr.SetClip(new Rectangle(0, rowRect.Y, Columns[0].Width, rowRect.Bottom)); + + TreeNodeAdv curNode = node; + while (curNode != _root && curNode != null) + { + int level = curNode.Level; + int scaledIndent = node.Tree.GetScaledSize(_indent, false); + int x = (level - 1) * scaledIndent + NodePlusMinus.ImageSize / 2 + LeftMargin; + int width = node.Tree.GetScaledSize(NodePlusMinus.Width - NodePlusMinus.ImageSize / 2, false); + int y = rowRect.Y; + int y2 = y + rowRect.Height; + + if (curNode == node) + { + int midy = y + rowRect.Height / 2; + gr.DrawLine(_linePen, x, midy, x + width, midy); + if (curNode.NextNode == null) + y2 = y + rowRect.Height / 2; + } + + if (node.Row == 0) + y = rowRect.Height / 2; + if (curNode.NextNode != null || curNode == node) + gr.DrawLine(_linePen, x, y, x, y2); + + curNode = curNode.Parent; + } + + gr.ResetClip(); + } + + #region Performance + + private double _totalTime; + private int _paintCount; + + [Conditional("PERF_TEST")] + private void BeginPerformanceCount() + { + _paintCount++; + TimeCounter.Start(); + } + + [Conditional("PERF_TEST")] + private void EndPerformanceCount(PaintEventArgs e) + { + double time = TimeCounter.Finish(); + _totalTime += time; + string debugText = string.Format("FPS {0:0.0}; Avg. FPS {1:0.0}", + 1 / time, 1 / (_totalTime / _paintCount)); + e.Graphics.FillRectangle(Brushes.White, new Rectangle(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20, 150, 20)); + e.Graphics.DrawString(debugText, Control.DefaultFont, Brushes.Gray, + new PointF(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20)); + } + #endregion + + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.Editor.cs b/Aga.Controls/Tree/TreeViewAdv.Editor.cs similarity index 96% rename from External/Aga.Controls/Tree/TreeViewAdv.Editor.cs rename to Aga.Controls/Tree/TreeViewAdv.Editor.cs index 655bbac..b65aca0 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.Editor.cs +++ b/Aga.Controls/Tree/TreeViewAdv.Editor.cs @@ -1,145 +1,145 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using Aga.Controls.Tree.NodeControls; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - partial class TreeViewAdv - { - private TreeNodeAdv _editingNode; - - public EditableControl CurrentEditorOwner { get; private set; } - public Control CurrentEditor { get; private set; } - - public void HideEditor() - { - if (CurrentEditorOwner != null) - CurrentEditorOwner.EndEdit(false); - } - - internal void DisplayEditor(Control editor, EditableControl owner) - { - if (editor == null || owner == null || CurrentNode == null) - throw new ArgumentNullException(); - - HideEditor(false); - - CurrentEditor = editor; - CurrentEditorOwner = owner; - _editingNode = CurrentNode; - - editor.Validating += EditorValidating; - UpdateEditorBounds(); - UpdateView(); - editor.Parent = this; - editor.Focus(); - owner.UpdateEditor(editor); - } - - internal bool HideEditor(bool applyChanges) - { - if (CurrentEditor != null) - { - if (applyChanges) - { - if (!ApplyChanges()) - return false; - } - - //Check once more if editor was closed in ApplyChanges - if (CurrentEditor != null) - { - CurrentEditor.Validating -= EditorValidating; - CurrentEditorOwner.DoDisposeEditor(CurrentEditor); - - CurrentEditor.Parent = null; - CurrentEditor.Dispose(); - - CurrentEditor = null; - CurrentEditorOwner = null; - _editingNode = null; - } - } - return true; - } - - private bool ApplyChanges() - { - try - { - CurrentEditorOwner.ApplyChanges(_editingNode, CurrentEditor); - _errorProvider.Clear(); - return true; - } - catch (ArgumentException ex) - { - _errorProvider.SetError(CurrentEditor, ex.Message); - /*CurrentEditor.Validating -= EditorValidating; - MessageBox.Show(this, ex.Message, "Value is not valid", MessageBoxButtons.OK, MessageBoxIcon.Warning); - CurrentEditor.Focus(); - CurrentEditor.Validating += EditorValidating;*/ - return false; - } - } - - void EditorValidating(object sender, System.ComponentModel.CancelEventArgs e) - { - e.Cancel = !ApplyChanges(); - } - - public void UpdateEditorBounds() - { - if (CurrentEditor != null) - { - EditorContext context = new EditorContext(); - context.Owner = CurrentEditorOwner; - context.CurrentNode = CurrentNode; - context.Editor = CurrentEditor; - context.DrawContext = _measureContext; - SetEditorBounds(context); - } - } - - private void SetEditorBounds(EditorContext context) - { - foreach (NodeControlInfo info in GetNodeControls(context.CurrentNode)) - { - if (context.Owner == info.Control && info.Control is EditableControl) - { - Point p = info.Bounds.Location; - p.X += info.Control.LeftMargin; - p.X -= OffsetX; - p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); - int width = DisplayRectangle.Width - p.X; - if (UseColumns && info.Control.ParentColumn != null && Columns.Contains(info.Control.ParentColumn)) - { - Rectangle rect = GetColumnBounds(info.Control.ParentColumn.Index); - width = rect.Right - OffsetX - p.X; - } - context.Bounds = new Rectangle(p.X, p.Y, width, info.Bounds.Height); - ((EditableControl)info.Control).SetEditorBounds(context); - return; - } - } - } - - private Rectangle GetColumnBounds(int column) - { - int x = 0; - for (int i = 0; i < Columns.Count; i++) - { - if (Columns[i].IsVisible) - { - if (i < column) - x += Columns[i].Width; - else - return new Rectangle(x, 0, Columns[i].Width, 0); - } - } - return Rectangle.Empty; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using Aga.Controls.Tree.NodeControls; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + partial class TreeViewAdv + { + private TreeNodeAdv _editingNode; + + public EditableControl CurrentEditorOwner { get; private set; } + public Control CurrentEditor { get; private set; } + + public void HideEditor() + { + if (CurrentEditorOwner != null) + CurrentEditorOwner.EndEdit(false); + } + + internal void DisplayEditor(Control editor, EditableControl owner) + { + if (editor == null || owner == null || CurrentNode == null) + throw new ArgumentNullException(); + + HideEditor(false); + + CurrentEditor = editor; + CurrentEditorOwner = owner; + _editingNode = CurrentNode; + + editor.Validating += EditorValidating; + UpdateEditorBounds(); + UpdateView(); + editor.Parent = this; + editor.Focus(); + owner.UpdateEditor(editor); + } + + internal bool HideEditor(bool applyChanges) + { + if (CurrentEditor != null) + { + if (applyChanges) + { + if (!ApplyChanges()) + return false; + } + + //Check once more if editor was closed in ApplyChanges + if (CurrentEditor != null) + { + CurrentEditor.Validating -= EditorValidating; + CurrentEditorOwner.DoDisposeEditor(CurrentEditor); + + CurrentEditor.Parent = null; + CurrentEditor.Dispose(); + + CurrentEditor = null; + CurrentEditorOwner = null; + _editingNode = null; + } + } + return true; + } + + private bool ApplyChanges() + { + try + { + CurrentEditorOwner.ApplyChanges(_editingNode, CurrentEditor); + _errorProvider.Clear(); + return true; + } + catch (ArgumentException ex) + { + _errorProvider.SetError(CurrentEditor, ex.Message); + /*CurrentEditor.Validating -= EditorValidating; + MessageBox.Show(this, ex.Message, "Value is not valid", MessageBoxButtons.OK, MessageBoxIcon.Warning); + CurrentEditor.Focus(); + CurrentEditor.Validating += EditorValidating;*/ + return false; + } + } + + void EditorValidating(object sender, System.ComponentModel.CancelEventArgs e) + { + e.Cancel = !ApplyChanges(); + } + + public void UpdateEditorBounds() + { + if (CurrentEditor != null) + { + EditorContext context = new EditorContext(); + context.Owner = CurrentEditorOwner; + context.CurrentNode = CurrentNode; + context.Editor = CurrentEditor; + context.DrawContext = _measureContext; + SetEditorBounds(context); + } + } + + private void SetEditorBounds(EditorContext context) + { + foreach (NodeControlInfo info in GetNodeControls(context.CurrentNode)) + { + if (context.Owner == info.Control && info.Control is EditableControl) + { + Point p = info.Bounds.Location; + p.X += info.Control.LeftMargin; + p.X -= OffsetX; + p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); + int width = DisplayRectangle.Width - p.X; + if (UseColumns && info.Control.ParentColumn != null && Columns.Contains(info.Control.ParentColumn)) + { + Rectangle rect = GetColumnBounds(info.Control.ParentColumn.Index); + width = rect.Right - OffsetX - p.X; + } + context.Bounds = new Rectangle(p.X, p.Y, width, info.Bounds.Height); + ((EditableControl)info.Control).SetEditorBounds(context); + return; + } + } + } + + private Rectangle GetColumnBounds(int column) + { + int x = 0; + for (int i = 0; i < Columns.Count; i++) + { + if (Columns[i].IsVisible) + { + if (i < column) + x += Columns[i].Width; + else + return new Rectangle(x, 0, Columns[i].Width, 0); + } + } + return Rectangle.Empty; + } + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.Input.cs b/Aga.Controls/Tree/TreeViewAdv.Input.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeViewAdv.Input.cs rename to Aga.Controls/Tree/TreeViewAdv.Input.cs index fe796b7..57d1ecf 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.Input.cs +++ b/Aga.Controls/Tree/TreeViewAdv.Input.cs @@ -1,558 +1,558 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using Aga.Controls.Tree.NodeControls; -using System.Drawing.Imaging; -using System.Threading; - -namespace Aga.Controls.Tree -{ - public partial class TreeViewAdv - { - #region Keys - - protected override bool IsInputChar(char charCode) - { - return true; - } - - protected override bool IsInputKey(Keys keyData) - { - if (((keyData & Keys.Up) == Keys.Up) - || ((keyData & Keys.Down) == Keys.Down) - || ((keyData & Keys.Left) == Keys.Left) - || ((keyData & Keys.Right) == Keys.Right)) - return true; - else - return base.IsInputKey(keyData); - } - - internal void ChangeInput() - { - if ((ModifierKeys & Keys.Shift) == Keys.Shift) - { - if (!(Input is InputWithShift)) - Input = new InputWithShift(this); - } - else if ((ModifierKeys & Keys.Control) == Keys.Control) - { - if (!(Input is InputWithControl)) - Input = new InputWithControl(this); - } - else - { - if (!(Input.GetType() == typeof(NormalInputState))) - Input = new NormalInputState(this); - } - } - - protected override void OnKeyDown(KeyEventArgs e) - { - base.OnKeyDown(e); - if (!e.Handled) - { - if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) - ChangeInput(); - Input.KeyDown(e); - if (!e.Handled) - { - foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) - { - item.Control.KeyDown(e); - if (e.Handled) - break; - } - } - } - } - - protected override void OnKeyUp(KeyEventArgs e) - { - base.OnKeyUp(e); - if (!e.Handled) - { - if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) - ChangeInput(); - if (!e.Handled) - { - foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) - { - item.Control.KeyUp(e); - if (e.Handled) - return; - } - } - } - } - - protected override void OnKeyPress(KeyPressEventArgs e) - { - base.OnKeyPress(e); - if (!e.Handled) - _search.Search(e.KeyChar); - } - - #endregion - - #region Mouse - - private TreeNodeAdvMouseEventArgs CreateMouseArgs(MouseEventArgs e) - { - TreeNodeAdvMouseEventArgs args = new TreeNodeAdvMouseEventArgs(e); - args.ViewLocation = new Point(e.X + OffsetX, - e.Y + _rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); - args.ModifierKeys = ModifierKeys; - args.Node = GetNodeAt(e.Location); - NodeControlInfo info = GetNodeControlInfoAt(args.Node, e.Location); - args.ControlBounds = info.Bounds; - args.Control = info.Control; - return args; - } - - protected override void OnMouseWheel(MouseEventArgs e) - { - _search.EndSearch(); - if (SystemInformation.MouseWheelScrollLines > 0) - { - int lines = e.Delta / 120 * SystemInformation.MouseWheelScrollLines; - int newValue = _vScrollBar.Value - lines; - newValue = Math.Min(_vScrollBar.Maximum - _vScrollBar.LargeChange + 1, newValue); - newValue = Math.Min(_vScrollBar.Maximum, newValue); - _vScrollBar.Value = Math.Max(_vScrollBar.Minimum, newValue); - } - base.OnMouseWheel(e); - } - - protected override void OnMouseDown(MouseEventArgs e) - { - if (CurrentEditorOwner != null) - { - CurrentEditorOwner.EndEdit(true); - return; - } - - if (!Focused) - Focus(); - - _search.EndSearch(); - if (e.Button == MouseButtons.Left) - { - TreeColumn c; - c = GetColumnDividerAt(e.Location); - if (c != null) - { - Input = new ResizeColumnState(this, c, e.Location); - return; - } - c = GetColumnAt(e.Location); - if (c != null) - { - Input = new ClickColumnState(this, c, e.Location); - UpdateView(); - return; - } - } - - ChangeInput(); - TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); - - if (args.Node != null && args.Control != null) - args.Control.MouseDown(args); - - if (!args.Handled) - Input.MouseDown(args); - - base.OnMouseDown(e); - } - - protected override void OnMouseClick(MouseEventArgs e) - { - //TODO: Disable when click on plusminus icon - TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); - if (args.Node != null) - OnNodeMouseClick(args); - - base.OnMouseClick(e); - } - - protected override void OnMouseDoubleClick(MouseEventArgs e) - { - TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); - - if (args.Node != null && args.Control != null) - args.Control.MouseDoubleClick(args); - - if (!args.Handled) - { - if (args.Node != null) - OnNodeMouseDoubleClick(args); - else - Input.MouseDoubleClick(args); - - if (!args.Handled) - { - if (args.Node != null && args.Button == MouseButtons.Left) - args.Node.IsExpanded = !args.Node.IsExpanded; - } - } - - base.OnMouseDoubleClick(e); - } - - protected override void OnMouseUp(MouseEventArgs e) - { - TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); - if (Input is ResizeColumnState) - Input.MouseUp(args); - else - { - if (args.Node != null && args.Control != null) - args.Control.MouseUp(args); - if (!args.Handled) - Input.MouseUp(args); - - base.OnMouseUp(e); - } - } - - protected override void OnMouseMove(MouseEventArgs e) - { - if (Input.MouseMove(e)) - return; - - base.OnMouseMove(e); - SetCursor(e); - UpdateToolTip(e); - if (ItemDragMode && Dist(e.Location, ItemDragStart) > ItemDragSensivity - && CurrentNode != null && CurrentNode.IsSelected) - { - ItemDragMode = false; - _toolTip.Active = false; - OnItemDrag(e.Button, Selection.ToArray()); - } - } - - protected override void OnMouseLeave(EventArgs e) - { - _hotColumn = null; - UpdateHeaders(); - base.OnMouseLeave(e); - } - - private void SetCursor(MouseEventArgs e) - { - TreeColumn col; - col = GetColumnDividerAt(e.Location); - if (col == null) - _innerCursor = null; - else - { - if (col.Width == 0) - _innerCursor = ResourceHelper.DVSplitCursor; - else - _innerCursor = Cursors.VSplit; - } - - col = GetColumnAt(e.Location); - if (col != _hotColumn) - { - _hotColumn = col; - UpdateHeaders(); - } - } - - internal TreeColumn GetColumnAt(Point p) - { - if (p.Y > ColumnHeaderHeight) - return null; - - int x = -OffsetX; - foreach (TreeColumn col in Columns) - { - if (col.IsVisible) - { - Rectangle rect = new Rectangle(x, 0, col.Width, ColumnHeaderHeight); - x += col.Width; - if (rect.Contains(p)) - return col; - } - } - return null; - } - - internal int GetColumnX(TreeColumn column) - { - int x = -OffsetX; - foreach (TreeColumn col in Columns) - { - if (col.IsVisible) - { - if (column == col) - return x; - else - x += col.Width; - } - } - return x; - } - - internal TreeColumn GetColumnDividerAt(Point p) - { - if (p.Y > ColumnHeaderHeight) - return null; - - int x = -OffsetX; - TreeColumn prevCol = null; - Rectangle left, right; - foreach (TreeColumn col in Columns) - { - if (col.IsVisible) - { - if (col.Width > 0) - { - left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); - right = new Rectangle(x + col.Width - (DividerWidth / 2), 0, DividerWidth / 2, ColumnHeaderHeight); - if (left.Contains(p) && prevCol != null) - return prevCol; - else if (right.Contains(p)) - return col; - } - prevCol = col; - x += col.Width; - } - } - - left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); - if (left.Contains(p) && prevCol != null) - return prevCol; - - return null; - } - - TreeColumn _tooltipColumn; - private void UpdateToolTip(MouseEventArgs e) - { - TreeColumn col = GetColumnAt(e.Location); - if (col != null) - { - if (col != _tooltipColumn) - SetTooltip(col.TooltipText); - } - else - DisplayNodesTooltip(e); - _tooltipColumn = col; - } - - TreeNodeAdv _hotNode; - NodeControl _hotControl; - private void DisplayNodesTooltip(MouseEventArgs e) - { - if (ShowNodeToolTips) - { - TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); - if (args.Node != null && args.Control != null) - { - if (args.Node != _hotNode || args.Control != _hotControl) - SetTooltip(GetNodeToolTip(args)); - } - else - _toolTip.SetToolTip(this, null); - - _hotControl = args.Control; - _hotNode = args.Node; - } - else - _toolTip.SetToolTip(this, null); - } - - private void SetTooltip(string text) - { - if (!String.IsNullOrEmpty(text)) - { - _toolTip.Active = false; - _toolTip.SetToolTip(this, text); - _toolTip.Active = true; - } - else - _toolTip.SetToolTip(this, null); - } - - private string GetNodeToolTip(TreeNodeAdvMouseEventArgs args) - { - string msg = args.Control.GetToolTip(args.Node); - - BaseTextControl btc = args.Control as BaseTextControl; - if (btc != null && btc.DisplayHiddenContentInToolTip && String.IsNullOrEmpty(msg)) - { - Size ms = btc.GetActualSize(args.Node, _measureContext); - if (ms.Width > args.ControlBounds.Size.Width || ms.Height > args.ControlBounds.Size.Height - || args.ControlBounds.Right - OffsetX > DisplayRectangle.Width) - msg = btc.GetLabel(args.Node); - } - - if (String.IsNullOrEmpty(msg) && DefaultToolTipProvider != null) - msg = DefaultToolTipProvider.GetToolTip(args.Node, args.Control); - - return msg; - } - - #endregion - - #region DragDrop - - private bool _dragAutoScrollFlag = false; - private Bitmap _dragBitmap = null; - private System.Threading.Timer _dragTimer; - - private void StartDragTimer() - { - if (_dragTimer == null) - _dragTimer = new System.Threading.Timer(new TimerCallback(DragTimerTick), null, 0, 100); - } - - private void StopDragTimer() - { - if (_dragTimer != null) - { - _dragTimer.Dispose(); - _dragTimer = null; - } - } - - private void SetDropPosition(Point pt) - { - TreeNodeAdv node = GetNodeAt(pt); - OnDropNodeValidating(pt, ref node); - _dropPosition.Node = node; - if (node != null) - { - Rectangle first = _rowLayout.GetRowBounds(FirstVisibleRow); - Rectangle bounds = _rowLayout.GetRowBounds(node.Row); - float pos = (pt.Y + first.Y - ColumnHeaderHeight - bounds.Y) / (float)bounds.Height; - if (pos < TopEdgeSensivity) - _dropPosition.Position = NodePosition.Before; - else if (pos > (1 - BottomEdgeSensivity)) - _dropPosition.Position = NodePosition.After; - else - _dropPosition.Position = NodePosition.Inside; - } - } - - private void DragTimerTick(object state) - { - _dragAutoScrollFlag = true; - } - - private void DragAutoScroll() - { - _dragAutoScrollFlag = false; - Point pt = PointToClient(MousePosition); - if (pt.Y < 20 && _vScrollBar.Value > 0) - _vScrollBar.Value--; - else if (pt.Y > Height - 20 && _vScrollBar.Value <= _vScrollBar.Maximum - _vScrollBar.LargeChange) - _vScrollBar.Value++; - } - - public void DoDragDropSelectedNodes(DragDropEffects allowedEffects) - { - if (SelectedNodes.Count > 0) - { - TreeNodeAdv[] nodes = new TreeNodeAdv[SelectedNodes.Count]; - SelectedNodes.CopyTo(nodes, 0); - DoDragDrop(nodes, allowedEffects); - } - } - - private void CreateDragBitmap(IDataObject data) - { - if (UseColumns || !DisplayDraggingNodes) - return; - - TreeNodeAdv[] nodes = data.GetData(typeof(TreeNodeAdv[])) as TreeNodeAdv[]; - if (nodes != null && nodes.Length > 0) - { - Rectangle rect = DisplayRectangle; - Bitmap bitmap = new Bitmap(rect.Width, rect.Height); - using (Graphics gr = Graphics.FromImage(bitmap)) - { - gr.Clear(BackColor); - DrawContext context = new DrawContext(); - context.Graphics = gr; - context.Font = Font; - context.Enabled = true; - int y = 0; - int maxWidth = 0; - foreach (TreeNodeAdv node in nodes) - { - if (node.Tree == this) - { - int x = 0; - int height = _rowLayout.GetRowBounds(node.Row).Height; - foreach (NodeControl c in NodeControls) - { - Size s = c.GetActualSize(node, context); - if (!s.IsEmpty) - { - int width = s.Width; - rect = new Rectangle(x, y, width, height); - x += (width + 1); - context.Bounds = rect; - c.Draw(node, context); - } - } - y += height; - maxWidth = Math.Max(maxWidth, x); - } - } - - if (maxWidth > 0 && y > 0) - { - _dragBitmap = new Bitmap(maxWidth, y, PixelFormat.Format32bppArgb); - using (Graphics tgr = Graphics.FromImage(_dragBitmap)) - tgr.DrawImage(bitmap, Point.Empty); - BitmapHelper.SetAlphaChanelValue(_dragBitmap, 150); - } - else - _dragBitmap = null; - } - } - } - - protected override void OnDragOver(DragEventArgs drgevent) - { - ItemDragMode = false; - Point pt = PointToClient(new Point(drgevent.X, drgevent.Y)); - if (_dragAutoScrollFlag) - DragAutoScroll(); - SetDropPosition(pt); - UpdateView(); - base.OnDragOver(drgevent); - } - - protected override void OnDragEnter(DragEventArgs drgevent) - { - _search.EndSearch(); - DragMode = true; - CreateDragBitmap(drgevent.Data); - base.OnDragEnter(drgevent); - } - - protected override void OnDragLeave(EventArgs e) - { - DragMode = false; - UpdateView(); - base.OnDragLeave(e); - } - - protected override void OnDragDrop(DragEventArgs drgevent) - { - DragMode = false; - UpdateView(); - base.OnDragDrop(drgevent); - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using Aga.Controls.Tree.NodeControls; +using System.Drawing.Imaging; +using System.Threading; + +namespace Aga.Controls.Tree +{ + public partial class TreeViewAdv + { + #region Keys + + protected override bool IsInputChar(char charCode) + { + return true; + } + + protected override bool IsInputKey(Keys keyData) + { + if (((keyData & Keys.Up) == Keys.Up) + || ((keyData & Keys.Down) == Keys.Down) + || ((keyData & Keys.Left) == Keys.Left) + || ((keyData & Keys.Right) == Keys.Right)) + return true; + else + return base.IsInputKey(keyData); + } + + internal void ChangeInput() + { + if ((ModifierKeys & Keys.Shift) == Keys.Shift) + { + if (!(Input is InputWithShift)) + Input = new InputWithShift(this); + } + else if ((ModifierKeys & Keys.Control) == Keys.Control) + { + if (!(Input is InputWithControl)) + Input = new InputWithControl(this); + } + else + { + if (!(Input.GetType() == typeof(NormalInputState))) + Input = new NormalInputState(this); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (!e.Handled) + { + if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) + ChangeInput(); + Input.KeyDown(e); + if (!e.Handled) + { + foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) + { + item.Control.KeyDown(e); + if (e.Handled) + break; + } + } + } + } + + protected override void OnKeyUp(KeyEventArgs e) + { + base.OnKeyUp(e); + if (!e.Handled) + { + if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) + ChangeInput(); + if (!e.Handled) + { + foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) + { + item.Control.KeyUp(e); + if (e.Handled) + return; + } + } + } + } + + protected override void OnKeyPress(KeyPressEventArgs e) + { + base.OnKeyPress(e); + if (!e.Handled) + _search.Search(e.KeyChar); + } + + #endregion + + #region Mouse + + private TreeNodeAdvMouseEventArgs CreateMouseArgs(MouseEventArgs e) + { + TreeNodeAdvMouseEventArgs args = new TreeNodeAdvMouseEventArgs(e); + args.ViewLocation = new Point(e.X + OffsetX, + e.Y + _rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); + args.ModifierKeys = ModifierKeys; + args.Node = GetNodeAt(e.Location); + NodeControlInfo info = GetNodeControlInfoAt(args.Node, e.Location); + args.ControlBounds = info.Bounds; + args.Control = info.Control; + return args; + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + _search.EndSearch(); + if (SystemInformation.MouseWheelScrollLines > 0) + { + int lines = e.Delta / 120 * SystemInformation.MouseWheelScrollLines; + int newValue = _vScrollBar.Value - lines; + newValue = Math.Min(_vScrollBar.Maximum - _vScrollBar.LargeChange + 1, newValue); + newValue = Math.Min(_vScrollBar.Maximum, newValue); + _vScrollBar.Value = Math.Max(_vScrollBar.Minimum, newValue); + } + base.OnMouseWheel(e); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + if (CurrentEditorOwner != null) + { + CurrentEditorOwner.EndEdit(true); + return; + } + + if (!Focused) + Focus(); + + _search.EndSearch(); + if (e.Button == MouseButtons.Left) + { + TreeColumn c; + c = GetColumnDividerAt(e.Location); + if (c != null) + { + Input = new ResizeColumnState(this, c, e.Location); + return; + } + c = GetColumnAt(e.Location); + if (c != null) + { + Input = new ClickColumnState(this, c, e.Location); + UpdateView(); + return; + } + } + + ChangeInput(); + TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); + + if (args.Node != null && args.Control != null) + args.Control.MouseDown(args); + + if (!args.Handled) + Input.MouseDown(args); + + base.OnMouseDown(e); + } + + protected override void OnMouseClick(MouseEventArgs e) + { + //TODO: Disable when click on plusminus icon + TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); + if (args.Node != null) + OnNodeMouseClick(args); + + base.OnMouseClick(e); + } + + protected override void OnMouseDoubleClick(MouseEventArgs e) + { + TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); + + if (args.Node != null && args.Control != null) + args.Control.MouseDoubleClick(args); + + if (!args.Handled) + { + if (args.Node != null) + OnNodeMouseDoubleClick(args); + else + Input.MouseDoubleClick(args); + + if (!args.Handled) + { + if (args.Node != null && args.Button == MouseButtons.Left) + args.Node.IsExpanded = !args.Node.IsExpanded; + } + } + + base.OnMouseDoubleClick(e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); + if (Input is ResizeColumnState) + Input.MouseUp(args); + else + { + if (args.Node != null && args.Control != null) + args.Control.MouseUp(args); + if (!args.Handled) + Input.MouseUp(args); + + base.OnMouseUp(e); + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + if (Input.MouseMove(e)) + return; + + base.OnMouseMove(e); + SetCursor(e); + UpdateToolTip(e); + if (ItemDragMode && Dist(e.Location, ItemDragStart) > ItemDragSensivity + && CurrentNode != null && CurrentNode.IsSelected) + { + ItemDragMode = false; + _toolTip.Active = false; + OnItemDrag(e.Button, Selection.ToArray()); + } + } + + protected override void OnMouseLeave(EventArgs e) + { + _hotColumn = null; + UpdateHeaders(); + base.OnMouseLeave(e); + } + + private void SetCursor(MouseEventArgs e) + { + TreeColumn col; + col = GetColumnDividerAt(e.Location); + if (col == null) + _innerCursor = null; + else + { + if (col.Width == 0) + _innerCursor = ResourceHelper.DVSplitCursor; + else + _innerCursor = Cursors.VSplit; + } + + col = GetColumnAt(e.Location); + if (col != _hotColumn) + { + _hotColumn = col; + UpdateHeaders(); + } + } + + internal TreeColumn GetColumnAt(Point p) + { + if (p.Y > ColumnHeaderHeight) + return null; + + int x = -OffsetX; + foreach (TreeColumn col in Columns) + { + if (col.IsVisible) + { + Rectangle rect = new Rectangle(x, 0, col.Width, ColumnHeaderHeight); + x += col.Width; + if (rect.Contains(p)) + return col; + } + } + return null; + } + + internal int GetColumnX(TreeColumn column) + { + int x = -OffsetX; + foreach (TreeColumn col in Columns) + { + if (col.IsVisible) + { + if (column == col) + return x; + else + x += col.Width; + } + } + return x; + } + + internal TreeColumn GetColumnDividerAt(Point p) + { + if (p.Y > ColumnHeaderHeight) + return null; + + int x = -OffsetX; + TreeColumn prevCol = null; + Rectangle left, right; + foreach (TreeColumn col in Columns) + { + if (col.IsVisible) + { + if (col.Width > 0) + { + left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); + right = new Rectangle(x + col.Width - (DividerWidth / 2), 0, DividerWidth / 2, ColumnHeaderHeight); + if (left.Contains(p) && prevCol != null) + return prevCol; + else if (right.Contains(p)) + return col; + } + prevCol = col; + x += col.Width; + } + } + + left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); + if (left.Contains(p) && prevCol != null) + return prevCol; + + return null; + } + + TreeColumn _tooltipColumn; + private void UpdateToolTip(MouseEventArgs e) + { + TreeColumn col = GetColumnAt(e.Location); + if (col != null) + { + if (col != _tooltipColumn) + SetTooltip(col.TooltipText); + } + else + DisplayNodesTooltip(e); + _tooltipColumn = col; + } + + TreeNodeAdv _hotNode; + NodeControl _hotControl; + private void DisplayNodesTooltip(MouseEventArgs e) + { + if (ShowNodeToolTips) + { + TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); + if (args.Node != null && args.Control != null) + { + if (args.Node != _hotNode || args.Control != _hotControl) + SetTooltip(GetNodeToolTip(args)); + } + else + _toolTip.SetToolTip(this, null); + + _hotControl = args.Control; + _hotNode = args.Node; + } + else + _toolTip.SetToolTip(this, null); + } + + private void SetTooltip(string text) + { + if (!String.IsNullOrEmpty(text)) + { + _toolTip.Active = false; + _toolTip.SetToolTip(this, text); + _toolTip.Active = true; + } + else + _toolTip.SetToolTip(this, null); + } + + private string GetNodeToolTip(TreeNodeAdvMouseEventArgs args) + { + string msg = args.Control.GetToolTip(args.Node); + + BaseTextControl btc = args.Control as BaseTextControl; + if (btc != null && btc.DisplayHiddenContentInToolTip && String.IsNullOrEmpty(msg)) + { + Size ms = btc.GetActualSize(args.Node, _measureContext); + if (ms.Width > args.ControlBounds.Size.Width || ms.Height > args.ControlBounds.Size.Height + || args.ControlBounds.Right - OffsetX > DisplayRectangle.Width) + msg = btc.GetLabel(args.Node); + } + + if (String.IsNullOrEmpty(msg) && DefaultToolTipProvider != null) + msg = DefaultToolTipProvider.GetToolTip(args.Node, args.Control); + + return msg; + } + + #endregion + + #region DragDrop + + private bool _dragAutoScrollFlag = false; + private Bitmap _dragBitmap = null; + private System.Threading.Timer _dragTimer; + + private void StartDragTimer() + { + if (_dragTimer == null) + _dragTimer = new System.Threading.Timer(new TimerCallback(DragTimerTick), null, 0, 100); + } + + private void StopDragTimer() + { + if (_dragTimer != null) + { + _dragTimer.Dispose(); + _dragTimer = null; + } + } + + private void SetDropPosition(Point pt) + { + TreeNodeAdv node = GetNodeAt(pt); + OnDropNodeValidating(pt, ref node); + _dropPosition.Node = node; + if (node != null) + { + Rectangle first = _rowLayout.GetRowBounds(FirstVisibleRow); + Rectangle bounds = _rowLayout.GetRowBounds(node.Row); + float pos = (pt.Y + first.Y - ColumnHeaderHeight - bounds.Y) / (float)bounds.Height; + if (pos < TopEdgeSensivity) + _dropPosition.Position = NodePosition.Before; + else if (pos > (1 - BottomEdgeSensivity)) + _dropPosition.Position = NodePosition.After; + else + _dropPosition.Position = NodePosition.Inside; + } + } + + private void DragTimerTick(object state) + { + _dragAutoScrollFlag = true; + } + + private void DragAutoScroll() + { + _dragAutoScrollFlag = false; + Point pt = PointToClient(MousePosition); + if (pt.Y < 20 && _vScrollBar.Value > 0) + _vScrollBar.Value--; + else if (pt.Y > Height - 20 && _vScrollBar.Value <= _vScrollBar.Maximum - _vScrollBar.LargeChange) + _vScrollBar.Value++; + } + + public void DoDragDropSelectedNodes(DragDropEffects allowedEffects) + { + if (SelectedNodes.Count > 0) + { + TreeNodeAdv[] nodes = new TreeNodeAdv[SelectedNodes.Count]; + SelectedNodes.CopyTo(nodes, 0); + DoDragDrop(nodes, allowedEffects); + } + } + + private void CreateDragBitmap(IDataObject data) + { + if (UseColumns || !DisplayDraggingNodes) + return; + + TreeNodeAdv[] nodes = data.GetData(typeof(TreeNodeAdv[])) as TreeNodeAdv[]; + if (nodes != null && nodes.Length > 0) + { + Rectangle rect = DisplayRectangle; + Bitmap bitmap = new Bitmap(rect.Width, rect.Height); + using (Graphics gr = Graphics.FromImage(bitmap)) + { + gr.Clear(BackColor); + DrawContext context = new DrawContext(); + context.Graphics = gr; + context.Font = Font; + context.Enabled = true; + int y = 0; + int maxWidth = 0; + foreach (TreeNodeAdv node in nodes) + { + if (node.Tree == this) + { + int x = 0; + int height = _rowLayout.GetRowBounds(node.Row).Height; + foreach (NodeControl c in NodeControls) + { + Size s = c.GetActualSize(node, context); + if (!s.IsEmpty) + { + int width = s.Width; + rect = new Rectangle(x, y, width, height); + x += (width + 1); + context.Bounds = rect; + c.Draw(node, context); + } + } + y += height; + maxWidth = Math.Max(maxWidth, x); + } + } + + if (maxWidth > 0 && y > 0) + { + _dragBitmap = new Bitmap(maxWidth, y, PixelFormat.Format32bppArgb); + using (Graphics tgr = Graphics.FromImage(_dragBitmap)) + tgr.DrawImage(bitmap, Point.Empty); + BitmapHelper.SetAlphaChanelValue(_dragBitmap, 150); + } + else + _dragBitmap = null; + } + } + } + + protected override void OnDragOver(DragEventArgs drgevent) + { + ItemDragMode = false; + Point pt = PointToClient(new Point(drgevent.X, drgevent.Y)); + if (_dragAutoScrollFlag) + DragAutoScroll(); + SetDropPosition(pt); + UpdateView(); + base.OnDragOver(drgevent); + } + + protected override void OnDragEnter(DragEventArgs drgevent) + { + _search.EndSearch(); + DragMode = true; + CreateDragBitmap(drgevent.Data); + base.OnDragEnter(drgevent); + } + + protected override void OnDragLeave(EventArgs e) + { + DragMode = false; + UpdateView(); + base.OnDragLeave(e); + } + + protected override void OnDragDrop(DragEventArgs drgevent) + { + DragMode = false; + UpdateView(); + base.OnDragDrop(drgevent); + } + + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.Properties.cs b/Aga.Controls/Tree/TreeViewAdv.Properties.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeViewAdv.Properties.cs rename to Aga.Controls/Tree/TreeViewAdv.Properties.cs index 302d48c..6d042d0 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.Properties.cs +++ b/Aga.Controls/Tree/TreeViewAdv.Properties.cs @@ -1,727 +1,727 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Design; -using System.Windows.Forms; - -using Aga.Controls.Tree.NodeControls; - -namespace Aga.Controls.Tree -{ - public partial class TreeViewAdv - { - private Cursor _innerCursor = null; - - public override Cursor Cursor - { - get - { - if (_innerCursor != null) - return _innerCursor; - else - return base.Cursor; - } - set - { - base.Cursor = value; - } - } - - #region Internal Properties - - private IRowLayout _rowLayout; - - private bool _dragMode; - private bool DragMode - { - get { return _dragMode; } - set - { - _dragMode = value; - if (!value) - { - StopDragTimer(); - if (_dragBitmap != null) - _dragBitmap.Dispose(); - _dragBitmap = null; - } - else - StartDragTimer(); - } - } - - internal int ColumnHeaderHeight - { - get - { - if (UseColumns) - return _columnHeaderHeight; - else - return 0; - } - } - - /// - /// returns all nodes, which parent is expanded - /// - private IEnumerable VisibleNodes - { - get - { - TreeNodeAdv node = Root; - while (node != null) - { - node = node.NextVisibleNode; - if (node != null) - yield return node; - } - } - } - - private bool _suspendSelectionEvent; - internal bool SuspendSelectionEvent - { - get { return _suspendSelectionEvent; } - set - { - if (value != _suspendSelectionEvent) - { - _suspendSelectionEvent = value; - if (!_suspendSelectionEvent && _fireSelectionEvent) - OnSelectionChanged(); - } - } - } - - private List _rowMap; - internal List RowMap - { - get { return _rowMap; } - } - - private TreeNodeAdv _selectionStart; - internal TreeNodeAdv SelectionStart - { - get { return _selectionStart; } - set { _selectionStart = value; } - } - - private InputState _input; - internal InputState Input - { - get { return _input; } - set - { - _input = value; - } - } - - private bool _itemDragMode; - internal bool ItemDragMode - { - get { return _itemDragMode; } - set { _itemDragMode = value; } - } - - private Point _itemDragStart; - internal Point ItemDragStart - { - get { return _itemDragStart; } - set { _itemDragStart = value; } - } - - - /// - /// Number of rows fits to the current page - /// - internal int CurrentPageSize - { - get - { - return _rowLayout.CurrentPageSize; - } - } - - /// - /// Number of all visible nodes (which parent is expanded) - /// - internal int RowCount - { - get - { - return RowMap.Count; - } - } - - private int _contentWidth = 0; - private int ContentWidth - { - get - { - return _contentWidth; - } - } - - private int _firstVisibleRow; - internal int FirstVisibleRow - { - get { return _firstVisibleRow; } - set - { - HideEditor(); - _firstVisibleRow = value; - UpdateView(); - } - } - - private int _offsetX; - public int OffsetX - { - get { return _offsetX; } - private set - { - HideEditor(); - _offsetX = value; - UpdateView(); - } - } - - public override Rectangle DisplayRectangle - { - get - { - Rectangle r = ClientRectangle; - //r.Y += ColumnHeaderHeight; - //r.Height -= ColumnHeaderHeight; - int w = _vScrollBar.Visible ? _vScrollBar.Width : 0; - int h = _hScrollBar.Visible ? _hScrollBar.Height : 0; - return new Rectangle(r.X, r.Y, r.Width - w, r.Height - h); - } - } - - private List _selection; - internal List Selection - { - get { return _selection; } - } - - #endregion - - #region Public Properties - - #region DesignTime - - private bool _shiftFirstNode; - [DefaultValue(false), Category("Behavior")] - public bool ShiftFirstNode - { - get { return _shiftFirstNode; } - set { _shiftFirstNode = value; } - } - - private bool _displayDraggingNodes; - [DefaultValue(false), Category("Behavior")] - public bool DisplayDraggingNodes - { - get { return _displayDraggingNodes; } - set { _displayDraggingNodes = value; } - } - - private bool _fullRowSelect; - [DefaultValue(false), Category("Behavior")] - public bool FullRowSelect - { - get { return _fullRowSelect; } - set - { - _fullRowSelect = value; - UpdateView(); - } - } - - private bool _useColumns; - [DefaultValue(false), Category("Behavior")] - public bool UseColumns - { - get { return _useColumns; } - set - { - _useColumns = value; - FullUpdate(); - } - } - - private bool _allowColumnReorder; - [DefaultValue(false), Category("Behavior")] - public bool AllowColumnReorder - { - get { return _allowColumnReorder; } - set { _allowColumnReorder = value; } - } - - private bool _showLines = true; - [DefaultValue(true), Category("Behavior")] - public bool ShowLines - { - get { return _showLines; } - set - { - _showLines = value; - UpdateView(); - } - } - - private bool _showPlusMinus = true; - [DefaultValue(true), Category("Behavior")] - public bool ShowPlusMinus - { - get { return _showPlusMinus; } - set - { - _showPlusMinus = value; - FullUpdate(); - } - } - - private bool _showNodeToolTips = false; - [DefaultValue(false), Category("Behavior")] - public bool ShowNodeToolTips - { - get { return _showNodeToolTips; } - set { _showNodeToolTips = value; } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), DefaultValue(true), Category("Behavior"), Obsolete("No longer used")] - public bool KeepNodesExpanded - { - get { return true; } - set {} - } - - private ITreeModel _model; - /// - /// The model associated with this . - /// - /// - /// - [Browsable(false)] - public ITreeModel Model - { - get { return _model; } - set - { - if (_model != value) - { - AbortBackgroundExpandingThreads(); - if (_model != null) - UnbindModelEvents(); - _model = value; - CreateNodes(); - FullUpdate(); - if (_model != null) - BindModelEvents(); - } - } - } - - private static Font _font = SystemFonts.MessageBoxFont; - /// - /// The font to render content in. - /// - [Category("Appearance"), Description("The font to render TreeViewAdv content in.")] - public override Font Font - { - get - { - return (base.Font); - } - set - { - if (value == null) - base.Font = _font; - else - { - if (value == DefaultFont) - base.Font = _font; - else - base.Font = value; - } - } - } - public override void ResetFont() - { - Font = null; - } - private bool ShouldSerializeFont() - { - return (!Font.Equals(_font)); - } - // End font property - - private BorderStyle _borderStyle = BorderStyle.Fixed3D; - [DefaultValue(BorderStyle.Fixed3D), Category("Appearance")] - public BorderStyle BorderStyle - { - get - { - return this._borderStyle; - } - set - { - if (_borderStyle != value) - { - _borderStyle = value; - base.UpdateStyles(); - } - } - } - - private bool _autoRowHeight = false; - /// - /// Set to true to expand each row's height to fit the text of it's largest column. - /// - [DefaultValue(false), Category("Appearance"), Description("Expand each row's height to fit the text of it's largest column.")] - public bool AutoRowHeight - { - get - { - return _autoRowHeight; - } - set - { - _autoRowHeight = value; - if (value) - _rowLayout = new AutoRowHeightLayout(this, RowHeight); - else - _rowLayout = new FixedRowHeightLayout(this, RowHeight); - FullUpdate(); - } - } - - private GridLineStyle _gridLineStyle = GridLineStyle.None; - [DefaultValue(GridLineStyle.None), Category("Appearance")] - public GridLineStyle GridLineStyle - { - get - { - return _gridLineStyle; - } - set - { - if (value != _gridLineStyle) - { - _gridLineStyle = value; - UpdateView(); - OnGridLineStyleChanged(); - } - } - } - - private int _rowHeight = 16; - [DefaultValue(16), Category("Appearance")] - public int RowHeight - { - get - { - return _rowHeight; - } - set - { - if (value <= 0) - throw new ArgumentOutOfRangeException("value"); - - _rowHeight = value; - _rowLayout.PreferredRowHeight = value; - FullUpdate(); - } - } - - private TreeSelectionMode _selectionMode = TreeSelectionMode.Single; - [DefaultValue(TreeSelectionMode.Single), Category("Behavior")] - public TreeSelectionMode SelectionMode - { - get { return _selectionMode; } - set { _selectionMode = value; } - } - - private bool _hideSelection; - [DefaultValue(false), Category("Behavior")] - public bool HideSelection - { - get { return _hideSelection; } - set - { - _hideSelection = value; - UpdateView(); - } - } - - private float _topEdgeSensivity = 0.3f; - [DefaultValue(0.3f), Category("Behavior")] - public float TopEdgeSensivity - { - get { return _topEdgeSensivity; } - set - { - if (value < 0 || value > 1) - throw new ArgumentOutOfRangeException(); - _topEdgeSensivity = value; - } - } - - private float _bottomEdgeSensivity = 0.3f; - [DefaultValue(0.3f), Category("Behavior")] - public float BottomEdgeSensivity - { - get { return _bottomEdgeSensivity; } - set - { - if (value < 0 || value > 1) - throw new ArgumentOutOfRangeException("value should be from 0 to 1"); - _bottomEdgeSensivity = value; - } - } - - private bool _loadOnDemand; - [DefaultValue(false), Category("Behavior")] - public bool LoadOnDemand - { - get { return _loadOnDemand; } - set { _loadOnDemand = value; } - } - - private bool _unloadCollapsedOnReload = false; - [DefaultValue(false), Category("Behavior")] - public bool UnloadCollapsedOnReload - { - get { return _unloadCollapsedOnReload; } - set { _unloadCollapsedOnReload = value; } - } - - private int _indent = 19; - [DefaultValue(19), Category("Behavior")] - public int Indent - { - get { return _indent; } - set - { - _indent = value; - UpdateView(); - } - } - - private Color _lineColor = SystemColors.ControlDark; - [Category("Behavior")] - public Color LineColor - { - get { return _lineColor; } - set - { - _lineColor = value; - CreateLinePen(); - UpdateView(); - } - } - - private Color _dragDropMarkColor = Color.Black; - [Category("Behavior")] - public Color DragDropMarkColor - { - get { return _dragDropMarkColor; } - set - { - _dragDropMarkColor = value; - CreateMarkPen(); - } - } - - private float _dragDropMarkWidth = 3.0f; - [DefaultValue(3.0f), Category("Behavior")] - public float DragDropMarkWidth - { - get { return _dragDropMarkWidth; } - set - { - _dragDropMarkWidth = value; - CreateMarkPen(); - } - } - - private bool _highlightDropPosition = true; - [DefaultValue(true), Category("Behavior")] - public bool HighlightDropPosition - { - get { return _highlightDropPosition; } - set { _highlightDropPosition = value; } - } - - private TreeColumnCollection _columns; - [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public Collection Columns - { - get { return _columns; } - } - - private NodeControlsCollection _controls; - [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [Editor(typeof(NodeControlCollectionEditor), typeof(UITypeEditor))] - public Collection NodeControls - { - get - { - return _controls; - } - } - - private bool _asyncExpanding; - /// - /// When set to true, node contents will be read in background thread. - /// - [Category("Behavior"), DefaultValue(false), Description("Read children in a background thread when expanding.")] - public bool AsyncExpanding - { - get { return _asyncExpanding; } - set { _asyncExpanding = value; } - } - - #endregion - - #region RunTime - - private IToolTipProvider _defaultToolTipProvider = null; - [Browsable(false)] - public IToolTipProvider DefaultToolTipProvider - { - get { return _defaultToolTipProvider; } - set { _defaultToolTipProvider = value; } - } - - [Browsable(false)] - public IEnumerable AllNodes - { - get - { - if (_root.Nodes.Count > 0) - { - TreeNodeAdv node = _root.Nodes[0]; - while (node != null) - { - yield return node; - if (node.Nodes.Count > 0) - node = node.Nodes[0]; - else if (node.NextNode != null) - node = node.NextNode; - else - node = node.BottomNode; - } - } - } - } - - private DropPosition _dropPosition; - [Browsable(false)] - public DropPosition DropPosition - { - get { return _dropPosition; } - set { _dropPosition = value; } - } - - private TreeNodeAdv _root; - [Browsable(false)] - public TreeNodeAdv Root - { - get { return _root; } - } - - private ReadOnlyCollection _readonlySelection; - [Browsable(false)] - public ReadOnlyCollection SelectedNodes - { - get - { - return _readonlySelection; - } - } - - [Browsable(false)] - public TreeNodeAdv SelectedNode - { - get - { - if (Selection.Count > 0) - { - if (CurrentNode != null && CurrentNode.IsSelected) - return CurrentNode; - else - return Selection[0]; - } - else - return null; - } - set - { - if (SelectedNode == value) - return; - - BeginUpdate(); - try - { - if (value == null) - { - ClearSelectionInternal(); - } - else - { - if (!IsMyNode(value)) - throw new ArgumentException(); - - ClearSelectionInternal(); - value.IsSelected = true; - CurrentNode = value; - EnsureVisible(value); - } - } - finally - { - EndUpdate(); - } - } - } - - private TreeNodeAdv _currentNode; - [Browsable(false)] - public TreeNodeAdv CurrentNode - { - get { return _currentNode; } - internal set { _currentNode = value; } - } - - [Browsable(false)] - public int ItemCount - { - get { return RowMap.Count; } - } - - /// - /// Indicates the distance the content is scrolled to the left - /// - [Browsable(false)] - public int HorizontalScrollPosition - { - get - { - if (_hScrollBar.Visible) - return _hScrollBar.Value; - else - return 0; - } - } - - #endregion - - #endregion - - } -} +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Design; +using System.Windows.Forms; + +using Aga.Controls.Tree.NodeControls; + +namespace Aga.Controls.Tree +{ + public partial class TreeViewAdv + { + private Cursor _innerCursor = null; + + public override Cursor Cursor + { + get + { + if (_innerCursor != null) + return _innerCursor; + else + return base.Cursor; + } + set + { + base.Cursor = value; + } + } + + #region Internal Properties + + private IRowLayout _rowLayout; + + private bool _dragMode; + private bool DragMode + { + get { return _dragMode; } + set + { + _dragMode = value; + if (!value) + { + StopDragTimer(); + if (_dragBitmap != null) + _dragBitmap.Dispose(); + _dragBitmap = null; + } + else + StartDragTimer(); + } + } + + internal int ColumnHeaderHeight + { + get + { + if (UseColumns) + return _columnHeaderHeight; + else + return 0; + } + } + + /// + /// returns all nodes, which parent is expanded + /// + private IEnumerable VisibleNodes + { + get + { + TreeNodeAdv node = Root; + while (node != null) + { + node = node.NextVisibleNode; + if (node != null) + yield return node; + } + } + } + + private bool _suspendSelectionEvent; + internal bool SuspendSelectionEvent + { + get { return _suspendSelectionEvent; } + set + { + if (value != _suspendSelectionEvent) + { + _suspendSelectionEvent = value; + if (!_suspendSelectionEvent && _fireSelectionEvent) + OnSelectionChanged(); + } + } + } + + private List _rowMap; + internal List RowMap + { + get { return _rowMap; } + } + + private TreeNodeAdv _selectionStart; + internal TreeNodeAdv SelectionStart + { + get { return _selectionStart; } + set { _selectionStart = value; } + } + + private InputState _input; + internal InputState Input + { + get { return _input; } + set + { + _input = value; + } + } + + private bool _itemDragMode; + internal bool ItemDragMode + { + get { return _itemDragMode; } + set { _itemDragMode = value; } + } + + private Point _itemDragStart; + internal Point ItemDragStart + { + get { return _itemDragStart; } + set { _itemDragStart = value; } + } + + + /// + /// Number of rows fits to the current page + /// + internal int CurrentPageSize + { + get + { + return _rowLayout.CurrentPageSize; + } + } + + /// + /// Number of all visible nodes (which parent is expanded) + /// + internal int RowCount + { + get + { + return RowMap.Count; + } + } + + private int _contentWidth = 0; + private int ContentWidth + { + get + { + return _contentWidth; + } + } + + private int _firstVisibleRow; + internal int FirstVisibleRow + { + get { return _firstVisibleRow; } + set + { + HideEditor(); + _firstVisibleRow = value; + UpdateView(); + } + } + + private int _offsetX; + public int OffsetX + { + get { return _offsetX; } + private set + { + HideEditor(); + _offsetX = value; + UpdateView(); + } + } + + public override Rectangle DisplayRectangle + { + get + { + Rectangle r = ClientRectangle; + //r.Y += ColumnHeaderHeight; + //r.Height -= ColumnHeaderHeight; + int w = _vScrollBar.Visible ? _vScrollBar.Width : 0; + int h = _hScrollBar.Visible ? _hScrollBar.Height : 0; + return new Rectangle(r.X, r.Y, r.Width - w, r.Height - h); + } + } + + private List _selection; + internal List Selection + { + get { return _selection; } + } + + #endregion + + #region Public Properties + + #region DesignTime + + private bool _shiftFirstNode; + [DefaultValue(false), Category("Behavior")] + public bool ShiftFirstNode + { + get { return _shiftFirstNode; } + set { _shiftFirstNode = value; } + } + + private bool _displayDraggingNodes; + [DefaultValue(false), Category("Behavior")] + public bool DisplayDraggingNodes + { + get { return _displayDraggingNodes; } + set { _displayDraggingNodes = value; } + } + + private bool _fullRowSelect; + [DefaultValue(false), Category("Behavior")] + public bool FullRowSelect + { + get { return _fullRowSelect; } + set + { + _fullRowSelect = value; + UpdateView(); + } + } + + private bool _useColumns; + [DefaultValue(false), Category("Behavior")] + public bool UseColumns + { + get { return _useColumns; } + set + { + _useColumns = value; + FullUpdate(); + } + } + + private bool _allowColumnReorder; + [DefaultValue(false), Category("Behavior")] + public bool AllowColumnReorder + { + get { return _allowColumnReorder; } + set { _allowColumnReorder = value; } + } + + private bool _showLines = true; + [DefaultValue(true), Category("Behavior")] + public bool ShowLines + { + get { return _showLines; } + set + { + _showLines = value; + UpdateView(); + } + } + + private bool _showPlusMinus = true; + [DefaultValue(true), Category("Behavior")] + public bool ShowPlusMinus + { + get { return _showPlusMinus; } + set + { + _showPlusMinus = value; + FullUpdate(); + } + } + + private bool _showNodeToolTips = false; + [DefaultValue(false), Category("Behavior")] + public bool ShowNodeToolTips + { + get { return _showNodeToolTips; } + set { _showNodeToolTips = value; } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), DefaultValue(true), Category("Behavior"), Obsolete("No longer used")] + public bool KeepNodesExpanded + { + get { return true; } + set {} + } + + private ITreeModel _model; + /// + /// The model associated with this . + /// + /// + /// + [Browsable(false)] + public ITreeModel Model + { + get { return _model; } + set + { + if (_model != value) + { + AbortBackgroundExpandingThreads(); + if (_model != null) + UnbindModelEvents(); + _model = value; + CreateNodes(); + FullUpdate(); + if (_model != null) + BindModelEvents(); + } + } + } + + private static Font _font = SystemFonts.MessageBoxFont; + /// + /// The font to render content in. + /// + [Category("Appearance"), Description("The font to render TreeViewAdv content in.")] + public override Font Font + { + get + { + return (base.Font); + } + set + { + if (value == null) + base.Font = _font; + else + { + if (value == DefaultFont) + base.Font = _font; + else + base.Font = value; + } + } + } + public override void ResetFont() + { + Font = null; + } + private bool ShouldSerializeFont() + { + return (!Font.Equals(_font)); + } + // End font property + + private BorderStyle _borderStyle = BorderStyle.Fixed3D; + [DefaultValue(BorderStyle.Fixed3D), Category("Appearance")] + public BorderStyle BorderStyle + { + get + { + return this._borderStyle; + } + set + { + if (_borderStyle != value) + { + _borderStyle = value; + base.UpdateStyles(); + } + } + } + + private bool _autoRowHeight = false; + /// + /// Set to true to expand each row's height to fit the text of it's largest column. + /// + [DefaultValue(false), Category("Appearance"), Description("Expand each row's height to fit the text of it's largest column.")] + public bool AutoRowHeight + { + get + { + return _autoRowHeight; + } + set + { + _autoRowHeight = value; + if (value) + _rowLayout = new AutoRowHeightLayout(this, RowHeight); + else + _rowLayout = new FixedRowHeightLayout(this, RowHeight); + FullUpdate(); + } + } + + private GridLineStyle _gridLineStyle = GridLineStyle.None; + [DefaultValue(GridLineStyle.None), Category("Appearance")] + public GridLineStyle GridLineStyle + { + get + { + return _gridLineStyle; + } + set + { + if (value != _gridLineStyle) + { + _gridLineStyle = value; + UpdateView(); + OnGridLineStyleChanged(); + } + } + } + + private int _rowHeight = 16; + [DefaultValue(16), Category("Appearance")] + public int RowHeight + { + get + { + return _rowHeight; + } + set + { + if (value <= 0) + throw new ArgumentOutOfRangeException("value"); + + _rowHeight = value; + _rowLayout.PreferredRowHeight = value; + FullUpdate(); + } + } + + private TreeSelectionMode _selectionMode = TreeSelectionMode.Single; + [DefaultValue(TreeSelectionMode.Single), Category("Behavior")] + public TreeSelectionMode SelectionMode + { + get { return _selectionMode; } + set { _selectionMode = value; } + } + + private bool _hideSelection; + [DefaultValue(false), Category("Behavior")] + public bool HideSelection + { + get { return _hideSelection; } + set + { + _hideSelection = value; + UpdateView(); + } + } + + private float _topEdgeSensivity = 0.3f; + [DefaultValue(0.3f), Category("Behavior")] + public float TopEdgeSensivity + { + get { return _topEdgeSensivity; } + set + { + if (value < 0 || value > 1) + throw new ArgumentOutOfRangeException(); + _topEdgeSensivity = value; + } + } + + private float _bottomEdgeSensivity = 0.3f; + [DefaultValue(0.3f), Category("Behavior")] + public float BottomEdgeSensivity + { + get { return _bottomEdgeSensivity; } + set + { + if (value < 0 || value > 1) + throw new ArgumentOutOfRangeException("value should be from 0 to 1"); + _bottomEdgeSensivity = value; + } + } + + private bool _loadOnDemand; + [DefaultValue(false), Category("Behavior")] + public bool LoadOnDemand + { + get { return _loadOnDemand; } + set { _loadOnDemand = value; } + } + + private bool _unloadCollapsedOnReload = false; + [DefaultValue(false), Category("Behavior")] + public bool UnloadCollapsedOnReload + { + get { return _unloadCollapsedOnReload; } + set { _unloadCollapsedOnReload = value; } + } + + private int _indent = 19; + [DefaultValue(19), Category("Behavior")] + public int Indent + { + get { return _indent; } + set + { + _indent = value; + UpdateView(); + } + } + + private Color _lineColor = SystemColors.ControlDark; + [Category("Behavior")] + public Color LineColor + { + get { return _lineColor; } + set + { + _lineColor = value; + CreateLinePen(); + UpdateView(); + } + } + + private Color _dragDropMarkColor = Color.Black; + [Category("Behavior")] + public Color DragDropMarkColor + { + get { return _dragDropMarkColor; } + set + { + _dragDropMarkColor = value; + CreateMarkPen(); + } + } + + private float _dragDropMarkWidth = 3.0f; + [DefaultValue(3.0f), Category("Behavior")] + public float DragDropMarkWidth + { + get { return _dragDropMarkWidth; } + set + { + _dragDropMarkWidth = value; + CreateMarkPen(); + } + } + + private bool _highlightDropPosition = true; + [DefaultValue(true), Category("Behavior")] + public bool HighlightDropPosition + { + get { return _highlightDropPosition; } + set { _highlightDropPosition = value; } + } + + private TreeColumnCollection _columns; + [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public Collection Columns + { + get { return _columns; } + } + + private NodeControlsCollection _controls; + [Category("Behavior"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [Editor(typeof(NodeControlCollectionEditor), typeof(UITypeEditor))] + public Collection NodeControls + { + get + { + return _controls; + } + } + + private bool _asyncExpanding; + /// + /// When set to true, node contents will be read in background thread. + /// + [Category("Behavior"), DefaultValue(false), Description("Read children in a background thread when expanding.")] + public bool AsyncExpanding + { + get { return _asyncExpanding; } + set { _asyncExpanding = value; } + } + + #endregion + + #region RunTime + + private IToolTipProvider _defaultToolTipProvider = null; + [Browsable(false)] + public IToolTipProvider DefaultToolTipProvider + { + get { return _defaultToolTipProvider; } + set { _defaultToolTipProvider = value; } + } + + [Browsable(false)] + public IEnumerable AllNodes + { + get + { + if (_root.Nodes.Count > 0) + { + TreeNodeAdv node = _root.Nodes[0]; + while (node != null) + { + yield return node; + if (node.Nodes.Count > 0) + node = node.Nodes[0]; + else if (node.NextNode != null) + node = node.NextNode; + else + node = node.BottomNode; + } + } + } + } + + private DropPosition _dropPosition; + [Browsable(false)] + public DropPosition DropPosition + { + get { return _dropPosition; } + set { _dropPosition = value; } + } + + private TreeNodeAdv _root; + [Browsable(false)] + public TreeNodeAdv Root + { + get { return _root; } + } + + private ReadOnlyCollection _readonlySelection; + [Browsable(false)] + public ReadOnlyCollection SelectedNodes + { + get + { + return _readonlySelection; + } + } + + [Browsable(false)] + public TreeNodeAdv SelectedNode + { + get + { + if (Selection.Count > 0) + { + if (CurrentNode != null && CurrentNode.IsSelected) + return CurrentNode; + else + return Selection[0]; + } + else + return null; + } + set + { + if (SelectedNode == value) + return; + + BeginUpdate(); + try + { + if (value == null) + { + ClearSelectionInternal(); + } + else + { + if (!IsMyNode(value)) + throw new ArgumentException(); + + ClearSelectionInternal(); + value.IsSelected = true; + CurrentNode = value; + EnsureVisible(value); + } + } + finally + { + EndUpdate(); + } + } + } + + private TreeNodeAdv _currentNode; + [Browsable(false)] + public TreeNodeAdv CurrentNode + { + get { return _currentNode; } + internal set { _currentNode = value; } + } + + [Browsable(false)] + public int ItemCount + { + get { return RowMap.Count; } + } + + /// + /// Indicates the distance the content is scrolled to the left + /// + [Browsable(false)] + public int HorizontalScrollPosition + { + get + { + if (_hScrollBar.Visible) + return _hScrollBar.Value; + else + return 0; + } + } + + #endregion + + #endregion + + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.cs b/Aga.Controls/Tree/TreeViewAdv.cs similarity index 95% rename from External/Aga.Controls/Tree/TreeViewAdv.cs rename to Aga.Controls/Tree/TreeViewAdv.cs index 6c26fc1..cc9d144 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.cs +++ b/Aga.Controls/Tree/TreeViewAdv.cs @@ -1,1244 +1,1244 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Drawing; -using System.Security.Permissions; -using System.Threading; -using System.Windows.Forms; -using System.Collections; - -using Aga.Controls.Tree.NodeControls; -using Aga.Controls.Threading; - - -namespace Aga.Controls.Tree -{ - /// - /// Extensible advanced implemented in 100% managed C# code. - /// Features: Model/View architecture. Multiple column per node. Ability to select - /// multiple tree nodes. Different types of controls for each node column: - /// , Icon, Label... Drag and Drop highlighting. Load on - /// demand of nodes. Incremental search of nodes. - /// - public partial class TreeViewAdv : Control - { - private const int LeftMargin = 7; - internal const int ItemDragSensivity = 4; - private readonly int _columnHeaderHeight; - private const int DividerWidth = 9; - private const int DividerCorrectionGap = -2; - - private Pen _linePen; - private Pen _markPen; - private bool _suspendUpdate; - private bool _needFullUpdate; - private bool _fireSelectionEvent; - private NodePlusMinus _plusMinus; - private ToolTip _toolTip; - private DrawContext _measureContext; - private TreeColumn _hotColumn; - private IncrementalSearch _search; - private List _expandingNodes = new List(); - private AbortableThreadPool _threadPool = new AbortableThreadPool(); - - private float dpiX; - private float dpiY; - private float dpiXscale = 1; - private float dpiYscale = 1; - - #region Public Events - - [Category("Action")] - public event ItemDragEventHandler ItemDrag; - private void OnItemDrag(MouseButtons buttons, object item) - { - if (ItemDrag != null) - ItemDrag(this, new ItemDragEventArgs(buttons, item)); - } - - [Category("Behavior")] - public event EventHandler NodeMouseClick; - private void OnNodeMouseClick(TreeNodeAdvMouseEventArgs args) - { - if (NodeMouseClick != null) - NodeMouseClick(this, args); - } - - [Category("Behavior")] - public event EventHandler NodeMouseDoubleClick; - private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args) - { - if (NodeMouseDoubleClick != null) - NodeMouseDoubleClick(this, args); - } - - [Category("Behavior")] - public event EventHandler ColumnWidthChanged; - internal void OnColumnWidthChanged(TreeColumn column) - { - if (ColumnWidthChanged != null) - ColumnWidthChanged(this, new TreeColumnEventArgs(column)); - } - - [Category("Behavior")] - public event EventHandler ColumnReordered; - internal void OnColumnReordered(TreeColumn column) - { - if (ColumnReordered != null) - ColumnReordered(this, new TreeColumnEventArgs(column)); - } - - [Category("Behavior")] - public event EventHandler ColumnClicked; - internal void OnColumnClicked(TreeColumn column) - { - if (ColumnClicked != null) - ColumnClicked(this, new TreeColumnEventArgs(column)); - } - - [Category("Behavior")] - public event EventHandler SelectionChanged; - internal void OnSelectionChanged() - { - if (SuspendSelectionEvent) - _fireSelectionEvent = true; - else - { - _fireSelectionEvent = false; - if (SelectionChanged != null) - SelectionChanged(this, EventArgs.Empty); - } - } - - [Category("Behavior")] - public event EventHandler Collapsing; - private void OnCollapsing(TreeNodeAdv node) - { - if (Collapsing != null) - Collapsing(this, new TreeViewAdvEventArgs(node)); - } - - [Category("Behavior")] - public event EventHandler Collapsed; - private void OnCollapsed(TreeNodeAdv node) - { - if (Collapsed != null) - Collapsed(this, new TreeViewAdvEventArgs(node)); - } - - [Category("Behavior")] - public event EventHandler Expanding; - private void OnExpanding(TreeNodeAdv node) - { - if (Expanding != null) - Expanding(this, new TreeViewAdvEventArgs(node)); - } - - [Category("Behavior")] - public event EventHandler Expanded; - private void OnExpanded(TreeNodeAdv node) - { - if (Expanded != null) - Expanded(this, new TreeViewAdvEventArgs(node)); - } - - [Category("Behavior")] - public event EventHandler GridLineStyleChanged; - private void OnGridLineStyleChanged() - { - if (GridLineStyleChanged != null) - GridLineStyleChanged(this, EventArgs.Empty); - } - - [Category("Behavior")] - public event ScrollEventHandler Scroll; - protected virtual void OnScroll(ScrollEventArgs e) - { - if (Scroll != null) - Scroll(this, e); - } - - [Category("Behavior")] - public event EventHandler RowDraw; - protected virtual void OnRowDraw(PaintEventArgs e, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect) - { - if (RowDraw != null) - { - TreeViewRowDrawEventArgs args = new TreeViewRowDrawEventArgs(e.Graphics, e.ClipRectangle, node, context, row, rowRect); - RowDraw(this, args); - } - } - - /// - /// Fires when control is going to draw. Can be used to change text or back color - /// - [Category("Behavior")] - public event EventHandler DrawControl; - - internal bool DrawControlMustBeFired() - { - return DrawControl != null; - } - - internal void FireDrawControl(DrawEventArgs args) - { - OnDrawControl(args); - } - - protected virtual void OnDrawControl(DrawEventArgs args) - { - if (DrawControl != null) - DrawControl(this, args); - } - - - [Category("Drag Drop")] - public event EventHandler DropNodeValidating; - protected virtual void OnDropNodeValidating(Point point, ref TreeNodeAdv node) - { - if (DropNodeValidating != null) - { - DropNodeValidatingEventArgs args = new DropNodeValidatingEventArgs(point, node); - DropNodeValidating(this, args); - node = args.Node; - } - } - #endregion - - public TreeViewAdv() - { - InitializeComponent(); - SetDPI(); - SetStyle(ControlStyles.AllPaintingInWmPaint - | ControlStyles.UserPaint - | ControlStyles.OptimizedDoubleBuffer - | ControlStyles.ResizeRedraw - | ControlStyles.Selectable - , true); - - - if (Application.RenderWithVisualStyles) - _columnHeaderHeight = 20; - else - _columnHeaderHeight = 17; - _columnHeaderHeight = GetScaledSize(_columnHeaderHeight); - - //BorderStyle = BorderStyle.Fixed3D; - _hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; - _vScrollBar.Width = SystemInformation.VerticalScrollBarWidth; - _rowLayout = new FixedRowHeightLayout(this, RowHeight); - _rowMap = new List(); - _selection = new List(); - _readonlySelection = new ReadOnlyCollection(_selection); - _columns = new TreeColumnCollection(this); - _toolTip = new ToolTip(); - - _measureContext = new DrawContext(); - _measureContext.Font = Font; - _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); - - Input = new NormalInputState(this); - _search = new IncrementalSearch(this); - CreateNodes(); - CreatePens(); - - ArrangeControls(); - - _plusMinus = new NodePlusMinus(); - _controls = new NodeControlsCollection(this); - - Font = _font; - ExpandingIcon.IconChanged += ExpandingIconChanged; - } - - public void SetDPI() - { - // https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx - const int _default_dpi = 96; - Graphics g = this.CreateGraphics(); - - try - { - this.dpiX = g.DpiX; - this.dpiY = g.DpiY; - } - finally - { - g.Dispose(); - } - if (dpiX > 0) - { - this.dpiXscale = dpiX / _default_dpi; - } - if (dpiY > 0) - { - this.dpiYscale = dpiY / _default_dpi; - } - } - - public int GetScaledSize(int size, bool useY = true) - { - int scaledsize = size; - - if (useY && this.dpiYscale > 1) - { - scaledsize = (int)(this.dpiYscale * size); - } - else if (this.dpiXscale > 1) - { - scaledsize = (int)(this.dpiXscale * size); - } - return scaledsize; - } - - void ExpandingIconChanged(object sender, EventArgs e) - { - if (IsHandleCreated && !IsDisposed) - BeginInvoke(new MethodInvoker(DrawIcons)); - } - - private void DrawIcons() - { - using (Graphics gr = Graphics.FromHwnd(this.Handle)) - { - //Apply the same Graphics Transform logic as used in OnPaint. - int y = 0; - if (UseColumns) - { - y += ColumnHeaderHeight; - if (Columns.Count == 0) - return; - } - int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y; - y -= firstRowY; - gr.ResetTransform(); - gr.TranslateTransform(-OffsetX, y); - - DrawContext context = new DrawContext(); - context.Graphics = gr; - for (int i = 0; i < _expandingNodes.Count; i++) - { - foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i])) - { - if (item.Control is ExpandingIcon) - { - Rectangle bounds = item.Bounds; - if (item.Node.Parent == null && UseColumns) - bounds.Location = Point.Empty; // display root expanding icon at 0,0 - - context.Bounds = bounds; - item.Control.Draw(item.Node, context); - } - } - } - } - } - - #region Public Methods - - public TreePath GetPath(TreeNodeAdv node) - { - if (node == _root) - return TreePath.Empty; - else - { - Stack stack = new Stack(); - while (node != _root && node != null) - { - stack.Push(node.Tag); - node = node.Parent; - } - return new TreePath(stack.ToArray()); - } - } - - public TreeNodeAdv GetNodeAt(Point point) - { - NodeControlInfo info = GetNodeControlInfoAt(point); - return info.Node; - } - - public NodeControlInfo GetNodeControlInfoAt(Point point) - { - if (point.X < 0 || point.Y < 0) - return NodeControlInfo.Empty; - - int row = _rowLayout.GetRowAt(point); - if (row < RowCount && row >= 0) - return GetNodeControlInfoAt(RowMap[row], point); - else - return NodeControlInfo.Empty; - } - - private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point) - { - Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow); - point.Y += (rect.Y - ColumnHeaderHeight); - point.X += OffsetX; - foreach (NodeControlInfo info in GetNodeControls(node)) - if (info.Bounds.Contains(point)) - return info; - - if (FullRowSelect) - return new NodeControlInfo(null, Rectangle.Empty, node); - else - return NodeControlInfo.Empty; - } - - public void BeginUpdate() - { - _suspendUpdate = true; - SuspendSelectionEvent = true; - } - - public void EndUpdate() - { - _suspendUpdate = false; - if (_needFullUpdate) - FullUpdate(); - else - UpdateView(); - SuspendSelectionEvent = false; - } - - public void ExpandAll() - { - _root.ExpandAll(); - } - - public void CollapseAll() - { - _root.CollapseAll(); - } - - /// - /// Expand all parent nodes, andd scroll to the specified node - /// - public void EnsureVisible(TreeNodeAdv node) - { - if (node == null) - throw new ArgumentNullException("node"); - - if (!IsMyNode(node)) - throw new ArgumentException(); - - TreeNodeAdv parent = node.Parent; - while (parent != _root) - { - parent.IsExpanded = true; - parent = parent.Parent; - } - ScrollTo(node); - } - - /// - /// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded - /// - /// - public void ScrollTo(TreeNodeAdv node) - { - if (node == null) - throw new ArgumentNullException("node"); - - if (!IsMyNode(node)) - throw new ArgumentException(); - - if (node.Row < 0) - CreateRowMap(); - - int row = -1; - - if (node.Row < FirstVisibleRow) - row = node.Row; - else - { - int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top; - int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom; - if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight) - row = _rowLayout.GetFirstRow(node.Row); - } - - if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum) - _vScrollBar.Value = row; - } - - public void ClearSelection() - { - BeginUpdate(); - try - { - ClearSelectionInternal(); - } - finally - { - EndUpdate(); - } - } - - internal void ClearSelectionInternal() - { - while (Selection.Count > 0) - { - var t = Selection[0]; - t.IsSelected = false; - Selection.Remove(t); //hack - } - } - - #endregion - - protected override void OnSizeChanged(EventArgs e) - { - ArrangeControls(); - SafeUpdateScrollBars(); - base.OnSizeChanged(e); - } - - private void ArrangeControls() - { - int hBarSize = _hScrollBar.Height; - int vBarSize = _vScrollBar.Width; - Rectangle clientRect = ClientRectangle; - - _hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize, - clientRect.Width - vBarSize, hBarSize); - - _vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y, - vBarSize, clientRect.Height - hBarSize); - } - - private void SafeUpdateScrollBars() - { - if (InvokeRequired) - BeginInvoke(new MethodInvoker(UpdateScrollBars)); - else - UpdateScrollBars(); - } - - private void UpdateScrollBars() - { - UpdateVScrollBar(); - UpdateHScrollBar(); - UpdateVScrollBar(); - UpdateHScrollBar(); - _hScrollBar.Width = DisplayRectangle.Width; - _vScrollBar.Height = DisplayRectangle.Height; - } - - private void UpdateHScrollBar() - { - _hScrollBar.Maximum = ContentWidth; - _hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0); - _hScrollBar.SmallChange = 5; - _hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum; - _hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1); - } - - private void UpdateVScrollBar() - { - _vScrollBar.Maximum = Math.Max(RowCount - 1, 0); - _vScrollBar.LargeChange = _rowLayout.PageRowCount; - _vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum); - _vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1); - } - - protected override CreateParams CreateParams - { - [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] - get - { - CreateParams res = base.CreateParams; - switch (BorderStyle) - { - case BorderStyle.FixedSingle: - res.Style |= 0x800000; - break; - case BorderStyle.Fixed3D: - res.ExStyle |= 0x200; - break; - } - return res; - } - } - - protected override void OnGotFocus(EventArgs e) - { - UpdateView(); - ChangeInput(); - base.OnGotFocus(e); - } - - protected override void OnFontChanged(EventArgs e) - { - base.OnFontChanged(e); - _measureContext.Font = Font; - FullUpdate(); - } - - internal IEnumerable GetNodeControls(TreeNodeAdv node) - { - if (node == null) - yield break; - Rectangle rowRect = _rowLayout.GetRowBounds(node.Row); - foreach (NodeControlInfo n in GetNodeControls(node, rowRect)) - yield return n; - } - - internal IEnumerable GetNodeControls(TreeNodeAdv node, Rectangle rowRect) - { - if (node == null) - yield break; - - int scaledIndent = node.Tree.GetScaledSize(_indent, false); - int y = rowRect.Y; - int x = (node.Level - 1) * scaledIndent + LeftMargin; - int width = 0; - if (node.Row == 0 && ShiftFirstNode) - x -= scaledIndent; - Rectangle rect = Rectangle.Empty; - - if (ShowPlusMinus) - { - width = _plusMinus.GetActualSize(node, _measureContext).Width; - rect = new Rectangle(x, y, width, rowRect.Height); - if (UseColumns && Columns.Count > 0 && Columns[0].Width < rect.Right) - rect.Width = Columns[0].Width - x; - - yield return new NodeControlInfo(_plusMinus, rect, node); - x += width; - } - - if (!UseColumns) - { - foreach (NodeControl c in NodeControls) - { - Size s = c.GetActualSize(node, _measureContext); - if (!s.IsEmpty) - { - width = s.Width; - rect = new Rectangle(x, y, width, rowRect.Height); - x += rect.Width; - yield return new NodeControlInfo(c, rect, node); - } - } - } - else - { - int right = 0; - foreach (TreeColumn col in Columns) - { - if (col.IsVisible && col.Width > 0) - { - right += col.Width; - for (int i = 0; i < NodeControls.Count; i++) - { - NodeControl nc = NodeControls[i]; - if (nc.ParentColumn == col) - { - Size s = nc.GetActualSize(node, _measureContext); - if (!s.IsEmpty) - { - bool isLastControl = true; - for (int k = i + 1; k < NodeControls.Count; k++) - if (NodeControls[k].ParentColumn == col) - { - isLastControl = false; - break; - } - - width = right - x; - if (!isLastControl) - width = s.Width; - int maxWidth = Math.Max(0, right - x); - rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height); - x += width; - yield return new NodeControlInfo(nc, rect, node); - } - } - } - x = right; - } - } - } - } - - internal static double Dist(Point p1, Point p2) - { - return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2)); - } - - public void FullUpdate() - { - HideEditor(); - if (InvokeRequired) - BeginInvoke(new MethodInvoker(UnsafeFullUpdate)); - else - UnsafeFullUpdate(); - } - - private void UnsafeFullUpdate() - { - _rowLayout.ClearCache(); - CreateRowMap(); - SafeUpdateScrollBars(); - UpdateView(); - _needFullUpdate = false; - } - - internal void UpdateView() - { - if (!_suspendUpdate) - Invalidate(false); - } - - internal void UpdateHeaders() - { - Invalidate(new Rectangle(0, 0, Width, ColumnHeaderHeight)); - } - - internal void UpdateColumns() - { - FullUpdate(); - } - - private void CreateNodes() - { - Selection.Clear(); - SelectionStart = null; - _root = new TreeNodeAdv(this, null); - _root.IsExpanded = true; - if (_root.Nodes.Count > 0) - CurrentNode = _root.Nodes[0]; - else - CurrentNode = null; - } - - internal void ReadChilds(TreeNodeAdv parentNode) - { - ReadChilds(parentNode, false); - } - - internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate) - { - if (!parentNode.IsLeaf) - { - parentNode.IsExpandedOnce = true; - parentNode.Nodes.Clear(); - - if (Model != null) - { - IEnumerable items = Model.GetChildren(GetPath(parentNode)); - if (items != null) - foreach (object obj in items) - { - AddNewNode(parentNode, obj, -1); - if (performFullUpdate) - FullUpdate(); - } - } - - if (parentNode.AutoExpandOnStructureChanged) - parentNode.ExpandAll(); - } - } - - private void AddNewNode(TreeNodeAdv parent, object tag, int index) - { - TreeNodeAdv node = new TreeNodeAdv(this, tag); - AddNode(parent, index, node); - } - - private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node) - { - if (index >= 0 && index < parent.Nodes.Count) - parent.Nodes.Insert(index, node); - else - parent.Nodes.Add(node); - - node.IsLeaf = Model.IsLeaf(GetPath(node)); - if (node.IsLeaf) - node.Nodes.Clear(); - if (!LoadOnDemand || node.IsExpandedOnce) - ReadChilds(node); - } - - private struct ExpandArgs - { - public TreeNodeAdv Node; - public bool Value; - public bool IgnoreChildren; - } - - public void AbortBackgroundExpandingThreads() - { - _threadPool.CancelAll(true); - for (int i = 0; i < _expandingNodes.Count; i++) - _expandingNodes[i].IsExpandingNow = false; - _expandingNodes.Clear(); - Invalidate(); - } - - internal void SetIsExpanded(TreeNodeAdv node, bool value, bool ignoreChildren) - { - ExpandArgs eargs = new ExpandArgs(); - eargs.Node = node; - eargs.Value = value; - eargs.IgnoreChildren = ignoreChildren; - - if (AsyncExpanding && LoadOnDemand && !_threadPool.IsMyThread(Thread.CurrentThread)) - { - WaitCallback wc = delegate(object argument) { SetIsExpanded((ExpandArgs)argument); }; - _threadPool.QueueUserWorkItem(wc, eargs); - } - else - SetIsExpanded(eargs); - } - - private void SetIsExpanded(ExpandArgs eargs) - { - bool update = !eargs.IgnoreChildren && !AsyncExpanding; - if (update) - BeginUpdate(); - try - { - if (IsMyNode(eargs.Node) && eargs.Node.IsExpanded != eargs.Value) - SetIsExpanded(eargs.Node, eargs.Value); - - if (!eargs.IgnoreChildren) - SetIsExpandedRecursive(eargs.Node, eargs.Value); - } - finally - { - if (update) - EndUpdate(); - } - } - - internal void SetIsExpanded(TreeNodeAdv node, bool value) - { - if (Root == node && !value) - return; //Can't collapse root node - - if (value) - { - OnExpanding(node); - node.OnExpanding(); - } - else - { - OnCollapsing(node); - node.OnCollapsing(); - } - - if (value && !node.IsExpandedOnce) - { - if (AsyncExpanding && LoadOnDemand) - { - AddExpandingNode(node); - node.AssignIsExpanded(true); - Invalidate(); - } - ReadChilds(node, AsyncExpanding); - RemoveExpandingNode(node); - } - node.AssignIsExpanded(value); - SmartFullUpdate(); - - if (value) - { - OnExpanded(node); - node.OnExpanded(); - } - else - { - OnCollapsed(node); - node.OnCollapsed(); - } - } - - private void RemoveExpandingNode(TreeNodeAdv node) - { - node.IsExpandingNow = false; - _expandingNodes.Remove(node); - if (_expandingNodes.Count <= 0) - ExpandingIcon.Stop(); - } - - private void AddExpandingNode(TreeNodeAdv node) - { - node.IsExpandingNow = true; - _expandingNodes.Add(node); - ExpandingIcon.Start(); - } - - internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value) - { - for (int i = 0; i < root.Nodes.Count; i++) - { - TreeNodeAdv node = root.Nodes[i]; - node.IsExpanded = value; - SetIsExpandedRecursive(node, value); - } - } - - private void CreateRowMap() - { - RowMap.Clear(); - int row = 0; - _contentWidth = 0; - foreach (TreeNodeAdv node in VisibleNodes) - { - node.Row = row; - RowMap.Add(node); - if (!UseColumns) - { - _contentWidth = Math.Max(_contentWidth, GetNodeWidth(node)); - } - row++; - } - if (UseColumns) - { - _contentWidth = 0; - foreach (TreeColumn col in _columns) - if (col.IsVisible) - _contentWidth += col.Width; - } - } - - private int GetNodeWidth(TreeNodeAdv node) - { - if (node.RightBounds == null) - { - Rectangle res = GetNodeBounds(GetNodeControls(node, Rectangle.Empty)); - node.RightBounds = res.Right; - } - return node.RightBounds.Value; - } - - internal Rectangle GetNodeBounds(TreeNodeAdv node) - { - return GetNodeBounds(GetNodeControls(node)); - } - - private Rectangle GetNodeBounds(IEnumerable nodeControls) - { - Rectangle res = Rectangle.Empty; - foreach (NodeControlInfo info in nodeControls) - { - if (res == Rectangle.Empty) - res = info.Bounds; - else - res = Rectangle.Union(res, info.Bounds); - } - return res; - } - - private void _vScrollBar_ValueChanged(object sender, EventArgs e) - { - FirstVisibleRow = _vScrollBar.Value; - } - - private void _hScrollBar_ValueChanged(object sender, EventArgs e) - { - OffsetX = _hScrollBar.Value; - } - - private void _vScrollBar_Scroll(object sender, ScrollEventArgs e) - { - OnScroll(e); - } - - private void _hScrollBar_Scroll(object sender, ScrollEventArgs e) - { - OnScroll(e); - } - - internal void SmartFullUpdate() - { - if (_suspendUpdate) - _needFullUpdate = true; - else - FullUpdate(); - } - - internal bool IsMyNode(TreeNodeAdv node) - { - if (node == null) - return false; - - if (node.Tree != this) - return false; - - while (node.Parent != null) - node = node.Parent; - - return node == _root; - } - - internal void UpdateSelection() - { - bool flag = false; - - if (!IsMyNode(CurrentNode)) - CurrentNode = null; - if (!IsMyNode(_selectionStart)) - _selectionStart = null; - - for (int i = Selection.Count - 1; i >= 0; i--) - if (!IsMyNode(Selection[i])) - { - flag = true; - Selection.RemoveAt(i); - } - - if (flag) - OnSelectionChanged(); - } - - internal void ChangeColumnWidth(TreeColumn column) - { - if (!(_input is ResizeColumnState)) - { - FullUpdate(); - OnColumnWidthChanged(column); - } - } - - public TreeNodeAdv FindNode(TreePath path) - { - return FindNode(path, false); - } - - public TreeNodeAdv FindNode(TreePath path, bool readChilds) - { - if (path.IsEmpty()) - return _root; - else - return FindNode(_root, path, 0, readChilds); - } - - private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level, bool readChilds) - { - if (!root.IsExpandedOnce && readChilds) - ReadChilds(root); - - for (int i = 0; i < root.Nodes.Count; i++) - { - TreeNodeAdv node = root.Nodes[i]; - if (node.Tag == path.FullPath[level]) - { - if (level == path.FullPath.Length - 1) - return node; - else - return FindNode(node, path, level + 1, readChilds); - } - } - return null; - } - - public TreeNodeAdv FindNodeByTag(object tag) - { - return FindNodeByTag(_root, tag); - } - - private TreeNodeAdv FindNodeByTag(TreeNodeAdv root, object tag) - { - foreach (TreeNodeAdv node in root.Nodes) - { - if (node.Tag == tag) - return node; - TreeNodeAdv res = FindNodeByTag(node, tag); - if (res != null) - return res; - } - return null; - } - - public void SelectAllNodes() - { - SuspendSelectionEvent = true; - try - { - if (SelectionMode == TreeSelectionMode.MultiSameParent) - { - if (CurrentNode != null) - { - foreach (TreeNodeAdv n in CurrentNode.Parent.Nodes) - n.IsSelected = true; - } - } - else if (SelectionMode == TreeSelectionMode.Multi) - { - SelectNodes(Root.Nodes); - } - } - finally - { - SuspendSelectionEvent = false; - } - } - - private void SelectNodes(Collection nodes) - { - foreach (TreeNodeAdv n in nodes) - { - n.IsSelected = true; - if (n.IsExpanded) - SelectNodes(n.Nodes); - } - } - - #region ModelEvents - private void BindModelEvents() - { - _model.NodesChanged += new EventHandler(_model_NodesChanged); - _model.NodesInserted += new EventHandler(_model_NodesInserted); - _model.NodesRemoved += new EventHandler(_model_NodesRemoved); - _model.StructureChanged += new EventHandler(_model_StructureChanged); - } - - private void UnbindModelEvents() - { - _model.NodesChanged -= new EventHandler(_model_NodesChanged); - _model.NodesInserted -= new EventHandler(_model_NodesInserted); - _model.NodesRemoved -= new EventHandler(_model_NodesRemoved); - _model.StructureChanged -= new EventHandler(_model_StructureChanged); - } - - private void _model_StructureChanged(object sender, TreePathEventArgs e) - { - if (e.Path == null) - throw new ArgumentNullException(); - - TreeNodeAdv node = FindNode(e.Path); - if (node != null) - { - if (node != Root) - node.IsLeaf = Model.IsLeaf(GetPath(node)); - - var list = new Dictionary(); - SaveExpandedNodes(node, list); - ReadChilds(node); - RestoreExpandedNodes(node, list); - - UpdateSelection(); - SmartFullUpdate(); - } - //else - // throw new ArgumentException("Path not found"); - } - - private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary list) - { - if (node.Tag != null && list.ContainsKey(node.Tag)) - { - node.IsExpanded = true; - foreach (var child in node.Children) - RestoreExpandedNodes(child, list); - } - } - - private void SaveExpandedNodes(TreeNodeAdv node, Dictionary list) - { - if (node.IsExpanded && node.Tag != null) - { - list.Add(node.Tag, null); - foreach (var child in node.Children) - SaveExpandedNodes(child, list); - } - } - - private void _model_NodesRemoved(object sender, TreeModelEventArgs e) - { - TreeNodeAdv parent = FindNode(e.Path); - if (parent != null) - { - if (e.Indices != null) - { - List list = new List(e.Indices); - list.Sort(); - for (int n = list.Count - 1; n >= 0; n--) - { - int index = list[n]; - if (index >= 0 && index <= parent.Nodes.Count) - parent.Nodes.RemoveAt(index); - else - throw new ArgumentOutOfRangeException("Index out of range"); - } - } - else - { - for (int i = parent.Nodes.Count - 1; i >= 0; i--) - { - for (int n = 0; n < e.Children.Length; n++) - if (parent.Nodes[i].Tag == e.Children[n]) - { - parent.Nodes.RemoveAt(i); - break; - } - } - } - } - UpdateSelection(); - SmartFullUpdate(); - } - - private void _model_NodesInserted(object sender, TreeModelEventArgs e) - { - if (e.Indices == null) - throw new ArgumentNullException("Indices"); - - TreeNodeAdv parent = FindNode(e.Path); - if (parent != null) - { - for (int i = 0; i < e.Children.Length; i++) - AddNewNode(parent, e.Children[i], e.Indices[i]); - } - SmartFullUpdate(); - } - - private void _model_NodesChanged(object sender, TreeModelEventArgs e) - { - TreeNodeAdv parent = FindNode(e.Path); - if (parent != null && parent.IsVisible && parent.IsExpanded) - { - if (InvokeRequired) - BeginInvoke(new UpdateContentWidthDelegate(ClearNodesSize), e, parent); - else - ClearNodesSize(e, parent); - SmartFullUpdate(); - } - } - - private delegate void UpdateContentWidthDelegate(TreeModelEventArgs e, TreeNodeAdv parent); - private void ClearNodesSize(TreeModelEventArgs e, TreeNodeAdv parent) - { - if (e.Indices != null) - { - foreach (int index in e.Indices) - { - if (index >= 0 && index < parent.Nodes.Count) - { - TreeNodeAdv node = parent.Nodes[index]; - node.Height = node.RightBounds = null; - } - else - throw new ArgumentOutOfRangeException("Index out of range"); - } - } - else - { - foreach (TreeNodeAdv node in parent.Nodes) - { - foreach (object obj in e.Children) - if (node.Tag == obj) - { - node.Height = node.RightBounds = null; - } - } - } - } - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Drawing; +using System.Security.Permissions; +using System.Threading; +using System.Windows.Forms; +using System.Collections; + +using Aga.Controls.Tree.NodeControls; +using Aga.Controls.Threading; + + +namespace Aga.Controls.Tree +{ + /// + /// Extensible advanced implemented in 100% managed C# code. + /// Features: Model/View architecture. Multiple column per node. Ability to select + /// multiple tree nodes. Different types of controls for each node column: + /// , Icon, Label... Drag and Drop highlighting. Load on + /// demand of nodes. Incremental search of nodes. + /// + public partial class TreeViewAdv : Control + { + private const int LeftMargin = 7; + internal const int ItemDragSensivity = 4; + private readonly int _columnHeaderHeight; + private const int DividerWidth = 9; + private const int DividerCorrectionGap = -2; + + private Pen _linePen; + private Pen _markPen; + private bool _suspendUpdate; + private bool _needFullUpdate; + private bool _fireSelectionEvent; + private NodePlusMinus _plusMinus; + private ToolTip _toolTip; + private DrawContext _measureContext; + private TreeColumn _hotColumn; + private IncrementalSearch _search; + private List _expandingNodes = new List(); + private AbortableThreadPool _threadPool = new AbortableThreadPool(); + + private float dpiX; + private float dpiY; + private float dpiXscale = 1; + private float dpiYscale = 1; + + #region Public Events + + [Category("Action")] + public event ItemDragEventHandler ItemDrag; + private void OnItemDrag(MouseButtons buttons, object item) + { + if (ItemDrag != null) + ItemDrag(this, new ItemDragEventArgs(buttons, item)); + } + + [Category("Behavior")] + public event EventHandler NodeMouseClick; + private void OnNodeMouseClick(TreeNodeAdvMouseEventArgs args) + { + if (NodeMouseClick != null) + NodeMouseClick(this, args); + } + + [Category("Behavior")] + public event EventHandler NodeMouseDoubleClick; + private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args) + { + if (NodeMouseDoubleClick != null) + NodeMouseDoubleClick(this, args); + } + + [Category("Behavior")] + public event EventHandler ColumnWidthChanged; + internal void OnColumnWidthChanged(TreeColumn column) + { + if (ColumnWidthChanged != null) + ColumnWidthChanged(this, new TreeColumnEventArgs(column)); + } + + [Category("Behavior")] + public event EventHandler ColumnReordered; + internal void OnColumnReordered(TreeColumn column) + { + if (ColumnReordered != null) + ColumnReordered(this, new TreeColumnEventArgs(column)); + } + + [Category("Behavior")] + public event EventHandler ColumnClicked; + internal void OnColumnClicked(TreeColumn column) + { + if (ColumnClicked != null) + ColumnClicked(this, new TreeColumnEventArgs(column)); + } + + [Category("Behavior")] + public event EventHandler SelectionChanged; + internal void OnSelectionChanged() + { + if (SuspendSelectionEvent) + _fireSelectionEvent = true; + else + { + _fireSelectionEvent = false; + if (SelectionChanged != null) + SelectionChanged(this, EventArgs.Empty); + } + } + + [Category("Behavior")] + public event EventHandler Collapsing; + private void OnCollapsing(TreeNodeAdv node) + { + if (Collapsing != null) + Collapsing(this, new TreeViewAdvEventArgs(node)); + } + + [Category("Behavior")] + public event EventHandler Collapsed; + private void OnCollapsed(TreeNodeAdv node) + { + if (Collapsed != null) + Collapsed(this, new TreeViewAdvEventArgs(node)); + } + + [Category("Behavior")] + public event EventHandler Expanding; + private void OnExpanding(TreeNodeAdv node) + { + if (Expanding != null) + Expanding(this, new TreeViewAdvEventArgs(node)); + } + + [Category("Behavior")] + public event EventHandler Expanded; + private void OnExpanded(TreeNodeAdv node) + { + if (Expanded != null) + Expanded(this, new TreeViewAdvEventArgs(node)); + } + + [Category("Behavior")] + public event EventHandler GridLineStyleChanged; + private void OnGridLineStyleChanged() + { + if (GridLineStyleChanged != null) + GridLineStyleChanged(this, EventArgs.Empty); + } + + [Category("Behavior")] + public event ScrollEventHandler Scroll; + protected virtual void OnScroll(ScrollEventArgs e) + { + if (Scroll != null) + Scroll(this, e); + } + + [Category("Behavior")] + public event EventHandler RowDraw; + protected virtual void OnRowDraw(PaintEventArgs e, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect) + { + if (RowDraw != null) + { + TreeViewRowDrawEventArgs args = new TreeViewRowDrawEventArgs(e.Graphics, e.ClipRectangle, node, context, row, rowRect); + RowDraw(this, args); + } + } + + /// + /// Fires when control is going to draw. Can be used to change text or back color + /// + [Category("Behavior")] + public event EventHandler DrawControl; + + internal bool DrawControlMustBeFired() + { + return DrawControl != null; + } + + internal void FireDrawControl(DrawEventArgs args) + { + OnDrawControl(args); + } + + protected virtual void OnDrawControl(DrawEventArgs args) + { + if (DrawControl != null) + DrawControl(this, args); + } + + + [Category("Drag Drop")] + public event EventHandler DropNodeValidating; + protected virtual void OnDropNodeValidating(Point point, ref TreeNodeAdv node) + { + if (DropNodeValidating != null) + { + DropNodeValidatingEventArgs args = new DropNodeValidatingEventArgs(point, node); + DropNodeValidating(this, args); + node = args.Node; + } + } + #endregion + + public TreeViewAdv() + { + InitializeComponent(); + SetDPI(); + SetStyle(ControlStyles.AllPaintingInWmPaint + | ControlStyles.UserPaint + | ControlStyles.OptimizedDoubleBuffer + | ControlStyles.ResizeRedraw + | ControlStyles.Selectable + , true); + + + if (Application.RenderWithVisualStyles) + _columnHeaderHeight = 20; + else + _columnHeaderHeight = 17; + _columnHeaderHeight = GetScaledSize(_columnHeaderHeight); + + //BorderStyle = BorderStyle.Fixed3D; + _hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; + _vScrollBar.Width = SystemInformation.VerticalScrollBarWidth; + _rowLayout = new FixedRowHeightLayout(this, RowHeight); + _rowMap = new List(); + _selection = new List(); + _readonlySelection = new ReadOnlyCollection(_selection); + _columns = new TreeColumnCollection(this); + _toolTip = new ToolTip(); + + _measureContext = new DrawContext(); + _measureContext.Font = Font; + _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); + + Input = new NormalInputState(this); + _search = new IncrementalSearch(this); + CreateNodes(); + CreatePens(); + + ArrangeControls(); + + _plusMinus = new NodePlusMinus(); + _controls = new NodeControlsCollection(this); + + Font = _font; + ExpandingIcon.IconChanged += ExpandingIconChanged; + } + + public void SetDPI() + { + // https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx + const int _default_dpi = 96; + Graphics g = this.CreateGraphics(); + + try + { + this.dpiX = g.DpiX; + this.dpiY = g.DpiY; + } + finally + { + g.Dispose(); + } + if (dpiX > 0) + { + this.dpiXscale = dpiX / _default_dpi; + } + if (dpiY > 0) + { + this.dpiYscale = dpiY / _default_dpi; + } + } + + public int GetScaledSize(int size, bool useY = true) + { + int scaledsize = size; + + if (useY && this.dpiYscale > 1) + { + scaledsize = (int)(this.dpiYscale * size); + } + else if (this.dpiXscale > 1) + { + scaledsize = (int)(this.dpiXscale * size); + } + return scaledsize; + } + + void ExpandingIconChanged(object sender, EventArgs e) + { + if (IsHandleCreated && !IsDisposed) + BeginInvoke(new MethodInvoker(DrawIcons)); + } + + private void DrawIcons() + { + using (Graphics gr = Graphics.FromHwnd(this.Handle)) + { + //Apply the same Graphics Transform logic as used in OnPaint. + int y = 0; + if (UseColumns) + { + y += ColumnHeaderHeight; + if (Columns.Count == 0) + return; + } + int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y; + y -= firstRowY; + gr.ResetTransform(); + gr.TranslateTransform(-OffsetX, y); + + DrawContext context = new DrawContext(); + context.Graphics = gr; + for (int i = 0; i < _expandingNodes.Count; i++) + { + foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i])) + { + if (item.Control is ExpandingIcon) + { + Rectangle bounds = item.Bounds; + if (item.Node.Parent == null && UseColumns) + bounds.Location = Point.Empty; // display root expanding icon at 0,0 + + context.Bounds = bounds; + item.Control.Draw(item.Node, context); + } + } + } + } + } + + #region Public Methods + + public TreePath GetPath(TreeNodeAdv node) + { + if (node == _root) + return TreePath.Empty; + else + { + Stack stack = new Stack(); + while (node != _root && node != null) + { + stack.Push(node.Tag); + node = node.Parent; + } + return new TreePath(stack.ToArray()); + } + } + + public TreeNodeAdv GetNodeAt(Point point) + { + NodeControlInfo info = GetNodeControlInfoAt(point); + return info.Node; + } + + public NodeControlInfo GetNodeControlInfoAt(Point point) + { + if (point.X < 0 || point.Y < 0) + return NodeControlInfo.Empty; + + int row = _rowLayout.GetRowAt(point); + if (row < RowCount && row >= 0) + return GetNodeControlInfoAt(RowMap[row], point); + else + return NodeControlInfo.Empty; + } + + private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point) + { + Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow); + point.Y += (rect.Y - ColumnHeaderHeight); + point.X += OffsetX; + foreach (NodeControlInfo info in GetNodeControls(node)) + if (info.Bounds.Contains(point)) + return info; + + if (FullRowSelect) + return new NodeControlInfo(null, Rectangle.Empty, node); + else + return NodeControlInfo.Empty; + } + + public void BeginUpdate() + { + _suspendUpdate = true; + SuspendSelectionEvent = true; + } + + public void EndUpdate() + { + _suspendUpdate = false; + if (_needFullUpdate) + FullUpdate(); + else + UpdateView(); + SuspendSelectionEvent = false; + } + + public void ExpandAll() + { + _root.ExpandAll(); + } + + public void CollapseAll() + { + _root.CollapseAll(); + } + + /// + /// Expand all parent nodes, andd scroll to the specified node + /// + public void EnsureVisible(TreeNodeAdv node) + { + if (node == null) + throw new ArgumentNullException("node"); + + if (!IsMyNode(node)) + throw new ArgumentException(); + + TreeNodeAdv parent = node.Parent; + while (parent != _root) + { + parent.IsExpanded = true; + parent = parent.Parent; + } + ScrollTo(node); + } + + /// + /// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded + /// + /// + public void ScrollTo(TreeNodeAdv node) + { + if (node == null) + throw new ArgumentNullException("node"); + + if (!IsMyNode(node)) + throw new ArgumentException(); + + if (node.Row < 0) + CreateRowMap(); + + int row = -1; + + if (node.Row < FirstVisibleRow) + row = node.Row; + else + { + int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top; + int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom; + if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight) + row = _rowLayout.GetFirstRow(node.Row); + } + + if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum) + _vScrollBar.Value = row; + } + + public void ClearSelection() + { + BeginUpdate(); + try + { + ClearSelectionInternal(); + } + finally + { + EndUpdate(); + } + } + + internal void ClearSelectionInternal() + { + while (Selection.Count > 0) + { + var t = Selection[0]; + t.IsSelected = false; + Selection.Remove(t); //hack + } + } + + #endregion + + protected override void OnSizeChanged(EventArgs e) + { + ArrangeControls(); + SafeUpdateScrollBars(); + base.OnSizeChanged(e); + } + + private void ArrangeControls() + { + int hBarSize = _hScrollBar.Height; + int vBarSize = _vScrollBar.Width; + Rectangle clientRect = ClientRectangle; + + _hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize, + clientRect.Width - vBarSize, hBarSize); + + _vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y, + vBarSize, clientRect.Height - hBarSize); + } + + private void SafeUpdateScrollBars() + { + if (InvokeRequired) + BeginInvoke(new MethodInvoker(UpdateScrollBars)); + else + UpdateScrollBars(); + } + + private void UpdateScrollBars() + { + UpdateVScrollBar(); + UpdateHScrollBar(); + UpdateVScrollBar(); + UpdateHScrollBar(); + _hScrollBar.Width = DisplayRectangle.Width; + _vScrollBar.Height = DisplayRectangle.Height; + } + + private void UpdateHScrollBar() + { + _hScrollBar.Maximum = ContentWidth; + _hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0); + _hScrollBar.SmallChange = 5; + _hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum; + _hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1); + } + + private void UpdateVScrollBar() + { + _vScrollBar.Maximum = Math.Max(RowCount - 1, 0); + _vScrollBar.LargeChange = _rowLayout.PageRowCount; + _vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum); + _vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1); + } + + protected override CreateParams CreateParams + { + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] + get + { + CreateParams res = base.CreateParams; + switch (BorderStyle) + { + case BorderStyle.FixedSingle: + res.Style |= 0x800000; + break; + case BorderStyle.Fixed3D: + res.ExStyle |= 0x200; + break; + } + return res; + } + } + + protected override void OnGotFocus(EventArgs e) + { + UpdateView(); + ChangeInput(); + base.OnGotFocus(e); + } + + protected override void OnFontChanged(EventArgs e) + { + base.OnFontChanged(e); + _measureContext.Font = Font; + FullUpdate(); + } + + internal IEnumerable GetNodeControls(TreeNodeAdv node) + { + if (node == null) + yield break; + Rectangle rowRect = _rowLayout.GetRowBounds(node.Row); + foreach (NodeControlInfo n in GetNodeControls(node, rowRect)) + yield return n; + } + + internal IEnumerable GetNodeControls(TreeNodeAdv node, Rectangle rowRect) + { + if (node == null) + yield break; + + int scaledIndent = node.Tree.GetScaledSize(_indent, false); + int y = rowRect.Y; + int x = (node.Level - 1) * scaledIndent + LeftMargin; + int width = 0; + if (node.Row == 0 && ShiftFirstNode) + x -= scaledIndent; + Rectangle rect = Rectangle.Empty; + + if (ShowPlusMinus) + { + width = _plusMinus.GetActualSize(node, _measureContext).Width; + rect = new Rectangle(x, y, width, rowRect.Height); + if (UseColumns && Columns.Count > 0 && Columns[0].Width < rect.Right) + rect.Width = Columns[0].Width - x; + + yield return new NodeControlInfo(_plusMinus, rect, node); + x += width; + } + + if (!UseColumns) + { + foreach (NodeControl c in NodeControls) + { + Size s = c.GetActualSize(node, _measureContext); + if (!s.IsEmpty) + { + width = s.Width; + rect = new Rectangle(x, y, width, rowRect.Height); + x += rect.Width; + yield return new NodeControlInfo(c, rect, node); + } + } + } + else + { + int right = 0; + foreach (TreeColumn col in Columns) + { + if (col.IsVisible && col.Width > 0) + { + right += col.Width; + for (int i = 0; i < NodeControls.Count; i++) + { + NodeControl nc = NodeControls[i]; + if (nc.ParentColumn == col) + { + Size s = nc.GetActualSize(node, _measureContext); + if (!s.IsEmpty) + { + bool isLastControl = true; + for (int k = i + 1; k < NodeControls.Count; k++) + if (NodeControls[k].ParentColumn == col) + { + isLastControl = false; + break; + } + + width = right - x; + if (!isLastControl) + width = s.Width; + int maxWidth = Math.Max(0, right - x); + rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height); + x += width; + yield return new NodeControlInfo(nc, rect, node); + } + } + } + x = right; + } + } + } + } + + internal static double Dist(Point p1, Point p2) + { + return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2)); + } + + public void FullUpdate() + { + HideEditor(); + if (InvokeRequired) + BeginInvoke(new MethodInvoker(UnsafeFullUpdate)); + else + UnsafeFullUpdate(); + } + + private void UnsafeFullUpdate() + { + _rowLayout.ClearCache(); + CreateRowMap(); + SafeUpdateScrollBars(); + UpdateView(); + _needFullUpdate = false; + } + + internal void UpdateView() + { + if (!_suspendUpdate) + Invalidate(false); + } + + internal void UpdateHeaders() + { + Invalidate(new Rectangle(0, 0, Width, ColumnHeaderHeight)); + } + + internal void UpdateColumns() + { + FullUpdate(); + } + + private void CreateNodes() + { + Selection.Clear(); + SelectionStart = null; + _root = new TreeNodeAdv(this, null); + _root.IsExpanded = true; + if (_root.Nodes.Count > 0) + CurrentNode = _root.Nodes[0]; + else + CurrentNode = null; + } + + internal void ReadChilds(TreeNodeAdv parentNode) + { + ReadChilds(parentNode, false); + } + + internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate) + { + if (!parentNode.IsLeaf) + { + parentNode.IsExpandedOnce = true; + parentNode.Nodes.Clear(); + + if (Model != null) + { + IEnumerable items = Model.GetChildren(GetPath(parentNode)); + if (items != null) + foreach (object obj in items) + { + AddNewNode(parentNode, obj, -1); + if (performFullUpdate) + FullUpdate(); + } + } + + if (parentNode.AutoExpandOnStructureChanged) + parentNode.ExpandAll(); + } + } + + private void AddNewNode(TreeNodeAdv parent, object tag, int index) + { + TreeNodeAdv node = new TreeNodeAdv(this, tag); + AddNode(parent, index, node); + } + + private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node) + { + if (index >= 0 && index < parent.Nodes.Count) + parent.Nodes.Insert(index, node); + else + parent.Nodes.Add(node); + + node.IsLeaf = Model.IsLeaf(GetPath(node)); + if (node.IsLeaf) + node.Nodes.Clear(); + if (!LoadOnDemand || node.IsExpandedOnce) + ReadChilds(node); + } + + private struct ExpandArgs + { + public TreeNodeAdv Node; + public bool Value; + public bool IgnoreChildren; + } + + public void AbortBackgroundExpandingThreads() + { + _threadPool.CancelAll(true); + for (int i = 0; i < _expandingNodes.Count; i++) + _expandingNodes[i].IsExpandingNow = false; + _expandingNodes.Clear(); + Invalidate(); + } + + internal void SetIsExpanded(TreeNodeAdv node, bool value, bool ignoreChildren) + { + ExpandArgs eargs = new ExpandArgs(); + eargs.Node = node; + eargs.Value = value; + eargs.IgnoreChildren = ignoreChildren; + + if (AsyncExpanding && LoadOnDemand && !_threadPool.IsMyThread(Thread.CurrentThread)) + { + WaitCallback wc = delegate(object argument) { SetIsExpanded((ExpandArgs)argument); }; + _threadPool.QueueUserWorkItem(wc, eargs); + } + else + SetIsExpanded(eargs); + } + + private void SetIsExpanded(ExpandArgs eargs) + { + bool update = !eargs.IgnoreChildren && !AsyncExpanding; + if (update) + BeginUpdate(); + try + { + if (IsMyNode(eargs.Node) && eargs.Node.IsExpanded != eargs.Value) + SetIsExpanded(eargs.Node, eargs.Value); + + if (!eargs.IgnoreChildren) + SetIsExpandedRecursive(eargs.Node, eargs.Value); + } + finally + { + if (update) + EndUpdate(); + } + } + + internal void SetIsExpanded(TreeNodeAdv node, bool value) + { + if (Root == node && !value) + return; //Can't collapse root node + + if (value) + { + OnExpanding(node); + node.OnExpanding(); + } + else + { + OnCollapsing(node); + node.OnCollapsing(); + } + + if (value && !node.IsExpandedOnce) + { + if (AsyncExpanding && LoadOnDemand) + { + AddExpandingNode(node); + node.AssignIsExpanded(true); + Invalidate(); + } + ReadChilds(node, AsyncExpanding); + RemoveExpandingNode(node); + } + node.AssignIsExpanded(value); + SmartFullUpdate(); + + if (value) + { + OnExpanded(node); + node.OnExpanded(); + } + else + { + OnCollapsed(node); + node.OnCollapsed(); + } + } + + private void RemoveExpandingNode(TreeNodeAdv node) + { + node.IsExpandingNow = false; + _expandingNodes.Remove(node); + if (_expandingNodes.Count <= 0) + ExpandingIcon.Stop(); + } + + private void AddExpandingNode(TreeNodeAdv node) + { + node.IsExpandingNow = true; + _expandingNodes.Add(node); + ExpandingIcon.Start(); + } + + internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value) + { + for (int i = 0; i < root.Nodes.Count; i++) + { + TreeNodeAdv node = root.Nodes[i]; + node.IsExpanded = value; + SetIsExpandedRecursive(node, value); + } + } + + private void CreateRowMap() + { + RowMap.Clear(); + int row = 0; + _contentWidth = 0; + foreach (TreeNodeAdv node in VisibleNodes) + { + node.Row = row; + RowMap.Add(node); + if (!UseColumns) + { + _contentWidth = Math.Max(_contentWidth, GetNodeWidth(node)); + } + row++; + } + if (UseColumns) + { + _contentWidth = 0; + foreach (TreeColumn col in _columns) + if (col.IsVisible) + _contentWidth += col.Width; + } + } + + private int GetNodeWidth(TreeNodeAdv node) + { + if (node.RightBounds == null) + { + Rectangle res = GetNodeBounds(GetNodeControls(node, Rectangle.Empty)); + node.RightBounds = res.Right; + } + return node.RightBounds.Value; + } + + internal Rectangle GetNodeBounds(TreeNodeAdv node) + { + return GetNodeBounds(GetNodeControls(node)); + } + + private Rectangle GetNodeBounds(IEnumerable nodeControls) + { + Rectangle res = Rectangle.Empty; + foreach (NodeControlInfo info in nodeControls) + { + if (res == Rectangle.Empty) + res = info.Bounds; + else + res = Rectangle.Union(res, info.Bounds); + } + return res; + } + + private void _vScrollBar_ValueChanged(object sender, EventArgs e) + { + FirstVisibleRow = _vScrollBar.Value; + } + + private void _hScrollBar_ValueChanged(object sender, EventArgs e) + { + OffsetX = _hScrollBar.Value; + } + + private void _vScrollBar_Scroll(object sender, ScrollEventArgs e) + { + OnScroll(e); + } + + private void _hScrollBar_Scroll(object sender, ScrollEventArgs e) + { + OnScroll(e); + } + + internal void SmartFullUpdate() + { + if (_suspendUpdate) + _needFullUpdate = true; + else + FullUpdate(); + } + + internal bool IsMyNode(TreeNodeAdv node) + { + if (node == null) + return false; + + if (node.Tree != this) + return false; + + while (node.Parent != null) + node = node.Parent; + + return node == _root; + } + + internal void UpdateSelection() + { + bool flag = false; + + if (!IsMyNode(CurrentNode)) + CurrentNode = null; + if (!IsMyNode(_selectionStart)) + _selectionStart = null; + + for (int i = Selection.Count - 1; i >= 0; i--) + if (!IsMyNode(Selection[i])) + { + flag = true; + Selection.RemoveAt(i); + } + + if (flag) + OnSelectionChanged(); + } + + internal void ChangeColumnWidth(TreeColumn column) + { + if (!(_input is ResizeColumnState)) + { + FullUpdate(); + OnColumnWidthChanged(column); + } + } + + public TreeNodeAdv FindNode(TreePath path) + { + return FindNode(path, false); + } + + public TreeNodeAdv FindNode(TreePath path, bool readChilds) + { + if (path.IsEmpty()) + return _root; + else + return FindNode(_root, path, 0, readChilds); + } + + private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level, bool readChilds) + { + if (!root.IsExpandedOnce && readChilds) + ReadChilds(root); + + for (int i = 0; i < root.Nodes.Count; i++) + { + TreeNodeAdv node = root.Nodes[i]; + if (node.Tag == path.FullPath[level]) + { + if (level == path.FullPath.Length - 1) + return node; + else + return FindNode(node, path, level + 1, readChilds); + } + } + return null; + } + + public TreeNodeAdv FindNodeByTag(object tag) + { + return FindNodeByTag(_root, tag); + } + + private TreeNodeAdv FindNodeByTag(TreeNodeAdv root, object tag) + { + foreach (TreeNodeAdv node in root.Nodes) + { + if (node.Tag == tag) + return node; + TreeNodeAdv res = FindNodeByTag(node, tag); + if (res != null) + return res; + } + return null; + } + + public void SelectAllNodes() + { + SuspendSelectionEvent = true; + try + { + if (SelectionMode == TreeSelectionMode.MultiSameParent) + { + if (CurrentNode != null) + { + foreach (TreeNodeAdv n in CurrentNode.Parent.Nodes) + n.IsSelected = true; + } + } + else if (SelectionMode == TreeSelectionMode.Multi) + { + SelectNodes(Root.Nodes); + } + } + finally + { + SuspendSelectionEvent = false; + } + } + + private void SelectNodes(Collection nodes) + { + foreach (TreeNodeAdv n in nodes) + { + n.IsSelected = true; + if (n.IsExpanded) + SelectNodes(n.Nodes); + } + } + + #region ModelEvents + private void BindModelEvents() + { + _model.NodesChanged += new EventHandler(_model_NodesChanged); + _model.NodesInserted += new EventHandler(_model_NodesInserted); + _model.NodesRemoved += new EventHandler(_model_NodesRemoved); + _model.StructureChanged += new EventHandler(_model_StructureChanged); + } + + private void UnbindModelEvents() + { + _model.NodesChanged -= new EventHandler(_model_NodesChanged); + _model.NodesInserted -= new EventHandler(_model_NodesInserted); + _model.NodesRemoved -= new EventHandler(_model_NodesRemoved); + _model.StructureChanged -= new EventHandler(_model_StructureChanged); + } + + private void _model_StructureChanged(object sender, TreePathEventArgs e) + { + if (e.Path == null) + throw new ArgumentNullException(); + + TreeNodeAdv node = FindNode(e.Path); + if (node != null) + { + if (node != Root) + node.IsLeaf = Model.IsLeaf(GetPath(node)); + + var list = new Dictionary(); + SaveExpandedNodes(node, list); + ReadChilds(node); + RestoreExpandedNodes(node, list); + + UpdateSelection(); + SmartFullUpdate(); + } + //else + // throw new ArgumentException("Path not found"); + } + + private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary list) + { + if (node.Tag != null && list.ContainsKey(node.Tag)) + { + node.IsExpanded = true; + foreach (var child in node.Children) + RestoreExpandedNodes(child, list); + } + } + + private void SaveExpandedNodes(TreeNodeAdv node, Dictionary list) + { + if (node.IsExpanded && node.Tag != null) + { + list.Add(node.Tag, null); + foreach (var child in node.Children) + SaveExpandedNodes(child, list); + } + } + + private void _model_NodesRemoved(object sender, TreeModelEventArgs e) + { + TreeNodeAdv parent = FindNode(e.Path); + if (parent != null) + { + if (e.Indices != null) + { + List list = new List(e.Indices); + list.Sort(); + for (int n = list.Count - 1; n >= 0; n--) + { + int index = list[n]; + if (index >= 0 && index <= parent.Nodes.Count) + parent.Nodes.RemoveAt(index); + else + throw new ArgumentOutOfRangeException("Index out of range"); + } + } + else + { + for (int i = parent.Nodes.Count - 1; i >= 0; i--) + { + for (int n = 0; n < e.Children.Length; n++) + if (parent.Nodes[i].Tag == e.Children[n]) + { + parent.Nodes.RemoveAt(i); + break; + } + } + } + } + UpdateSelection(); + SmartFullUpdate(); + } + + private void _model_NodesInserted(object sender, TreeModelEventArgs e) + { + if (e.Indices == null) + throw new ArgumentNullException("Indices"); + + TreeNodeAdv parent = FindNode(e.Path); + if (parent != null) + { + for (int i = 0; i < e.Children.Length; i++) + AddNewNode(parent, e.Children[i], e.Indices[i]); + } + SmartFullUpdate(); + } + + private void _model_NodesChanged(object sender, TreeModelEventArgs e) + { + TreeNodeAdv parent = FindNode(e.Path); + if (parent != null && parent.IsVisible && parent.IsExpanded) + { + if (InvokeRequired) + BeginInvoke(new UpdateContentWidthDelegate(ClearNodesSize), e, parent); + else + ClearNodesSize(e, parent); + SmartFullUpdate(); + } + } + + private delegate void UpdateContentWidthDelegate(TreeModelEventArgs e, TreeNodeAdv parent); + private void ClearNodesSize(TreeModelEventArgs e, TreeNodeAdv parent) + { + if (e.Indices != null) + { + foreach (int index in e.Indices) + { + if (index >= 0 && index < parent.Nodes.Count) + { + TreeNodeAdv node = parent.Nodes[index]; + node.Height = node.RightBounds = null; + } + else + throw new ArgumentOutOfRangeException("Index out of range"); + } + } + else + { + foreach (TreeNodeAdv node in parent.Nodes) + { + foreach (object obj in e.Children) + if (node.Tag == obj) + { + node.Height = node.RightBounds = null; + } + } + } + } + #endregion + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdv.resx b/Aga.Controls/Tree/TreeViewAdv.resx similarity index 98% rename from External/Aga.Controls/Tree/TreeViewAdv.resx rename to Aga.Controls/Tree/TreeViewAdv.resx index 78ea3d3..f11f8f7 100644 --- a/External/Aga.Controls/Tree/TreeViewAdv.resx +++ b/Aga.Controls/Tree/TreeViewAdv.resx @@ -1,132 +1,132 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 127, 17 - - - 17, 17 - - - 236, 17 - - - False - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 127, 17 + + + 17, 17 + + + 236, 17 + + + False + \ No newline at end of file diff --git a/External/Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs b/Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs similarity index 93% rename from External/Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs rename to Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs index 4b41580..2fb0827 100644 --- a/External/Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs +++ b/Aga.Controls/Tree/TreeViewAdvCancelEventArgs.cs @@ -1,23 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public class TreeViewAdvCancelEventArgs : TreeViewAdvEventArgs - { - private bool _cancel; - - public bool Cancel - { - get { return _cancel; } - set { _cancel = value; } - } - - public TreeViewAdvCancelEventArgs(TreeNodeAdv node) - : base(node) - { - } - - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public class TreeViewAdvCancelEventArgs : TreeViewAdvEventArgs + { + private bool _cancel; + + public bool Cancel + { + get { return _cancel; } + set { _cancel = value; } + } + + public TreeViewAdvCancelEventArgs(TreeNodeAdv node) + : base(node) + { + } + + } +} diff --git a/External/Aga.Controls/Tree/TreeViewAdvEventArgs.cs b/Aga.Controls/Tree/TreeViewAdvEventArgs.cs similarity index 93% rename from External/Aga.Controls/Tree/TreeViewAdvEventArgs.cs rename to Aga.Controls/Tree/TreeViewAdvEventArgs.cs index 254a8be..c041fc4 100644 --- a/External/Aga.Controls/Tree/TreeViewAdvEventArgs.cs +++ b/Aga.Controls/Tree/TreeViewAdvEventArgs.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Aga.Controls.Tree -{ - public class TreeViewAdvEventArgs : EventArgs - { - private TreeNodeAdv _node; - - public TreeNodeAdv Node - { - get { return _node; } - } - - public TreeViewAdvEventArgs(TreeNodeAdv node) - { - _node = node; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Aga.Controls.Tree +{ + public class TreeViewAdvEventArgs : EventArgs + { + private TreeNodeAdv _node; + + public TreeNodeAdv Node + { + get { return _node; } + } + + public TreeViewAdvEventArgs(TreeNodeAdv node) + { + _node = node; + } + } +} diff --git a/External/Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs b/Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs similarity index 94% rename from External/Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs rename to Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs index 5fd3b52..f27f001 100644 --- a/External/Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs +++ b/Aga.Controls/Tree/TreeViewRowDrawEventArgs.cs @@ -1,46 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; - -namespace Aga.Controls.Tree -{ - public class TreeViewRowDrawEventArgs: PaintEventArgs - { - TreeNodeAdv _node; - DrawContext _context; - int _row; - Rectangle _rowRect; - - public TreeViewRowDrawEventArgs(Graphics graphics, Rectangle clipRectangle, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect) - : base(graphics, clipRectangle) - { - _node = node; - _context = context; - _row = row; - _rowRect = rowRect; - } - - public TreeNodeAdv Node - { - get { return _node; } - } - - public DrawContext Context - { - get { return _context; } - } - - public int Row - { - get { return _row; } - } - - public Rectangle RowRect - { - get { return _rowRect; } - } - } - -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; + +namespace Aga.Controls.Tree +{ + public class TreeViewRowDrawEventArgs: PaintEventArgs + { + TreeNodeAdv _node; + DrawContext _context; + int _row; + Rectangle _rowRect; + + public TreeViewRowDrawEventArgs(Graphics graphics, Rectangle clipRectangle, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect) + : base(graphics, clipRectangle) + { + _node = node; + _context = context; + _row = row; + _rowRect = rowRect; + } + + public TreeNodeAdv Node + { + get { return _node; } + } + + public DrawContext Context + { + get { return _context; } + } + + public int Row + { + get { return _row; } + } + + public Rectangle RowRect + { + get { return _rowRect; } + } + } + +} diff --git a/External/Aga.Controls/license.txt b/Aga.Controls/license.txt similarity index 98% rename from External/Aga.Controls/license.txt rename to Aga.Controls/license.txt index 00a76f1..428ceed 100644 --- a/External/Aga.Controls/license.txt +++ b/Aga.Controls/license.txt @@ -1,25 +1,25 @@ -The BSD License - -Copyright (c) 2009, Andrey Gliznetsov (a.gliznetsov@gmail.com) - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met - -- Redistributions of source code must retain the above copyright notice, this list of conditions -and the following disclaimer. -- Redistributions in binary form must reproduce the above copyright notice, this list of conditions -and the following disclaimer in the documentation andor other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +The BSD License + +Copyright (c) 2009, Andrey Gliznetsov (a.gliznetsov@gmail.com) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided +that the following conditions are met + +- Redistributions of source code must retain the above copyright notice, this list of conditions +and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, this list of conditions +and the following disclaimer in the documentation andor other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/Hardware/ATI/ADL.cs b/Hardware/ATI/ADL.cs deleted file mode 100644 index 403d6c7..0000000 --- a/Hardware/ATI/ADL.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.ATI { - - [StructLayout(LayoutKind.Sequential)] - internal struct ADLAdapterInfo { - public int Size; - public int AdapterIndex; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string UDID; - public int BusNumber; - public int DeviceNumber; - public int FunctionNumber; - public int VendorID; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string AdapterName; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string DisplayName; - public int Present; - public int Exist; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string DriverPath; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string DriverPathExt; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ADL.ADL_MAX_PATH)] - public string PNPString; - public int OSDisplayIndex; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ADLPMActivity { - public int Size; - public int EngineClock; - public int MemoryClock; - public int Vddc; - public int ActivityPercent; - public int CurrentPerformanceLevel; - public int CurrentBusSpeed; - public int CurrentBusLanes; - public int MaximumBusLanes; - public int Reserved; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ADLTemperature { - public int Size; - public int Temperature; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ADLFanSpeedValue { - public int Size; - public int SpeedType; - public int FanSpeed; - public int Flags; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ADLFanSpeedInfo { - public int Size; - public int Flags; - public int MinPercent; - public int MaxPercent; - public int MinRPM; - public int MaxRPM; - } - - internal class ADL { - public const int ADL_MAX_PATH = 256; - public const int ADL_MAX_ADAPTERS = 40; - public const int ADL_MAX_DISPLAYS = 40; - public const int ADL_MAX_DEVICENAME = 32; - public const int ADL_OK = 0; - public const int ADL_ERR = -1; - public const int ADL_DRIVER_OK = 0; - public const int ADL_MAX_GLSYNC_PORTS = 8; - public const int ADL_MAX_GLSYNC_PORT_LEDS = 8; - public const int ADL_MAX_NUM_DISPLAYMODES = 1024; - - public const int ADL_DL_FANCTRL_SPEED_TYPE_PERCENT = 1; - public const int ADL_DL_FANCTRL_SPEED_TYPE_RPM = 2; - - public const int ADL_DL_FANCTRL_SUPPORTS_PERCENT_READ = 1; - public const int ADL_DL_FANCTRL_SUPPORTS_PERCENT_WRITE = 2; - public const int ADL_DL_FANCTRL_SUPPORTS_RPM_READ = 4; - public const int ADL_DL_FANCTRL_SUPPORTS_RPM_WRITE = 8; - public const int ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED = 1; - - public const int ATI_VENDOR_ID = 0x1002; - - internal const string DllName = "atiadlxx.dll"; - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Main_Control_Create(ADL_Main_Memory_AllocDelegate callback, int enumConnectedAdapters); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Main_Control_Destroy(); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Adapter_AdapterInfo_Get(IntPtr info, int size); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Adapter_NumberOfAdapters_Get(); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Adapter_NumberOfAdapters_Get(ref int numAdapters); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Adapter_ID_Get(int adapterIndex, out int adapterId); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Display_AdapterID_Get(int adapterIndex, out int adapterId); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Adapter_Active_Get(int adapterIndex, out int status); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_CurrentActivity_Get(int iAdapterIndex, ref ADLPMActivity activity); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_Temperature_Get(int adapterIndex, int thermalControllerIndex, ref ADLTemperature temperature); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL2_OverdriveN_Temperature_Get(IntPtr context, int adapterIndex, int thermalControllerIndex, ref int temp); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_FanSpeed_Get(int adapterIndex, int thermalControllerIndex, ref ADLFanSpeedValue fanSpeedValue); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_FanSpeedInfo_Get(int adapterIndex, int thermalControllerIndex, ref ADLFanSpeedInfo fanSpeedInfo); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_FanSpeedToDefault_Set(int adapterIndex, int thermalControllerIndex); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive5_FanSpeed_Set(int adapterIndex, int thermalControllerIndex, ref ADLFanSpeedValue fanSpeedValue); - [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] - public static extern int ADL_Overdrive_Caps(int adapterIndex, ref int supported, ref int enabled, ref int version); - - public static int ADL_Main_Control_Create(int enumConnectedAdapters) { - try { - if (Kernel32.LoadLibrary(DllName) != IntPtr.Zero) - return ADL_Main_Control_Create(Main_Memory_Alloc, enumConnectedAdapters); - - return ADL_ERR; - } catch { - return ADL_ERR; - } - } - - public static int ADL_Adapter_AdapterInfo_Get(ADLAdapterInfo[] info) { - int elementSize = Marshal.SizeOf(typeof(ADLAdapterInfo)); - int size = info.Length * elementSize; - IntPtr ptr = Marshal.AllocHGlobal(size); - int result = ADL_Adapter_AdapterInfo_Get(ptr, size); - for (int i = 0; i < info.Length; i++) - info[i] = (ADLAdapterInfo) - Marshal.PtrToStructure((IntPtr)((long)ptr + i * elementSize), - typeof(ADLAdapterInfo)); - Marshal.FreeHGlobal(ptr); - - // the ADLAdapterInfo.VendorID field reported by ADL is wrong on - // Windows systems (parse error), so we fix this here - for (int i = 0; i < info.Length; i++) { - // try Windows UDID format - Match m = Regex.Match(info[i].UDID, "PCI_VEN_([A-Fa-f0-9]{1,4})&.*"); - if (m.Success && m.Groups.Count == 2) { - info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 16); - continue; - } - // if above failed, try Unix UDID format - m = Regex.Match(info[i].UDID, "[0-9]+:[0-9]+:([0-9]+):[0-9]+:[0-9]+"); - if (m.Success && m.Groups.Count == 2) { - info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 10); - } - } - - return result; - } - - public delegate IntPtr ADL_Main_Memory_AllocDelegate(int size); - - // create a Main_Memory_Alloc delegate and keep it alive - public static ADL_Main_Memory_AllocDelegate Main_Memory_Alloc = - delegate(int size) { - return Marshal.AllocHGlobal(size); - }; - - public static void Main_Memory_Free(IntPtr buffer) { - if (IntPtr.Zero != buffer) - Marshal.FreeHGlobal(buffer); - } - } -} diff --git a/Hardware/ATI/ATIGPU.cs b/Hardware/ATI/ATIGPU.cs deleted file mode 100644 index 3614077..0000000 --- a/Hardware/ATI/ATIGPU.cs +++ /dev/null @@ -1,237 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2014 Michael Möller - -*/ - -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware.ATI { - internal sealed class ATIGPU : Hardware { - - private readonly int adapterIndex; - private readonly int busNumber; - private readonly int deviceNumber; - private readonly Sensor temperatureCore; - private readonly Sensor temperatureHBM; - private readonly Sensor temperatureVDDC; - private readonly Sensor temperatureMVDD; - private readonly Sensor temperatureHotSpot; - private readonly Sensor fan; - private readonly Sensor coreClock; - private readonly Sensor memoryClock; - private readonly Sensor coreVoltage; - private readonly Sensor coreLoad; - private readonly Sensor controlSensor; - private readonly Control fanControl; - private readonly bool isOverdriveNSupported; - - public ATIGPU(string name, int adapterIndex, int busNumber, - int deviceNumber, ISettings settings) - : base(name, new Identifier("atigpu", - adapterIndex.ToString(CultureInfo.InvariantCulture)), settings) - { - this.adapterIndex = adapterIndex; - this.busNumber = busNumber; - this.deviceNumber = deviceNumber; - - this.temperatureCore = new Sensor("GPU Core", 0, SensorType.Temperature, this, settings); - this.temperatureHBM = new Sensor("GPU HBM", 1, SensorType.Temperature, this, settings); - this.temperatureVDDC = new Sensor("GPU VDDC", 2, SensorType.Temperature, this, settings); - this.temperatureMVDD = new Sensor("GPU MVDD", 3, SensorType.Temperature, this, settings); - this.temperatureHotSpot = new Sensor("GPU Hot Spot", 4, SensorType.Temperature, this, settings); - this.fan = new Sensor("GPU Fan", 0, SensorType.Fan, this, settings); - this.coreClock = new Sensor("GPU Core", 0, SensorType.Clock, this, settings); - this.memoryClock = new Sensor("GPU Memory", 1, SensorType.Clock, this, settings); - this.coreVoltage = new Sensor("GPU Core", 0, SensorType.Voltage, this, settings); - this.coreLoad = new Sensor("GPU Core", 0, SensorType.Load, this, settings); - this.controlSensor = new Sensor("GPU Fan", 0, SensorType.Control, this, settings); - - int supported = 0; - int enabled = 0; - int version = 0; - isOverdriveNSupported = ADL.ADL_Overdrive_Caps(1, ref supported, ref enabled, ref version) == ADL.ADL_OK && version >= 7; - - ADLFanSpeedInfo afsi = new ADLFanSpeedInfo(); - if (ADL.ADL_Overdrive5_FanSpeedInfo_Get(adapterIndex, 0, ref afsi) - != ADL.ADL_OK) - { - afsi.MaxPercent = 100; - afsi.MinPercent = 0; - } - - this.fanControl = new Control(controlSensor, settings, afsi.MinPercent, - afsi.MaxPercent); - this.fanControl.ControlModeChanged += ControlModeChanged; - this.fanControl.SoftwareControlValueChanged += - SoftwareControlValueChanged; - ControlModeChanged(fanControl); - this.controlSensor.Control = fanControl; - Update(); - } - - private void SoftwareControlValueChanged(IControl control) { - if (control.ControlMode == ControlMode.Software) { - ADLFanSpeedValue adlf = new ADLFanSpeedValue(); - adlf.SpeedType = ADL.ADL_DL_FANCTRL_SPEED_TYPE_PERCENT; - adlf.Flags = ADL.ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED; - adlf.FanSpeed = (int)control.SoftwareValue; - ADL.ADL_Overdrive5_FanSpeed_Set(adapterIndex, 0, ref adlf); - } - } - - private void ControlModeChanged(IControl control) { - switch (control.ControlMode) { - case ControlMode.Undefined: - return; - case ControlMode.Default: - SetDefaultFanSpeed(); - break; - case ControlMode.Software: - SoftwareControlValueChanged(control); - break; - default: - return; - } - } - - private void SetDefaultFanSpeed() { - ADL.ADL_Overdrive5_FanSpeedToDefault_Set(adapterIndex, 0); - } - - public int BusNumber { get { return busNumber; } } - - public int DeviceNumber { get { return deviceNumber; } } - - - public override HardwareType HardwareType { - get { return HardwareType.GpuAti; } - } - - public override void Update() { - - if (isOverdriveNSupported) { - int temp = 0; - IntPtr context = IntPtr.Zero; - - if (ADL.ADL2_OverdriveN_Temperature_Get(context, adapterIndex, 1, ref temp) == ADL.ADL_OK) { - temperatureCore.Value = 0.001f * temp; - ActivateSensor(temperatureCore); - } else { - temperatureCore.Value = null; - } - - if (ADL.ADL2_OverdriveN_Temperature_Get(context, adapterIndex, 2, ref temp) == ADL.ADL_OK) { - temperatureHBM.Value = temp; - ActivateSensor(temperatureHBM); - } else { - temperatureHBM.Value = null; - } - - if (ADL.ADL2_OverdriveN_Temperature_Get(context, adapterIndex, 3, ref temp) == ADL.ADL_OK) { - temperatureVDDC.Value = temp; - ActivateSensor(temperatureVDDC); - } else { - temperatureVDDC.Value = null; - } - - if (ADL.ADL2_OverdriveN_Temperature_Get(context, adapterIndex, 4, ref temp) == ADL.ADL_OK) { - temperatureMVDD.Value = temp; - ActivateSensor(temperatureMVDD); - } else { - temperatureMVDD.Value = null; - } - - if (ADL.ADL2_OverdriveN_Temperature_Get(context, adapterIndex, 7, ref temp) == ADL.ADL_OK) { - temperatureHotSpot.Value = temp; - ActivateSensor(temperatureHotSpot); - } else { - temperatureHotSpot.Value = null; - } - - if (context != IntPtr.Zero) { - Marshal.FreeHGlobal(context); - } - } else { - ADLTemperature adlt = new ADLTemperature(); - if (ADL.ADL_Overdrive5_Temperature_Get(adapterIndex, 0, ref adlt) == ADL.ADL_OK) { - temperatureCore.Value = 0.001f * adlt.Temperature; - ActivateSensor(temperatureCore); - } else { - temperatureCore.Value = null; - } - } - - ADLFanSpeedValue adlf = new ADLFanSpeedValue(); - adlf.SpeedType = ADL.ADL_DL_FANCTRL_SPEED_TYPE_RPM; - if (ADL.ADL_Overdrive5_FanSpeed_Get(adapterIndex, 0, ref adlf) - == ADL.ADL_OK) - { - fan.Value = adlf.FanSpeed; - ActivateSensor(fan); - } else { - fan.Value = null; - } - - adlf = new ADLFanSpeedValue(); - adlf.SpeedType = ADL.ADL_DL_FANCTRL_SPEED_TYPE_PERCENT; - if (ADL.ADL_Overdrive5_FanSpeed_Get(adapterIndex, 0, ref adlf) - == ADL.ADL_OK) { - controlSensor.Value = adlf.FanSpeed; - ActivateSensor(controlSensor); - } else { - controlSensor.Value = null; - } - - ADLPMActivity adlp = new ADLPMActivity(); - if (ADL.ADL_Overdrive5_CurrentActivity_Get(adapterIndex, ref adlp) - == ADL.ADL_OK) - { - if (adlp.EngineClock > 0) { - coreClock.Value = 0.01f * adlp.EngineClock; - ActivateSensor(coreClock); - } else { - coreClock.Value = null; - } - - if (adlp.MemoryClock > 0) { - memoryClock.Value = 0.01f * adlp.MemoryClock; - ActivateSensor(memoryClock); - } else { - memoryClock.Value = null; - } - - if (adlp.Vddc > 0) { - coreVoltage.Value = 0.001f * adlp.Vddc; - ActivateSensor(coreVoltage); - } else { - coreVoltage.Value = null; - } - - coreLoad.Value = Math.Min(adlp.ActivityPercent, 100); - ActivateSensor(coreLoad); - } else { - coreClock.Value = null; - memoryClock.Value = null; - coreVoltage.Value = null; - coreLoad.Value = null; - } - } - - public override void Close() { - this.fanControl.ControlModeChanged -= ControlModeChanged; - this.fanControl.SoftwareControlValueChanged -= - SoftwareControlValueChanged; - - if (this.fanControl.ControlMode != ControlMode.Undefined) - SetDefaultFanSpeed(); - base.Close(); - } - } -} diff --git a/Hardware/ATI/ATIGroup.cs b/Hardware/ATI/ATIGroup.cs deleted file mode 100644 index 32047b1..0000000 --- a/Hardware/ATI/ATIGroup.cs +++ /dev/null @@ -1,121 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.ATI { - internal class ATIGroup : IGroup { - - private readonly List hardware = new List(); - private readonly StringBuilder report = new StringBuilder(); - private readonly int status; - public ATIGroup(ISettings settings) { - try { - status = ADL.ADL_Main_Control_Create(1); - - report.AppendLine("AMD Display Library"); - report.AppendLine(); - report.Append("Status: "); - report.AppendLine(status == ADL.ADL_OK ? "OK" : - status.ToString(CultureInfo.InvariantCulture)); - report.AppendLine(); - - if (status == ADL.ADL_OK) { - int numberOfAdapters = 0; - ADL.ADL_Adapter_NumberOfAdapters_Get(ref numberOfAdapters); - - report.Append("Number of adapters: "); - report.AppendLine(numberOfAdapters.ToString(CultureInfo.InvariantCulture)); - report.AppendLine(); - - if (numberOfAdapters > 0) { - ADLAdapterInfo[] adapterInfo = new ADLAdapterInfo[numberOfAdapters]; - if (ADL.ADL_Adapter_AdapterInfo_Get(adapterInfo) == ADL.ADL_OK) - for (int i = 0; i < numberOfAdapters; i++) { - ADL.ADL_Adapter_Active_Get(adapterInfo[i].AdapterIndex, out var isActive); - ADL.ADL_Adapter_ID_Get(adapterInfo[i].AdapterIndex, out var adapterId); - - report.Append("AdapterIndex: "); - report.AppendLine(i.ToString(CultureInfo.InvariantCulture)); - report.Append("isActive: "); - report.AppendLine(isActive.ToString(CultureInfo.InvariantCulture)); - report.Append("AdapterName: "); - report.AppendLine(adapterInfo[i].AdapterName); - report.Append("UDID: "); - report.AppendLine(adapterInfo[i].UDID); - report.Append("Present: "); - report.AppendLine(adapterInfo[i].Present.ToString( - CultureInfo.InvariantCulture)); - report.Append("VendorID: 0x"); - report.AppendLine(adapterInfo[i].VendorID.ToString("X", - CultureInfo.InvariantCulture)); - report.Append("BusNumber: "); - report.AppendLine(adapterInfo[i].BusNumber.ToString( - CultureInfo.InvariantCulture)); - report.Append("DeviceNumber: "); - report.AppendLine(adapterInfo[i].DeviceNumber.ToString( - CultureInfo.InvariantCulture)); - report.Append("FunctionNumber: "); - report.AppendLine(adapterInfo[i].FunctionNumber.ToString( - CultureInfo.InvariantCulture)); - report.Append("AdapterID: 0x"); - report.AppendLine(adapterId.ToString("X", - CultureInfo.InvariantCulture)); - - if (!string.IsNullOrEmpty(adapterInfo[i].UDID) && - adapterInfo[i].VendorID == ADL.ATI_VENDOR_ID) - { - bool found = false; - foreach (ATIGPU gpu in hardware) - if (gpu.BusNumber == adapterInfo[i].BusNumber && - gpu.DeviceNumber == adapterInfo[i].DeviceNumber) { - found = true; - break; - } - if (!found) - hardware.Add(new ATIGPU( - adapterInfo[i].AdapterName.Trim(), - adapterInfo[i].AdapterIndex, - adapterInfo[i].BusNumber, - adapterInfo[i].DeviceNumber, settings)); - } - - report.AppendLine(); - } - } - } - } catch (DllNotFoundException) { } - catch (EntryPointNotFoundException e) { - report.AppendLine(); - report.AppendLine(e.ToString()); - report.AppendLine(); - } - } - - public IEnumerable Hardware => hardware; - - public string GetReport() { - return report.ToString(); - } - - public void Close() { - try { - foreach (ATIGPU gpu in hardware) - gpu.Close(); - if (status == ADL.ADL_OK) - ADL.ADL_Main_Control_Destroy(); - } catch (Exception) { } - } - } -} diff --git a/Hardware/Aquacomputer/AquacomputerGroup.cs b/Hardware/Aquacomputer/AquacomputerGroup.cs deleted file mode 100644 index 9873825..0000000 --- a/Hardware/Aquacomputer/AquacomputerGroup.cs +++ /dev/null @@ -1,67 +0,0 @@ -using HidLibrary; -using System.Collections.Generic; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Aquacomputer -{ - public class AquacomputerGroup : IGroup - { - private readonly List _hardware = new List(); - private readonly StringBuilder _report = new StringBuilder(); - - public AquacomputerGroup(ISettings settings) - { - _report.AppendLine($"Aquacomputer Hardware"); - _report.AppendLine(); - - foreach (HidDevice dev in HidDevices.Enumerate(0x0c70)) - { - byte[] productNameBytes; - dev.ReadProduct(out productNameBytes); - string ProductName = UnicodeEncoding.Unicode.GetString(productNameBytes).Replace("\0", string.Empty); - ProductName = ProductName.Substring(0,1).ToUpper() + ProductName.Substring(1); - - switch (dev.Attributes.ProductId) - { - case 0xf0b6: - { - var device = new AquastreamXT(dev, settings); - _report.AppendLine($"Device name: {ProductName}"); - _report.AppendLine($"Device variant: {device.Variant}"); - _report.AppendLine($"Firmware version: {device.FirmwareVersion}"); - _report.AppendLine($"{device.Status}"); - _report.AppendLine(); - _hardware.Add(device); - break; - } - default: - { - _report.AppendLine($"Unknown Hardware PID: {dev.Attributes.ProductHexId} Name: {ProductName}"); - _report.AppendLine(); - break; - } - } - } - if (_hardware.Count == 0) - { - _report.AppendLine("No Aquacomputer Hardware found."); - _report.AppendLine(); - } - } - - public IEnumerable Hardware => _hardware; - - public void Close() - { - foreach (Hardware h in _hardware) - { - h.Close(); - } - } - - public string GetReport() - { - return _report.ToString(); - } - } -} diff --git a/Hardware/Aquacomputer/AquastreamXT.cs b/Hardware/Aquacomputer/AquastreamXT.cs deleted file mode 100644 index 4035f7e..0000000 --- a/Hardware/Aquacomputer/AquastreamXT.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using HidLibrary; - -namespace OpenHardwareMonitor.Hardware.Aquacomputer -{ - /* - * TODO: - * Check tested and fix unknown variables in Update() - * Check if property "Variant" is valid interpreted - * Implement Fan Control in SetControl() - */ - internal class AquastreamXT : Hardware - { - [Flags] - enum PumpAlarms : byte - { - ALARM_SENSOR1 = 1, - ALARM_SENSOR2 = 2, - ALARM_PUMP = 4, - ALARM_FAN = 8, - ALARM_FLOW = 16, - ALARM_FAN_SHORT = 32, - ALARM_FAN_TEMP90 = 64, - ALARM_FAN_TEMP70 = 128 - } - - [Flags] - enum PumpMode : byte - { - MODE_PUMP_ADV = 1, - MODE_FAN_AMP = 2, - MODE_FAN_CONTROLLER = 4 - } - - #region USB - private HidDevice device; - private byte[] rawData; - public UInt16 FirmwareVersion { get; private set; } - #endregion - - private readonly Sensor _fanControl, _pumpPower, _pumpFlow; - private readonly Sensor[] _rpmSensors = new Sensor[2]; - private readonly Sensor[] _temperatures = new Sensor[3]; - private readonly Sensor[] _voltages = new Sensor[2]; - private readonly Sensor[] _frequencies = new Sensor[2]; - - public AquastreamXT(HidDevice dev, ISettings settings) : base("Aquastream XT", new Identifier(dev.DevicePath), settings) - { - device = dev; - - do - { - device.ReadFeatureData(out rawData, 0x4); - } while (rawData[0] != 0x4); - - Name = $"Aquastream XT {Variant}"; - FirmwareVersion = BitConverter.ToUInt16(rawData, 50); - - _temperatures[0] = new Sensor("External Fan VRM", 0, SensorType.Temperature, this, new ParameterDescription[0], settings); - ActivateSensor(_temperatures[0]); - _temperatures[1] = new Sensor("External", 1, SensorType.Temperature, this, new ParameterDescription[0], settings); - ActivateSensor(_temperatures[1]); - _temperatures[2] = new Sensor("Internal Water", 2, SensorType.Temperature, this, new ParameterDescription[0], settings); - ActivateSensor(_temperatures[2]); - - _voltages[0] = new Sensor("External Fan", 1, SensorType.Voltage, this, new ParameterDescription[0], settings); - ActivateSensor(_voltages[0]); - _voltages[1] = new Sensor("Pump", 2, SensorType.Voltage, this, new ParameterDescription[0], settings); - ActivateSensor(_voltages[1]); - - _pumpPower = new Sensor("Pump", 0, SensorType.Power, this, new ParameterDescription[0], settings); - ActivateSensor(_pumpPower); - - _pumpFlow = new Sensor("Pump", 0, SensorType.Flow, this, new ParameterDescription[0], settings); - ActivateSensor(_pumpFlow); - - _rpmSensors[0] = new Sensor("External Fan", 0, SensorType.Fan, this, new ParameterDescription[0], settings); - ActivateSensor(_rpmSensors[0]); - _rpmSensors[1] = new Sensor("Pump", 1, SensorType.Fan, this, new ParameterDescription[0], settings); - ActivateSensor(_rpmSensors[1]); - - _fanControl = new Sensor("External Fan", 0, SensorType.Control, this, new ParameterDescription[0], settings); - Control control = new Control(_fanControl, settings, 0, 100); - control.ControlModeChanged += (cc) => { - switch (cc.ControlMode) - { - case ControlMode.Undefined: - return; - case ControlMode.Default: - SetControl(null); - break; - case ControlMode.Software: - SetControl((byte)(cc.SoftwareValue * 2.55)); - break; - default: - return; - } - }; - control.SoftwareControlValueChanged += (cc) => { - if (cc.ControlMode == ControlMode.Software) - SetControl((byte)(cc.SoftwareValue * 2.55)); - }; - - switch (control.ControlMode) - { - case ControlMode.Undefined: - break; - case ControlMode.Default: - SetControl(null); - break; - case ControlMode.Software: - SetControl((byte)(control.SoftwareValue * 2.55)); - break; - default: - break; - } - _fanControl.Control = control; - ActivateSensor(_fanControl); - - _frequencies[0] = new Sensor("Pump Frequency", 0, SensorType.Frequency, this, new ParameterDescription[0], settings); - ActivateSensor(_frequencies[0]); - _frequencies[1] = new Sensor("Pump MaxFrequency", 1, SensorType.Frequency, this, new ParameterDescription[0], settings); - ActivateSensor(_frequencies[1]); - } - - //TODO: Implement Fan Control - private void SetControl(byte? v) - { - throw new NotImplementedException(); - } - - //TODO: Check if valid - public string Variant - { - get - { - PumpMode mode = (PumpMode)rawData[33]; - - if (mode.HasFlag(PumpMode.MODE_PUMP_ADV)) - return "Ultra + Internal Flow Sensor"; - else if (mode.HasFlag(PumpMode.MODE_FAN_CONTROLLER)) - return "Ultra"; - else if (mode.HasFlag(PumpMode.MODE_FAN_AMP)) - return "Advanced"; - else - return "Standard"; - } - } - - public override HardwareType HardwareType - { - get - { - return HardwareType.Aquacomputer; - } - } - - public string Status { - get { - FirmwareVersion = BitConverter.ToUInt16(rawData, 50); - - if (FirmwareVersion < 1008) - { - return $"Status: Untested Firmware Version {FirmwareVersion}! Please consider Updating to Version 1018"; - } - return "Status: OK"; - } - } - - public override void Close() - { - device.CloseDevice(); - base.Close(); - } - - //TODO: Check tested and fix unknown variables - public override void Update() - { - device.ReadFeatureData(out rawData, 0x4); - - if (rawData[0] != 0x4) - return; - - //var rawSensorsFan = BitConverter.ToUInt16(rawData, 1); //unknown - redundant? - //var rawSensorsExt = BitConverter.ToUInt16(rawData, 3); //unknown - redundant? - //var rawSensorsWater = BitConverter.ToUInt16(rawData, 5); //unknown - redundant? - - _voltages[0].Value = BitConverter.ToUInt16(rawData, 7) / 61f; //External Fan Voltage: tested - OK - _voltages[1].Value = BitConverter.ToUInt16(rawData, 9) / 61f; //Pump Voltage: tested - OK - _pumpPower.Value = _voltages[1].Value * BitConverter.ToInt16(rawData, 11) / 625f; //Pump Voltage * Pump Current: tested - OK - - _temperatures[0].Value = BitConverter.ToUInt16(rawData, 13) / 100f; //External Fan VRM Temperature: untested - _temperatures[1].Value = BitConverter.ToUInt16(rawData, 15) / 100f; //External Temperature Sensor: untested - _temperatures[2].Value = BitConverter.ToUInt16(rawData, 17) / 100f; //Internal Water Temperature Sensor: tested - OK - - _frequencies[0].Value = (1f / BitConverter.ToInt16(rawData, 19)) * 750000; //Pump Frequency: tested - OK - _rpmSensors[1].Value = _frequencies[0].Value * 60f; //Pump RPM: tested - OK - _frequencies[1].Value = (1f / BitConverter.ToUInt16(rawData, 21)) * 750000; //Pump Max Frequency: tested - OK - - _pumpFlow.Value = BitConverter.ToUInt32(rawData, 23); //Internal Pump Flow Sensor: unknown - - _rpmSensors[0].Value = BitConverter.ToUInt32(rawData, 27); //External Fan RPM: untested - - _fanControl.Value = 100f / byte.MaxValue * rawData[31]; //External Fan Control: tested, External Fan Voltage scales by this value - OK - } - } -} diff --git a/Hardware/CPU/AMD0FCPU.cs b/Hardware/CPU/AMD0FCPU.cs deleted file mode 100644 index 526815a..0000000 --- a/Hardware/CPU/AMD0FCPU.cs +++ /dev/null @@ -1,154 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - Copyright (C) 2010 Paul Werelds - -*/ - -using System.Globalization; -using System.Text; -using System.Threading; - -namespace OpenHardwareMonitor.Hardware.CPU { - internal sealed class AMD0FCPU : AMDCPU { - - private readonly Sensor[] coreTemperatures; - private readonly Sensor[] coreClocks; - private readonly Sensor busClock; - - private const uint FIDVID_STATUS = 0xC0010042; - - private const byte MISCELLANEOUS_CONTROL_FUNCTION = 3; - private const ushort MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1103; - private const uint THERMTRIP_STATUS_REGISTER = 0xE4; - - private readonly byte thermSenseCoreSelCPU0; - private readonly byte thermSenseCoreSelCPU1; - private readonly uint miscellaneousControlAddress; - - public AMD0FCPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(processorIndex, cpuid, settings) - { - float offset = -49.0f; - - // AM2+ 65nm +21 offset - uint model = cpuid[0][0].Model; - if (model >= 0x69 && model != 0xc1 && model != 0x6c && model != 0x7c) - offset += 21; - - if (model < 40) { - // AMD Athlon 64 Processors - thermSenseCoreSelCPU0 = 0x0; - thermSenseCoreSelCPU1 = 0x4; - } else { - // AMD NPT Family 0Fh Revision F, G have the core selection swapped - thermSenseCoreSelCPU0 = 0x4; - thermSenseCoreSelCPU1 = 0x0; - } - - // check if processor supports a digital thermal sensor - if (cpuid[0][0].ExtData.GetLength(0) > 7 && - (cpuid[0][0].ExtData[7, 3] & 1) != 0) - { - coreTemperatures = new Sensor[coreCount]; - for (int i = 0; i < coreCount; i++) { - coreTemperatures[i] = - new Sensor("Core #" + (i + 1), i, SensorType.Temperature, - this, new [] { new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", offset) - }, settings); - } - } else { - coreTemperatures = new Sensor[0]; - } - - miscellaneousControlAddress = GetPciAddress( - MISCELLANEOUS_CONTROL_FUNCTION, MISCELLANEOUS_CONTROL_DEVICE_ID); - - busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings); - coreClocks = new Sensor[coreCount]; - for (int i = 0; i < coreClocks.Length; i++) { - coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock, - this, settings); - if (HasTimeStampCounter) - ActivateSensor(coreClocks[i]); - } - - Update(); - } - - protected override uint[] GetMSRs() { - return new [] { FIDVID_STATUS }; - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - r.Append(base.GetReport()); - - r.Append("Miscellaneous Control Address: 0x"); - r.AppendLine((miscellaneousControlAddress).ToString("X", - CultureInfo.InvariantCulture)); - r.AppendLine(); - - return r.ToString(); - } - - public override void Update() { - base.Update(); - - if (miscellaneousControlAddress != Ring0.InvalidPciAddress) { - for (uint i = 0; i < coreTemperatures.Length; i++) { - if (Ring0.WritePciConfig( - miscellaneousControlAddress, THERMTRIP_STATUS_REGISTER, - i > 0 ? thermSenseCoreSelCPU1 : thermSenseCoreSelCPU0)) { - uint value; - if (Ring0.ReadPciConfig( - miscellaneousControlAddress, THERMTRIP_STATUS_REGISTER, - out value)) - { - coreTemperatures[i].Value = ((value >> 16) & 0xFF) + - coreTemperatures[i].Parameters[0].Value; - ActivateSensor(coreTemperatures[i]); - } else { - DeactivateSensor(coreTemperatures[i]); - } - } - } - } - - if (HasTimeStampCounter) { - double newBusClock = 0; - - for (int i = 0; i < coreClocks.Length; i++) { - Thread.Sleep(1); - - uint eax, edx; - if (Ring0.RdmsrTx(FIDVID_STATUS, out eax, out edx, - 1UL << cpuid[i][0].Thread)) { - // CurrFID can be found in eax bits 0-5, MaxFID in 16-21 - // 8-13 hold StartFID, we don't use that here. - double curMP = 0.5 * ((eax & 0x3F) + 8); - double maxMP = 0.5 * ((eax >> 16 & 0x3F) + 8); - coreClocks[i].Value = - (float)(curMP * TimeStampCounterFrequency / maxMP); - newBusClock = (float)(TimeStampCounterFrequency / maxMP); - } else { - // Fail-safe value - if the code above fails, we'll use this instead - coreClocks[i].Value = (float)TimeStampCounterFrequency; - } - } - - if (newBusClock > 0) { - this.busClock.Value = (float)newBusClock; - ActivateSensor(this.busClock); - } - } - } - - } -} diff --git a/Hardware/CPU/AMD10CPU.cs b/Hardware/CPU/AMD10CPU.cs deleted file mode 100644 index 9395f46..0000000 --- a/Hardware/CPU/AMD10CPU.cs +++ /dev/null @@ -1,453 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2013 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading; - -namespace OpenHardwareMonitor.Hardware.CPU { - - internal sealed class AMD10CPU : AMDCPU { - - private readonly Sensor coreTemperature; - private readonly Sensor[] coreClocks; - private readonly Sensor busClock; - private readonly Sensor[] cStatesResidency; - private readonly Sensor coreVoltage; - private readonly Sensor northbridgeVoltage; - - private const uint PERF_CTL_0 = 0xC0010000; - private const uint PERF_CTR_0 = 0xC0010004; - private const uint HWCR = 0xC0010015; - private const uint P_STATE_0 = 0xC0010064; - private const uint COFVID_STATUS = 0xC0010071; - - private const byte MISCELLANEOUS_CONTROL_FUNCTION = 3; - private const ushort FAMILY_10H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1203; - private const ushort FAMILY_11H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1303; - private const ushort FAMILY_12H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1703; - private const ushort FAMILY_14H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1703; - private const ushort FAMILY_15H_MODEL_00_MISC_CONTROL_DEVICE_ID = 0x1603; - private const ushort FAMILY_15H_MODEL_10_MISC_CONTROL_DEVICE_ID = 0x1403; - private const ushort FAMILY_15H_MODEL_30_MISC_CONTROL_DEVICE_ID = 0x141D; - private const ushort FAMILY_15H_MODEL_60_MISC_CONTROL_DEVICE_ID = 0x1573; - private const ushort FAMILY_16H_MODEL_00_MISC_CONTROL_DEVICE_ID = 0x1533; - private const ushort FAMILY_16H_MODEL_30_MISC_CONTROL_DEVICE_ID = 0x1583; - private const ushort FAMILY_17H_MODEL_00_MISC_CONTROL_DEVICE_ID = 0x1577; - - private const uint REPORTED_TEMPERATURE_CONTROL_REGISTER = 0xA4; - private const uint CLOCK_POWER_TIMING_CONTROL_0_REGISTER = 0xD4; - - private const uint F15H_M60H_REPORTED_TEMP_CTRL_OFFSET = 0xD8200CA4; - - private readonly uint miscellaneousControlAddress; - private readonly ushort miscellaneousControlDeviceId; - - private const uint cStatesIoPort = 0xCD6; - private readonly byte cStatesIoOffset; - - private readonly bool isSVI2; - - private readonly FileStream temperatureStream; - - private readonly double timeStampCounterMultiplier; - private readonly bool corePerformanceBoostSupport; - - public AMD10CPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(processorIndex, cpuid, settings) - { - // AMD family 1Xh processors support only one temperature sensor - coreTemperature = new Sensor("CPU Cores", 0, SensorType.Temperature, this, new[] { - new ParameterDescription("Offset [°C]", "Temperature offset.", 0) - }, settings); - - coreVoltage = new Sensor("CPU Cores", 0, SensorType.Voltage, this, settings); - ActivateSensor(coreVoltage); - northbridgeVoltage = new Sensor("Northbridge", 0, - SensorType.Voltage, this, settings); - ActivateSensor(northbridgeVoltage); - isSVI2 = (family == 0x15 && model >= 0x10) || family == 0x16; - - switch (family) { - case 0x10: - miscellaneousControlDeviceId = - FAMILY_10H_MISCELLANEOUS_CONTROL_DEVICE_ID; break; - case 0x11: - miscellaneousControlDeviceId = - FAMILY_11H_MISCELLANEOUS_CONTROL_DEVICE_ID; break; - case 0x12: - miscellaneousControlDeviceId = - FAMILY_12H_MISCELLANEOUS_CONTROL_DEVICE_ID; break; - case 0x14: - miscellaneousControlDeviceId = - FAMILY_14H_MISCELLANEOUS_CONTROL_DEVICE_ID; break; - case 0x15: - switch (model & 0xF0) { - case 0x00: - miscellaneousControlDeviceId = - FAMILY_15H_MODEL_00_MISC_CONTROL_DEVICE_ID; break; - case 0x10: - miscellaneousControlDeviceId = - FAMILY_15H_MODEL_10_MISC_CONTROL_DEVICE_ID; break; - case 0x30: - miscellaneousControlDeviceId = - FAMILY_15H_MODEL_30_MISC_CONTROL_DEVICE_ID; break; - case 0x70: - case 0x60: - miscellaneousControlDeviceId = - FAMILY_15H_MODEL_60_MISC_CONTROL_DEVICE_ID; break; - default: miscellaneousControlDeviceId = 0; break; - } - break; - case 0x16: - switch (model & 0xF0) { - case 0x00: - miscellaneousControlDeviceId = - FAMILY_16H_MODEL_00_MISC_CONTROL_DEVICE_ID; break; - case 0x30: - miscellaneousControlDeviceId = - FAMILY_16H_MODEL_30_MISC_CONTROL_DEVICE_ID; break; - default: miscellaneousControlDeviceId = 0; break; - } - break; - case 0x17: - miscellaneousControlDeviceId = - FAMILY_17H_MODEL_00_MISC_CONTROL_DEVICE_ID; break; - default: miscellaneousControlDeviceId = 0; break; - } - - // get the pci address for the Miscellaneous Control registers - miscellaneousControlAddress = GetPciAddress( - MISCELLANEOUS_CONTROL_FUNCTION, miscellaneousControlDeviceId); - - busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings); - coreClocks = new Sensor[coreCount]; - for (int i = 0; i < coreClocks.Length; i++) { - coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock, - this, settings); - if (HasTimeStampCounter) - ActivateSensor(coreClocks[i]); - } - - corePerformanceBoostSupport = (cpuid[0][0].ExtData[7, 3] & (1 << 9)) > 0; - - // set affinity to the first thread for all frequency estimations - ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread); - - // disable core performance boost - uint hwcrEax, hwcrEdx; - Ring0.Rdmsr(HWCR, out hwcrEax, out hwcrEdx); - if (corePerformanceBoostSupport) - Ring0.Wrmsr(HWCR, hwcrEax | (1 << 25), hwcrEdx); - - uint ctlEax, ctlEdx; - Ring0.Rdmsr(PERF_CTL_0, out ctlEax, out ctlEdx); - uint ctrEax, ctrEdx; - Ring0.Rdmsr(PERF_CTR_0, out ctrEax, out ctrEdx); - - timeStampCounterMultiplier = estimateTimeStampCounterMultiplier(); - - // restore the performance counter registers - Ring0.Wrmsr(PERF_CTL_0, ctlEax, ctlEdx); - Ring0.Wrmsr(PERF_CTR_0, ctrEax, ctrEdx); - - // restore core performance boost - if (corePerformanceBoostSupport) - Ring0.Wrmsr(HWCR, hwcrEax, hwcrEdx); - - // restore the thread affinity. - ThreadAffinity.Set(mask); - - // the file reader for lm-sensors support on Linux - temperatureStream = null; - - if (Software.OperatingSystem.IsLinux) { - string[] devicePaths = Directory.GetDirectories("/sys/class/hwmon/"); - foreach (string path in devicePaths) { - string name = null; - try { - using (StreamReader reader = new StreamReader(path + "/device/name")) - name = reader.ReadLine(); - } catch (IOException) { } - switch (name) { - case "k10temp": - temperatureStream = new FileStream(path + "/device/temp1_input", - FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - break; - } - } - } - - uint addr = Ring0.GetPciAddress(0, 20, 0); - if (Ring0.ReadPciConfig(addr, 0, out uint dev)) { - Ring0.ReadPciConfig(addr, 8, out uint rev); - - if (dev == 0x43851002) - cStatesIoOffset = (byte)((rev & 0xFF) < 0x40 ? 0xB3 : 0x9C); - else if (dev == 0x780B1022 || dev == 0x790B1022) - cStatesIoOffset = (byte)0x9C; - } - if (cStatesIoOffset != 0) { - cStatesResidency = new Sensor[]{ - new Sensor("CPU Package C2", 0, SensorType.Level, this, settings), - new Sensor("CPU Package C3", 1, SensorType.Level, this, settings) }; - ActivateSensor(cStatesResidency[0]); - ActivateSensor(cStatesResidency[1]); - } - Update(); - } - - private double estimateTimeStampCounterMultiplier() { - // preload the function - estimateTimeStampCounterMultiplier(0); - estimateTimeStampCounterMultiplier(0); - - // estimate the multiplier - List estimate = new List(3); - for (int i = 0; i < 3; i++) - estimate.Add(estimateTimeStampCounterMultiplier(0.025)); - estimate.Sort(); - return estimate[1]; - } - - private double estimateTimeStampCounterMultiplier(double timeWindow) { - uint eax, edx; - - // select event "076h CPU Clocks not Halted" and enable the counter - Ring0.Wrmsr(PERF_CTL_0, - (1 << 22) | // enable performance counter - (1 << 17) | // count events in user mode - (1 << 16) | // count events in operating-system mode - 0x76, 0x00000000); - - // set the counter to 0 - Ring0.Wrmsr(PERF_CTR_0, 0, 0); - - long ticks = (long)(timeWindow * Stopwatch.Frequency); - uint lsbBegin, msbBegin, lsbEnd, msbEnd; - - long timeBegin = Stopwatch.GetTimestamp() + - (long)Math.Ceiling(0.001 * ticks); - long timeEnd = timeBegin + ticks; - while (Stopwatch.GetTimestamp() < timeBegin) { } - Ring0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin); - - while (Stopwatch.GetTimestamp() < timeEnd) { } - Ring0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd); - Ring0.Rdmsr(COFVID_STATUS, out eax, out edx); - double coreMultiplier = GetCoreMultiplier(eax); - - ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin; - ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd; - - double coreFrequency = 1e-6 * - (((double)(countEnd - countBegin)) * Stopwatch.Frequency) / - (timeEnd - timeBegin); - - double busFrequency = coreFrequency / coreMultiplier; - - return 0.25 * Math.Round(4 * TimeStampCounterFrequency / busFrequency); - } - - protected override uint[] GetMSRs() { - return new uint[] { PERF_CTL_0, PERF_CTR_0, HWCR, P_STATE_0, - COFVID_STATUS }; - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - r.Append(base.GetReport()); - - r.Append("Miscellaneous Control Address: 0x"); - r.AppendLine((miscellaneousControlAddress).ToString("X", - CultureInfo.InvariantCulture)); - r.Append("Time Stamp Counter Multiplier: "); - r.AppendLine(timeStampCounterMultiplier.ToString( - CultureInfo.InvariantCulture)); - if (family == 0x14) { - uint value = 0; - Ring0.ReadPciConfig(miscellaneousControlAddress, - CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value); - r.Append("PCI Register D18F3xD4: "); - r.AppendLine(value.ToString("X8", CultureInfo.InvariantCulture)); - } - r.AppendLine(); - - return r.ToString(); - } - - private double GetCoreMultiplier(uint cofvidEax) { - switch (family) { - case 0x10: - case 0x11: - case 0x15: - case 0x16: { - // 8:6 CpuDid: current core divisor ID - // 5:0 CpuFid: current core frequency ID - uint cpuDid = (cofvidEax >> 6) & 7; - uint cpuFid = cofvidEax & 0x1F; - return 0.5 * (cpuFid + 0x10) / (1 << (int)cpuDid); - } - case 0x12: { - // 8:4 CpuFid: current CPU core frequency ID - // 3:0 CpuDid: current CPU core divisor ID - uint cpuFid = (cofvidEax >> 4) & 0x1F; - uint cpuDid = cofvidEax & 0xF; - double divisor; - switch (cpuDid) { - case 0: divisor = 1; break; - case 1: divisor = 1.5; break; - case 2: divisor = 2; break; - case 3: divisor = 3; break; - case 4: divisor = 4; break; - case 5: divisor = 6; break; - case 6: divisor = 8; break; - case 7: divisor = 12; break; - case 8: divisor = 16; break; - default: divisor = 1; break; - } - return (cpuFid + 0x10) / divisor; - } - case 0x14: { - // 8:4: current CPU core divisor ID most significant digit - // 3:0: current CPU core divisor ID least significant digit - uint divisorIdMSD = (cofvidEax >> 4) & 0x1F; - uint divisorIdLSD = cofvidEax & 0xF; - uint value = 0; - Ring0.ReadPciConfig(miscellaneousControlAddress, - CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value); - uint frequencyId = value & 0x1F; - return (frequencyId + 0x10) / - (divisorIdMSD + (divisorIdLSD * 0.25) + 1); - } - default: - return 1; - } - } - - private string ReadFirstLine(Stream stream) { - StringBuilder sb = new StringBuilder(); - try { - stream.Seek(0, SeekOrigin.Begin); - int b = stream.ReadByte(); - while (b != -1 && b != 10) { - sb.Append((char)b); - b = stream.ReadByte(); - } - } catch { } - return sb.ToString(); - } - - public override void Update() { - base.Update(); - - if (temperatureStream == null) { - if (miscellaneousControlAddress != Ring0.InvalidPciAddress) { - uint value; - if (miscellaneousControlAddress == FAMILY_15H_MODEL_60_MISC_CONTROL_DEVICE_ID) { - Ring0.WritePciConfig(Ring0.GetPciAddress(0, 0, 0), 0xB8, F15H_M60H_REPORTED_TEMP_CTRL_OFFSET); - Ring0.ReadPciConfig(Ring0.GetPciAddress(0, 0, 0), 0xBC, out value); - } else { - Ring0.ReadPciConfig(miscellaneousControlAddress, - REPORTED_TEMPERATURE_CONTROL_REGISTER, out value); - } - if ((family == 0x15 || family == 0x16) && (value & 0x30000) == 0x3000) { - if (family == 0x15 && (model & 0xF0) == 0x00) { - coreTemperature.Value = ((value >> 21) & 0x7FC) / 8.0f + - coreTemperature.Parameters[0].Value - 49; - } else { - coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f + - coreTemperature.Parameters[0].Value - 49; - } - } else { - coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f + - coreTemperature.Parameters[0].Value; - } - ActivateSensor(coreTemperature); - } else { - DeactivateSensor(coreTemperature); - } - } else { - string s = ReadFirstLine(temperatureStream); - try { - coreTemperature.Value = 0.001f * - long.Parse(s, CultureInfo.InvariantCulture); - ActivateSensor(coreTemperature); - } catch { - DeactivateSensor(coreTemperature); - } - } - - if (HasTimeStampCounter) { - double newBusClock = 0; - float maxCoreVoltage = 0, maxNBVoltage = 0; - - for (int i = 0; i < coreClocks.Length; i++) { - Thread.Sleep(1); - - uint curEax, curEdx; - if (Ring0.RdmsrTx(COFVID_STATUS, out curEax, out curEdx, 1UL << cpuid[i][0].Thread)) { - double multiplier; - multiplier = GetCoreMultiplier(curEax); - - coreClocks[i].Value = - (float)(multiplier * TimeStampCounterFrequency / - timeStampCounterMultiplier); - newBusClock = - (float)(TimeStampCounterFrequency / timeStampCounterMultiplier); - } else { - coreClocks[i].Value = (float)TimeStampCounterFrequency; - } - - float SVI2Volt(uint vid) => vid < 0b1111_1000 ? 1.5500f - 0.00625f * vid : 0; - float SVI1Volt(uint vid) => vid < 0x7C ? 1.550f - 0.0125f * vid : 0; - float newCoreVoltage, newNBVoltage; - uint coreVid60 = (curEax >> 9) & 0x7F; - if (isSVI2) { - newCoreVoltage = SVI2Volt(curEax >> 13 & 0x80 | coreVid60); - newNBVoltage = SVI2Volt(curEax >> 24); - } else { - newCoreVoltage = SVI1Volt(coreVid60); - newNBVoltage = SVI1Volt(curEax >> 25); - } - if (newCoreVoltage > maxCoreVoltage) - maxCoreVoltage = newCoreVoltage; - if (newNBVoltage > maxNBVoltage) - maxNBVoltage = newNBVoltage; - } - coreVoltage.Value = maxCoreVoltage; - northbridgeVoltage.Value = maxNBVoltage; - - if (newBusClock > 0) { - this.busClock.Value = (float)newBusClock; - ActivateSensor(this.busClock); - } - } - - if (cStatesResidency != null) { - for (int i = 0; i < cStatesResidency.Length; i++) { - Ring0.WriteIoPort(cStatesIoPort, (byte)(cStatesIoOffset + i)); - cStatesResidency[i].Value = Ring0.ReadIoPort(cStatesIoPort + 1) / 256f * 100; - } - } - } - - public override void Close() { - if (temperatureStream != null) { - temperatureStream.Close(); - } - base.Close(); - } - } -} diff --git a/Hardware/CPU/AMD17CPU.cs b/Hardware/CPU/AMD17CPU.cs deleted file mode 100644 index 92aba6d..0000000 --- a/Hardware/CPU/AMD17CPU.cs +++ /dev/null @@ -1,488 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) 2016-2019 Sebastian Grams -// Copyright (C) 2016-2019 Aqua Computer - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.CPU -{ - internal sealed class AMD17CPU : AMDCPU - { - // counter, to create sensor index values - private int _sensorTemperatures = 0; - private int _sensorPower = 0; - private int _sensorVoltage = 0; - private int _sensorClock = 0; - private int _sensorMulti = 0; - - // register index names for CPUID[] - private const int EAX = 0; - private const int EBX = 1; - private const int ECX = 2; - private const int EDX = 3; - - #region amd zen registers - private const uint PERF_CTL_0 = 0xC0010000; - private const uint PERF_CTR_0 = 0xC0010004; - private const uint HWCR = 0xC0010015; - - private const uint MSR_PSTATE_L = 0xC0010061; - private const uint MSR_PSTATE_C = 0xC0010062; - private const uint MSR_PSTATE_S = 0xC0010063; - private const uint MSR_PSTATE_0 = 0xC0010064; - - private const uint MSR_PWR_UNIT = 0xC0010299; - private const uint MSR_CORE_ENERGY_STAT = 0xC001029A; - private const uint MSR_PKG_ENERGY_STAT = 0xC001029B; - private const uint MSR_HARDWARE_PSTATE_STATUS = 0xC0010293; - private const uint COFVID_STATUS = 0xC0010071; - private const uint FAMILY_17H_PCI_CONTROL_REGISTER = 0x60; - private const uint FAMILY_17H_MODEL_01_MISC_CONTROL_DEVICE_ID = 0x1463; - private const uint F17H_M01H_THM_TCON_CUR_TMP = 0x00059800; - private const uint F17H_M01H_SVI = 0x0005A000; - - public const uint F17H_TEMP_OFFSET_FLAG = 0x80000; - #endregion - - #region Processor - private class Processor - { - private AMD17CPU _hw = null; - private DateTime _lastPwrTime = new DateTime(0); - private uint _lastPwrValue = 0; - private Sensor _packagePower = null; - private Sensor _coreTemperatureTctl = null; - private Sensor _coreTemperatureTdie = null; - private Sensor _coreVoltage = null; - private Sensor _socVoltage = null; - public List Nodes { get; private set; } - - public Processor(Hardware hw) - { - this._hw = (AMD17CPU)hw; - Nodes = new List(); - - _packagePower = new Sensor("Package Power", this._hw._sensorPower++, SensorType.Power, this._hw, this._hw.settings); - _coreTemperatureTctl = new Sensor("Core (Tctl)", this._hw._sensorTemperatures++, SensorType.Temperature, this._hw, this._hw.settings); - _coreTemperatureTdie = new Sensor("Core (Tdie)", this._hw._sensorTemperatures++, SensorType.Temperature, this._hw, this._hw.settings); - _coreVoltage = new Sensor("Core (SVI2 TFN)", this._hw._sensorVoltage++, SensorType.Voltage, this._hw, this._hw.settings); - _socVoltage = new Sensor("SoC (SVI2 TFN)", this._hw._sensorVoltage++, SensorType.Voltage, this._hw, this._hw.settings); - - _hw.ActivateSensor(_packagePower); - _hw.ActivateSensor(_coreTemperatureTctl); - _hw.ActivateSensor(_coreTemperatureTdie); - _hw.ActivateSensor(_coreVoltage); - } - - #region UpdateSensors - public void UpdateSensors() - { - var node = Nodes[0]; - if (node == null) - return; - Core core = node.Cores[0]; - if (core == null) - return; - CPUID cpu = core.Threads[0]; - if (cpu == null) - return; - uint eax, edx; - - ulong mask = Ring0.ThreadAffinitySet(1UL << cpu.Thread); - - // MSRC001_0299 - // TU [19:16] - // ESU [12:8] -> Unit 15.3 micro Joule per increment - // PU [3:0] - Ring0.Rdmsr(MSR_PWR_UNIT, out eax, out edx); - int tu = (int)((eax >> 16) & 0xf); - int esu = (int)((eax >> 12) & 0xf); - int pu = (int)(eax & 0xf); - - // MSRC001_029B - // total_energy [31:0] - DateTime sample_time = DateTime.Now; - Ring0.Rdmsr(MSR_PKG_ENERGY_STAT, out eax, out edx); - uint total_energy = eax; - - // THM_TCON_CUR_TMP - // CUR_TEMP [31:21] - uint temperature = 0; - Ring0.WritePciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER, F17H_M01H_THM_TCON_CUR_TMP); - Ring0.ReadPciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER + 4, out temperature); - - // SVI0_TFN_PLANE0 [0] - // SVI0_TFN_PLANE1 [1] - uint smusvi0_tfn = 0; - Ring0.WritePciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER, F17H_M01H_SVI + 0x8); - Ring0.ReadPciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER + 4, out smusvi0_tfn); - - // SVI0_PLANE0_VDDCOR [24:16] - // SVI0_PLANE0_IDDCOR [7:0] - uint smusvi0_tel_plane0 = 0; - Ring0.WritePciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER, F17H_M01H_SVI + 0xc); - Ring0.ReadPciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER + 4, out smusvi0_tel_plane0); - - // SVI0_PLANE1_VDDCOR [24:16] - // SVI0_PLANE1_IDDCOR [7:0] - uint smusvi0_tel_plane1 = 0; - Ring0.WritePciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER, F17H_M01H_SVI + 0x10); - Ring0.ReadPciConfig(Ring0.GetPciAddress(0, 0, 0), FAMILY_17H_PCI_CONTROL_REGISTER + 4, out smusvi0_tel_plane1); - - Ring0.ThreadAffinitySet(mask); - - // power consumption - // power.Value = (float) ((double)pu * 0.125); - // esu = 15.3 micro Joule per increment - if (_lastPwrTime.Ticks == 0) - { - _lastPwrTime = sample_time; - _lastPwrValue = total_energy; - } - // ticks diff - TimeSpan time = sample_time - _lastPwrTime; - long pwr; - if (_lastPwrValue <= total_energy) - pwr = total_energy - _lastPwrValue; - else - pwr = (0xffffffff - _lastPwrValue) + total_energy; - - // update for next sample - _lastPwrTime = sample_time; - _lastPwrValue = total_energy; - - double energy = 15.3e-6 * pwr; - energy /= time.TotalSeconds; - - if (!double.IsNaN(energy)) - _packagePower.Value = (float)energy; - - // current temp Bit [31:21] - //If bit 19 of the Temperature Control register is set, there is an additional offset of 49 degrees C. - bool temp_offset_flag = (temperature & F17H_TEMP_OFFSET_FLAG) != 0; - temperature = (temperature >> 21) * 125; - - float offset = 0.0f; - if (string.IsNullOrWhiteSpace(cpu.Name)) - offset = 0; - else if (cpu.Name.Contains("1600X") || cpu.Name.Contains("1700X") || cpu.Name.Contains("1800X")) - offset = -20.0f; - else if (cpu.Name.Contains("1920X") || cpu.Name.Contains("1950X") || cpu.Name.Contains("1900X") || - cpu.Name.Contains("2920") || cpu.Name.Contains("2950") || cpu.Name.Contains("2970") || cpu.Name.Contains("2990")) - offset = -27.0f; - else if (cpu.Name.Contains("2600X") || cpu.Name.Contains("2700X") || cpu.Name.Contains("2800X") || - cpu.Name.Contains("1910") || cpu.Name.Contains("1920") || cpu.Name.Contains("1950")) - offset = -10.0f; - - float t = temperature * 0.001f; - if (temp_offset_flag) - t += -49.0f; - - _coreTemperatureTctl.Value = t; - _coreTemperatureTdie.Value = t + offset; - - // voltage - double VIDStep = 0.00625; - double vcc; - uint svi0_plane_x_vddcor; - uint svi0_plane_x_iddcor; - - //Core - if ((smusvi0_tfn & 0x01) == 0) - { - svi0_plane_x_vddcor = (smusvi0_tel_plane0 >> 16) & 0xff; - svi0_plane_x_iddcor = smusvi0_tel_plane0 & 0xff; - vcc = 1.550 - (double)VIDStep * svi0_plane_x_vddcor; - _coreVoltage.Value = (float)vcc; - } - - // SoC - // not every zen cpu has this voltage - if ((smusvi0_tfn & 0x02) == 0) - { - svi0_plane_x_vddcor = (smusvi0_tel_plane1 >> 16) & 0xff; - svi0_plane_x_iddcor = smusvi0_tel_plane1 & 0xff; - vcc = 1.550 - (double)VIDStep * svi0_plane_x_vddcor; - _socVoltage.Value = (float)vcc; - _hw.ActivateSensor(_socVoltage); - } - - } - #endregion - - public void AppendThread(CPUID thread, int numa_id, int core_id) - { - NumaNode node = null; - foreach (var n in Nodes) - { - if (n.NodeId == numa_id) - { - node = n; - break; - } - } - if (node == null) - { - node = new NumaNode(_hw, numa_id); - Nodes.Add(node); - } - if (thread != null) - node.AppendThread(thread, core_id); - } - } - #endregion - - #region NumaNode - private class NumaNode - { - private AMD17CPU _hw = null; - public int NodeId { get; private set; } - public List Cores { get; private set; } - - public NumaNode(Hardware hw, int id) - { - Cores = new List(); - NodeId = id; - _hw = (AMD17CPU)hw; - } - - public void AppendThread(CPUID thread, int core_id) - { - Core core = null; - foreach (var c in Cores) - { - if (c.CoreId == core_id) - core = c; - } - if (core == null) - { - core = new Core(_hw, core_id); - Cores.Add(core); - } - if (thread != null) - core.Threads.Add(thread); - } - - #region UpdateSensors - public void UpdateSensors() - { - } - #endregion - } - #endregion - - #region Core - private class Core - { - private DateTime _lastPwrTime = new DateTime(0); - private uint _lastPwrValue = 0; - private AMD17CPU _hw = null; - private Sensor _clock = null; - private Sensor _vcore = null; - private Sensor _power = null; - private Sensor _multiplier = null; - public int CoreId { get; private set; } - public List Threads { get; private set; } - - public Core(Hardware hw, int id) - { - Threads = new List(); - CoreId = id; - _hw = (AMD17CPU)hw; - _clock = new Sensor("Core #" + CoreId, _hw._sensorClock++, SensorType.Clock, _hw, _hw.settings); - _multiplier = new Sensor("Core #" + CoreId, _hw._sensorMulti++, SensorType.Factor, _hw, _hw.settings); - _power = new Sensor("Core #" + CoreId + " (SMU)", _hw._sensorPower++, SensorType.Power, _hw, _hw.settings); - _vcore = new Sensor("Core #" + CoreId + " VID", _hw._sensorVoltage++, SensorType.Voltage, _hw, _hw.settings); - - _hw.ActivateSensor(_clock); - _hw.ActivateSensor(_multiplier); - _hw.ActivateSensor(_power); - _hw.ActivateSensor(_vcore); - } - - #region UpdateSensors - public void UpdateSensors() - { - // CPUID cpu = threads.FirstOrDefault(); - CPUID cpu = Threads[0]; - if (cpu == null) - return; - uint eax, edx; - ulong mask = Ring0.ThreadAffinitySet(1UL << cpu.Thread); - - // MSRC001_0299 - // TU [19:16] - // ESU [12:8] -> Unit 15.3 micro Joule per increment - // PU [3:0] - Ring0.Rdmsr(MSR_PWR_UNIT, out eax, out edx); - int tu = (int)((eax >> 16) & 0xf); - int esu = (int)((eax >> 12) & 0xf); - int pu = (int)(eax & 0xf); - - // MSRC001_029A - // total_energy [31:0] - DateTime sample_time = DateTime.Now; - Ring0.Rdmsr(MSR_CORE_ENERGY_STAT, out eax, out edx); - uint total_energy = eax; - - // MSRC001_0293 - // CurHwPstate [24:22] - // CurCpuVid [21:14] - // CurCpuDfsId [13:8] - // CurCpuFid [7:0] - Ring0.Rdmsr(MSR_HARDWARE_PSTATE_STATUS, out eax, out edx); - int CurHwPstate = (int)((eax >> 22) & 0x3); - int CurCpuVid = (int)((eax >> 14) & 0xff); - int CurCpuDfsId = (int)((eax >> 8) & 0x3f); - int CurCpuFid = (int)(eax & 0xff); - - // MSRC001_0064 + x - // IddDiv [31:30] - // IddValue [29:22] - // CpuVid [21:14] - // CpuDfsId [13:8] - // CpuFid [7:0] - // Ring0.Rdmsr(MSR_PSTATE_0 + (uint)CurHwPstate, out eax, out edx); - // int IddDiv = (int)((eax >> 30) & 0x03); - // int IddValue = (int)((eax >> 22) & 0xff); - // int CpuVid = (int)((eax >> 14) & 0xff); - Ring0.ThreadAffinitySet(mask); - - // clock - // CoreCOF is (Core::X86::Msr::PStateDef[CpuFid[7:0]] / Core::X86::Msr::PStateDef[CpuDfsId]) * 200 - _clock.Value = (float)((double)CurCpuFid / (double)CurCpuDfsId * 200.0); - - // multiplier - _multiplier.Value = (float)((double)CurCpuFid / (double)CurCpuDfsId * 2.0); - - // Voltage - double VIDStep = 0.00625; - double vcc = 1.550 - (double)VIDStep * CurCpuVid; - _vcore.Value = (float)vcc; - - // power consumption - // power.Value = (float) ((double)pu * 0.125); - // esu = 15.3 micro Joule per increment - if (_lastPwrTime.Ticks == 0) - { - _lastPwrTime = sample_time; - _lastPwrValue = total_energy; - } - // ticks diff - TimeSpan time = sample_time - _lastPwrTime; - long pwr; - if (_lastPwrValue <= total_energy) - pwr = total_energy - _lastPwrValue; - else - pwr = (0xffffffff - _lastPwrValue) + total_energy; - - // update for next sample - _lastPwrTime = sample_time; - _lastPwrValue = total_energy; - - double energy = 15.3e-6 * pwr; - energy /= time.TotalSeconds; - - if (!double.IsNaN(energy)) - _power.Value = (float)energy; - } - #endregion - } - #endregion - - private Processor _ryzen = null; - - public AMD17CPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(processorIndex, cpuid, settings) - { - // add all numa nodes - // Register ..1E_ECX, [10:8] + 1 - _ryzen = new Processor(this); - - // add all numa nodes - - const int initialCoreId = 1_000_000_000; - - int coreId = 1; - int lastCoreId = initialCoreId; - - // Ryzen 3000's skip some core ids. - // So start at 1 and count upwards when the read core changes. - - foreach (CPUID[] cpu in cpuid.OrderBy(x => x[0].ExtData[0x1e, EBX] & 0xFF)) - { - CPUID thread = cpu[0]; - - // coreID - // Register ..1E_EBX, [7:0] - int coreIdRead = (int)(thread.ExtData[0x1e, EBX] & 0xff); - - // nodeID - // Register ..1E_ECX, [7:0] - int nodeId = (int)(thread.ExtData[0x1e, ECX] & 0xff); - - _ryzen.AppendThread(thread, nodeId, coreId); - - if (lastCoreId != initialCoreId && coreIdRead != lastCoreId) { - coreId++; - } - - lastCoreId = coreIdRead; - } - - Update(); - } - - protected override uint[] GetMSRs() - { - return new uint[] { PERF_CTL_0, PERF_CTR_0, HWCR, MSR_PSTATE_0, COFVID_STATUS }; - } - - public override string GetReport() - { - StringBuilder r = new StringBuilder(); - r.Append(base.GetReport()); - r.Append("Ryzen"); - return r.ToString(); - } - - private string ReadFirstLine(Stream stream) - { - StringBuilder sb = new StringBuilder(); - try - { - stream.Seek(0, SeekOrigin.Begin); - int b = stream.ReadByte(); - while (b != -1 && b != 10) - { - sb.Append((char)b); - b = stream.ReadByte(); - } - } - catch { } - return sb.ToString(); - } - - public override void Update() - { - base.Update(); - - _ryzen.UpdateSensors(); - foreach (NumaNode node in _ryzen.Nodes) - { - node.UpdateSensors(); - - foreach (Core c in node.Cores) - { - c.UpdateSensors(); - } - } - } - } -} diff --git a/Hardware/CPU/AMDCPU.cs b/Hardware/CPU/AMDCPU.cs deleted file mode 100644 index 99ff651..0000000 --- a/Hardware/CPU/AMDCPU.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.CPU { - - internal abstract class AMDCPU : GenericCPU { - - private const byte PCI_BUS = 0; - private const byte PCI_BASE_DEVICE = 0x18; - private const byte DEVICE_VENDOR_ID_REGISTER = 0; - private const ushort AMD_VENDOR_ID = 0x1022; - - public AMDCPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(processorIndex, cpuid, settings) { } - - protected uint GetPciAddress(byte function, ushort deviceId) { - - // assemble the pci address - uint address = Ring0.GetPciAddress(PCI_BUS, - (byte)(PCI_BASE_DEVICE + processorIndex), function); - - // verify that we have the correct bus, device and function - uint deviceVendor; - if (!Ring0.ReadPciConfig( - address, DEVICE_VENDOR_ID_REGISTER, out deviceVendor)) - return Ring0.InvalidPciAddress; - - if (deviceVendor != (deviceId << 16 | AMD_VENDOR_ID)) - return Ring0.InvalidPciAddress; - - return address; - } - - } -} diff --git a/Hardware/CPU/CPUGroup.cs b/Hardware/CPU/CPUGroup.cs deleted file mode 100644 index 7d7914e..0000000 --- a/Hardware/CPU/CPUGroup.cs +++ /dev/null @@ -1,198 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2014 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.CPU { - - internal class CPUGroup : IGroup { - private readonly List hardware = new List(); - - private readonly CPUID[][][] threads; - - private static CPUID[][] GetProcessorThreads() { - - List threads = new List(); - for (int i = 0; i < 64; i++) { - try - { - threads.Add(new CPUID(i)); - } - catch (ArgumentOutOfRangeException) - { - // All cores found. - break; - } - } - - SortedDictionary> processors = - new SortedDictionary>(); - foreach (CPUID thread in threads) { - List list; - processors.TryGetValue(thread.ProcessorId, out list); - if (list == null) { - list = new List(); - processors.Add(thread.ProcessorId, list); - } - list.Add(thread); - } - - CPUID[][] processorThreads = new CPUID[processors.Count][]; - int index = 0; - foreach (List list in processors.Values) { - processorThreads[index] = list.ToArray(); - index++; - } - return processorThreads; - } - - private static CPUID[][] GroupThreadsByCore(IEnumerable threads) { - - SortedDictionary> cores = - new SortedDictionary>(); - foreach (CPUID thread in threads) { - List coreList; - cores.TryGetValue(thread.CoreId, out coreList); - if (coreList == null) { - coreList = new List(); - cores.Add(thread.CoreId, coreList); - } - coreList.Add(thread); - } - - CPUID[][] coreThreads = new CPUID[cores.Count][]; - int index = 0; - foreach (List list in cores.Values) { - coreThreads[index] = list.ToArray(); - index++; - } - return coreThreads; - } - - public CPUGroup(ISettings settings) { - - CPUID[][] processorThreads = GetProcessorThreads(); - this.threads = new CPUID[processorThreads.Length][][]; - - int index = 0; - foreach (CPUID[] threads in processorThreads) { - if (threads.Length == 0) - continue; - - CPUID[][] coreThreads = GroupThreadsByCore(threads); - - this.threads[index] = coreThreads; - - switch (threads[0].Vendor) { - case Vendor.Intel: - hardware.Add(new IntelCPU(index, coreThreads, settings)); - break; - case Vendor.AMD: - switch (threads[0].Family) { - case 0x0F: - hardware.Add(new AMD0FCPU(index, coreThreads, settings)); - break; - case 0x10: - case 0x11: - case 0x12: - case 0x14: - case 0x15: - case 0x16: - hardware.Add(new AMD10CPU(index, coreThreads, settings)); - break; - case 0x17: - hardware.Add(new AMD17CPU(index, coreThreads, settings)); - break; - default: - hardware.Add(new GenericCPU(index, coreThreads, settings)); - break; - } break; - default: - hardware.Add(new GenericCPU(index, coreThreads, settings)); - break; - } - - index++; - } - } - - public IEnumerable Hardware => hardware; - - private static void AppendCpuidData(StringBuilder r, uint[,] data, - uint offset) - { - for (int i = 0; i < data.GetLength(0); i++) { - r.Append(" "); - r.Append((i + offset).ToString("X8", CultureInfo.InvariantCulture)); - for (int j = 0; j < 4; j++) { - r.Append(" "); - r.Append(data[i, j].ToString("X8", CultureInfo.InvariantCulture)); - } - r.AppendLine(); - } - } - - public string GetReport() { - if (threads == null) - return null; - - StringBuilder r = new StringBuilder(); - - r.AppendLine("CPUID"); - r.AppendLine(); - - for (int i = 0; i < threads.Length; i++) { - - r.AppendLine("Processor " + i); - r.AppendLine(); - r.AppendFormat("Processor Vendor: {0}{1}", threads[i][0][0].Vendor, - Environment.NewLine); - r.AppendFormat("Processor Brand: {0}{1}", threads[i][0][0].BrandString, - Environment.NewLine); - r.AppendFormat("Family: 0x{0}{1}", - threads[i][0][0].Family.ToString("X", CultureInfo.InvariantCulture), - Environment.NewLine); - r.AppendFormat("Model: 0x{0}{1}", - threads[i][0][0].Model.ToString("X", CultureInfo.InvariantCulture), - Environment.NewLine); - r.AppendFormat("Stepping: 0x{0}{1}", - threads[i][0][0].Stepping.ToString("X", CultureInfo.InvariantCulture), - Environment.NewLine); - r.AppendLine(); - - r.AppendLine("CPUID Return Values"); - r.AppendLine(); - for (int j = 0; j < threads[i].Length; j++) - for (int k = 0; k < threads[i][j].Length; k++) { - r.AppendLine(" CPU Thread: " + threads[i][j][k].Thread); - r.AppendLine(" APIC ID: " + threads[i][j][k].ApicId); - r.AppendLine(" Processor ID: " + threads[i][j][k].ProcessorId); - r.AppendLine(" Core ID: " + threads[i][j][k].CoreId); - r.AppendLine(" Thread ID: " + threads[i][j][k].ThreadId); - r.AppendLine(); - r.AppendLine(" Function EAX EBX ECX EDX"); - AppendCpuidData(r, threads[i][j][k].Data, CPUID.CPUID_0); - AppendCpuidData(r, threads[i][j][k].ExtData, CPUID.CPUID_EXT); - r.AppendLine(); - } - } - return r.ToString(); - } - - public void Close() { - foreach (GenericCPU cpu in hardware) { - cpu.Close(); - } - } - } -} diff --git a/Hardware/CPU/CPUID.cs b/Hardware/CPU/CPUID.cs deleted file mode 100644 index 6907218..0000000 --- a/Hardware/CPU/CPUID.cs +++ /dev/null @@ -1,258 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2014 Michael Möller - -*/ - -using System; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.CPU { - public enum Vendor { - Unknown, - Intel, - AMD - } - - public class CPUID { - public const uint CPUID_0 = 0; - public const uint CPUID_EXT = 0x80000000; - private readonly uint coreMaskWith; - private readonly uint threadMaskWith; - - public CPUID(int thread) { - Thread = thread; - uint maxCpuidExt; - - uint eax, ebx, ecx, edx; - - if (thread >= 64) - throw new ArgumentOutOfRangeException("thread"); - - - ulong mask = 1UL << thread; - - - uint maxCpuid; - if (Opcode.CpuidTx(CPUID_0, - 0, - out eax, - out ebx, - out ecx, - out edx, - mask)) { - if (eax > 0) - maxCpuid = eax; - else - return; - - - StringBuilder vendorBuilder = new StringBuilder(); - AppendRegister(vendorBuilder, ebx); - AppendRegister(vendorBuilder, edx); - AppendRegister(vendorBuilder, ecx); - string cpuVendor = vendorBuilder.ToString(); - switch (cpuVendor) { - case "GenuineIntel": - Vendor = Vendor.Intel; - break; - case "AuthenticAMD": - Vendor = Vendor.AMD; - break; - default: - Vendor = Vendor.Unknown; - break; - } - - eax = ebx = ecx = edx = 0; - if (Opcode.CpuidTx(CPUID_EXT, - 0, - out eax, - out ebx, - out ecx, - out edx, - mask)) { - if (eax > CPUID_EXT) - maxCpuidExt = eax - CPUID_EXT; - else - return; - } else { - throw new ArgumentOutOfRangeException("thread"); - } - } else { - throw new ArgumentOutOfRangeException("thread"); - } - - maxCpuid = Math.Min(maxCpuid, 1024); - maxCpuidExt = Math.Min(maxCpuidExt, 1024); - - Data = new uint[maxCpuid + 1, 4]; - for (uint i = 0; i < (maxCpuid + 1); i++) - Opcode.CpuidTx(CPUID_0 + i, - 0, - out Data[i, 0], - out Data[i, 1], - out Data[i, 2], - out Data[i, 3], - mask); - - ExtData = new uint[maxCpuidExt + 1, 4]; - for (uint i = 0; i < (maxCpuidExt + 1); i++) - Opcode.CpuidTx(CPUID_EXT + i, - 0, - out ExtData[i, 0], - out ExtData[i, 1], - out ExtData[i, 2], - out ExtData[i, 3], - mask); - - StringBuilder nameBuilder = new StringBuilder(); - for (uint i = 2; i <= 4; i++) { - if (Opcode.CpuidTx(CPUID_EXT + i, - 0, - out eax, - out ebx, - out ecx, - out edx, - mask)) { - AppendRegister(nameBuilder, eax); - AppendRegister(nameBuilder, ebx); - AppendRegister(nameBuilder, ecx); - AppendRegister(nameBuilder, edx); - } - } - - nameBuilder.Replace('\0', ' '); - BrandString = nameBuilder.ToString().Trim(); - nameBuilder.Replace("(R)", " "); - nameBuilder.Replace("(TM)", " "); - nameBuilder.Replace("(tm)", ""); - nameBuilder.Replace("CPU", ""); - nameBuilder.Replace("Quad-Core Processor", ""); - nameBuilder.Replace("Six-Core Processor", ""); - nameBuilder.Replace("Eight-Core Processor", ""); - for (int i = 0; i < 10; i++) nameBuilder.Replace(" ", " "); - Name = nameBuilder.ToString(); - if (Name.Contains("@")) - Name = Name.Remove(Name.LastIndexOf('@')); - - Name = Name.Trim(); - - Family = ((Data[1, 0] & 0x0FF00000) >> 20) + - ((Data[1, 0] & 0x0F00) >> 8); - - Model = ((Data[1, 0] & 0x0F0000) >> 12) + - ((Data[1, 0] & 0xF0) >> 4); - - Stepping = (Data[1, 0] & 0x0F); - - ApicId = (Data[1, 1] >> 24) & 0xFF; - - switch (Vendor) { - case Vendor.Intel: - uint maxCoreAndThreadIdPerPackage = (Data[1, 1] >> 16) & 0xFF; - uint maxCoreIdPerPackage; - if (maxCpuid >= 4) - maxCoreIdPerPackage = ((Data[4, 0] >> 26) & 0x3F) + 1; - else - maxCoreIdPerPackage = 1; - - threadMaskWith = - NextLog2(maxCoreAndThreadIdPerPackage / maxCoreIdPerPackage); - - coreMaskWith = NextLog2(maxCoreIdPerPackage); - break; - case Vendor.AMD: - uint corePerPackage; - if (maxCpuidExt >= 8) - corePerPackage = (ExtData[8, 2] & 0xFF) + 1; - else - corePerPackage = 1; - - threadMaskWith = 0; - coreMaskWith = NextLog2(corePerPackage); - - if (Family == 0x17) { - // ApicIdCoreIdSize: APIC ID size. - // cores per DIE - // we need this for Ryzen 5 (4 cores, 8 threads) ans Ryzen 6 (6 cores, 12 threads) - // Ryzen 5: [core0][core1][dummy][dummy][core2][core3] (Core0 EBX = 00080800, Core2 EBX = 08080800) - uint max_cores_per_die = (ExtData[8, 2] >> 12) & 0xF; - switch (max_cores_per_die) { - case 0x04: // Ryzen - coreMaskWith = NextLog2(16); - break; - case 0x05: // Threadripper - coreMaskWith = NextLog2(32); - break; - case 0x06: // Epic - coreMaskWith = NextLog2(64); - break; - } - } - - break; - default: - threadMaskWith = 0; - coreMaskWith = 0; - break; - } - - ProcessorId = (ApicId >> (int) (coreMaskWith + threadMaskWith)); - CoreId = ((ApicId >> (int) (threadMaskWith)) - (ProcessorId << (int) (coreMaskWith))); - ThreadId = ApicId - (ProcessorId << (int) (coreMaskWith + threadMaskWith)) - (CoreId << (int) (threadMaskWith)); - } - - public uint ApicId { get; } - - public string BrandString { get; } = ""; - - public uint CoreId { get; } - - public uint[,] Data { get; } = new uint[0, 0]; - - public uint[,] ExtData { get; } = new uint[0, 0]; - - public uint Family { get; } - - public uint Model { get; } - - public string Name { get; } = ""; - - public uint ProcessorId { get; } - - public uint Stepping { get; } - - public int Thread { get; } - - public uint ThreadId { get; } - - public Vendor Vendor { get; } = Vendor.Unknown; - - private static void AppendRegister(StringBuilder b, uint value) { - b.Append((char) ((value) & 0xff)); - b.Append((char) ((value >> 8) & 0xff)); - b.Append((char) ((value >> 16) & 0xff)); - b.Append((char) ((value >> 24) & 0xff)); - } - - private static uint NextLog2(long x) { - if (x <= 0) - return 0; - - - x--; - uint count = 0; - while (x > 0) { - x >>= 1; - count++; - } - - return count; - } - } -} \ No newline at end of file diff --git a/Hardware/CPU/CPULoad.cs b/Hardware/CPU/CPULoad.cs deleted file mode 100644 index fc3eb36..0000000 --- a/Hardware/CPU/CPULoad.cs +++ /dev/null @@ -1,155 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware.CPU { - internal class CPULoad { - - [StructLayout(LayoutKind.Sequential)] - protected struct SystemProcessorPerformanceInformation { - public long IdleTime; - public long KernelTime; - public long UserTime; - public long Reserved0; - public long Reserved1; - public ulong Reserved2; - } - - protected enum SystemInformationClass { - SystemBasicInformation = 0, - SystemCpuInformation = 1, - SystemPerformanceInformation = 2, - SystemTimeOfDayInformation = 3, - SystemProcessInformation = 5, - SystemProcessorPerformanceInformation = 8 - } - - private readonly CPUID[][] cpuid; - - private long[] idleTimes; - private long[] totalTimes; - - private float totalLoad; - private readonly float[] coreLoads; - - private readonly bool available; - - private static bool GetTimes(out long[] idle, out long[] total) { - SystemProcessorPerformanceInformation[] informations = new - SystemProcessorPerformanceInformation[64]; - - int size = Marshal.SizeOf(typeof(SystemProcessorPerformanceInformation)); - - idle = null; - total = null; - - IntPtr returnLength; - if (NativeMethods.NtQuerySystemInformation( - SystemInformationClass.SystemProcessorPerformanceInformation, - informations, informations.Length * size, out returnLength) != 0) - return false; - - idle = new long[(int)returnLength / size]; - total = new long[(int)returnLength / size]; - - for (int i = 0; i < idle.Length; i++) { - idle[i] = informations[i].IdleTime; - total[i] = informations[i].KernelTime + informations[i].UserTime; - } - - return true; - } - - public CPULoad(CPUID[][] cpuid) { - this.cpuid = cpuid; - this.coreLoads = new float[cpuid.Length]; - this.totalLoad = 0; - try { - GetTimes(out idleTimes, out totalTimes); - } catch (Exception) { - this.idleTimes = null; - this.totalTimes = null; - } - if (idleTimes != null) - available = true; - } - - public bool IsAvailable { - get { return available; } - } - - public float GetTotalLoad() { - return totalLoad; - } - - public float GetCoreLoad(int core) { - return coreLoads[core]; - } - - public void Update() { - if (this.idleTimes == null) - return; - - long[] newIdleTimes; - long[] newTotalTimes; - - if (!GetTimes(out newIdleTimes, out newTotalTimes)) - return; - - for (int i = 0; i < Math.Min(newTotalTimes.Length, totalTimes.Length); i++) - if (newTotalTimes[i] - this.totalTimes[i] < 100000) - return; - - if (newIdleTimes == null || newTotalTimes == null) - return; - - float total = 0; - int count = 0; - for (int i = 0; i < cpuid.Length; i++) { - float value = 0; - for (int j = 0; j < cpuid[i].Length; j++) { - long index = cpuid[i][j].Thread; - if (index < newIdleTimes.Length && index < totalTimes.Length) { - float idle = - (float)(newIdleTimes[index] - this.idleTimes[index]) / - (float)(newTotalTimes[index] - this.totalTimes[index]); - value += idle; - total += idle; - count++; - } - } - value = 1.0f - value / cpuid[i].Length; - value = value < 0 ? 0 : value; - coreLoads[i] = value * 100; - } - if (count > 0) { - total = 1.0f - total / count; - total = total < 0 ? 0 : total; - } else { - total = 0; - } - this.totalLoad = total * 100; - - this.totalTimes = newTotalTimes; - this.idleTimes = newIdleTimes; - } - - protected static class NativeMethods { - - [DllImport("ntdll.dll")] - public static extern int NtQuerySystemInformation( - SystemInformationClass informationClass, - [Out] SystemProcessorPerformanceInformation[] informations, - int structSize, out IntPtr returnLength); - } - } -} diff --git a/Hardware/CPU/GenericCPU.cs b/Hardware/CPU/GenericCPU.cs deleted file mode 100644 index fc63e62..0000000 --- a/Hardware/CPU/GenericCPU.cs +++ /dev/null @@ -1,299 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2011 Michael Möller - -*/ - -using System; -using System.Diagnostics; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.CPU { - public class GenericCPU : Hardware { - - protected readonly CPUID[][] cpuid; - - protected readonly uint family; - protected readonly uint model; - protected readonly uint stepping; - - protected readonly int processorIndex; - protected readonly int coreCount; - - private readonly bool isInvariantTimeStampCounter; - private readonly double estimatedTimeStampCounterFrequency; - private readonly double estimatedTimeStampCounterFrequencyError; - - private ulong lastTimeStampCount; - private long lastTime; - - private readonly Vendor vendor; - - private readonly CPULoad cpuLoad; - private readonly Sensor totalLoad; - private readonly Sensor[] coreLoads; - - /// - /// Gets the CPUID. - /// - public CPUID[][] CPUID => cpuid; - - protected string CoreString(int i) { - if (coreCount == 1) - return "CPU Core"; - else - return "CPU Core #" + (i + 1); - } - - public GenericCPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(cpuid[0][0].Name, CreateIdentifier(cpuid[0][0].Vendor, - processorIndex), settings) - { - this.cpuid = cpuid; - - vendor = cpuid[0][0].Vendor; - - family = cpuid[0][0].Family; - model = cpuid[0][0].Model; - stepping = cpuid[0][0].Stepping; - - this.processorIndex = processorIndex; - coreCount = cpuid.Length; - - // check if processor has MSRs - if (cpuid[0][0].Data.GetLength(0) > 1 - && (cpuid[0][0].Data[1, 3] & 0x20) != 0) - HasModelSpecificRegisters = true; - else - HasModelSpecificRegisters = false; - - // check if processor has a TSC - if (cpuid[0][0].Data.GetLength(0) > 1 - && (cpuid[0][0].Data[1, 3] & 0x10) != 0) - HasTimeStampCounter = true; - else - HasTimeStampCounter = false; - - // check if processor supports an invariant TSC - if (cpuid[0][0].ExtData.GetLength(0) > 7 - && (cpuid[0][0].ExtData[7, 3] & 0x100) != 0) - isInvariantTimeStampCounter = true; - else - isInvariantTimeStampCounter = false; - - if (coreCount > 1) - totalLoad = new Sensor("CPU Total", 0, SensorType.Load, this, settings); - else - totalLoad = null; - coreLoads = new Sensor[coreCount]; - for (int i = 0; i < coreLoads.Length; i++) - coreLoads[i] = new Sensor(CoreString(i), i + 1, - SensorType.Load, this, settings); - cpuLoad = new CPULoad(cpuid); - if (cpuLoad.IsAvailable) { - foreach (Sensor sensor in coreLoads) - ActivateSensor(sensor); - if (totalLoad != null) - ActivateSensor(totalLoad); - } - - if (HasTimeStampCounter) { - ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread); - - EstimateTimeStampCounterFrequency( - out estimatedTimeStampCounterFrequency, - out estimatedTimeStampCounterFrequencyError); - - ThreadAffinity.Set(mask); - } else { - estimatedTimeStampCounterFrequency = 0; - } - - TimeStampCounterFrequency = estimatedTimeStampCounterFrequency; - } - - private static Identifier CreateIdentifier(Vendor vendor, - int processorIndex) - { - string s; - switch (vendor) { - case Vendor.AMD: s = "amdcpu"; break; - case Vendor.Intel: s = "intelcpu"; break; - default: s = "genericcpu"; break; - } - return new Identifier(s, - processorIndex.ToString(CultureInfo.InvariantCulture)); - } - - private void EstimateTimeStampCounterFrequency(out double frequency, - out double error) - { - double f, e; - - // preload the function - EstimateTimeStampCounterFrequency(0, out f, out e); - EstimateTimeStampCounterFrequency(0, out f, out e); - - // estimate the frequency - error = double.MaxValue; - frequency = 0; - for (int i = 0; i < 5; i++) { - EstimateTimeStampCounterFrequency(0.025, out f, out e); - if (e < error) { - error = e; - frequency = f; - } - - if (error < 1e-4) - break; - } - } - - private void EstimateTimeStampCounterFrequency(double timeWindow, - out double frequency, out double error) - { - long ticks = (long)(timeWindow * Stopwatch.Frequency); - ulong countBegin, countEnd; - - long timeBegin = Stopwatch.GetTimestamp() + - (long)Math.Ceiling(0.001 * ticks); - long timeEnd = timeBegin + ticks; - - while (Stopwatch.GetTimestamp() < timeBegin) { } - countBegin = Opcode.Rdtsc(); - long afterBegin = Stopwatch.GetTimestamp(); - - while (Stopwatch.GetTimestamp() < timeEnd) { } - countEnd = Opcode.Rdtsc(); - long afterEnd = Stopwatch.GetTimestamp(); - - double delta = (timeEnd - timeBegin); - frequency = 1e-6 * - (((double)(countEnd - countBegin)) * Stopwatch.Frequency) / delta; - - double beginError = (afterBegin - timeBegin) / delta; - double endError = (afterEnd - timeEnd) / delta; - error = beginError + endError; - } - - - private static void AppendMSRData(StringBuilder r, uint msr, int thread) { - uint eax, edx; - if (Ring0.RdmsrTx(msr, out eax, out edx, 1UL << thread)) { - r.Append(" "); - r.Append((msr).ToString("X8", CultureInfo.InvariantCulture)); - r.Append(" "); - r.Append((edx).ToString("X8", CultureInfo.InvariantCulture)); - r.Append(" "); - r.Append((eax).ToString("X8", CultureInfo.InvariantCulture)); - r.AppendLine(); - } - } - - protected virtual uint[] GetMSRs() { - return null; - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - - switch (vendor) { - case Vendor.AMD: r.AppendLine("AMD CPU"); break; - case Vendor.Intel: r.AppendLine("Intel CPU"); break; - default: r.AppendLine("Generic CPU"); break; - } - - r.AppendLine(); - r.AppendFormat("Name: {0}{1}", name, Environment.NewLine); - r.AppendFormat("Number of Cores: {0}{1}", coreCount, - Environment.NewLine); - r.AppendFormat("Threads per Core: {0}{1}", cpuid[0].Length, - Environment.NewLine); - r.AppendLine(string.Format(CultureInfo.InvariantCulture, - "Timer Frequency: {0} MHz", Stopwatch.Frequency * 1e-6)); - r.AppendLine("Time Stamp Counter: " + (HasTimeStampCounter ? ( - isInvariantTimeStampCounter ? "Invariant" : "Not Invariant") : "None")); - r.AppendLine(string.Format(CultureInfo.InvariantCulture, - "Estimated Time Stamp Counter Frequency: {0} MHz", - Math.Round(estimatedTimeStampCounterFrequency * 100) * 0.01)); - r.AppendLine(string.Format(CultureInfo.InvariantCulture, - "Estimated Time Stamp Counter Frequency Error: {0} Mhz", - Math.Round(estimatedTimeStampCounterFrequency * - estimatedTimeStampCounterFrequencyError * 1e5) * 1e-5)); - r.AppendLine(string.Format(CultureInfo.InvariantCulture, - "Time Stamp Counter Frequency: {0} MHz", - Math.Round(TimeStampCounterFrequency * 100) * 0.01)); - r.AppendLine(); - - uint[] msrArray = GetMSRs(); - if (msrArray != null && msrArray.Length > 0) { - for (int i = 0; i < cpuid.Length; i++) { - r.AppendLine("MSR Core #" + (i + 1)); - r.AppendLine(); - r.AppendLine(" MSR EDX EAX"); - foreach (uint msr in msrArray) - AppendMSRData(r, msr, cpuid[i][0].Thread); - r.AppendLine(); - } - } - - return r.ToString(); - } - - public override HardwareType HardwareType => HardwareType.CPU; - - public bool HasModelSpecificRegisters { get; } - - public bool HasTimeStampCounter { get; } - - public double TimeStampCounterFrequency { get; private set; } - - public override void Update() { - if (HasTimeStampCounter && isInvariantTimeStampCounter) { - - // make sure always the same thread is used - ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread); - - // read time before and after getting the TSC to estimate the error - long firstTime = Stopwatch.GetTimestamp(); - ulong timeStampCount = Opcode.Rdtsc(); - long time = Stopwatch.GetTimestamp(); - - // restore the thread affinity mask - ThreadAffinity.Set(mask); - - double delta = ((double)(time - lastTime)) / Stopwatch.Frequency; - double error = ((double)(time - firstTime)) / Stopwatch.Frequency; - - // only use data if they are measured accuarte enough (max 0.1ms delay) - if (error < 0.0001) { - - // ignore the first reading because there are no initial values - // ignore readings with too large or too small time window - if (lastTime != 0 && delta > 0.5 && delta < 2) { - - // update the TSC frequency with the new value - TimeStampCounterFrequency = - (timeStampCount - lastTimeStampCount) / (1e6 * delta); - } - - lastTimeStampCount = timeStampCount; - lastTime = time; - } - } - - if (cpuLoad.IsAvailable) { - cpuLoad.Update(); - for (int i = 0; i < coreLoads.Length; i++) - coreLoads[i].Value = cpuLoad.GetCoreLoad(i); - if (totalLoad != null) - totalLoad.Value = cpuLoad.GetTotalLoad(); - } - } - } -} diff --git a/Hardware/CPU/IntelCPU.cs b/Hardware/CPU/IntelCPU.cs deleted file mode 100644 index 438010c..0000000 --- a/Hardware/CPU/IntelCPU.cs +++ /dev/null @@ -1,530 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2017 Michael Möller - -*/ - -using System; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.CPU { - internal sealed class IntelCPU : GenericCPU { - - private enum Microarchitecture { - Unknown, - NetBurst, - Core, - Atom, - Nehalem, - SandyBridge, - IvyBridge, - Haswell, - Broadwell, - Silvermont, - Skylake, - Airmont, - KabyLake, - ApolloLake, - CoffeeLake - } - - private readonly Sensor[] coreTemperatures; - private readonly Sensor packageTemperature; - private readonly Sensor[] coreClocks; - private readonly Sensor busClock; - private readonly Sensor[] powerSensors; - private readonly Sensor[] distToTjMaxTemperatures; - private readonly Sensor coreMax; - private readonly Sensor coreAvg; - - private readonly Microarchitecture microarchitecture; - private readonly double timeStampCounterMultiplier; - - private const uint IA32_THERM_STATUS_MSR = 0x019C; - private const uint IA32_TEMPERATURE_TARGET = 0x01A2; - private const uint IA32_PERF_STATUS = 0x0198; - private const uint MSR_PLATFORM_INFO = 0xCE; - private const uint IA32_PACKAGE_THERM_STATUS = 0x1B1; - private const uint MSR_RAPL_POWER_UNIT = 0x606; - private const uint MSR_PKG_ENERY_STATUS = 0x611; - private const uint MSR_DRAM_ENERGY_STATUS = 0x619; - private const uint MSR_PP0_ENERY_STATUS = 0x639; - private const uint MSR_PP1_ENERY_STATUS = 0x641; - - private readonly uint[] energyStatusMSRs = { MSR_PKG_ENERY_STATUS, - MSR_PP0_ENERY_STATUS, MSR_PP1_ENERY_STATUS, MSR_DRAM_ENERGY_STATUS }; - private readonly string[] powerSensorLabels = - { "CPU Package", "CPU Cores", "CPU Graphics", "CPU DRAM" }; - private float energyUnitMultiplier = 0; - private DateTime[] lastEnergyTime; - private uint[] lastEnergyConsumed; - - - private float[] Floats(float f) { - float[] result = new float[coreCount]; - for (int i = 0; i < coreCount; i++) - result[i] = f; - return result; - } - - private float[] GetTjMaxFromMSR() { - uint eax, edx; - float[] result = new float[coreCount]; - for (int i = 0; i < coreCount; i++) { - if (Ring0.RdmsrTx(IA32_TEMPERATURE_TARGET, out eax, - out edx, 1UL << cpuid[i][0].Thread)) { - result[i] = (eax >> 16) & 0xFF; - } else { - result[i] = 100; - } - } - return result; - } - - public IntelCPU(int processorIndex, CPUID[][] cpuid, ISettings settings) - : base(processorIndex, cpuid, settings) { - // set tjMax - float[] tjMax; - switch (family) { - case 0x06: { - switch (model) { - case 0x0F: // Intel Core 2 (65nm) - microarchitecture = Microarchitecture.Core; - switch (stepping) { - case 0x06: // B2 - switch (coreCount) { - case 2: - tjMax = Floats(80 + 10); break; - case 4: - tjMax = Floats(90 + 10); break; - default: - tjMax = Floats(85 + 10); break; - } - break; - case 0x0B: // G0 - tjMax = Floats(90 + 10); break; - case 0x0D: // M0 - tjMax = Floats(85 + 10); break; - default: - tjMax = Floats(85 + 10); break; - } break; - case 0x17: // Intel Core 2 (45nm) - microarchitecture = Microarchitecture.Core; - tjMax = Floats(100); break; - case 0x1C: // Intel Atom (45nm) - microarchitecture = Microarchitecture.Atom; - switch (stepping) { - case 0x02: // C0 - tjMax = Floats(90); break; - case 0x0A: // A0, B0 - tjMax = Floats(100); break; - default: - tjMax = Floats(90); break; - } break; - case 0x1A: // Intel Core i7 LGA1366 (45nm) - case 0x1E: // Intel Core i5, i7 LGA1156 (45nm) - case 0x1F: // Intel Core i5, i7 - case 0x25: // Intel Core i3, i5, i7 LGA1156 (32nm) - case 0x2C: // Intel Core i7 LGA1366 (32nm) 6 Core - case 0x2E: // Intel Xeon Processor 7500 series (45nm) - case 0x2F: // Intel Xeon Processor (32nm) - microarchitecture = Microarchitecture.Nehalem; - tjMax = GetTjMaxFromMSR(); - break; - case 0x2A: // Intel Core i5, i7 2xxx LGA1155 (32nm) - case 0x2D: // Next Generation Intel Xeon, i7 3xxx LGA2011 (32nm) - microarchitecture = Microarchitecture.SandyBridge; - tjMax = GetTjMaxFromMSR(); - break; - case 0x3A: // Intel Core i5, i7 3xxx LGA1155 (22nm) - case 0x3E: // Intel Core i7 4xxx LGA2011 (22nm) - microarchitecture = Microarchitecture.IvyBridge; - tjMax = GetTjMaxFromMSR(); - break; - case 0x3C: // Intel Core i5, i7 4xxx LGA1150 (22nm) - case 0x3F: // Intel Xeon E5-2600/1600 v3, Core i7-59xx - // LGA2011-v3, Haswell-E (22nm) - case 0x45: // Intel Core i5, i7 4xxxU (22nm) - case 0x46: - microarchitecture = Microarchitecture.Haswell; - tjMax = GetTjMaxFromMSR(); - break; - case 0x3D: // Intel Core M-5xxx (14nm) - case 0x47: // Intel i5, i7 5xxx, Xeon E3-1200 v4 (14nm) - case 0x4F: // Intel Xeon E5-26xx v4 - case 0x56: // Intel Xeon D-15xx - microarchitecture = Microarchitecture.Broadwell; - tjMax = GetTjMaxFromMSR(); - break; - case 0x36: // Intel Atom S1xxx, D2xxx, N2xxx (32nm) - microarchitecture = Microarchitecture.Atom; - tjMax = GetTjMaxFromMSR(); - break; - case 0x37: // Intel Atom E3xxx, Z3xxx (22nm) - case 0x4A: - case 0x4D: // Intel Atom C2xxx (22nm) - case 0x5A: - case 0x5D: - microarchitecture = Microarchitecture.Silvermont; - tjMax = GetTjMaxFromMSR(); - break; - case 0x4E: - case 0x5E: // Intel Core i5, i7 6xxxx LGA1151 (14nm) - case 0x55: // Intel Core X i7, i9 7xxx LGA2066 (14nm) - microarchitecture = Microarchitecture.Skylake; - tjMax = GetTjMaxFromMSR(); - break; - case 0x4C: - microarchitecture = Microarchitecture.Airmont; - tjMax = GetTjMaxFromMSR(); - break; - case 0x8E: - case 0x9E: // Intel Core i5, i7 7xxxx (14nm) - microarchitecture = Microarchitecture.KabyLake; - tjMax = GetTjMaxFromMSR(); - break; - case 0x5C: // Intel ApolloLake - microarchitecture = Microarchitecture.ApolloLake; - tjMax = GetTjMaxFromMSR(); - break; - case 0xAE: // Intel Core i5, i7 8xxxx (14nm++) - microarchitecture = Microarchitecture.CoffeeLake; - tjMax = GetTjMaxFromMSR(); - break; - default: - microarchitecture = Microarchitecture.Unknown; - tjMax = Floats(100); - break; - } - } break; - case 0x0F: { - switch (model) { - case 0x00: // Pentium 4 (180nm) - case 0x01: // Pentium 4 (130nm) - case 0x02: // Pentium 4 (130nm) - case 0x03: // Pentium 4, Celeron D (90nm) - case 0x04: // Pentium 4, Pentium D, Celeron D (90nm) - case 0x06: // Pentium 4, Pentium D, Celeron D (65nm) - microarchitecture = Microarchitecture.NetBurst; - tjMax = Floats(100); - break; - default: - microarchitecture = Microarchitecture.Unknown; - tjMax = Floats(100); - break; - } - } break; - default: - microarchitecture = Microarchitecture.Unknown; - tjMax = Floats(100); - break; - } - - // set timeStampCounterMultiplier - switch (microarchitecture) { - case Microarchitecture.NetBurst: - case Microarchitecture.Atom: - case Microarchitecture.Core: { - uint eax, edx; - if (Ring0.Rdmsr(IA32_PERF_STATUS, out eax, out edx)) { - timeStampCounterMultiplier = - ((edx >> 8) & 0x1f) + 0.5 * ((edx >> 14) & 1); - } - } break; - case Microarchitecture.Nehalem: - case Microarchitecture.SandyBridge: - case Microarchitecture.IvyBridge: - case Microarchitecture.Haswell: - case Microarchitecture.Broadwell: - case Microarchitecture.Silvermont: - case Microarchitecture.Skylake: - case Microarchitecture.Airmont: - case Microarchitecture.ApolloLake: - case Microarchitecture.KabyLake: - case Microarchitecture.CoffeeLake: { - uint eax, edx; - if (Ring0.Rdmsr(MSR_PLATFORM_INFO, out eax, out edx)) { - timeStampCounterMultiplier = (eax >> 8) & 0xff; - } - } break; - default: - timeStampCounterMultiplier = 0; - break; - } - - int coreSensorId = 0; - - // check if processor supports a digital thermal sensor at core level - if (cpuid[0][0].Data.GetLength(0) > 6 && (cpuid[0][0].Data[6, 0] & 1) != 0 && microarchitecture != Microarchitecture.Unknown) - { - coreTemperatures = new Sensor[coreCount]; - for (int i = 0; i < coreTemperatures.Length; i++) - { - coreTemperatures[i] = new Sensor(CoreString(i), coreSensorId, SensorType.Temperature, this, new[] { - new ParameterDescription( - "TjMax [°C]", "TjMax temperature of the core sensor.\n" + - "Temperature = TjMax - TSlope * Value.", tjMax[i]), - new ParameterDescription("TSlope [°C]", - "Temperature slope of the digital thermal sensor.\n" + - "Temperature = TjMax - TSlope * Value.", 1)}, settings); - ActivateSensor(coreTemperatures[i]); - coreSensorId++; - } - } else { - coreTemperatures = new Sensor[0]; - } - - // check if processor supports a digital thermal sensor at package level - if (cpuid[0][0].Data.GetLength(0) > 6 && (cpuid[0][0].Data[6, 0] & 0x40) != 0 && microarchitecture != Microarchitecture.Unknown) - { - packageTemperature = new Sensor("CPU Package", coreSensorId, SensorType.Temperature, this, new[] { - new ParameterDescription( - "TjMax [°C]", "TjMax temperature of the package sensor.\n" + - "Temperature = TjMax - TSlope * Value.", tjMax[0]), - new ParameterDescription("TSlope [°C]", - "Temperature slope of the digital thermal sensor.\n" + - "Temperature = TjMax - TSlope * Value.", 1)}, settings); - ActivateSensor(packageTemperature); - coreSensorId++; - } - - // dist to tjmax sensor - if (cpuid[0][0].Data.GetLength(0) > 6 && (cpuid[0][0].Data[6, 0] & 1) != 0 && microarchitecture != Microarchitecture.Unknown) - { - distToTjMaxTemperatures = new Sensor[coreCount]; - for (int i = 0; i < distToTjMaxTemperatures.Length; i++) - { - distToTjMaxTemperatures[i] = new Sensor(CoreString(i) + " Distance to TjMax", coreSensorId, SensorType.Temperature, this, settings); - ActivateSensor(distToTjMaxTemperatures[i]); - coreSensorId++; - } - } - else - { - distToTjMaxTemperatures = new Sensor[0]; - } - - //core temp avg and max value - //is only available when the cpu has more than 1 core - if (cpuid[0][0].Data.GetLength(0) > 6 && (cpuid[0][0].Data[6, 0] & 0x40) != 0 && microarchitecture != Microarchitecture.Unknown && coreCount > 1) - { - coreMax = new Sensor("Core Max", coreSensorId, SensorType.Temperature, this, settings); - ActivateSensor(coreMax); - coreSensorId++; - - coreAvg = new Sensor("Core Average", coreSensorId, SensorType.Temperature, this, settings); - ActivateSensor(coreAvg); - coreSensorId++; - } - else - { - coreMax = null; - coreAvg = null; - } - - busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings); - coreClocks = new Sensor[coreCount]; - for (int i = 0; i < coreClocks.Length; i++) - { - coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock, this, settings); - if (HasTimeStampCounter && microarchitecture != Microarchitecture.Unknown) - ActivateSensor(coreClocks[i]); - } - - if (microarchitecture == Microarchitecture.SandyBridge || - microarchitecture == Microarchitecture.IvyBridge || - microarchitecture == Microarchitecture.Haswell || - microarchitecture == Microarchitecture.Broadwell || - microarchitecture == Microarchitecture.Skylake || - microarchitecture == Microarchitecture.Silvermont || - microarchitecture == Microarchitecture.Airmont || - microarchitecture == Microarchitecture.KabyLake || - microarchitecture == Microarchitecture.ApolloLake) - { - powerSensors = new Sensor[energyStatusMSRs.Length]; - lastEnergyTime = new DateTime[energyStatusMSRs.Length]; - lastEnergyConsumed = new uint[energyStatusMSRs.Length]; - - uint eax, edx; - if (Ring0.Rdmsr(MSR_RAPL_POWER_UNIT, out eax, out edx)) - switch (microarchitecture) { - case Microarchitecture.Silvermont: - case Microarchitecture.Airmont: - energyUnitMultiplier = 1.0e-6f * (1 << (int)((eax >> 8) & 0x1F)); - break; - default: - energyUnitMultiplier = 1.0f / (1 << (int)((eax >> 8) & 0x1F)); - break; - } - if (energyUnitMultiplier != 0) { - for (int i = 0; i < energyStatusMSRs.Length; i++) { - if (!Ring0.Rdmsr(energyStatusMSRs[i], out eax, out edx)) - continue; - - lastEnergyTime[i] = DateTime.UtcNow; - lastEnergyConsumed[i] = eax; - powerSensors[i] = new Sensor(powerSensorLabels[i], i, - SensorType.Power, this, settings); - ActivateSensor(powerSensors[i]); - } - } - } - - Update(); - } - - protected override uint[] GetMSRs() { - return new[] { - MSR_PLATFORM_INFO, - IA32_PERF_STATUS , - IA32_THERM_STATUS_MSR, - IA32_TEMPERATURE_TARGET, - IA32_PACKAGE_THERM_STATUS, - MSR_RAPL_POWER_UNIT, - MSR_PKG_ENERY_STATUS, - MSR_DRAM_ENERGY_STATUS, - MSR_PP0_ENERY_STATUS, - MSR_PP1_ENERY_STATUS - }; - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - r.Append(base.GetReport()); - - r.Append("Microarchitecture: "); - r.AppendLine(microarchitecture.ToString()); - r.Append("Time Stamp Counter Multiplier: "); - r.AppendLine(timeStampCounterMultiplier.ToString( - CultureInfo.InvariantCulture)); - r.AppendLine(); - - return r.ToString(); - } - - public override void Update() { - base.Update(); - - float core_max = float.MinValue; - float core_avg = 0; - - for (int i = 0; i < coreTemperatures.Length; i++) { - uint eax, edx; - // if reading is valid - if (Ring0.RdmsrTx(IA32_THERM_STATUS_MSR, out eax, out edx, 1UL << cpuid[i][0].Thread) && (eax & 0x80000000) != 0) - { - // get the dist from tjMax from bits 22:16 - float deltaT = ((eax & 0x007F0000) >> 16); - float tjMax = coreTemperatures[i].Parameters[0].Value; - float tSlope = coreTemperatures[i].Parameters[1].Value; - coreTemperatures[i].Value = tjMax - tSlope * deltaT; - - core_avg += (float)coreTemperatures[i].Value; - if (core_max < coreTemperatures[i].Value) - core_max = (float)coreTemperatures[i].Value; - - distToTjMaxTemperatures[i].Value = deltaT; - - } else { - coreTemperatures[i].Value = null; - distToTjMaxTemperatures[i].Value = null; - } - } - - //calculate average cpu temperature over all cores - if (coreMax != null && core_max != float.MinValue) - { - coreMax.Value = core_max; - core_avg /= coreTemperatures.Length; - coreAvg.Value = core_avg; - } - - if (packageTemperature != null) { - uint eax, edx; - // if reading is valid - if (Ring0.RdmsrTx(IA32_PACKAGE_THERM_STATUS, out eax, out edx, - 1UL << cpuid[0][0].Thread) && (eax & 0x80000000) != 0) - { - // get the dist from tjMax from bits 22:16 - float deltaT = ((eax & 0x007F0000) >> 16); - float tjMax = packageTemperature.Parameters[0].Value; - float tSlope = packageTemperature.Parameters[1].Value; - packageTemperature.Value = tjMax - tSlope * deltaT; - } else { - packageTemperature.Value = null; - } - } - - if (HasTimeStampCounter && timeStampCounterMultiplier > 0) { - double newBusClock = 0; - uint eax, edx; - for (int i = 0; i < coreClocks.Length; i++) { - System.Threading.Thread.Sleep(1); - if (Ring0.RdmsrTx(IA32_PERF_STATUS, out eax, out edx, - 1UL << cpuid[i][0].Thread)) { - newBusClock = - TimeStampCounterFrequency / timeStampCounterMultiplier; - switch (microarchitecture) { - case Microarchitecture.Nehalem: { - uint multiplier = eax & 0xff; - coreClocks[i].Value = (float)(multiplier * newBusClock); - } break; - case Microarchitecture.SandyBridge: - case Microarchitecture.IvyBridge: - case Microarchitecture.Haswell: - case Microarchitecture.Broadwell: - case Microarchitecture.Silvermont: - case Microarchitecture.Skylake: - case Microarchitecture.ApolloLake: - case Microarchitecture.KabyLake: - case Microarchitecture.CoffeeLake: { - uint multiplier = (eax >> 8) & 0xff; - coreClocks[i].Value = (float)(multiplier * newBusClock); - } break; - default: { - double multiplier = - ((eax >> 8) & 0x1f) + 0.5 * ((eax >> 14) & 1); - coreClocks[i].Value = (float)(multiplier * newBusClock); - } break; - } - } else { - // if IA32_PERF_STATUS is not available, assume TSC frequency - coreClocks[i].Value = (float)TimeStampCounterFrequency; - } - } - if (newBusClock > 0) { - this.busClock.Value = (float)newBusClock; - ActivateSensor(this.busClock); - } - } - - if (powerSensors != null) { - foreach (Sensor sensor in powerSensors) { - if (sensor == null) - continue; - - uint eax, edx; - if (!Ring0.Rdmsr(energyStatusMSRs[sensor.Index], out eax, out edx)) - continue; - - DateTime time = DateTime.UtcNow; - uint energyConsumed = eax; - float deltaTime = - (float)(time - lastEnergyTime[sensor.Index]).TotalSeconds; - if (deltaTime < 0.01) - continue; - - sensor.Value = energyUnitMultiplier * unchecked( - energyConsumed - lastEnergyConsumed[sensor.Index]) / deltaTime; - lastEnergyTime[sensor.Index] = time; - lastEnergyConsumed[sensor.Index] = energyConsumed; - } - } - } - } -} diff --git a/Hardware/Computer.cs b/Hardware/Computer.cs deleted file mode 100644 index 0520a4c..0000000 --- a/Hardware/Computer.cs +++ /dev/null @@ -1,423 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Security.Permissions; -using System.Net.NetworkInformation; - -namespace OpenHardwareMonitor.Hardware { - - public class Computer : IComputer { - - private readonly List groups = new List(); - private readonly ISettings settings; - - private SMBIOS smbios; - - private bool open; - - private bool mainboardEnabled; - private bool cpuEnabled; - private bool ramEnabled; - private bool gpuEnabled; - private bool fanControllerEnabled; - private bool hddEnabled; - private bool nicEnabled; - private int nicCount; - - public Computer() { - this.settings = new Settings(); - } - - public Computer(ISettings settings) { - this.settings = settings ?? new Settings(); - } - - private void Add(IGroup group) { - if (groups.Contains(group)) - return; - - groups.Add(group); - - if (HardwareAdded != null) - foreach (IHardware hardware in group.Hardware) - HardwareAdded(hardware); - } - - private void Remove(IGroup group) { - if (!groups.Contains(group)) - return; - - groups.Remove(group); - - if (HardwareRemoved != null) - foreach (IHardware hardware in group.Hardware) - HardwareRemoved(hardware); - - group.Close(); - } - - private void RemoveType() where T : IGroup { - List list = new List(); - foreach (IGroup group in groups) - if (group is T) - list.Add(group); - foreach (IGroup group in list) - Remove(group); - } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - public void Open() { - if (open) - return; - - this.smbios = new SMBIOS(); - - Ring0.Open(); - Opcode.Open(); - - if (mainboardEnabled) - Add(new Mainboard.MainboardGroup(smbios, settings)); - - if (cpuEnabled) - Add(new CPU.CPUGroup(settings)); - - if (ramEnabled) - Add(new RAM.RAMGroup(smbios, settings)); - - if (gpuEnabled) { - Add(new ATI.ATIGroup(settings)); - Add(new Nvidia.NvidiaGroup(settings)); - } - - if (fanControllerEnabled) { - Add(new TBalancer.TBalancerGroup(settings)); - Add(new Heatmaster.HeatmasterGroup(settings)); - Add(new Aquacomputer.AquacomputerGroup(settings)); - } - - if (hddEnabled) - Add(new HDD.HarddriveGroup(settings)); - - if (nicEnabled) - { - nicCount = NetworkInterface.GetAllNetworkInterfaces().Length; - Add(new Nic.NicGroup(settings)); - } - - open = true; - } - - public bool MainboardEnabled { - get { return mainboardEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != mainboardEnabled) { - if (value) - Add(new Mainboard.MainboardGroup(smbios, settings)); - else - RemoveType(); - } - mainboardEnabled = value; - } - } - - public bool CPUEnabled { - get { return cpuEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != cpuEnabled) { - if (value) - Add(new CPU.CPUGroup(settings)); - else - RemoveType(); - } - cpuEnabled = value; - } - } - - public bool RAMEnabled { - get { return ramEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != ramEnabled) { - if (value) - Add(new RAM.RAMGroup(smbios, settings)); - else - RemoveType(); - } - ramEnabled = value; - } - } - - public bool GPUEnabled { - get { return gpuEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != gpuEnabled) { - if (value) { - Add(new ATI.ATIGroup(settings)); - Add(new Nvidia.NvidiaGroup(settings)); - } else { - RemoveType(); - RemoveType(); - } - } - gpuEnabled = value; - } - } - - public bool FanControllerEnabled { - get { return fanControllerEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != fanControllerEnabled) { - if (value) { - Add(new TBalancer.TBalancerGroup(settings)); - Add(new Heatmaster.HeatmasterGroup(settings)); - Add(new Aquacomputer.AquacomputerGroup(settings)); - } else { - RemoveType(); - RemoveType(); - RemoveType(); - } - } - fanControllerEnabled = value; - } - } - - public bool HDDEnabled { - get { return hddEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != hddEnabled) { - if (value) - Add(new HDD.HarddriveGroup(settings)); - else - RemoveType(); - } - hddEnabled = value; - } - } - - public bool NICEnabled { - get { return nicEnabled; } - - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] - set { - if (open && value != nicEnabled) { - if (value) - Add(new Nic.NicGroup(settings)); - else - RemoveType(); - } - nicEnabled = value; - } - } - - public IHardware[] Hardware { - get { - List list = new List(); - foreach (IGroup group in groups) - foreach (IHardware hardware in group.Hardware) - list.Add(hardware); - return list.ToArray(); - } - } - - private static void NewSection(TextWriter writer) { - for (int i = 0; i < 8; i++) - writer.Write("----------"); - writer.WriteLine(); - writer.WriteLine(); - } - - private static int CompareSensor(ISensor a, ISensor b) { - int c = a.SensorType.CompareTo(b.SensorType); - if (c == 0) - return a.Index.CompareTo(b.Index); - else - return c; - } - - private static void ReportHardwareSensorTree( - IHardware hardware, TextWriter w, string space) - { - w.WriteLine("{0}|", space); - w.WriteLine("{0}+- {1} ({2})", - space, hardware.Name, hardware.Identifier); - ISensor[] sensors = hardware.Sensors; - Array.Sort(sensors, CompareSensor); - foreach (ISensor sensor in sensors) { - w.WriteLine("{0}| +- {1,-14} : {2,8:G6} {3,8:G6} {4,8:G6} ({5})", - space, sensor.Name, sensor.Value, sensor.Min, sensor.Max, - sensor.Identifier); - } - foreach (IHardware subHardware in hardware.SubHardware) - ReportHardwareSensorTree(subHardware, w, "| "); - } - - private static void ReportHardwareParameterTree( - IHardware hardware, TextWriter w, string space) { - w.WriteLine("{0}|", space); - w.WriteLine("{0}+- {1} ({2})", - space, hardware.Name, hardware.Identifier); - ISensor[] sensors = hardware.Sensors; - Array.Sort(sensors, CompareSensor); - foreach (ISensor sensor in sensors) { - string innerSpace = space + "| "; - if (sensor.Parameters.Count > 0) { - w.WriteLine("{0}|", innerSpace); - w.WriteLine("{0}+- {1} ({2})", - innerSpace, sensor.Name, sensor.Identifier); - foreach (IParameter parameter in sensor.Parameters) { - string innerInnerSpace = innerSpace + "| "; - w.WriteLine("{0}+- {1} : {2}", - innerInnerSpace, parameter.Name, - string.Format(CultureInfo.InvariantCulture, "{0} : {1}", - parameter.DefaultValue, parameter.Value)); - } - } - } - foreach (IHardware subHardware in hardware.SubHardware) - ReportHardwareParameterTree(subHardware, w, "| "); - } - - private static void ReportHardware(IHardware hardware, TextWriter w) { - string hardwareReport = hardware.GetReport(); - if (!string.IsNullOrEmpty(hardwareReport)) { - NewSection(w); - w.Write(hardwareReport); - } - foreach (IHardware subHardware in hardware.SubHardware) - ReportHardware(subHardware, w); - } - - public string GetReport() { - - using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture)) { - - w.WriteLine(); - w.WriteLine("Open Hardware Monitor Report"); - w.WriteLine(); - - Version version = typeof(Computer).Assembly.GetName().Version; - - NewSection(w); - w.Write("Version: "); w.WriteLine(version.ToString()); - w.WriteLine(); - - NewSection(w); - w.Write("Common Language Runtime: "); - w.WriteLine(Environment.Version.ToString()); - w.Write("Operating System: "); - w.WriteLine(Environment.OSVersion.ToString()); - w.Write("Process Type: "); - w.WriteLine(IntPtr.Size == 4 ? "32-Bit" : "64-Bit"); - w.WriteLine(); - - string r = Ring0.GetReport(); - if (r != null) { - NewSection(w); - w.Write(r); - w.WriteLine(); - } - - NewSection(w); - w.WriteLine("Sensors"); - w.WriteLine(); - foreach (IGroup group in groups) { - foreach (IHardware hardware in group.Hardware) - ReportHardwareSensorTree(hardware, w, ""); - } - w.WriteLine(); - - NewSection(w); - w.WriteLine("Parameters"); - w.WriteLine(); - foreach (IGroup group in groups) { - foreach (IHardware hardware in group.Hardware) - ReportHardwareParameterTree(hardware, w, ""); - } - w.WriteLine(); - - foreach (IGroup group in groups) { - string report = group.GetReport(); - if (!string.IsNullOrEmpty(report)) { - NewSection(w); - w.Write(report); - } - - var hardwareArray = group.Hardware; - foreach (IHardware hardware in hardwareArray) - ReportHardware(hardware, w); - - } - return w.ToString(); - } - } - - public void Close() { - if (!open) - return; - - while (groups.Count > 0) { - IGroup group = groups[groups.Count - 1]; - Remove(group); - } - - Opcode.Close(); - Ring0.Close(); - - this.smbios = null; - - open = false; - } - - public event HardwareEventHandler HardwareAdded; - public event HardwareEventHandler HardwareRemoved; - - public void Accept(IVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("visitor"); - visitor.VisitComputer(this); - } - - public void Traverse(IVisitor visitor) { - foreach (IGroup group in groups) - foreach (IHardware hardware in group.Hardware) - hardware.Accept(visitor); - } - - private class Settings : ISettings { - - public bool Contains(string name) { - return false; - } - - public void SetValue(string name, string value) { } - - public string GetValue(string name, string value) { - return value; - } - - public void Remove(string name) { } - } - } -} \ No newline at end of file diff --git a/Hardware/Control.cs b/Hardware/Control.cs deleted file mode 100644 index b46476a..0000000 --- a/Hardware/Control.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2014 Michael Möller - -*/ - -using System.Globalization; - -namespace OpenHardwareMonitor.Hardware { - - internal delegate void ControlEventHandler(Control control); - - internal class Control : IControl { - - private readonly Identifier identifier; - private readonly ISettings settings; - private ControlMode mode; - private float softwareValue; - private float minSoftwareValue; - private float maxSoftwareValue; - - public Control(ISensor sensor, ISettings settings, float minSoftwareValue, - float maxSoftwareValue) - { - this.identifier = new Identifier(sensor.Identifier, "control"); - this.settings = settings; - this.minSoftwareValue = minSoftwareValue; - this.maxSoftwareValue = maxSoftwareValue; - - if (!float.TryParse(settings.GetValue( - new Identifier(identifier, "value").ToString(), "0"), - NumberStyles.Float, CultureInfo.InvariantCulture, - out this.softwareValue)) - { - this.softwareValue = 0; - } - int mode; - if (!int.TryParse(settings.GetValue( - new Identifier(identifier, "mode").ToString(), - ((int)ControlMode.Undefined).ToString(CultureInfo.InvariantCulture)), - NumberStyles.Integer, CultureInfo.InvariantCulture, - out mode)) - { - this.mode = ControlMode.Undefined; - } else { - this.mode = (ControlMode)mode; - } - } - - public Identifier Identifier { - get { - return identifier; - } - } - - public ControlMode ControlMode { - get { - return mode; - } - private set { - if (mode != value) { - mode = value; - if (ControlModeChanged != null) - ControlModeChanged(this); - this.settings.SetValue(new Identifier(identifier, "mode").ToString(), - ((int)mode).ToString(CultureInfo.InvariantCulture)); - } - } - } - - public float SoftwareValue { - get { - return softwareValue; - } - private set { - if (softwareValue != value) { - softwareValue = value; - if (SoftwareControlValueChanged != null) - SoftwareControlValueChanged(this); - this.settings.SetValue(new Identifier(identifier, - "value").ToString(), - value.ToString(CultureInfo.InvariantCulture)); - } - } - } - - public void SetDefault() { - ControlMode = ControlMode.Default; - } - - public float MinSoftwareValue { - get { - return minSoftwareValue; - } - } - - public float MaxSoftwareValue { - get { - return maxSoftwareValue; - } - } - - public void SetSoftware(float value) { - ControlMode = ControlMode.Software; - SoftwareValue = value; - } - - internal event ControlEventHandler ControlModeChanged; - internal event ControlEventHandler SoftwareControlValueChanged; - } -} diff --git a/Hardware/FirmwareTable.cs b/Hardware/FirmwareTable.cs deleted file mode 100644 index 79ecb49..0000000 --- a/Hardware/FirmwareTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2011 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace OpenHardwareMonitor.Hardware { - - internal static class FirmwareTable { - - public static byte[] GetTable(Provider provider, string table) { - int id = table[3] << 24 | table[2] << 16 | table[1] << 8 | table[0]; - return GetTable(provider, id); - } - - public static byte[] GetTable(Provider provider, int table) { - - int size; - try { - size = NativeMethods.GetSystemFirmwareTable(provider, table, - IntPtr.Zero, 0); - } catch (DllNotFoundException) { return null; } - catch (EntryPointNotFoundException) { return null; } - - if (size <= 0) - return null; - - IntPtr nativeBuffer = Marshal.AllocHGlobal(size); - NativeMethods.GetSystemFirmwareTable(provider, table, nativeBuffer, size); - - if (Marshal.GetLastWin32Error() != 0) - return null; - - byte[] buffer = new byte[size]; - Marshal.Copy(nativeBuffer, buffer, 0, size); - Marshal.FreeHGlobal(nativeBuffer); - - return buffer; - } - - public static string[] EnumerateTables(Provider provider) { - int size; - try { - size = NativeMethods.EnumSystemFirmwareTables( - provider, IntPtr.Zero, 0); - } catch (DllNotFoundException) { return null; } - catch (EntryPointNotFoundException) { return null; } - - IntPtr nativeBuffer = Marshal.AllocHGlobal(size); - NativeMethods.EnumSystemFirmwareTables( - provider, nativeBuffer, size); - byte[] buffer = new byte[size]; - Marshal.Copy(nativeBuffer, buffer, 0, size); - Marshal.FreeHGlobal(nativeBuffer); - - string[] result = new string[size / 4]; - for (int i = 0; i < result.Length; i++) - result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); - - return result; - } - - public enum Provider : int { - ACPI = (byte)'A' << 24 | (byte)'C' << 16 | (byte)'P' << 8 | (byte)'I', - FIRM = (byte)'F' << 24 | (byte)'I' << 16 | (byte)'R' << 8 | (byte)'M', - RSMB = (byte)'R' << 24 | (byte)'S' << 16 | (byte)'M' << 8 | (byte)'B' - } - - private static class NativeMethods { - private const string KERNEL = "kernel32.dll"; - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - public static extern int EnumSystemFirmwareTables( - Provider firmwareTableProviderSignature, - IntPtr firmwareTableBuffer, int bufferSize); - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - public static extern int GetSystemFirmwareTable( - Provider firmwareTableProviderSignature, - int firmwareTableID, IntPtr firmwareTableBuffer, int bufferSize); - } - } -} diff --git a/Hardware/HDD/ATAStorage.cs b/Hardware/HDD/ATAStorage.cs deleted file mode 100644 index 674be59..0000000 --- a/Hardware/HDD/ATAStorage.cs +++ /dev/null @@ -1,253 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public abstract class ATAStorage : AbstractStorage { - // array of all harddrive types, matching type is searched in this order - private static readonly Type[] hddTypes = { typeof(SSDPlextor), typeof(SSDIntel), typeof(SSDSandforce), typeof(SSDIndilinx), typeof(SSDSamsung), typeof(SSDMicron), typeof(GenericHarddisk) }; - - private readonly ISmart smart; - private readonly List smartAttributes; - private IDictionary sensors; - - /// - /// Gets the SMART data. - /// - public ISmart Smart => smart; - - /// - /// Gets the SMART attributes. - /// - public IReadOnlyList SmartAttributes => smartAttributes; - - internal ATAStorage(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, string id, int index, IEnumerable smartAttributes, ISettings settings) - : base(storageInfo, name, firmwareRevision, id, index, settings) { - this.smart = smart; - if (smart.IsValid) - smart.EnableSmart(); - - this.smartAttributes = new List(smartAttributes); - CreateSensors(); - } - - internal static AbstractStorage CreateInstance(StorageInfo info, ISettings settings) { - ISmart smart = new WindowsSmart(info.Index); - string name = null; - string firmwareRevision = null; - Kernel32.SMART_ATTRIBUTE[] values = { }; - - if (smart.IsValid) { - bool nameValid = smart.ReadNameAndFirmwareRevision(out name, out firmwareRevision); - bool smartEnabled = smart.EnableSmart(); - - if (smartEnabled) - values = smart.ReadSmartData(); - - if (!nameValid) { - name = null; - firmwareRevision = null; - } - } else { - string[] logicalDrives = WindowsStorage.GetLogicalDrives(info.Index); - if (logicalDrives == null || logicalDrives.Length == 0) { - smart.Close(); - return null; - } - - bool hasNonZeroSizeDrive = false; - foreach (string logicalDrive in logicalDrives) { - try { - var di = new DriveInfo(logicalDrive); - if (di.TotalSize > 0) { - hasNonZeroSizeDrive = true; - break; - } - } catch (ArgumentException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } - } - - if (!hasNonZeroSizeDrive) { - smart.Close(); - return null; - } - } - - if (string.IsNullOrEmpty(name)) - name = string.IsNullOrEmpty(info.Name) ? "Generic Hard Disk" : info.Name; - - if (string.IsNullOrEmpty(firmwareRevision)) - firmwareRevision = string.IsNullOrEmpty(info.Revision) ? "Unknown" : info.Revision; - - foreach (Type type in hddTypes) { - // get the array of name prefixes for the current type - var namePrefixes = type.GetCustomAttributes(typeof(NamePrefixAttribute), true) as NamePrefixAttribute[]; - - // get the array of the required SMART attributes for the current type - var requiredAttributes = type.GetCustomAttributes(typeof(RequireSmartAttribute), true) as RequireSmartAttribute[]; - - // check if all required attributes are present - bool allRequiredAttributesFound = true; - foreach (var requireAttribute in requiredAttributes) { - bool attributeFound = false; - foreach (Kernel32.SMART_ATTRIBUTE value in values) { - if (value.Id == requireAttribute.AttributeId) { - attributeFound = true; - break; - } - } - - if (!attributeFound) { - allRequiredAttributesFound = false; - break; - } - } - - // if an attribute is missing, then try the next type - if (!allRequiredAttributesFound) - continue; - - - // check if there is a matching name prefix for this type - foreach (NamePrefixAttribute prefix in namePrefixes) { - if (name.StartsWith(prefix.Prefix, StringComparison.InvariantCulture)) { - var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; - return Activator.CreateInstance(type, flags, null, new object[] { info, smart, name, firmwareRevision, info.Index, settings }, null) as ATAStorage; - } - } - } - - // no matching type has been found - smart.Close(); - return null; - } - - protected sealed override void CreateSensors() { - sensors = new Dictionary(); - - if (smart.IsValid) { - var smartIds = smart.ReadSmartData().Select(attrValue => attrValue.Id); - - // unique attributes by SensorType and SensorChannel. - var uniqueAttributes = smartAttributes - .Where(a => a.SensorType.HasValue && smartIds.Contains(a.Identifier)) - .GroupBy(a => new { a.SensorType.Value, a.SensorChannel }) - .Select(g => g.First()); - - sensors = uniqueAttributes.ToDictionary(attr => attr, - attr => new Sensor(attr.SensorName, - attr.SensorChannel, - attr.DefaultHiddenSensor, - attr.SensorType.Value, - this, - attr.ParameterDescriptions, - settings)); - - foreach (var sensor in sensors) { - ActivateSensor(sensor.Value); - } - } - - base.CreateSensors(); - } - - protected virtual void UpdateAdditionalSensors(Kernel32.SMART_ATTRIBUTE[] values) { } - - protected override void UpdateSensors() { - if (smart.IsValid) { - Kernel32.SMART_ATTRIBUTE[] values = smart.ReadSmartData(); - - foreach (KeyValuePair keyValuePair in sensors) { - SmartAttribute attribute = keyValuePair.Key; - foreach (Kernel32.SMART_ATTRIBUTE value in values) { - if (value.Id == attribute.Identifier) { - Sensor sensor = keyValuePair.Value; - sensor.Value = attribute.ConvertValue(value, sensor.Parameters); - } - } - } - - UpdateAdditionalSensors(values); - } - } - - protected override void GetReport(StringBuilder r) { - if (smart.IsValid) { - Kernel32.SMART_ATTRIBUTE[] values = smart.ReadSmartData(); - Kernel32.SMART_THRESHOLD[] thresholds = smart.ReadSmartThresholds(); - - if (values.Length > 0) { - r.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1}{2}{3}{4}{5}{6}{7}", - "Id".PadRight(3), - "Description".PadRight(35), - "Raw Value".PadRight(13), - "Worst".PadRight(6), - "Value".PadRight(6), - "Threshold".PadRight(6), - "Physical".PadRight(8), - Environment.NewLine); - - foreach (Kernel32.SMART_ATTRIBUTE value in values) { - if (value.Id == 0x00) - break; - - - byte? threshold = null; - foreach (Kernel32.SMART_THRESHOLD t in thresholds) { - if (t.Id == value.Id) { - threshold = t.Threshold; - } - } - - string description = "Unknown"; - float? physical = null; - foreach (SmartAttribute a in smartAttributes) { - if (a.Identifier == value.Id) { - description = a.Name; - if (a.HasRawValueConversion | a.SensorType.HasValue) - physical = a.ConvertValue(value, null); - else - physical = null; - } - } - - string raw = BitConverter.ToString(value.RawValue); - r.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1}{2}{3}{4}{5}{6}{7}", - value.Id.ToString("X2").PadRight(3), - description.PadRight(35), - raw.Replace("-", "").PadRight(13), - value.WorstValue.ToString(CultureInfo.InvariantCulture).PadRight(6), - value.CurrentValue.ToString(CultureInfo.InvariantCulture).PadRight(6), - (threshold.HasValue - ? threshold.Value.ToString(CultureInfo.InvariantCulture) - : "-").PadRight(6), - (physical.HasValue ? physical.Value.ToString(CultureInfo.InvariantCulture) : "-").PadRight(8), - Environment.NewLine); - } - - r.AppendLine(); - } - } - } - - protected static float RawToInt(byte[] raw, byte value, IReadOnlyList parameters) { - return (raw[3] << 24) | (raw[2] << 16) | (raw[1] << 8) | raw[0]; - } - - public override void Close() { - smart.Close(); - base.Close(); - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/AbstractStorage.cs b/Hardware/HDD/AbstractStorage.cs deleted file mode 100644 index c6061dc..0000000 --- a/Hardware/HDD/AbstractStorage.cs +++ /dev/null @@ -1,267 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Management; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public abstract class AbstractStorage : Hardware { - private readonly PerformanceValue perfTotal = new PerformanceValue(); - private readonly PerformanceValue perfWrite = new PerformanceValue(); - private readonly StorageInfo storageInfo; - private readonly TimeSpan updateInterval = TimeSpan.FromSeconds(60); - private bool canUpdateWmi = true; - - private double lastTime; - private DateTime lastUpdate = DateTime.MinValue; - private ulong readRateCounterlast; - private Sensor sensorDiskReadRate; - private Sensor sensorDiskTotalActivity; - private Sensor sensorDiskWriteActivity; - private Sensor sensorDiskWriteRate; - private Sensor usageSensor; - private ulong writeRateCounterlast; - - internal AbstractStorage(StorageInfo storageInfo, string name, string firmwareRevision, string id, int index, ISettings settings) - : base(name, new Identifier(id, index.ToString(CultureInfo.InvariantCulture)), settings) { - this.storageInfo = storageInfo; - FirmwareRevision = firmwareRevision; - Index = index; - - string[] logicalDrives = WindowsStorage.GetLogicalDrives(index); - var driveInfoList = new List(logicalDrives.Length); - foreach (string logicalDrive in logicalDrives) { - try { - var di = new DriveInfo(logicalDrive); - if (di.TotalSize > 0) - driveInfoList.Add(new DriveInfo(logicalDrive)); - } catch (ArgumentException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } - } - - DriveInfos = driveInfoList.ToArray(); - } - - public DriveInfo[] DriveInfos { get; } - - public string FirmwareRevision { get; } - - public override HardwareType HardwareType => HardwareType.HDD; - - public int Index { get; } - - public static AbstractStorage CreateInstance(string deviceId, uint driveNumber, ulong diskSize, int scsiPort, ISettings settings) { - StorageInfo info = WindowsStorage.GetStorageInfo(deviceId, driveNumber); - info.DiskSize = diskSize; - info.DeviceId = deviceId; - info.Scsi = $@"\\.\SCSI{scsiPort}:"; - - if (info.Removable || info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeVirtual || info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeFileBackedVirtual) - return null; - - - //fallback, when it is not possible to read out with the nvme implementation, - //try it with the sata smart implementation - if (info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeNvme) { - var x = NVMeGeneric.CreateInstance(info, settings); - if (x != null) - return x; - } - - if (info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeAta || - info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeSata || - info.BusType == Kernel32.STORAGE_BUS_TYPE.BusTypeNvme) { - return ATAStorage.CreateInstance(info, settings); - } - - return StorageGeneric.CreateInstance(info, settings); - } - - protected virtual void CreateSensors() { - if (DriveInfos.Length > 0) { - usageSensor = new Sensor("Used Space", 0, SensorType.Load, this, settings); - ActivateSensor(usageSensor); - } - - sensorDiskWriteActivity = new Sensor("Write Activity", 32, SensorType.Load, this, settings); - ActivateSensor(sensorDiskWriteActivity); - - sensorDiskTotalActivity = new Sensor("Total Activity", 33, SensorType.Load, this, settings); - ActivateSensor(sensorDiskTotalActivity); - - sensorDiskReadRate = new Sensor("Read Rate", 34, SensorType.Throughput, this, settings); - ActivateSensor(sensorDiskReadRate); - - sensorDiskWriteRate = new Sensor("Write Rate", 35, SensorType.Throughput, this, settings); - ActivateSensor(sensorDiskWriteRate); - } - - protected abstract void UpdateSensors(); - - private void UpdateStatisticsFromWmi(int driveIndex) { - string query = $"SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk Where Name LIKE \"{driveIndex}%\""; - - var perfData = new ManagementObjectSearcher(query); - var data = perfData.Get().OfType().FirstOrDefault(); - - if (data == null) { - perfData.Dispose(); - return; - } - - var value = (ulong) data.Properties["PercentDiskWriteTime"].Value; - var valueBase = (ulong) data.Properties["PercentDiskWriteTime_Base"].Value; - perfWrite.Update(value, valueBase); - sensorDiskWriteActivity.Value = (float) (perfWrite.Result); - - value = (ulong) data.Properties["PercentIdleTime"].Value; - valueBase = (ulong) data.Properties["PercentIdleTime_Base"].Value; - perfTotal.Update(value, valueBase); - sensorDiskTotalActivity.Value = (float) (100.0 - perfTotal.Result); - - ulong readRateCounter = (ulong) data.Properties["DiskReadBytesPerSec"].Value; - ulong readRate = readRateCounter - readRateCounterlast; - readRateCounterlast = readRateCounter; - - ulong writeRateCounter = (ulong) data.Properties["DiskWriteBytesPerSec"].Value; - ulong writeRate = writeRateCounter - writeRateCounterlast; - writeRateCounterlast = writeRateCounter; - - ulong timestampPerfTime = (ulong) data.Properties["Timestamp_PerfTime"].Value; - ulong frequencyPerfTime = (ulong) data.Properties["Frequency_Perftime"].Value; - double currentTime = (double) timestampPerfTime / frequencyPerfTime; - - double timeDeltaSeconds = currentTime - lastTime; - if (lastTime == 0 || timeDeltaSeconds > 0.2) { - double writeSpeed = writeRate; - writeSpeed *= (1 / timeDeltaSeconds); - sensorDiskWriteRate.Value = (float) writeSpeed; - - double readSpeed = readRate; - readSpeed *= (1 / timeDeltaSeconds); - sensorDiskReadRate.Value = (float) readSpeed; - } - - if (lastTime == 0 || timeDeltaSeconds > 0.2) { - lastTime = currentTime; - } - - perfData.Dispose(); - } - - public override void Update() { - //update statistics from WMI on every update - if (storageInfo != null && canUpdateWmi) { - try { - UpdateStatisticsFromWmi(storageInfo.Index); - } catch (ManagementException managementException) { - // Invalid query. - if (managementException.HResult == -2146233087) { - DeactivateSensor(sensorDiskTotalActivity); - DeactivateSensor(sensorDiskWriteActivity); - DeactivateSensor(sensorDiskReadRate); - DeactivateSensor(sensorDiskWriteRate); - - canUpdateWmi = false; - } - } catch { } - } - - //read out with updateInterval - var tDiff = DateTime.UtcNow - lastUpdate; - if (tDiff > updateInterval) { - lastUpdate = DateTime.UtcNow; - - UpdateSensors(); - - if (usageSensor != null) { - long totalSize = 0; - long totalFreeSpace = 0; - - for (int i = 0; i < DriveInfos.Length; i++) { - if (!DriveInfos[i].IsReady) - continue; - - - try { - totalSize += DriveInfos[i].TotalSize; - totalFreeSpace += DriveInfos[i].TotalFreeSpace; - } catch (IOException) { } catch (UnauthorizedAccessException) { } - } - - if (totalSize > 0) { - usageSensor.Value = 100.0f - (100.0f * totalFreeSpace) / totalSize; - } else { - usageSensor.Value = null; - } - } - } - } - - protected abstract void GetReport(StringBuilder r); - - public override string GetReport() { - var r = new StringBuilder(); - r.AppendLine("Storage"); - r.AppendLine(); - r.AppendLine("Drive Name: " + name); - r.AppendLine("Firmware Version: " + FirmwareRevision); - r.AppendLine(); - GetReport(r); - - foreach (DriveInfo di in DriveInfos) { - if (!di.IsReady) - continue; - - - try { - r.AppendLine("Logical Drive Name: " + di.Name); - r.AppendLine("Format: " + di.DriveFormat); - r.AppendLine("Total Size: " + di.TotalSize); - r.AppendLine("Total Free Space: " + di.TotalFreeSpace); - r.AppendLine(); - } catch (IOException) { } catch (UnauthorizedAccessException) { } - } - - return r.ToString(); - } - - public override void Traverse(IVisitor visitor) { - foreach (ISensor sensor in Sensors) - sensor.Accept(visitor); - } - - /// - /// Helper to calculate the disk performance with base timestamps - /// https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-perfrawdata - /// - private class PerformanceValue { - public double Result { get; private set; } - - private ulong Time { get; set; } - - private ulong Value { get; set; } - - public void Update(ulong val, ulong valBase) { - ulong diffValue = val - Value; - ulong diffTime = valBase - Time; - - Value = val; - Time = valBase; - Result = 100.0 / diffTime * diffValue; - - //sometimes it is possible that diff_value > diff_timebase - //limit result to 100%, this is because timing issues during read from pcie controller an latency between IO operation - if (Result > 100) - Result = 100; - } - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/DebugSmart.cs b/Hardware/HDD/DebugSmart.cs deleted file mode 100644 index 22e0abe..0000000 --- a/Hardware/HDD/DebugSmart.cs +++ /dev/null @@ -1,449 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Collections.Generic; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { -#if DEBUG - - internal class DebugSmart : ISmart { - private readonly Drive[] drives = { - new Drive("KINGSTON SNV425S264GB", - null, - 16, - @" 01 000000000000 100 100 - 02 000000000000 100 100 - 03 000000000000 100 100 - 05 000000000000 100 100 - 07 000000000000 100 100 - 08 000000000000 100 100 - 09 821E00000000 100 100 - 0A 000000000000 100 100 - 0C 950200000000 100 100 - A8 000000000000 100 100 - AF 000000000000 100 100 - C0 000000000000 100 100 - C2 290014002B00 100 41 - C5 000000000000 100 100 - F0 000000000000 100 100 - AA 07007B000000 100 100 - AD 0E1E71304919 100 100"), - new Drive("PLEXTOR PX-128M2S", - "1.03", - 16, - @" 01 000000000000 100 100 0 - 03 000000000000 100 100 0 - 04 000000000000 100 100 0 - 05 000000000000 100 100 0 - 09 250100000000 100 100 0 - 0A 000000000000 100 100 0 - 0C D10000000000 100 100 0 - B2 000000000000 100 100 0 - BB 000000000000 100 100 0 - BE 000000000000 100 100 0 - C0 000000000000 100 100 0 - C1 000000000000 100 100 0 - C2 000000000000 100 100 0 - C3 000000000000 100 100 0 - C5 000000000000 100 100 0 - C6 000000000000 100 100 0 - C7 000000000000 100 100 0"), - new Drive("OCZ-VERTEX2", - "1.25", - 16, - @" 01 DADAD5000000 100 106 50 - 05 000000000000 100 100 3 - 09 DF0900004A2F 100 100 0 - 0C FC0100000000 100 100 0 - AB 000000000000 0 0 0 - AC 000000000000 0 0 0 - AE 1F0000000000 0 0 0 - B1 000000000000 0 0 0 - B5 000000000000 0 0 0 - B6 000000000000 0 0 0 - BB 000000000000 100 100 0 - C2 010081007F00 129 1 0 - C3 DADAD5000000 100 106 0 - C4 000000000000 100 100 0 - E7 000000000000 100 100 10 - E9 800400000000 0 0 0 - EA 000600000000 0 0 0 - F1 000600000000 0 0 0 - F2 801200000000 0 0 0"), - new Drive("WDC WD5000AADS-00S9B0", - null, - 10, - @" 1 000000000000 200 200 - 3 820D00000000 149 150 - 4 610800000000 98 98 - 5 000000000000 200 200 - 7 000000000000 253 100 - 9 0F1F00000000 90 90 - 10 000000000000 100 100 - 11 000000000000 100 100 - 12 880200000000 100 100 - 192 6B0000000000 200 200 - 193 E9CB03000000 118 118 - 194 280000000000 94 103 - 196 000000000000 200 200 - 197 000000000000 200 200 - 198 000000000000 200 200 - 199 000000000000 200 200 - 200 000000000000 200 200 - 130 7B0300010002 1 41 - 5 000000000000 0 0 - 1 000000000000 0 0"), - new Drive("INTEL SSDSA2M080G2GC", - null, - 10, - @" 3 000000000000 100 100 - 4 000000000000 100 100 - 5 010000000000 100 100 - 9 B10B00000000 100 100 - 12 DD0300000000 100 100 - 192 480000000000 100 100 - 225 89DB00000000 200 200 - 226 3D1B00000000 100 100 - 227 030000000000 100 100 - 228 7F85703C0000 100 100 - 232 000000000000 99 99 - 233 000000000000 98 98 - 184 000000000000 100 100 - 1 000000000000 0 0"), - new Drive("OCZ-VERTEX", - null, - 10, - @" 1 000000000000 0 8 - 9 000000000000 30 99 - 12 000000000000 0 15 - 184 000000000000 0 7 - 195 000000000000 0 0 - 196 000000000000 0 2 - 197 000000000000 0 0 - 198 B9ED00000000 214 176 - 199 352701000000 143 185 - 200 B10500000000 105 55 - 201 F40A00000000 238 194 - 202 020000000000 137 35 - 203 020000000000 125 63 - 204 000000000000 0 0 - 205 000000000000 19 136 - 206 000000000000 22 54 - 207 010000000000 113 226 - 208 000000000000 49 232 - 209 000000000000 0 98 - 211 000000000000 0 0 - 212 000000000000 0 0 - 213 000000000000 0 0"), - new Drive("INTEL SSDSA2CW120G3", - null, - 16, - @"03 000000000000 100 100 0 - 04 000000000000 100 100 0 - 05 000000000000 100 100 0 - 09 830200000000 100 100 0 - 0C 900100000000 100 100 0 - AA 000000000000 100 100 0 - AB 000000000000 100 100 0 - AC 000000000000 100 100 0 - B8 000000000000 100 100 0 - BB 000000000000 100 100 0 - C0 040000000000 100 100 0 - E1 FF4300000000 100 100 0 - E2 E57D14000000 100 100 0 - E3 000000000000 100 100 0 - E4 E39600000000 100 100 0 - E8 000000000000 100 100 0 - E9 000000000000 100 100 0 - F1 FF4300000000 100 100 0 - F2 264F00000000 100 100 0"), - new Drive("CORSAIR CMFSSD-128GBG2D", - "VBM19C1Q", - 16, - @"09 100900000000 99 99 0 - 0C 560200000000 99 99 0 - AF 000000000000 100 100 10 - B0 000000000000 100 100 10 - B1 2A0000000000 99 99 17 - B2 180000000000 60 60 10 - B3 4B0000000000 98 98 10 - B4 B50E00000000 98 98 10 - B5 000000000000 100 100 10 - B6 000000000000 100 100 10 - B7 000000000000 100 100 10 - BB 000000000000 100 100 0 - C3 000000000000 200 200 0 - C6 000000000000 100 100 0 - C7 810100000000 253 253 0 - E8 240000000000 60 60 10 - E9 630594120000 92 92 0"), - new Drive("Maxtor 6L300R0", - null, - 10, - @"3 9E5500000000 183 193 - 4 0A0D00000000 252 252 - 5 010000000000 253 253 - 6 000000000000 253 253 - 7 000000000000 252 253 - 8 DFA700000000 224 245 - 9 CE5700000000 155 155 - 10 000000000000 252 253 - 11 000000000000 252 253 - 12 BA0400000000 250 250 - 192 000000000000 253 253 - 193 000000000000 253 253 - 194 3D0000000000 253 42 - 195 5D1F00000000 252 253 - 196 000000000000 253 253 - 197 010000000000 253 253 - 198 000000000000 253 253 - 199 030000000000 196 199 - 200 000000000000 252 253 - 201 000000000000 252 253 - 202 000000000000 252 253 - 203 000000000000 252 253 - 204 000000000000 252 253 - 205 000000000000 252 253 - 207 000000000000 252 253 - 208 000000000000 252 253 - 209 EA0000000000 234 234 - 210 000000000000 252 253 - 211 000000000000 252 253 - 212 000000000000 252 253 - 130 5B0300010002 1 9 - 59 FC3203030100 205 0 - 1 000000000000 0 0 - 144 000000000000 0 34 "), - new Drive("M4-CT256M4SSD2", - "0309", - 16, - @"01 000000000000 100 100 50 - 05 000000000000 100 100 10 - 09 AB0100000000 100 100 1 - 0C 6E0000000000 100 100 1 - AA 000000000000 100 100 10 - AB 000000000000 100 100 1 - AC 000000000000 100 100 1 - AD 060000000000 100 100 10 - AE 000000000000 100 100 1 - B5 79003D00B700 100 100 1 - B7 000000000000 100 100 1 - B8 000000000000 100 100 50 - BB 000000000000 100 100 1 - BC 000000000000 100 100 1 - BD 5B0000000000 100 100 1 - C2 000000000000 100 100 0 - C3 000000000000 100 100 1 - C4 000000000000 100 100 1 - C5 000000000000 100 100 1 - C6 000000000000 100 100 1 - C7 000000000000 100 100 1 - CA 000000000000 100 100 1 - CE 000000000000 100 100 1 "), - new Drive("C300-CTFDDAC256MAG", - "0007", - 16, - @"01 000000000000 100 100 0 - 05 000000000000 100 100 0 - 09 4C0A00000000 100 100 0 - 0C 0F0100000000 100 100 0 - AA 000000000000 100 100 0 - AB 000000000000 100 100 0 - AC 000000000000 100 100 0 - AD 1B0000000000 100 100 0 - AE 000000000000 100 100 0 - B5 D30357012B05 100 100 0 - B7 000000000000 100 100 0 - B8 000000000000 100 100 0 - BB 000000000000 100 100 0 - BC 000000000000 100 100 0 - BD C60100000000 100 100 0 - C3 000000000000 100 100 0 - C4 000000000000 100 100 0 - C5 000000000000 100 100 0 - C6 000000000000 100 100 0 - C7 000000000000 100 100 0 - CA 000000000000 100 100 0 - CE 000000000000 100 100 0"), - new Drive("M4-CT064M4SSD2", - "0009", - 16, - @"01 000000000000 100 100 50 - 05 000000000000 100 100 10 - 09 260000000000 100 100 1 - 0C 5A0000000000 100 100 1 - AA 000000000000 100 100 10 - AB 000000000000 100 100 1 - AC 000000000000 100 100 1 - AD 010000000000 100 100 10 - AE 000000000000 100 100 1 - B5 2B000E003A00 100 100 1 - B7 000000000000 100 100 1 - B8 000000000000 100 100 50 - BB 000000000000 100 100 1 - BC 000000000000 100 100 1 - BD 310000000000 100 100 1 - C2 000000000000 100 100 0 - C3 000000000000 100 100 1 - C4 000000000000 100 100 1 - C5 000000000000 100 100 1 - C6 000000000000 100 100 1 - C7 000000000000 100 100 1 - CA 000000000000 100 100 1 - CE 000000000000 100 100 1"), - new Drive("M4-CT128M4SSD2", - "000F", - 16, - @"01 000000000000 100 100 50 - 05 000000000000 100 100 10 - 09 CA1400000000 100 100 1 - 0C A30200000000 100 100 1 - AA 000000000000 100 100 10 - AB 000000000000 100 100 1 - AC 000000000000 100 100 1 - AD 1F0000000000 99 99 10 - AE 140000000000 100 100 1 - B5 12037C028E05 100 100 1 - B7 000000000000 100 100 1 - B8 000000000000 100 100 50 - BB 000000000000 100 100 1 - BC 000000000000 100 100 1 - BD 510000000000 100 100 1 - C2 000000000000 100 100 0 - C3 000000000000 100 100 1 - C4 000000000000 100 100 1 - C5 000000000000 100 100 1 - C6 000000000000 100 100 1 - C7 000000000000 100 100 1 - CA 010000000000 99 99 1 - CE 000000000000 100 100 1 "), - new Drive("Samsung SSD 840 PRO Series", - "DXM05B0Q", - 16, - @"05 000000000000 100 100 10 - 09 541200000000 99 99 0 - 0C 820500000000 98 98 0 - B1 B90200000000 80 80 0 - B3 000000000000 100 100 10 - B5 000000000000 100 100 10 - B6 000000000000 100 100 10 - B7 000000000000 100 100 10 - BB 000000000000 100 100 0 - BE 1C0000000000 48 72 0 - C3 000000000000 200 200 0 - C7 020000000000 99 99 0 - EB 690000000000 99 99 0 - F1 A56AA1F60200 99 99 0") - }; - - private int driveNumber; - - public DebugSmart(int driveNumber) { - this.driveNumber = driveNumber; - } - - public bool IsValid => true; - - public void Close() { - Dispose(true); - GC.SuppressFinalize(this); - } - - public bool EnableSmart() { - if (driveNumber < 0) - throw new ObjectDisposedException(nameof(DebugSmart)); - - - return true; - } - - public Kernel32.SMART_ATTRIBUTE[] ReadSmartData() { - if (driveNumber < 0) - throw new ObjectDisposedException(nameof(DebugSmart)); - - - return drives[driveNumber].DriveAttributeValues; - } - - public Kernel32.SMART_THRESHOLD[] ReadSmartThresholds() { - if (driveNumber < 0) - throw new ObjectDisposedException(nameof(DebugSmart)); - - - return drives[driveNumber].DriveThresholdValues; - } - - public bool ReadNameAndFirmwareRevision(out string name, out string firmwareRevision) { - if (driveNumber < 0) - throw new ObjectDisposedException(nameof(DebugSmart)); - - - name = drives[driveNumber].Name; - firmwareRevision = drives[driveNumber].FirmwareVersion; - return true; - } - - public void Dispose() { - Close(); - } - - protected void Dispose(bool disposing) { - if (disposing) - driveNumber = -1; - } - - private class Drive { - public Drive(string name, string firmware, int idBase, string value) { - Name = name; - FirmwareVersion = firmware; - - string[] lines = value.Split(new[] { '\r', '\n' }, - StringSplitOptions.RemoveEmptyEntries); - - DriveAttributeValues = new Kernel32.SMART_ATTRIBUTE[lines.Length]; - var thresholds = new List(); - - for (int i = 0; i < lines.Length; i++) { - string[] array = lines[i].Split(new[] { ' ' }, - StringSplitOptions.RemoveEmptyEntries); - - if (array.Length != 4 && array.Length != 5) - throw new Exception(); - - - var v = new Kernel32.SMART_ATTRIBUTE { Id = Convert.ToByte(array[0], idBase), RawValue = new byte[6] }; - - for (int j = 0; j < 6; j++) { - v.RawValue[j] = Convert.ToByte(array[1].Substring(2 * j, 2), 16); - } - - v.WorstValue = Convert.ToByte(array[2], 10); - v.CurrentValue = Convert.ToByte(array[3], 10); - - DriveAttributeValues[i] = v; - - if (array.Length == 5) { - var t = new Kernel32.SMART_THRESHOLD { Id = v.Id, Threshold = Convert.ToByte(array[4], 10) }; - thresholds.Add(t); - } - } - - DriveThresholdValues = thresholds.ToArray(); - } - - public Kernel32.SMART_ATTRIBUTE[] DriveAttributeValues { get; } - - public Kernel32.SMART_THRESHOLD[] DriveThresholdValues { get; } - - public string FirmwareVersion { get; } - - public string Name { get; } - } - } - -#endif -} \ No newline at end of file diff --git a/Hardware/HDD/GenericHarddisk.cs b/Hardware/HDD/GenericHarddisk.cs deleted file mode 100644 index e5982c1..0000000 --- a/Hardware/HDD/GenericHarddisk.cs +++ /dev/null @@ -1,119 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix("")] - public class GenericHarddisk : ATAStorage { - private static readonly List smartAttributes = - new List { - new SmartAttribute(0x01, SmartNames.ReadErrorRate), - new SmartAttribute(0x02, SmartNames.ThroughputPerformance), - new SmartAttribute(0x03, SmartNames.SpinUpTime), - new SmartAttribute(0x04, SmartNames.StartStopCount, RawToInt), - new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount), - new SmartAttribute(0x06, SmartNames.ReadChannelMargin), - new SmartAttribute(0x07, SmartNames.SeekErrorRate), - new SmartAttribute(0x08, SmartNames.SeekTimePerformance), - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0A, SmartNames.SpinRetryCount), - new SmartAttribute(0x0B, SmartNames.RecalibrationRetries), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0x0D, SmartNames.SoftReadErrorRate), - new SmartAttribute(0xAA, SmartNames.Unknown), - new SmartAttribute(0xAB, SmartNames.Unknown), - new SmartAttribute(0xAC, SmartNames.Unknown), - new SmartAttribute(0xB7, SmartNames.SataDownshiftErrorCount, RawToInt), - new SmartAttribute(0xB8, SmartNames.EndToEndError), - new SmartAttribute(0xB9, SmartNames.HeadStability), - new SmartAttribute(0xBA, SmartNames.InducedOpVibrationDetection), - new SmartAttribute(0xBB, SmartNames.ReportedUncorrectableErrors, RawToInt), - new SmartAttribute(0xBC, SmartNames.CommandTimeout, RawToInt), - new SmartAttribute(0xBD, SmartNames.HighFlyWrites), - new SmartAttribute(0xBF, SmartNames.GSenseErrorRate), - new SmartAttribute(0xC0, SmartNames.EmergencyRetractCycleCount), - new SmartAttribute(0xC1, SmartNames.LoadCycleCount), - new SmartAttribute(0xC3, SmartNames.HardwareEccRecovered), - new SmartAttribute(0xC4, SmartNames.ReallocationEventCount), - new SmartAttribute(0xC5, SmartNames.CurrentPendingSectorCount), - new SmartAttribute(0xC6, SmartNames.UncorrectableSectorCount), - new SmartAttribute(0xC7, SmartNames.UltraDmaCrcErrorCount), - new SmartAttribute(0xC8, SmartNames.WriteErrorRate), - new SmartAttribute(0xCA, SmartNames.DataAddressMarkErrors), - new SmartAttribute(0xCB, SmartNames.RunOutCancel), - new SmartAttribute(0xCC, SmartNames.SoftEccCorrection), - new SmartAttribute(0xCD, SmartNames.ThermalAsperityRate), - new SmartAttribute(0xCE, SmartNames.FlyingHeight), - new SmartAttribute(0xCF, SmartNames.SpinHighCurrent), - new SmartAttribute(0xD0, SmartNames.SpinBuzz), - new SmartAttribute(0xD1, SmartNames.OfflineSeekPerformance), - new SmartAttribute(0xD3, SmartNames.VibrationDuringWrite), - new SmartAttribute(0xD4, SmartNames.ShockDuringWrite), - new SmartAttribute(0xDC, SmartNames.DiskShift), - new SmartAttribute(0xDD, SmartNames.AlternativeGSenseErrorRate), - new SmartAttribute(0xDE, SmartNames.LoadedHours), - new SmartAttribute(0xDF, SmartNames.LoadUnloadRetryCount), - new SmartAttribute(0xE0, SmartNames.LoadFriction), - new SmartAttribute(0xE1, SmartNames.LoadUnloadCycleCount), - new SmartAttribute(0xE2, SmartNames.LoadInTime), - new SmartAttribute(0xE3, SmartNames.TorqueAmplificationCount), - new SmartAttribute(0xE4, SmartNames.PowerOffRetractCycle), - new SmartAttribute(0xE6, SmartNames.GmrHeadAmplitude), - new SmartAttribute(0xE8, SmartNames.EnduranceRemaining), - new SmartAttribute(0xE9, SmartNames.PowerOnHours), - new SmartAttribute(0xF0, SmartNames.HeadFlyingHours), - new SmartAttribute(0xF1, SmartNames.TotalLbasWritten), - new SmartAttribute(0xF2, SmartNames.TotalLbasRead), - new SmartAttribute(0xFA, SmartNames.ReadErrorRetryRate), - new SmartAttribute(0xFE, SmartNames.FreeFallProtection), - new SmartAttribute(0xC2, - SmartNames.Temperature, - (r, v, p) - => r[0] + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - SmartNames.Temperature, - false, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }), - new SmartAttribute(0xE7, - SmartNames.Temperature, - (r, v, p) - => r[0] + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - SmartNames.Temperature, - false, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }), - new SmartAttribute(0xBE, - SmartNames.TemperatureDifferenceFrom100, - (r, v, p) - => r[0] + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - "Temperature", - false, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }) - }; - - internal GenericHarddisk(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "hdd", index, smartAttributes, settings) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/HarddriveGroup.cs b/Hardware/HDD/HarddriveGroup.cs deleted file mode 100644 index d413b87..0000000 --- a/Hardware/HDD/HarddriveGroup.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Collections.Generic; -using System.Management; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class HarddriveGroup : IGroup { - private readonly List hardware = new List(); - - public HarddriveGroup(ISettings settings) { - if (Software.OperatingSystem.IsLinux) return; - - - //https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-diskdrive - var mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); - ManagementObjectCollection queryCollection = mosDisks.Get(); // get the results - - foreach (var disk in queryCollection) { - var deviceId = (string) disk.Properties["DeviceId"].Value; // is \\.\PhysicalDrive0..n - var idx = Convert.ToUInt32(disk.Properties["Index"].Value); - var diskSize = Convert.ToUInt64(disk.Properties["Size"].Value); - var scsi = Convert.ToInt32(disk.Properties["SCSIPort"].Value); - - if (deviceId != null) { - var instance = AbstractStorage.CreateInstance(deviceId, idx, diskSize, scsi, settings); - if (instance != null) { - hardware.Add(instance); - } - } - } - - queryCollection.Dispose(); - mosDisks.Dispose(); - } - - public IEnumerable Hardware => hardware; - - public string GetReport() { - return null; - } - - public void Close() { - foreach (AbstractStorage storage in hardware) - storage.Close(); - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/INVMeDrive.cs b/Hardware/HDD/INVMeDrive.cs deleted file mode 100644 index 5fd9682..0000000 --- a/Hardware/HDD/INVMeDrive.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal interface INVMeDrive { - SafeHandle Identify(StorageInfo storageInfo); - - bool IdentifyController(SafeHandle hDevice, out Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data); - - bool HealthInfoLog(SafeHandle hDevice, out Kernel32.NVME_HEALTH_INFO_LOG data); - } -} \ No newline at end of file diff --git a/Hardware/HDD/ISmart.cs b/Hardware/HDD/ISmart.cs deleted file mode 100644 index ad29000..0000000 --- a/Hardware/HDD/ISmart.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public interface ISmart : IDisposable { - bool IsValid { get; } - - void Close(); - - bool EnableSmart(); - - Kernel32.SMART_ATTRIBUTE[] ReadSmartData(); - - Kernel32.SMART_THRESHOLD[] ReadSmartThresholds(); - - bool ReadNameAndFirmwareRevision(out string name, out string firmwareRevision); - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeGeneric.cs b/Hardware/HDD/NVMeGeneric.cs deleted file mode 100644 index 99bbc6e..0000000 --- a/Hardware/HDD/NVMeGeneric.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public sealed class NVMeGeneric : AbstractStorage { - private const ulong Scale = 1000000; - private const ulong Units = 512; - - private readonly NVMeInfo info; - private readonly List sensors = new List(); - private readonly NVMeSmart smart; - - /// - /// Gets the SMART data. - /// - public NVMeSmart Smart => smart; - - private NVMeGeneric(StorageInfo storageInfo, NVMeInfo info, int index, ISettings settings) - : base(storageInfo, info.Model, info.Revision, "nvme", index, settings) { - smart = new NVMeSmart(storageInfo); - this.info = info; - CreateSensors(); - } - - private static NVMeInfo GetDeviceInfo(StorageInfo storageInfo) { - var smart = new NVMeSmart(storageInfo); - NVMeInfo info = smart.GetInfo(); - return info; - } - - internal static AbstractStorage CreateInstance(StorageInfo storageInfo, ISettings settings) { - NVMeInfo nvmeInfo = GetDeviceInfo(storageInfo); - return nvmeInfo == null ? null : new NVMeGeneric(storageInfo, nvmeInfo, storageInfo.Index, settings); - } - - protected override void CreateSensors() { - NVMeHealthInfo log = smart.GetHealthInfo(); - if (log != null) { - AddSensor("Temperature", 0, false, SensorType.Temperature, health => health.Temperature); - AddSensor("Available Spare", 1, false, SensorType.Level, health => health.AvailableSpare); - AddSensor("Available Spare Threshold", 2, false, SensorType.Level, health => health.AvailableSpareThreshold); - AddSensor("Percentage Used", 3, false, SensorType.Level, health => health.PercentageUsed); - AddSensor("Data Read", 4, false, SensorType.Data, health => UnitsToData(health.DataUnitRead)); - AddSensor("Data Written", 5, false, SensorType.Data, health => UnitsToData(health.DataUnitWritten)); - - int sensorIdx = 6; - for (int i = 0; i < log.TemperatureSensors.Length; i++) { - int idx = i; - if (log.TemperatureSensors[idx] > short.MinValue) { - AddSensor("Temperature " + (idx + 1), sensorIdx, false, SensorType.Temperature, health => health.TemperatureSensors[idx]); - sensorIdx++; - } - } - } - - base.CreateSensors(); - } - - private void AddSensor(string name, int index, bool defaultHidden, SensorType sensorType, GetSensorValue getValue) { - var sensor = new NVMeSensor(name, index, defaultHidden, sensorType, this, settings, getValue); - ActivateSensor(sensor); - sensor.Value = 0; - sensors.Add(sensor); - } - - private static float UnitsToData(ulong u) { - // one unit is 512 * 1000 bytes, return in GB (not GiB) - return Units * u / Scale; - } - - protected override void UpdateSensors() { - NVMeHealthInfo health = smart.GetHealthInfo(); - foreach (NVMeSensor sensor in sensors) - sensor.Update(health); - } - - protected override void GetReport(StringBuilder r) { - if (info == null) - return; - - - r.AppendLine("PCI Vendor ID: 0x" + info.VID.ToString("x04")); - if (info.VID != info.SSVID) - r.AppendLine("PCI Subsystem Vendor ID: 0x" + info.VID.ToString("x04")); - - r.AppendLine("IEEE OUI Identifier: 0x" + info.IEEE[2].ToString("x02") + info.IEEE[1].ToString("x02") + info.IEEE[0].ToString("x02")); - r.AppendLine("Total NVM Capacity: " + info.TotalCapacity); - r.AppendLine("Unallocated NVM Capacity: " + info.UnallocatedCapacity); - r.AppendLine("Controller ID: " + info.ControllerId); - r.AppendLine("Number of Namespaces: " + info.NumberNamespaces); - - NVMeHealthInfo health = smart.GetHealthInfo(); - if (health == null) - return; - - - if (health.CriticalWarning == Kernel32.NVME_CRITICAL_WARNING.None) - r.AppendLine("Critical Warning: -"); - else { - if ((health.CriticalWarning & Kernel32.NVME_CRITICAL_WARNING.AvailableSpaceLow) != 0) - r.AppendLine("Critical Warning: the available spare space has fallen below the threshold."); - - if ((health.CriticalWarning & Kernel32.NVME_CRITICAL_WARNING.TemperatureThreshold) != 0) - r.AppendLine("Critical Warning: a temperature is above an over temperature threshold or below an under temperature threshold."); - - if ((health.CriticalWarning & Kernel32.NVME_CRITICAL_WARNING.ReliabilityDegraded) != 0) - r.AppendLine("Critical Warning: the device reliability has been degraded due to significant media related errors or any internal error that degrades device reliability."); - - if ((health.CriticalWarning & Kernel32.NVME_CRITICAL_WARNING.ReadOnly) != 0) - r.AppendLine("Critical Warning: the media has been placed in read only mode."); - - if ((health.CriticalWarning & Kernel32.NVME_CRITICAL_WARNING.VolatileMemoryBackupDeviceFailed) != 0) - r.AppendLine("Critical Warning: the volatile memory backup device has failed."); - } - - r.AppendLine("Temperature: " + health.Temperature + " Celsius"); - r.AppendLine("Available Spare: " + health.AvailableSpare + "%"); - r.AppendLine("Available Spare Threshold: " + health.AvailableSpareThreshold + "%"); - r.AppendLine("Percentage Used: " + health.PercentageUsed + "%"); - r.AppendLine("Data Units Read: " + health.DataUnitRead); - r.AppendLine("Data Units Written: " + health.DataUnitWritten); - r.AppendLine("Host Read Commands: " + health.HostReadCommands); - r.AppendLine("Host Write Commands: " + health.HostWriteCommands); - r.AppendLine("Controller Busy Time: " + health.ControllerBusyTime); - r.AppendLine("Power Cycles: " + health.PowerCycle); - r.AppendLine("Power On Hours: " + health.PowerOnHours); - r.AppendLine("Unsafe Shutdowns: " + health.UnsafeShutdowns); - r.AppendLine("Media Errors: " + health.MediaErrors); - r.AppendLine("Number of Error Information Log Entries: " + health.ErrorInfoLogEntryCount); - r.AppendLine("Warning Composite Temperature Time: " + health.WarningCompositeTemperatureTime); - r.AppendLine("Critical Composite Temperature Time: " + health.CriticalCompositeTemperatureTime); - for (int i = 0; i < health.TemperatureSensors.Length; i++) { - if (health.TemperatureSensors[i] > short.MinValue) - r.AppendLine("Temperature Sensor " + (i + 1) + ": " + health.TemperatureSensors[i] + " Celsius"); - } - } - - public override void Close() { - smart?.Close(); - - base.Close(); - } - - private delegate float GetSensorValue(NVMeHealthInfo health); - - private class NVMeSensor : Sensor { - private readonly GetSensorValue getValue; - - public NVMeSensor(string name, int index, bool defaultHidden, SensorType sensorType, Hardware hardware, ISettings settings, GetSensorValue getValue) - : base(name, index, defaultHidden, sensorType, hardware, null, settings) { - this.getValue = getValue; - } - - public void Update(NVMeHealthInfo health) { - Value = getValue(health); - } - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeHealthInfo.cs b/Hardware/HDD/NVMeHealthInfo.cs deleted file mode 100644 index 86645ba..0000000 --- a/Hardware/HDD/NVMeHealthInfo.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public abstract class NVMeHealthInfo { - public byte AvailableSpare { get; protected set; } - - public byte AvailableSpareThreshold { get; protected set; } - - public ulong ControllerBusyTime { get; protected set; } - - public uint CriticalCompositeTemperatureTime { get; protected set; } - - public Kernel32.NVME_CRITICAL_WARNING CriticalWarning { get; protected set; } - - public ulong DataUnitRead { get; protected set; } - - public ulong DataUnitWritten { get; protected set; } - - public ulong ErrorInfoLogEntryCount { get; protected set; } - - public ulong HostReadCommands { get; protected set; } - - public ulong HostWriteCommands { get; protected set; } - - public ulong MediaErrors { get; protected set; } - - public byte PercentageUsed { get; protected set; } - - public ulong PowerCycle { get; protected set; } - - public ulong PowerOnHours { get; protected set; } - - public short Temperature { get; protected set; } - - public short[] TemperatureSensors { get; protected set; } - - public ulong UnsafeShutdowns { get; protected set; } - - public uint WarningCompositeTemperatureTime { get; protected set; } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeInfo.cs b/Hardware/HDD/NVMeInfo.cs deleted file mode 100644 index 617862b..0000000 --- a/Hardware/HDD/NVMeInfo.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -namespace OpenHardwareMonitor.Hardware.HDD { - public abstract class NVMeInfo { - public ushort ControllerId { get; protected set; } - - public byte[] IEEE { get; protected set; } - - public int Index { get; protected set; } - - public string Model { get; protected set; } - - public uint NumberNamespaces { get; protected set; } - - public string Revision { get; protected set; } - - public string Serial { get; protected set; } - - public ushort SSVID { get; protected set; } - - public ulong TotalCapacity { get; protected set; } - - public ulong UnallocatedCapacity { get; protected set; } - - public ushort VID { get; protected set; } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeIntel.cs b/Hardware/HDD/NVMeIntel.cs deleted file mode 100644 index 4284f89..0000000 --- a/Hardware/HDD/NVMeIntel.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Runtime.InteropServices; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class NVMeIntel : INVMeDrive { - //intel nvme access - - public SafeHandle Identify(StorageInfo storageInfo) { - return NVMeWindows.IdentifyDevice(storageInfo); - } - - public bool IdentifyController(SafeHandle hDevice, out Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature1); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd = new uint[16]; - passThrough.NVMeCmd[0] = 6; //identify - passThrough.NVMeCmd[10] = 1; //return to host - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.NVME_PASS_THROUGH_IOCTL.DataBuffer)); - var newPtr = IntPtr.Add(buffer, offset.ToInt32()); - int finalSize = Marshal.SizeOf(); - var ptr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Kernel32.RtlZeroMemory(ptr, finalSize); - int len = Math.Min(finalSize, passThrough.DataBuffer.Length); - Kernel32.CopyMemory(ptr, newPtr, (uint) len); - Marshal.FreeHGlobal(buffer); - - var item = Marshal.PtrToStructure(ptr); - data = item; - Marshal.FreeHGlobal(ptr); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public bool HealthInfoLog(SafeHandle hDevice, out Kernel32.NVME_HEALTH_INFO_LOG data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature1); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd[0] = (uint) Kernel32.STORAGE_PROTOCOL_NVME_DATA_TYPE.NVMeDataTypeLogPage; // GetLogPage - passThrough.NVMeCmd[1] = 0xFFFFFFFF; // address - passThrough.NVMeCmd[10] = 0x007f0002; // uint cdw10 = 0x000000002 | (((size / 4) - 1) << 16); - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - var buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.NVME_PASS_THROUGH_IOCTL.DataBuffer)); - var newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public static SafeHandle IdentifyDevice(StorageInfo storageInfo) { - var handle = Kernel32.OpenDevice(storageInfo.Scsi); - if (handle == null || handle.IsInvalid) - return null; - - - bool validTransfer; - IntPtr buffer; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature1); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd = new uint[16]; - passThrough.NVMeCmd[0] = 6; //identify - passThrough.NVMeCmd[10] = 1; //return to host - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - Marshal.FreeHGlobal(buffer); - - if (validTransfer) { } else { - handle.Close(); - handle = null; - } - - return handle; - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeIntelRST.cs b/Hardware/HDD/NVMeIntelRST.cs deleted file mode 100644 index b90de56..0000000 --- a/Hardware/HDD/NVMeIntelRST.cs +++ /dev/null @@ -1,154 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Runtime.InteropServices; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class NVMeIntelRst : INVMeDrive { - //intel RST (raid) nvme access - - public SafeHandle Identify(StorageInfo storageInfo) { - return NVMeWindows.IdentifyDevice(storageInfo); - } - - public bool IdentifyController(SafeHandle hDevice, out Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature2); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd = new uint[16]; - passThrough.NVMeCmd[0] = 6; //identify - passThrough.NVMeCmd[10] = 1; //return to host - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.NVME_PASS_THROUGH_IOCTL.DataBuffer)); - IntPtr newPtr = IntPtr.Add(buffer, offset.ToInt32()); - int finalSize = Marshal.SizeOf(); - var ptr = Marshal.AllocHGlobal(Marshal.SizeOf()); - Kernel32.RtlZeroMemory(ptr, finalSize); - int len = Math.Min(finalSize, passThrough.DataBuffer.Length); - Kernel32.CopyMemory(ptr, newPtr, (uint) len); - Marshal.FreeHGlobal(buffer); - - var item = Marshal.PtrToStructure(ptr); - data = item; - Marshal.FreeHGlobal(ptr); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public bool HealthInfoLog(SafeHandle hDevice, out Kernel32.NVME_HEALTH_INFO_LOG data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature2); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd[0] = (uint) Kernel32.STORAGE_PROTOCOL_NVME_DATA_TYPE.NVMeDataTypeLogPage; // GetLogPage - passThrough.NVMeCmd[1] = 0xFFFFFFFF; // address - passThrough.NVMeCmd[10] = 0x007f0002; // uint cdw10 = 0x000000002 | (((size / 4) - 1) << 16); - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.NVME_PASS_THROUGH_IOCTL.DataBuffer)); - IntPtr newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public static SafeHandle IdentifyDevice(StorageInfo storageInfo) { - var handle = Kernel32.OpenDevice(storageInfo.Scsi); - if (handle == null || handle.IsInvalid) - return null; - - - bool validTransfer; - IntPtr buffer; - - Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct(); - passThrough.srb.HeaderLenght = (uint) Marshal.SizeOf(); - passThrough.srb.Signature = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature2); - passThrough.srb.Timeout = 10; - passThrough.srb.ControlCode = Kernel32.NVMePassThroughSrbIoCode; - passThrough.srb.ReturnCode = 0; - passThrough.srb.Length = (uint) Marshal.SizeOf() - (uint) Marshal.SizeOf(); - passThrough.NVMeCmd = new uint[16]; - passThrough.NVMeCmd[0] = 6; //identify - passThrough.NVMeCmd[10] = 1; //return to host - passThrough.Direction = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST; - passThrough.QueueId = 0; - passThrough.DataBufferLen = (uint) passThrough.DataBuffer.Length; - passThrough.MetaDataLen = 0; - passThrough.ReturnBufferLen = (uint) Marshal.SizeOf(); - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(passThrough, buffer, false); - - validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero); - Marshal.FreeHGlobal(buffer); - - if (validTransfer) { } else { - handle.Close(); - handle = null; - } - - return handle; - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeSamsung.cs b/Hardware/HDD/NVMeSamsung.cs deleted file mode 100644 index fff114d..0000000 --- a/Hardware/HDD/NVMeSamsung.cs +++ /dev/null @@ -1,243 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class NVMeSamsung : INVMeDrive { - //samsung nvme access - //https://github.com/hiyohiyo/CrystalDiskInfo - //https://github.com/hiyohiyo/CrystalDiskInfo/blob/master/AtaSmart.cpp - - public SafeHandle Identify(StorageInfo storageInfo) { - return NVMeWindows.IdentifyDevice(storageInfo); - } - - public bool IdentifyController(SafeHandle hDevice, out Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS sptwb = Kernel32.CreateStruct(); - - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xB5; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 5; // Identify - sptwb.Spt.Cdb[8] = 0; // Transfer Length - sptwb.Spt.Cdb[9] = 0x40; // Transfer Length - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_OUT; - sptwb.DataBuf[0] = 1; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - Marshal.FreeHGlobal(buffer); - - if (validTransfer) { - //read data from samsung SSD - sptwb = Kernel32.CreateStruct(); - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xA2; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 5; // Identify - sptwb.Spt.Cdb[8] = 2; // Transfer Length (high) - sptwb.Spt.Cdb[9] = 0; // Transfer Length (low) - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_IN; - - length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - - validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - IntPtr newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - } - - return result; - } - - public bool HealthInfoLog(SafeHandle hDevice, out Kernel32.NVME_HEALTH_INFO_LOG data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS sptwb = Kernel32.CreateStruct(); - - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xB5; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 6; // Log Data - sptwb.Spt.Cdb[8] = 0; // Transfer Length - sptwb.Spt.Cdb[9] = 0x40; // Transfer Length - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_OUT; - sptwb.DataBuf[0] = 2; - sptwb.DataBuf[4] = 0xff; - sptwb.DataBuf[5] = 0xff; - sptwb.DataBuf[6] = 0xff; - sptwb.DataBuf[7] = 0xff; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - Marshal.FreeHGlobal(buffer); - - if (validTransfer) { - //read data from samsung SSD - sptwb = Kernel32.CreateStruct(); - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xA2; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 6; // Log Data - sptwb.Spt.Cdb[8] = 2; // Transfer Length (high) - sptwb.Spt.Cdb[9] = 0; // Transfer Length (low) - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_IN; - - length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - - validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - var offset = Marshal.OffsetOf(nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - IntPtr newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - } - - return result; - } - - public static SafeHandle IdentifyDevice(StorageInfo storageInfo) { - var handle = Kernel32.OpenDevice(storageInfo.DeviceId); - if (handle == null || handle.IsInvalid) - return null; - - - IntPtr buffer; - Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS sptwb = Kernel32.CreateStruct(); - - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xB5; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 5; // Identify - sptwb.Spt.Cdb[8] = 0; // Transfer Length - sptwb.Spt.Cdb[9] = 0x40; - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_OUT; - sptwb.DataBuf[0] = 1; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - Marshal.FreeHGlobal(buffer); - - if (validTransfer) { - //read data from samsung SSD - sptwb = Kernel32.CreateStruct(); - sptwb.Spt.Length = (ushort) Marshal.SizeOf(); - sptwb.Spt.PathId = 0; - sptwb.Spt.TargetId = 0; - sptwb.Spt.Lun = 0; - sptwb.Spt.SenseInfoLength = 24; - sptwb.Spt.DataTransferLength = Kernel32.SCSI_PASS_THROUGH_BUFFER_SIZE; - sptwb.Spt.TimeOutValue = 2; - sptwb.Spt.DataBufferOffset = Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.DataBuf)); - sptwb.Spt.SenseInfoOffset = (uint) Marshal.OffsetOf(typeof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS), nameof(Kernel32.SCSI_PASS_THROUGH_WITH_BUFFERS.SenseBuf)); - sptwb.Spt.CdbLength = 16; - sptwb.Spt.Cdb[0] = 0xA2; // SECURITY PROTOCOL IN - sptwb.Spt.Cdb[1] = 0xFE; // Samsung Protocol - sptwb.Spt.Cdb[3] = 5; // Identify - sptwb.Spt.Cdb[8] = 2; // Transfer Length - sptwb.Spt.Cdb[9] = 0; - sptwb.Spt.DataIn = (byte) Kernel32.SCSI_IOCTL_DATA.SCSI_IOCTL_DATA_IN; - - length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(sptwb, buffer, false); - - validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_SCSI_PASS_THROUGH, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - Marshal.PtrToStructure(buffer); - Marshal.FreeHGlobal(buffer); - } else { - Marshal.FreeHGlobal(buffer); - handle.Close(); - handle = null; - } - } - - return handle; - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeSmart.cs b/Hardware/HDD/NVMeSmart.cs deleted file mode 100644 index cfd7f60..0000000 --- a/Hardware/HDD/NVMeSmart.cs +++ /dev/null @@ -1,169 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Runtime.InteropServices; -using System.Text; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public class NVMeSmart : IDisposable { - private readonly int driveNumber; - private readonly SafeHandle handle; - - internal NVMeSmart(StorageInfo storageInfo) { - driveNumber = storageInfo.Index; - NVMeDrive = null; - - //test samsung protocol - if (NVMeDrive == null && storageInfo.Name.ToLower().Contains("samsung")) { - handle = NVMeSamsung.IdentifyDevice(storageInfo); - if (handle != null) { - NVMeDrive = new NVMeSamsung(); - } - } - - //test intel protocol - if (NVMeDrive == null && storageInfo.Name.ToLower().Contains("intel")) { - handle = NVMeIntel.IdentifyDevice(storageInfo); - if (handle != null) { - NVMeDrive = new NVMeIntel(); - } - } - - //test intel raid protocol - if (NVMeDrive == null && storageInfo.Name.ToLower().Contains("intel")) { - handle = NVMeIntelRst.IdentifyDevice(storageInfo); - if (handle != null) { - NVMeDrive = new NVMeIntelRst(); - } - } - - //test windows generic driver protocol - if (NVMeDrive == null) { - handle = NVMeWindows.IdentifyDevice(storageInfo); - if (handle != null) { - NVMeDrive = new NVMeWindows(); - } - } - } - - public bool IsValid { - get { - if (handle == null || handle.IsInvalid) - return false; - - - return true; - } - } - - internal INVMeDrive NVMeDrive { get; } - - public void Dispose() { - Close(); - } - - private static string GetString(byte[] s) { - return Encoding.ASCII.GetString(s).Trim('\t', '\n', '\r', ' ', '\0'); - } - - private static short KelvinToCelsius(ushort k) { - return (short) (k > 0 ? k - 273 : short.MinValue); - } - - private static short KelvinToCelsius(byte[] k) { - return KelvinToCelsius(BitConverter.ToUInt16(k, 0)); - } - - public void Close() { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected void Dispose(bool disposing) { - if (disposing) { - if (handle != null && !handle.IsClosed) - handle.Close(); - } - } - - public HDD.NVMeInfo GetInfo() { - if (handle == null || handle.IsClosed) - return null; - - - bool valid = false; - var data = new Kernel32.NVME_IDENTIFY_CONTROLLER_DATA(); - if (NVMeDrive != null) - valid = NVMeDrive.IdentifyController(handle, out data); - - if (!valid) - return null; - - - return new NVMeInfo(driveNumber, data); - } - - public HDD.NVMeHealthInfo GetHealthInfo() { - if (handle == null || handle.IsClosed) - return null; - - - bool valid = false; - var data = new Kernel32.NVME_HEALTH_INFO_LOG(); - if (NVMeDrive != null) - valid = NVMeDrive.HealthInfoLog(handle, out data); - - if (!valid) - return null; - - - return new NVMeHealthInfo(data); - } - - private class NVMeInfo : HDD.NVMeInfo { - public NVMeInfo(int index, Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data) { - Index = index; - VID = data.VID; - SSVID = data.SSVID; - Serial = GetString(data.SN); - Model = GetString(data.MN); - Revision = GetString(data.FR); - IEEE = data.IEEE; - TotalCapacity = BitConverter.ToUInt64(data.TNVMCAP, 0); // 128bit little endian - UnallocatedCapacity = BitConverter.ToUInt64(data.UNVMCAP, 0); - ControllerId = data.CNTLID; - NumberNamespaces = data.NN; - } - } - - private class NVMeHealthInfo : HDD.NVMeHealthInfo { - public NVMeHealthInfo(Kernel32.NVME_HEALTH_INFO_LOG log) { - CriticalWarning = (Kernel32.NVME_CRITICAL_WARNING) log.CriticalWarning; - Temperature = KelvinToCelsius(log.CompositeTemp); - AvailableSpare = log.AvailableSpare; - AvailableSpareThreshold = log.AvailableSpareThreshold; - PercentageUsed = log.PercentageUsed; - DataUnitRead = BitConverter.ToUInt64(log.DataUnitRead, 0); - DataUnitWritten = BitConverter.ToUInt64(log.DataUnitWritten, 0); - HostReadCommands = BitConverter.ToUInt64(log.HostReadCommands, 0); - HostWriteCommands = BitConverter.ToUInt64(log.HostWriteCommands, 0); - ControllerBusyTime = BitConverter.ToUInt64(log.ControllerBusyTime, 0); - PowerCycle = BitConverter.ToUInt64(log.PowerCycles, 0); - PowerOnHours = BitConverter.ToUInt64(log.PowerOnHours, 0); - UnsafeShutdowns = BitConverter.ToUInt64(log.UnsafeShutdowns, 0); - MediaErrors = BitConverter.ToUInt64(log.MediaAndDataIntegrityErrors, 0); - ErrorInfoLogEntryCount = BitConverter.ToUInt64(log.NumberErrorInformationLogEntries, 0); - WarningCompositeTemperatureTime = log.WarningCompositeTemperatureTime; - CriticalCompositeTemperatureTime = log.CriticalCompositeTemperatureTime; - - TemperatureSensors = new short[log.TemperatureSensor.Length]; - for (int i = 0; i < TemperatureSensors.Length; i++) - TemperatureSensors[i] = KelvinToCelsius(log.TemperatureSensor[i]); - } - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NVMeWindows.cs b/Hardware/HDD/NVMeWindows.cs deleted file mode 100644 index f9d3e1c..0000000 --- a/Hardware/HDD/NVMeWindows.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class NVMeWindows : INVMeDrive { - //windows generic driver nvme access - - public SafeHandle Identify(StorageInfo storageInfo) { - return IdentifyDevice(storageInfo); - } - - public bool IdentifyController(SafeHandle hDevice, out Kernel32.NVME_IDENTIFY_CONTROLLER_DATA data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - - Kernel32.STORAGE_QUERY_BUFFER nptwb = Kernel32.CreateStruct(); - nptwb.ProtocolSpecific.ProtocolType = Kernel32.STORAGE_PROTOCOL_TYPE.ProtocolTypeNvme; - nptwb.ProtocolSpecific.DataType = (uint) Kernel32.STORAGE_PROTOCOL_NVME_DATA_TYPE.NVMeDataTypeIdentify; - nptwb.ProtocolSpecific.ProtocolDataOffset = (uint) Marshal.SizeOf(); - nptwb.ProtocolSpecific.ProtocolDataLength = (uint) nptwb.Buffer.Length; - nptwb.PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageAdapterProtocolSpecificProperty; - nptwb.QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(nptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - //map NVME_IDENTIFY_CONTROLLER_DATA to nptwb.Buffer - var offset = Marshal.OffsetOf(nameof(Kernel32.STORAGE_QUERY_BUFFER.Buffer)); - var newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public bool HealthInfoLog(SafeHandle hDevice, out Kernel32.NVME_HEALTH_INFO_LOG data) { - data = Kernel32.CreateStruct(); - if (hDevice == null || hDevice.IsInvalid) - return false; - - - bool result = false; - IntPtr buffer; - - Kernel32.STORAGE_QUERY_BUFFER nptwb = Kernel32.CreateStruct(); - nptwb.ProtocolSpecific.ProtocolType = Kernel32.STORAGE_PROTOCOL_TYPE.ProtocolTypeNvme; - nptwb.ProtocolSpecific.DataType = (uint) Kernel32.STORAGE_PROTOCOL_NVME_DATA_TYPE.NVMeDataTypeLogPage; - nptwb.ProtocolSpecific.ProtocolDataRequestValue = (uint) Kernel32.NVME_LOG_PAGES.NVME_LOG_PAGE_HEALTH_INFO; - nptwb.ProtocolSpecific.ProtocolDataOffset = (uint) Marshal.SizeOf(); - nptwb.ProtocolSpecific.ProtocolDataLength = (uint) nptwb.Buffer.Length; - nptwb.PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageAdapterProtocolSpecificProperty; - nptwb.QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(nptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(hDevice, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - //map NVME_HEALTH_INFO_LOG to nptwb.Buffer - var offset = Marshal.OffsetOf(nameof(Kernel32.STORAGE_QUERY_BUFFER.Buffer)); - var newPtr = IntPtr.Add(buffer, offset.ToInt32()); - var item = Marshal.PtrToStructure(newPtr); - data = item; - Marshal.FreeHGlobal(buffer); - result = true; - } else { - Marshal.FreeHGlobal(buffer); - } - - return result; - } - - public static SafeHandle IdentifyDevice(StorageInfo storageInfo) { - var handle = Kernel32.OpenDevice(storageInfo.DeviceId); - if (handle == null || handle.IsInvalid) - return null; - - - IntPtr buffer; - - Kernel32.STORAGE_QUERY_BUFFER nptwb = Kernel32.CreateStruct(); - nptwb.ProtocolSpecific.ProtocolType = Kernel32.STORAGE_PROTOCOL_TYPE.ProtocolTypeNvme; - nptwb.ProtocolSpecific.DataType = (uint) Kernel32.STORAGE_PROTOCOL_NVME_DATA_TYPE.NVMeDataTypeIdentify; - nptwb.ProtocolSpecific.ProtocolDataOffset = (uint) Marshal.SizeOf(); - nptwb.ProtocolSpecific.ProtocolDataLength = (uint) nptwb.Buffer.Length; - nptwb.PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageAdapterProtocolSpecificProperty; - nptwb.QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery; - - var length = Marshal.SizeOf(); - buffer = Marshal.AllocHGlobal(length); - Marshal.StructureToPtr(nptwb, buffer, false); - var validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, buffer, length, buffer, length, out _, IntPtr.Zero); - if (validTransfer) { - Marshal.FreeHGlobal(buffer); - } else { - Marshal.FreeHGlobal(buffer); - handle.Close(); - handle = null; - } - - return handle; - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/NamePrefixAttribute.cs b/Hardware/HDD/NamePrefixAttribute.cs deleted file mode 100644 index b49f488..0000000 --- a/Hardware/HDD/NamePrefixAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; - -namespace OpenHardwareMonitor.Hardware.HDD { - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - internal class NamePrefixAttribute : Attribute { - public NamePrefixAttribute(string namePrefix) { - Prefix = namePrefix; - } - - public string Prefix { get; } - } -} \ No newline at end of file diff --git a/Hardware/HDD/RequireSmartAttribute.cs b/Hardware/HDD/RequireSmartAttribute.cs deleted file mode 100644 index 3e1e1bc..0000000 --- a/Hardware/HDD/RequireSmartAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; - -namespace OpenHardwareMonitor.Hardware.HDD { - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - internal class RequireSmartAttribute : Attribute { - public RequireSmartAttribute(byte attributeId) { - AttributeId = attributeId; - } - - public byte AttributeId { get; } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDIndilinx.cs b/Hardware/HDD/SSDIndilinx.cs deleted file mode 100644 index 98a7e6e..0000000 --- a/Hardware/HDD/SSDIndilinx.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix(""), RequireSmart(0x01), RequireSmart(0x09), RequireSmart(0x0C), RequireSmart(0xD1), RequireSmart(0xCE), RequireSmart(0xCF)] - internal class SSDIndilinx : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x01, SmartNames.ReadErrorRate), - new SmartAttribute(0x09, SmartNames.PowerOnHours), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount), - new SmartAttribute(0xB8, SmartNames.InitialBadBlockCount), - new SmartAttribute(0xC3, SmartNames.ProgramFailure), - new SmartAttribute(0xC4, SmartNames.EraseFailure), - new SmartAttribute(0xC5, SmartNames.ReadFailure), - new SmartAttribute(0xC6, SmartNames.SectorsRead), - new SmartAttribute(0xC7, SmartNames.SectorsWritten), - new SmartAttribute(0xC8, SmartNames.ReadCommands), - new SmartAttribute(0xC9, SmartNames.WriteCommands), - new SmartAttribute(0xCA, SmartNames.BitErrors), - new SmartAttribute(0xCB, SmartNames.CorrectedErrors), - new SmartAttribute(0xCC, SmartNames.BadBlockFullFlag), - new SmartAttribute(0xCD, SmartNames.MaxCellCycles), - new SmartAttribute(0xCE, SmartNames.MinErase), - new SmartAttribute(0xCF, SmartNames.MaxErase), - new SmartAttribute(0xD0, SmartNames.AverageEraseCount), - new SmartAttribute(0xD1, - SmartNames.RemainingLife, - null, - SensorType.Level, - 0, - SmartNames.RemainingLife), - new SmartAttribute(0xD2, SmartNames.UnknownUnique), - new SmartAttribute(0xD3, SmartNames.SataErrorCountCrc), - new SmartAttribute(0xD4, SmartNames.SataErrorCountHandshake) - }; - - public SSDIndilinx(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDIntel.cs b/Hardware/HDD/SSDIntel.cs deleted file mode 100644 index 826989d..0000000 --- a/Hardware/HDD/SSDIntel.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix("INTEL SSD"), RequireSmart(0xE1), RequireSmart(0xE8), RequireSmart(0xE9)] - internal class SSDIntel : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x01, SmartNames.ReadErrorRate), - new SmartAttribute(0x03, SmartNames.SpinUpTime), - new SmartAttribute(0x04, SmartNames.StartStopCount, RawToInt), - new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount), - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0xAA, SmartNames.AvailableReservedSpace), - new SmartAttribute(0xAB, SmartNames.ProgramFailCount), - new SmartAttribute(0xAC, SmartNames.EraseFailCount), - new SmartAttribute(0xB8, SmartNames.EndToEndError), - new SmartAttribute(0xBE, - SmartNames.Temperature, - (r, v, p) - => r[0] + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - SmartNames.AirflowTemperature, - false, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }), - new SmartAttribute(0xC0, SmartNames.UnsafeShutdownCount), - new SmartAttribute(0xE1, - SmartNames.HostWrites, - (r, v, p) - => RawToInt(r, v, p) / 0x20, - SensorType.Data, - 0, - SmartNames.HostWrites), - new SmartAttribute(0xE8, - SmartNames.RemainingLife, - null, - SensorType.Level, - 0, - SmartNames.RemainingLife), - new SmartAttribute(0xE9, SmartNames.MediaWearOutIndicator), - new SmartAttribute(0xF1, - SmartNames.HostWrites, - (r, v, p) - => RawToInt(r, v, p) / 0x20, - SensorType.Data, - 0, - SmartNames.HostWrites), - new SmartAttribute(0xF2, - SmartNames.HostReads, - (r, v, p) - => RawToInt(r, v, p) / 0x20, - SensorType.Data, - 1, - SmartNames.HostReads) - }; - - public SSDIntel(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDMicron.cs b/Hardware/HDD/SSDMicron.cs deleted file mode 100644 index 2622628..0000000 --- a/Hardware/HDD/SSDMicron.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix(""), RequireSmart(0xAA), RequireSmart(0xAB), RequireSmart(0xAC), RequireSmart(0xAD), RequireSmart(0xAE), RequireSmart(0xCA)] - internal class SSDMicron : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x01, SmartNames.ReadErrorRate, RawToInt), - new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount, RawToInt), - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0xAA, SmartNames.NewFailingBlockCount, RawToInt), - new SmartAttribute(0xAB, SmartNames.ProgramFailCount, RawToInt), - new SmartAttribute(0xAC, SmartNames.EraseFailCount, RawToInt), - new SmartAttribute(0xAD, SmartNames.WearLevelingCount, RawToInt), - new SmartAttribute(0xAE, SmartNames.UnexpectedPowerLossCount, RawToInt), - new SmartAttribute(0xB5, - SmartNames.Non4KAlignedAccess, - (raw, value, p) - => 6e4f * ((raw[5] << 8) | raw[4])), - new SmartAttribute(0xB7, SmartNames.SataDownshiftErrorCount, RawToInt), - new SmartAttribute(0xBB, SmartNames.ReportedUncorrectableErrors, RawToInt), - new SmartAttribute(0xBC, SmartNames.CommandTimeout, RawToInt), - new SmartAttribute(0xBD, SmartNames.FactoryBadBlockCount, RawToInt), - new SmartAttribute(0xC4, SmartNames.ReallocationEventCount, RawToInt), - new SmartAttribute(0xC5, SmartNames.CurrentPendingSectorCount), - new SmartAttribute(0xC6, SmartNames.OffLineUncorrectableErrorCount, RawToInt), - new SmartAttribute(0xC7, SmartNames.UltraDmaCrcErrorCount, RawToInt), - new SmartAttribute(0xCA, - SmartNames.RemainingLife, - (raw, value, p) - => 100 - RawToInt(raw, value, p), - SensorType.Level, - 0, - SmartNames.RemainingLife), - new SmartAttribute(0xCE, - SmartNames.WriteErrorRate, - (raw, value, p) - => 6e4f * ((raw[1] << 8) | raw[0])) - }; - - public SSDMicron(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDPlextor.cs b/Hardware/HDD/SSDPlextor.cs deleted file mode 100644 index 472db40..0000000 --- a/Hardware/HDD/SSDPlextor.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix("PLEXTOR")] - internal class SSDPlextor : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0xF1, SmartNames.HostWrites, RawToGb, SensorType.Data, 0, SmartNames.HostWrites), - new SmartAttribute(0xF2, SmartNames.HostReads, RawToGb, SensorType.Data, 1, SmartNames.HostReads) - }; - - public SSDPlextor(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { } - - private static float RawToGb(byte[] rawValue, byte value, IReadOnlyList parameters) { - return RawToInt(rawValue, value, parameters) / 32; - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDSamsung.cs b/Hardware/HDD/SSDSamsung.cs deleted file mode 100644 index f0aab05..0000000 --- a/Hardware/HDD/SSDSamsung.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix(""), RequireSmart(0xB1), RequireSmart(0xB3), RequireSmart(0xB5), RequireSmart(0xB6), RequireSmart(0xB7), RequireSmart(0xBB), RequireSmart(0xC3), RequireSmart(0xC7)] - internal class SSDSamsung : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount), - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0xAF, SmartNames.ProgramFailCountChip, RawToInt), - new SmartAttribute(0xB0, SmartNames.EraseFailCountChip, RawToInt), - new SmartAttribute(0xB1, SmartNames.WearLevelingCount, RawToInt), - new SmartAttribute(0xB2, SmartNames.UsedReservedBlockCountChip, RawToInt), - new SmartAttribute(0xB3, SmartNames.UsedReservedBlockCountTotal, RawToInt), - - // Unused Reserved Block Count (Total) - new SmartAttribute(0xB4, SmartNames.RemainingLife, null, SensorType.Level, 0, SmartNames.RemainingLife), - new SmartAttribute(0xB5, SmartNames.ProgramFailCountTotal, RawToInt), - new SmartAttribute(0xB6, SmartNames.EraseFailCountTotal, RawToInt), - new SmartAttribute(0xB7, SmartNames.RuntimeBadBlockTotal, RawToInt), - new SmartAttribute(0xBB, SmartNames.UncorrectableErrorCount, RawToInt), - new SmartAttribute(0xBE, - SmartNames.Temperature, - (r, v, p) - => r[0] + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - SmartNames.Temperature, - false, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }), - new SmartAttribute(0xC2, SmartNames.AirflowTemperature), - new SmartAttribute(0xC3, SmartNames.EccRate), - new SmartAttribute(0xC6, SmartNames.OffLineUncorrectableErrorCount, RawToInt), - new SmartAttribute(0xC7, SmartNames.CrcErrorCount, RawToInt), - new SmartAttribute(0xC9, SmartNames.SupercapStatus), - new SmartAttribute(0xCA, SmartNames.ExceptionModeStatus), - new SmartAttribute(0xEB, SmartNames.PowerRecoveryCount), - new SmartAttribute(0xF1, - SmartNames.TotalLbasWritten, - (r, v, p) => (((long) r[5] << 40) | - ((long) r[4] << 32) | - ((long) r[3] << 24) | - ((long) r[2] << 16) | - ((long) r[1] << 8) | - r[0]) * - (512.0f / 1024 / 1024 / 1024), - SensorType.Data, - 0, - "Total Bytes Written") - }; - - public SSDSamsung(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SSDSandforce.cs b/Hardware/HDD/SSDSandforce.cs deleted file mode 100644 index 7a7e43c..0000000 --- a/Hardware/HDD/SSDSandforce.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - [NamePrefix(""), RequireSmart(0xAB), RequireSmart(0xB1)] - internal class SSDSandforce : ATAStorage { - private static readonly IEnumerable smartAttributes = - new List { - new SmartAttribute(0x01, SmartNames.RawReadErrorRate), - new SmartAttribute(0x05, SmartNames.RetiredBlockCount, RawToInt), - new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt), - new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt), - new SmartAttribute(0xAB, SmartNames.ProgramFailCount, RawToInt), - new SmartAttribute(0xAC, SmartNames.EraseFailCount, RawToInt), - new SmartAttribute(0xAE, SmartNames.UnexpectedPowerLossCount, RawToInt), - new SmartAttribute(0xB1, SmartNames.WearRangeDelta, RawToInt), - new SmartAttribute(0xB5, SmartNames.AlternativeProgramFailCount, RawToInt), - new SmartAttribute(0xB6, SmartNames.AlternativeEraseFailCount, RawToInt), - new SmartAttribute(0xBB, SmartNames.UncorrectableErrorCount, RawToInt), - new SmartAttribute(0xC2, - SmartNames.Temperature, - (raw, value, p) - => value + (p?[0].Value ?? 0), - SensorType.Temperature, - 0, - SmartNames.Temperature, - true, - new[] { - new ParameterDescription("Offset [°C]", - "Temperature offset of the thermal sensor.\n" + - "Temperature = Value + Offset.", - 0) - }), - new SmartAttribute(0xC3, SmartNames.UnrecoverableEcc), - new SmartAttribute(0xC4, SmartNames.ReallocationEventCount, RawToInt), - new SmartAttribute(0xE7, SmartNames.RemainingLife, null, SensorType.Level, 0, SmartNames.RemainingLife), - new SmartAttribute(0xE9, SmartNames.ControllerWritesToNand, RawToInt, SensorType.Data, 0, SmartNames.ControllerWritesToNand), - new SmartAttribute(0xEA, SmartNames.HostWritesToController, RawToInt, SensorType.Data, 1, SmartNames.HostWritesToController), - new SmartAttribute(0xF1, SmartNames.HostWrites, RawToInt, SensorType.Data, 1, SmartNames.HostWrites), - new SmartAttribute(0xF2, SmartNames.HostReads, RawToInt, SensorType.Data, 2, SmartNames.HostReads) - }; - - private readonly Sensor writeAmplification; - - public SSDSandforce(StorageInfo storageInfo, ISmart smart, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, smart, name, firmwareRevision, "ssd", index, smartAttributes, settings) { - writeAmplification = new Sensor("Write Amplification", 1, SensorType.Factor, this, settings); - } - - protected override void UpdateAdditionalSensors(Kernel32.SMART_ATTRIBUTE[] values) { - float? controllerWritesToNand = null; - float? hostWritesToController = null; - foreach (Kernel32.SMART_ATTRIBUTE value in values) { - if (value.Id == 0xE9) - controllerWritesToNand = RawToInt(value.RawValue, value.CurrentValue, null); - - if (value.Id == 0xEA) - hostWritesToController = RawToInt(value.RawValue, value.CurrentValue, null); - } - - if (controllerWritesToNand.HasValue && hostWritesToController.HasValue) { - if (hostWritesToController.Value > 0) - writeAmplification.Value = - controllerWritesToNand.Value / hostWritesToController.Value; - else - writeAmplification.Value = 0; - - ActivateSensor(writeAmplification); - } - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SmartAttribute.cs b/Hardware/HDD/SmartAttribute.cs deleted file mode 100644 index 1d13784..0000000 --- a/Hardware/HDD/SmartAttribute.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - public class SmartAttribute { - private readonly RawValueConversion rawValueConversion; - - public delegate float RawValueConversion(byte[] rawValue, byte value, IReadOnlyList parameters); - - /// - /// Initializes a new instance of the class. - /// - /// The SMART identifier of the attribute. - /// The name of the attribute. - public SmartAttribute(byte identifier, string name) : - this(identifier, name, null, null, 0, null) { } - - /// - /// Initializes a new instance of the class. - /// - /// The SMART identifier of the attribute. - /// The name of the attribute. - /// - /// A delegate for converting the raw byte - /// array into a value (or null to use the attribute value). - /// - public SmartAttribute - ( - byte identifier, - string name, - RawValueConversion rawValueConversion) : - this(identifier, name, rawValueConversion, null, 0, null) { } - - /// - /// Initializes a new instance of the class. - /// - /// The SMART identifier of the attribute. - /// The name of the attribute. - /// - /// A delegate for converting the raw byte - /// array into a value (or null to use the attribute value). - /// - /// - /// Type of the sensor or null if no sensor is to - /// be created. - /// - /// - /// If there exists more than one attribute with - /// the same sensor channel and type, then a sensor is created only for the - /// first attribute. - /// - /// - /// The name to be used for the sensor, or null if - /// no sensor is created. - /// - /// True to hide the sensor initially. - /// - /// Description for the parameters of the sensor - /// (or null). - /// - public SmartAttribute - ( - byte identifier, - string name, - RawValueConversion rawValueConversion, - SensorType? sensorType, - int sensorChannel, - string sensorName, - bool defaultHiddenSensor = false, - ParameterDescription[] parameterDescriptions = null) { - Identifier = identifier; - Name = name; - this.rawValueConversion = rawValueConversion; - SensorType = sensorType; - SensorChannel = sensorChannel; - SensorName = sensorName; - DefaultHiddenSensor = defaultHiddenSensor; - ParameterDescriptions = parameterDescriptions; - } - - public bool DefaultHiddenSensor { get; } - - public bool HasRawValueConversion => rawValueConversion != null; - - /// - /// Gets the SMART identifier. - /// - public byte Identifier { get; } - - public string Name { get; } - - public ParameterDescription[] ParameterDescriptions { get; } - - public int SensorChannel { get; } - - public string SensorName { get; } - - public SensorType? SensorType { get; } - - internal float ConvertValue(Kernel32.SMART_ATTRIBUTE value, IReadOnlyList parameters) { - if (rawValueConversion == null) { - return value.CurrentValue; - } - - return rawValueConversion(value.RawValue, value.CurrentValue, parameters); - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/SmartNames.cs b/Hardware/HDD/SmartNames.cs deleted file mode 100644 index f36aa32..0000000 --- a/Hardware/HDD/SmartNames.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -namespace OpenHardwareMonitor.Hardware.HDD { - /// - /// Localization class for SMART attribute names. - /// - public static class SmartNames { - public static string AirflowTemperature => "Airflow Temperature"; - - public static string AlternativeEraseFailCount => "Alternative Erase Fail Count"; - - public static string AlternativeGSenseErrorRate => "Alternative G-Sense Error Rate"; - - public static string AlternativeProgramFailCount => "Alternative Program Fail Count"; - - public static string AvailableReservedSpace => "Available Reserved Space"; - - public static string AverageEraseCount => "Average Erase Count"; - - public static string BadBlockFullFlag => "Bad Block Full Flag"; - - public static string BitErrors => "Bit Errors"; - - public static string CalibrationRetryCount => "Calibration Retry Count"; - - public static string CommandTimeout => "Command Timeout"; - - public static string ControllerWritesToNand => "Controller Writes to NAND"; - - public static string CorrectedErrors => "Corrected Errors"; - - public static string CrcErrorCount => "CRC Error Count"; - - public static string CurrentPendingSectorCount => "Current Pending Sector Count"; - - public static string DataAddressMarkErrors => "Data Address Mark errors"; - - public static string DiskShift => "Disk Shift"; - - public static string DriveTemperature => "Drive Temperature"; - - public static string EccRate => "ECC Rate"; - - public static string EmergencyRetractCycleCount => "Emergency Retract Cycle Count"; - - public static string EndToEndError => "End-to-End error"; - - public static string EnduranceRemaining => "Endurance Remaining"; - - public static string EraseFailCount => "Erase Fail Count"; - - public static string EraseFailCountChip => "Erase Fail Count (Chip)"; - - public static string EraseFailCountTotal => "Erase Fail Count (Total)"; - - public static string EraseFailure => "Erase Failure"; - - public static string ExceptionModeStatus => "Exception Mode Status"; - - public static string FactoryBadBlockCount => "Factory Bad Block Count"; - - public static string FlyingHeight => "Flying Height"; - - public static string FreeFallProtection => "Free Fall Protection"; - - public static string GmrHeadAmplitude => "GMR Head Amplitude"; - - public static string GSenseErrorRate => "G-sense Error Rate"; - - public static string HardwareEccRecovered => "Hardware ECC Recovered"; - - public static string HeadFlyingHours => "Head Flying Hours"; - - public static string HeadStability => "Head Stability"; - - public static string HighFlyWrites => "High Fly Writes"; - - public static string HostReads => "Host Reads"; - - public static string HostWrites => "Host Writes"; - - public static string HostWritesToController => "Host Writes to Controller"; - - public static string InducedOpVibrationDetection => "Induced Op-Vibration Detection"; - - public static string InitialBadBlockCount => "Initial Bad Block Count"; - - public static string LoadCycleCount => "Load Cycle Count"; - - public static string LoadedHours => "Loaded Hours"; - - public static string LoadFriction => "Load Friction"; - - public static string LoadInTime => "Load 'In'-time"; - - public static string LoadUnloadCycleCount => "Load/Unload Cycle Count"; - - public static string LoadUnloadCycleCountFujitsu => "Load/Unload Cycle Count (Fujitus)"; - - public static string LoadUnloadRetryCount => "Load/Unload Retry Count"; - - public static string MaxCellCycles => "Max Cell Cycles"; - - public static string MaxErase => "Max Erase"; - - public static string MediaWearOutIndicator => "Media Wear Out Indicator"; - - public static string MinErase => "Min Erase"; - - public static string MultiZoneErrorRate => "Multi-Zone Error Rate"; - - public static string NewFailingBlockCount => "New Failing Block Count"; - - public static string Non4KAlignedAccess => "Non-4k Aligned Access"; - - public static string OfflineSeekPerformance => "Offline Seek Performance"; - - public static string OffLineUncorrectableErrorCount => "Off-Line Uncorrectable Error Count"; - - public static string PowerCycleCount => "Power Cycle Count"; - - public static string PowerOffRetractCycle => "Power-Off Retract Cycle"; - - public static string PowerOnHours => "Power-On Hours (POH)"; - - public static string PowerRecoveryCount => "Power Recovery Count"; - - public static string ProgramFailCount => "Program Fail Count"; - - public static string ProgramFailCountChip => "Program Fail Count (Chip)"; - - public static string ProgramFailCountTotal => "Program Fail Count (Total)"; - - public static string ProgramFailure => "Program Failure"; - - public static string RawReadErrorRate => "Raw Read Error Rate"; - - public static string ReadChannelMargin => "Read Channel Margin"; - - public static string ReadCommands => "Read Commands"; - - public static string ReadErrorRate => "Read Error Rate"; - - public static string ReadErrorRetryRate => "Read Error Retry Rate"; - - public static string ReadFailure => "Read Failure"; - - public static string ReallocatedSectorsCount => "Reallocated Sectors Count"; - - public static string ReallocationEventCount => "Reallocation Event Count"; - - public static string RecalibrationRetries => "Recalibration Retries"; - - public static string RemainingLife => "Remaining Life"; - - public static string ReportedUncorrectableErrors => "Reported Uncorrectable Errors"; - - public static string RetiredBlockCount => "Retired Block Count"; - - public static string RunOutCancel => "Run Out Cancel"; - - public static string RuntimeBadBlockTotal => "Runtime Bad Block Total"; - - public static string SataDownshiftErrorCount => "SATA Downshift Error Count"; - - public static string SataErrorCountCrc => "SATA Error Count CRC"; - - public static string SataErrorCountHandshake => "SATA Error Count Handshake"; - - public static string SectorsRead => "Sectors Read"; - - public static string SectorsWritten => "Sectors Written"; - - public static string SeekErrorRate => "Seek Error Rate"; - - public static string SeekTimePerformance => "Seek Time Performance"; - - public static string ShockDuringWrite => "Shock During Write"; - - public static string SoftEccCorrection => "Soft ECC Correction"; - - public static string SoftReadErrorRate => "Soft Read Error Rate"; - - public static string SpinBuzz => "Spin Buzz"; - - public static string SpinHighCurrent => "Spin High Current"; - - public static string SpinRetryCount => "Spin Retry Count"; - - public static string SpinUpTime => "Spin-Up Time"; - - public static string StartStopCount => "Start/Stop Count"; - - public static string SupercapStatus => "Supercap Status"; - - public static string TaCounterDetected => "TA Counter Detected"; - - public static string Temperature => "Temperature"; - - public static string TemperatureDifferenceFrom100 => "Temperature Difference from 100"; - - public static string TemperatureExceedCount => "Temperature Exceed Count"; - - public static string ThermalAsperityRate => "Thermal Asperity Rate (TAR)"; - - public static string ThroughputPerformance => "Throughput Performance"; - - public static string TorqueAmplificationCount => "Torque Amplification Count"; - - public static string TotalLbasRead => "Total LBAs Read"; - - public static string TotalLbasWritten => "Total LBAs Written"; - - public static string TransferErrorRate => "Transfer Error Rate"; - - public static string UltraDmaCrcErrorCount => "UltraDMA CRC Error Count"; - - public static string UncorrectableErrorCount => "Uncorrectable Error Count"; - - public static string UncorrectableSectorCount => "Uncorrectable Sector Count"; - - public static string UnexpectedPowerLossCount => "Unexpected Power Loss Count"; - - public static string Unknown => "Unknown"; - - public static string UnknownUnique => "Unknown Unique"; - - public static string UnrecoverableEcc => "Unrecoverable ECC"; - - public static string UnsafeShutdownCount => "Unsafe Shutdown Count"; - - public static string UsedReservedBlockCountChip => "Used Reserved Block Count (Chip)"; - - public static string UsedReservedBlockCountTotal => "Used Reserved Block Count (Total)"; - - public static string VibrationDuringWrite => "Vibration During Write"; - - public static string WearLevelingCount => "Wear Leveling Count"; - - public static string WearRangeDelta => "Wear Range Delta"; - - public static string WriteCommands => "Write Commands"; - - public static string WriteErrorRate => "Write Error Rate"; - } -} \ No newline at end of file diff --git a/Hardware/HDD/StorageGeneric.cs b/Hardware/HDD/StorageGeneric.cs deleted file mode 100644 index ebaa278..0000000 --- a/Hardware/HDD/StorageGeneric.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Text; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal sealed class StorageGeneric : AbstractStorage { - private StorageGeneric(StorageInfo storageInfo, string name, string firmwareRevision, int index, ISettings settings) - : base(storageInfo, name, firmwareRevision, "hdd", index, settings) { - CreateSensors(); - } - - public static AbstractStorage CreateInstance(StorageInfo info, ISettings settings) { - string name = string.IsNullOrEmpty(info.Name) ? "Generic Hard Disk" : info.Name; - string firmwareRevision = string.IsNullOrEmpty(info.Revision) ? "Unknown" : info.Revision; - return new StorageGeneric(info, name, firmwareRevision, info.Index, settings); - } - - protected override void UpdateSensors() { } - - protected override void GetReport(StringBuilder r) { } - } -} \ No newline at end of file diff --git a/Hardware/HDD/StorageInfo.cs b/Hardware/HDD/StorageInfo.cs deleted file mode 100644 index 29f0798..0000000 --- a/Hardware/HDD/StorageInfo.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal abstract class StorageInfo { - public Kernel32.STORAGE_BUS_TYPE BusType { get; protected set; } - - public string DeviceId { get; set; } - - public ulong DiskSize { get; set; } - - public int Index { get; protected set; } - - public string Name => (Vendor + " " + Product).Trim(); - - public string Product { get; protected set; } - - public byte[] RawData { get; protected set; } - - public bool Removable { get; protected set; } - - public string Revision { get; protected set; } - - public string Scsi { get; set; } - - public string Serial { get; protected set; } - - public string Vendor { get; protected set; } - } -} \ No newline at end of file diff --git a/Hardware/HDD/WindowsSmart.cs b/Hardware/HDD/WindowsSmart.cs deleted file mode 100644 index 2fc9f7e..0000000 --- a/Hardware/HDD/WindowsSmart.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.IO; -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal class WindowsSmart : ISmart { - private readonly int driveNumber; - private readonly SafeHandle handle; - - public WindowsSmart(int driveNumber) { - this.driveNumber = driveNumber; - handle = Kernel32.CreateFile(@"\\.\PhysicalDrive" + driveNumber, - FileAccess.ReadWrite, - FileShare.ReadWrite, - IntPtr.Zero, - FileMode.Open, - FileAttributes.Normal, - IntPtr.Zero); - } - - public bool IsValid => !handle.IsInvalid; - - public void Dispose() { - Close(); - } - - public void Close() { - Dispose(true); - GC.SuppressFinalize(this); - } - - public bool EnableSmart() { - if (handle.IsClosed) - throw new ObjectDisposedException("WindowsATASmart"); - - - var parameter = new Kernel32.SENDCMDINPARAMS { - bDriveNumber = (byte) driveNumber, - irDriveRegs = { - bFeaturesReg = Kernel32.SMART_FEATURES.ENABLE_SMART, - bCylLowReg = Kernel32.SMART_LBA_MID, - bCylHighReg = Kernel32.SMART_LBA_HI, - bCommandReg = Kernel32.ATA_COMMAND.ATA_SMART - } - }; - - - return Kernel32.DeviceIoControl(handle, - Kernel32.DFP.DFP_SEND_DRIVE_COMMAND, - ref parameter, - Marshal.SizeOf(parameter), - out Kernel32.SENDCMDOUTPARAMS _, - Marshal.SizeOf(), - out _, - IntPtr.Zero); - } - - public Kernel32.SMART_ATTRIBUTE[] ReadSmartData() { - if (handle.IsClosed) - throw new ObjectDisposedException("WindowsATASmart"); - - - var parameter = new Kernel32.SENDCMDINPARAMS { - bDriveNumber = (byte) driveNumber, - irDriveRegs = { - bFeaturesReg = Kernel32.SMART_FEATURES.SMART_READ_DATA, - bCylLowReg = Kernel32.SMART_LBA_MID, - bCylHighReg = Kernel32.SMART_LBA_HI, - bCommandReg = Kernel32.ATA_COMMAND.ATA_SMART - } - }; - - - bool isValid = Kernel32.DeviceIoControl(handle, - Kernel32.DFP.DFP_RECEIVE_DRIVE_DATA, - ref parameter, - Marshal.SizeOf(parameter), - out Kernel32.ATTRIBUTECMDOUTPARAMS result, - Marshal.SizeOf(), - out _, - IntPtr.Zero); - - return (isValid) ? result.Attributes : new Kernel32.SMART_ATTRIBUTE[0]; - } - - public Kernel32.SMART_THRESHOLD[] ReadSmartThresholds() { - if (handle.IsClosed) - throw new ObjectDisposedException("WindowsATASmart"); - - - var parameter = new Kernel32.SENDCMDINPARAMS { - bDriveNumber = (byte) driveNumber, - irDriveRegs = { - bFeaturesReg = Kernel32.SMART_FEATURES.READ_THRESHOLDS, - bCylLowReg = Kernel32.SMART_LBA_MID, - bCylHighReg = Kernel32.SMART_LBA_HI, - bCommandReg = Kernel32.ATA_COMMAND.ATA_SMART - } - }; - - - bool isValid = Kernel32.DeviceIoControl(handle, - Kernel32.DFP.DFP_RECEIVE_DRIVE_DATA, - ref parameter, - Marshal.SizeOf(parameter), - out Kernel32.THRESHOLDCMDOUTPARAMS result, - Marshal.SizeOf(), - out _, - IntPtr.Zero); - - return (isValid) ? result.Thresholds : new Kernel32.SMART_THRESHOLD[0]; - } - - public bool ReadNameAndFirmwareRevision(out string name, out string firmwareRevision) { - if (handle.IsClosed) - throw new ObjectDisposedException("WindowsATASmart"); - - - var parameter = new Kernel32.SENDCMDINPARAMS { bDriveNumber = (byte) driveNumber, irDriveRegs = { bCommandReg = Kernel32.ATA_COMMAND.ATA_IDENTIFY_DEVICE } }; - - - bool valid = Kernel32.DeviceIoControl(handle, - Kernel32.DFP.DFP_RECEIVE_DRIVE_DATA, - ref parameter, - Marshal.SizeOf(parameter), - out Kernel32.IDENTIFYCMDOUTPARAMS result, - Marshal.SizeOf(), - out _, - IntPtr.Zero); - - if (!valid) { - name = null; - firmwareRevision = null; - return false; - } - - name = GetString(result.Identify.ModelNumber); - firmwareRevision = GetString(result.Identify.FirmwareRevision); - return true; - } - - protected void Dispose(bool disposing) { - if (disposing) { - if (!handle.IsClosed) - handle.Close(); - } - } - - private string GetString(byte[] bytes) { - char[] chars = new char[bytes.Length]; - for (int i = 0; i < bytes.Length; i += 2) { - chars[i] = (char) bytes[i + 1]; - chars[i + 1] = (char) bytes[i]; - } - - return new string(chars).Trim(' ', '\0'); - } - } -} \ No newline at end of file diff --git a/Hardware/HDD/WindowsStorage.cs b/Hardware/HDD/WindowsStorage.cs deleted file mode 100644 index b28c73e..0000000 --- a/Hardware/HDD/WindowsStorage.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.Collections.Generic; -using System.Management; -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.HDD { - internal static class WindowsStorage { - public static HDD.StorageInfo GetStorageInfo(string deviceId, uint driveIndex) { - using (SafeHandle handle = Kernel32.OpenDevice(deviceId)) { - if (handle == null || handle.IsInvalid) - return null; - - - var query = new Kernel32.STORAGE_PROPERTY_QUERY { PropertyId = Kernel32.STORAGE_PROPERTY_ID.StorageDeviceProperty, QueryType = Kernel32.STORAGE_QUERY_TYPE.PropertyStandardQuery }; - - - if (!Kernel32.DeviceIoControl(handle, - Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, - ref query, - Marshal.SizeOf(query), - out var header, - Marshal.SizeOf(), - out _, - IntPtr.Zero)) - return null; - - - IntPtr descriptorPtr = Marshal.AllocHGlobal((int) header.Size); - try { - if (!Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_STORAGE_QUERY_PROPERTY, ref query, Marshal.SizeOf(query), descriptorPtr, header.Size, out _, IntPtr.Zero)) - return null; - - - return new StorageInfo((int) driveIndex, descriptorPtr); - } finally { - Marshal.FreeHGlobal(descriptorPtr); - } - } - } - - public static string[] GetLogicalDrives(int driveIndex) { - var list = new List(); - try { - using (var s = - new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskPartition " + "WHERE DiskIndex = " + driveIndex)) { - using (ManagementObjectCollection dpc = s.Get()) { - foreach (ManagementObject dp in dpc) { - using (ManagementObjectCollection ldc = dp.GetRelated("Win32_LogicalDisk")) { - foreach (ManagementBaseObject ld in ldc) { - list.Add(((string) ld["Name"]).TrimEnd(':')); - } - } - } - } - } - } catch { } - - return list.ToArray(); - } - - private class StorageInfo : HDD.StorageInfo { - public StorageInfo(int index, IntPtr descriptorPtr) { - Kernel32.STORAGE_DEVICE_DESCRIPTOR descriptor = Marshal.PtrToStructure(descriptorPtr); - Index = index; - Vendor = GetString(descriptorPtr, descriptor.VendorIdOffset); - Product = GetString(descriptorPtr, descriptor.ProductIdOffset); - Revision = GetString(descriptorPtr, descriptor.ProductRevisionOffset); - Serial = GetString(descriptorPtr, descriptor.SerialNumberOffset); - BusType = descriptor.BusType; - Removable = descriptor.RemovableMedia; - RawData = new byte[descriptor.Size]; - Marshal.Copy(descriptorPtr, RawData, 0, RawData.Length); - } - - private static string GetString(IntPtr descriptorPtr, uint offset) { - return (offset > 0) ? Marshal.PtrToStringAnsi(new IntPtr(descriptorPtr.ToInt64() + offset)).Trim() : string.Empty; - } - } - } -} \ No newline at end of file diff --git a/Hardware/Hardware.cs b/Hardware/Hardware.cs deleted file mode 100644 index d7697f1..0000000 --- a/Hardware/Hardware.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace OpenHardwareMonitor.Hardware -{ - public abstract class Hardware : IHardware { - - private readonly Identifier identifier; - protected readonly string name; - private string customName; - protected readonly ISettings settings; - protected readonly HashSet active = new HashSet(); - - public Hardware(string name, Identifier identifier, ISettings settings) { - this.settings = settings; - this.identifier = identifier; - this.name = name; - this.customName = settings.GetValue( - new Identifier(Identifier, "name").ToString(), name); - } - - public IHardware[] SubHardware { - get { return new IHardware[0]; } - } - - public virtual IHardware Parent { - get { return null; } - } - - public virtual ISensor[] Sensors { - get { return active.ToArray(); } - } - - protected virtual void ActivateSensor(ISensor sensor) { - if (active.Add(sensor)) - SensorAdded?.Invoke(sensor); - } - - protected virtual void DeactivateSensor(ISensor sensor) { - if (active.Remove(sensor)) - SensorRemoved?.Invoke(sensor); - } - - public string Name { - get { - return customName; - } - set { - if (!string.IsNullOrEmpty(value)) - customName = value; - else - customName = name; - settings.SetValue(new Identifier(Identifier, "name").ToString(), - customName); - } - } - - public Identifier Identifier { - get { - return identifier; - } - } - - #pragma warning disable 67 - public event SensorEventHandler SensorAdded; - public event SensorEventHandler SensorRemoved; - #pragma warning restore 67 - - - public abstract HardwareType HardwareType { get; } - - public virtual string GetReport() { - return null; - } - - public abstract void Update(); - - public event HardwareEventHandler Closing; - - public virtual void Close() { - if (Closing != null) - Closing(this); - } - - public void Accept(IVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("visitor"); - visitor.VisitHardware(this); - } - - public virtual void Traverse(IVisitor visitor) { - foreach (ISensor sensor in active) - sensor.Accept(visitor); - } - } -} diff --git a/Hardware/Heatmaster/Heatmaster.cs b/Hardware/Heatmaster/Heatmaster.cs deleted file mode 100644 index 10fb3e9..0000000 --- a/Hardware/Heatmaster/Heatmaster.cs +++ /dev/null @@ -1,275 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2011 Michael Möller - -*/ - -using System; -using System.Globalization; -using System.IO; -using System.IO.Ports; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; - -namespace OpenHardwareMonitor.Hardware.Heatmaster { - internal class Heatmaster : Hardware, IDisposable { - - private readonly string portName; - private SerialPort serialPort; - - private readonly int hardwareRevision; - private readonly int firmwareRevision; - private readonly int firmwareCRC; - - private readonly Sensor[] fans; - private readonly Sensor[] controls; - private readonly Sensor[] temperatures; - private readonly Sensor[] flows; - private readonly Sensor[] relays; - - private readonly bool available; - - private readonly StringBuilder buffer = new StringBuilder(); - - private string ReadLine(int timeout) { - int i = 0; - StringBuilder builder = new StringBuilder(); - while (i <= timeout) { - while (serialPort.BytesToRead > 0) { - byte b = (byte)serialPort.ReadByte(); - switch (b) { - case 0xAA: return ((char)b).ToString(); - case 0x0D: return builder.ToString(); - default: builder.Append((char)b); break; - } - } - i++; - Thread.Sleep(1); - } - throw new TimeoutException(); - } - - private string ReadField(int device, char field) { - serialPort.WriteLine("[0:" + device + "]R" + field); - for (int i = 0; i < 5; i++) { - string s = ReadLine(200); - Match match = Regex.Match(s, @"-\[0:" + - device.ToString(CultureInfo.InvariantCulture) + @"\]R" + - Regex.Escape(field.ToString(CultureInfo.InvariantCulture)) + ":(.*)"); - if (match.Success) - return match.Groups[1].Value; - } - return null; - } - - protected string ReadString(int device, char field) { - string s = ReadField(device, field); - if (s != null && s[0] == '"' && s[s.Length - 1] == '"') - return s.Substring(1, s.Length - 2); - else - return null; - } - - protected int ReadInteger(int device, char field) { - string s = ReadField(device, field); - int i; - if (int.TryParse(s, out i)) - return i; - else - return 0; - } - - private bool WriteField(int device, char field, string value) { - serialPort.WriteLine("[0:" + device + "]W" + field + ":" + value); - for (int i = 0; i < 5; i++) { - string s = ReadLine(200); - Match match = Regex.Match(s, @"-\[0:" + - device.ToString(CultureInfo.InvariantCulture) + @"\]W" + - Regex.Escape(field.ToString(CultureInfo.InvariantCulture)) + - ":" + value); - if (match.Success) - return true; - } - return false; - } - - protected bool WriteInteger(int device, char field, int value) { - return WriteField(device, field, - value.ToString(CultureInfo.InvariantCulture)); - } - - protected bool WriteString(int device, char field, string value) { - return WriteField(device, field, '"' + value + '"'); - } - - public Heatmaster(string portName, ISettings settings) - : base("Heatmaster", new Identifier("heatmaster", - portName.TrimStart(new [] {'/'}).ToLowerInvariant()), settings) - { - this.portName = portName; - try { - serialPort = new SerialPort(portName, 38400, Parity.None, 8, - StopBits.One); - serialPort.Open(); - serialPort.NewLine = ((char)0x0D).ToString(); - - hardwareRevision = ReadInteger(0, 'H'); - firmwareRevision = ReadInteger(0, 'V'); - firmwareCRC = ReadInteger(0, 'C'); - - int fanCount = Math.Min(ReadInteger(32, '?'), 4); - int temperatureCount = Math.Min(ReadInteger(48, '?'), 6); - int flowCount = Math.Min(ReadInteger(64, '?'), 1); - int relayCount = Math.Min(ReadInteger(80, '?'), 1); - - fans = new Sensor[fanCount]; - controls = new Sensor[fanCount]; - for (int i = 0; i < fanCount; i++) { - int device = 33 + i; - string name = ReadString(device, 'C'); - fans[i] = new Sensor(name, device, SensorType.Fan, this, settings); - fans[i].Value = ReadInteger(device, 'R'); - ActivateSensor(fans[i]); - controls[i] = - new Sensor(name, device, SensorType.Control, this, settings); - controls[i].Value = (100 / 255.0f) * ReadInteger(device, 'P'); - ActivateSensor(controls[i]); - } - - temperatures = new Sensor[temperatureCount]; - for (int i = 0; i < temperatureCount; i++) { - int device = 49 + i; - string name = ReadString(device, 'C'); - temperatures[i] = - new Sensor(name, device, SensorType.Temperature, this, settings); - int value = ReadInteger(device, 'T'); - temperatures[i].Value = 0.1f * value; - if (value != -32768) - ActivateSensor(temperatures[i]); - } - - flows = new Sensor[flowCount]; - for (int i = 0; i < flowCount; i++) { - int device = 65 + i; - string name = ReadString(device, 'C'); - flows[i] = new Sensor(name, device, SensorType.Flow, this, settings); - flows[i].Value = 0.1f * ReadInteger(device, 'L'); - ActivateSensor(flows[i]); - } - - relays = new Sensor[relayCount]; - for (int i = 0; i < relayCount; i++) { - int device = 81 + i; - string name = ReadString(device, 'C'); - relays[i] = - new Sensor(name, device, SensorType.Control, this, settings); - relays[i].Value = 100 * ReadInteger(device, 'S'); - ActivateSensor(relays[i]); - } - - // set the update rate to 2 Hz - WriteInteger(0, 'L', 2); - - available = true; - - } catch (IOException) { } catch (TimeoutException) { } - } - - public override HardwareType HardwareType { - get { return HardwareType.Heatmaster; } - } - - private void ProcessUpdateLine(string line) { - Match match = Regex.Match(line, @">\[0:(\d+)\]([0-9:\|-]+)"); - if (match.Success) { - int device; - if (int.TryParse(match.Groups[1].Value, out device)) { - foreach (string s in match.Groups[2].Value.Split('|')) { - string[] strings = s.Split(':'); - int[] ints = new int[strings.Length]; - bool valid = true; - for (int i = 0; i < ints.Length; i++) - if (!int.TryParse(strings[i], out ints[i])) { - valid = false; - break; - } - if (!valid) - continue; - switch (device) { - case 32: - if (ints.Length == 3 && ints[0] <= fans.Length) { - fans[ints[0] - 1].Value = ints[1]; - controls[ints[0] - 1].Value = (100 / 255.0f) * ints[2]; - } - break; - case 48: - if (ints.Length == 2 && ints[0] <= temperatures.Length) - temperatures[ints[0] - 1].Value = 0.1f * ints[1]; - break; - case 64: - if (ints.Length == 3 && ints[0] <= flows.Length) - flows[ints[0] - 1].Value = 0.1f * ints[1]; - break; - case 80: - if (ints.Length == 2 && ints[0] <= relays.Length) - relays[ints[0] - 1].Value = 100 * ints[1]; - break; - } - } - } - } - } - - public override void Update() { - if (!available) - return; - - while (serialPort.IsOpen && serialPort.BytesToRead > 0) { - byte b = (byte)serialPort.ReadByte(); - if (b == 0x0D) { - ProcessUpdateLine(buffer.ToString()); - buffer.Length = 0; - } else { - buffer.Append((char)b); - } - } - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("Heatmaster"); - r.AppendLine(); - r.Append("Port: "); - r.AppendLine(portName); - r.Append("Hardware Revision: "); - r.AppendLine(hardwareRevision.ToString(CultureInfo.InvariantCulture)); - r.Append("Firmware Revision: "); - r.AppendLine(firmwareRevision.ToString(CultureInfo.InvariantCulture)); - r.Append("Firmware CRC: "); - r.AppendLine(firmwareCRC.ToString(CultureInfo.InvariantCulture)); - r.AppendLine(); - - return r.ToString(); - } - - public override void Close() { - serialPort.Close(); - serialPort.Dispose(); - serialPort = null; - base.Close(); - } - - public void Dispose() { - if (serialPort != null) { - serialPort.Dispose(); - serialPort = null; - } - } - } -} diff --git a/Hardware/Heatmaster/HeatmasterGroup.cs b/Hardware/Heatmaster/HeatmasterGroup.cs deleted file mode 100644 index dc927d9..0000000 --- a/Hardware/Heatmaster/HeatmasterGroup.cs +++ /dev/null @@ -1,167 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO.Ports; -using System.Security; -using System.Text; -using System.Threading; -using Microsoft.Win32; - -namespace OpenHardwareMonitor.Hardware.Heatmaster { - internal class HeatmasterGroup : IGroup { - - private readonly List hardware = new List(); - private readonly StringBuilder report = new StringBuilder(); - - private static string ReadLine(SerialPort port, int timeout) { - int i = 0; - StringBuilder builder = new StringBuilder(); - while (i < timeout) { - while (port.BytesToRead > 0) { - byte b = (byte)port.ReadByte(); - switch (b) { - case 0xAA: return ((char)b).ToString(); - case 0x0D: return builder.ToString(); - default: builder.Append((char)b); break; - } - } - i++; - Thread.Sleep(1); - } - throw new TimeoutException(); - } - - private static string[] GetRegistryPortNames() { - List result = new List(); - string[] paths = { "", "&MI_00" }; - try { - foreach (string path in paths) { - RegistryKey key = Registry.LocalMachine.OpenSubKey( - @"SYSTEM\CurrentControlSet\Enum\USB\VID_10C4&PID_EA60" + path); - if (key != null) { - foreach (string subKeyName in key.GetSubKeyNames()) { - RegistryKey subKey = - key.OpenSubKey(subKeyName + "\\" + "Device Parameters"); - if (subKey != null) { - string name = subKey.GetValue("PortName") as string; - if (name != null && !result.Contains(name)) - result.Add(name); - } - } - } - } - } catch (SecurityException) { } - return result.ToArray(); - } - - public HeatmasterGroup(ISettings settings) { - - // No implementation for Heatmaster on Unix systems - if (Software.OperatingSystem.IsLinux) return; - - string[] portNames = GetRegistryPortNames(); - for (int i = 0; i < portNames.Length; i++) { - bool isValid = false; - try { - using (SerialPort serialPort = - new SerialPort(portNames[i], 38400, Parity.None, 8, StopBits.One)) { - serialPort.NewLine = ((char)0x0D).ToString(); - report.Append("Port Name: "); report.AppendLine(portNames[i]); - - try { - serialPort.Open(); - } catch (UnauthorizedAccessException) { - report.AppendLine("Exception: Access Denied"); - } - - if (serialPort.IsOpen) { - serialPort.DiscardInBuffer(); - serialPort.DiscardOutBuffer(); - serialPort.Write(new byte[] { 0xAA }, 0, 1); - - int j = 0; - while (serialPort.BytesToRead == 0 && j < 10) { - Thread.Sleep(20); - j++; - } - if (serialPort.BytesToRead > 0) { - bool flag = false; - while (serialPort.BytesToRead > 0 && !flag) { - flag |= (serialPort.ReadByte() == 0xAA); - } - if (flag) { - serialPort.WriteLine("[0:0]RH"); - try { - int k = 0; - int revision = 0; - while (k < 5) { - string line = ReadLine(serialPort, 100); - if (line.StartsWith("-[0:0]RH:", - StringComparison.Ordinal)) { - revision = int.Parse(line.Substring(9), - CultureInfo.InvariantCulture); - break; - } - k++; - } - isValid = (revision == 770); - if (!isValid) { - report.Append("Status: Wrong Hardware Revision " + - revision.ToString(CultureInfo.InvariantCulture)); - } - } catch (TimeoutException) { - report.AppendLine("Status: Timeout Reading Revision"); - } - } else { - report.AppendLine("Status: Wrong Startflag"); - } - } else { - report.AppendLine("Status: No Response"); - } - serialPort.DiscardInBuffer(); - } else { - report.AppendLine("Status: Port not Open"); - } - } - } catch (Exception e) { - report.AppendLine(e.ToString()); - } - - if (isValid) { - report.AppendLine("Status: OK"); - hardware.Add(new Heatmaster(portNames[i], settings)); - } - report.AppendLine(); - } - } - - public IEnumerable Hardware => hardware; - - public string GetReport() { - if (report.Length > 0) { - StringBuilder r = new StringBuilder(); - r.AppendLine("Serial Port Heatmaster"); - r.AppendLine(); - r.Append(report); - r.AppendLine(); - return r.ToString(); - } else - return null; - } - - public void Close() { - foreach (Heatmaster heatmaster in hardware) - heatmaster.Close(); - } - } -} diff --git a/Hardware/HexStringArray.cs b/Hardware/HexStringArray.cs deleted file mode 100644 index 15a4988..0000000 --- a/Hardware/HexStringArray.cs +++ /dev/null @@ -1,32 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System; - -namespace OpenHardwareMonitor.Hardware { - internal static class HexStringArray { - - public static byte Read(string s, ushort address) { - string[] lines = s.Split(new[] { '\r', '\n' }, - StringSplitOptions.RemoveEmptyEntries); - - foreach (string line in lines) { - string[] array = line.Split(new[] { ' ', '\t' }, - StringSplitOptions.RemoveEmptyEntries); - if (array.Length == 0) - continue; - if (Convert.ToInt32(array[0], 16) == (address & 0xFFF0)) - return Convert.ToByte(array[(address & 0x0F) + 1], 16); - } - - throw new ArgumentException(); - } - } -} diff --git a/Hardware/IComputer.cs b/Hardware/IComputer.cs deleted file mode 100644 index b3342db..0000000 --- a/Hardware/IComputer.cs +++ /dev/null @@ -1,33 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public delegate void HardwareEventHandler(IHardware hardware); - - public interface IComputer : IElement { - - IHardware[] Hardware { get; } - - bool MainboardEnabled { get; } - bool CPUEnabled { get; } - bool RAMEnabled { get; } - bool GPUEnabled { get; } - bool FanControllerEnabled { get; } - bool HDDEnabled { get; } - bool NICEnabled { get; } - - - string GetReport(); - - event HardwareEventHandler HardwareAdded; - event HardwareEventHandler HardwareRemoved; - } -} diff --git a/Hardware/IControl.cs b/Hardware/IControl.cs deleted file mode 100644 index ff5716f..0000000 --- a/Hardware/IControl.cs +++ /dev/null @@ -1,35 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2014 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public enum ControlMode { - Undefined, - Software, - Default - } - - public interface IControl { - - Identifier Identifier { get; } - - ControlMode ControlMode { get; } - - float SoftwareValue { get; } - - void SetDefault(); - - float MinSoftwareValue { get; } - float MaxSoftwareValue { get; } - - void SetSoftware(float value); - - } -} diff --git a/Hardware/IElement.cs b/Hardware/IElement.cs deleted file mode 100644 index acebaac..0000000 --- a/Hardware/IElement.cs +++ /dev/null @@ -1,21 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public interface IElement { - // accept visitor on this element - void Accept(IVisitor visitor); - - // call accept(visitor) on all child elements (called only from visitors) - void Traverse(IVisitor visitor); - } - -} diff --git a/Hardware/IGroup.cs b/Hardware/IGroup.cs deleted file mode 100644 index 29ad71e..0000000 --- a/Hardware/IGroup.cs +++ /dev/null @@ -1,24 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware { - - internal interface IGroup { - - IEnumerable Hardware { get; } - - string GetReport(); - - void Close(); - } - -} diff --git a/Hardware/IHardware.cs b/Hardware/IHardware.cs deleted file mode 100644 index 522a27c..0000000 --- a/Hardware/IHardware.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public delegate void SensorEventHandler(ISensor sensor); - - public enum HardwareType { - Mainboard, - SuperIO, - Aquacomputer, - CPU, - RAM, - GpuNvidia, - GpuAti, - TBalancer, - Heatmaster, - HDD, - NIC - } - - public interface IHardware : IElement { - - string Name { get; set; } - Identifier Identifier { get; } - - HardwareType HardwareType { get; } - - string GetReport(); - - void Update(); - - IHardware[] SubHardware { get; } - - IHardware Parent { get; } - - ISensor[] Sensors { get; } - - event SensorEventHandler SensorAdded; - event SensorEventHandler SensorRemoved; - } -} diff --git a/Hardware/IOControlCode.cs b/Hardware/IOControlCode.cs deleted file mode 100644 index 2376a66..0000000 --- a/Hardware/IOControlCode.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010 Michael Möller - -*/ - -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware { - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct IOControlCode { - private uint code; - - public IOControlCode(uint deviceType, uint function, Access access) : - this(deviceType, function, Method.Buffered, access) { } - - public IOControlCode(uint deviceType, uint function, Method method, - Access access) - { - code = (deviceType << 16) | - ((uint)access << 14) | (function << 2) | (uint)method; - } - - public enum Method : uint { - Buffered = 0, - InDirect = 1, - OutDirect = 2, - Neither = 3 - } - - public enum Access : uint { - Any = 0, - Read = 1, - Write = 2 - } - } -} diff --git a/Hardware/IParameter.cs b/Hardware/IParameter.cs deleted file mode 100644 index f31c3bc..0000000 --- a/Hardware/IParameter.cs +++ /dev/null @@ -1,24 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public interface IParameter : IElement { - - ISensor Sensor { get; } - Identifier Identifier { get; } - - string Name { get; } - string Description { get; } - float Value { get; set; } - float DefaultValue { get; } - bool IsDefault { get; set; } - } -} diff --git a/Hardware/ISensor.cs b/Hardware/ISensor.cs deleted file mode 100644 index 3a719a7..0000000 --- a/Hardware/ISensor.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware -{ - - public enum SensorType { - Voltage, // V - Clock, // MHz - Temperature, // °C - Load, // % - Frequency, // Hz - Fan, // RPM - Flow, // L/h - Control, // % - Level, // % - Factor, // 1 - Power, // W - Data, // GB = 2^30 Bytes - SmallData, // MB = 2^20 Bytes - Throughput, // B/s - } - - public struct SensorValue { - private readonly float value; - private readonly DateTime time; - - public SensorValue(float value, DateTime time) { - this.value = value; - this.time = time; - } - - public float Value { get { return value; } } - public DateTime Time { get { return time; } } - } - - public interface ISensor : IElement { - - IHardware Hardware { get; } - - SensorType SensorType { get; } - Identifier Identifier { get; } - - string Name { get; set; } - int Index { get; } - - bool IsDefaultHidden { get; } - - IReadOnlyList Parameters { get; } - - float? Value { get; } - float? Min { get; } - float? Max { get; } - - void ResetMin(); - void ResetMax(); - - IEnumerable Values { get; } - TimeSpan ValuesTimeWindow { get; set; } - - IControl Control { get; } - } - -} diff --git a/Hardware/ISettings.cs b/Hardware/ISettings.cs deleted file mode 100644 index c8ac595..0000000 --- a/Hardware/ISettings.cs +++ /dev/null @@ -1,22 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - public interface ISettings { - - bool Contains(string name); - - void SetValue(string name, string value); - - string GetValue(string name, string value); - - void Remove(string name); - } -} diff --git a/Hardware/IVisitor.cs b/Hardware/IVisitor.cs deleted file mode 100644 index f3b2ebf..0000000 --- a/Hardware/IVisitor.cs +++ /dev/null @@ -1,20 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware { - - public interface IVisitor { - void VisitComputer(IComputer computer); - void VisitHardware(IHardware hardware); - void VisitSensor(ISensor sensor); - void VisitParameter(IParameter parameter); - } - -} diff --git a/Hardware/Identifier.cs b/Hardware/Identifier.cs deleted file mode 100644 index 1205f10..0000000 --- a/Hardware/Identifier.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace OpenHardwareMonitor.Hardware { - public class Identifier : IComparable { - private readonly string identifier; - - private const char Separator = '/'; - - private static void CheckIdentifiers(IEnumerable identifiers) { - foreach (string s in identifiers) - if (s.Contains(" ") || s.Contains(Separator.ToString())) - throw new ArgumentException("Invalid identifier"); - } - - public Identifier(params string[] identifiers) { - CheckIdentifiers(identifiers); - - StringBuilder s = new StringBuilder(); - for (int i = 0; i < identifiers.Length; i++) { - s.Append(Separator); - s.Append(identifiers[i]); - } - this.identifier = s.ToString(); - } - - public Identifier(Identifier identifier, params string[] extensions) { - CheckIdentifiers(extensions); - - StringBuilder s = new StringBuilder(); - s.Append(identifier.ToString()); - for (int i = 0; i < extensions.Length; i++) { - s.Append(Separator); - s.Append(extensions[i]); - } - this.identifier = s.ToString(); - } - - public override string ToString() { - return identifier; - } - - public override bool Equals(Object obj) { - if (obj == null) - return false; - - Identifier id = obj as Identifier; - if (id == null) - return false; - - return (identifier == id.identifier); - } - - public override int GetHashCode() { - return identifier.GetHashCode(); - } - - public int CompareTo(Identifier other) { - if (other == null) - return 1; - else - return string.Compare(this.identifier, other.identifier, - StringComparison.Ordinal); - } - - public static bool operator ==(Identifier id1, Identifier id2) { - if (id1.Equals(null)) - return id2.Equals(null); - else - return id1.Equals(id2); - } - - public static bool operator !=(Identifier id1, Identifier id2) { - return !(id1 == id2); - } - - public static bool operator <(Identifier id1, Identifier id2) { - if (id1 == null) - return id2 != null; - else - return (id1.CompareTo(id2) < 0); - } - - public static bool operator >(Identifier id1, Identifier id2) { - if (id1 == null) - return false; - else - return (id1.CompareTo(id2) > 0); - } - - } -} diff --git a/Hardware/KernelDriver.cs b/Hardware/KernelDriver.cs deleted file mode 100644 index 8817487..0000000 --- a/Hardware/KernelDriver.cs +++ /dev/null @@ -1,298 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2012 Michael Möller - -*/ - -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using Microsoft.Win32.SafeHandles; - -namespace OpenHardwareMonitor.Hardware { - internal class KernelDriver { - - private string id; - - private SafeFileHandle device; - - public KernelDriver(string id) { - this.id = id; - } - - public bool Install(string path, out string errorMessage) { - IntPtr manager = NativeMethods.OpenSCManager(null, null, - ServiceControlManagerAccessRights.SC_MANAGER_ALL_ACCESS); - - if (manager == IntPtr.Zero) { - errorMessage = "OpenSCManager returned zero."; - return false; - } - - IntPtr service = NativeMethods.CreateService(manager, id, id, - ServiceAccessRights.SERVICE_ALL_ACCESS, - ServiceType.SERVICE_KERNEL_DRIVER, StartType.SERVICE_DEMAND_START, - ErrorControl.SERVICE_ERROR_NORMAL, path, null, null, null, null, - null); - - if (service == IntPtr.Zero) { - if (Marshal.GetHRForLastWin32Error() == ERROR_SERVICE_EXISTS) { - errorMessage = "Service already exists"; - return false; - } else { - errorMessage = "CreateService returned the error: " + - Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message; - NativeMethods.CloseServiceHandle(manager); - return false; - } - } - - if (!NativeMethods.StartService(service, 0, null)) { - if (Marshal.GetHRForLastWin32Error() != ERROR_SERVICE_ALREADY_RUNNING) { - errorMessage = "StartService returned the error: " + - Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message; - NativeMethods.CloseServiceHandle(service); - NativeMethods.CloseServiceHandle(manager); - return false; - } - } - - NativeMethods.CloseServiceHandle(service); - NativeMethods.CloseServiceHandle(manager); - -#if !NETSTANDARD2_0 - try { - // restrict the driver access to system (SY) and builtin admins (BA) - // TODO: replace with a call to IoCreateDeviceSecure in the driver - FileSecurity fileSecurity = File.GetAccessControl(@"\\.\" + id); - fileSecurity.SetSecurityDescriptorSddlForm( - "O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)"); - File.SetAccessControl(@"\\.\" + id, fileSecurity); - } catch { } -#endif - errorMessage = null; - return true; - } - - - public bool Open() { - device = new SafeFileHandle(NativeMethods.CreateFile(@"\\.\" + id, - FileAccess.GENERIC_READ | FileAccess.GENERIC_WRITE, 0, IntPtr.Zero, - CreationDisposition.OPEN_EXISTING, FileAttributes.FILE_ATTRIBUTE_NORMAL, - IntPtr.Zero), true); - - if (device.IsInvalid) { - device.Close(); - device.Dispose(); - device = null; - } - - return device != null; - } - - public bool IsOpen { - get { return device != null; } - } - - public bool DeviceIOControl(IOControlCode ioControlCode, object inBuffer) { - if (device == null) - return false; - - uint bytesReturned; - bool b = NativeMethods.DeviceIoControl(device, ioControlCode, - inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer), - null, 0, out bytesReturned, IntPtr.Zero); - return b; - } - - public bool DeviceIOControl(IOControlCode ioControlCode, object inBuffer, - ref T outBuffer) - { - if (device == null) - return false; - - object boxedOutBuffer = outBuffer; - uint bytesReturned; - bool b = NativeMethods.DeviceIoControl(device, ioControlCode, - inBuffer, inBuffer == null ? 0 : (uint)Marshal.SizeOf(inBuffer), - boxedOutBuffer, (uint)Marshal.SizeOf(boxedOutBuffer), - out bytesReturned, IntPtr.Zero); - outBuffer = (T)boxedOutBuffer; - return b; - } - - public void Close() { - if (device != null) { - device.Close(); - device.Dispose(); - device = null; - } - } - - public bool Delete() { - IntPtr manager = NativeMethods.OpenSCManager(null, null, - ServiceControlManagerAccessRights.SC_MANAGER_ALL_ACCESS); - - if (manager == IntPtr.Zero) - return false; - - IntPtr service = NativeMethods.OpenService(manager, id, - ServiceAccessRights.SERVICE_ALL_ACCESS); - - if (service == IntPtr.Zero) - return true; - - ServiceStatus status = new ServiceStatus(); - NativeMethods.ControlService(service, ServiceControl.SERVICE_CONTROL_STOP, - ref status); - - NativeMethods.DeleteService(service); - - NativeMethods.CloseServiceHandle(service); - NativeMethods.CloseServiceHandle(manager); - - return true; - } - - private enum ServiceAccessRights : uint { - SERVICE_ALL_ACCESS = 0xF01FF - } - - private enum ServiceControlManagerAccessRights : uint { - SC_MANAGER_ALL_ACCESS = 0xF003F - } - - private enum ServiceType : uint { - SERVICE_KERNEL_DRIVER = 1, - SERVICE_FILE_SYSTEM_DRIVER = 2 - } - - private enum StartType : uint { - SERVICE_BOOT_START = 0, - SERVICE_SYSTEM_START = 1, - SERVICE_AUTO_START = 2, - SERVICE_DEMAND_START = 3, - SERVICE_DISABLED = 4 - } - - private enum ErrorControl : uint { - SERVICE_ERROR_IGNORE = 0, - SERVICE_ERROR_NORMAL = 1, - SERVICE_ERROR_SEVERE = 2, - SERVICE_ERROR_CRITICAL = 3 - } - - private enum ServiceControl : uint { - SERVICE_CONTROL_STOP = 1, - SERVICE_CONTROL_PAUSE = 2, - SERVICE_CONTROL_CONTINUE = 3, - SERVICE_CONTROL_INTERROGATE = 4, - SERVICE_CONTROL_SHUTDOWN = 5, - SERVICE_CONTROL_PARAMCHANGE = 6, - SERVICE_CONTROL_NETBINDADD = 7, - SERVICE_CONTROL_NETBINDREMOVE = 8, - SERVICE_CONTROL_NETBINDENABLE = 9, - SERVICE_CONTROL_NETBINDDISABLE = 10, - SERVICE_CONTROL_DEVICEEVENT = 11, - SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12, - SERVICE_CONTROL_POWEREVENT = 13, - SERVICE_CONTROL_SESSIONCHANGE = 14 - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct ServiceStatus { - public uint dwServiceType; - public uint dwCurrentState; - public uint dwControlsAccepted; - public uint dwWin32ExitCode; - public uint dwServiceSpecificExitCode; - public uint dwCheckPoint; - public uint dwWaitHint; - } - - private enum FileAccess : uint { - GENERIC_READ = 0x80000000, - GENERIC_WRITE = 0x40000000 - } - - private enum CreationDisposition : uint { - CREATE_NEW = 1, - CREATE_ALWAYS = 2, - OPEN_EXISTING = 3, - OPEN_ALWAYS = 4, - TRUNCATE_EXISTING = 5 - } - - private enum FileAttributes : uint { - FILE_ATTRIBUTE_NORMAL = 0x80 - } - - private const int - ERROR_SERVICE_EXISTS = unchecked((int)0x80070431), - ERROR_SERVICE_ALREADY_RUNNING = unchecked((int)0x80070420); - - private static class NativeMethods { - private const string ADVAPI = "advapi32.dll"; - private const string KERNEL = "kernel32.dll"; - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi)] - public static extern IntPtr OpenSCManager(string machineName, - string databaseName, ServiceControlManagerAccessRights dwAccess); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool CloseServiceHandle(IntPtr hSCObject); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - public static extern IntPtr CreateService(IntPtr hSCManager, - string lpServiceName, string lpDisplayName, - ServiceAccessRights dwDesiredAccess, ServiceType dwServiceType, - StartType dwStartType, ErrorControl dwErrorControl, - string lpBinaryPathName, string lpLoadOrderGroup, string lpdwTagId, - string lpDependencies, string lpServiceStartName, string lpPassword); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - public static extern IntPtr OpenService(IntPtr hSCManager, - string lpServiceName, ServiceAccessRights dwDesiredAccess); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool DeleteService(IntPtr hService); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool StartService(IntPtr hService, - uint dwNumServiceArgs, string[] lpServiceArgVectors); - - [DllImport(ADVAPI, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool ControlService(IntPtr hService, - ServiceControl dwControl, ref ServiceStatus lpServiceStatus); - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] - public static extern bool DeviceIoControl(SafeFileHandle device, - IOControlCode ioControlCode, - [MarshalAs(UnmanagedType.AsAny)] [In] object inBuffer, - uint inBufferSize, - [MarshalAs(UnmanagedType.AsAny)] [Out] object outBuffer, - uint nOutBufferSize, out uint bytesReturned, IntPtr overlapped); - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi, - SetLastError = true)] - public static extern IntPtr CreateFile(string lpFileName, - FileAccess dwDesiredAccess, uint dwShareMode, - IntPtr lpSecurityAttributes, CreationDisposition dwCreationDisposition, - FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); - } - } -} diff --git a/Hardware/LPC/Chip.cs b/Hardware/LPC/Chip.cs deleted file mode 100644 index 89bd226..0000000 --- a/Hardware/LPC/Chip.cs +++ /dev/null @@ -1,130 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.LPC { - - internal enum Chip : ushort { - Unknown = 0, - - ATK0110 = 0x0110, - - F71858 = 0x0507, - F71862 = 0x0601, - F71869 = 0x0814, - F71869A = 0x1007, - F71878AD = 0x1106, - F71882 = 0x0541, - F71889AD = 0x1005, - F71889ED = 0x0909, - F71889F = 0x0723, - F71808E = 0x0901, - - IT8620E = 0x8620, - IT8628E = 0x8628, - IT8665E = 0x8665, - IT8686E = 0x8686, - IT8688E = 0x8688, - IT8705F = 0x8705, - IT8712F = 0x8712, - IT8716F = 0x8716, - IT8718F = 0x8718, - IT8720F = 0x8720, - IT8721F = 0x8721, - IT8726F = 0x8726, - IT8728F = 0x8728, - IT8771E = 0x8771, - IT8772E = 0x8772, - - NCT6771F = 0xB470, - NCT6776F = 0xC330, - NCT610X = 0xC452, - NCT6779D = 0xC560, - NCT6791D = 0xC803, - NCT6792D = 0xC911, - NCT6793D = 0xD121, - NCT6795D = 0xD352, - NCT6796D = 0xD423, - NCT6797D = 0xD451, - NCT6798D = 0xD42B, - - W83627DHG = 0xA020, - W83627DHGP = 0xB070, - W83627EHF = 0x8800, - W83627HF = 0x5200, - W83627THF = 0x8280, - W83667HG = 0xA510, - W83667HGB = 0xB350, - W83687THF = 0x8541 - } - - internal class ChipName { - - private ChipName() { } - - public static string GetName(Chip chip) { - switch (chip) { - case Chip.ATK0110: return "Asus ATK0110"; - - case Chip.F71858: return "Fintek F71858"; - case Chip.F71862: return "Fintek F71862"; - case Chip.F71869: return "Fintek F71869"; - case Chip.F71878AD: return "Fintek F71878AD"; - case Chip.F71869A: return "Fintek F71869A"; - case Chip.F71882: return "Fintek F71882"; - case Chip.F71889AD: return "Fintek F71889AD"; - case Chip.F71889ED: return "Fintek F71889ED"; - case Chip.F71889F: return "Fintek F71889F"; - case Chip.F71808E: return "Fintek F71808E"; - - case Chip.IT8620E: return "ITE IT8620E"; - case Chip.IT8628E: return "ITE IT8628E"; - case Chip.IT8665E: return "ITE IT8665E"; - case Chip.IT8686E: return "ITE IT8686E"; - case Chip.IT8688E: return "ITE IT8688E"; - case Chip.IT8705F: return "ITE IT8705F"; - case Chip.IT8712F: return "ITE IT8712F"; - case Chip.IT8716F: return "ITE IT8716F"; - case Chip.IT8718F: return "ITE IT8718F"; - case Chip.IT8720F: return "ITE IT8720F"; - case Chip.IT8721F: return "ITE IT8721F"; - case Chip.IT8726F: return "ITE IT8726F"; - case Chip.IT8728F: return "ITE IT8728F"; - case Chip.IT8771E: return "ITE IT8771E"; - case Chip.IT8772E: return "ITE IT8772E"; - - case Chip.NCT610X: return "Nuvoton NCT610X"; - - case Chip.NCT6771F: return "Nuvoton NCT6771F"; - case Chip.NCT6776F: return "Nuvoton NCT6776F"; - case Chip.NCT6779D: return "Nuvoton NCT6779D"; - case Chip.NCT6791D: return "Nuvoton NCT6791D"; - case Chip.NCT6792D: return "Nuvoton NCT6792D"; - case Chip.NCT6793D: return "Nuvoton NCT6793D"; - case Chip.NCT6795D: return "Nuvoton NCT6795D"; - case Chip.NCT6796D: return "Nuvoton NCT6796D"; - case Chip.NCT6797D: return "Nuvoton NCT6797D"; - case Chip.NCT6798D: return "Nuvoton NCT6798D"; - - case Chip.W83627DHG: return "Winbond W83627DHG"; - case Chip.W83627DHGP: return "Winbond W83627DHG-P"; - case Chip.W83627EHF: return "Winbond W83627EHF"; - case Chip.W83627HF: return "Winbond W83627HF"; - case Chip.W83627THF: return "Winbond W83627THF"; - case Chip.W83667HG: return "Winbond W83667HG"; - case Chip.W83667HGB: return "Winbond W83667HG-B"; - case Chip.W83687THF: return "Winbond W83687THF"; - - case Chip.Unknown: return "Unkown"; - default: return "Unknown"; - } - } - } - -} diff --git a/Hardware/LPC/F718XX.cs b/Hardware/LPC/F718XX.cs deleted file mode 100644 index e737c6e..0000000 --- a/Hardware/LPC/F718XX.cs +++ /dev/null @@ -1,177 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.LPC { - internal class F718XX : ISuperIO { - - private readonly ushort address; - private readonly Chip chip; - - private readonly float?[] voltages; - private readonly float?[] temperatures; - private readonly float?[] fans; - private readonly float?[] controls; - - // Hardware Monitor - private const byte ADDRESS_REGISTER_OFFSET = 0x05; - private const byte DATA_REGISTER_OFFSET = 0x06; - - private const byte PWM_VALUES_OFFSET = 0x2D; - - // Hardware Monitor Registers - private const byte VOLTAGE_BASE_REG = 0x20; - private const byte TEMPERATURE_CONFIG_REG = 0x69; - private const byte TEMPERATURE_BASE_REG = 0x70; - private readonly byte[] FAN_TACHOMETER_REG = - new byte[] { 0xA0, 0xB0, 0xC0, 0xD0 }; - private readonly byte[] FAN_PWM_REG = - new byte[] { 0xA3, 0xB3, 0xC3, 0xD3 }; - - private byte ReadByte(byte register) { - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), register); - return Ring0.ReadIoPort((ushort)(address + DATA_REGISTER_OFFSET)); - } - private void WriteByte(byte register, byte value) { - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), register); - Ring0.WriteIoPort((ushort)(address + DATA_REGISTER_OFFSET), value); - } - - public byte? ReadGPIO(int index) { - return null; - } - - public void WriteGPIO(int index, byte value) { } - - public void SetControl(int index, byte? value) { - if(index < controls.Length) - WriteByte(FAN_PWM_REG[index], value ?? 128); - } - - public F718XX(Chip chip, ushort address) { - this.address = address; - this.chip = chip; - - voltages = new float?[chip == Chip.F71858 ? 3 : 9]; - temperatures = new float?[chip == Chip.F71808E ? 2 : 3]; - fans = new float?[chip == Chip.F71882 || chip == Chip.F71858 ? 4 : 3]; - controls = new float?[chip == Chip.F71878AD ? 3 : 0]; - } - - public Chip Chip { get { return chip; } } - public float?[] Voltages { get { return voltages; } } - public float?[] Temperatures { get { return temperatures; } } - public float?[] Fans { get { return fans; } } - public float?[] Controls { get { return controls; } } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("LPC " + this.GetType().Name); - r.AppendLine(); - r.Append("Base Adress: 0x"); - r.AppendLine(address.ToString("X4", CultureInfo.InvariantCulture)); - r.AppendLine(); - - if (!Ring0.WaitIsaBusMutex(100)) - return r.ToString(); - - r.AppendLine("Hardware Monitor Registers"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - for (int i = 0; i <= 0xF; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X2", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - r.Append(" "); - r.Append(ReadByte((byte)((i << 4) | j)).ToString("X2", - CultureInfo.InvariantCulture)); - } - r.AppendLine(); - } - r.AppendLine(); - - Ring0.ReleaseIsaBusMutex(); - - return r.ToString(); - } - - public void Update() { - if (!Ring0.WaitIsaBusMutex(10)) - return; - - for (int i = 0; i < voltages.Length; i++) { - if (chip == Chip.F71808E && i == 6) { - // 0x26 is reserved on F71808E - voltages[i] = 0; - } else { - int value = ReadByte((byte)(VOLTAGE_BASE_REG + i)); - voltages[i] = 0.008f * value; - } - } - - for (int i = 0; i < temperatures.Length; i++) { - switch (chip) { - case Chip.F71858: { - int tableMode = 0x3 & ReadByte(TEMPERATURE_CONFIG_REG); - int high = - ReadByte((byte)(TEMPERATURE_BASE_REG + 2 * i)); - int low = - ReadByte((byte)(TEMPERATURE_BASE_REG + 2 * i + 1)); - if (high != 0xbb && high != 0xcc) { - int bits = 0; - switch (tableMode) { - case 0: bits = 0; break; - case 1: bits = 0; break; - case 2: bits = (high & 0x80) << 8; break; - case 3: bits = (low & 0x01) << 15; break; - } - bits |= high << 7; - bits |= (low & 0xe0) >> 1; - short value = (short)(bits & 0xfff0); - temperatures[i] = value / 128.0f; - } else { - temperatures[i] = null; - } - } break; - default: { - sbyte value = (sbyte)ReadByte((byte)( - TEMPERATURE_BASE_REG + 2 * (i + 1))); - if (value < sbyte.MaxValue && value > 0) - temperatures[i] = value; - else - temperatures[i] = null; - } break; - } - } - - for (int i = 0; i < fans.Length; i++) { - int value = ReadByte(FAN_TACHOMETER_REG[i]) << 8; - value |= ReadByte((byte)(FAN_TACHOMETER_REG[i] + 1)); - - if (value > 0) - fans[i] = (value < 0x0fff) ? 1.5e6f / value : 0; - else - fans[i] = null; - } - for (int i = 0; i < controls.Length; i++) { - controls[i] = (100*ReadByte((byte)(PWM_VALUES_OFFSET + i)))/256.0f; - } - - Ring0.ReleaseIsaBusMutex(); - } - } -} diff --git a/Hardware/LPC/ISuperIO.cs b/Hardware/LPC/ISuperIO.cs deleted file mode 100644 index 50d4453..0000000 --- a/Hardware/LPC/ISuperIO.cs +++ /dev/null @@ -1,33 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.LPC { - internal interface ISuperIO { - - Chip Chip { get; } - - // get voltage, temperature, fan and control channel values - float?[] Voltages { get; } - float?[] Temperatures { get; } - float?[] Fans { get; } - float?[] Controls { get; } - - // set control value, null = auto - void SetControl(int index, byte? value); - - // read and write GPIO - byte? ReadGPIO(int index); - void WriteGPIO(int index, byte value); - - string GetReport(); - - void Update(); - } -} diff --git a/Hardware/LPC/IT87XX.cs b/Hardware/LPC/IT87XX.cs deleted file mode 100644 index 035bbe2..0000000 --- a/Hardware/LPC/IT87XX.cs +++ /dev/null @@ -1,443 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - -*/ - -using System.Globalization; -using System.Text; -using System; - -namespace OpenHardwareMonitor.Hardware.LPC { - internal class IT87XX : ISuperIO { - - private readonly ushort address; - private readonly Chip chip; - private readonly byte version; - - private readonly ushort gpioAddress; - private readonly int gpioCount; - - private readonly ushort addressReg; - private readonly ushort dataReg; - - private readonly float?[] voltages = new float?[0]; - private readonly float?[] temperatures = new float?[0]; - private readonly float?[] fans = new float?[0]; - private readonly bool[] fansDisabled = new bool[0]; - private readonly float?[] controls = new float?[0]; - - private readonly float voltageGain; - private readonly bool has16bitFanCounter; - private readonly bool hasNewerAutopwm; - - // Consts - private const byte ITE_VENDOR_ID = 0x90; - - // Environment Controller - private const byte ADDRESS_REGISTER_OFFSET = 0x05; - private const byte DATA_REGISTER_OFFSET = 0x06; - - // Environment Controller Registers - private const byte CONFIGURATION_REGISTER = 0x00; - private const byte TEMPERATURE_BASE_REG = 0x29; - private const byte VENDOR_ID_REGISTER = 0x58; - private const byte FAN_TACHOMETER_DIVISOR_REGISTER = 0x0B; - private const byte FAN_TACHOMETER_16BIT_REGISTER = 0x0C; - private readonly byte[] FAN_TACHOMETER_REG = - { 0x0d, 0x0e, 0x0f, 0x80, 0x82, 0x4c }; - private readonly byte[] FAN_TACHOMETER_EXT_REG = - { 0x18, 0x19, 0x1a, 0x81, 0x83, 0x4c }; - private const byte VOLTAGE_BASE_REG = 0x20; - private readonly byte[] FAN_PWM_CTRL_REG = { 0x15, 0x16, 0x17 }; - private readonly byte[] FAN_PWM_DUTY_REG = { 0x63, 0x6b, 0x73 }; - - private bool[] restoreDefaultFanPwmControlRequired = new bool[3]; - private byte[] initialFanPwmControl = new byte[3]; - private byte[] initialFanPwmControlMode = new byte[3]; - - private byte ReadByte(byte register, out bool valid) { - Ring0.WriteIoPort(addressReg, register); - byte value = Ring0.ReadIoPort(dataReg); - valid = register == Ring0.ReadIoPort(addressReg); - // IT8688E doesn't return the value we wrote to - // addressReg when we read it back. - if (this.chip == Chip.IT8688E) - valid = true; - return value; - } - - private bool WriteByte(byte register, byte value) { - Ring0.WriteIoPort(addressReg, register); - Ring0.WriteIoPort(dataReg, value); - return register == Ring0.ReadIoPort(addressReg); - } - - public byte? ReadGPIO(int index) { - if (index >= gpioCount) - return null; - - return Ring0.ReadIoPort((ushort)(gpioAddress + index)); - } - - public void WriteGPIO(int index, byte value) { - if (index >= gpioCount) - return; - - Ring0.WriteIoPort((ushort)(gpioAddress + index), value); - } - - private void SaveDefaultFanPwmControl(int index) { - bool valid; - if (hasNewerAutopwm) { - if (!restoreDefaultFanPwmControlRequired[index]) { - initialFanPwmControlMode[index] = - ReadByte(FAN_PWM_CTRL_REG[index], out valid); - - initialFanPwmControl[index] = - ReadByte(FAN_PWM_DUTY_REG[index], out valid); - } - } else { - if (!restoreDefaultFanPwmControlRequired[index]) { - initialFanPwmControl[index] = - ReadByte(FAN_PWM_CTRL_REG[index], out valid); - } - } - - restoreDefaultFanPwmControlRequired[index] = true; - } - - private void RestoreDefaultFanPwmControl(int index) { - if (hasNewerAutopwm) { - if (restoreDefaultFanPwmControlRequired[index]) { - WriteByte(FAN_PWM_CTRL_REG[index], initialFanPwmControlMode[index]); - WriteByte(FAN_PWM_DUTY_REG[index], initialFanPwmControl[index]); - restoreDefaultFanPwmControlRequired[index] = false; - } - } else { - if (restoreDefaultFanPwmControlRequired[index]) { - WriteByte(FAN_PWM_CTRL_REG[index], initialFanPwmControl[index]); - restoreDefaultFanPwmControlRequired[index] = false; - } - } - } - - public void SetControl(int index, byte? value) { - if (index < 0 || index >= controls.Length) - throw new ArgumentOutOfRangeException("index"); - - if (!Ring0.WaitIsaBusMutex(10)) - return; - - if (value.HasValue) { - SaveDefaultFanPwmControl(index); - - if (hasNewerAutopwm) { - bool valid = false; - byte ctrlValue = ReadByte(FAN_PWM_CTRL_REG[index], out valid); - - if (valid) { - bool isOnAutoControl = (ctrlValue & (1 << 7)) > 0; - if (isOnAutoControl) { - // Set to manual speed control - ctrlValue &= byte.MaxValue ^ (1 << 7); - WriteByte(FAN_PWM_CTRL_REG[index], ctrlValue); - } - } - - // set speed - WriteByte(FAN_PWM_DUTY_REG[index], value.Value); - } else { - // set output value - WriteByte(FAN_PWM_CTRL_REG[index], (byte)((value.Value >> 1))); - } - } else { - RestoreDefaultFanPwmControl(index); - } - - Ring0.ReleaseIsaBusMutex(); - } - - public IT87XX(Chip chip, ushort address, ushort gpioAddress, byte version) { - - this.address = address; - this.chip = chip; - this.version = version; - this.addressReg = (ushort)(address + ADDRESS_REGISTER_OFFSET); - this.dataReg = (ushort)(address + DATA_REGISTER_OFFSET); - this.gpioAddress = gpioAddress; - - // Check vendor id - bool valid; - byte vendorId = ReadByte(VENDOR_ID_REGISTER, out valid); - if (!valid || vendorId != ITE_VENDOR_ID) - return; - - // Bit 0x10 of the configuration register should always be 1 - byte config = ReadByte(CONFIGURATION_REGISTER, out valid); - if ((config & 0x10) == 0 && chip != Chip.IT8665E) - return; - if (!valid) - return; - - // IT8686E has more sensors - if (chip == Chip.IT8686E) { - voltages = new float?[10]; - temperatures = new float?[5]; - fans = new float?[5]; - fansDisabled = new bool[5]; - controls = new float?[3]; - } else if (chip == Chip.IT8665E) { - voltages = new float?[10]; - temperatures = new float?[6]; - fans = new float?[6]; - fansDisabled = new bool[6]; - controls = new float?[3]; - } else if (chip == Chip.IT8688E) { - voltages = new float?[11]; - temperatures = new float?[6]; - fans = new float?[5]; - fansDisabled = new bool[5]; - controls = new float?[3]; - } else { - voltages = new float?[9]; - temperatures = new float?[3]; - fans = new float?[chip == Chip.IT8705F ? 3 : 5]; - fansDisabled = new bool[chip == Chip.IT8705F ? 3 : 5]; - controls = new float?[3]; - } - - // IT8620E, IT8628E, IT8721F, IT8728F, IT8772E and IT8686E use a 12mV resultion - // ADC, all others 16mV - if (chip == Chip.IT8620E || chip == Chip.IT8628E || chip == Chip.IT8721F - || chip == Chip.IT8728F || chip == Chip.IT8771E || chip == Chip.IT8772E - || chip == Chip.IT8686E || chip == Chip.IT8688E) { - voltageGain = 0.012f; - } else if (chip == Chip.IT8665E) { - voltageGain = 0.0109f; - } else { - voltageGain = 0.016f; - } - - // older IT8705F and IT8721F revisions do not have 16-bit fan counters - if ((chip == Chip.IT8705F && version < 3) || - (chip == Chip.IT8712F && version < 8)) { - has16bitFanCounter = false; - } else { - has16bitFanCounter = true; - } - - if (chip == Chip.IT8620E) { - hasNewerAutopwm = true; - } - - // Disable any fans that aren't set with 16-bit fan counters - if (has16bitFanCounter) { - int modes = ReadByte(FAN_TACHOMETER_16BIT_REGISTER, out valid); - - if (!valid) - return; - - if (fans.Length >= 5) { - fansDisabled[3] = (modes & (1 << 4)) == 0; - fansDisabled[4] = (modes & (1 << 5)) == 0; - } - if (fans.Length >= 6) { - fansDisabled[5] = (modes & (1 << 2)) == 0; - } - } - - // Set the number of GPIO sets - switch (chip) { - case Chip.IT8712F: - case Chip.IT8716F: - case Chip.IT8718F: - case Chip.IT8726F: - gpioCount = 5; - break; - case Chip.IT8720F: - case Chip.IT8721F: - gpioCount = 8; - break; - case Chip.IT8620E: - case Chip.IT8628E: - case Chip.IT8688E: - case Chip.IT8705F: - case Chip.IT8728F: - case Chip.IT8771E: - case Chip.IT8772E: - gpioCount = 0; - break; - } - } - - public Chip Chip { get { return chip; } } - public float?[] Voltages { get { return voltages; } } - public float?[] Temperatures { get { return temperatures; } } - public float?[] Fans { get { return fans; } } - public float?[] Controls { get { return controls; } } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("LPC " + this.GetType().Name); - r.AppendLine(); - r.Append("Chip ID: 0x"); r.AppendLine(chip.ToString("X")); - r.Append("Chip Version: 0x"); r.AppendLine( - version.ToString("X", CultureInfo.InvariantCulture)); - r.Append("Base Address: 0x"); r.AppendLine( - address.ToString("X4", CultureInfo.InvariantCulture)); - r.Append("GPIO Address: 0x"); r.AppendLine( - gpioAddress.ToString("X4", CultureInfo.InvariantCulture)); - r.AppendLine(); - - if (!Ring0.WaitIsaBusMutex(100)) - return r.ToString(); - - r.AppendLine("Environment Controller Registers"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - for (int i = 0; i <= 0xA; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X2", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - r.Append(" "); - bool valid; - byte value = ReadByte((byte)((i << 4) | j), out valid); - r.Append( - valid ? value.ToString("X2", CultureInfo.InvariantCulture) : "??"); - } - r.AppendLine(); - } - r.AppendLine(); - - r.AppendLine("GPIO Registers"); - r.AppendLine(); - for (int i = 0; i < gpioCount; i++) { - r.Append(" "); - r.Append(ReadGPIO(i).Value.ToString("X2", - CultureInfo.InvariantCulture)); - } - r.AppendLine(); - r.AppendLine(); - - Ring0.ReleaseIsaBusMutex(); - - return r.ToString(); - } - - public void Update() { - if (!Ring0.WaitIsaBusMutex(10)) - return; - - for (int i = 0; i < voltages.Length; i++) { - bool valid; - - float value = - voltageGain * ReadByte((byte)(VOLTAGE_BASE_REG + i), out valid); - - if (!valid) - continue; - if (value > 0) - voltages[i] = value; - else - voltages[i] = null; - } - - for (int i = 0; i < temperatures.Length; i++) { - bool valid; - sbyte value = (sbyte)ReadByte( - (byte)(TEMPERATURE_BASE_REG + i), out valid); - if (!valid) - continue; - - if (value < sbyte.MaxValue && value > 0) - temperatures[i] = value; - else - temperatures[i] = null; - } - - if (has16bitFanCounter) { - for (int i = 0; i < fans.Length; i++) { - if (fansDisabled[i]) - continue; - bool valid; - int value = ReadByte(FAN_TACHOMETER_REG[i], out valid); - if (!valid) - continue; - value |= ReadByte(FAN_TACHOMETER_EXT_REG[i], out valid) << 8; - if (!valid) - continue; - - if (value > 0x3f) { - fans[i] = (value < 0xffff) ? 1.35e6f / (value * 2) : 0; - } else { - fans[i] = null; - } - } - } else { - for (int i = 0; i < fans.Length; i++) { - bool valid; - int value = ReadByte(FAN_TACHOMETER_REG[i], out valid); - if (!valid) - continue; - - int divisor = 2; - if (i < 2) { - int divisors = ReadByte(FAN_TACHOMETER_DIVISOR_REGISTER, out valid); - if (!valid) - continue; - divisor = 1 << ((divisors >> (3 * i)) & 0x7); - } - - if (value > 0) { - fans[i] = (value < 0xff) ? 1.35e6f / (value * divisor) : 0; - } else { - fans[i] = null; - } - } - } - - for (int i = 0; i < controls.Length; i++) { - if (hasNewerAutopwm) { - bool valid; - byte value = ReadByte(FAN_PWM_DUTY_REG[i], out valid); - if (!valid) - continue; - - byte ctrlValue = ReadByte(FAN_PWM_CTRL_REG[i], out valid); - if (!valid) - continue; - - if ((ctrlValue & 0x80) > 0) { - // automatic operation (value can't be read) - controls[i] = null; - } else { - controls[i] = (float)Math.Round((value) * 100.0f / 0xFF); - } - } else { - bool valid; - byte value = ReadByte(FAN_PWM_CTRL_REG[i], out valid); - if (!valid) - continue; - - if ((value & 0x80) > 0) { - // automatic operation (value can't be read) - controls[i] = null; - } else { - // software operation - controls[i] = (float)Math.Round((value & 0x7F) * 100.0f / 0x7F); - } - } - } - - Ring0.ReleaseIsaBusMutex(); - } - } -} \ No newline at end of file diff --git a/Hardware/LPC/LMSensors.cs b/Hardware/LPC/LMSensors.cs deleted file mode 100755 index c4584a8..0000000 --- a/Hardware/LPC/LMSensors.cs +++ /dev/null @@ -1,233 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2013 Michael Möller - -*/ - -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.LPC { - - internal class LMSensors { - - private readonly List lmChips = new List(); - - public LMSensors() { - string[] basePaths = Directory.GetDirectories("/sys/class/hwmon/"); - foreach (string basePath in basePaths) { - foreach (string devicePath in new[] { "/device", "" }) { - string path = basePath + devicePath; - - string name = null; - try { - using (StreamReader reader = new StreamReader(path + "/name")) - name = reader.ReadLine(); - } catch (IOException) { } - - switch (name) { - case "atk0110": - lmChips.Add(new LMChip(Chip.ATK0110, path)); break; - - case "f71858fg": - lmChips.Add(new LMChip(Chip.F71858, path)); break; - case "f71862fg": - lmChips.Add(new LMChip(Chip.F71862, path)); break; - case "f71869": - lmChips.Add(new LMChip(Chip.F71869, path)); break; - case "f71869a": - lmChips.Add(new LMChip(Chip.F71869A, path)); break; - case "f71882fg": - lmChips.Add(new LMChip(Chip.F71882, path)); break; - case "f71889a": - lmChips.Add(new LMChip(Chip.F71889AD, path)); break; - case "f71878ad": - lmChips.Add(new LMChip(Chip.F71878AD, path)); break; - case "f71889ed": - lmChips.Add(new LMChip(Chip.F71889ED, path)); break; - case "f71889fg": - lmChips.Add(new LMChip(Chip.F71889F, path)); break; - case "f71808e": - lmChips.Add(new LMChip(Chip.F71808E, path)); break; - - case "it8705": - lmChips.Add(new LMChip(Chip.IT8705F, path)); break; - case "it8712": - lmChips.Add(new LMChip(Chip.IT8712F, path)); break; - case "it8716": - lmChips.Add(new LMChip(Chip.IT8716F, path)); break; - case "it8718": - lmChips.Add(new LMChip(Chip.IT8718F, path)); break; - case "it8720": - lmChips.Add(new LMChip(Chip.IT8720F, path)); break; - - case "nct6775": - lmChips.Add(new LMChip(Chip.NCT6771F, path)); break; - case "nct6776": - lmChips.Add(new LMChip(Chip.NCT6776F, path)); break; - case "nct6779": - lmChips.Add(new LMChip(Chip.NCT6779D, path)); break; - case "nct6791": - lmChips.Add(new LMChip(Chip.NCT6791D, path)); break; - case "nct6792": - lmChips.Add(new LMChip(Chip.NCT6792D, path)); break; - case "nct6793": - lmChips.Add(new LMChip(Chip.NCT6793D, path)); break; - case "nct6795": - lmChips.Add(new LMChip(Chip.NCT6795D, path)); break; - case "nct6796": - lmChips.Add(new LMChip(Chip.NCT6796D, path)); break; - case "nct6797": - lmChips.Add(new LMChip(Chip.NCT6797D, path)); break; - case "nct6798": - lmChips.Add(new LMChip(Chip.NCT6798D, path)); break; - - case "w83627ehf": - lmChips.Add(new LMChip(Chip.W83627EHF, path)); break; - case "w83627dhg": - lmChips.Add(new LMChip(Chip.W83627DHG, path)); break; - case "w83667hg": - lmChips.Add(new LMChip(Chip.W83667HG, path)); break; - case "w83627hf": - lmChips.Add(new LMChip(Chip.W83627HF, path)); break; - case "w83627thf": - lmChips.Add(new LMChip(Chip.W83627THF, path)); break; - case "w83687thf": - lmChips.Add(new LMChip(Chip.W83687THF, path)); break; - } - } - } - } - - public void Close() { - foreach (LMChip lmChip in lmChips) - lmChip.Close(); - } - - public ISuperIO[] SuperIO { - get { - return lmChips.ToArray(); - } - } - - private class LMChip : ISuperIO { - - private string path; - private readonly Chip chip; - - private readonly float?[] voltages; - private readonly float?[] temperatures; - private readonly float?[] fans; - private readonly float?[] controls; - - private readonly FileStream[] voltageStreams; - private readonly FileStream[] temperatureStreams; - private readonly FileStream[] fanStreams; - - public Chip Chip { get { return chip; } } - public float?[] Voltages { get { return voltages; } } - public float?[] Temperatures { get { return temperatures; } } - public float?[] Fans { get { return fans; } } - public float?[] Controls { get { return controls; } } - - public LMChip(Chip chip, string path) { - this.path = path; - this.chip = chip; - - string[] voltagePaths = Directory.GetFiles(path, "in*_input"); - this.voltages = new float?[voltagePaths.Length]; - this.voltageStreams = new FileStream[voltagePaths.Length]; - for (int i = 0; i < voltagePaths.Length; i++) - voltageStreams[i] = new FileStream(voltagePaths[i], - FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - string[] temperaturePaths = Directory.GetFiles(path, "temp*_input"); - this.temperatures = new float?[temperaturePaths.Length]; - this.temperatureStreams = new FileStream[temperaturePaths.Length]; - for (int i = 0; i < temperaturePaths.Length; i++) - temperatureStreams[i] = new FileStream(temperaturePaths[i], - FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - string[] fanPaths = Directory.GetFiles(path, "fan*_input"); - this.fans = new float?[fanPaths.Length]; - this.fanStreams = new FileStream[fanPaths.Length]; - for (int i = 0; i < fanPaths.Length; i++) - fanStreams[i] = new FileStream(fanPaths[i], - FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - this.controls = new float?[0]; - } - - public byte? ReadGPIO(int index) { - return null; - } - - public void WriteGPIO(int index, byte value) { } - - public string GetReport() { - return null; - } - - public void SetControl(int index, byte? value) { } - - private string ReadFirstLine(Stream stream) { - StringBuilder sb = new StringBuilder(); - try { - stream.Seek(0, SeekOrigin.Begin); - int b = stream.ReadByte(); - while (b != -1 && b != 10) { - sb.Append((char)b); - b = stream.ReadByte(); - } - } catch { } - return sb.ToString(); - } - - public void Update() { - for (int i = 0; i < voltages.Length; i++) { - string s = ReadFirstLine(voltageStreams[i]); - try { - voltages[i] = 0.001f * - long.Parse(s, CultureInfo.InvariantCulture); - } catch { - voltages[i] = null; - } - } - - for (int i = 0; i < temperatures.Length; i++) { - string s = ReadFirstLine(temperatureStreams[i]); - try { - temperatures[i] = 0.001f * - long.Parse(s, CultureInfo.InvariantCulture); - } catch { - temperatures[i] = null; - } - } - - for (int i = 0; i < fans.Length; i++) { - string s = ReadFirstLine(fanStreams[i]); - try { - fans[i] = long.Parse(s, CultureInfo.InvariantCulture); - } catch { - fans[i] = null; - } - } - } - - public void Close() { - foreach (FileStream stream in voltageStreams) - stream.Close(); - foreach (FileStream stream in temperatureStreams) - stream.Close(); - foreach (FileStream stream in fanStreams) - stream.Close(); - } - } - } -} diff --git a/Hardware/LPC/LPCIO.cs b/Hardware/LPC/LPCIO.cs deleted file mode 100644 index c25a96f..0000000 --- a/Hardware/LPC/LPCIO.cs +++ /dev/null @@ -1,525 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using System.Threading; - -namespace OpenHardwareMonitor.Hardware.LPC { - internal class LPCIO { - - private readonly List superIOs = new List(); - private readonly StringBuilder report = new StringBuilder(); - - // I/O Ports - private readonly ushort[] REGISTER_PORTS = new ushort[] { 0x2E, 0x4E }; - private readonly ushort[] VALUE_PORTS = new ushort[] { 0x2F, 0x4F }; - - // Registers - private const byte CHIP_ID_REGISTER = 0x20; - private const byte CHIP_REVISION_REGISTER = 0x21; - private const byte BASE_ADDRESS_REGISTER = 0x60; - - private void ReportUnknownChip(LPCPort port, string type, int chip) { - report.Append("Chip ID: Unknown "); - report.Append(type); - report.Append(" with ID 0x"); - report.Append(chip.ToString("X", CultureInfo.InvariantCulture)); - report.Append(" at 0x"); - report.Append(port.RegisterPort.ToString("X", - CultureInfo.InvariantCulture)); - report.Append("/0x"); - report.AppendLine(port.ValuePort.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine(); - } - - #region Winbond, Nuvoton, Fintek - - private const byte FINTEK_VENDOR_ID_REGISTER = 0x23; - private const ushort FINTEK_VENDOR_ID = 0x1934; - - private const byte WINBOND_NUVOTON_HARDWARE_MONITOR_LDN = 0x0B; - - private const byte F71858_HARDWARE_MONITOR_LDN = 0x02; - private const byte FINTEK_HARDWARE_MONITOR_LDN = 0x04; - - private bool DetectWinbondFintek(LPCPort port) { - port.WinbondNuvotonFintekEnter(); - - byte logicalDeviceNumber = 0; - byte id = port.ReadByte(CHIP_ID_REGISTER); - byte revision = port.ReadByte(CHIP_REVISION_REGISTER); - Chip chip = Chip.Unknown; - switch (id) { - case 0x05: - switch (revision) { - case 0x07: - chip = Chip.F71858; - logicalDeviceNumber = F71858_HARDWARE_MONITOR_LDN; - break; - case 0x41: - chip = Chip.F71882; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x06: - switch (revision) { - case 0x01: - chip = Chip.F71862; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x07: - switch (revision) { - case 0x23: - chip = Chip.F71889F; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x08: - switch (revision) { - case 0x14: - chip = Chip.F71869; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x09: - switch (revision) { - case 0x01: - chip = Chip.F71808E; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - case 0x09: - chip = Chip.F71889ED; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x10: - switch (revision) { - case 0x05: - chip = Chip.F71889AD; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - case 0x07: - chip = Chip.F71869A; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x11: - switch (revision) { - case 0x06: - chip = Chip.F71878AD; - logicalDeviceNumber = FINTEK_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x52: - switch (revision) { - case 0x17: - case 0x3A: - case 0x41: - chip = Chip.W83627HF; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x82: - switch (revision & 0xF0) { - case 0x80: - chip = Chip.W83627THF; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x85: - switch (revision) { - case 0x41: - chip = Chip.W83687THF; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0x88: - switch (revision & 0xF0) { - case 0x50: - case 0x60: - chip = Chip.W83627EHF; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xA0: - switch (revision & 0xF0) { - case 0x20: - chip = Chip.W83627DHG; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xA5: - switch (revision & 0xF0) { - case 0x10: - chip = Chip.W83667HG; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xB0: - switch (revision & 0xF0) { - case 0x70: - chip = Chip.W83627DHGP; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xB3: - switch (revision & 0xF0) { - case 0x50: - chip = Chip.W83667HGB; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xB4: - switch (revision & 0xF0) { - case 0x70: - chip = Chip.NCT6771F; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xC3: - switch (revision & 0xF0) { - case 0x30: - chip = Chip.NCT6776F; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xC4: - switch (revision & 0xF0) { - case 0x50: - chip = Chip.NCT610X; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xC5: - switch (revision & 0xF0) { - case 0x60: - chip = Chip.NCT6779D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xC8: - switch (revision) { - case 0x03: - chip = Chip.NCT6791D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xC9: - switch (revision) { - case 0x11: - chip = Chip.NCT6792D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xD1: - switch (revision) { - case 0x21: - chip = Chip.NCT6793D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xD3: - switch (revision) { - case 0x52: - chip = Chip.NCT6795D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - case 0xD4: - switch (revision) { - case 0x23: - chip = Chip.NCT6796D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - case 0x51: - chip = Chip.NCT6797D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - case 0x2B: - chip = Chip.NCT6798D; - logicalDeviceNumber = WINBOND_NUVOTON_HARDWARE_MONITOR_LDN; - break; - } break; - } - if (chip == Chip.Unknown) { - if (id != 0 && id != 0xff) { - port.WinbondNuvotonFintekExit(); - - ReportUnknownChip(port, "Winbond / Nuvoton / Fintek", - ((id << 8) | revision)); - } - } else { - - port.Select(logicalDeviceNumber); - ushort address = port.ReadWord(BASE_ADDRESS_REGISTER); - Thread.Sleep(1); - ushort verify = port.ReadWord(BASE_ADDRESS_REGISTER); - - ushort vendorID = port.ReadWord(FINTEK_VENDOR_ID_REGISTER); - - // disable the hardware monitor i/o space lock on NCT679*D chips - if (address == verify && (chip == Chip.NCT6791D || chip == Chip.NCT6796D || chip == Chip.NCT6793D || chip == Chip.NCT6795D || chip == Chip.NCT6798D || chip == Chip.NCT6797D)) { - port.NuvotonDisableIOSpaceLock(); - } - - port.WinbondNuvotonFintekExit(); - - if (address != verify) { - report.Append("Chip ID: 0x"); - report.AppendLine(chip.ToString("X")); - report.Append("Chip revision: 0x"); - report.AppendLine(revision.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine("Error: Address verification failed"); - report.AppendLine(); - return false; - } - - // some Fintek chips have address register offset 0x05 added already - if ((address & 0x07) == 0x05) - address &= 0xFFF8; - - if (address < 0x100 || (address & 0xF007) != 0) { - report.Append("Chip ID: 0x"); - report.AppendLine(chip.ToString("X")); - report.Append("Chip revision: 0x"); - report.AppendLine(revision.ToString("X", - CultureInfo.InvariantCulture)); - report.Append("Error: Invalid address 0x"); - report.AppendLine(address.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine(); - return false; - } - - switch (chip) { - case Chip.W83627DHG: - case Chip.W83627DHGP: - case Chip.W83627EHF: - case Chip.W83627HF: - case Chip.W83627THF: - case Chip.W83667HG: - case Chip.W83667HGB: - case Chip.W83687THF: - superIOs.Add(new W836XX(chip, revision, address)); - break; - case Chip.NCT610X: - case Chip.NCT6771F: - case Chip.NCT6776F: - case Chip.NCT6779D: - case Chip.NCT6791D: - case Chip.NCT6792D: - case Chip.NCT6793D: - case Chip.NCT6795D: - case Chip.NCT6796D: - case Chip.NCT6797D: - case Chip.NCT6798D: - superIOs.Add(new NCT677X(chip, revision, address, port)); - break; - case Chip.F71858: - case Chip.F71862: - case Chip.F71869: - case Chip.F71878AD: - case Chip.F71869A: - case Chip.F71882: - case Chip.F71889AD: - case Chip.F71889ED: - case Chip.F71889F: - case Chip.F71808E: - if (vendorID != FINTEK_VENDOR_ID) { - report.Append("Chip ID: 0x"); - report.AppendLine(chip.ToString("X")); - report.Append("Chip revision: 0x"); - report.AppendLine(revision.ToString("X", - CultureInfo.InvariantCulture)); - report.Append("Error: Invalid vendor ID 0x"); - report.AppendLine(vendorID.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine(); - return false; - } - superIOs.Add(new F718XX(chip, address)); - break; - default: break; - } - - return true; - } - - return false; - } - - #endregion - - #region ITE - - private const byte IT87_ENVIRONMENT_CONTROLLER_LDN = 0x04; - private const byte IT8705_GPIO_LDN = 0x05; - private const byte IT87XX_GPIO_LDN = 0x07; - private const byte IT87_CHIP_VERSION_REGISTER = 0x22; - - private bool DetectIT87(LPCPort port) { - - // IT87XX can enter only on port 0x2E - if (port.RegisterPort != 0x2E) - return false; - - port.IT87Enter(); - - ushort chipID = port.ReadWord(CHIP_ID_REGISTER); - Chip chip; - switch (chipID) { - case 0x8620: chip = Chip.IT8620E; break; - case 0x8628: chip = Chip.IT8628E; break; - case 0x8665: chip = Chip.IT8665E; break; - case 0x8686: chip = Chip.IT8686E; break; - case 0x8688: chip = Chip.IT8688E; break; - case 0x8705: chip = Chip.IT8705F; break; - case 0x8712: chip = Chip.IT8712F; break; - case 0x8716: chip = Chip.IT8716F; break; - case 0x8718: chip = Chip.IT8718F; break; - case 0x8720: chip = Chip.IT8720F; break; - case 0x8721: chip = Chip.IT8721F; break; - case 0x8726: chip = Chip.IT8726F; break; - case 0x8728: chip = Chip.IT8728F; break; - case 0x8771: chip = Chip.IT8771E; break; - case 0x8772: chip = Chip.IT8772E; break; - default: chip = Chip.Unknown; break; - } - if (chip == Chip.Unknown) { - if (chipID != 0 && chipID != 0xffff) { - port.IT87Exit(); - - ReportUnknownChip(port, "ITE", chipID); - } - } else { - port.Select(IT87_ENVIRONMENT_CONTROLLER_LDN); - ushort address = port.ReadWord(BASE_ADDRESS_REGISTER); - Thread.Sleep(1); - ushort verify = port.ReadWord(BASE_ADDRESS_REGISTER); - - byte version = (byte)(port.ReadByte(IT87_CHIP_VERSION_REGISTER) & 0x0F); - - ushort gpioAddress; - ushort gpioVerify; - if (chip == Chip.IT8705F) { - port.Select(IT8705_GPIO_LDN); - gpioAddress = port.ReadWord(BASE_ADDRESS_REGISTER); - Thread.Sleep(1); - gpioVerify = port.ReadWord(BASE_ADDRESS_REGISTER); - } else { - port.Select(IT87XX_GPIO_LDN); - gpioAddress = port.ReadWord(BASE_ADDRESS_REGISTER + 2); - Thread.Sleep(1); - gpioVerify = port.ReadWord(BASE_ADDRESS_REGISTER + 2); - } - - port.IT87Exit(); - - if (address != verify || address < 0x100 || (address & 0xF007) != 0) { - report.Append("Chip ID: 0x"); - report.AppendLine(chip.ToString("X")); - report.Append("Error: Invalid address 0x"); - report.AppendLine(address.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine(); - return false; - } - - if (gpioAddress != gpioVerify || gpioAddress < 0x100 || - (gpioAddress & 0xF007) != 0) { - report.Append("Chip ID: 0x"); - report.AppendLine(chip.ToString("X")); - report.Append("Error: Invalid GPIO address 0x"); - report.AppendLine(gpioAddress.ToString("X", - CultureInfo.InvariantCulture)); - report.AppendLine(); - return false; - } - - superIOs.Add(new IT87XX(chip, address, gpioAddress, version)); - return true; - } - - return false; - } - - #endregion - - #region SMSC - - private bool DetectSMSC(LPCPort port) { - port.SMSCEnter(); - - ushort chipID = port.ReadWord(CHIP_ID_REGISTER); - Chip chip; - switch (chipID) { - default: chip = Chip.Unknown; break; - } - if (chip == Chip.Unknown) { - if (chipID != 0 && chipID != 0xffff) { - port.SMSCExit(); - - ReportUnknownChip(port, "SMSC", chipID); - } - } else { - port.SMSCExit(); - return true; - } - - return false; - } - - #endregion - - private void Detect() { - - for (int i = 0; i < REGISTER_PORTS.Length; i++) { - var port = new LPCPort(REGISTER_PORTS[i], VALUE_PORTS[i]); - - if (DetectWinbondFintek(port)) continue; - - if (DetectIT87(port)) continue; - - if (DetectSMSC(port)) continue; - } - } - - public LPCIO() { - if (!Ring0.IsOpen) - return; - - if (!Ring0.WaitIsaBusMutex(100)) - return; - - Detect(); - - Ring0.ReleaseIsaBusMutex(); - } - - public ISuperIO[] SuperIO { - get { - return superIOs.ToArray(); - } - } - - public string GetReport() { - if (report.Length > 0) { - return "LPCIO" + Environment.NewLine + Environment.NewLine + report; - } else - return null; - } - } -} diff --git a/Hardware/LPC/LPCPort.cs b/Hardware/LPC/LPCPort.cs deleted file mode 100644 index 829b1d7..0000000 --- a/Hardware/LPC/LPCPort.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.LPC { - - internal class LPCPort { - private readonly ushort registerPort; - private readonly ushort valuePort; - - public LPCPort(ushort registerPort, ushort valuePort) { - this.registerPort = registerPort; - this.valuePort = valuePort; - } - - public ushort RegisterPort { - get { - return registerPort; - } - } - - public ushort ValuePort { - get { - return valuePort; - } - } - - private const byte DEVCIE_SELECT_REGISTER = 0x07; - private const byte CONFIGURATION_CONTROL_REGISTER = 0x02; - - public byte ReadByte(byte register) { - Ring0.WriteIoPort(registerPort, register); - return Ring0.ReadIoPort(valuePort); - } - - public void WriteByte(byte register, byte value) { - Ring0.WriteIoPort(registerPort, register); - Ring0.WriteIoPort(valuePort, value); - } - - public ushort ReadWord(byte register) { - return (ushort)((ReadByte(register) << 8) | - ReadByte((byte)(register + 1))); - } - - public void Select(byte logicalDeviceNumber) { - Ring0.WriteIoPort(registerPort, DEVCIE_SELECT_REGISTER); - Ring0.WriteIoPort(valuePort, logicalDeviceNumber); - } - - public void WinbondNuvotonFintekEnter() { - Ring0.WriteIoPort(registerPort, 0x87); - Ring0.WriteIoPort(registerPort, 0x87); - } - - public void WinbondNuvotonFintekExit() { - Ring0.WriteIoPort(registerPort, 0xAA); - } - - private const byte NUVOTON_HARDWARE_MONITOR_IO_SPACE_LOCK = 0x28; - - public void NuvotonDisableIOSpaceLock() { - byte options = ReadByte(NUVOTON_HARDWARE_MONITOR_IO_SPACE_LOCK); - - // if the i/o space lock is enabled - if ((options & 0x10) > 0) { - - // disable the i/o space lock - WriteByte(NUVOTON_HARDWARE_MONITOR_IO_SPACE_LOCK, - (byte)(options & ~0x10)); - } - } - - public void IT87Enter() { - Ring0.WriteIoPort(registerPort, 0x87); - Ring0.WriteIoPort(registerPort, 0x01); - Ring0.WriteIoPort(registerPort, 0x55); - Ring0.WriteIoPort(registerPort, 0x55); - } - - public void IT87Exit() { - Ring0.WriteIoPort(registerPort, CONFIGURATION_CONTROL_REGISTER); - Ring0.WriteIoPort(valuePort, 0x02); - } - - public void SMSCEnter() { - Ring0.WriteIoPort(registerPort, 0x55); - } - - public void SMSCExit() { - Ring0.WriteIoPort(registerPort, 0xAA); - } - } - -} diff --git a/Hardware/LPC/NCT677X.cs b/Hardware/LPC/NCT677X.cs deleted file mode 100644 index 9568bb8..0000000 --- a/Hardware/LPC/NCT677X.cs +++ /dev/null @@ -1,563 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2015 Michael Möller - Copyright (C) 2015 Dawid Gan - -*/ - -using System; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.LPC { - internal class NCT677X : ISuperIO { - - private readonly ushort port; - private readonly byte revision; - - private readonly Chip chip; - private readonly LPCPort lpcPort; - - private readonly bool isNuvotonVendor; - - private readonly float?[] voltages = new float?[0]; - private readonly float?[] temperatures = new float?[0]; - private readonly float?[] fans = new float?[0]; - private readonly float?[] controls = new float?[0]; - - // Hardware Monitor - private const uint ADDRESS_REGISTER_OFFSET = 0x05; - private const uint DATA_REGISTER_OFFSET = 0x06; - private const byte BANK_SELECT_REGISTER = 0x4E; - - private byte ReadByte(ushort address) { - byte bank = (byte)(address >> 8); - byte register = (byte)(address & 0xFF); - Ring0.WriteIoPort(port + ADDRESS_REGISTER_OFFSET, BANK_SELECT_REGISTER); - Ring0.WriteIoPort(port + DATA_REGISTER_OFFSET, bank); - Ring0.WriteIoPort(port + ADDRESS_REGISTER_OFFSET, register); - return Ring0.ReadIoPort(port + DATA_REGISTER_OFFSET); - } - - private void WriteByte(ushort address, byte value) { - byte bank = (byte)(address >> 8); - byte register = (byte)(address & 0xFF); - Ring0.WriteIoPort(port + ADDRESS_REGISTER_OFFSET, BANK_SELECT_REGISTER); - Ring0.WriteIoPort(port + DATA_REGISTER_OFFSET, bank); - Ring0.WriteIoPort(port + ADDRESS_REGISTER_OFFSET, register); - Ring0.WriteIoPort(port + DATA_REGISTER_OFFSET, value); - } - - // Consts - private const ushort NUVOTON_VENDOR_ID = 0x5CA3; - - // Hardware Monitor Registers - private readonly ushort VENDOR_ID_HIGH_REGISTER; - private readonly ushort VENDOR_ID_LOW_REGISTER; - - private readonly ushort[] FAN_PWM_OUT_REG; - private readonly ushort[] FAN_PWM_COMMAND_REG; - private readonly ushort[] FAN_CONTROL_MODE_REG; - - private readonly ushort fanRpmBaseRegister; - private readonly int minFanRPM; - - private bool[] restoreDefaultFanControlRequired = new bool[6]; - private byte[] initialFanControlMode = new byte[6]; - private byte[] initialFanPwmCommand = new byte[6]; - - private readonly ushort[] voltageRegisters; - private readonly ushort voltageVBatRegister; - private readonly ushort vBatMonitorControlRegister; - - private readonly byte[] temperaturesSource; - - private readonly ushort[] temperatureRegister; - private readonly ushort[] temperatureHalfRegister; - private readonly int[] temperatureHalfBit; - private readonly ushort[] temperatureSourceRegister; - - private readonly ushort?[] alternateTemperatureRegister; - - private enum SourceNCT6771F : byte { - SYSTIN = 1, - CPUTIN = 2, - AUXTIN = 3, - SMBUSMASTER = 4, - PECI_0 = 5, - PECI_1 = 6, - PECI_2 = 7, - PECI_3 = 8, - PECI_4 = 9, - PECI_5 = 10, - PECI_6 = 11, - PECI_7 = 12, - PCH_CHIP_CPU_MAX_TEMP = 13, - PCH_CHIP_TEMP = 14, - PCH_CPU_TEMP = 15, - PCH_MCH_TEMP = 16, - PCH_DIM0_TEMP = 17, - PCH_DIM1_TEMP = 18, - PCH_DIM2_TEMP = 19, - PCH_DIM3_TEMP = 20 - } - - private enum SourceNCT6776F : byte { - SYSTIN = 1, - CPUTIN = 2, - AUXTIN = 3, - SMBUSMASTER_0 = 4, - SMBUSMASTER_1 = 5, - SMBUSMASTER_2 = 6, - SMBUSMASTER_3 = 7, - SMBUSMASTER_4 = 8, - SMBUSMASTER_5 = 9, - SMBUSMASTER_6 = 10, - SMBUSMASTER_7 = 11, - PECI_0 = 12, - PECI_1 = 13, - PCH_CHIP_CPU_MAX_TEMP = 14, - PCH_CHIP_TEMP = 15, - PCH_CPU_TEMP = 16, - PCH_MCH_TEMP = 17, - PCH_DIM0_TEMP = 18, - PCH_DIM1_TEMP = 19, - PCH_DIM2_TEMP = 20, - PCH_DIM3_TEMP = 21, - BYTE_TEMP = 22 - } - - private enum SourceNCT67XXD : byte { - SYSTIN = 1, - CPUTIN = 2, - AUXTIN0 = 3, - AUXTIN1 = 4, - AUXTIN2 = 5, - AUXTIN3 = 6, - SMBUSMASTER_0 = 8, - SMBUSMASTER_1 = 9, - SMBUSMASTER_2 = 10, - SMBUSMASTER_3 = 11, - SMBUSMASTER_4 = 12, - SMBUSMASTER_5 = 13, - SMBUSMASTER_6 = 14, - SMBUSMASTER_7 = 15, - PECI_0 = 16, - PECI_1 = 17, - PCH_CHIP_CPU_MAX_TEMP = 18, - PCH_CHIP_TEMP = 19, - PCH_CPU_TEMP = 20, - PCH_MCH_TEMP = 21, - PCH_DIM0_TEMP = 22, - PCH_DIM1_TEMP = 23, - PCH_DIM2_TEMP = 24, - PCH_DIM3_TEMP = 25, - BYTE_TEMP = 26 - } - - private enum SourceNCT610X : byte { - SYSTIN = 1, - CPUTIN = 2, - AUXTIN = 3, - SMBUSMASTER_0 = 4, - SMBUSMASTER_1 = 5, - SMBUSMASTER_2 = 6, - SMBUSMASTER_3 = 7, - SMBUSMASTER_4 = 8, - SMBUSMASTER_5 = 9, - SMBUSMASTER_6 = 10, - SMBUSMASTER_7 = 11, - PECI_0 = 12, - PECI_1 = 13, - PCH_CHIP_CPU_MAX_TEMP = 14, - PCH_CHIP_TEMP = 15, - PCH_CPU_TEMP = 16, - PCH_MCH_TEMP = 17, - PCH_DIM0_TEMP = 18, - PCH_DIM1_TEMP = 19, - PCH_DIM2_TEMP = 20, - PCH_DIM3_TEMP = 21, - BYTE_TEMP = 22 - } - - public NCT677X(Chip chip, byte revision, ushort port, LPCPort lpcPort) - { - this.chip = chip; - this.revision = revision; - this.port = port; - this.lpcPort = lpcPort; - - if (chip == LPC.Chip.NCT610X) { - VENDOR_ID_HIGH_REGISTER = 0x80FE; - VENDOR_ID_LOW_REGISTER = 0x00FE; - - FAN_PWM_OUT_REG = new ushort[] { 0x04A, 0x04B, 0x04C }; - FAN_PWM_COMMAND_REG = new ushort[] { 0x119, 0x129, 0x139 }; - FAN_CONTROL_MODE_REG = new ushort[] { 0x113, 0x123, 0x133 }; - - vBatMonitorControlRegister = 0x0318; - } else { - VENDOR_ID_HIGH_REGISTER = 0x804F; - VENDOR_ID_LOW_REGISTER = 0x004F; - - FAN_PWM_OUT_REG = new ushort[] { - 0x001, 0x003, 0x011, 0x013, 0x015, 0x017 }; - FAN_PWM_COMMAND_REG = new ushort[] { - 0x109, 0x209, 0x309, 0x809, 0x909, 0xA09 }; - FAN_CONTROL_MODE_REG = new ushort[] { - 0x102, 0x202, 0x302, 0x802, 0x902, 0xA02 }; - - vBatMonitorControlRegister = 0x005D; - } - - this.isNuvotonVendor = IsNuvotonVendor(); - - if (!isNuvotonVendor) - return; - - switch (chip) { - case Chip.NCT6771F: - case Chip.NCT6776F: - if (chip == Chip.NCT6771F) { - fans = new float?[4]; - - // min value RPM value with 16-bit fan counter - minFanRPM = (int)(1.35e6 / 0xFFFF); - - temperaturesSource = new byte[] { - (byte)SourceNCT6771F.PECI_0, - (byte)SourceNCT6771F.CPUTIN, - (byte)SourceNCT6771F.AUXTIN, - (byte)SourceNCT6771F.SYSTIN - }; - } else { - fans = new float?[5]; - - // min value RPM value with 13-bit fan counter - minFanRPM = (int)(1.35e6 / 0x1FFF); - - temperaturesSource = new byte[] { - (byte)SourceNCT6776F.PECI_0, - (byte)SourceNCT6776F.CPUTIN, - (byte)SourceNCT6776F.AUXTIN, - (byte)SourceNCT6776F.SYSTIN - }; - } - fanRpmBaseRegister = 0x656; - - controls = new float?[3]; - - voltages = new float?[9]; - voltageRegisters = new ushort[] - { 0x020, 0x021, 0x022, 0x023, 0x024, 0x025, 0x026, 0x550, 0x551 }; - voltageVBatRegister = 0x551; - - temperatures = new float?[4]; - temperatureRegister = new ushort[] - { 0x027, 0x073, 0x075, 0x077, 0x150, 0x250, 0x62B, 0x62C, 0x62D }; - temperatureHalfRegister = new ushort[] - { 0, 0x074, 0x076, 0x078, 0x151, 0x251, 0x62E, 0x62E, 0x62E }; - temperatureHalfBit = new int[] - { -1, 7, 7, 7, 7, 7, 0, 1, 2 }; - temperatureSourceRegister = new ushort[] - { 0x621, 0x100, 0x200, 0x300, 0x622, 0x623, 0x624, 0x625, 0x626 }; - - alternateTemperatureRegister = new ushort?[] - { null, null, null, null }; - break; - - case Chip.NCT6779D: - case Chip.NCT6791D: - case Chip.NCT6792D: - case Chip.NCT6793D: - case Chip.NCT6795D: - case Chip.NCT6796D: - case Chip.NCT6797D: - case Chip.NCT6798D: - if (chip == Chip.NCT6779D) { - fans = new float?[5]; - controls = new float?[5]; - } else { - fans = new float?[6]; - controls = new float?[6]; - } - - fanRpmBaseRegister = 0x4C0; - - // min value RPM value with 13-bit fan counter - minFanRPM = (int)(1.35e6 / 0x1FFF); - - voltages = new float?[15]; - voltageRegisters = new ushort[] - { 0x480, 0x481, 0x482, 0x483, 0x484, 0x485, 0x486, 0x487, 0x488, - 0x489, 0x48A, 0x48B, 0x48C, 0x48D, 0x48E }; - voltageVBatRegister = 0x488; - - temperatures = new float?[7]; - temperaturesSource = new byte[] { - (byte)SourceNCT67XXD.PECI_0, - (byte)SourceNCT67XXD.CPUTIN, - (byte)SourceNCT67XXD.SYSTIN, - (byte)SourceNCT67XXD.AUXTIN0, - (byte)SourceNCT67XXD.AUXTIN1, - (byte)SourceNCT67XXD.AUXTIN2, - (byte)SourceNCT67XXD.AUXTIN3 - }; - - temperatureRegister = new ushort[] - { 0x027, 0x073, 0x075, 0x077, 0x079, 0x07B, 0x150 }; - temperatureHalfRegister = new ushort[] - { 0, 0x074, 0x076, 0x078, 0x07A, 0x07C, 0x151 }; - temperatureHalfBit = new int[] - { -1, 7, 7, 7, 7, 7, 7 }; - temperatureSourceRegister = new ushort[] - { 0x621, 0x100, 0x200, 0x300, 0x800, 0x900, 0x622 }; - - alternateTemperatureRegister = new ushort?[] - {null, 0x491, 0x490, 0x492, 0x493, 0x494, 0x495 }; - - break; - case Chip.NCT610X: - - fans = new float?[3]; - controls = new float?[3]; - - fanRpmBaseRegister = 0x030; - - // min value RPM value with 13-bit fan counter - minFanRPM = (int)(1.35e6 / 0x1FFF); - - voltages = new float?[9]; - voltageRegisters = new ushort[] - { 0x300, 0x301, 0x302, 0x303, 0x304, 0x305, 0x307, 0x308, 0x309 }; - voltageVBatRegister = 0x308; - - temperatures = new float?[4]; - temperaturesSource = new byte[] { - (byte)SourceNCT610X.PECI_0, - (byte)SourceNCT610X.SYSTIN, - (byte)SourceNCT610X.CPUTIN, - (byte)SourceNCT610X.AUXTIN - }; - - temperatureRegister = new ushort[] - { 0x027, 0x018, 0x019, 0x01A }; - temperatureHalfRegister = new ushort[] - { 0, 0x01B, 0x11B, 0x21B }; - temperatureHalfBit = new int[] - { -1, 7, 7, 7 }; - temperatureSourceRegister = new ushort[] - { 0x621, 0x100, 0x200, 0x300 }; - - alternateTemperatureRegister = new ushort?[] - {null, 0x018, 0x019, 0x01A }; - - break; - } - } - - private bool IsNuvotonVendor() { - return ((ReadByte(VENDOR_ID_HIGH_REGISTER) << 8) | - ReadByte(VENDOR_ID_LOW_REGISTER)) == NUVOTON_VENDOR_ID; - } - - public byte? ReadGPIO(int index) { - return null; - } - - public void WriteGPIO(int index, byte value) { } - - - private void SaveDefaultFanControl(int index) { - if (!restoreDefaultFanControlRequired[index]) { - initialFanControlMode[index] = ReadByte(FAN_CONTROL_MODE_REG[index]); - initialFanPwmCommand[index] = ReadByte(FAN_PWM_COMMAND_REG[index]); - restoreDefaultFanControlRequired[index] = true; - } - } - - private void RestoreDefaultFanControl(int index) { - if (restoreDefaultFanControlRequired[index]) { - WriteByte(FAN_CONTROL_MODE_REG[index], initialFanControlMode[index]); - WriteByte(FAN_PWM_COMMAND_REG[index], initialFanPwmCommand[index]); - restoreDefaultFanControlRequired[index] = false; - } - } - - public void SetControl(int index, byte? value) { - if (!isNuvotonVendor) - return; - - if (index < 0 || index >= controls.Length) - throw new ArgumentOutOfRangeException("index"); - - if (!Ring0.WaitIsaBusMutex(10)) - return; - - if (value.HasValue) { - SaveDefaultFanControl(index); - - // set manual mode - WriteByte(FAN_CONTROL_MODE_REG[index], 0); - - // set output value - WriteByte(FAN_PWM_COMMAND_REG[index], value.Value); - } else { - RestoreDefaultFanControl(index); - } - - Ring0.ReleaseIsaBusMutex(); - } - - public Chip Chip { get { return chip; } } - public float?[] Voltages { get { return voltages; } } - public float?[] Temperatures { get { return temperatures; } } - public float?[] Fans { get { return fans; } } - public float?[] Controls { get { return controls; } } - - private void DisableIOSpaceLock() { - if (chip != Chip.NCT6791D && chip != Chip.NCT6796D && chip != Chip.NCT6793D && chip != Chip.NCT6795D && chip != Chip.NCT6798D && chip != Chip.NCT6797D) - return; - - // the lock is disabled already if the vendor ID can be read - if (IsNuvotonVendor()) - return; - - lpcPort.WinbondNuvotonFintekEnter(); - lpcPort.NuvotonDisableIOSpaceLock(); - lpcPort.WinbondNuvotonFintekExit(); - } - - public void Update() { - if (!isNuvotonVendor) - return; - - if (!Ring0.WaitIsaBusMutex(10)) - return; - - DisableIOSpaceLock(); - - for (int i = 0; i < voltages.Length; i++) { - float value = 0.008f * ReadByte(voltageRegisters[i]); - bool valid = value > 0; - - // check if battery voltage monitor is enabled - if (valid && voltageRegisters[i] == voltageVBatRegister) - valid = (ReadByte(vBatMonitorControlRegister) & 0x01) > 0; - - voltages[i] = valid ? value : (float?)null; - } - - int temperatureSourceMask = 0; - for (int i = temperatureRegister.Length - 1; i >= 0 ; i--) { - int value = ((sbyte)ReadByte(temperatureRegister[i])) << 1; - if (temperatureHalfBit[i] > 0) { - value |= ((ReadByte(temperatureHalfRegister[i]) >> - temperatureHalfBit[i]) & 0x1); - } - - byte source = ReadByte(temperatureSourceRegister[i]); - temperatureSourceMask |= 1 << source; - - float? temperature = 0.5f * value; - if (temperature > 125 || temperature < -55) - temperature = null; - - for (int j = 0; j < temperatures.Length; j++) - if (temperaturesSource[j] == source) - temperatures[j] = temperature; - } - for (int i = 0; i < alternateTemperatureRegister.Length; i++) { - if (!alternateTemperatureRegister[i].HasValue) - continue; - - if ((temperatureSourceMask & (1 << temperaturesSource[i])) > 0) - continue; - - float? temperature = (sbyte) - ReadByte(alternateTemperatureRegister[i].Value); - - if (temperature > 125 || temperature < -55) - temperature = null; - - temperatures[i] = temperature; - } - - for (int i = 0; i < fans.Length; i++) { - byte high = ReadByte((ushort)(fanRpmBaseRegister + (i << 1))); - byte low = ReadByte((ushort)(fanRpmBaseRegister + (i << 1) + 1)); - int value = (high << 8) | low; - - fans[i] = value > minFanRPM ? value : 0; - } - - for (int i = 0; i < controls.Length; i++) { - int value = ReadByte(FAN_PWM_OUT_REG[i]); - controls[i] = value / 2.55f; - } - - Ring0.ReleaseIsaBusMutex(); - } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("LPC " + this.GetType().Name); - r.AppendLine(); - r.Append("Chip ID: 0x"); r.AppendLine(chip.ToString("X")); - r.Append("Chip revision: 0x"); - r.AppendLine(revision.ToString("X", CultureInfo.InvariantCulture)); - r.Append("Base Adress: 0x"); - r.AppendLine(port.ToString("X4", CultureInfo.InvariantCulture)); - r.AppendLine(); - - if (!Ring0.WaitIsaBusMutex(100)) - return r.ToString(); - - ushort[] addresses = new ushort[] { - 0x000, 0x010, 0x020, 0x030, 0x040, 0x050, 0x060, 0x070, 0x0F0, - 0x100, 0x110, 0x120, 0x130, 0x140, 0x150, - 0x200, 0x210, 0x220, 0x230, 0x240, 0x250, 0x260, - 0x300, 0x320, 0x330, 0x340, 0x360, - 0x400, 0x410, 0x420, 0x440, 0x450, 0x460, 0x480, 0x490, 0x4B0, - 0x4C0, 0x4F0, - 0x500, 0x550, 0x560, - 0x600, 0x610 ,0x620, 0x630, 0x640, 0x650, 0x660, 0x670, - 0x700, 0x710, 0x720, 0x730, - 0x800, 0x820, 0x830, 0x840, - 0x900, 0x920, 0x930, 0x940, 0x960, - 0xA00, 0xA10, 0xA20, 0xA30, 0xA40, 0xA50, 0xA60, 0xA70, - 0xB00, 0xB10, 0xB20, 0xB30, 0xB50, 0xB60, 0xB70, - 0xC00, 0xC10, 0xC20, 0xC30, 0xC50, 0xC60, 0xC70, - 0xD00, 0xD10, 0xD20, 0xD30, 0xD50, 0xD60, - 0xE00, 0xE10, 0xE20, 0xE30, - 0xF00, 0xF10, 0xF20, 0xF30, - 0x8040, 0x80F0}; - - r.AppendLine("Hardware Monitor Registers"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - foreach (ushort address in addresses) { - r.Append(" "); - r.Append(address.ToString("X4", CultureInfo.InvariantCulture)); - r.Append(" "); - for (ushort j = 0; j <= 0xF; j++) { - r.Append(" "); - r.Append(ReadByte((ushort)(address | j)).ToString( - "X2", CultureInfo.InvariantCulture)); - } - r.AppendLine(); - } - r.AppendLine(); - - Ring0.ReleaseIsaBusMutex(); - - return r.ToString(); - } - } -} diff --git a/Hardware/LPC/W836XX.cs b/Hardware/LPC/W836XX.cs deleted file mode 100644 index 6265613..0000000 --- a/Hardware/LPC/W836XX.cs +++ /dev/null @@ -1,325 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.LPC { - internal class W836XX : ISuperIO { - - private readonly ushort address; - private readonly byte revision; - - private readonly Chip chip; - - private readonly float?[] voltages = new float?[0]; - private readonly float?[] temperatures = new float?[0]; - private readonly float?[] fans = new float?[0]; - private readonly float?[] controls = new float?[0]; - - private readonly bool[] peciTemperature = new bool[0]; - private readonly byte[] voltageRegister = new byte[0]; - private readonly byte[] voltageBank = new byte[0]; - private readonly float voltageGain = 0.008f; - - // Consts - private const ushort WINBOND_VENDOR_ID = 0x5CA3; - private const byte HIGH_BYTE = 0x80; - - // Hardware Monitor - private const byte ADDRESS_REGISTER_OFFSET = 0x05; - private const byte DATA_REGISTER_OFFSET = 0x06; - - // Hardware Monitor Registers - private const byte VOLTAGE_VBAT_REG = 0x51; - private const byte BANK_SELECT_REGISTER = 0x4E; - private const byte VENDOR_ID_REGISTER = 0x4F; - private const byte TEMPERATURE_SOURCE_SELECT_REG = 0x49; - - private readonly byte[] TEMPERATURE_REG = new byte[] { 0x50, 0x50, 0x27 }; - private readonly byte[] TEMPERATURE_BANK = new byte[] { 1, 2, 0 }; - - private readonly byte[] FAN_TACHO_REG = - new byte[] { 0x28, 0x29, 0x2A, 0x3F, 0x53 }; - private readonly byte[] FAN_TACHO_BANK = - new byte[] { 0, 0, 0, 0, 5 }; - private readonly byte[] FAN_BIT_REG = - new byte[] { 0x47, 0x4B, 0x4C, 0x59, 0x5D }; - private readonly byte[] FAN_DIV_BIT0 = new byte[] { 36, 38, 30, 8, 10 }; - private readonly byte[] FAN_DIV_BIT1 = new byte[] { 37, 39, 31, 9, 11 }; - private readonly byte[] FAN_DIV_BIT2 = new byte[] { 5, 6, 7, 23, 15 }; - - private byte ReadByte(byte bank, byte register) { - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), BANK_SELECT_REGISTER); - Ring0.WriteIoPort( - (ushort)(address + DATA_REGISTER_OFFSET), bank); - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), register); - return Ring0.ReadIoPort( - (ushort)(address + DATA_REGISTER_OFFSET)); - } - - private void WriteByte(byte bank, byte register, byte value) { - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), BANK_SELECT_REGISTER); - Ring0.WriteIoPort( - (ushort)(address + DATA_REGISTER_OFFSET), bank); - Ring0.WriteIoPort( - (ushort)(address + ADDRESS_REGISTER_OFFSET), register); - Ring0.WriteIoPort( - (ushort)(address + DATA_REGISTER_OFFSET), value); - } - - public byte? ReadGPIO(int index) { - return null; - } - - public void WriteGPIO(int index, byte value) { } - - public void SetControl(int index, byte? value) { } - - public W836XX(Chip chip, byte revision, ushort address) { - this.address = address; - this.revision = revision; - this.chip = chip; - - if (!IsWinbondVendor()) - return; - - temperatures = new float?[3]; - peciTemperature = new bool[3]; - switch (chip) { - case Chip.W83667HG: - case Chip.W83667HGB: - // note temperature sensor registers that read PECI - byte flag = ReadByte(0, TEMPERATURE_SOURCE_SELECT_REG); - peciTemperature[0] = (flag & 0x04) != 0; - peciTemperature[1] = (flag & 0x40) != 0; - peciTemperature[2] = false; - break; - case Chip.W83627DHG: - case Chip.W83627DHGP: - // note temperature sensor registers that read PECI - byte sel = ReadByte(0, TEMPERATURE_SOURCE_SELECT_REG); - peciTemperature[0] = (sel & 0x07) != 0; - peciTemperature[1] = (sel & 0x70) != 0; - peciTemperature[2] = false; - break; - default: - // no PECI support - peciTemperature[0] = false; - peciTemperature[1] = false; - peciTemperature[2] = false; - break; - } - - switch (chip) { - case Chip.W83627EHF: - voltages = new float?[10]; - voltageRegister = new byte[] { - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x50, 0x51, 0x52 }; - voltageBank = new byte[] { 0, 0, 0, 0, 0, 0, 0, 5, 5, 5 }; - voltageGain = 0.008f; - fans = new float?[5]; - break; - case Chip.W83627DHG: - case Chip.W83627DHGP: - case Chip.W83667HG: - case Chip.W83667HGB: - voltages = new float?[9]; - voltageRegister = new byte[] { - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x50, 0x51 }; - voltageBank = new byte[] { 0, 0, 0, 0, 0, 0, 0, 5, 5 }; - voltageGain = 0.008f; - fans = new float?[5]; - break; - case Chip.W83627HF: - case Chip.W83627THF: - case Chip.W83687THF: - voltages = new float?[7]; - voltageRegister = new byte[] { - 0x20, 0x21, 0x22, 0x23, 0x24, 0x50, 0x51 }; - voltageBank = new byte[] { 0, 0, 0, 0, 0, 5, 5 }; - voltageGain = 0.016f; - fans = new float?[3]; - break; - } - } - - private bool IsWinbondVendor() { - ushort vendorId = - (ushort)((ReadByte(HIGH_BYTE, VENDOR_ID_REGISTER) << 8) | - ReadByte(0, VENDOR_ID_REGISTER)); - return vendorId == WINBOND_VENDOR_ID; - } - - private static ulong SetBit(ulong target, int bit, int value) { - if ((value & 1) != value) - throw new ArgumentException("Value must be one bit only."); - - if (bit < 0 || bit > 63) - throw new ArgumentException("Bit out of range."); - - ulong mask = (((ulong)1) << bit); - return value > 0 ? target | mask : target & ~mask; - } - - public Chip Chip { get { return chip; } } - public float?[] Voltages { get { return voltages; } } - public float?[] Temperatures { get { return temperatures; } } - public float?[] Fans { get { return fans; } } - public float?[] Controls { get { return controls; } } - - public void Update() { - if (!Ring0.WaitIsaBusMutex(10)) - return; - - for (int i = 0; i < voltages.Length; i++) { - if (voltageRegister[i] != VOLTAGE_VBAT_REG) { - // two special VCore measurement modes for W83627THF - float fvalue; - if ((chip == Chip.W83627HF || chip == Chip.W83627THF || - chip == Chip.W83687THF) && i == 0) - { - byte vrmConfiguration = ReadByte(0, 0x18); - int value = ReadByte(voltageBank[i], voltageRegister[i]); - if ((vrmConfiguration & 0x01) == 0) - fvalue = 0.016f * value; // VRM8 formula - else - fvalue = 0.00488f * value + 0.69f; // VRM9 formula - } else { - int value = ReadByte(voltageBank[i], voltageRegister[i]); - fvalue = voltageGain * value; - } - if (fvalue > 0) - voltages[i] = fvalue; - else - voltages[i] = null; - } else { - // Battery voltage - bool valid = (ReadByte(0, 0x5D) & 0x01) > 0; - if (valid) { - voltages[i] = voltageGain * ReadByte(5, VOLTAGE_VBAT_REG); - } else { - voltages[i] = null; - } - } - } - - for (int i = 0; i < temperatures.Length; i++) { - int value = ((sbyte)ReadByte(TEMPERATURE_BANK[i], - TEMPERATURE_REG[i])) << 1; - if (TEMPERATURE_BANK[i] > 0) - value |= ReadByte(TEMPERATURE_BANK[i], - (byte)(TEMPERATURE_REG[i] + 1)) >> 7; - - float temperature = value / 2.0f; - if (temperature <= 125 && temperature >= -55 && !peciTemperature[i]) { - temperatures[i] = temperature; - } else { - temperatures[i] = null; - } - } - - ulong bits = 0; - for (int i = 0; i < FAN_BIT_REG.Length; i++) - bits = (bits << 8) | ReadByte(0, FAN_BIT_REG[i]); - ulong newBits = bits; - for (int i = 0; i < fans.Length; i++) { - int count = ReadByte(FAN_TACHO_BANK[i], FAN_TACHO_REG[i]); - - // assemble fan divisor - int divisorBits = (int)( - (((bits >> FAN_DIV_BIT2[i]) & 1) << 2) | - (((bits >> FAN_DIV_BIT1[i]) & 1) << 1) | - ((bits >> FAN_DIV_BIT0[i]) & 1)); - int divisor = 1 << divisorBits; - - float value = (count < 0xff) ? 1.35e6f / (count * divisor) : 0; - fans[i] = value; - - // update fan divisor - if (count > 192 && divisorBits < 7) - divisorBits++; - if (count < 96 && divisorBits > 0) - divisorBits--; - - newBits = SetBit(newBits, FAN_DIV_BIT2[i], (divisorBits >> 2) & 1); - newBits = SetBit(newBits, FAN_DIV_BIT1[i], (divisorBits >> 1) & 1); - newBits = SetBit(newBits, FAN_DIV_BIT0[i], divisorBits & 1); - } - - // write new fan divisors - for (int i = FAN_BIT_REG.Length - 1; i >= 0; i--) { - byte oldByte = (byte)(bits & 0xFF); - byte newByte = (byte)(newBits & 0xFF); - bits = bits >> 8; - newBits = newBits >> 8; - if (oldByte != newByte) - WriteByte(0, FAN_BIT_REG[i], newByte); - } - - Ring0.ReleaseIsaBusMutex(); - } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("LPC " + this.GetType().Name); - r.AppendLine(); - r.Append("Chip ID: 0x"); r.AppendLine(chip.ToString("X")); - r.Append("Chip revision: 0x"); - r.AppendLine(revision.ToString("X", CultureInfo.InvariantCulture)); - r.Append("Base Adress: 0x"); - r.AppendLine(address.ToString("X4", CultureInfo.InvariantCulture)); - r.AppendLine(); - - if (!Ring0.WaitIsaBusMutex(100)) - return r.ToString(); - - r.AppendLine("Hardware Monitor Registers"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - for (int i = 0; i <= 0x7; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X2", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - r.Append(" "); - r.Append(ReadByte(0, (byte)((i << 4) | j)).ToString( - "X2", CultureInfo.InvariantCulture)); - } - r.AppendLine(); - } - for (int k = 1; k <= 15; k++) { - r.AppendLine("Bank " + k); - for (int i = 0x5; i < 0x6; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X2", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - r.Append(" "); - r.Append(ReadByte((byte)(k), (byte)((i << 4) | j)).ToString( - "X2", CultureInfo.InvariantCulture)); - } - r.AppendLine(); - } - } - r.AppendLine(); - - Ring0.ReleaseIsaBusMutex(); - - return r.ToString(); - } - } -} diff --git a/Hardware/Mainboard/GigabyteTAMG.cs b/Hardware/Mainboard/GigabyteTAMG.cs deleted file mode 100644 index 12ca9f0..0000000 --- a/Hardware/Mainboard/GigabyteTAMG.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2011 Michael Möller - -*/ - -using System; -using System.IO; -using System.IO.Compression; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Mainboard { - - internal class GigabyteTAMG { - private byte[] table; - - private Sensor[] sensors; - - private struct Sensor { - public string Name; - public SensorType Type; - public int Channel; - public float Value; - } - - private enum SensorType { - Voltage = 1, - Temperature = 2, - Fan = 4, - Case = 8, - } - - public GigabyteTAMG(byte[] table) { - if (table == null) - throw new ArgumentNullException("table"); - - this.table = table; - - int index = IndexOf(table, Encoding.ASCII.GetBytes("$HEALTH$"), 0); - - if (index >= 0) { - index += 8; - using (MemoryStream m = - new MemoryStream(table, index, table.Length - index)) - using (BinaryReader r = new BinaryReader(m)) { - try { - r.ReadInt64(); - int count = r.ReadInt32(); - r.ReadInt64(); - r.ReadInt32(); - sensors = new Sensor[count]; - for (int i = 0; i < sensors.Length; i++) { - sensors[i].Name = new string(r.ReadChars(32)).TrimEnd('\0'); - sensors[i].Type = (SensorType)r.ReadByte(); - sensors[i].Channel = r.ReadInt16(); - sensors[i].Channel |= r.ReadByte() << 24; - r.ReadInt64(); - int value = r.ReadInt32(); - switch (sensors[i].Type) { - case SensorType.Voltage: - sensors[i].Value = 1e-3f * value; break; - default: - sensors[i].Value = value; break; - } - r.ReadInt64(); - } - } catch (IOException) { sensors = new Sensor[0]; } - } - } else { - sensors = new Sensor[0]; - } - } - - public static int IndexOf(byte[] array, byte[] pattern, int startIndex) { - if (array == null || pattern == null || pattern.Length > array.Length) - return -1; - - for (int i = startIndex; i < array.Length - pattern.Length; i++) { - bool found = true; - for (int j = 0; j < pattern.Length; j++) { - if (array[i + j] != pattern[j]) { - found = false; - break; - } - } - if (found) - return i; - } - return -1; - } - - private string GetCompressedAndEncodedTable() { - string base64; - using (MemoryStream m = new MemoryStream()) { - using (GZipStream c = new GZipStream(m, CompressionMode.Compress)) { - c.Write(table, 0, table.Length); - } - base64 = Convert.ToBase64String(m.ToArray()); - } - - StringBuilder r = new StringBuilder(); - for (int i = 0; i < Math.Ceiling(base64.Length / 64.0); i++) { - r.Append(" "); - for (int j = 0; j < 0x40; j++) { - int index = (i << 6) | j; - if (index < base64.Length) { - r.Append(base64[index]); - } - } - r.AppendLine(); - } - - return r.ToString(); - } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - if (sensors.Length > 0) { - r.AppendLine("Gigabyte TAMG Sensors"); - r.AppendLine(); - - foreach (Sensor sensor in sensors) { - r.AppendFormat(" {0,-10}: {1,8:G6} ({2})", sensor.Name, sensor.Value, - sensor.Type); - r.AppendLine(); - } - r.AppendLine(); - } - - if (table.Length > 0) { - r.AppendLine("Gigabyte TAMG Table"); - r.AppendLine(); - r.Append(GetCompressedAndEncodedTable()); - r.AppendLine(); - } - - return r.ToString(); - } - } -} diff --git a/Hardware/Mainboard/Identification.cs b/Hardware/Mainboard/Identification.cs deleted file mode 100644 index 1284da0..0000000 --- a/Hardware/Mainboard/Identification.cs +++ /dev/null @@ -1,254 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2012 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.Mainboard { - internal class Identification { - - public static Manufacturer GetManufacturer(string name) { - switch (name) { - case "Alienware": - return Manufacturer.Alienware; - case "Apple Inc.": - return Manufacturer.Apple; - case "ASRock": - return Manufacturer.ASRock; - case "ASUSTeK Computer INC.": - case "ASUSTeK COMPUTER INC.": - return Manufacturer.ASUS; - case "Dell Inc.": - return Manufacturer.Dell; - case "DFI": - case "DFI Inc.": - return Manufacturer.DFI; - case "ECS": - return Manufacturer.ECS; - case "EPoX COMPUTER CO., LTD": - return Manufacturer.EPoX; - case "EVGA": - return Manufacturer.EVGA; - case "First International Computer, Inc.": - return Manufacturer.FIC; - case "FUJITSU": - case "FUJITSU SIEMENS": - return Manufacturer.Fujitsu; - case "Gigabyte Technology Co., Ltd.": - return Manufacturer.Gigabyte; - case "Hewlett-Packard": - return Manufacturer.HP; - case "IBM": - return Manufacturer.IBM; - case "Intel": - case "Intel Corp.": - case "Intel Corporation": - case "INTEL Corporation": - return Manufacturer.Intel; - case "Lenovo": - case "LENOVO": - return Manufacturer.Lenovo; - case "Micro-Star International": - case "Micro-Star International Co., Ltd": - case "MICRO-STAR INTERNATIONAL CO., LTD": - case "MICRO-STAR INTERNATIONAL CO.,LTD": - case "MSI": - return Manufacturer.MSI; - case "Shuttle": - return Manufacturer.Shuttle; - case "Supermicro": - return Manufacturer.Supermicro; - case "TOSHIBA": - return Manufacturer.Toshiba; - case "XFX": - return Manufacturer.XFX; - case "To be filled by O.E.M.": - return Manufacturer.Unknown; - default: - return Manufacturer.Unknown; - } - } - - public static Model GetModel(string name) { - switch (name) { - case "880GMH/USB3": - return Model._880GMH_USB3; - case "B85M-DGS": - return Model.B85M_DGS; - case "ASRock AOD790GX/128M": - return Model.AOD790GX_128M; - case "AB350 Pro4": - return Model.AB350_PRO4; - case "AB350M Pro4": - return Model.AB350M_PRO4; - case "AB350M": - return Model.AB350M; - case "Fatal1ty AB350 Gaming K4": - return Model.Fatal1ty_AB350_Gaming_K4; - case "AB350M-HDV": - return Model.AB350M_HDV; - case "X399 Phantom Gaming 6": - return Model.PHANTOM_GAMING_6; - case "A320M-HDV": - return Model.A320M_HDV; - case "P55 Deluxe": - return Model.P55_Deluxe; - case "Crosshair III Formula": - return Model.Crosshair_III_Formula; - case "M2N-SLI DELUXE": - return Model.M2N_SLI_DELUXE; - case "M4A79XTD EVO": - return Model.M4A79XTD_EVO; - case "P5W DH Deluxe": - return Model.P5W_DH_Deluxe; - case "P6T": - return Model.P6T; - case "P6X58D-E": - return Model.P6X58D_E; - case "P8P67": - case "P8P67 REV 3.1": - return Model.P8P67; - case "P8P67 EVO": - return Model.P8P67_EVO; - case "P8P67 PRO": - return Model.P8P67_PRO; - case "P8P67-M PRO": - return Model.P8P67_M_PRO; - case "P8Z77-V": - return Model.P8Z77_V; - case "P9X79": - return Model.P9X79; - case "Rampage Extreme": - return Model.Rampage_Extreme; - case "Rampage II GENE": - return Model.Rampage_II_GENE; - case "LP BI P45-T2RS Elite": - return Model.LP_BI_P45_T2RS_Elite; - case "LP DK P55-T3eH9": - return Model.LP_DK_P55_T3eH9; - case "A890GXM-A": - return Model.A890GXM_A; - case "X58 SLI Classified": - return Model.X58_SLI_Classified; - case "965P-S3": - return Model._965P_S3; - case "EP45-DS3R": - return Model.EP45_DS3R; - case "EP45-UD3R": - return Model.EP45_UD3R; - case "EX58-EXTREME": - return Model.EX58_EXTREME; - case "EX58-UD3R": - return Model.EX58_UD3R; - case "G41M-Combo": - return Model.G41M_Combo; - case "G41MT-S2": - return Model.G41MT_S2; - case "G41MT-S2P": - return Model.G41MT_S2P; - case "GA-970A-UD3": - return Model._970A_UD3; - case "GA-MA770T-UD3": - return Model.MA770T_UD3; - case "GA-MA770T-UD3P": - return Model.MA770T_UD3P; - case "GA-MA785GM-US2H": - return Model.MA785GM_US2H; - case "GA-MA785GMT-UD2H": - return Model.MA785GMT_UD2H; - case "GA-MA78LM-S2H": - return Model.MA78LM_S2H; - case "GA-MA790X-UD3P": - return Model.MA790X_UD3P; - case "H55-USB3": - return Model.H55_USB3; - case "H55N-USB3": - return Model.H55N_USB3; - case "H61M-DS2 REV 1.2": - return Model.H61M_DS2_REV_1_2; - case "H61M-USB3-B3 REV 2.0": - return Model.H61M_USB3_B3_REV_2_0; - case "H67A-UD3H-B3": - return Model.H67A_UD3H_B3; - case "H67A-USB3-B3": - return Model.H67A_USB3_B3; - case "P35-DS3": - return Model.P35_DS3; - case "P35-DS3L": - return Model.P35_DS3L; - case "P55-UD4": - return Model.P55_UD4; - case "P55A-UD3": - return Model.P55A_UD3; - case "P55M-UD4": - return Model.P55M_UD4; - case "P67A-UD3-B3": - return Model.P67A_UD3_B3; - case "P67A-UD3R-B3": - return Model.P67A_UD3R_B3; - case "P67A-UD4-B3": - return Model.P67A_UD4_B3; - case "P8Z68-V PRO": - return Model.P8Z68_V_PRO; - case "X38-DS5": - return Model.X38_DS5; - case "X58A-UD3R": - return Model.X58A_UD3R; - case "Z270 PC MATE": - case "Z270 PC MATE (MS-7A72)": - return Model.Z270_PC_MATE; - case "X79-UD3": - return Model.X79_UD3; - case "Z68A-D3H-B3": - return Model.Z68A_D3H_B3; - case "Z68AP-D3": - return Model.Z68AP_D3; - case "Z68X-UD3H-B3": - return Model.Z68X_UD3H_B3; - case "Z68X-UD7-B3": - return Model.Z68X_UD7_B3; - case "Z390 M GAMING-CF": - return Model.Z390_M_GAMING; - case "Z390 AORUS ULTRA": - return Model.Z390_AORUS_ULTRA; - case "Z390 UD": - return Model.Z390_UD; - case "FH67": - return Model.FH67; - case "AX370-Gaming K7": - return Model.AX370_K7; - case "PRIME X370-PRO": - return Model.PRIME_X370_PRO; - case "ROG MAXIMUS X APEX": - return Model.ROG_MAXIMUS_APEX; - case "AB350-Gaming 3-CF": - return Model.AB350_Gaming_3_CF; - case "X399 AORUS Gaming 7": - return Model.X399_AOURUS_GAMING7; - case "ROG ZENITH EXTREME": - return Model.ROG_ZENITH_EXTREME; - case "Z170-A": - return Model.Z170_A; - case "Z77 Pro4-M": - return Model.Z77PRO4M; - case "AX370-Gaming 5": - return Model.AX370_Gaming_5; - case "TUF X470-PLUS GAMING": - return Model.TUF_X470_PLUS_GAMING; - case "B360M PRO-VDH (MS-7B24)": - return Model.B360M_PRO_VDH; - case "B450-A PRO (MS-7B86)": - return Model.B450A_PRO; - case "Base Board Product Name": - case "To be filled by O.E.M.": - return Model.Unknown; - default: - return Model.Unknown; - } - } - } -} \ No newline at end of file diff --git a/Hardware/Mainboard/Mainboard.cs b/Hardware/Mainboard/Mainboard.cs deleted file mode 100644 index 969a328..0000000 --- a/Hardware/Mainboard/Mainboard.cs +++ /dev/null @@ -1,152 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Text; -using OpenHardwareMonitor.Hardware.LPC; - -namespace OpenHardwareMonitor.Hardware.Mainboard { - public class Mainboard : IHardware { - private readonly SMBIOS smbios; - private readonly string name; - private string customName; - private readonly ISettings settings; - private readonly LPCIO lpcio; - private readonly LMSensors lmSensors; - private readonly Hardware[] superIOHardware; - - /// - /// Gets the SMBIOS information. - /// - public SMBIOS SMBIOS => smbios; - - public Mainboard(SMBIOS smbios, ISettings settings) { - this.settings = settings; - this.smbios = smbios; - - Manufacturer manufacturer = smbios.Board == null ? Manufacturer.Unknown : - Identification.GetManufacturer(smbios.Board.ManufacturerName); - - Model model = smbios.Board == null ? Model.Unknown : - Identification.GetModel(smbios.Board.ProductName); - - if (smbios.Board != null) { - if (!string.IsNullOrEmpty(smbios.Board.ProductName)) { - if (manufacturer == Manufacturer.Unknown) - this.name = smbios.Board.ProductName; - else - this.name = manufacturer + " " + - smbios.Board.ProductName; - } else { - this.name = manufacturer.ToString(); - } - } else { - this.name = Manufacturer.Unknown.ToString(); - } - - this.customName = settings.GetValue( - new Identifier(Identifier, "name").ToString(), name); - - ISuperIO[] superIO; - - if (Software.OperatingSystem.IsLinux) { - this.lmSensors = new LMSensors(); - superIO = lmSensors.SuperIO; - } else { - this.lpcio = new LPCIO(); - superIO = lpcio.SuperIO; - } - - superIOHardware = new Hardware[superIO.Length]; - for (int i = 0; i < superIO.Length; i++) - superIOHardware[i] = new SuperIOHardware(this, superIO[i], - manufacturer, model, settings); - } - - public string Name { - get { - return customName; - } - set { - if (!string.IsNullOrEmpty(value)) - customName = value; - else - customName = name; - settings.SetValue(new Identifier(Identifier, "name").ToString(), - customName); - } - } - - public Identifier Identifier { - get { return new Identifier("mainboard"); } - } - - public HardwareType HardwareType { - get { return HardwareType.Mainboard; } - } - - public virtual IHardware Parent { - get { return null; } - } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("Mainboard"); - r.AppendLine(); - r.Append(smbios.GetReport()); - - if (lpcio != null) - r.Append(lpcio.GetReport()); - - byte[] table = - FirmwareTable.GetTable(FirmwareTable.Provider.ACPI, "TAMG"); - if (table != null) { - GigabyteTAMG tamg = new GigabyteTAMG(table); - r.Append(tamg.GetReport()); - } - - return r.ToString(); - } - - public void Update() { } - - public void Close() { - if (lmSensors != null) - lmSensors.Close(); - foreach (Hardware hardware in superIOHardware) - hardware.Close(); - } - - public IHardware[] SubHardware { - get { return superIOHardware; } - } - - public ISensor[] Sensors { - get { return new ISensor[0]; } - } - - #pragma warning disable 67 - public event SensorEventHandler SensorAdded; - public event SensorEventHandler SensorRemoved; - #pragma warning restore 67 - - public void Accept(IVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("visitor"); - visitor.VisitHardware(this); - } - - public void Traverse(IVisitor visitor) { - foreach (IHardware hardware in superIOHardware) - hardware.Accept(visitor); - } - } -} diff --git a/Hardware/Mainboard/MainboardGroup.cs b/Hardware/Mainboard/MainboardGroup.cs deleted file mode 100644 index f7884fc..0000000 --- a/Hardware/Mainboard/MainboardGroup.cs +++ /dev/null @@ -1,37 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.Mainboard { - internal class MainboardGroup : IGroup { - - private readonly Mainboard[] mainboards; - - public MainboardGroup(SMBIOS smbios, ISettings settings) { - mainboards = new Mainboard[1]; - mainboards[0] = new Mainboard(smbios, settings); - } - - public void Close() { - foreach (Mainboard mainboard in mainboards) - mainboard.Close(); - } - - public string GetReport() { - return null; - } - - public IEnumerable Hardware { - get { return mainboards; } - - } - } -} diff --git a/Hardware/Mainboard/Manufacturer.cs b/Hardware/Mainboard/Manufacturer.cs deleted file mode 100644 index 1d168e4..0000000 --- a/Hardware/Mainboard/Manufacturer.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -namespace OpenHardwareMonitor.Hardware.Mainboard { - - internal enum Manufacturer { - Alienware, - Apple, - ASRock, - ASUS, - Dell, - DFI, - ECS, - EPoX, - EVGA, - FIC, - Fujitsu, - Gigabyte, - HP, - IBM, - Intel, - Lenovo, - MSI, - Shuttle, - Supermicro, - Toshiba, - XFX, - Unknown - } - -} diff --git a/Hardware/Mainboard/Model.cs b/Hardware/Mainboard/Model.cs deleted file mode 100644 index 9fbc0c9..0000000 --- a/Hardware/Mainboard/Model.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -// ReSharper disable InconsistentNaming - -namespace OpenHardwareMonitor.Hardware.Mainboard { - - internal enum Model { - // ASRock - _880GMH_USB3, - AOD790GX_128M, - P55_Deluxe, - B85M_DGS, - Z77PRO4M, - AB350M_PRO4, - AB350_PRO4, - AB350M, - Fatal1ty_AB350_Gaming_K4, - AB350M_HDV, - PHANTOM_GAMING_6, - A320M_HDV, - - // ASUS - Crosshair_III_Formula, - M2N_SLI_DELUXE, - M4A79XTD_EVO, - P5W_DH_Deluxe, - P6T, - P6X58D_E, - P8P67, - P8P67_EVO, - P8P67_PRO, - P8P67_M_PRO, - P8Z77_V, - P9X79, - Rampage_Extreme, - Rampage_II_GENE, - PRIME_X370_PRO, - ROG_MAXIMUS_APEX, - ROG_ZENITH_EXTREME, - Z170_A, - TUF_X470_PLUS_GAMING, - - // DFI - LP_BI_P45_T2RS_Elite, - LP_DK_P55_T3eH9, - - // ECS - A890GXM_A, - - // MSI - Z270_PC_MATE, - B360M_PRO_VDH, - B450A_PRO, - - // EVGA - X58_SLI_Classified, - - // Gigabyte - _965P_S3, - EP45_DS3R, - EP45_UD3R, - EX58_EXTREME, - EX58_UD3R, - G41M_Combo, - G41MT_S2, - G41MT_S2P, - _970A_UD3, - MA770T_UD3, - MA770T_UD3P, - MA785GM_US2H, - MA785GMT_UD2H, - MA78LM_S2H, - MA790X_UD3P, - H55_USB3, - H55N_USB3, - H61M_DS2_REV_1_2, - H61M_USB3_B3_REV_2_0, - H67A_UD3H_B3, - H67A_USB3_B3, - P35_DS3, - P35_DS3L, - P55_UD4, - P55A_UD3, - P55M_UD4, - P67A_UD3_B3, - P67A_UD3R_B3, - P67A_UD4_B3, - P8Z68_V_PRO, - X38_DS5, - X58A_UD3R, - X79_UD3, - Z68A_D3H_B3, - Z68AP_D3, - Z68X_UD3H_B3, - Z68X_UD7_B3, - AX370_K7, - Z390_M_GAMING, - Z390_AORUS_ULTRA, - Z390_UD, - AB350_Gaming_3_CF, - X399_AOURUS_GAMING7, - AX370_Gaming_5, - - // Shuttle - FH67, - - // Unknown - Unknown - } -} diff --git a/Hardware/Mainboard/SuperIOHardware.cs b/Hardware/Mainboard/SuperIOHardware.cs deleted file mode 100644 index 7899a85..0000000 --- a/Hardware/Mainboard/SuperIOHardware.cs +++ /dev/null @@ -1,2017 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Threading; -using OpenHardwareMonitor.Hardware.LPC; - -namespace OpenHardwareMonitor.Hardware.Mainboard { - internal sealed class SuperIOHardware : Hardware { - - private readonly Mainboard mainboard; - private readonly ISuperIO superIO; - - private readonly List voltages = new List(); - private readonly List temperatures = new List(); - private readonly List fans = new List(); - private readonly List controls = new List(); - - private delegate float? ReadValueDelegate(int index); - private delegate void UpdateDelegate(); - - // delegates for mainboard specific sensor reading code - private readonly ReadValueDelegate readVoltage; - private readonly ReadValueDelegate readTemperature; - private readonly ReadValueDelegate readFan; - private readonly ReadValueDelegate readControl; - - // delegate for post update mainboard specific code - private readonly UpdateDelegate postUpdate; - - // mainboard specific mutex - - public SuperIOHardware(Mainboard mainboard, ISuperIO superIO, - Manufacturer manufacturer, Model model, ISettings settings) - : base(ChipName.GetName(superIO.Chip), new Identifier("lpc", - superIO.Chip.ToString().ToLowerInvariant()), settings) - { - this.mainboard = mainboard; - this.superIO = superIO; - - IList v; - IList t; - IList f; - IList c; - GetBoardSpecificConfiguration(superIO, manufacturer, model, - out v, out t, out f, out c, - out readVoltage, out readTemperature, out readFan, out readControl, - out postUpdate, out _); - - CreateVoltageSensors(superIO, settings, v); - CreateTemperatureSensors(superIO, settings, t); - CreateFanSensors(superIO, settings, f); - CreateControlSensors(superIO, settings, c); - } - - private void CreateControlSensors(ISuperIO superIO, ISettings settings, - IList c) - { - foreach (Ctrl ctrl in c) { - int index = ctrl.Index; - if (index < superIO.Controls.Length) { - Sensor sensor = new Sensor(ctrl.Name, index, SensorType.Control, - this, settings); - Control control = new Control(sensor, settings, 0, 100); - control.ControlModeChanged += (cc) => { - switch (cc.ControlMode) { - case ControlMode.Undefined: - return; - case ControlMode.Default: - superIO.SetControl(index, null); - break; - case ControlMode.Software: - superIO.SetControl(index, (byte)(cc.SoftwareValue * 2.55)); - break; - default: - return; - } - }; - control.SoftwareControlValueChanged += (cc) => { - if (cc.ControlMode == ControlMode.Software) - superIO.SetControl(index, (byte)(cc.SoftwareValue * 2.55)); - }; - - switch (control.ControlMode) { - case ControlMode.Undefined: - break; - case ControlMode.Default: - superIO.SetControl(index, null); - break; - case ControlMode.Software: - superIO.SetControl(index, (byte)(control.SoftwareValue * 2.55)); - break; - } - - sensor.Control = control; - controls.Add(sensor); - ActivateSensor(sensor); - } - } - } - - private void CreateFanSensors(ISuperIO superIO, ISettings settings, - IList f) - { - foreach (Fan fan in f) { - if (fan.Index < superIO.Fans.Length) { - Sensor sensor = new Sensor(fan.Name, fan.Index, SensorType.Fan, - this, settings); - fans.Add(sensor); - } - } - } - - private void CreateTemperatureSensors(ISuperIO superIO, ISettings settings, - IList t) - { - foreach (Temperature temperature in t) - if (temperature.Index < superIO.Temperatures.Length) { - Sensor sensor = new Sensor(temperature.Name, temperature.Index, - SensorType.Temperature, this, new[] { - new ParameterDescription("Offset [°C]", "Temperature offset.", 0) - }, settings); - temperatures.Add(sensor); - } - } - - private void CreateVoltageSensors(ISuperIO superIO, ISettings settings, - IList v) - { - const string formula = "Voltage = value + (value - Vf) * Ri / Rf."; - foreach (Voltage voltage in v) - if (voltage.Index < superIO.Voltages.Length) { - Sensor sensor = new Sensor(voltage.Name, voltage.Index, - voltage.Hidden, SensorType.Voltage, this, new[] { - new ParameterDescription("Ri [kΩ]", "Input resistance.\n" + - formula, voltage.Ri), - new ParameterDescription("Rf [kΩ]", "Reference resistance.\n" + - formula, voltage.Rf), - new ParameterDescription("Vf [V]", "Reference voltage.\n" + - formula, voltage.Vf) - }, settings); - voltages.Add(sensor); - } - } - - private static void GetBoardSpecificConfiguration(ISuperIO superIO, - Manufacturer manufacturer, Model model, out IList v, - out IList t, out IList f, out IList c, - out ReadValueDelegate readVoltage, - out ReadValueDelegate readTemperature, - out ReadValueDelegate readFan, - out ReadValueDelegate readControl, - out UpdateDelegate postUpdate, out Mutex mutex) { - readVoltage = (index) => superIO.Voltages[index]; - readTemperature = (index) => superIO.Temperatures[index]; - readFan = (index) => superIO.Fans[index]; - readControl = (index) => superIO.Controls[index]; - - postUpdate = () => { }; - mutex = null; - - v = new List(); - t = new List(); - f = new List(); - c = new List(); - - switch (superIO.Chip) { - case Chip.IT8688E: - case Chip.IT8705F: - case Chip.IT8712F: - case Chip.IT8716F: - case Chip.IT8718F: - case Chip.IT8720F: - case Chip.IT8726F: - case Chip.IT8665E: - case Chip.IT8686E: - GetITEConfigurationsA(superIO, manufacturer, model, v, t, f, c, - ref readFan, ref postUpdate, ref mutex); - break; - - case Chip.IT8620E: - case Chip.IT8628E: - case Chip.IT8721F: - case Chip.IT8728F: - case Chip.IT8771E: - case Chip.IT8772E: - GetITEConfigurationsB(superIO, manufacturer, model, v, t, f, c); - break; - - case Chip.F71858: - v.Add(new Voltage("VCC3V", 0, 150, 150)); - v.Add(new Voltage("VSB3V", 1, 150, 150)); - v.Add(new Voltage("Battery", 2, 150, 150)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - case Chip.F71862: - case Chip.F71869: - case Chip.F71869A: - case Chip.F71882: - case Chip.F71889AD: - case Chip.F71889ED: - case Chip.F71889F: - case Chip.F71808E: - GetFintekConfiguration(superIO, manufacturer, model, v, t, f, c); - break; - - case Chip.W83627EHF: - GetWinbondConfigurationEHF(manufacturer, model, v, t, f); - break; - case Chip.W83627DHG: - case Chip.W83627DHGP: - case Chip.W83667HG: - case Chip.W83667HGB: - GetWinbondConfigurationHG(manufacturer, model, v, t, f); - break; - case Chip.W83627HF: - case Chip.W83627THF: - case Chip.W83687THF: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("AVCC", 3, 34, 51)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("5VSB", 5, 34, 51)); - v.Add(new Voltage("VBat", 6)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - break; - case Chip.NCT6771F: - case Chip.NCT6776F: - GetNuvotonConfigurationF(superIO, manufacturer, model, v, t, f, c); - break; - case Chip.NCT610X: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #0", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #1", 4, true)); - v.Add(new Voltage("Voltage #2", 5, true)); - v.Add(new Voltage("Reserved", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("Voltage #10", 9, true)); - t.Add(new Temperature("SYS", 1)); - t.Add(new Temperature("CPU Core", 2)); - t.Add(new Temperature("AUX", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - case Chip.NCT6779D: - case Chip.NCT6791D: - case Chip.NCT6792D: - case Chip.NCT6793D: - case Chip.NCT6795D: - case Chip.NCT6796D: - case Chip.NCT6797D: - case Chip.NCT6798D: - GetNuvotonConfigurationD(superIO, manufacturer, model, v, t, f, c); - break; - default: - GetDefaultConfiguration(superIO, v, t, f, c); - break; - } - } - - private static void GetDefaultConfiguration(ISuperIO superIO, - IList v, IList t, IList f, IList c) - { - for (int i = 0; i < superIO.Voltages.Length; i++) - v.Add(new Voltage("Voltage #" + (i + 1), i, true)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - } - - private static void GetITEConfigurationsA(ISuperIO superIO, - Manufacturer manufacturer, Model model, - IList v, IList t, IList f, IList c, - ref ReadValueDelegate readFan, ref UpdateDelegate postUpdate, - ref Mutex mutex) - { - switch (manufacturer) { - case Manufacturer.ASUS: - switch (model) { - case Model.Crosshair_III_Formula: // IT8720F - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 0)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - case Model.M2N_SLI_DELUXE: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+3.3V", 1)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 30, 10)); - v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Chassis Fan #1", 1)); - f.Add(new Fan("Power Fan", 2)); - break; - case Model.M4A79XTD_EVO: // IT8720F - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Chassis Fan #1", 1)); - f.Add(new Fan("Chassis Fan #2", 2)); - break; - case Model.PRIME_X370_PRO: // IT8665E - case Model.TUF_X470_PLUS_GAMING: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("SB 2.5V", 1)); - v.Add(new Voltage("+12V", 2, 5, 1)); - v.Add(new Voltage("+5V", 3, 1.5f, 1)); - v.Add(new Voltage("Voltage #4", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("+3.3V", 7, 10, 10)); - v.Add(new Voltage("VBAT", 8, 10, 10)); - v.Add(new Voltage("Voltage #10", 9, true)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 1)); - t.Add(new Temperature("PCH", 2)); - for (int i = 3; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - f.Add(new Fan("CPU Fan", 0)); - for (int i = 1; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - - case Model.ROG_ZENITH_EXTREME: // IT8665E - v.Add(new Voltage("Vcore", 0, 10, 10, 0, false)); - v.Add(new Voltage("DIMM AB", 1, 10, 10, 0, false)); - v.Add(new Voltage("+12V", 2, 5, 1,0, false)); - v.Add(new Voltage("+5V", 3, 1.5f, 1, 0, false)); - v.Add(new Voltage("SB 1.05V", 4, 10, 10, 0, false)); - v.Add(new Voltage("DIMM CD", 5, 10, 10, 0, false)); - v.Add(new Voltage("1.8V PLL", 6, 10, 10, 0, false)); - v.Add(new Voltage("+3.3V", 7, 10, 10, 0, false)); - v.Add(new Voltage("VBat", 8, 10, 10, 0, false)); - - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Mainboard", 1)); - t.Add(new Temperature("CPU Socket", 2)); - t.Add(new Temperature("Temperature #4", 3)); - t.Add(new Temperature("Temperature #5", 4)); - t.Add(new Temperature("VRM", 5)); - - int x = superIO.Fans.Length; - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Chassis Fan 1", 1)); - f.Add(new Fan("Chassis Fan 2", 2)); - f.Add(new Fan("High Amp Fan", 3)); - f.Add(new Fan("Fan 5", 4)); - f.Add(new Fan("Fan 6", 5)); - - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Voltage #8", 7, true)); - v.Add(new Voltage("VBat", 8)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - - case Manufacturer.ASRock: - switch (model) { - case Model.P55_Deluxe: // IT8720F - GetASRockConfiguration(superIO, v, t, f, - ref readFan, ref postUpdate, ref mutex); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Voltage #8", 7, true)); - v.Add(new Voltage("VBat", 8)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - }; - break; - - case Manufacturer.DFI: - switch (model) { - case Model.LP_BI_P45_T2RS_Elite: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("FSB VTT", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 30, 10)); - v.Add(new Voltage("NB Core", 5)); - v.Add(new Voltage("VDIMM", 6)); - v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("System", 1)); - t.Add(new Temperature("Chipset", 2)); - f.Add(new Fan("Fan #1", 0)); - f.Add(new Fan("Fan #2", 1)); - f.Add(new Fan("Fan #3", 2)); - break; - case Model.LP_DK_P55_T3eH9: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("VTT", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 30, 10)); - v.Add(new Voltage("CPU PLL", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("Chipset", 0)); - t.Add(new Temperature("CPU PWM", 1)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("Fan #1", 0)); - f.Add(new Fan("Fan #2", 1)); - f.Add(new Fan("Fan #3", 2)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("VTT", 1, true)); - v.Add(new Voltage("+3.3V", 2, true)); - v.Add(new Voltage("+5V", 3, 6.8f, 10, 0, true)); - v.Add(new Voltage("+12V", 4, 30, 10, 0, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("DIMM", 6, true)); - v.Add(new Voltage("+5VSB", 7, 6.8f, 10, 0, true)); - v.Add(new Voltage("VBat", 8)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - - case Manufacturer.Gigabyte: - switch (model) { - case Model._965P_S3: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - break; - case Model.EP45_DS3R: // IT8718F - case Model.EP45_UD3R: - case Model.X38_DS5: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #2", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #1", 3)); - break; - case Model.EX58_EXTREME: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("Northbridge", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #2", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #1", 3)); - break; - case Model.P35_DS3: // IT8718F - case Model.P35_DS3L: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("Power Fan", 3)); - break; - case Model.P55_UD4: // IT8720F - case Model.P55A_UD3: // IT8720F - case Model.P55M_UD4: // IT8720F - case Model.H55_USB3: // IT8720F - case Model.EX58_UD3R: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #2", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #1", 3)); - break; - case Model.H55N_USB3: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - break; - case Model.G41M_Combo: // IT8718F - case Model.G41MT_S2: // IT8718F - case Model.G41MT_S2P: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - break; - case Model._970A_UD3: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("Power Fan", 4)); - c.Add(new Ctrl("PWM 1", 0)); - c.Add(new Ctrl("PWM 2", 1)); - c.Add(new Ctrl("PWM 3", 2)); - break; - case Model.MA770T_UD3: // IT8720F - case Model.MA770T_UD3P: // IT8720F - case Model.MA790X_UD3P: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("Power Fan", 3)); - break; - case Model.MA78LM_S2H: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("VRM", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("Power Fan", 3)); - break; - case Model.MA785GM_US2H: // IT8718F - case Model.MA785GMT_UD2H: // IT8718F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - f.Add(new Fan("NB Fan", 2)); - break; - case Model.X58A_UD3R: // IT8720F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+5V", 3, 6.8f, 10)); - v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("Northbridge", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #2", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #1", 3)); - break; - case Model.AX370_K7: // IT8686E - case Model.AX370_Gaming_5: - case Model.AB350_Gaming_3_CF: // IT8686E - // Note: v3.3, v12, v5, and AVCC3 might be slightly off. - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+3.3V", 1, 0.65f, 1)); - v.Add(new Voltage("+12V", 2, 5, 1)); - v.Add(new Voltage("+5V", 3, 1.5f, 1)); - v.Add(new Voltage("VSOC", 4)); - v.Add(new Voltage("VDDP", 5)); - v.Add(new Voltage("VDRAM", 6)); - v.Add(new Voltage("3VSB", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - v.Add(new Voltage("AVCC3", 9, 7.53f, 1)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("Chipset", 1)); - t.Add(new Temperature("CPU", 2)); - t.Add(new Temperature("PCIEX16", 3)); - t.Add(new Temperature("VRM MOS", 4)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - case Model.Z390_M_GAMING: // IT8688E - case Model.Z390_AORUS_ULTRA: - case Model.Z390_UD: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); - v.Add(new Voltage("+12V", 2, 5f, 1)); - v.Add(new Voltage("+5V", 3, 1.5f, 1)); - v.Add(new Voltage("CPU VCCGT", 4)); - v.Add(new Voltage("CPU VCCSA", 5)); - v.Add(new Voltage("VDDQ", 6)); - v.Add(new Voltage("DDRVTT", 7)); - v.Add(new Voltage("PCHCore", 8)); - v.Add(new Voltage("CPU VCCIO", 9)); - v.Add(new Voltage("DDRVPP", 10)); - t.Add(new Temperature("System1", 0)); - t.Add(new Temperature("PCH", 1)); - t.Add(new Temperature("CPU", 2)); - t.Add(new Temperature("PCIEX16", 3)); - t.Add(new Temperature("VRM MOS", 4)); - t.Add(new Temperature("System2", 5)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("System Fan #3", 3)); - break; - case Model.X399_AOURUS_GAMING7: //ITE IT8686E - v.Add(new Voltage("Vcore", 0, 0, 1, 0, false)); - v.Add(new Voltage("+3.3V", 1, 6.5F, 10, 0, false)); - v.Add(new Voltage("+12V", 2, 5, 1, 0, false)); - v.Add(new Voltage("+5V", 3, 1.5F, 1, 0, false)); - v.Add(new Voltage("DIMM CD", 4, 0, 1, 0, false)); - v.Add(new Voltage("SOC Vcore", 5, 0, 1, 0, false)); - v.Add(new Voltage("DIMM AB", 6, 0, 1, 0, false)); - v.Add(new Voltage("3VSB", 7, 10, 10, 0, false)); - v.Add(new Voltage("VBat", 8, 10, 10, 0, false)); - v.Add(new Voltage("AVCC3", 9, 54, 10, 0, false)); - - t.Add(new Temperature("System 1", 0)); - t.Add(new Temperature("Chipset", 1)); - t.Add(new Temperature("CPU", 2)); - t.Add(new Temperature("PCIE_X16", 3)); - t.Add(new Temperature("VRM", 4)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1, true)); - v.Add(new Voltage("+3.3V", 2, true)); - v.Add(new Voltage("+5V", 3, 6.8f, 10, 0, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Voltage #8", 7, true)); - v.Add(new Voltage("VBat", 8)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Voltage #8", 7, true)); - v.Add(new Voltage("VBat", 8)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - } - - private static void GetASRockConfiguration(ISuperIO superIO, - IList v, IList t, IList f, - ref ReadValueDelegate readFan, ref UpdateDelegate postUpdate, - ref Mutex mutex) - { - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+3.3V", 2)); - v.Add(new Voltage("+12V", 4, 30, 10)); - v.Add(new Voltage("+5V", 5, 6.8f, 10)); - v.Add(new Voltage("VBat", 8)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 1)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Chassis Fan #1", 1)); - - // this mutex is also used by the official ASRock tool - mutex = new Mutex(false, "ASRockOCMark"); - - bool exclusiveAccess = false; - try { - exclusiveAccess = mutex.WaitOne(10, false); - } catch (AbandonedMutexException) { } - catch (InvalidOperationException) { } - - // only read additional fans if we get exclusive access - if (exclusiveAccess) { - - f.Add(new Fan("Chassis Fan #2", 2)); - f.Add(new Fan("Chassis Fan #3", 3)); - f.Add(new Fan("Power Fan", 4)); - - readFan = (index) => { - if (index < 2) { - return superIO.Fans[index]; - } else { - // get GPIO 80-87 - byte? gpio = superIO.ReadGPIO(7); - if (!gpio.HasValue) - return null; - - // read the last 3 fans based on GPIO 83-85 - int[] masks = { 0x05, 0x03, 0x06 }; - return (((gpio.Value >> 3) & 0x07) == - masks[index - 2]) ? superIO.Fans[2] : null; - } - }; - - int fanIndex = 0; - postUpdate = () => { - // get GPIO 80-87 - byte? gpio = superIO.ReadGPIO(7); - if (!gpio.HasValue) - return; - - // prepare the GPIO 83-85 for the next update - int[] masks = { 0x05, 0x03, 0x06 }; - superIO.WriteGPIO(7, - (byte)((gpio.Value & 0xC7) | (masks[fanIndex] << 3))); - fanIndex = (fanIndex + 1) % 3; - }; - } - } - - private static void GetITEConfigurationsB(ISuperIO superIO, - Manufacturer manufacturer, Model model, - IList v, IList t, IList f, IList c) - { - switch (manufacturer) { - case Manufacturer.ECS: - switch (model) { - case Model.A890GXM_A: // IT8721F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("VDIMM", 1)); - v.Add(new Voltage("NB Voltage", 2)); - v.Add(new Voltage("Analog +3.3V", 3, 10, 10)); - // v.Add(new Voltage("VDIMM", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("System", 1)); - t.Add(new Temperature("Northbridge", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - break; - default: - v.Add(new Voltage("Voltage #1", 0, true)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Analog +3.3V", 3, 10, 10, 0, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10, 0, true)); - v.Add(new Voltage("VBat", 8, 10, 10)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - case Manufacturer.Gigabyte: - switch (model) { - case Model.H61M_DS2_REV_1_2: // IT8728F - case Model.H61M_USB3_B3_REV_2_0: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("+12V", 2, 30.9f, 10)); - v.Add(new Voltage("Vcore", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan", 1)); - break; - case Model.H67A_UD3H_B3: // IT8728F - case Model.H67A_USB3_B3: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("+5V", 1, 15, 10)); - v.Add(new Voltage("+12V", 2, 30.9f, 10)); - v.Add(new Voltage("Vcore", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #2", 3)); - break; - case Model.Z68A_D3H_B3: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); - v.Add(new Voltage("+12V", 2, 30.9f, 10)); - v.Add(new Voltage("+5V", 3, 7.15f, 10)); - v.Add(new Voltage("Vcore", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #2", 3)); - break; - case Model.P67A_UD3_B3: // IT8728F - case Model.P67A_UD3R_B3: // IT8728F - case Model.P67A_UD4_B3: // IT8728F - case Model.Z68AP_D3: // IT8728F - case Model.Z68X_UD3H_B3: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); - v.Add(new Voltage("+12V", 2, 30.9f, 10)); - v.Add(new Voltage("+5V", 3, 7.15f, 10)); - v.Add(new Voltage("Vcore", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #2", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("System Fan #1", 3)); - break; - case Model.Z68X_UD7_B3: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); - v.Add(new Voltage("+12V", 2, 30.9f, 10)); - v.Add(new Voltage("+5V", 3, 7.15f, 10)); - v.Add(new Voltage("Vcore", 5)); - v.Add(new Voltage("DIMM", 6)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("System 3", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Power Fan", 1)); - f.Add(new Fan("System Fan #1", 2)); - f.Add(new Fan("System Fan #2", 3)); - f.Add(new Fan("System Fan #3", 4)); - break; - case Model.X79_UD3: // IT8728F - v.Add(new Voltage("VTT", 0)); - v.Add(new Voltage("DIMM CH A/B", 1)); - v.Add(new Voltage("+12V", 2, 10, 2)); - v.Add(new Voltage("+5V", 3, 15, 10)); - v.Add(new Voltage("VIN4", 4)); - v.Add(new Voltage("VCore", 5)); - v.Add(new Voltage("DIMM CH C/D", 6)); - v.Add(new Voltage("+3V Standby", 7, 1, 1)); - v.Add(new Voltage("VBat", 8, 1, 1)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("Northbridge", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("System Fan #1", 1)); - f.Add(new Fan("System Fan #2", 2)); - f.Add(new Fan("System Fan #3", 3)); - break; - default: - v.Add(new Voltage("Voltage #1", 0, true)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10, 0, true)); - v.Add(new Voltage("VBat", 8, 10, 10)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - case Manufacturer.Shuttle: - switch (model) { - case Model.FH67: // IT8772E - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("DIMM", 1)); - v.Add(new Voltage("PCH VCCIO", 2)); - v.Add(new Voltage("CPU VCCIO", 3)); - v.Add(new Voltage("Graphic Voltage", 4)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10)); - v.Add(new Voltage("VBat", 8, 10, 10)); - t.Add(new Temperature("System", 0)); - t.Add(new Temperature("CPU", 1)); - f.Add(new Fan("Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - break; - default: - v.Add(new Voltage("Voltage #1", 0, true)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10, 0, true)); - v.Add(new Voltage("VBat", 8, 10, 10)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - default: - v.Add(new Voltage("Voltage #1", 0, true)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 10, 10, 0, true)); - v.Add(new Voltage("VBat", 8, 10, 10)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - } - - private static void GetFintekConfiguration(ISuperIO superIO, - Manufacturer manufacturer, Model model, - IList v, IList t, IList f, IList c) - { - switch (manufacturer) { - case Manufacturer.EVGA: - switch (model) { - case Model.X58_SLI_Classified: // F71882 - v.Add(new Voltage("VCC3V", 0, 150, 150)); - v.Add(new Voltage("Vcore", 1, 47, 100)); - v.Add(new Voltage("DIMM", 2, 47, 100)); - v.Add(new Voltage("CPU VTT", 3, 24, 100)); - v.Add(new Voltage("IOH Vcore", 4, 24, 100)); - v.Add(new Voltage("+5V", 5, 51, 12)); - v.Add(new Voltage("+12V", 6, 56, 6.8f)); - v.Add(new Voltage("3VSB", 7, 150, 150)); - v.Add(new Voltage("VBat", 8, 150, 150)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("VREG", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Power Fan", 1)); - f.Add(new Fan("Chassis Fan", 2)); - break; - default: - v.Add(new Voltage("VCC3V", 0, 150, 150)); - v.Add(new Voltage("Vcore", 1)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("VSB3V", 7, 150, 150)); - v.Add(new Voltage("VBat", 8, 150, 150)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - break; - } - break; - default: - v.Add(new Voltage("VCC3V", 0, 150, 150)); - v.Add(new Voltage("Vcore", 1)); - v.Add(new Voltage("Voltage #3", 2, true)); - v.Add(new Voltage("Voltage #4", 3, true)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - if (superIO.Chip != Chip.F71808E) - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("VSB3V", 7, 150, 150)); - v.Add(new Voltage("VBat", 8, 150, 150)); - for (int i = 0; i < superIO.Temperatures.Length; i++) - t.Add(new Temperature("Temperature #" + (i + 1), i)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - - break; - } - } - - private static void GetNuvotonConfigurationF(ISuperIO superIO, - Manufacturer manufacturer, Model model, - IList v, IList t, IList f, IList c) - { - switch (manufacturer) { - case Manufacturer.ASUS: - switch (model) { - case Model.P8P67: // NCT6776F - case Model.P8P67_EVO: // NCT6776F - case Model.P8P67_PRO: // NCT6776F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 11, 1)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 12, 3)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 2)); - t.Add(new Temperature("Motherboard", 3)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("Chassis Fan #2", 3)); - c.Add(new Ctrl("Chassis Fan #2", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("Chassis Fan #1", 2)); - break; - case Model.P8P67_M_PRO: // NCT6776F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 11, 1)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 12, 3)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 3)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Chassis Fan #2", 2)); - f.Add(new Fan("Power Fan", 3)); - f.Add(new Fan("Auxiliary Fan", 4)); - break; - case Model.P8Z68_V_PRO: // NCT6776F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 11, 1)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 12, 3)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 2)); - t.Add(new Temperature("Motherboard", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan #" + (i + 1), i)); - break; - case Model.P9X79: // NCT6776F - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 11, 1)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 12, 3)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - case Manufacturer.ASRock: - { - switch (model) - { - case Model.B85M_DGS: - { - v.Add(new Voltage("CPU VCCIN", 0, 1, 1)); - v.Add(new Voltage("+12V", 1, 56, 10)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("VIN1", 4, true)); - v.Add(new Voltage("+5V", 5, 12, 3)); - v.Add(new Voltage("VIN3", 6, true)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 2)); - t.Add(new Temperature("Motherboard", 3)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("Chassis Fan #2", 3)); - c.Add(new Ctrl("Chassis Fan #2", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("Chassis Fan #1", 2)); - } - break; - case Model.Z77PRO4M: //NCT6776F - v.Add(new Voltage("Vcore", 0, 0, 1, 0, false)); - v.Add(new Voltage("+12V", 1, 56, 10, 0, false)); - v.Add(new Voltage("AVCC", 2, 10, 10, 0, false)); - v.Add(new Voltage("3VCC", 3, 10, 10, 0, false)); - //v.Add(new Voltage("#Unused 4", 4, 0, 1, 0, true)); - v.Add(new Voltage("+5V", 5, 20, 10, 0, false)); - //v.Add(new Voltage("#Unused 6", 6, 0, 1, 0, true)); - v.Add(new Voltage("3VSB", 7, 10, 10, 0, false)); - v.Add(new Voltage("VBat", 8, 10, 10, 0, false)); - - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("AUX", 2)); - t.Add(new Temperature("Mainboard", 3)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - } - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - } - - private static void GetNuvotonConfigurationD(ISuperIO superIO, - Manufacturer manufacturer, Model model, - IList v, IList t, IList f, IList c) - { - switch (manufacturer) { - case Manufacturer.ASRock: - switch (model) - { - case Model.A320M_HDV: //NCT6779D - v.Add(new Voltage("Vcore", 0, 10, 10, 0, false)); - v.Add(new Voltage("Chipset 1.05V", 1, 0, 1, 0, false)); - v.Add(new Voltage("AVCC", 2, 10, 10, 0, false)); - v.Add(new Voltage("3VCC", 3, 10, 10, 0, false)); - v.Add(new Voltage("+12V", 4, 56, 10, 0, false)); - v.Add(new Voltage("VcoreRef", 5, 0, 1, 0, false)); - v.Add(new Voltage("DIMM", 6, 0, 1, 0, false)); - v.Add(new Voltage("3VSB", 7, 10, 10, 0, false)); - v.Add(new Voltage("VBat", 8, 10, 10, 0, false)); - //v.Add(new Voltage("#Unused 9", 9, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused 10", 10, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused 11", 11, 34, 34, 0, true)); - v.Add(new Voltage("+5V", 12, 20, 10, 0, false)); - //v.Add(new Voltage("#Unused 13", 13, 10, 10, 0, true)); - //v.Add(new Voltage("#Unused 14", 14, 0, 1, 0, true)); - - //t.Add(new Temperature("#Unused 0", 0)); - //t.Add(new Temperature("#Unused 1", 1)); - t.Add(new Temperature("Mainboard", 2)); - //t.Add(new Temperature("#Unused 3", 3)); - //t.Add(new Temperature("#Unused 4", 4)); - t.Add(new Temperature("AUX", 5)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - - case Model.AB350_PRO4: //NCT6779D - case Model.AB350M_PRO4: - case Model.AB350M: - case Model.Fatal1ty_AB350_Gaming_K4: - case Model.AB350M_HDV: - v.Add(new Voltage("1 Vcore", 0, 10, 10, 0, false)); - //v.Add(new Voltage("#Unused", 1, 0, 1, 0, true)); - v.Add(new Voltage("3 AVCC", 2, 10, 10, 0, false)); - v.Add(new Voltage("4 3VCC", 3, 10, 10, 0, false)); - v.Add(new Voltage("5 +12V", 4, 28, 5, 0, false)); - //v.Add(new Voltage("#Unused 5", 5, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused 6", 6, 0, 1, 0, true)); - v.Add(new Voltage("3VSB", 7, 10, 10, 0, false)); - v.Add(new Voltage("9 VBat", 8, 34, 34)); - //v.Add(new Voltage("#Unused 9", 9, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused 10", 10, 0, 1, 0, true)); - v.Add(new Voltage("Chipset 1.05V", 11, 0, 1, 0, false)); - v.Add(new Voltage("+5V", 12, 20, 10, 0, false)); - //v.Add(new Voltage("#Unused 13", 13, 0, 1, 0, true)); - v.Add(new Voltage("+1.8V", 14, 0, 1, 0, false)); - - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("Mainboard", 2)); - t.Add(new Temperature("AUX", 3)); - t.Add(new Temperature("VRM", 4)); - t.Add(new Temperature("AUXTIN2", 5)); - t.Add(new Temperature("Temperature #6", 6)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - - case Model.PHANTOM_GAMING_6: //NCT6779D - v.Add(new Voltage("Vcore", 0, 10, 10, 0, false)); - v.Add(new Voltage("Chipset 1.05V", 1, 0, 1, 0, false)); - v.Add(new Voltage("AVCC", 2, 10, 10, 0, false)); - v.Add(new Voltage("3VCC", 3, 10, 10, 0, false)); - v.Add(new Voltage("+12V", 4, 56, 10, 0, false)); - v.Add(new Voltage("VDDCR_SOC", 5, 0, 1, 0, false)); - v.Add(new Voltage("DIMM", 6, 0, 1, 0, false)); - v.Add(new Voltage("3VSB", 7, 10, 10, 0, false)); - v.Add(new Voltage("VBat", 8, 10, 10, 0, false)); - //v.Add(new Voltage("#Unused", 9, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused", 10, 0, 1, 0, true)); - //v.Add(new Voltage("#Unused", 11, 0, 1, 0, true)); - v.Add(new Voltage("+5V", 12, 20, 10, 0, false)); - v.Add(new Voltage("+1.8V", 13, 10, 10, 0, false)); - //v.Add(new Voltage("unused", 14, 34, 34, 0, true)); - - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Mainboard", 1)); - t.Add(new Temperature("AUX", 2)); - t.Add(new Temperature("Chipset", 3)); - t.Add(new Temperature("Core VRM", 4)); - t.Add(new Temperature("Core SOC", 5)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - - default: - v.Add(new Voltage("Vcore", 0, 10,10, 0, false)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("Voltage #11", 10, true)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("Voltage #13", 12, true)); - v.Add(new Voltage("Voltage #14", 13, true)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - t.Add(new Temperature("Temperature #4", 4)); - t.Add(new Temperature("Temperature #5", 5)); - t.Add(new Temperature("Temperature #6", 6)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - case Manufacturer.ASUS: - switch (model) { - case Model.P8Z77_V: // NCT6779D - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("Voltage #11", 10, true)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("Voltage #13", 12, true)); - v.Add(new Voltage("Voltage #14", 13, true)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Chassis Fan #2", 2)); - f.Add(new Fan("Chassis Fan #3", 3)); - c.Add(new Ctrl("Chassis Fan #1", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("Chassis Fan #2", 2)); - c.Add(new Ctrl("Chassis Fan #3", 3)); - break; - case Model.ROG_MAXIMUS_APEX: // NCT6793D - v.Add(new Voltage("Vcore", 0, 2, 2)); - v.Add(new Voltage("+5V", 1, 4, 1)); - v.Add(new Voltage("AVSB", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("+12V", 4, 11, 1)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("CPU GFX", 6, 2, 2)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("DIMM", 10, 1, 1)); - v.Add(new Voltage("VCCSA", 11)); - v.Add(new Voltage("PCH Core", 12)); - v.Add(new Voltage("CPU PLLs", 13)); - v.Add(new Voltage("CPU VCCIO/IMC", 14)); - t.Add(new Temperature("CPU (PECI)", 0)); - t.Add(new Temperature("T2", 1)); - t.Add(new Temperature("T1", 2)); - t.Add(new Temperature("CPU", 3)); - t.Add(new Temperature("PCH", 4)); - t.Add(new Temperature("Temperature #4", 5)); - t.Add(new Temperature("Temperature #5", 6)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Chassis Fan #2", 2)); - f.Add(new Fan("Chassis Fan #3", 3)); - f.Add(new Fan("AIO Pump", 4)); - c.Add(new Ctrl("Chassis Fan #1", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("Chassis Fan #2", 2)); - c.Add(new Ctrl("Chassis Fan #3", 3)); - c.Add(new Ctrl("AIO Pump", 4)); - break; - case Model.Z170_A: //NCT6793D - v.Add(new Voltage("Vcore", 0, 2, 2)); - v.Add(new Voltage("+5V", 1, 4, 1)); - v.Add(new Voltage("AVSB", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("+12V", 4, 11, 1)); - v.Add(new Voltage("Voltage #6", 5, 0, 1, 0, true)); - v.Add(new Voltage("CPU GFX", 6, 2, 2)); - v.Add(new Voltage("3VSB_ATX", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("DIMM", 10, 1, 1)); - v.Add(new Voltage("VCCSA", 11)); - v.Add(new Voltage("PCH Core", 12)); - v.Add(new Voltage("CPU PLLs", 13)); - v.Add(new Voltage("CPU VCCIO/IMC", 14)); - - t.Add(new Temperature("CPU (PECI)", 0)); - t.Add(new Temperature("CPU", 1)); - t.Add(new Temperature("Mainboard", 2)); - t.Add(new Temperature("CPU", 3)); - t.Add(new Temperature("PCH", 4)); - t.Add(new Temperature("Temperature #4", 5)); - t.Add(new Temperature("Temperature #5", 6)); - - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("Voltage #11", 10, true)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("Voltage #13", 12, true)); - v.Add(new Voltage("Voltage #14", 13, true)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - t.Add(new Temperature("Temperature #4", 4)); - t.Add(new Temperature("Temperature #5", 5)); - t.Add(new Temperature("Temperature #6", 6)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - case Manufacturer.MSI: - switch (model) { - case Model.B360M_PRO_VDH: // NCT6797D - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+5V", 1, 4, 1)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("+12V", 4, 11, 1)); - //v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("CPU I/O", 6)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("CPU SA", 10)); - //v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("NB/SoC", 12)); - v.Add(new Voltage("DIMM", 13, 1, 1)); - //v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("Motherboard", 2)); - t.Add(new Temperature("Temperature #1", 5)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("System Fan #1", 2)); - f.Add(new Fan("System Fan #2", 3)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("System Fan #1", 2)); - c.Add(new Ctrl("System Fan #2", 3)); - break; - case Model.B450A_PRO: // NCT6797D - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+5V", 1, 4, 1)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("+12V", 4, 11, 1)); - //v.Add(new Voltage("Voltage #6", 5, false)); - //v.Add(new Voltage("CPU I/O", 6)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("CPU SA", 10)); - //v.Add(new Voltage("Voltage #12", 11, false)); - v.Add(new Voltage("NB/SoC", 12)); - v.Add(new Voltage("DIMM", 13, 1, 1)); - //v.Add(new Voltage("Voltage #15", 14, false)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("CPU (PECI)", 1)); - t.Add(new Temperature("System", 2)); - t.Add(new Temperature("VR MOSS", 3)); - t.Add(new Temperature("PCH", 5)); - f.Add(new Fan("Pump Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("System Fan #1", 2)); - f.Add(new Fan("System Fan #2", 3)); - f.Add(new Fan("System Fan #3", 4)); - f.Add(new Fan("System Fan #4", 5)); - c.Add(new Ctrl("Pump Fan", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("System Fan #1", 2)); - c.Add(new Ctrl("System Fan #2", 3)); - c.Add(new Ctrl("System Fan #3", 4)); - c.Add(new Ctrl("System Fan #4", 5)); - break; - case Model.Z270_PC_MATE: // NCT6795D - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+5V", 1, 4, 1)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("+12V", 4, 11, 1)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("CPU I/O", 6)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("CPU SA", 10)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("PCH", 12)); - v.Add(new Voltage("DIMM", 13, 1, 1)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("Pump Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("System Fan #1", 2)); - f.Add(new Fan("System Fan #2", 3)); - f.Add(new Fan("System Fan #3", 4)); - f.Add(new Fan("System Fan #4", 5)); - c.Add(new Ctrl("Pump Fan", 0)); - c.Add(new Ctrl("CPU Fan", 1)); - c.Add(new Ctrl("System Fan #1", 2)); - c.Add(new Ctrl("System Fan #2", 3)); - c.Add(new Ctrl("System Fan #3", 4)); - c.Add(new Ctrl("System Fan #4", 5)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("Voltage #11", 10, true)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("Voltage #13", 12, true)); - v.Add(new Voltage("Voltage #14", 13, true)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - t.Add(new Temperature("Temperature #4", 4)); - t.Add(new Temperature("Temperature #5", 5)); - t.Add(new Temperature("Temperature #6", 6)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("VTT", 9)); - v.Add(new Voltage("Voltage #11", 10, true)); - v.Add(new Voltage("Voltage #12", 11, true)); - v.Add(new Voltage("Voltage #13", 12, true)); - v.Add(new Voltage("Voltage #14", 13, true)); - v.Add(new Voltage("Voltage #15", 14, true)); - t.Add(new Temperature("CPU Core", 0)); - t.Add(new Temperature("Temperature #1", 1)); - t.Add(new Temperature("Temperature #2", 2)); - t.Add(new Temperature("Temperature #3", 3)); - t.Add(new Temperature("Temperature #4", 4)); - t.Add(new Temperature("Temperature #5", 5)); - t.Add(new Temperature("Temperature #6", 6)); - for (int i = 0; i < superIO.Fans.Length; i++) - f.Add(new Fan("Fan #" + (i + 1), i)); - for (int i = 0; i < superIO.Controls.Length; i++) - c.Add(new Ctrl("Fan Control #" + (i + 1), i)); - break; - } - } - - private static void GetWinbondConfigurationEHF(Manufacturer manufacturer, - Model model, IList v, IList t, IList f) - { - switch (manufacturer) { - case Manufacturer.ASRock: - switch (model) { - case Model.AOD790GX_128M: // W83627EHF - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 4, 10, 10)); - v.Add(new Voltage("+5V", 5, 20, 10)); - v.Add(new Voltage("+12V", 6, 28, 5)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("CPU Fan", 0)); - f.Add(new Fan("Chassis Fan", 1)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("Voltage #10", 9, true)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - f.Add(new Fan("CPU Fan #2", 3)); - f.Add(new Fan("Auxiliary Fan #2", 4)); - break; - } break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - v.Add(new Voltage("Voltage #10", 9, true)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - f.Add(new Fan("CPU Fan #2", 3)); - f.Add(new Fan("Auxiliary Fan #2", 4)); - break; - } - } - - private static void GetWinbondConfigurationHG(Manufacturer manufacturer, - Model model, IList v, IList t, IList f) - { - switch (manufacturer) { - case Manufacturer.ASRock: - switch (model) { - case Model._880GMH_USB3: // W83627DHG-P - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 5, 15, 7.5f)); - v.Add(new Voltage("+12V", 6, 56, 10)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("Chassis Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - f.Add(new Fan("CPU Fan #2", 3)); - f.Add(new Fan("Auxiliary Fan #2", 4)); - break; - } - break; - case Manufacturer.ASUS: - switch (model) { - case Model.P6T: // W83667HG - case Model.P6X58D_E: // W83667HG - case Model.Rampage_II_GENE: // W83667HG - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 11.5f, 1.91f)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 15, 7.5f)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("Chassis Fan #2", 3)); - f.Add(new Fan("Chassis Fan #3", 4)); - break; - case Model.Rampage_Extreme: // W83667HG - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("+12V", 1, 12, 2)); - v.Add(new Voltage("Analog +3.3V", 2, 34, 34)); - v.Add(new Voltage("+3.3V", 3, 34, 34)); - v.Add(new Voltage("+5V", 4, 15, 7.5f)); - v.Add(new Voltage("Standby +3.3V", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Motherboard", 2)); - f.Add(new Fan("Chassis Fan #1", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Power Fan", 2)); - f.Add(new Fan("Chassis Fan #2", 3)); - f.Add(new Fan("Chassis Fan #3", 4)); - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - f.Add(new Fan("CPU Fan #2", 3)); - f.Add(new Fan("Auxiliary Fan #2", 4)); - break; - } - break; - default: - v.Add(new Voltage("Vcore", 0)); - v.Add(new Voltage("Voltage #2", 1, true)); - v.Add(new Voltage("AVCC", 2, 34, 34)); - v.Add(new Voltage("3VCC", 3, 34, 34)); - v.Add(new Voltage("Voltage #5", 4, true)); - v.Add(new Voltage("Voltage #6", 5, true)); - v.Add(new Voltage("Voltage #7", 6, true)); - v.Add(new Voltage("3VSB", 7, 34, 34)); - v.Add(new Voltage("VBat", 8, 34, 34)); - t.Add(new Temperature("CPU", 0)); - t.Add(new Temperature("Auxiliary", 1)); - t.Add(new Temperature("System", 2)); - f.Add(new Fan("System Fan", 0)); - f.Add(new Fan("CPU Fan", 1)); - f.Add(new Fan("Auxiliary Fan", 2)); - f.Add(new Fan("CPU Fan #2", 3)); - f.Add(new Fan("Auxiliary Fan #2", 4)); - break; - } - } - - public override HardwareType HardwareType { - get { return HardwareType.SuperIO; } - } - - public override IHardware Parent { - get { return mainboard; } - } - - - public override string GetReport() { - return superIO.GetReport(); - } - - public override void Update() { - superIO.Update(); - - foreach (Sensor sensor in voltages) { - float? value = readVoltage(sensor.Index); - if (value.HasValue) { - sensor.Value = value + (value - sensor.Parameters[2].Value) * - sensor.Parameters[0].Value / sensor.Parameters[1].Value; - ActivateSensor(sensor); - } - } - - foreach (Sensor sensor in temperatures) { - float? value = readTemperature(sensor.Index); - if (value.HasValue) { - sensor.Value = value + sensor.Parameters[0].Value; - ActivateSensor(sensor); - } - } - - foreach (Sensor sensor in fans) { - float? value = readFan(sensor.Index); - if (value.HasValue) { - sensor.Value = value; - if (value.Value > 0) - ActivateSensor(sensor); - } - } - - foreach (Sensor sensor in controls) { - float? value = readControl(sensor.Index); - sensor.Value = value; - } - - postUpdate(); - } - - public override void Close() { - foreach (Sensor sensor in controls) { - // restore all controls back to default - superIO.SetControl(sensor.Index, null); - } - base.Close(); - } - - private class Voltage { - public readonly string Name; - public readonly int Index; - public readonly float Ri; - public readonly float Rf; - public readonly float Vf; - public readonly bool Hidden; - - public Voltage(string name, int index) : - this(name, index, false) { } - - public Voltage(string name, int index, bool hidden) : - this(name, index, 0, 1, 0, hidden) { } - - public Voltage(string name, int index, float ri, float rf) : - this(name, index, ri, rf, 0, false) { } - - // float ri = 0, float rf = 1, float vf = 0, bool hidden = false) - - public Voltage(string name, int index, - float ri, float rf, float vf, bool hidden) - { - this.Name = name; - this.Index = index; - this.Ri = ri; - this.Rf = rf; - this.Vf = vf; - this.Hidden = hidden; - } - } - - private class Temperature { - public readonly string Name; - public readonly int Index; - - public Temperature(string name, int index) { - this.Name = name; - this.Index = index; - } - } - - private class Fan { - public readonly string Name; - public readonly int Index; - - public Fan(string name, int index) { - this.Name = name; - this.Index = index; - } - } - - private class Ctrl { - public readonly string Name; - public readonly int Index; - - public Ctrl(string name, int index) { - this.Name = name; - this.Index = index; - } - } - } -} diff --git a/Hardware/Nic/Nic.cs b/Hardware/Nic/Nic.cs deleted file mode 100644 index 3f53d51..0000000 --- a/Hardware/Nic/Nic.cs +++ /dev/null @@ -1,98 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) 2012 Michael Möller - -using System; -using System.Diagnostics; -using System.Net.NetworkInformation; - -namespace OpenHardwareMonitor.Hardware.Nic { - internal class Nic : Hardware { - private Sensor dataUploaded; - private Sensor dataDownloaded; - private Sensor uploadSpeed; - private Sensor downloadSpeed; - private Sensor networkUtilization; - private long lastTick; - - private long bytesUploaded; - private long bytesDownloaded; - private readonly NetworkInterface networkInterface; - - public Nic(NetworkInterface networkInterface, ISettings settings) - : base(networkInterface.Name, new Identifier("nic", networkInterface.Id), settings) { - this.networkInterface = networkInterface; - dataUploaded = new Sensor("Data Uploaded", 2, SensorType.Data, this, settings); - ActivateSensor(dataUploaded); - dataDownloaded = new Sensor("Data Downloaded", 3, SensorType.Data, this, settings); - ActivateSensor(dataDownloaded); - uploadSpeed = new Sensor("Upload Speed", 7, SensorType.Throughput, this, settings); - ActivateSensor(uploadSpeed); - downloadSpeed = new Sensor("Download Speed", 8, SensorType.Throughput, this, settings); - ActivateSensor(downloadSpeed); - networkUtilization = new Sensor("Network Utilization", 1, SensorType.Load, this, settings); - ActivateSensor(networkUtilization); - bytesUploaded = NetworkInterface.GetIPStatistics().BytesSent; - bytesDownloaded = NetworkInterface.GetIPStatistics().BytesReceived; - lastTick = Stopwatch.GetTimestamp(); - } - - public override HardwareType HardwareType { - get { - return HardwareType.NIC; - } - } - - internal NetworkInterface NetworkInterface { - get { - return networkInterface; - } - } - - public override void Update() { - long newTick = Stopwatch.GetTimestamp(); - double dt = new TimeSpan(newTick - lastTick).TotalSeconds; - - IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetIPv4Statistics(); - - // Report out the number of GB (2^30 Bytes) that this interface has up/downloaded. Note - // that these values can reset back at zero (eg: after waking from sleep). - dataUploaded.Value = (float)(interfaceStats.BytesSent / (double)0x40000000); - dataDownloaded.Value = (float)(interfaceStats.BytesReceived / (double)0x40000000); - - // Detect a reset in interface stats if the new total is less than what was previously - // seen. While setting the previous values to zero doesn't encapsulate the value the - // instant before the reset, it is the best approximation we have. - if (interfaceStats.BytesSent < bytesUploaded || interfaceStats.BytesReceived < bytesDownloaded) { - bytesUploaded = 0; - bytesDownloaded = 0; - } - - long dBytesUploaded = interfaceStats.BytesSent - bytesUploaded; - long dBytesDownloaded = interfaceStats.BytesReceived - bytesDownloaded; - - // Upload and download speeds are reported as the number of bytes transfered over the - // time difference since the last report. In this way, the values represent the average - // number of bytes up/downloaded in a second. - uploadSpeed.Value = (float)(dBytesUploaded / dt); - downloadSpeed.Value = (float)(dBytesDownloaded / dt); - - // Network speed is in bits per second, so when calculating the load on the NIC we first - // grab the total number of bits up/downloaded - long dbits = (dBytesUploaded + dBytesDownloaded) * 8; - - // Converts the ratio of total bits transferred over time over theoretical max bits - // transfer rate into a percentage load - double load = (dbits / dt / NetworkInterface.Speed) * 100; - - // Finally clamp the value between 0% and 100% to avoid reporting nonsensical numbers - networkUtilization.Value = (float)Math.Min(Math.Max(load, 0), 100); - - // Store the recorded values and time, so they can be used in the next update - bytesUploaded = interfaceStats.BytesSent; - bytesDownloaded = interfaceStats.BytesReceived; - lastTick = newTick; - } - } -} \ No newline at end of file diff --git a/Hardware/Nic/NicGroup.cs b/Hardware/Nic/NicGroup.cs deleted file mode 100644 index a876fb3..0000000 --- a/Hardware/Nic/NicGroup.cs +++ /dev/null @@ -1,103 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) 2012 Michael Möller - -using System.Collections.Generic; -using System.Linq; -using System.Net.NetworkInformation; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Nic { - internal class NicGroup : IGroup { - private readonly ISettings _settings; - private List _hardware = new List(); - private readonly object _scanLock = new object(); - private readonly Dictionary _nics = new Dictionary(); - - public NicGroup(ISettings settings) { - _settings = settings; - ScanNics(settings); - NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged; - NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAddressChanged; - } - - private void ScanNics(ISettings settings) { - // If no network is marked up (excluding loopback and tunnel) then don't scan - // for interfaces. - if (!NetworkInterface.GetIsNetworkAvailable()) { - return; - } - - // When multiple events fire concurrently, we don't want threads interfering - // with others as they manipulate non-thread safe state. - lock (_scanLock) { - var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(DesiredNetworkType) - .OrderBy(x => x.Name); - - var scanned = networkInterfaces.ToDictionary(x => x.Id, x => x); - var newNics = scanned.Where(x => !_nics.ContainsKey(x.Key)); - var removedNics = _nics.Where(x => !scanned.ContainsKey(x.Key)).ToList(); - - - - foreach (var nic in removedNics) { - nic.Value.Close(); - _nics.Remove(nic.Key); - } - - foreach (var nic in newNics) { - _nics.Add(nic.Key, new Nic(nic.Value, settings)); - } - - _hardware = _nics.Values.OrderBy(x => x.Name).ToList(); - } - } - - private void NetworkChange_NetworkAddressChanged(object sender, System.EventArgs e) { - ScanNics(_settings); - } - - private static bool DesiredNetworkType(NetworkInterface nic) { - switch (nic.NetworkInterfaceType) { - case NetworkInterfaceType.Loopback: - case NetworkInterfaceType.Tunnel: - case NetworkInterfaceType.Unknown: - return false; - default: - return true; - } - } - - public string GetReport() { - var report = new StringBuilder(); - - foreach (Nic hw in _hardware) { - report.AppendLine(hw.NetworkInterface.Description); - report.AppendLine(hw.NetworkInterface.OperationalStatus.ToString()); - report.AppendLine(); - foreach (var sensor in hw.Sensors) { - report.AppendLine(sensor.Name); - report.AppendLine(sensor.Value.ToString() + sensor.SensorType); - report.AppendLine(); - } - } - - return report.ToString(); - } - - public IEnumerable Hardware { - get { - return _hardware; - } - } - - public void Close() { - NetworkChange.NetworkAddressChanged -= NetworkChange_NetworkAddressChanged; - NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAddressChanged; - foreach (var nic in _hardware) - nic.Close(); - } - } -} \ No newline at end of file diff --git a/Hardware/Nvidia/NVAPI.cs b/Hardware/Nvidia/NVAPI.cs deleted file mode 100644 index d005d31..0000000 --- a/Hardware/Nvidia/NVAPI.cs +++ /dev/null @@ -1,434 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - Copyright (C) 2011 Christian Vallières - -*/ - -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Nvidia { - - internal enum NvStatus { - OK = 0, - ERROR = -1, - LIBRARY_NOT_FOUND = -2, - NO_IMPLEMENTATION = -3, - API_NOT_INTIALIZED = -4, - INVALID_ARGUMENT = -5, - NVIDIA_DEVICE_NOT_FOUND = -6, - END_ENUMERATION = -7, - INVALID_HANDLE = -8, - INCOMPATIBLE_STRUCT_VERSION = -9, - HANDLE_INVALIDATED = -10, - OPENGL_CONTEXT_NOT_CURRENT = -11, - NO_GL_EXPERT = -12, - INSTRUMENTATION_DISABLED = -13, - EXPECTED_LOGICAL_GPU_HANDLE = -100, - EXPECTED_PHYSICAL_GPU_HANDLE = -101, - EXPECTED_DISPLAY_HANDLE = -102, - INVALID_COMBINATION = -103, - NOT_SUPPORTED = -104, - PORTID_NOT_FOUND = -105, - EXPECTED_UNATTACHED_DISPLAY_HANDLE = -106, - INVALID_PERF_LEVEL = -107, - DEVICE_BUSY = -108, - NV_PERSIST_FILE_NOT_FOUND = -109, - PERSIST_DATA_NOT_FOUND = -110, - EXPECTED_TV_DISPLAY = -111, - EXPECTED_TV_DISPLAY_ON_DCONNECTOR = -112, - NO_ACTIVE_SLI_TOPOLOGY = -113, - SLI_RENDERING_MODE_NOTALLOWED = -114, - EXPECTED_DIGITAL_FLAT_PANEL = -115, - ARGUMENT_EXCEED_MAX_SIZE = -116, - DEVICE_SWITCHING_NOT_ALLOWED = -117, - TESTING_CLOCKS_NOT_SUPPORTED = -118, - UNKNOWN_UNDERSCAN_CONFIG = -119, - TIMEOUT_RECONFIGURING_GPU_TOPO = -120, - DATA_NOT_FOUND = -121, - EXPECTED_ANALOG_DISPLAY = -122, - NO_VIDLINK = -123, - REQUIRES_REBOOT = -124, - INVALID_HYBRID_MODE = -125, - MIXED_TARGET_TYPES = -126, - SYSWOW64_NOT_SUPPORTED = -127, - IMPLICIT_SET_GPU_TOPOLOGY_CHANGE_NOT_ALLOWED = -128, - REQUEST_USER_TO_CLOSE_NON_MIGRATABLE_APPS = -129, - OUT_OF_MEMORY = -130, - WAS_STILL_DRAWING = -131, - FILE_NOT_FOUND = -132, - TOO_MANY_UNIQUE_STATE_OBJECTS = -133, - INVALID_CALL = -134, - D3D10_1_LIBRARY_NOT_FOUND = -135, - FUNCTION_NOT_FOUND = -136 - } - - internal enum NvThermalController { - NONE = 0, - GPU_INTERNAL, - ADM1032, - MAX6649, - MAX1617, - LM99, - LM89, - LM64, - ADT7473, - SBMAX6649, - VBIOSEVT, - OS, - UNKNOWN = -1, - } - - internal enum NvThermalTarget { - NONE = 0, - GPU = 1, - MEMORY = 2, - POWER_SUPPLY = 4, - BOARD = 8, - ALL = 15, - UNKNOWN = -1 - }; - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvSensor { - public NvThermalController Controller; - public uint DefaultMinTemp; - public uint DefaultMaxTemp; - public uint CurrentTemp; - public NvThermalTarget Target; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvGPUThermalSettings { - public uint Version; - public uint Count; - [MarshalAs(UnmanagedType.ByValArray, - SizeConst = NVAPI.MAX_THERMAL_SENSORS_PER_GPU)] - public NvSensor[] Sensor; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NvDisplayHandle { - private readonly IntPtr ptr; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NvPhysicalGpuHandle { - private readonly IntPtr ptr; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvClocks { - public uint Version; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_CLOCKS_PER_GPU)] - public uint[] Clock; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvPState { - public bool Present; - public int Percentage; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvPStates { - public uint Version; - public uint Flags; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_PSTATES_PER_GPU)] - public NvPState[] PStates; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvUsages { - public uint Version; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_USAGES_PER_GPU)] - public uint[] Usage; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvCooler { - public int Type; - public int Controller; - public int DefaultMin; - public int DefaultMax; - public int CurrentMin; - public int CurrentMax; - public int CurrentLevel; - public int DefaultPolicy; - public int CurrentPolicy; - public int Target; - public int ControlType; - public int Active; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvGPUCoolerSettings { - public uint Version; - public uint Count; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_COOLER_PER_GPU)] - public NvCooler[] Cooler; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvLevel { - public int Level; - public int Policy; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvGPUCoolerLevels { - public uint Version; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = NVAPI.MAX_COOLER_PER_GPU)] - public NvLevel[] Levels; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvMemoryInfo { - public uint Version; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = - NVAPI.MAX_MEMORY_VALUES_PER_GPU)] - public uint[] Values; - } - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - internal struct NvDisplayDriverVersion { - public uint Version; - public uint DriverVersion; - public uint BldChangeListNum; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NVAPI.SHORT_STRING_MAX)] - public string BuildBranch; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NVAPI.SHORT_STRING_MAX)] - public string Adapter; - } - - internal class NVAPI { - - public const int MAX_PHYSICAL_GPUS = 64; - public const int SHORT_STRING_MAX = 64; - - public const int MAX_THERMAL_SENSORS_PER_GPU = 3; - public const int MAX_CLOCKS_PER_GPU = 0x120; - public const int MAX_PSTATES_PER_GPU = 8; - public const int MAX_USAGES_PER_GPU = 33; - public const int MAX_COOLER_PER_GPU = 20; - public const int MAX_MEMORY_VALUES_PER_GPU = 5; - - public static readonly uint GPU_THERMAL_SETTINGS_VER = (uint) - Marshal.SizeOf(typeof(NvGPUThermalSettings)) | 0x10000; - public static readonly uint GPU_CLOCKS_VER = (uint) - Marshal.SizeOf(typeof(NvClocks)) | 0x20000; - public static readonly uint GPU_PSTATES_VER = (uint) - Marshal.SizeOf(typeof(NvPStates)) | 0x10000; - public static readonly uint GPU_USAGES_VER = (uint) - Marshal.SizeOf(typeof(NvUsages)) | 0x10000; - public static readonly uint GPU_COOLER_SETTINGS_VER = (uint) - Marshal.SizeOf(typeof(NvGPUCoolerSettings)) | 0x20000; - public static readonly uint GPU_MEMORY_INFO_VER = (uint) - Marshal.SizeOf(typeof(NvMemoryInfo)) | 0x20000; - public static readonly uint DISPLAY_DRIVER_VERSION_VER = (uint) - Marshal.SizeOf(typeof(NvDisplayDriverVersion)) | 0x10000; - public static readonly uint GPU_COOLER_LEVELS_VER = (uint) - Marshal.SizeOf(typeof(NvGPUCoolerLevels)) | 0x10000; - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate IntPtr nvapi_QueryInterfaceDelegate(uint id); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate NvStatus NvAPI_InitializeDelegate(); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate NvStatus NvAPI_GPU_GetFullNameDelegate( - NvPhysicalGpuHandle gpuHandle, StringBuilder name); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetThermalSettingsDelegate( - NvPhysicalGpuHandle gpuHandle, int sensorIndex, - ref NvGPUThermalSettings nvGPUThermalSettings); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_EnumNvidiaDisplayHandleDelegate(int thisEnum, - ref NvDisplayHandle displayHandle); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GetPhysicalGPUsFromDisplayDelegate( - NvDisplayHandle displayHandle, [Out] NvPhysicalGpuHandle[] gpuHandles, - out uint gpuCount); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_EnumPhysicalGPUsDelegate( - [Out] NvPhysicalGpuHandle[] gpuHandles, out int gpuCount); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetTachReadingDelegate( - NvPhysicalGpuHandle gpuHandle, out int value); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetAllClocksDelegate( - NvPhysicalGpuHandle gpuHandle, ref NvClocks nvClocks); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetPStatesDelegate( - NvPhysicalGpuHandle gpuHandle, ref NvPStates nvPStates); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetUsagesDelegate( - NvPhysicalGpuHandle gpuHandle, ref NvUsages nvUsages); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetCoolerSettingsDelegate( - NvPhysicalGpuHandle gpuHandle, int coolerIndex, - ref NvGPUCoolerSettings nvGPUCoolerSettings); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_SetCoolerLevelsDelegate( - NvPhysicalGpuHandle gpuHandle, int coolerIndex, - ref NvGPUCoolerLevels NvGPUCoolerLevels); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetMemoryInfoDelegate( - NvDisplayHandle displayHandle, ref NvMemoryInfo nvMemoryInfo); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GetDisplayDriverVersionDelegate( - NvDisplayHandle displayHandle, [In, Out] ref NvDisplayDriverVersion - nvDisplayDriverVersion); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GetInterfaceVersionStringDelegate( - StringBuilder version); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate NvStatus NvAPI_GPU_GetPCIIdentifiersDelegate( - NvPhysicalGpuHandle gpuHandle, out uint deviceId, out uint subSystemId, - out uint revisionId, out uint extDeviceId); - - private static readonly bool available; - [DllImport(@"nvapi.dll", EntryPoint = @"nvapi_QueryInterface", CallingConvention = CallingConvention.Cdecl, PreserveSig = true)] - private static extern IntPtr NvAPI32_QueryInterface(uint interfaceId); - [DllImport(@"nvapi64.dll", EntryPoint = @"nvapi_QueryInterface", CallingConvention = CallingConvention.Cdecl, PreserveSig = true)] - private static extern IntPtr NvAPI64_QueryInterface(uint interfaceId); - private static readonly NvAPI_InitializeDelegate NvAPI_Initialize; - private static readonly NvAPI_GPU_GetFullNameDelegate - _NvAPI_GPU_GetFullName; - private static readonly NvAPI_GetInterfaceVersionStringDelegate - _NvAPI_GetInterfaceVersionString; - - public static readonly NvAPI_GPU_GetThermalSettingsDelegate - NvAPI_GPU_GetThermalSettings; - public static readonly NvAPI_EnumNvidiaDisplayHandleDelegate - NvAPI_EnumNvidiaDisplayHandle; - public static readonly NvAPI_GetPhysicalGPUsFromDisplayDelegate - NvAPI_GetPhysicalGPUsFromDisplay; - public static readonly NvAPI_EnumPhysicalGPUsDelegate - NvAPI_EnumPhysicalGPUs; - public static readonly NvAPI_GPU_GetTachReadingDelegate - NvAPI_GPU_GetTachReading; - public static readonly NvAPI_GPU_GetAllClocksDelegate - NvAPI_GPU_GetAllClocks; - public static readonly NvAPI_GPU_GetPStatesDelegate - NvAPI_GPU_GetPStates; - public static readonly NvAPI_GPU_GetUsagesDelegate - NvAPI_GPU_GetUsages; - public static readonly NvAPI_GPU_GetCoolerSettingsDelegate - NvAPI_GPU_GetCoolerSettings; - public static readonly NvAPI_GPU_SetCoolerLevelsDelegate - NvAPI_GPU_SetCoolerLevels; - public static readonly NvAPI_GPU_GetMemoryInfoDelegate - NvAPI_GPU_GetMemoryInfo; - public static readonly NvAPI_GetDisplayDriverVersionDelegate - NvAPI_GetDisplayDriverVersion; - public static readonly NvAPI_GPU_GetPCIIdentifiersDelegate - NvAPI_GPU_GetPCIIdentifiers; - - private NVAPI() { } - - public static NvStatus NvAPI_GPU_GetFullName(NvPhysicalGpuHandle gpuHandle, - out string name) { - StringBuilder builder = new StringBuilder(SHORT_STRING_MAX); - NvStatus status; - if (_NvAPI_GPU_GetFullName != null) - status = _NvAPI_GPU_GetFullName(gpuHandle, builder); - else - status = NvStatus.FUNCTION_NOT_FOUND; - name = builder.ToString(); - return status; - } - - public static NvStatus NvAPI_GetInterfaceVersionString(out string version) { - StringBuilder builder = new StringBuilder(SHORT_STRING_MAX); - NvStatus status; - if (_NvAPI_GetInterfaceVersionString != null) - status = _NvAPI_GetInterfaceVersionString(builder); - else - status = NvStatus.FUNCTION_NOT_FOUND; - version = builder.ToString(); - return status; - } - - private static string GetDllName() { - if (IntPtr.Size == 4) { - return "nvapi.dll"; - } else { - return "nvapi64.dll"; - } - } - - private static void GetDelegate(uint id, out T newDelegate) - where T : class { - IntPtr ptr; - if (IntPtr.Size == 4) - { - ptr = NvAPI32_QueryInterface(id); - } - else - { - ptr = NvAPI64_QueryInterface(id); - } - if (ptr != IntPtr.Zero) { - newDelegate = - Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T; - } else { - newDelegate = null; - } - } - - static NVAPI() { - try { - GetDelegate(0x0150E828, out NvAPI_Initialize); - } catch (DllNotFoundException) { return; } - catch (EntryPointNotFoundException) { return; } - catch (ArgumentNullException) { return; } - - if (NvAPI_Initialize() == NvStatus.OK) { - GetDelegate(0xE3640A56, out NvAPI_GPU_GetThermalSettings); - GetDelegate(0xCEEE8E9F, out _NvAPI_GPU_GetFullName); - GetDelegate(0x9ABDD40D, out NvAPI_EnumNvidiaDisplayHandle); - GetDelegate(0x34EF9506, out NvAPI_GetPhysicalGPUsFromDisplay); - GetDelegate(0xE5AC921F, out NvAPI_EnumPhysicalGPUs); - GetDelegate(0x5F608315, out NvAPI_GPU_GetTachReading); - GetDelegate(0x1BD69F49, out NvAPI_GPU_GetAllClocks); - GetDelegate(0x60DED2ED, out NvAPI_GPU_GetPStates); - GetDelegate(0x189A1FDF, out NvAPI_GPU_GetUsages); - GetDelegate(0xDA141340, out NvAPI_GPU_GetCoolerSettings); - GetDelegate(0x891FA0AE, out NvAPI_GPU_SetCoolerLevels); - GetDelegate(0x774AA982, out NvAPI_GPU_GetMemoryInfo); - GetDelegate(0xF951A4D1, out NvAPI_GetDisplayDriverVersion); - GetDelegate(0x01053FA5, out _NvAPI_GetInterfaceVersionString); - GetDelegate(0x2DDFB66E, out NvAPI_GPU_GetPCIIdentifiers); - - available = true; - } - } - - public static bool IsAvailable { - get { return available; } - } - - } -} diff --git a/Hardware/Nvidia/NVML.cs b/Hardware/Nvidia/NVML.cs deleted file mode 100644 index e9fcd48..0000000 --- a/Hardware/Nvidia/NVML.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware.Nvidia { - internal class NVML { - private const string LinuxDllName = "nvidia-ml"; - - private delegate NvmlReturn WindowsNvmlDelegate(); - private WindowsNvmlDelegate WindowsNvmlInit; - private WindowsNvmlDelegate WindowsNvmlShutdown; - - private delegate NvmlReturn WindowsNvmlGetHandleDelegate(int index, out NvmlDevice device); - private WindowsNvmlGetHandleDelegate WindowsNvmlDeviceGetHandleByIndex; - - private delegate NvmlReturn WindowsNvmlGetPowerUsageDelegate(NvmlDevice device, out int power); - private WindowsNvmlGetPowerUsageDelegate WindowsNvmlDeviceGetPowerUsage; - - private readonly IntPtr windowsDll; - - internal bool Initialised { get; } - - internal NVML() { - if (Software.OperatingSystem.IsLinux) { - try { - Initialised = (LinuxNvmlInit() == NvmlReturn.Success); - } - catch (DllNotFoundException) { - return; - } - catch (EntryPointNotFoundException) { - try { - Initialised = (LinuxNvmlInitLegacy() == NvmlReturn.Success); - } - catch (EntryPointNotFoundException) { - return; - } - } - } - else if (IsNvmlCompatibleWindowsVersion()) { - // Attempt to load the Nvidia Management Library from the - // windows standard search order for applications. This will - // help installations that either have the library in - // %windir%/system32 or provide their own library - windowsDll = LoadLibrary("nvml.dll"); - - // If there is no dll in the path, then attempt to load it - // from program files - if (windowsDll == IntPtr.Zero) - { - var programFilesDirectory = Environment.ExpandEnvironmentVariables("%ProgramW6432%"); - var dllPath = Path.Combine(programFilesDirectory, @"NVIDIA Corporation\NVSMI\nvml.dll"); - - windowsDll = LoadLibrary(dllPath); - } - - if (windowsDll == IntPtr.Zero) - return; - - Initialised = InitialiseDelegates() && (WindowsNvmlInit() == NvmlReturn.Success); - } - } - - private static bool IsNvmlCompatibleWindowsVersion() - { - return Software.OperatingSystem.Is64Bit && - ((Environment.OSVersion.Version.Major > 6) || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 1)); - } - - private bool InitialiseDelegates() - { - var nvmlInit = GetProcAddress(windowsDll, "nvmlInit_v2"); - if (nvmlInit != IntPtr.Zero) - WindowsNvmlInit = (WindowsNvmlDelegate)Marshal.GetDelegateForFunctionPointer(nvmlInit, typeof(WindowsNvmlDelegate)); - else { - nvmlInit = GetProcAddress(windowsDll, "nvmlInit"); - if (nvmlInit != IntPtr.Zero) - WindowsNvmlInit = (WindowsNvmlDelegate)Marshal.GetDelegateForFunctionPointer(nvmlInit, typeof(WindowsNvmlDelegate)); - else - return false; - } - - var nvmlShutdown = GetProcAddress(windowsDll, "nvmlShutdown"); - if (nvmlShutdown != IntPtr.Zero) - WindowsNvmlShutdown = (WindowsNvmlDelegate)Marshal.GetDelegateForFunctionPointer(nvmlShutdown, typeof(WindowsNvmlDelegate)); - else - return false; - - var nvmlGetHandle = GetProcAddress(windowsDll, "nvmlDeviceGetHandleByIndex_v2"); - if (nvmlGetHandle != IntPtr.Zero) - WindowsNvmlDeviceGetHandleByIndex = (WindowsNvmlGetHandleDelegate)Marshal.GetDelegateForFunctionPointer(nvmlGetHandle, typeof(WindowsNvmlGetHandleDelegate)); - else { - nvmlGetHandle = GetProcAddress(windowsDll, "nvmlDeviceGetHandleByIndex"); - if (nvmlGetHandle != IntPtr.Zero) - WindowsNvmlDeviceGetHandleByIndex = (WindowsNvmlGetHandleDelegate)Marshal.GetDelegateForFunctionPointer(nvmlGetHandle, typeof(WindowsNvmlGetHandleDelegate)); - else - return false; - } - - var nvmlGetPowerUsage = GetProcAddress(windowsDll, "nvmlDeviceGetPowerUsage"); - if (nvmlGetPowerUsage != IntPtr.Zero) - WindowsNvmlDeviceGetPowerUsage = (WindowsNvmlGetPowerUsageDelegate)Marshal.GetDelegateForFunctionPointer(nvmlGetPowerUsage, typeof(WindowsNvmlGetPowerUsageDelegate)); - else - return false; - - return true; - } - - internal void Close() { - if (Initialised) { - if (Software.OperatingSystem.IsLinux) - LinuxNvmlShutdown(); - else if (windowsDll != IntPtr.Zero) { - WindowsNvmlShutdown(); - FreeLibrary(windowsDll); - } - } - } - - internal NvmlDevice? NvmlDeviceGetHandleByIndex(int index) { - if (Initialised) { - NvmlDevice nvmlDevice; - if (Software.OperatingSystem.IsLinux) { - try { - if (LinuxNvmlDeviceGetHandleByIndex(index, out nvmlDevice) == NvmlReturn.Success) - return nvmlDevice; - } - catch (EntryPointNotFoundException) { - if (LinuxNvmlDeviceGetHandleByIndexLegacy(index, out nvmlDevice) == NvmlReturn.Success) - return nvmlDevice; - } - } - else if (WindowsNvmlDeviceGetHandleByIndex(index, out nvmlDevice) == NvmlReturn.Success) - return nvmlDevice; - } - - return null; - } - - internal int? NvmlDeviceGetPowerUsage(NvmlDevice nvmlDevice) { - if (Initialised) { - int powerUsage; - if (Software.OperatingSystem.IsLinux) { - if (LinuxNvmlDeviceGetPowerUsage(nvmlDevice, out powerUsage) == NvmlReturn.Success) - return powerUsage; - } - else if (WindowsNvmlDeviceGetPowerUsage(nvmlDevice, out powerUsage) == NvmlReturn.Success) - return powerUsage; - } - - return null; - } - - [DllImport("kernel32")] - private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string dllPath); - - [DllImport("kernel32", ExactSpelling = true)] - private static extern IntPtr GetProcAddress(IntPtr module, string methodName); - - [DllImport("kernel32")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool FreeLibrary(IntPtr module); - - [DllImport(LinuxDllName, EntryPoint = "nvmlInit_v2", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlInit(); - - [DllImport(LinuxDllName, EntryPoint = "nvmlInit", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlInitLegacy(); - - [DllImport(LinuxDllName, EntryPoint = "nvmlShutdown", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlShutdown(); - - [DllImport(LinuxDllName, EntryPoint = "nvmlDeviceGetHandleByIndex_v2", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlDeviceGetHandleByIndex(int index, out NvmlDevice device); - - [DllImport(LinuxDllName, EntryPoint = "nvmlDeviceGetHandleByIndex", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlDeviceGetHandleByIndexLegacy(int index, out NvmlDevice device); - - [DllImport(LinuxDllName, EntryPoint = "nvmlDeviceGetPowerUsage", ExactSpelling = true)] - private static extern NvmlReturn LinuxNvmlDeviceGetPowerUsage(NvmlDevice device, out int power); - } -} diff --git a/Hardware/Nvidia/NvidiaGPU.cs b/Hardware/Nvidia/NvidiaGPU.cs deleted file mode 100644 index b7f5fe3..0000000 --- a/Hardware/Nvidia/NvidiaGPU.cs +++ /dev/null @@ -1,507 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2015 Michael Möller - Copyright (C) 2011 Christian Vallières - -*/ - -using System; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Nvidia { - internal class NvidiaGPU : Hardware { - - private readonly int adapterIndex; - private readonly NvPhysicalGpuHandle handle; - private readonly NvDisplayHandle? displayHandle; - private readonly NVML nvml; - private readonly NvmlDevice? nvmlDevice; - - private readonly Sensor[] temperatures; - private readonly Sensor fan; - private readonly Sensor[] clocks; - private readonly Sensor[] loads; - private readonly Sensor control; - private readonly Sensor memoryLoad; - private readonly Sensor memoryUsed; - private readonly Sensor memoryFree; - private readonly Sensor memoryAvail; - private readonly Sensor powerUsage; - private readonly Control fanControl; - - public NvidiaGPU(int adapterIndex, NvPhysicalGpuHandle handle, - NvDisplayHandle? displayHandle, ISettings settings, NVML nvml) - : base(GetName(handle), new Identifier("nvidiagpu", - adapterIndex.ToString(CultureInfo.InvariantCulture)), settings) { - this.adapterIndex = adapterIndex; - this.handle = handle; - this.displayHandle = displayHandle; - this.nvml = nvml; - - NvGPUThermalSettings thermalSettings = GetThermalSettings(); - temperatures = new Sensor[thermalSettings.Count]; - for (int i = 0; i < temperatures.Length; i++) { - NvSensor sensor = thermalSettings.Sensor[i]; - string name; - switch (sensor.Target) { - case NvThermalTarget.BOARD: name = "GPU Board"; break; - case NvThermalTarget.GPU: name = "GPU Core"; break; - case NvThermalTarget.MEMORY: name = "GPU Memory"; break; - case NvThermalTarget.POWER_SUPPLY: name = "GPU Power Supply"; break; - case NvThermalTarget.UNKNOWN: name = "GPU Unknown"; break; - default: name = "GPU"; break; - } - temperatures[i] = new Sensor(name, i, SensorType.Temperature, this, - new ParameterDescription[0], settings); - ActivateSensor(temperatures[i]); - } - - int value; - if (NVAPI.NvAPI_GPU_GetTachReading != null && - NVAPI.NvAPI_GPU_GetTachReading(handle, out value) == NvStatus.OK) { - if (value >= 0) { - fan = new Sensor("GPU", 0, SensorType.Fan, this, settings); - ActivateSensor(fan); - } - } - - clocks = new Sensor[3]; - clocks[0] = new Sensor("GPU Core", 0, SensorType.Clock, this, settings); - clocks[1] = new Sensor("GPU Memory", 1, SensorType.Clock, this, settings); - clocks[2] = new Sensor("GPU Shader", 2, SensorType.Clock, this, settings); - for (int i = 0; i < clocks.Length; i++) - ActivateSensor(clocks[i]); - - loads = new Sensor[3]; - loads[0] = new Sensor("GPU Core", 0, SensorType.Load, this, settings); - loads[1] = new Sensor("GPU Memory Controller", 1, SensorType.Load, this, settings); - loads[2] = new Sensor("GPU Video Engine", 2, SensorType.Load, this, settings); - memoryLoad = new Sensor("GPU Memory", 3, SensorType.Load, this, settings); - memoryFree = new Sensor("GPU Memory Free", 1, SensorType.SmallData, this, settings); - memoryUsed = new Sensor("GPU Memory Used", 2, SensorType.SmallData, this, settings); - memoryAvail = new Sensor("GPU Memory Total", 3, SensorType.SmallData, this, settings); - control = new Sensor("GPU Fan", 0, SensorType.Control, this, settings); - - NvGPUCoolerSettings coolerSettings = GetCoolerSettings(); - if (coolerSettings.Count > 0) { - fanControl = new Control(control, settings, - coolerSettings.Cooler[0].DefaultMin, - coolerSettings.Cooler[0].DefaultMax); - fanControl.ControlModeChanged += ControlModeChanged; - fanControl.SoftwareControlValueChanged += SoftwareControlValueChanged; - ControlModeChanged(fanControl); - control.Control = fanControl; - } - - if (nvml.Initialised) - { - nvmlDevice = nvml.NvmlDeviceGetHandleByIndex(adapterIndex); - if (nvmlDevice.HasValue) { - powerUsage = new Sensor("GPU Package", 0, SensorType.Power, this, settings); - } - } - - Update(); - } - - private static string GetName(NvPhysicalGpuHandle handle) { - string gpuName; - if (NVAPI.NvAPI_GPU_GetFullName(handle, out gpuName) == NvStatus.OK) { - return "NVIDIA " + gpuName.Trim(); - } else { - return "NVIDIA"; - } - } - - public override HardwareType HardwareType { - get { return HardwareType.GpuNvidia; } - } - - private NvGPUThermalSettings GetThermalSettings() { - NvGPUThermalSettings settings = new NvGPUThermalSettings(); - settings.Version = NVAPI.GPU_THERMAL_SETTINGS_VER; - settings.Count = NVAPI.MAX_THERMAL_SENSORS_PER_GPU; - settings.Sensor = new NvSensor[NVAPI.MAX_THERMAL_SENSORS_PER_GPU]; - if (!(NVAPI.NvAPI_GPU_GetThermalSettings != null && - NVAPI.NvAPI_GPU_GetThermalSettings(handle, (int)NvThermalTarget.ALL, - ref settings) == NvStatus.OK)) - { - settings.Count = 0; - } - return settings; - } - - private NvGPUCoolerSettings GetCoolerSettings() { - NvGPUCoolerSettings settings = new NvGPUCoolerSettings(); - settings.Version = NVAPI.GPU_COOLER_SETTINGS_VER; - settings.Cooler = new NvCooler[NVAPI.MAX_COOLER_PER_GPU]; - if (!(NVAPI.NvAPI_GPU_GetCoolerSettings != null && - NVAPI.NvAPI_GPU_GetCoolerSettings(handle, 0, - ref settings) == NvStatus.OK)) - { - settings.Count = 0; - } - return settings; - } - - private uint[] GetClocks() { - NvClocks allClocks = new NvClocks(); - allClocks.Version = NVAPI.GPU_CLOCKS_VER; - allClocks.Clock = new uint[NVAPI.MAX_CLOCKS_PER_GPU]; - if (NVAPI.NvAPI_GPU_GetAllClocks != null && - NVAPI.NvAPI_GPU_GetAllClocks(handle, ref allClocks) == NvStatus.OK) { - return allClocks.Clock; - } - return null; - } - - public override void Update() { - NvGPUThermalSettings settings = GetThermalSettings(); - foreach (Sensor sensor in temperatures) - sensor.Value = settings.Sensor[sensor.Index].CurrentTemp; - - if (fan != null) { - int value = 0; - NVAPI.NvAPI_GPU_GetTachReading(handle, out value); - fan.Value = value; - } - - uint[] values = GetClocks(); - if (values != null) { - clocks[1].Value = 0.001f * values[8]; - if (values[30] != 0) { - clocks[0].Value = 0.0005f * values[30]; - clocks[2].Value = 0.001f * values[30]; - } else { - clocks[0].Value = 0.001f * values[0]; - clocks[2].Value = 0.001f * values[14]; - } - } - - NvPStates states = new NvPStates(); - states.Version = NVAPI.GPU_PSTATES_VER; - states.PStates = new NvPState[NVAPI.MAX_PSTATES_PER_GPU]; - if (NVAPI.NvAPI_GPU_GetPStates != null && - NVAPI.NvAPI_GPU_GetPStates(handle, ref states) == NvStatus.OK) { - for (int i = 0; i < 3; i++) - if (states.PStates[i].Present) { - loads[i].Value = states.PStates[i].Percentage; - ActivateSensor(loads[i]); - } - } else { - NvUsages usages = new NvUsages(); - usages.Version = NVAPI.GPU_USAGES_VER; - usages.Usage = new uint[NVAPI.MAX_USAGES_PER_GPU]; - if (NVAPI.NvAPI_GPU_GetUsages != null && - NVAPI.NvAPI_GPU_GetUsages(handle, ref usages) == NvStatus.OK) { - loads[0].Value = usages.Usage[2]; - loads[1].Value = usages.Usage[6]; - loads[2].Value = usages.Usage[10]; - for (int i = 0; i < 3; i++) - ActivateSensor(loads[i]); - } - } - - - NvGPUCoolerSettings coolerSettings = GetCoolerSettings(); - if (coolerSettings.Count > 0) { - control.Value = coolerSettings.Cooler[0].CurrentLevel; - ActivateSensor(control); - } - - NvMemoryInfo memoryInfo = new NvMemoryInfo(); - memoryInfo.Version = NVAPI.GPU_MEMORY_INFO_VER; - memoryInfo.Values = new uint[NVAPI.MAX_MEMORY_VALUES_PER_GPU]; - if (NVAPI.NvAPI_GPU_GetMemoryInfo != null && displayHandle.HasValue && - NVAPI.NvAPI_GPU_GetMemoryInfo(displayHandle.Value, ref memoryInfo) == - NvStatus.OK) { - uint totalMemory = memoryInfo.Values[0]; - uint freeMemory = memoryInfo.Values[4]; - float usedMemory = Math.Max(totalMemory - freeMemory, 0); - memoryFree.Value = (float)freeMemory/ 1024; - memoryAvail.Value = (float)totalMemory/ 1024; - memoryUsed.Value = usedMemory/ 1024; - memoryLoad.Value = 100f * usedMemory / totalMemory; - ActivateSensor(memoryAvail); - ActivateSensor(memoryUsed); - ActivateSensor(memoryFree); - ActivateSensor(memoryLoad); - } - - if (nvml.Initialised && nvmlDevice.HasValue) { - var result = nvml.NvmlDeviceGetPowerUsage(nvmlDevice.Value); - if (result.HasValue) { - powerUsage.Value = (float)result.Value / 1000; - ActivateSensor(powerUsage); - } - } - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("Nvidia GPU"); - r.AppendLine(); - - r.AppendFormat("Name: {0}{1}", name, Environment.NewLine); - r.AppendFormat("Index: {0}{1}", adapterIndex, Environment.NewLine); - - if (displayHandle.HasValue && NVAPI.NvAPI_GetDisplayDriverVersion != null) { - NvDisplayDriverVersion driverVersion = new NvDisplayDriverVersion(); - driverVersion.Version = NVAPI.DISPLAY_DRIVER_VERSION_VER; - if (NVAPI.NvAPI_GetDisplayDriverVersion(displayHandle.Value, - ref driverVersion) == NvStatus.OK) { - r.Append("Driver Version: "); - r.Append(driverVersion.DriverVersion / 100); - r.Append("."); - r.Append((driverVersion.DriverVersion % 100).ToString("00", - CultureInfo.InvariantCulture)); - r.AppendLine(); - r.Append("Driver Branch: "); - r.AppendLine(driverVersion.BuildBranch); - } - } - r.AppendLine(); - - if (NVAPI.NvAPI_GPU_GetPCIIdentifiers != null) { - uint deviceId, subSystemId, revisionId, extDeviceId; - - NvStatus status = NVAPI.NvAPI_GPU_GetPCIIdentifiers(handle, - out deviceId, out subSystemId, out revisionId, out extDeviceId); - - if (status == NvStatus.OK) { - r.Append("DeviceID: 0x"); - r.AppendLine(deviceId.ToString("X", CultureInfo.InvariantCulture)); - r.Append("SubSystemID: 0x"); - r.AppendLine(subSystemId.ToString("X", CultureInfo.InvariantCulture)); - r.Append("RevisionID: 0x"); - r.AppendLine(revisionId.ToString("X", CultureInfo.InvariantCulture)); - r.Append("ExtDeviceID: 0x"); - r.AppendLine(extDeviceId.ToString("X", CultureInfo.InvariantCulture)); - r.AppendLine(); - } - } - - if (NVAPI.NvAPI_GPU_GetThermalSettings != null) { - NvGPUThermalSettings settings = new NvGPUThermalSettings(); - settings.Version = NVAPI.GPU_THERMAL_SETTINGS_VER; - settings.Count = NVAPI.MAX_THERMAL_SENSORS_PER_GPU; - settings.Sensor = new NvSensor[NVAPI.MAX_THERMAL_SENSORS_PER_GPU]; - - NvStatus status = NVAPI.NvAPI_GPU_GetThermalSettings(handle, - (int)NvThermalTarget.ALL, ref settings); - - r.AppendLine("Thermal Settings"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < settings.Count; i++) { - r.AppendFormat(" Sensor[{0}].Controller: {1}{2}", i, - settings.Sensor[i].Controller, Environment.NewLine); - r.AppendFormat(" Sensor[{0}].DefaultMinTemp: {1}{2}", i, - settings.Sensor[i].DefaultMinTemp, Environment.NewLine); - r.AppendFormat(" Sensor[{0}].DefaultMaxTemp: {1}{2}", i, - settings.Sensor[i].DefaultMaxTemp, Environment.NewLine); - r.AppendFormat(" Sensor[{0}].CurrentTemp: {1}{2}", i, - settings.Sensor[i].CurrentTemp, Environment.NewLine); - r.AppendFormat(" Sensor[{0}].Target: {1}{2}", i, - settings.Sensor[i].Target, Environment.NewLine); - } - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetAllClocks != null) { - NvClocks allClocks = new NvClocks(); - allClocks.Version = NVAPI.GPU_CLOCKS_VER; - allClocks.Clock = new uint[NVAPI.MAX_CLOCKS_PER_GPU]; - NvStatus status = NVAPI.NvAPI_GPU_GetAllClocks(handle, ref allClocks); - - r.AppendLine("Clocks"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < allClocks.Clock.Length; i++) - if (allClocks.Clock[i] > 0) { - r.AppendFormat(" Clock[{0}]: {1}{2}", i, allClocks.Clock[i], - Environment.NewLine); - } - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetTachReading != null) { - int tachValue; - NvStatus status = NVAPI.NvAPI_GPU_GetTachReading(handle, out tachValue); - - r.AppendLine("Tachometer"); - r.AppendLine(); - if (status == NvStatus.OK) { - r.AppendFormat(" Value: {0}{1}", tachValue, Environment.NewLine); - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetPStates != null) { - NvPStates states = new NvPStates(); - states.Version = NVAPI.GPU_PSTATES_VER; - states.PStates = new NvPState[NVAPI.MAX_PSTATES_PER_GPU]; - NvStatus status = NVAPI.NvAPI_GPU_GetPStates(handle, ref states); - - r.AppendLine("P-States"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < states.PStates.Length; i++) - if (states.PStates[i].Present) - r.AppendFormat(" Percentage[{0}]: {1}{2}", i, - states.PStates[i].Percentage, Environment.NewLine); - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetUsages != null) { - NvUsages usages = new NvUsages(); - usages.Version = NVAPI.GPU_USAGES_VER; - usages.Usage = new uint[NVAPI.MAX_USAGES_PER_GPU]; - NvStatus status = NVAPI.NvAPI_GPU_GetUsages(handle, ref usages); - - r.AppendLine("Usages"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < usages.Usage.Length; i++) - if (usages.Usage[i] > 0) - r.AppendFormat(" Usage[{0}]: {1}{2}", i, - usages.Usage[i], Environment.NewLine); - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetCoolerSettings != null) { - NvGPUCoolerSettings settings = new NvGPUCoolerSettings(); - settings.Version = NVAPI.GPU_COOLER_SETTINGS_VER; - settings.Cooler = new NvCooler[NVAPI.MAX_COOLER_PER_GPU]; - NvStatus status = - NVAPI.NvAPI_GPU_GetCoolerSettings(handle, 0, ref settings); - - r.AppendLine("Cooler Settings"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < settings.Count; i++) { - r.AppendFormat(" Cooler[{0}].Type: {1}{2}", i, - settings.Cooler[i].Type, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].Controller: {1}{2}", i, - settings.Cooler[i].Controller, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].DefaultMin: {1}{2}", i, - settings.Cooler[i].DefaultMin, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].DefaultMax: {1}{2}", i, - settings.Cooler[i].DefaultMax, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].CurrentMin: {1}{2}", i, - settings.Cooler[i].CurrentMin, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].CurrentMax: {1}{2}", i, - settings.Cooler[i].CurrentMax, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].CurrentLevel: {1}{2}", i, - settings.Cooler[i].CurrentLevel, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].DefaultPolicy: {1}{2}", i, - settings.Cooler[i].DefaultPolicy, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].CurrentPolicy: {1}{2}", i, - settings.Cooler[i].CurrentPolicy, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].Target: {1}{2}", i, - settings.Cooler[i].Target, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].ControlType: {1}{2}", i, - settings.Cooler[i].ControlType, Environment.NewLine); - r.AppendFormat(" Cooler[{0}].Active: {1}{2}", i, - settings.Cooler[i].Active, Environment.NewLine); - } - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - if (NVAPI.NvAPI_GPU_GetMemoryInfo != null && displayHandle.HasValue) { - NvMemoryInfo memoryInfo = new NvMemoryInfo(); - memoryInfo.Version = NVAPI.GPU_MEMORY_INFO_VER; - memoryInfo.Values = new uint[NVAPI.MAX_MEMORY_VALUES_PER_GPU]; - NvStatus status = NVAPI.NvAPI_GPU_GetMemoryInfo(displayHandle.Value, - ref memoryInfo); - - r.AppendLine("Memory Info"); - r.AppendLine(); - if (status == NvStatus.OK) { - for (int i = 0; i < memoryInfo.Values.Length; i++) - r.AppendFormat(" Value[{0}]: {1}{2}", i, - memoryInfo.Values[i], Environment.NewLine); - } else { - r.Append(" Status: "); - r.AppendLine(status.ToString()); - } - r.AppendLine(); - } - - return r.ToString(); - } - - private void SoftwareControlValueChanged(IControl control) { - NvGPUCoolerLevels coolerLevels = new NvGPUCoolerLevels(); - coolerLevels.Version = NVAPI.GPU_COOLER_LEVELS_VER; - coolerLevels.Levels = new NvLevel[NVAPI.MAX_COOLER_PER_GPU]; - coolerLevels.Levels[0].Level = (int)control.SoftwareValue; - coolerLevels.Levels[0].Policy = 1; - NVAPI.NvAPI_GPU_SetCoolerLevels(handle, 0, ref coolerLevels); - } - - private void ControlModeChanged(IControl control) { - switch (control.ControlMode) { - case ControlMode.Undefined: - return; - case ControlMode.Default: - SetDefaultFanSpeed(); - break; - case ControlMode.Software: - SoftwareControlValueChanged(control); - break; - default: - return; - } - } - - private void SetDefaultFanSpeed() { - NvGPUCoolerLevels coolerLevels = new NvGPUCoolerLevels(); - coolerLevels.Version = NVAPI.GPU_COOLER_LEVELS_VER; - coolerLevels.Levels = new NvLevel[NVAPI.MAX_COOLER_PER_GPU]; - coolerLevels.Levels[0].Policy = 0x20; - NVAPI.NvAPI_GPU_SetCoolerLevels(handle, 0, ref coolerLevels); - } - - public override void Close() { - if (this.fanControl != null) { - this.fanControl.ControlModeChanged -= ControlModeChanged; - this.fanControl.SoftwareControlValueChanged -= - SoftwareControlValueChanged; - - if (this.fanControl.ControlMode != ControlMode.Undefined) - SetDefaultFanSpeed(); - } - base.Close(); - } - } -} diff --git a/Hardware/Nvidia/NvidiaGroup.cs b/Hardware/Nvidia/NvidiaGroup.cs deleted file mode 100644 index a14ac4f..0000000 --- a/Hardware/Nvidia/NvidiaGroup.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.Nvidia { - - internal class NvidiaGroup : IGroup { - private readonly List hardware = new List(); - private readonly StringBuilder report = new StringBuilder(); - private readonly NVML nvml = new NVML(); - - public NvidiaGroup(ISettings settings) { - if (!NVAPI.IsAvailable) - return; - - report.AppendLine("NVAPI"); - report.AppendLine(); - - string version; - if (NVAPI.NvAPI_GetInterfaceVersionString(out version) == NvStatus.OK) { - report.Append("Version: "); - report.AppendLine(version); - } - - NvPhysicalGpuHandle[] handles = - new NvPhysicalGpuHandle[NVAPI.MAX_PHYSICAL_GPUS]; - int count; - if (NVAPI.NvAPI_EnumPhysicalGPUs == null) { - report.AppendLine("Error: NvAPI_EnumPhysicalGPUs not available"); - report.AppendLine(); - return; - } else { - NvStatus status = NVAPI.NvAPI_EnumPhysicalGPUs(handles, out count); - if (status != NvStatus.OK) { - report.AppendLine("Status: " + status); - report.AppendLine(); - return; - } - } - - IDictionary displayHandles = - new Dictionary(); - - if (NVAPI.NvAPI_EnumNvidiaDisplayHandle != null && - NVAPI.NvAPI_GetPhysicalGPUsFromDisplay != null) - { - NvStatus status = NvStatus.OK; - int i = 0; - while (status == NvStatus.OK) { - NvDisplayHandle displayHandle = new NvDisplayHandle(); - status = NVAPI.NvAPI_EnumNvidiaDisplayHandle(i, ref displayHandle); - i++; - - if (status == NvStatus.OK) { - NvPhysicalGpuHandle[] handlesFromDisplay = - new NvPhysicalGpuHandle[NVAPI.MAX_PHYSICAL_GPUS]; - uint countFromDisplay; - if (NVAPI.NvAPI_GetPhysicalGPUsFromDisplay(displayHandle, - handlesFromDisplay, out countFromDisplay) == NvStatus.OK) { - for (int j = 0; j < countFromDisplay; j++) { - if (!displayHandles.ContainsKey(handlesFromDisplay[j])) - displayHandles.Add(handlesFromDisplay[j], displayHandle); - } - } - } - } - } - - report.Append("Number of GPUs: "); - report.AppendLine(count.ToString(CultureInfo.InvariantCulture)); - - for (int i = 0; i < count; i++) { - NvDisplayHandle displayHandle; - displayHandles.TryGetValue(handles[i], out displayHandle); - hardware.Add(new NvidiaGPU(i, handles[i], displayHandle, settings, nvml)); - } - - report.AppendLine(); - } - - public IEnumerable Hardware => hardware; - - public string GetReport() { - return report.ToString(); - } - - public void Close() { - foreach (Hardware gpu in hardware) - gpu.Close(); - - nvml.Close(); - } - } -} diff --git a/Hardware/Nvidia/NvmlDevice.cs b/Hardware/Nvidia/NvmlDevice.cs deleted file mode 100644 index 85369da..0000000 --- a/Hardware/Nvidia/NvmlDevice.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware.Nvidia { - [StructLayout(LayoutKind.Sequential)] - internal struct NvmlDevice { - public IntPtr Handle; - } -} diff --git a/Hardware/Nvidia/NvmlReturn.cs b/Hardware/Nvidia/NvmlReturn.cs deleted file mode 100644 index bcd19c3..0000000 --- a/Hardware/Nvidia/NvmlReturn.cs +++ /dev/null @@ -1,84 +0,0 @@ -namespace OpenHardwareMonitor.Hardware.Nvidia { - internal enum NvmlReturn { - /// - /// The operation was successful - /// - Success = 0, - /// - /// NVML was not first initialized with nvmlInit() - /// - Uninitialized = 1, - /// - /// A supplied argument is invalid - /// - InvalidArgument = 2, - /// - /// The requested operation is not available on target device - /// - NotSupported = 3, - /// - /// The current user does not have permission for operation - /// - NoPermission = 4, - /// - /// A query to find an object was unsuccessful - /// - NotFound = 6, - /// - /// An input argument is not large enough - /// - InsufficientSize = 7, - /// - /// A device's external power cables are not properly attached - /// - InsufficientPower = 8, - /// - /// NVIDIA driver is not loaded - /// - DriverNotLoaded = 9, - /// - /// User provided timeout passed - /// - TimeOut = 10, - /// - /// NVIDIA Kernel detected an interrupt issue with a GPU - /// - IRQIssue = 11, - /// - /// NVML Shared Library couldn't be found or loaded - /// - LibraryNotFound = 12, - /// - /// Local version of NVML doesn't implement this function - /// - FunctionNotFound = 13, - /// - /// infoROM is corrupted - /// - CorruptedInfoROM = 14, - /// - /// The GPU has fallen off the bus or has otherwise become inaccessible - /// - GPUIsLost = 15, - /// - /// The GPU requires a reset before it can be used again - /// - ResetRequired = 16, - /// - /// The GPU control device has been blocked by the operating system/cgroups - /// - OperatingSystem = 17, - /// - /// RM detects a driver/library version mismatch - /// - LibRMVersionMismatch = 18, - /// - /// An operation cannot be performed because the GPU is currently in use - /// - InUse = 19, - /// - /// An internal driver error occurred - /// - Unknown = 999 - } -} diff --git a/Hardware/Opcode.cs b/Hardware/Opcode.cs deleted file mode 100644 index 305698d..0000000 --- a/Hardware/Opcode.cs +++ /dev/null @@ -1,262 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; -using System.Reflection; - -namespace OpenHardwareMonitor.Hardware { - internal static class Opcode { - - private static IntPtr codeBuffer; - private static ulong size; - - public static void Open() { - - byte[] rdtscCode; - byte[] cpuidCode; - if (IntPtr.Size == 4) { - rdtscCode = RDTSC_32; - cpuidCode = CPUID_32; - } else { - rdtscCode = RDTSC_64; - - if (Software.OperatingSystem.IsLinux) { // Unix - cpuidCode = CPUID_64_LINUX; - } else { // Windows - cpuidCode = CPUID_64_WINDOWS; - } - } - - size = (ulong)(rdtscCode.Length + cpuidCode.Length); - - if (Software.OperatingSystem.IsLinux) { // Unix - Assembly assembly = - Assembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " + - "PublicKeyToken=0738eb9f132ed756"); - - Type syscall = assembly.GetType("Mono.Unix.Native.Syscall"); - MethodInfo mmap = syscall.GetMethod("mmap"); - - Type mmapProts = assembly.GetType("Mono.Unix.Native.MmapProts"); - object mmapProtsParam = Enum.ToObject(mmapProts, - (int)mmapProts.GetField("PROT_READ").GetValue(null) | - (int)mmapProts.GetField("PROT_WRITE").GetValue(null) | - (int)mmapProts.GetField("PROT_EXEC").GetValue(null)); - - Type mmapFlags = assembly.GetType("Mono.Unix.Native.MmapFlags"); - object mmapFlagsParam = Enum.ToObject(mmapFlags, - (int)mmapFlags.GetField("MAP_ANONYMOUS").GetValue(null) | - (int)mmapFlags.GetField("MAP_PRIVATE").GetValue(null)); - - codeBuffer = (IntPtr)mmap.Invoke(null, new object[] { IntPtr.Zero, - size, mmapProtsParam, mmapFlagsParam, -1, 0 }); - } else { // Windows - codeBuffer = NativeMethods.VirtualAlloc(IntPtr.Zero, - (UIntPtr)size, AllocationType.COMMIT | AllocationType.RESERVE, - MemoryProtection.EXECUTE_READWRITE); - } - - Marshal.Copy(rdtscCode, 0, codeBuffer, rdtscCode.Length); - - Rdtsc = Marshal.GetDelegateForFunctionPointer( - codeBuffer, typeof(RdtscDelegate)) as RdtscDelegate; - - IntPtr cpuidAddress = (IntPtr)((long)codeBuffer + rdtscCode.Length); - Marshal.Copy(cpuidCode, 0, cpuidAddress, cpuidCode.Length); - - Cpuid = Marshal.GetDelegateForFunctionPointer( - cpuidAddress, typeof(CpuidDelegate)) as CpuidDelegate; - } - - public static void Close() { - Rdtsc = null; - Cpuid = null; - - - if (Software.OperatingSystem.IsLinux) { // Unix - Assembly assembly = - Assembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " + - "PublicKeyToken=0738eb9f132ed756"); - - Type syscall = assembly.GetType("Mono.Unix.Native.Syscall"); - MethodInfo munmap = syscall.GetMethod("munmap"); - munmap.Invoke(null, new object[] { codeBuffer, size }); - - } else { // Windows - NativeMethods.VirtualFree(codeBuffer, UIntPtr.Zero, - FreeType.RELEASE); - } - } - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - public delegate ulong RdtscDelegate(); - - public static RdtscDelegate Rdtsc; - - // unsigned __int64 __stdcall rdtsc() { - // return __rdtsc(); - // } - - private static readonly byte[] RDTSC_32 = new byte[] { - 0x0F, 0x31, // rdtsc - 0xC3 // ret - }; - - private static readonly byte[] RDTSC_64 = new byte[] { - 0x0F, 0x31, // rdtsc - 0x48, 0xC1, 0xE2, 0x20, // shl rdx, 20h - 0x48, 0x0B, 0xC2, // or rax, rdx - 0xC3 // ret - }; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - public delegate bool CpuidDelegate(uint index, uint ecxValue, - out uint eax, out uint ebx, out uint ecx, out uint edx); - - public static CpuidDelegate Cpuid; - - - // void __stdcall cpuidex(unsigned int index, unsigned int ecxValue, - // unsigned int* eax, unsigned int* ebx, unsigned int* ecx, - // unsigned int* edx) - // { - // int info[4]; - // __cpuidex(info, index, ecxValue); - // *eax = info[0]; - // *ebx = info[1]; - // *ecx = info[2]; - // *edx = info[3]; - // } - - private static readonly byte[] CPUID_32 = new byte[] { - 0x55, // push ebp - 0x8B, 0xEC, // mov ebp, esp - 0x83, 0xEC, 0x10, // sub esp, 10h - 0x8B, 0x45, 0x08, // mov eax, dword ptr [ebp+8] - 0x8B, 0x4D, 0x0C, // mov ecx, dword ptr [ebp+0Ch] - 0x53, // push ebx - 0x0F, 0xA2, // cpuid - 0x56, // push esi - 0x8D, 0x75, 0xF0, // lea esi, [info] - 0x89, 0x06, // mov dword ptr [esi],eax - 0x8B, 0x45, 0x10, // mov eax, dword ptr [eax] - 0x89, 0x5E, 0x04, // mov dword ptr [esi+4], ebx - 0x89, 0x4E, 0x08, // mov dword ptr [esi+8], ecx - 0x89, 0x56, 0x0C, // mov dword ptr [esi+0Ch], edx - 0x8B, 0x4D, 0xF0, // mov ecx, dword ptr [info] - 0x89, 0x08, // mov dword ptr [eax], ecx - 0x8B, 0x45, 0x14, // mov eax, dword ptr [ebx] - 0x8B, 0x4D, 0xF4, // mov ecx, dword ptr [ebp-0Ch] - 0x89, 0x08, // mov dword ptr [eax], ecx - 0x8B, 0x45, 0x18, // mov eax, dword ptr [ecx] - 0x8B, 0x4D, 0xF8, // mov ecx, dword ptr [ebp-8] - 0x89, 0x08, // mov dword ptr [eax], ecx - 0x8B, 0x45, 0x1C, // mov eax, dword ptr [edx] - 0x8B, 0x4D, 0xFC, // mov ecx, dword ptr [ebp-4] - 0x5E, // pop esi - 0x89, 0x08, // mov dword ptr [eax], ecx - 0x5B, // pop ebx - 0xC9, // leave - 0xC2, 0x18, 0x00 // ret 18h - }; - - private static readonly byte[] CPUID_64_WINDOWS = new byte[] { - 0x48, 0x89, 0x5C, 0x24, 0x08, // mov qword ptr [rsp+8], rbx - 0x8B, 0xC1, // mov eax, ecx - 0x8B, 0xCA, // mov ecx, edx - 0x0F, 0xA2, // cpuid - 0x41, 0x89, 0x00, // mov dword ptr [r8], eax - 0x48, 0x8B, 0x44, 0x24, 0x28, // mov rax, qword ptr [rsp+28h] - 0x41, 0x89, 0x19, // mov dword ptr [r9], ebx - 0x48, 0x8B, 0x5C, 0x24, 0x08, // mov rbx, qword ptr [rsp+8] - 0x89, 0x08, // mov dword ptr [rax], ecx - 0x48, 0x8B, 0x44, 0x24, 0x30, // mov rax, qword ptr [rsp+30h] - 0x89, 0x10, // mov dword ptr [rax], edx - 0xC3 // ret - }; - - private static readonly byte[] CPUID_64_LINUX = new byte[] { - 0x49, 0x89, 0xD2, // mov r10, rdx - 0x49, 0x89, 0xCB, // mov r11, rcx - 0x53, // push rbx - 0x89, 0xF8, // mov eax, edi - 0x89, 0xF1, // mov ecx, esi - 0x0F, 0xA2, // cpuid - 0x41, 0x89, 0x02, // mov dword ptr [r10], eax - 0x41, 0x89, 0x1B, // mov dword ptr [r11], ebx - 0x41, 0x89, 0x08, // mov dword ptr [r8], ecx - 0x41, 0x89, 0x11, // mov dword ptr [r9], edx - 0x5B, // pop rbx - 0xC3, // ret - }; - - public static bool CpuidTx(uint index, uint ecxValue, - out uint eax, out uint ebx, out uint ecx, out uint edx, - ulong threadAffinityMask) { - - ulong mask = ThreadAffinity.Set(threadAffinityMask); - - if (mask == 0) { - eax = ebx = ecx = edx = 0; - return false; - } - - Cpuid(index, ecxValue, out eax, out ebx, out ecx, out edx); - - ThreadAffinity.Set(mask); - return true; - } - - [Flags()] - public enum AllocationType : uint { - COMMIT = 0x1000, - RESERVE = 0x2000, - RESET = 0x80000, - LARGE_PAGES = 0x20000000, - PHYSICAL = 0x400000, - TOP_DOWN = 0x100000, - WRITE_WATCH = 0x200000 - } - - [Flags()] - public enum MemoryProtection : uint { - EXECUTE = 0x10, - EXECUTE_READ = 0x20, - EXECUTE_READWRITE = 0x40, - EXECUTE_WRITECOPY = 0x80, - NOACCESS = 0x01, - READONLY = 0x02, - READWRITE = 0x04, - WRITECOPY = 0x08, - GUARD = 0x100, - NOCACHE = 0x200, - WRITECOMBINE = 0x400 - } - - [Flags] - public enum FreeType { - DECOMMIT = 0x4000, - RELEASE = 0x8000 - } - - private static class NativeMethods { - private const string KERNEL = "kernel32.dll"; - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] - public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, - AllocationType flAllocationType, MemoryProtection flProtect); - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] - public static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, - FreeType dwFreeType); - } - } -} diff --git a/Hardware/Parameter.cs b/Hardware/Parameter.cs deleted file mode 100644 index 0d4c00c..0000000 --- a/Hardware/Parameter.cs +++ /dev/null @@ -1,110 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -using System; -using System.Globalization; - -namespace OpenHardwareMonitor.Hardware { - public struct ParameterDescription { - private readonly string name; - private readonly string description; - private readonly float defaultValue; - - public ParameterDescription(string name, string description, - float defaultValue) { - this.name = name; - this.description = description; - this.defaultValue = defaultValue; - } - - public string Name { get { return name; } } - - public string Description { get { return description; } } - - public float DefaultValue { get { return defaultValue; } } - } - - internal class Parameter : IParameter { - private readonly ISensor sensor; - private ParameterDescription description; - private float value; - private bool isDefault; - private readonly ISettings settings; - - public Parameter(ParameterDescription description, ISensor sensor, - ISettings settings) - { - this.sensor = sensor; - this.description = description; - this.settings = settings; - this.isDefault = !settings.Contains(Identifier.ToString()); - this.value = description.DefaultValue; - if (!this.isDefault) { - if (!float.TryParse(settings.GetValue(Identifier.ToString(), "0"), - NumberStyles.Float, - CultureInfo.InvariantCulture, - out this.value)) - this.value = description.DefaultValue; - } - } - - public ISensor Sensor { - get { - return sensor; - } - } - - public Identifier Identifier { - get { - return new Identifier(sensor.Identifier, "parameter", - Name.Replace(" ", "").ToLowerInvariant()); - } - } - - public string Name { get { return description.Name; } } - - public string Description { get { return description.Description; } } - - public float Value { - get { - return value; - } - set { - this.isDefault = false; - this.value = value; - this.settings.SetValue(Identifier.ToString(), value.ToString( - CultureInfo.InvariantCulture)); - } - } - - public float DefaultValue { - get { return description.DefaultValue; } - } - - public bool IsDefault { - get { return isDefault; } - set { - this.isDefault = value; - if (value) { - this.value = description.DefaultValue; - this.settings.Remove(Identifier.ToString()); - } - } - } - - public void Accept(IVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("visitor"); - visitor.VisitParameter(this); - } - - public void Traverse(IVisitor visitor) { } - } -} diff --git a/Hardware/RAM/GenericRAM.cs b/Hardware/RAM/GenericRAM.cs deleted file mode 100644 index 13ee2cc..0000000 --- a/Hardware/RAM/GenericRAM.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Runtime.InteropServices; -using OpenHardwareMonitor.Interop; - -namespace OpenHardwareMonitor.Hardware.RAM { - internal class GenericRAM : Hardware { - - private Sensor physicalMemoryUsed; - private Sensor physicalMemoryAvailable; - private Sensor physicalMemoryLoad; - private Sensor virtualMemoryUsed; - private Sensor virtualMemoryAvailable; - private Sensor virtualMemoryLoad; - - public GenericRAM(string name, ISettings settings) - : base(name, new Identifier("ram"), settings) { - - physicalMemoryUsed = new Sensor("Memory Used", 0, SensorType.Data, this, settings); - ActivateSensor(physicalMemoryUsed); - - physicalMemoryAvailable = new Sensor("Memory Available", 1, SensorType.Data, this, settings); - ActivateSensor(physicalMemoryAvailable); - - physicalMemoryLoad = new Sensor("Memory", 0, SensorType.Load, this, settings); - ActivateSensor(physicalMemoryLoad); - - virtualMemoryUsed = new Sensor("Virtual Memory Used", 2, SensorType.Data, this, settings); - ActivateSensor(virtualMemoryUsed); - - virtualMemoryAvailable = new Sensor("Virtual Memory Available", 3, SensorType.Data, this, settings); - ActivateSensor(virtualMemoryAvailable); - - virtualMemoryLoad = new Sensor("Virtual Memory", 1, SensorType.Load, this, settings); - ActivateSensor(virtualMemoryLoad); - } - - public override HardwareType HardwareType { - get { - return HardwareType.RAM; - } - } - - public override void Update() { - Kernel32.MEMORYSTATUSEX status = new Kernel32.MEMORYSTATUSEX(); - status.dwLength = (uint)Marshal.SizeOf(); - - if (!Kernel32.GlobalMemoryStatusEx(ref status)) - return; - - physicalMemoryUsed.Value = (float)(status.ullTotalPhys - status.ullAvailPhys) / (1024 * 1024 * 1024); - physicalMemoryAvailable.Value = (float)status.ullAvailPhys / (1024 * 1024 * 1024); - physicalMemoryLoad.Value = 100.0f - (100.0f * status.ullAvailPhys) / status.ullTotalPhys; - - virtualMemoryUsed.Value = (float)(status.ullTotalPageFile - status.ullAvailPageFile) / (1024 * 1024 * 1024); - virtualMemoryAvailable.Value = (float)status.ullAvailPageFile / (1024 * 1024 * 1024); - virtualMemoryLoad.Value = 100.0f - (100.0f * status.ullAvailPageFile) / status.ullTotalPageFile; - } - } -} \ No newline at end of file diff --git a/Hardware/RAM/RAMGroup.cs b/Hardware/RAM/RAMGroup.cs deleted file mode 100644 index d018846..0000000 --- a/Hardware/RAM/RAMGroup.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Collections.Generic; - -namespace OpenHardwareMonitor.Hardware.RAM { - internal class RAMGroup : IGroup { - - private Hardware[] hardware; - - public RAMGroup(SMBIOS smbios, ISettings settings) { - - // No implementation for RAM on Unix systems - if (Software.OperatingSystem.IsLinux) { - hardware = new Hardware[0]; - return; - } - hardware = new Hardware[] { new GenericRAM("Generic Memory", settings) }; - } - - public string GetReport() { - return null; - } - - public IEnumerable Hardware => hardware; - - public void Close() { - foreach (Hardware ram in hardware) - ram.Close(); - } - } -} \ No newline at end of file diff --git a/Hardware/Ring0.cs b/Hardware/Ring0.cs deleted file mode 100644 index fcdffdc..0000000 --- a/Hardware/Ring0.cs +++ /dev/null @@ -1,427 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2016 Michael Möller - -*/ - -using System; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Threading; -using System.Text; -using System.Security.Principal; //SecurityIdentifier - -namespace OpenHardwareMonitor.Hardware { - internal static class Ring0 { - - private static KernelDriver driver; - private static string fileName; - private static Mutex isaBusMutex; - private static readonly StringBuilder report = new StringBuilder(); - - private const uint OLS_TYPE = 40000; - private static IOControlCode - IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801, - IOControlCode.Access.Any), - IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800, - IOControlCode.Access.Any), - IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821, - IOControlCode.Access.Any), - IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822, - IOControlCode.Access.Any), - IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833, - IOControlCode.Access.Read), - IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836, - IOControlCode.Access.Write), - IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851, - IOControlCode.Access.Read), - IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852, - IOControlCode.Access.Write), - IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841, - IOControlCode.Access.Read); - - private static Assembly GetAssembly() { - return typeof(Ring0).Assembly; - } - - private static string GetTempFileName() { - - // try to create one in the application folder - string location = GetAssembly().Location; - if (!string.IsNullOrEmpty(location)) { - try { - string fileName = Path.ChangeExtension(location, ".sys"); - using (FileStream stream = File.Create(fileName)) { - return fileName; - } - } catch (Exception) { } - } - - // if this failed, try to get a file in the temporary folder - try { - return Path.GetTempFileName(); - } catch (IOException) { - // some I/O exception - } - catch (UnauthorizedAccessException) { - // we do not have the right to create a file in the temp folder - } - catch (NotSupportedException) { - // invalid path format of the TMP system environment variable - } - - return null; - } - - private static bool ExtractDriver(string fileName) { - string resourceName = "OpenHardwareMonitor.Hardware." + - (Software.OperatingSystem.Is64Bit ? "WinRing0x64.sys" : - "WinRing0.sys"); - - string[] names = GetAssembly().GetManifestResourceNames(); - byte[] buffer = null; - for (int i = 0; i < names.Length; i++) { - if (names[i].Replace('\\', '.') == resourceName) { - using (Stream stream = GetAssembly(). - GetManifestResourceStream(names[i])) - { - buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - } - } - } - - if (buffer == null) - return false; - - try { - using (FileStream target = new FileStream(fileName, FileMode.Create)) { - target.Write(buffer, 0, buffer.Length); - target.Flush(); - } - } catch (IOException) { - // for example there is not enough space on the disk - return false; - } - - // make sure the file is actually writen to the file system - for (int i = 0; i < 20; i++) { - try { - if (File.Exists(fileName) && - new FileInfo(fileName).Length == buffer.Length) - { - return true; - } - Thread.Sleep(100); - } catch (IOException) { - Thread.Sleep(10); - } - } - - // file still has not the right size, something is wrong - return false; - } - - public static void Open() { - // no implementation for unix systems - if (Software.OperatingSystem.IsLinux) return; - - if (driver != null) - return; - - // clear the current report - report.Length = 0; - - driver = new KernelDriver("WinRing0_1_2_0"); - driver.Open(); - - if (!driver.IsOpen) { - // driver is not loaded, try to install and open - - fileName = GetTempFileName(); - if (fileName != null && ExtractDriver(fileName)) { - string installError; - if (driver.Install(fileName, out installError)) { - driver.Open(); - - if (!driver.IsOpen) { - driver.Delete(); - report.AppendLine("Status: Opening driver failed after install"); - } - } else { - string errorFirstInstall = installError; - - // install failed, try to delete and reinstall - driver.Delete(); - - // wait a short moment to give the OS a chance to remove the driver - Thread.Sleep(2000); - - string errorSecondInstall; - if (driver.Install(fileName, out errorSecondInstall)) { - driver.Open(); - - if (!driver.IsOpen) { - driver.Delete(); - report.AppendLine( - "Status: Opening driver failed after reinstall"); - } - } else { - report.AppendLine("Status: Installing driver \"" + - fileName + "\" failed" + - (File.Exists(fileName) ? " and file exists" : "")); - report.AppendLine("First Exception: " + errorFirstInstall); - report.AppendLine("Second Exception: " + errorSecondInstall); - } - } - } else { - report.AppendLine("Status: Extracting driver failed"); - } - - try { - // try to delte the driver file - if (File.Exists(fileName)) - File.Delete(fileName); - fileName = null; - } catch (IOException) { } - catch (UnauthorizedAccessException) { } - } - - if (!driver.IsOpen) - driver = null; - - string mutexName = "Global\\Access_ISABUS.HTP.Method"; - try { -#if NETSTANDARD2_0 - isaBusMutex = new Mutex(false, mutexName); -#else - //mutex permissions set to everyone to allow other software to access the hardware - //otherwise other monitoring software cant access - var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); - var securitySettings = new MutexSecurity(); - securitySettings.AddAccessRule(allowEveryoneRule); - isaBusMutex = new Mutex(false, mutexName, out _, securitySettings); -#endif - } - catch (UnauthorizedAccessException) { - try { -#if NETSTANDARD2_0 - isaBusMutex = Mutex.OpenExisting(mutexName); -#else - isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize); -#endif - } catch { } - } - } - - public static bool IsOpen { - get { return driver != null; } - } - - public static void Close() { - if (driver != null){ - uint refCount = 0; - driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount); - driver.Close(); - - if (refCount <= 1) - driver.Delete(); - driver = null; - } - - if (isaBusMutex != null) { - isaBusMutex.Close(); - isaBusMutex = null; - } - - // try to delete temporary driver file again if failed during open - if (fileName != null && File.Exists(fileName)) { - try { - File.Delete(fileName); - fileName = null; - } catch (IOException) { } - catch (UnauthorizedAccessException) { } - } - } - public static ulong ThreadAffinitySet(ulong mask) - { - return ThreadAffinity.Set(mask); - } - - public static string GetReport() { - if (report.Length > 0) { - StringBuilder r = new StringBuilder(); - r.AppendLine("Ring0"); - r.AppendLine(); - r.Append(report); - r.AppendLine(); - return r.ToString(); - } else - return null; - } - - public static bool WaitIsaBusMutex(int millisecondsTimeout) { - if (isaBusMutex == null) - return true; - try { - return isaBusMutex.WaitOne(millisecondsTimeout, false); - } catch (AbandonedMutexException) { return true; } - catch (InvalidOperationException) { return false; } - } - - public static void ReleaseIsaBusMutex() { - if (isaBusMutex == null) - return; - isaBusMutex.ReleaseMutex(); - } - - public static bool Rdmsr(uint index, out uint eax, out uint edx) { - if (driver == null) { - eax = 0; - edx = 0; - return false; - } - - ulong buffer = 0; - bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index, - ref buffer); - - edx = (uint)((buffer >> 32) & 0xFFFFFFFF); - eax = (uint)(buffer & 0xFFFFFFFF); - return result; - } - - public static bool RdmsrTx(uint index, out uint eax, out uint edx, - ulong threadAffinityMask) - { - ulong mask = ThreadAffinity.Set(threadAffinityMask); - - bool result = Rdmsr(index, out eax, out edx); - - ThreadAffinity.Set(mask); - return result; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct WrmsrInput { - public uint Register; - public ulong Value; - } - - public static bool Wrmsr(uint index, uint eax, uint edx) { - if (driver == null) - return false; - - WrmsrInput input = new WrmsrInput(); - input.Register = index; - input.Value = ((ulong)edx << 32) | eax; - - return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input); - } - - public static byte ReadIoPort(uint port) { - if (driver == null) - return 0; - - uint value = 0; - driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value); - - return (byte)(value & 0xFF); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct WriteIoPortInput { - public uint PortNumber; - public byte Value; - } - - public static void WriteIoPort(uint port, byte value) { - if (driver == null) - return; - - WriteIoPortInput input = new WriteIoPortInput(); - input.PortNumber = port; - input.Value = value; - - driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input); - } - - public const uint InvalidPciAddress = 0xFFFFFFFF; - - public static uint GetPciAddress(byte bus, byte device, byte function) { - return - (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7)); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct ReadPciConfigInput { - public uint PciAddress; - public uint RegAddress; - } - - public static bool ReadPciConfig(uint pciAddress, uint regAddress, - out uint value) - { - if (driver == null || (regAddress & 3) != 0) { - value = 0; - return false; - } - - ReadPciConfigInput input = new ReadPciConfigInput(); - input.PciAddress = pciAddress; - input.RegAddress = regAddress; - - value = 0; - return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, - ref value); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct WritePciConfigInput { - public uint PciAddress; - public uint RegAddress; - public uint Value; - } - - public static bool WritePciConfig(uint pciAddress, uint regAddress, - uint value) - { - if (driver == null || (regAddress & 3) != 0) - return false; - - WritePciConfigInput input = new WritePciConfigInput(); - input.PciAddress = pciAddress; - input.RegAddress = regAddress; - input.Value = value; - - return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input); - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct ReadMemoryInput { - public ulong address; - public uint unitSize; - public uint count; - } - - public static bool ReadMemory(ulong address, ref T buffer) { - if (driver == null) { - return false; - } - - ReadMemoryInput input = new ReadMemoryInput(); - input.address = address; - input.unitSize = 1; - input.count = (uint)Marshal.SizeOf(buffer); - - return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input, - ref buffer); - } - } -} diff --git a/Hardware/SMBIOS.cs b/Hardware/SMBIOS.cs deleted file mode 100644 index ad4b692..0000000 --- a/Hardware/SMBIOS.cs +++ /dev/null @@ -1,894 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Management; -using System.Text; - -namespace OpenHardwareMonitor.Hardware { - - public class SMBIOS { - - private readonly byte[] raw; - private readonly Structure[] table; - - private readonly Version version; - private readonly BIOSInformation biosInformation; - private readonly SystemInformation systemInformation; - private readonly BaseBoardInformation baseBoardInformation; - private readonly ChassisInformation chassisInformation; - private readonly ProcessorInformation processorInformation; - private readonly MemoryDevice[] memoryDevices; - - private static string ReadSysFS(string path) { - try { - if (File.Exists(path)) { - using (StreamReader reader = new StreamReader(path)) - return reader.ReadLine(); - } else { - return null; - } - } catch { - return null; - } - } - - public SMBIOS() - { - - if (Software.OperatingSystem.IsLinux) - { - this.raw = null; - this.table = null; - - string boardVendor = ReadSysFS("/sys/class/dmi/id/board_vendor"); - string boardName = ReadSysFS("/sys/class/dmi/id/board_name"); - string boardVersion = ReadSysFS("/sys/class/dmi/id/board_version"); - this.baseBoardInformation = new BaseBoardInformation( - boardVendor, boardName, boardVersion, null); - - string systemVendor = ReadSysFS("/sys/class/dmi/id/sys_vendor"); - string productName = ReadSysFS("/sys/class/dmi/id/product_name"); - string productVersion = ReadSysFS("/sys/class/dmi/id/product_version"); - this.systemInformation = new SystemInformation(systemVendor, - productName, productVersion, null, null); - - string biosVendor = ReadSysFS("/sys/class/dmi/id/bios_vendor"); - string biosVersion = ReadSysFS("/sys/class/dmi/id/bios_version"); - string biosDate = ReadSysFS("/sys/class/dmi/id/bios_date"); - this.biosInformation = new BIOSInformation(biosVendor, biosVersion, biosDate); - - this.memoryDevices = new MemoryDevice[0]; - } else { - List structureList = new List(); - List memoryDeviceList = new List(); - - raw = null; - byte majorVersion = 0; - byte minorVersion = 0; - try { - ManagementObjectCollection collection; - using (ManagementObjectSearcher searcher = - new ManagementObjectSearcher("root\\WMI", - "SELECT * FROM MSSMBios_RawSMBiosTables")) { - collection = searcher.Get(); - } - - foreach (ManagementObject mo in collection) { - raw = (byte[])mo["SMBiosData"]; - majorVersion = (byte)mo["SmbiosMajorVersion"]; - minorVersion = (byte)mo["SmbiosMinorVersion"]; - break; - } - } catch { } - - if (majorVersion > 0 || minorVersion > 0) - version = new Version(majorVersion, minorVersion); - - if (raw != null && raw.Length > 0) { - int offset = 0; - byte type = raw[offset]; - while (offset + 4 < raw.Length && type != 127) { - - type = raw[offset]; - int length = raw[offset + 1]; - ushort handle = (ushort)((raw[offset + 2] << 8) | raw[offset + 3]); - - if (offset + length > raw.Length) - break; - byte[] data = new byte[length]; - Array.Copy(raw, offset, data, 0, length); - offset += length; - - List stringsList = new List(); - if (offset < raw.Length && raw[offset] == 0) - offset++; - - while (offset < raw.Length && raw[offset] != 0) { - StringBuilder sb = new StringBuilder(); - while (offset < raw.Length && raw[offset] != 0) { - sb.Append((char)raw[offset]); offset++; - } - offset++; - stringsList.Add(sb.ToString()); - } - offset++; - switch (type) { - case 0x00: - this.biosInformation = new BIOSInformation( - type, handle, data, stringsList.ToArray()); - structureList.Add(this.biosInformation); break; - case 0x01: - this.systemInformation = new SystemInformation( - type, handle, data, stringsList.ToArray()); - structureList.Add(this.systemInformation); break; - case 0x02: this.baseBoardInformation = new BaseBoardInformation( - type, handle, data, stringsList.ToArray()); - structureList.Add(this.baseBoardInformation); break; - case 0x03: this.chassisInformation = new ChassisInformation( - type, handle, data, stringsList.ToArray()); - structureList.Add(chassisInformation); break; - case 0x04: this.processorInformation = new ProcessorInformation( - type, handle, data, stringsList.ToArray()); - structureList.Add(this.processorInformation); break; - case 0x11: MemoryDevice m = new MemoryDevice( - type, handle, data, stringsList.ToArray()); - memoryDeviceList.Add(m); - structureList.Add(m); break; - default: structureList.Add(new Structure( - type, handle, data, stringsList.ToArray())); break; - } - } - } - - memoryDevices = memoryDeviceList.ToArray(); - table = structureList.ToArray(); - } - } - - public string GetReport() { - StringBuilder r = new StringBuilder(); - - if (version != null) { - r.Append("SMBIOS Version: "); r.AppendLine(version.ToString(2)); - r.AppendLine(); - } - - if (BIOS != null) { - r.Append("BIOS Vendor: "); r.AppendLine(BIOS.Vendor); - r.Append("BIOS Version: "); r.AppendLine(BIOS.Version); - if (BIOS.Date != null) { - r.Append("BIOS Date: "); r.AppendLine(BIOS.Date.Value.ToShortDateString()); - } - if (BIOS.Size != null) { - const int megabyte = 1024 * 1024; - r.Append("BIOS Size: "); - if (BIOS.Size > megabyte) - r.AppendLine(BIOS.Size.Value / megabyte + " MB"); - else - r.AppendLine(BIOS.Size.Value / 1024 + " KB"); - } - r.AppendLine(); - } - - if (System != null) { - r.Append("System Manufacturer: "); - r.AppendLine(System.ManufacturerName); - r.Append("System Name: "); - r.AppendLine(System.ProductName); - r.Append("System Version: "); - r.AppendLine(System.Version); - r.Append("System Wakeup: "); - r.AppendLine(System.WakeUp.ToString()); - r.AppendLine(); - } - - if (Board != null) { - r.Append("Mainboard Manufacturer: "); - r.AppendLine(Board.ManufacturerName); - r.Append("Mainboard Name: "); - r.AppendLine(Board.ProductName); - r.Append("Mainboard Version: "); - r.AppendLine(Board.Version); - r.Append("Mainboard Serial: "); - r.AppendLine(Board.SerialNumber); - r.AppendLine(); - } - - if (Chassis != null) { - r.Append("Chassis Type: "); - r.AppendLine(Chassis.ChassisType.ToString()); - r.Append("Chassis Manufacturer: "); - r.AppendLine(Chassis.ManufacturerName); - r.Append("Chassis Version: "); - r.AppendLine(Chassis.Version); - r.Append("Chassis Serial: "); - r.AppendLine(Chassis.SerialNumber); - r.Append("Chassis Asset Tag: "); - r.AppendLine(Chassis.AssetTag); - if (!String.IsNullOrEmpty(Chassis.SKU)) { - r.Append("Chassis SKU: "); - r.AppendLine(Chassis.SKU); - } - r.Append("Chassis Boot Up State: "); - r.AppendLine(Chassis.BootUpState.ToString()); - r.Append("Chassis Power Supply State: "); - r.AppendLine(Chassis.PowerSupplyState.ToString()); - r.Append("Chassis Thermal State: "); - r.AppendLine(Chassis.ThermalState.ToString()); - r.Append("Chassis Power Cords: "); - r.AppendLine(Chassis.PowerCords.ToString()); - if (Chassis.RackHeight > 0) { - r.Append("Chassis Rack Height: "); - r.AppendLine(Chassis.RackHeight.ToString()); - } - r.Append("Chassis Lock Detected: "); - r.AppendLine(Chassis.LockDetected ? "Yes" : "No"); - r.Append("Chassis Security Status: "); - r.AppendLine(Chassis.SecurityStatus.ToString()); - r.AppendLine(); - } - - if (Processor != null) { - r.Append("Processor Manufacturer: "); - r.AppendLine(Processor.ManufacturerName); - r.Append("Processor Version: "); - r.AppendLine(Processor.Version); - r.Append("Processor Family: "); - r.AppendLine(Processor.Family.ToString()); - r.Append("Processor Core Count: "); - r.AppendLine(Processor.CoreCount.ToString()); - r.Append("Processor Core Enabled: "); - r.AppendLine(Processor.CoreEnabled.ToString()); - r.Append("Processor Thread Count: "); - r.AppendLine(Processor.ThreadCount.ToString()); - r.Append("Processor External Clock: "); - r.Append(Processor.ExternalClock); - r.AppendLine(" Mhz"); - r.AppendLine(); - } - - for (int i = 0; i < MemoryDevices.Length; i++) { - r.Append("Memory Device [" + i + "] Manufacturer: "); - r.AppendLine(MemoryDevices[i].ManufacturerName); - r.Append("Memory Device [" + i + "] Part Number: "); - r.AppendLine(MemoryDevices[i].PartNumber); - r.Append("Memory Device [" + i + "] Device Locator: "); - r.AppendLine(MemoryDevices[i].DeviceLocator); - r.Append("Memory Device [" + i + "] Bank Locator: "); - r.AppendLine(MemoryDevices[i].BankLocator); - r.Append("Memory Device [" + i + "] Speed: "); - r.Append(MemoryDevices[i].Speed); - r.AppendLine(" MHz"); - r.AppendLine(); - } - - if (raw != null) { - string base64 = Convert.ToBase64String(raw); - r.AppendLine("SMBIOS Table"); - r.AppendLine(); - - for (int i = 0; i < Math.Ceiling(base64.Length / 64.0); i++) { - r.Append(" "); - for (int j = 0; j < 0x40; j++) { - int index = (i << 6) | j; - if (index < base64.Length) { - r.Append(base64[index]); - } - } - r.AppendLine(); - } - r.AppendLine(); - } - - return r.ToString(); - } - - public BIOSInformation BIOS { - get { return biosInformation; } - } - - public SystemInformation System { - get { return systemInformation; } - } - - public BaseBoardInformation Board { - get { return baseBoardInformation; } - } - - public ChassisInformation Chassis { - get { return chassisInformation; } - } - - public ProcessorInformation Processor { - get { return processorInformation; } - } - - public MemoryDevice[] MemoryDevices { - get { return memoryDevices; } - } - - public class Structure { - private readonly byte type; - private readonly ushort handle; - - private readonly byte[] data; - private readonly string[] strings; - - protected int GetByte(int offset) { - if (offset < data.Length && offset >= 0) - return data[offset]; - else - return 0; - } - - protected int GetWord(int offset) { - if (offset + 1 < data.Length && offset >= 0) - return (data[offset + 1] << 8) | data[offset]; - else - return 0; - } - - protected string GetString(int offset) { - if (offset < data.Length && data[offset] > 0 && - data[offset] <= strings.Length) - return strings[data[offset] - 1]; - else - return ""; - } - - public Structure(byte type, ushort handle, byte[] data, string[] strings) - { - this.type = type; - this.handle = handle; - this.data = data; - this.strings = strings; - } - - public byte Type { get { return type; } } - - public ushort Handle { get { return handle; } } - } - - public class BIOSInformation : Structure { - - private readonly string vendor; - private readonly string version; - private readonly DateTime? date; - private readonly ulong? size; - - public BIOSInformation(string vendor, string version, string date = null, ulong? size = null) - : base (0x00, 0, null, null) - { - this.vendor = vendor; - this.version = version; - this.date = ParseBIOSDate(date); - this.size = size; - } - - public BIOSInformation(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) - { - this.vendor = GetString(0x04); - this.version = GetString(0x05); - this.date = ParseBIOSDate(GetString(0x08)); - this.size = CalculateBIOSRomSize(); - } - - private ulong? CalculateBIOSRomSize() - { - var biosROMSize = GetByte(0x09); - var extendedBIOSROMSize = GetWord(0x18); - var isExtendedBIOSROMSize = biosROMSize == 0xFF && extendedBIOSROMSize != 0; - if (!isExtendedBIOSROMSize) - return 65536 * (ulong)(biosROMSize + 1); - - var unit = (extendedBIOSROMSize & 0xC000) >> 14; - var extendedSize = (ulong)(extendedBIOSROMSize & ~0xC000) * 1024 * 1024; - - switch(unit) { - case 0x00: return extendedSize; // Megabytes - case 0x01: return extendedSize * 1024; // Gigabytes - might overflow in the future - default: - return null; // Other patterns not defined in DMI 3.2.0 - } - } - - private static DateTime? ParseBIOSDate(string biosDate) - { - var parts = (biosDate ?? "").Split('/'); - if (parts.Length == 3 && - int.TryParse(parts[0], out int month) && - int.TryParse(parts[1], out int day) && - int.TryParse(parts[2], out int year)) { - return new DateTime(year < 100 ? 1900 + year : year, month, day); - } - - return null; - } - - public DateTime? Date { get { return date; } } - - public ulong? Size { get { return size; } } - - public string Vendor { get { return vendor; } } - - public string Version { get { return version; } } - } - - public class SystemInformation : Structure { - - private readonly string manufacturerName; - private readonly string productName; - private readonly string version; - private readonly string serialNumber; - private readonly string family; - private readonly SystemWakeUp wakeUp; - - public SystemInformation(string manufacturerName, string productName, - string version, string serialNumber, string family, SystemWakeUp wakeUp = SystemWakeUp.Unknown) - : base (0x01, 0, null, null) - { - this.manufacturerName = manufacturerName; - this.productName = productName; - this.version = version; - this.serialNumber = serialNumber; - this.family = family; - this.wakeUp = wakeUp; - } - - public SystemInformation(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) - { - this.manufacturerName = GetString(0x04); - this.productName = GetString(0x05); - this.version = GetString(0x06); - this.serialNumber = GetString(0x07); - this.family = GetString(0x1A); - this.wakeUp = (SystemWakeUp)GetByte(0x18); - } - - public string ManufacturerName { get { return manufacturerName; } } - - public string ProductName { get { return productName; } } - - public string Version { get { return version; } } - - public string SerialNumber { get { return serialNumber; } } - - public string Family { get { return family; } } - - public SystemWakeUp WakeUp { get { return wakeUp; } } - } - - public enum SystemWakeUp - { - Reserved, - Other, - Unknown, - APMTimer, - ModemRing, - LANRemote, - PowerSwitch, - PCIPME, - ACPowerRestored - } - - public class ChassisInformation : Structure { - public ChassisInformation(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) { - ManufacturerName = GetString(0x04).Trim(); - Version = GetString(0x06).Trim(); - SerialNumber = GetString(0x07).Trim(); - AssetTag = GetString(0x08).Trim(); - RackHeight = GetByte(0x11); - PowerCords = GetByte(0x12); - SKU = GetString(0x15).Trim(); - LockDetected = (GetByte(0x05) & 128) == 128; - ChassisType = (ChassisType)(GetByte(0x05) & 127); - BootUpState = (ChassisStates)GetByte(0x09); - PowerSupplyState = (ChassisStates)GetByte(0x0A); - ThermalState = (ChassisStates)GetByte(0x0B); - SecurityStatus = (ChassisSecurityStatus)GetByte(0x0C); - } - - public string ManufacturerName { get; private set; } - public string Version { get; private set; } - public string SerialNumber { get; private set; } - public string AssetTag { get; private set; } - public string SKU { get; private set; } - public int RackHeight { get; private set; } - public int PowerCords { get; private set; } - public ChassisType ChassisType { get; private set; } - public ChassisStates BootUpState { get; private set; } - public ChassisStates PowerSupplyState { get; private set; } - public ChassisStates ThermalState { get; private set; } - public ChassisSecurityStatus SecurityStatus { get; set; } - public bool LockDetected { get; set; } - } - - public enum ChassisType { - Other = 1, - Unknown, - Desktop, - LowProfileDesktop, - PizzaBox, - MiniTower, - Tower, - Portable, - Laptop, - Notebook, - HandHeld, - DockingStation, - AllInOne, - SubNotebook, - SpaceSaving, - LunchBox, - MainServerChassis, - ExpansionChassis, - SubChassis, - BusExpansionChassis, - PeripheralChassis, - RAIDChassis, - RackMountChassis, - SealedCasePC, - MultiSystemChassis, - CompactPCI, - AdvancedTCA, - Blade, - BladeEnclosure, - Tablet, - Convertible, - Detachable, - IoTGateway, - EmbeddedPC, - MiniPC, - StickPC - } - - public enum ChassisStates { - Other = 1, - Unknown, - Safe, - Warning, - Critical, - NonRecoverable - } - - public enum ChassisSecurityStatus { - Other = 1, - Unknown, - None, - ExternalInterfaceLockedOut, - ExternalInterfaceEnabled - } - - public class BaseBoardInformation : Structure { - - private readonly string manufacturerName; - private readonly string productName; - private readonly string version; - private readonly string serialNumber; - - public BaseBoardInformation(string manufacturerName, string productName, - string version, string serialNumber) - : base(0x02, 0, null, null) - { - this.manufacturerName = manufacturerName; - this.productName = productName; - this.version = version; - this.serialNumber = serialNumber; - } - - public BaseBoardInformation(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) { - - this.manufacturerName = GetString(0x04).Trim(); - this.productName = GetString(0x05).Trim(); - this.version = GetString(0x06).Trim(); - this.serialNumber = GetString(0x07).Trim(); - } - - public string ManufacturerName { get { return manufacturerName; } } - - public string ProductName { get { return productName; } } - - public string Version { get { return version; } } - - public string SerialNumber { get { return serialNumber; } } - } - - public class ProcessorInformation : Structure { - - public ProcessorInformation(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) - { - this.ManufacturerName = GetString(0x07).Trim(); - this.Version = GetString(0x10).Trim(); - this.CoreCount = GetByte(0x23) != 255 ? GetByte(0x23) : GetWord(0x2A); - this.CoreEnabled = GetByte(0x24) != 255 ? GetByte(0x24) : GetWord(0x2C); - this.ThreadCount = GetByte(0x25) != 255 ? GetByte(0x25) : GetWord(0x2E); - this.ExternalClock = GetWord(0x12); - var family = GetByte(0x06); - this.Family = (ProcessorFamily) (family == 254 ? GetWord(0x28) : family); - } - - public string ManufacturerName { get; private set; } - - public string Version { get; private set; } - - public int CoreCount { get; private set; } - - public int CoreEnabled { get; private set; } - - public int ThreadCount { get; private set; } - - public int ExternalClock { get; private set; } - - public ProcessorFamily Family { get; private set; } - } - - public enum ProcessorFamily { - Other = 1, - Intel8086 = 3, - Intel80286 = 4, - Intel386, - Intel486, - Intel8087, - Intel80287, - Intel80387, - Intel80487, - IntelPentium, - IntelPentiumPro, - IntelPentiumII, - IntelPentiumMMX, - IntelCeleron, - IntelPentiumIIXeon, - IntelPentiumIII, - M1, - M2, - IntelCeleronM, - IntelPentium4HT, - AmdDuron = 24, - AmdK5, - AmdK6, - AmdK62, - AmdK63, - AmdAthlon, - Amd2900, - AmdK62Plus, - PowerPc, - PowerPc601, - PowerPc603, - PowerPc603Plus, - PowerPc604, - PowerPc620, - PowerPcx704, - PowerPc750, - IntelCoreDuo, - IntelCoreDuoMobile, - IntelCoreSoloMobile, - IntelAtom, - IntelCoreM, - IntelCoreM3, - IntelCoreM5, - IntelCoreM7, - Alpha, - Alpha21064, - Alpha21066, - Alpha21164, - Alpha21164Pc, - Alpha21164a, - Alpha21264, - Alpha21364, - AmdTurionIIUltraDualCoreMobileM, - AmdTurionDualCoreMobileM, - AmdAthlonIIDualCoreM, - AmdOpteron6100Series, - AmdOpteron4100Series, - AmdOpteron6200Series, - AmdOpteron4200Series, - AmdFxSeries, - Mips, - MipsR4000, - MipsR4200, - MipsR4400, - MipsR4600, - MipsR10000, - AmdCSeries, - AmdESeries, - AmdASeries, - AmdGSeries, - AmdZSeries, - AmdRSeries, - AmdOpteron4300Series, - AmdOpteron6300Series, - AmdOpteron3300Series, - AmdFireProSeries, - Sparc, - SuperSparc, - MicroSparcII, - MicroSparcIIep, - UltraSparc, - UltraSparcII, - UltraSparcIIi, - UltraSparcIII, - UltraSparcIIIi, - Motorola68040 = 96, - Motorola68xxx, - Motorola68000, - Motorola68010, - Motorola68020, - Motorola68030, - AmdAthlonX4QuadCore, - AmdOpteronX1000Series, - AmdOpteronX2000Series, - AmdOpteronASeries, - AmdOpteronX3000Series, - AmdZen, - Hobbit = 112, - CrusoeTm5000 = 120, - CrusoeTm3000, - EfficeonTm8000, - Weitek = 128, - IntelItanium = 130, - AmdAthlon64, - AmdOpteron, - AmdSempron, - AmdTurio64Mobile, - AmdOpteronDualCore, - AmdAthlon64X2DualCore, - AmdTurion64X2Mobile, - AmdOpteronQuadCore, - AmdOpteronThirdGen, - AmdPhenomFXQuadCore, - AmdPhenomX4QuadCore, - AmdPhenomX2DualCore, - AmdAthlonX2DualCore, - PaRisc, - PaRisc8500, - PaRisc8000, - PaRisc7300LC, - PaRisc7200, - PaRisc7100LC, - PaRisc7100, - V30 = 160, - IntelXeon3200QuadCoreSeries, - IntelXeon3000DualCoreSeries, - IntelXeon5300QuadCoreSeries, - IntelXeon5100DualCoreSeries, - IntelXeon5000DualCoreSeries, - IntelXeonLVDualCore, - IntelXeonULVDualCore, - IntelXeon7100Series, - IntelXeon5400Series, - IntelXeonQuadCore, - IntelXeon5200DualCoreSeries, - IntelXeon7200DualCoreSeries, - IntelXeon7300QuadCoreSeries, - IntelXeon7400QuadCoreSeries, - IntelXeon7400MultiCoreSeries, - IntelPentiumIIIXeon, - IntelPentiumIIISpeedStep, - IntelPentium4, - IntelXeon, - As400, - IntelXeonMP, - AmdAthlonXP, - AmdAthlonMP, - IntelItanium2, - IntelPentiumM, - IntelCeleronD, - IntelPentiumD, - IntelPentiumExtreme, - IntelCoreSolo, - IntelCore2Duo = 191, - IntelCore2Solo, - IntelCore2Extreme, - IntelCore2Quad, - IntelCore2ExtremeMobile, - IntelCore2DuoMobile, - IntelCore2SoloMobile, - IntelCoreI7, - IntelCeleronDualCore, - Ibm390, - PowerPcG4, - PowerPcG5, - Esa390G6, - ZArchitecture, - IntelCoreI5, - IntelCoreI3, - IntelCoreI9, - ViaC7M = 210, - ViaC7D, - ViaC7, - ViaEden, - IntelXeonMultiCore, - IntelXeon3xxxDualCoreSeries, - IntelXeon3xxxQuadCoreSeries, - ViaNano, - IntelXeon5xxxDualCoreSeries, - IntelXeon5xxxQuadCoreSeries, - IntelXeon7xxxDualCoreSeries = 221, - IntelXeon7xxxQuadCoreSeries, - IntelXeon7xxxMultiCoreSeries, - IntelXeon3400MultiCoreSeries, - AmdOpteron3000Series = 228, - AmdSempronII, - AmdOpteronQuadCoreEmbedded, - AmdPhenomTripleCore, - AmdTurionUltraDualCoreMobile, - AmdTurionDualCoreMobile, - AmdTurionDualCore, - AmdAthlonDualCore, - AmdSempronSI, - AmdPhenomII, - AmdAthlonII, - AmdOpteronSixCore, - AmdSempronM, - IntelI860 = 250, - IntelI960, - ArmV7 = 256, - ArmV8, - HitachiSh3, - HitachiSh4, - Arm, - StrongArm, - _686, - MediaGX, - MII, - WinChip, - Dsp, - VideoProcessor - } - - public class MemoryDevice : Structure { - - private readonly string deviceLocator; - private readonly string bankLocator; - private readonly string manufacturerName; - private readonly string serialNumber; - private readonly string partNumber; - private readonly int speed; - - public MemoryDevice(byte type, ushort handle, byte[] data, - string[] strings) - : base(type, handle, data, strings) - { - this.deviceLocator = GetString(0x10).Trim(); - this.bankLocator = GetString(0x11).Trim(); - this.manufacturerName = GetString(0x17).Trim(); - this.serialNumber = GetString(0x18).Trim(); - this.partNumber = GetString(0x1A).Trim(); - this.speed = GetWord(0x15); - } - - public string DeviceLocator { get { return deviceLocator; } } - - public string BankLocator { get { return bankLocator; } } - - public string ManufacturerName { get { return manufacturerName; } } - - public string SerialNumber { get { return serialNumber; } } - - public string PartNumber { get { return partNumber; } } - - public int Speed { get { return speed; } } - - } - } -} diff --git a/Hardware/Sensor.cs b/Hardware/Sensor.cs deleted file mode 100644 index 73f5df6..0000000 --- a/Hardware/Sensor.cs +++ /dev/null @@ -1,273 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.IO.Compression; - -namespace OpenHardwareMonitor.Hardware { - - internal class Sensor : ISensor { - - private readonly string defaultName; - private string name; - private readonly int index; - private readonly bool defaultHidden; - private readonly SensorType sensorType; - private readonly Hardware hardware; - private readonly IReadOnlyList parameters; - private float? currentValue; - private float? minValue; - private float? maxValue; - private readonly List values = new List(); - private TimeSpan valuesTimeWindow = TimeSpan.FromDays(1.0); - private readonly ISettings settings; - private IControl control; - - private float sum; - private int count; - - public Sensor(string name, int index, SensorType sensorType, - Hardware hardware, ISettings settings) : - this(name, index, sensorType, hardware, null, settings) { } - - public Sensor(string name, int index, SensorType sensorType, - Hardware hardware, ParameterDescription[] parameterDescriptions, - ISettings settings) : - this(name, index, false, sensorType, hardware, - parameterDescriptions, settings) { } - - public Sensor(string name, int index, bool defaultHidden, - SensorType sensorType, Hardware hardware, - ParameterDescription[] parameterDescriptions, ISettings settings) - { - this.index = index; - this.defaultHidden = defaultHidden; - this.sensorType = sensorType; - this.hardware = hardware; - Parameter[] parameters = new Parameter[parameterDescriptions == null ? - 0 : parameterDescriptions.Length]; - for (int i = 0; i < parameters.Length; i++ ) - parameters[i] = new Parameter(parameterDescriptions[i], this, settings); - this.parameters = parameters; - - this.settings = settings; - this.defaultName = name; - this.name = settings.GetValue( - new Identifier(Identifier, "name").ToString(), name); - - GetSensorValuesFromSettings(); - - hardware.Closing += delegate(IHardware h) { - SetSensorValuesToSettings(); - }; - } - - private void SetSensorValuesToSettings() { - using (MemoryStream m = new MemoryStream()) { - using (GZipStream c = new GZipStream(m, CompressionMode.Compress)) - using (BufferedStream b = new BufferedStream(c, 65536)) - using (BinaryWriter writer = new BinaryWriter(b)) { - long t = 0; - foreach (SensorValue sensorValue in values) { - long v = sensorValue.Time.ToBinary(); - writer.Write(v - t); - t = v; - writer.Write(sensorValue.Value); - } - writer.Flush(); - } - settings.SetValue(new Identifier(Identifier, "values").ToString(), - Convert.ToBase64String(m.ToArray())); - } - } - - private void GetSensorValuesFromSettings() { - string name = new Identifier(Identifier, "values").ToString(); - string s = settings.GetValue(name, null); - - if (!string.IsNullOrEmpty(s)) - { - try - { - byte[] array = Convert.FromBase64String(s); - s = null; - DateTime now = DateTime.UtcNow; - using (MemoryStream m = new MemoryStream(array)) - using (GZipStream c = new GZipStream(m, CompressionMode.Decompress)) - { - using (MemoryStream unzip = new MemoryStream()) - { - c.CopyTo(unzip); - unzip.Seek(0, SeekOrigin.Begin); - using (BinaryReader reader = new BinaryReader(unzip)) - { - try - { - long t = 0; - long readLen = reader.BaseStream.Length - reader.BaseStream.Position; - while (true && readLen > 0) - { - t += reader.ReadInt64(); - DateTime time = DateTime.FromBinary(t); - if (time > now) - break; - float value = reader.ReadSingle(); - AppendValue(value, time); - - readLen = reader.BaseStream.Length - reader.BaseStream.Position; - } - } - catch (EndOfStreamException e) - { } - } - } - } - } - catch { } - } - - if (values.Count > 0) - AppendValue(float.NaN, DateTime.UtcNow); - - //remove the value string from the settings to reduce memory usage - settings.Remove(name); - } - - private void AppendValue(float value, DateTime time) { - if (values.Count >= 2 && values[values.Count - 1].Value == value && - values[values.Count - 2].Value == value) { - values[values.Count - 1] = new SensorValue(value, time); - return; - } - - values.Add(new SensorValue(value, time)); - } - - public IHardware Hardware { - get { return hardware; } - } - - public SensorType SensorType { - get { return sensorType; } - } - - public Identifier Identifier { - get { - return new Identifier(hardware.Identifier, - sensorType.ToString().ToLowerInvariant(), - index.ToString(CultureInfo.InvariantCulture)); - } - } - - public string Name { - get { - return name; - } - set { - if (!string.IsNullOrEmpty(value)) - name = value; - else - name = defaultName; - settings.SetValue(new Identifier(Identifier, "name").ToString(), name); - } - } - - public int Index { - get { return index; } - } - - public bool IsDefaultHidden { - get { return defaultHidden; } - } - - public IReadOnlyList Parameters { - get { return parameters; } - } - - public float? Value { - get { - return currentValue; - } - set { - if (valuesTimeWindow != TimeSpan.Zero) { - DateTime now = DateTime.UtcNow; - while (values.Count > 0 && (now - values[0].Time) > valuesTimeWindow) - values.RemoveAt(0); - - if (value.HasValue) { - sum += value.Value; - count++; - if (count == 4) { - AppendValue(sum / count, now); - sum = 0; - count = 0; - } - } - } - - this.currentValue = value; - if (minValue > value || !minValue.HasValue) - minValue = value; - if (maxValue < value || !maxValue.HasValue) - maxValue = value; - } - } - - public float? Min { get { return minValue; } } - public float? Max { get { return maxValue; } } - - public void ResetMin() { - minValue = null; - } - - public void ResetMax() { - maxValue = null; - } - - public IEnumerable Values { - get { return values; } - } - - public TimeSpan ValuesTimeWindow { - get { - return valuesTimeWindow; - } - set { - this.valuesTimeWindow = value; - - if (value == TimeSpan.Zero) - values.Clear(); - } - } - - public void Accept(IVisitor visitor) { - if (visitor == null) - throw new ArgumentNullException("visitor"); - visitor.VisitSensor(this); - } - - public void Traverse(IVisitor visitor) { - foreach (IParameter parameter in parameters) - parameter.Accept(visitor); - } - - public IControl Control { - get { - return control; - } - internal set { - this.control = value; - } - } - } -} diff --git a/Hardware/SensorVisitor.cs b/Hardware/SensorVisitor.cs deleted file mode 100644 index fd9ab1d..0000000 --- a/Hardware/SensorVisitor.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2010 Michael Möller - -*/ - -using System; - -namespace OpenHardwareMonitor.Hardware { - - public class SensorVisitor : IVisitor { - private readonly SensorEventHandler handler; - - public SensorVisitor(SensorEventHandler handler) { - if (handler == null) - throw new ArgumentNullException("handler"); - this.handler = handler; - } - - public void VisitComputer(IComputer computer) { - if (computer == null) - throw new ArgumentNullException("computer"); - computer.Traverse(this); - } - - public void VisitHardware(IHardware hardware) { - if (hardware == null) - throw new ArgumentNullException("hardware"); - hardware.Traverse(this); - } - - public void VisitSensor(ISensor sensor) { - handler(sensor); - } - - public void VisitParameter(IParameter parameter) { } - } -} diff --git a/Hardware/TBalancer/FTD2XX.cs b/Hardware/TBalancer/FTD2XX.cs deleted file mode 100644 index aa2fa8e..0000000 --- a/Hardware/TBalancer/FTD2XX.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware.TBalancer { - - internal enum FT_DEVICE : uint { - FT_DEVICE_232BM, - FT_DEVICE_232AM, - FT_DEVICE_100AX, - FT_DEVICE_UNKNOWN, - FT_DEVICE_2232C, - FT_DEVICE_232R, - FT_DEVICE_2232H, - FT_DEVICE_4232H - } - - internal enum FT_STATUS { - FT_OK, - FT_INVALID_HANDLE, - FT_DEVICE_NOT_FOUND, - FT_DEVICE_NOT_OPENED, - FT_IO_ERROR, - FT_INSUFFICIENT_RESOURCES, - FT_INVALID_PARAMETER, - FT_INVALID_BAUD_RATE, - FT_DEVICE_NOT_OPENED_FOR_ERASE, - FT_DEVICE_NOT_OPENED_FOR_WRITE, - FT_FAILED_TO_WRITE_DEVICE, - FT_EEPROM_READ_FAILED, - FT_EEPROM_WRITE_FAILED, - FT_EEPROM_ERASE_FAILED, - FT_EEPROM_NOT_PRESENT, - FT_EEPROM_NOT_PROGRAMMED, - FT_INVALID_ARGS, - FT_OTHER_ERROR - } - - internal enum FT_FLOW_CONTROL : ushort { - FT_FLOW_DTR_DSR = 512, - FT_FLOW_NONE = 0, - FT_FLOW_RTS_CTS = 256, - FT_FLOW_XON_XOFF = 1024, - } - - internal enum FT_PURGE : uint { - FT_PURGE_RX = 1, - FT_PURGE_TX = 2, - FT_PURGE_ALL = 3, - } - - [StructLayout(LayoutKind.Sequential)] - internal struct FT_HANDLE { - private readonly uint handle; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct FT_DEVICE_INFO_NODE { - public uint Flags; - public FT_DEVICE Type; - public uint ID; - public uint LocId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] - public string SerialNumber; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] - public string Description; - public FT_HANDLE Handle; - } - - internal class FTD2XX { - - private const string FtdAssemblyName = "FTD2XX.dll"; - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_CreateDeviceInfoList(out uint numDevices); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_GetDeviceInfoList([Out] FT_DEVICE_INFO_NODE[] deviceInfoNodes, ref uint length); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_Open(int device, out FT_HANDLE handle); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_Close(FT_HANDLE handle); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_SetBaudRate(FT_HANDLE handle, uint baudRate); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_SetDataCharacteristics(FT_HANDLE handle, byte wordLength, byte stopBits, byte parity); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_SetFlowControl(FT_HANDLE handle, FT_FLOW_CONTROL flowControl, byte xon, byte xoff); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_SetTimeouts(FT_HANDLE handle, uint readTimeout, uint writeTimeout); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_Write(FT_HANDLE handle, byte[] buffer, uint bytesToWrite, out uint bytesWritten); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_Purge(FT_HANDLE handle, FT_PURGE mask); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_GetStatus(FT_HANDLE handle, out uint amountInRxQueue, out uint amountInTxQueue, out uint eventStatus); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_Read(FT_HANDLE handle, [Out] byte[] buffer, uint bytesToRead, out uint bytesReturned); - [DllImport(FtdAssemblyName)] - public static extern FT_STATUS FT_ReadByte(FT_HANDLE handle, out byte buffer, uint bytesToRead, out uint bytesReturned); - - private FTD2XX() { } - - public static FT_STATUS Write(FT_HANDLE handle, byte[] buffer) { - uint bytesWritten; - FT_STATUS status = FT_Write(handle, buffer, (uint)buffer.Length, - out bytesWritten); - if (bytesWritten != buffer.Length) - return FT_STATUS.FT_FAILED_TO_WRITE_DEVICE; - else - return status; - } - - public static int BytesToRead(FT_HANDLE handle) { - uint amountInRxQueue; - uint amountInTxQueue; - uint eventStatus; - if (FT_GetStatus(handle, out amountInRxQueue, out amountInTxQueue, - out eventStatus) == FT_STATUS.FT_OK) { - return (int)amountInRxQueue; - } else { - return 0; - } - } - - public static byte ReadByte(FT_HANDLE handle) { - byte buffer; - uint bytesReturned; - FT_STATUS status = FT_ReadByte(handle, out buffer, 1, out bytesReturned); - if (status != FT_STATUS.FT_OK || bytesReturned != 1) - throw new InvalidOperationException(); - return buffer; - } - - public static void Read(FT_HANDLE handle, byte[] buffer) { - uint bytesReturned; - FT_STATUS status = - FT_Read(handle, buffer, (uint)buffer.Length, out bytesReturned); - if (status != FT_STATUS.FT_OK || bytesReturned != buffer.Length) - throw new InvalidOperationException(); - } - - } -} diff --git a/Hardware/TBalancer/TBalancer.cs b/Hardware/TBalancer/TBalancer.cs deleted file mode 100644 index 7ccc784..0000000 --- a/Hardware/TBalancer/TBalancer.cs +++ /dev/null @@ -1,324 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2011 Michael Möller - -*/ - -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace OpenHardwareMonitor.Hardware.TBalancer { - internal class TBalancer : Hardware { - - private readonly int portIndex; - private readonly byte protocolVersion; - private readonly Sensor[] digitalTemperatures = new Sensor[8]; - private readonly Sensor[] analogTemperatures = new Sensor[4]; - private readonly Sensor[] sensorhubTemperatures = new Sensor[6]; - private readonly Sensor[] sensorhubFlows = new Sensor[2]; - private readonly Sensor[] fans = new Sensor[4]; - private readonly Sensor[] controls = new Sensor[4]; - private readonly Sensor[] miniNGTemperatures = new Sensor[4]; - private readonly Sensor[] miniNGFans = new Sensor[4]; - private readonly Sensor[] miniNGControls = new Sensor[4]; - private readonly List deactivating = new List(); - - private FT_HANDLE handle; - private byte[] data = new byte[285]; - private byte[] primaryData = new byte[0]; - private byte[] alternativeData = new byte[0]; - - public const byte STARTFLAG = 100; - public const byte ENDFLAG = 254; - - private delegate void MethodDelegate(); - private readonly MethodDelegate alternativeRequest; - - public TBalancer(int portIndex, byte protocolVersion, ISettings settings) - : base("T-Balancer bigNG", new Identifier("bigng", - portIndex.ToString(CultureInfo.InvariantCulture)), settings) - { - - this.portIndex = portIndex; - this.protocolVersion = protocolVersion; - - ParameterDescription[] parameter = new [] { - new ParameterDescription("Offset [°C]", "Temperature offset.", 0) - }; - int offset = 0; - for (int i = 0; i < digitalTemperatures.Length; i++) - digitalTemperatures[i] = new Sensor("Digital Sensor " + i, - offset + i, SensorType.Temperature, this, parameter, settings); - offset += digitalTemperatures.Length; - - for (int i = 0; i < analogTemperatures.Length; i++) - analogTemperatures[i] = new Sensor("Analog Sensor " + (i + 1), - offset + i, SensorType.Temperature, this, parameter, settings); - offset += analogTemperatures.Length; - - for (int i = 0; i < sensorhubTemperatures.Length; i++) - sensorhubTemperatures[i] = new Sensor("Sensorhub Sensor " + i, - offset + i, SensorType.Temperature, this, parameter, settings); - offset += sensorhubTemperatures.Length; - - for (int i = 0; i < miniNGTemperatures.Length; i++) - miniNGTemperatures[i] = new Sensor("miniNG #" + (i / 2 + 1) + - " Sensor " + (i % 2 + 1), offset + i, SensorType.Temperature, - this, parameter, settings); - offset += miniNGTemperatures.Length; - - for (int i = 0; i < sensorhubFlows.Length; i++) - sensorhubFlows[i] = new Sensor("Flowmeter " + (i + 1), - i, SensorType.Flow, this, new [] { - new ParameterDescription("Impulse Rate", - "The impulse rate of the flowmeter in pulses/L", 509) - }, settings); - - for (int i = 0; i < controls.Length; i++) { - controls[i] = new Sensor("Fan Channel " + i, i, SensorType.Control, - this, settings); - } - - for (int i = 0; i < miniNGControls.Length; i++) { - miniNGControls[i] = new Sensor("miniNG #" + (i / 2 + 1) + - " Fan Channel " + (i % 2 + 1), 4 + i, SensorType.Control, this, - settings); - } - - alternativeRequest = new MethodDelegate(DelayedAlternativeRequest); - - Open(); - Update(); - } - - protected override void ActivateSensor(ISensor sensor) { - deactivating.Remove(sensor); - base.ActivateSensor(sensor); - } - - protected override void DeactivateSensor(ISensor sensor) { - if (deactivating.Contains(sensor)) { - deactivating.Remove(sensor); - base.DeactivateSensor(sensor); - } else if (active.Contains(sensor)) { - deactivating.Add(sensor); - } - } - - private void ReadminiNG(int number) { - int offset = 1 + number * 65; - - if (data[offset + 61] != ENDFLAG) - return; - - for (int i = 0; i < 2; i++) { - Sensor sensor = miniNGTemperatures[number * 2 + i]; - if (data[offset + 7 + i] > 0) { - sensor.Value = 0.5f * data[offset + 7 + i] + - sensor.Parameters[0].Value; - ActivateSensor(sensor); - } else { - DeactivateSensor(sensor); - } - } - - for (int i = 0; i < 2; i++) { - if (miniNGFans[number * 2 + i] == null) - miniNGFans[number * 2 + i] = - new Sensor("miniNG #" + (number + 1) + " Fan Channel " + (i + 1), - 4 + number * 2 + i, SensorType.Fan, this, settings); - - Sensor sensor = miniNGFans[number * 2 + i]; - - sensor.Value = 20.0f * data[offset + 43 + 2 * i]; - ActivateSensor(sensor); - } - - for (int i = 0; i < 2; i++) { - Sensor sensor = miniNGControls[number * 2 + i]; - sensor.Value = data[offset + 15 + i]; - ActivateSensor(sensor); - } - } - - private void ReadData() { - FTD2XX.Read(handle, data); - - if (data[0] != STARTFLAG) { - FTD2XX.FT_Purge(handle, FT_PURGE.FT_PURGE_RX); - return; - } - - if (data[1] == 255 || data[1] == 88) { // bigNG - - if (data[274] != protocolVersion) - return; - - if (primaryData.Length == 0) - primaryData = new byte[data.Length]; - data.CopyTo(primaryData, 0); - - for (int i = 0; i < digitalTemperatures.Length; i++) - if (data[238 + i] > 0) { - digitalTemperatures[i].Value = 0.5f * data[238 + i] + - digitalTemperatures[i].Parameters[0].Value; - ActivateSensor(digitalTemperatures[i]); - } else { - DeactivateSensor(digitalTemperatures[i]); - } - - for (int i = 0; i < analogTemperatures.Length; i++) - if (data[260 + i] > 0) { - analogTemperatures[i].Value = 0.5f * data[260 + i] + - analogTemperatures[i].Parameters[0].Value; - ActivateSensor(analogTemperatures[i]); - } else { - DeactivateSensor(analogTemperatures[i]); - } - - for (int i = 0; i < sensorhubTemperatures.Length; i++) - if (data[246 + i] > 0) { - sensorhubTemperatures[i].Value = 0.5f * data[246 + i] + - sensorhubTemperatures[i].Parameters[0].Value; - ActivateSensor(sensorhubTemperatures[i]); - } else { - DeactivateSensor(sensorhubTemperatures[i]); - } - - for (int i = 0; i < sensorhubFlows.Length; i++) - if (data[231 + i] > 0 && data[234] > 0) { - float pulsesPerSecond = (data[231 + i] * 4.0f) / data[234]; - float pulsesPerLiter = sensorhubFlows[i].Parameters[0].Value; - sensorhubFlows[i].Value = pulsesPerSecond * 3600 / pulsesPerLiter; - ActivateSensor(sensorhubFlows[i]); - } else { - DeactivateSensor(sensorhubFlows[i]); - } - - for (int i = 0; i < fans.Length; i++) { - float maxRPM = 11.5f * ((data[149 + 2 * i] << 8) | data[148 + 2 * i]); - - if (fans[i] == null) - fans[i] = new Sensor("Fan Channel " + i, i, SensorType.Fan, - this, new [] { new ParameterDescription("MaxRPM", - "Maximum revolutions per minute (RPM) of the fan.", maxRPM) - }, settings); - - float value; - if ((data[136] & (1 << i)) == 0) // pwm mode - value = 0.02f * data[137 + i]; - else // analog mode - value = 0.01f * data[141 + i]; - - fans[i].Value = fans[i].Parameters[0].Value * value; - ActivateSensor(fans[i]); - - controls[i].Value = 100 * value; - ActivateSensor(controls[i]); - } - - } else if (data[1] == 253) { // miniNG #1 - if (alternativeData.Length == 0) - alternativeData = new byte[data.Length]; - data.CopyTo(alternativeData, 0); - - ReadminiNG(0); - - if (data[66] == 253) // miniNG #2 - ReadminiNG(1); - } - } - - public override HardwareType HardwareType { - get { return HardwareType.TBalancer; } - } - - public override string GetReport() { - StringBuilder r = new StringBuilder(); - - r.AppendLine("T-Balancer bigNG"); - r.AppendLine(); - r.Append("Port Index: "); - r.AppendLine(portIndex.ToString(CultureInfo.InvariantCulture)); - r.AppendLine(); - - r.AppendLine("Primary System Information Answer"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - for (int i = 0; i <= 0x11; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X3", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - int index = ((i << 4) | j); - if (index < primaryData.Length) { - r.Append(" "); - r.Append(primaryData[index].ToString("X2", CultureInfo.InvariantCulture)); - } - } - r.AppendLine(); - } - r.AppendLine(); - - if (alternativeData.Length > 0) { - r.AppendLine("Alternative System Information Answer"); - r.AppendLine(); - r.AppendLine(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"); - r.AppendLine(); - for (int i = 0; i <= 0x11; i++) { - r.Append(" "); - r.Append((i << 4).ToString("X3", CultureInfo.InvariantCulture)); - r.Append(" "); - for (int j = 0; j <= 0xF; j++) { - int index = ((i << 4) | j); - if (index < alternativeData.Length) { - r.Append(" "); - r.Append(alternativeData[index].ToString("X2", CultureInfo.InvariantCulture)); - } - } - r.AppendLine(); - } - r.AppendLine(); - } - - return r.ToString(); - } - - private void DelayedAlternativeRequest() { - System.Threading.Thread.Sleep(500); - FTD2XX.Write(handle, new byte[] { 0x37 }); - } - - public void Open() { - FTD2XX.FT_Open(portIndex, out handle); - FTD2XX.FT_SetBaudRate(handle, 19200); - FTD2XX.FT_SetDataCharacteristics(handle, 8, 1, 0); - FTD2XX.FT_SetFlowControl(handle, FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, - 0x13); - FTD2XX.FT_SetTimeouts(handle, 1000, 1000); - FTD2XX.FT_Purge(handle, FT_PURGE.FT_PURGE_ALL); - } - - public override void Update() { - while (FTD2XX.BytesToRead(handle) >= 285) - ReadData(); - if (FTD2XX.BytesToRead(handle) == 1) - FTD2XX.ReadByte(handle); - - FTD2XX.Write(handle, new byte[] { 0x38 }); - alternativeRequest.BeginInvoke(null, null); - } - - public override void Close() { - FTD2XX.FT_Close(handle); - base.Close(); - } - - } -} diff --git a/Hardware/TBalancer/TBalancerGroup.cs b/Hardware/TBalancer/TBalancerGroup.cs deleted file mode 100644 index 79b4a89..0000000 --- a/Hardware/TBalancer/TBalancerGroup.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2009-2012 Michael Möller - -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using System.Threading; - -namespace OpenHardwareMonitor.Hardware.TBalancer { - internal class TBalancerGroup : IGroup { - - private readonly List hardware = new List(); - private readonly StringBuilder report = new StringBuilder(); - - public TBalancerGroup(ISettings settings) { - - uint numDevices; - try { - if (FTD2XX.FT_CreateDeviceInfoList(out numDevices) != FT_STATUS.FT_OK) { - report.AppendLine("Status: FT_CreateDeviceInfoList failed"); - return; - } - } catch (DllNotFoundException) { return; } - catch (ArgumentNullException) { return; } - catch (EntryPointNotFoundException) { return; } - catch (BadImageFormatException) { return; } - - FT_DEVICE_INFO_NODE[] info = new FT_DEVICE_INFO_NODE[numDevices]; - if (FTD2XX.FT_GetDeviceInfoList(info, ref numDevices) != FT_STATUS.FT_OK) - { - report.AppendLine("Status: FT_GetDeviceInfoList failed"); - return; - } - - // make sure numDevices is not larger than the info array - if (numDevices > info.Length) - numDevices = (uint)info.Length; - - for (int i = 0; i < numDevices; i++) { - report.Append("Device Index: "); - report.AppendLine(i.ToString(CultureInfo.InvariantCulture)); - report.Append("Device Type: "); - report.AppendLine(info[i].Type.ToString()); - - // the T-Balancer always uses an FT232BM - if (info[i].Type != FT_DEVICE.FT_DEVICE_232BM) { - report.AppendLine("Status: Wrong device type"); - continue; - } - - FT_HANDLE handle; - FT_STATUS status = FTD2XX.FT_Open(i, out handle); - if (status != FT_STATUS.FT_OK) { - report.AppendLine("Open Status: " + status); - continue; - } - - FTD2XX.FT_SetBaudRate(handle, 19200); - FTD2XX.FT_SetDataCharacteristics(handle, 8, 1, 0); - FTD2XX.FT_SetFlowControl(handle, FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, - 0x13); - FTD2XX.FT_SetTimeouts(handle, 1000, 1000); - FTD2XX.FT_Purge(handle, FT_PURGE.FT_PURGE_ALL); - - status = FTD2XX.Write(handle, new byte[] { 0x38 }); - if (status != FT_STATUS.FT_OK) { - report.AppendLine("Write Status: " + status); - FTD2XX.FT_Close(handle); - continue; - } - - bool isValid = false; - byte protocolVersion = 0; - - int j = 0; - while (FTD2XX.BytesToRead(handle) == 0 && j < 2) { - Thread.Sleep(100); - j++; - } - if (FTD2XX.BytesToRead(handle) > 0) { - if (FTD2XX.ReadByte(handle) == TBalancer.STARTFLAG) { - while (FTD2XX.BytesToRead(handle) < 284 && j < 5) { - Thread.Sleep(100); - j++; - } - int length = FTD2XX.BytesToRead(handle); - if (length >= 284) { - byte[] data = new byte[285]; - data[0] = TBalancer.STARTFLAG; - for (int k = 1; k < data.Length; k++) - data[k] = FTD2XX.ReadByte(handle); - - // check protocol version 2X (protocols seen: 2C, 2A, 28) - isValid = (data[274] & 0xF0) == 0x20; - protocolVersion = data[274]; - if (!isValid) { - report.Append("Status: Wrong Protocol Version: 0x"); - report.AppendLine( - protocolVersion.ToString("X", CultureInfo.InvariantCulture)); - } - } else { - report.AppendLine("Status: Wrong Message Length: " + length); - } - } else { - report.AppendLine("Status: Wrong Startflag"); - } - } else { - report.AppendLine("Status: No Response"); - } - - FTD2XX.FT_Purge(handle, FT_PURGE.FT_PURGE_ALL); - FTD2XX.FT_Close(handle); - - if (isValid) { - report.AppendLine("Status: OK"); - hardware.Add(new TBalancer(i, protocolVersion, settings)); - } - - if (i < numDevices - 1) - report.AppendLine(); - } - } - - public IEnumerable Hardware => hardware; - - public string GetReport() { - if (report.Length > 0) { - StringBuilder r = new StringBuilder(); - r.AppendLine("FTD2XX"); - r.AppendLine(); - r.Append(report); - r.AppendLine(); - return r.ToString(); - } else - return null; - } - - public void Close() { - foreach (TBalancer tbalancer in hardware) - tbalancer.Close(); - } - } -} diff --git a/Hardware/ThreadAffinity.cs b/Hardware/ThreadAffinity.cs deleted file mode 100755 index 6324450..0000000 --- a/Hardware/ThreadAffinity.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - - Copyright (C) 2010-2014 Michael Möller - -*/ - -using System; -using System.Runtime.InteropServices; - -namespace OpenHardwareMonitor.Hardware { - - internal static class ThreadAffinity { - - public static ulong Set(ulong mask) { - if (mask == 0) - return 0; - - if (Software.OperatingSystem.IsLinux) - { // Unix - ulong result = 0; - if (NativeMethods.sched_getaffinity(0, (IntPtr)Marshal.SizeOf(result), - ref result) != 0) - return 0; - if (NativeMethods.sched_setaffinity(0, (IntPtr)Marshal.SizeOf(mask), - ref mask) != 0) - return 0; - return result; - } // Windows - UIntPtr uIntPtrMask; - try { - uIntPtrMask = (UIntPtr)mask; - } catch (OverflowException) { - throw new ArgumentOutOfRangeException("mask"); - } - return (ulong)NativeMethods.SetThreadAffinityMask( - NativeMethods.GetCurrentThread(), uIntPtrMask); - } - - private static class NativeMethods { - private const string KERNEL = "kernel32.dll"; - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] - public static extern UIntPtr - SetThreadAffinityMask(IntPtr handle, UIntPtr mask); - - [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] - public static extern IntPtr GetCurrentThread(); - - private const string LIBC = "libc"; - - [DllImport(LIBC)] - public static extern int sched_getaffinity(int pid, IntPtr maskSize, - ref ulong mask); - - [DllImport(LIBC)] - public static extern int sched_setaffinity(int pid, IntPtr maskSize, - ref ulong mask); - } - } -} - diff --git a/Interop/Kernel32.cs b/Interop/Kernel32.cs deleted file mode 100644 index c485235..0000000 --- a/Interop/Kernel32.cs +++ /dev/null @@ -1,834 +0,0 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.IO; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -// ReSharper disable InconsistentNaming - -namespace OpenHardwareMonitor.Interop { - public class Kernel32 { - internal const string IntelNVMeMiniPortSignature1 = "NvmeMini"; - internal const string IntelNVMeMiniPortSignature2 = "IntelNvm"; - internal const int MAX_DRIVE_ATTRIBUTES = 512; - internal const uint NVMePassThroughSrbIoCode = 0xe0002000; - internal const int SCSI_PASS_THROUGH_BUFFER_SIZE = 512; - internal const byte SMART_LBA_HI = 0xC2; - internal const byte SMART_LBA_MID = 0x4F; - - private const string DllName = "kernel32.dll"; - - internal enum DFP : uint { - DFP_GET_VERSION = 0x00074080, - DFP_SEND_DRIVE_COMMAND = 0x0007c084, - DFP_RECEIVE_DRIVE_DATA = 0x0007c088 - } - - internal enum IOCTL : uint { - IOCTL_SCSI_PASS_THROUGH = 0x04d004, - IOCTL_SCSI_MINIPORT = 0x04d008, - IOCTL_SCSI_PASS_THROUGH_DIRECT = 0x04d014, - IOCTL_SCSI_GET_ADDRESS = 0x41018, - IOCTL_STORAGE_QUERY_PROPERTY = 0x2D1400 - } - - [Flags] - public enum NVME_CRITICAL_WARNING { - None = 0x00, - AvailableSpaceLow = 0x01, // If set to 1, then the available spare space has fallen below the threshold. - TemperatureThreshold = 0x02, // If set to 1, then a temperature is above an over temperature threshold or below an under temperature threshold. - ReliabilityDegraded = 0x04, // If set to 1, then the device reliability has been degraded due to significant media related errors or any internal error that degrades device reliability. - ReadOnly = 0x08, // If set to 1, then the media has been placed in read only mode - VolatileMemoryBackupDeviceFailed = 0x10 // If set to 1, then the volatile memory backup device has failed. This field is only valid if the controller has a volatile memory backup solution. - } - - [Flags] - internal enum NVME_DIRECTION : uint { - NVME_FROM_HOST_TO_DEV = 1, - NVME_FROM_DEV_TO_HOST = 2, - NVME_BI_DIRECTION = NVME_FROM_DEV_TO_HOST | NVME_FROM_HOST_TO_DEV - } - - internal enum NVME_LOG_PAGES { - NVME_LOG_PAGE_ERROR_INFO = 0x01, - NVME_LOG_PAGE_HEALTH_INFO = 0x02, - NVME_LOG_PAGE_FIRMWARE_SLOT_INFO = 0x03, - NVME_LOG_PAGE_CHANGED_NAMESPACE_LIST = 0x04, - NVME_LOG_PAGE_COMMAND_EFFECTS = 0x05, - NVME_LOG_PAGE_DEVICE_SELF_TEST = 0x06, - NVME_LOG_PAGE_TELEMETRY_HOST_INITIATED = 0x07, - NVME_LOG_PAGE_TELEMETRY_CTLR_INITIATED = 0x08, - NVME_LOG_PAGE_RESERVATION_NOTIFICATION = 0x80, - NVME_LOG_PAGE_SANITIZE_STATUS = 0x81 - } - - internal enum ATA_COMMAND : byte { - /// - /// SMART data requested. - /// - ATA_SMART = 0xB0, - - /// - /// Identify data is requested. - /// - ATA_IDENTIFY_DEVICE = 0xEC - } - - internal enum SCSI_IOCTL_DATA { - SCSI_IOCTL_DATA_OUT = 0, - SCSI_IOCTL_DATA_IN = 1, - SCSI_IOCTL_DATA_UNSPECIFIED = 2 - } - - internal enum SMART_FEATURES : byte { - /// - /// Read SMART data. - /// - SMART_READ_DATA = 0xD0, - - /// - /// Read SMART thresholds. - /// - READ_THRESHOLDS = 0xD1, /* obsolete */ - - /// - /// Autosave SMART data. - /// - ENABLE_DISABLE_AUTOSAVE = 0xD2, - - /// - /// Save SMART attributes. - /// - SAVE_ATTRIBUTE_VALUES = 0xD3, - - /// - /// Set SMART to offline immediately. - /// - EXECUTE_OFFLINE_DIAGS = 0xD4, - - /// - /// Read SMART log. - /// - SMART_READ_LOG = 0xD5, - - /// - /// Write SMART log. - /// - SMART_WRITE_LOG = 0xD6, - - /// - /// Write SMART thresholds. - /// - WRITE_THRESHOLDS = 0xD7, /* obsolete */ - - /// - /// Enable SMART. - /// - ENABLE_SMART = 0xD8, - - /// - /// Disable SMART. - /// - DISABLE_SMART = 0xD9, - - /// - /// Get SMART status. - /// - RETURN_SMART_STATUS = 0xDA, - - /// - /// Set SMART to offline automatically. - /// - ENABLE_DISABLE_AUTO_OFFLINE = 0xDB /* obsolete */ - } - - internal enum STORAGE_BUS_TYPE { - BusTypeUnknown = 0x00, - BusTypeScsi, - BusTypeAtapi, - BusTypeAta, - BusType1394, - BusTypeSsa, - BusTypeFibre, - BusTypeUsb, - BusTypeRAID, - BusTypeiScsi, - BusTypeSas, - BusTypeSata, - BusTypeSd, - BusTypeMmc, - BusTypeVirtual, - BusTypeFileBackedVirtual, - BusTypeSpaces, - BusTypeNvme, - BusTypeSCM, - BusTypeMax, - BusTypeMaxReserved = 0x7F - } - - internal enum STORAGE_PROPERTY_ID { - StorageDeviceProperty = 0, - StorageAdapterProperty, - StorageDeviceIdProperty, - StorageDeviceUniqueIdProperty, - StorageDeviceWriteCacheProperty, - StorageMiniportProperty, - StorageAccessAlignmentProperty, - StorageDeviceSeekPenaltyProperty, - StorageDeviceTrimProperty, - StorageDeviceWriteAggregationProperty, - StorageDeviceDeviceTelemetryProperty, - StorageDeviceLBProvisioningProperty, - StorageDevicePowerProperty, - StorageDeviceCopyOffloadProperty, - StorageDeviceResiliencyProperty, - StorageDeviceMediumProductType, - StorageAdapterRpmbProperty, - StorageDeviceIoCapabilityProperty = 48, - StorageAdapterProtocolSpecificProperty, - StorageDeviceProtocolSpecificProperty, - StorageAdapterTemperatureProperty, - StorageDeviceTemperatureProperty, - StorageAdapterPhysicalTopologyProperty, - StorageDevicePhysicalTopologyProperty, - StorageDeviceAttributesProperty, - StorageDeviceManagementStatus, - StorageAdapterSerialNumberProperty, - StorageDeviceLocationProperty - } - - internal enum STORAGE_PROTOCOL_NVME_DATA_TYPE { - NVMeDataTypeUnknown = 0, - NVMeDataTypeIdentify, - NVMeDataTypeLogPage, - NVMeDataTypeFeature - } - - internal enum STORAGE_PROTOCOL_TYPE { - ProtocolTypeUnknown = 0x00, - ProtocolTypeScsi, - ProtocolTypeAta, - ProtocolTypeNvme, - ProtocolTypeSd, - ProtocolTypeProprietary = 0x7E, - ProtocolTypeMaxReserved = 0x7F - } - - internal enum STORAGE_QUERY_TYPE { - PropertyStandardQuery = 0, - PropertyExistsQuery, - PropertyMaskQuery, - PropertyQueryMaxDefined - } - - /// - /// Create a instance from a struct with zero initialized memory arrays - /// no need to init every inner array with the correct sizes - /// - /// type of struct that is needed - /// - internal static T CreateStruct() { - int size = Marshal.SizeOf(); - var ptr = Marshal.AllocHGlobal(size); - RtlZeroMemory(ptr, size); - var result = Marshal.PtrToStructure(ptr); - Marshal.FreeHGlobal(ptr); - return result; - } - - internal static SafeHandle OpenDevice(string devicePath) { - SafeHandle hDevice = CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero); - if (hDevice.IsInvalid || hDevice.IsClosed) - hDevice = null; - - return hDevice; - } - - [DllImport(DllName, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - internal static extern SafeFileHandle CreateFile - ( - [MarshalAs(UnmanagedType.LPTStr)] string lpFileName, - [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess, - [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, - IntPtr lpSecurityAttributes, - [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, - [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes, - IntPtr hTemplateFile); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - DFP dwIoControlCode, - ref SENDCMDINPARAMS lpInBuffer, - int nInBufferSize, - out ATTRIBUTECMDOUTPARAMS lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - DFP dwIoControlCode, - ref SENDCMDINPARAMS lpInBuffer, - int nInBufferSize, - out THRESHOLDCMDOUTPARAMS lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - DFP dwIoControlCode, - ref SENDCMDINPARAMS lpInBuffer, - int nInBufferSize, - out SENDCMDOUTPARAMS lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - DFP dwIoControlCode, - ref SENDCMDINPARAMS lpInBuffer, - int nInBufferSize, - out IDENTIFYCMDOUTPARAMS lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - IOCTL dwIoControlCode, - ref STORAGE_PROPERTY_QUERY lpInBuffer, - int nInBufferSize, - out STORAGE_DEVICE_DESCRIPTOR_HEADER lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, - CallingConvention = CallingConvention.Winapi, - CharSet = CharSet.Auto, - SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - IOCTL dwIoControlCode, - ref STORAGE_PROPERTY_QUERY lpInBuffer, - int nInBufferSize, - IntPtr lpOutBuffer, - uint nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeviceIoControl - ( - SafeHandle hDevice, - IOCTL dwIoControlCode, - IntPtr lpInBuffer, - int nInBufferSize, - IntPtr lpOutBuffer, - int nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport(DllName, SetLastError = true)] - internal static extern void RtlZeroMemory(IntPtr Destination, int Length); - - [DllImport(DllName, EntryPoint = "CopyMemory", SetLastError = false)] - internal static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length); - - [DllImport(DllName, SetLastError = true)] - internal static extern IntPtr LoadLibrary(string lpFileName); - - [StructLayout(LayoutKind.Sequential)] - internal struct MEMORYSTATUSEX { - public uint dwLength; - public uint dwMemoryLoad; - public ulong ullTotalPhys; - public ulong ullAvailPhys; - public ulong ullTotalPageFile; - public ulong ullAvailPageFile; - public ulong ullTotalVirtual; - public ulong ullAvailVirtual; - public ulong ullAvailExtendedVirtual; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct SMART_ATTRIBUTE { - public byte Id; - public short Flags; - public byte CurrentValue; - public byte WorstValue; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] - public byte[] RawValue; - - public byte Reserved; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct SMART_THRESHOLD { - public byte Id; - public byte Threshold; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] - public byte[] Reserved; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct SENDCMDINPARAMS { - public uint cBufferSize; - public IDEREGS irDriveRegs; - public byte bDriveNumber; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public byte[] bReserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - public uint[] dwReserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - public byte[] bBuffer; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct IDEREGS { - public SMART_FEATURES bFeaturesReg; - public byte bSectorCountReg; - public byte bSectorNumberReg; - public byte bCylLowReg; - public byte bCylHighReg; - public byte bDriveHeadReg; - public ATA_COMMAND bCommandReg; - public byte bReserved; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct DRIVERSTATUS { - public byte bDriverError; - public byte bIDEError; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] - public byte[] Reserved; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct SENDCMDOUTPARAMS { - public uint cBufferSize; - public DRIVERSTATUS DriverStatus; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - public byte[] bBuffer; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct ATTRIBUTECMDOUTPARAMS { - public uint cBufferSize; - public DRIVERSTATUS DriverStatus; - public byte Version; - public byte Reserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_DRIVE_ATTRIBUTES)] - public SMART_ATTRIBUTE[] Attributes; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct THRESHOLDCMDOUTPARAMS { - public uint cBufferSize; - public DRIVERSTATUS DriverStatus; - public byte Version; - public byte Reserved; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_DRIVE_ATTRIBUTES)] - public SMART_THRESHOLD[] Thresholds; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct IDENTIFY_DATA { - public ushort GeneralConfiguration; - public ushort NumberOfCylinders; - public ushort Reserved1; - public ushort NumberOfHeads; - public ushort UnformattedBytesPerTrack; - public ushort UnformattedBytesPerSector; - public ushort SectorsPerTrack; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public ushort[] VendorUnique; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public byte[] SerialNumber; - - public ushort BufferType; - public ushort BufferSectorSize; - public ushort NumberOfEccBytes; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public byte[] FirmwareRevision; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] - public byte[] ModelNumber; - - public byte MaximumBlockTransfer; - public byte VendorUnique2; - public ushort DoubleWordIo; - public ushort Capabilities; - public ushort Reserved2; - public byte VendorUnique3; - public byte PioCycleTimingMode; - public byte VendorUnique4; - public byte DmaCycleTimingMode; - public ushort TranslationFieldsValid; - public ushort NumberOfCurrentCylinders; - public ushort NumberOfCurrentHeads; - public ushort CurrentSectorsPerTrack; - public uint CurrentSectorCapacity; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 197)] - public ushort[] Reserved3; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct IDENTIFYCMDOUTPARAMS { - public uint cBufferSize; - public DRIVERSTATUS DriverStatus; - public IDENTIFY_DATA Identify; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_PROPERTY_QUERY { - public STORAGE_PROPERTY_ID PropertyId; - public STORAGE_QUERY_TYPE QueryType; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] - public byte[] AdditionalParameters; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_DEVICE_DESCRIPTOR_HEADER { - public uint Version; - public uint Size; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_DEVICE_DESCRIPTOR { - public uint Version; - public uint Size; - public byte DeviceType; - public byte DeviceTypeModifier; - - [MarshalAs(UnmanagedType.U1)] - public bool RemovableMedia; - - [MarshalAs(UnmanagedType.U1)] - public bool CommandQueueing; - - public uint VendorIdOffset; - public uint ProductIdOffset; - public uint ProductRevisionOffset; - public uint SerialNumberOffset; - public STORAGE_BUS_TYPE BusType; - public uint RawPropertiesLength; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SRB_IO_CONTROL { - public uint HeaderLenght; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public byte[] Signature; - - public uint Timeout; - public uint ControlCode; - public uint ReturnCode; - public uint Length; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NVME_PASS_THROUGH_IOCTL { - public SRB_IO_CONTROL srb; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] - public uint[] VendorSpecific; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public uint[] NVMeCmd; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] - public uint[] CplEntry; - - public NVME_DIRECTION Direction; - public uint QueueId; - public uint DataBufferLen; - public uint MetaDataLen; - public uint ReturnBufferLen; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096)] - public byte[] DataBuffer; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SCSI_PASS_THROUGH { - [MarshalAs(UnmanagedType.U2)] - public ushort Length; - - public byte ScsiStatus; - public byte PathId; - public byte TargetId; - public byte Lun; - public byte CdbLength; - public byte SenseInfoLength; - public byte DataIn; - public uint DataTransferLength; - public uint TimeOutValue; - public IntPtr DataBufferOffset; - public uint SenseInfoOffset; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] Cdb; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SCSI_PASS_THROUGH_WITH_BUFFERS { - public SCSI_PASS_THROUGH Spt; - - public uint Filler; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public byte[] SenseBuf; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = SCSI_PASS_THROUGH_BUFFER_SIZE)] - public byte[] DataBuf; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NVME_POWER_STATE_DESC { - public ushort MP; // bit 0:15 Maximum Power (MP) in centiwatts - public byte Reserved0; // bit 16:23 - public byte MPS_NOPS; // bit 24 Max Power Scale (MPS), bit 25 Non-Operational State (NOPS) - public uint ENLAT; // bit 32:63 Entry Latency (ENLAT) in microseconds - public uint EXLAT; // bit 64:95 Exit Latency (EXLAT) in microseconds - public byte RRT; // bit 96:100 Relative Read Throughput (RRT) - public byte RRL; // bit 104:108 Relative Read Latency (RRL) - public byte RWT; // bit 112:116 Relative Write Throughput (RWT) - public byte RWL; // bit 120:124 Relative Write Latency (RWL) - public ushort IDLP; // bit 128:143 Idle Power (IDLP) - public byte IPS; // bit 150:151 Idle Power Scale (IPS) - public byte Reserved7; // bit 152:159 - public ushort ACTP; // bit 160:175 Active Power (ACTP) - public byte APW_APS; // bit 176:178 Active Power Workload (APW), bit 182:183 Active Power Scale (APS) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)] - public byte[] Reserved9; // bit 184:255. - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NVME_IDENTIFY_CONTROLLER_DATA { - public ushort VID; // byte 0:1 M - PCI Vendor ID (VID) - public ushort SSVID; // byte 2:3 M - PCI Subsystem Vendor ID (SSVID) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] - public byte[] SN; // byte 4: 23 M - Serial Number (SN) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)] - public byte[] MN; // byte 24:63 M - Model Number (MN) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public byte[] FR; // byte 64:71 M - Firmware Revision (FR) - - public byte RAB; // byte 72 M - Recommended Arbitration Burst (RAB) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] - public byte[] IEEE; // byte 73:75 M - IEEE OUI Identifier (IEEE). Controller Vendor code. - - public byte CMIC; // byte 76 O - Controller Multi-Path I/O and Namespace Sharing Capabilities (CMIC) - public byte MDTS; // byte 77 M - Maximum Data Transfer Size (MDTS) - public ushort CNTLID; // byte 78:79 M - Controller ID (CNTLID) - public uint VER; // byte 80:83 M - Version (VER) - public uint RTD3R; // byte 84:87 M - RTD3 Resume Latency (RTD3R) - public uint RTD3E; // byte 88:91 M - RTD3 Entry Latency (RTD3E) - public uint OAES; // byte 92:95 M - Optional Asynchronous Events Supported (OAES) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 144)] - public byte[] Reserved0; // byte 96:239. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] ReservedForManagement; // byte 240:255. Refer to the NVMe Management Interface Specification for definition. - - public ushort OACS; // byte 256:257 M - Optional Admin Command Support (OACS) - public byte ACL; // byte 258 M - Abort Command Limit (ACL) - public byte AERL; // byte 259 M - Asynchronous Event Request Limit (AERL) - public byte FRMW; // byte 260 M - Firmware Updates (FRMW) - public byte LPA; // byte 261 M - Log Page Attributes (LPA) - public byte ELPE; // byte 262 M - Error Log Page Entries (ELPE) - public byte NPSS; // byte 263 M - Number of Power States Support (NPSS) - public byte AVSCC; // byte 264 M - Admin Vendor Specific Command Configuration (AVSCC) - public byte APSTA; // byte 265 O - Autonomous Power State Transition Attributes (APSTA) - public ushort WCTEMP; // byte 266:267 M - Warning Composite Temperature Threshold (WCTEMP) - public ushort CCTEMP; // byte 268:269 M - Critical Composite Temperature Threshold (CCTEMP) - public ushort MTFA; // byte 270:271 O - Maximum Time for Firmware Activation (MTFA) - public uint HMPRE; // byte 272:275 O - Host Memory Buffer Preferred Size (HMPRE) - public uint HMMIN; // byte 276:279 O - Host Memory Buffer Minimum Size (HMMIN) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] TNVMCAP; // byte 280:295 O - Total NVM Capacity (TNVMCAP) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] UNVMCAP; // byte 296:311 O - Unallocated NVM Capacity (UNVMCAP) - - public uint RPMBS; // byte 312:315 O - Replay Protected Memory Block Support (RPMBS) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 196)] - public byte[] Reserved1; // byte 316:511 - - public byte SQES; // byte 512 M - Submission Queue Entry Size (SQES) - public byte CQES; // byte 513 M - Completion Queue Entry Size (CQES) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public byte[] Reserved2; // byte 514:515 - - public uint NN; // byte 516:519 M - Number of Namespaces (NN) - public ushort ONCS; // byte 520:521 M - Optional NVM Command Support (ONCS) - public ushort FUSES; // byte 522:523 M - Fused Operation Support (FUSES) - public byte FNA; // byte 524 M - Format NVM Attributes (FNA) - public byte VWC; // byte 525 M - Volatile Write Cache (VWC) - public ushort AWUN; // byte 526:527 M - Atomic Write Unit Normal (AWUN) - public ushort AWUPF; // byte 528:529 M - Atomic Write Unit Power Fail (AWUPF) - public byte NVSCC; // byte 530 M - NVM Vendor Specific Command Configuration (NVSCC) - public byte Reserved3; // byte 531 - public ushort ACWU; // byte 532:533 O - Atomic Compare & Write Unit (ACWU) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public byte[] Reserved4; // byte 534:535 - - public uint SGLS; // byte 536:539 O - SGL Support (SGLS) - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 164)] - public byte[] Reserved5; // byte 540:703 - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1344)] - public byte[] Reserved6; // byte 704:2047 - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] - public NVME_POWER_STATE_DESC[] PDS; // byte 2048:3071 Power State Descriptors - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] - public byte[] VS; // byte 3072:4095 Vendor Specific - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NVME_HEALTH_INFO_LOG { - public byte CriticalWarning; // This field indicates critical warnings for the state of the controller. Each bit corresponds to a critical warning type; multiple bits may be set. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - public byte[] CompositeTemp; // Composite Temperature: Contains the temperature of the overall device (controller and NVM included) in units of Kelvin. - - public byte AvailableSpare; // Available Spare: Contains a normalized percentage (0 to 100%) of the remaining spare capacity available - - public byte - AvailableSpareThreshold; // Available Spare Threshold: When the Available Spare falls below the threshold indicated in this field, an asynchronous event completion may occur. The value is indicated as a normalized percentage (0 to 100%). - - public byte - PercentageUsed; // Percentage Used: Contains a vendor specific estimate of the percentage of NVM subsystem life used based on the actual usage and the manufacturer’s prediction of NVM life. A value of 100 indicates that the estimated endurance of the NVM in the NVM subsystem has been consumed, but may not indicate an NVM subsystem failure. The value is allowed to exceed 100. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] - public byte[] Reserved1; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] - DataUnitRead; // Data Units Read: Contains the number of 512 byte data units the host has read from the controller; this value does not include metadata. This value is reported in thousands (i.e., a value of 1 corresponds to 1000 units of 512 bytes read) and is rounded up. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] - DataUnitWritten; // Data Units Written: Contains the number of 512 byte data units the host has written to the controller; this value does not include metadata. This value is reported in thousands (i.e., a value of 1 corresponds to 1000 units of 512 bytes written) and is rounded up. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] - HostReadCommands; // Host Read Commands: Contains the number of read commands completed by the controller. For the NVM command set, this is the number of Compare and Read commands. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] HostWriteCommands; // Host Write Commands: Contains the number of write commands completed by the controller. For the NVM command set, this is the number of Write commands. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] ControllerBusyTime; // Controller Busy Time: Contains the amount of time the controller is busy with I/O commands. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] PowerCycles; // Power Cycles: Contains the number of power cycles. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] PowerOnHours; // Power On Hours: Contains the number of power-on hours. This does not include time that the controller was powered and in a low power state condition. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] UnsafeShutdowns; // Unsafe Shutdowns: Contains the number of unsafe shutdowns. This count is incremented when a shutdown notification is not received prior to loss of power. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] - MediaAndDataIntegrityErrors; // Media Errors: Contains the number of occurrences where the controller detected an unrecoverable data integrity error. Errors such as uncorrectable ECC, CRC checksum failure, or LBA tag mismatch are included in this field. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public byte[] NumberErrorInformationLogEntries; // Number of Error Information Log Entries: Contains the number of Error Information log entries over the life of the controller - - public uint - WarningCompositeTemperatureTime; // Warning Composite Temperature Time: Contains the amount of time in minutes that the controller is operational and the Composite Temperature is greater than or equal to the Warning Composite Temperature Threshold. - - public uint - CriticalCompositeTemperatureTime; // Critical Composite Temperature Time: Contains the amount of time in minutes that the controller is operational and the Composite Temperature is greater than the Critical Composite Temperature Threshold. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public ushort[] TemperatureSensor; // Contains the current temperature reported by temperature sensor 1-8. - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 296)] - internal byte[] Reserved2; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_PROTOCOL_SPECIFIC_DATA { - public STORAGE_PROTOCOL_TYPE ProtocolType; - public uint DataType; - public uint ProtocolDataRequestValue; - public uint ProtocolDataRequestSubValue; - public uint ProtocolDataOffset; - public uint ProtocolDataLength; - public uint FixedProtocolReturnData; - public uint ProtocolDataRequestSubValue2; - public uint ProtocolDataRequestSubValue3; - public uint Reserved; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct STORAGE_QUERY_BUFFER { - public STORAGE_PROPERTY_ID PropertyId; - public STORAGE_QUERY_TYPE QueryType; - public STORAGE_PROTOCOL_SPECIFIC_DATA ProtocolSpecific; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096)] - internal byte[] Buffer; - } - } -} \ No newline at end of file diff --git a/LibreHardwareMonitor.sln b/LibreHardwareMonitor.sln index faec3ff..43feba4 100644 --- a/LibreHardwareMonitor.sln +++ b/LibreHardwareMonitor.sln @@ -3,18 +3,18 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29306.81 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenHardwareMonitorLib", "OpenHardwareMonitorLib.csproj", "{B0397530-545A-471D-BB74-027AE456DF1A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibreHardwareMonitorLib", "LibreHardwareMonitorLib\LibreHardwareMonitorLib.csproj", "{B0397530-545A-471D-BB74-027AE456DF1A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibreHardwareMonitor", "LibreHardwareMonitor.csproj", "{F5E0C1F7-9E9B-46F2-AC88-8C9C1C923880}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibreHardwareMonitor", "LibreHardwareMonitor\LibreHardwareMonitor.csproj", "{F5E0C1F7-9E9B-46F2-AC88-8C9C1C923880}" ProjectSection(ProjectDependencies) = postProject {B0397530-545A-471D-BB74-027AE456DF1A} = {B0397530-545A-471D-BB74-027AE456DF1A} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "External\Aga.Controls\Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "Aga.Controls\Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OxyPlot", "External\OxyPlot\OxyPlot\OxyPlot.csproj", "{BCC43E58-E473-403E-A84D-63FEDC723040}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OxyPlot", "OxyPlot\OxyPlot\OxyPlot.csproj", "{BCC43E58-E473-403E-A84D-63FEDC723040}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OxyPlot.WindowsForms", "External\OxyPlot\OxyPlot.WindowsForms\OxyPlot.WindowsForms.csproj", "{D4554296-094E-4CAC-8EAE-44EB250666C6}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OxyPlot.WindowsForms", "OxyPlot\OxyPlot.WindowsForms\OxyPlot.WindowsForms.csproj", "{D4554296-094E-4CAC-8EAE-44EB250666C6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Controls", "Controls", "{23F54DBD-8998-4E22-A4E4-60F4F77F9B65}" EndProject diff --git a/LibreHardwareMonitor.csproj b/LibreHardwareMonitor/LibreHardwareMonitor.csproj similarity index 80% rename from LibreHardwareMonitor.csproj rename to LibreHardwareMonitor/LibreHardwareMonitor.csproj index ecec8cf..769fd63 100644 --- a/LibreHardwareMonitor.csproj +++ b/LibreHardwareMonitor/LibreHardwareMonitor.csproj @@ -1,306 +1,312 @@ - - - - Debug - AnyCPU - {F5E0C1F7-9E9B-46F2-AC88-8C9C1C923880} - 9.0.30729 - 2.0 - WinExe - win - false - OpenHardwareMonitor - v4.5.2 - 512 - OpenHardwareMonitor - Resources\icon.ico - Resources\app.manifest - OpenHardwareMonitor.Program - - - 3.5 - - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - - - true - full - false - Bin\Debug\ - TRACE;DEBUG - prompt - 4 - true - AllRules.ruleset - AnyCPU - false - - - none - true - Bin\Release\ - TRACE - prompt - 4 - false - AllRules.ruleset - false - - - - packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - UserControl - - - Form - - - PortForm.cs - - - - Form - - - ParameterForm.cs - - - - - - Component - - - - - - - - - - - - - - - - - Form - - - AboutBox.cs - - - - Form - - - MainForm.cs - - - - - - - - - - Component - - - - - AboutBox.cs - Designer - - - PortForm.cs - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - - - - - ParameterForm.cs - - - - - - - - - MainForm.cs - Designer - - - - - - {e73bb233-d88b-44a7-a98f-d71ee158381d} - Aga.Controls - - - {d4554296-094e-4cac-8eae-44eb250666c6} - OxyPlot.WindowsForms - - - {bcc43e58-e473-403e-a84d-63fedc723040} - OxyPlot - - - {B0397530-545A-471D-BB74-027AE456DF1A} - OpenHardwareMonitorLib - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Debug + AnyCPU + {F5E0C1F7-9E9B-46F2-AC88-8C9C1C923880} + 9.0.30729 + 2.0 + WinExe + win + false + LibreHardwareMonitor + v4.5.2 + 512 + LibreHardwareMonitor + Resources\icon.ico + Resources\app.manifest + LibreHardwareMonitor.Program + + + 3.5 + + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + {F5E0C1F7-9E9B-46F2-AC88-8C9C1C923880} + + + true + full + false + Bin\Debug\ + TRACE;DEBUG + prompt + 4 + true + AllRules.ruleset + AnyCPU + false + + + none + true + Bin\Release\ + TRACE + prompt + 4 + false + AllRules.ruleset + false + + + + False + ..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + Properties\AssemblyVersion.cs + + + + + + + UserControl + + + Form + + + PortForm.cs + + + + Form + + + ParameterForm.cs + + + + + + Component + + + + + + + + + + + + + + + + Form + + + AboutBox.cs + + + + Form + + + MainForm.cs + + + + + + + + + + Component + + + + + AboutBox.cs + Designer + + + PortForm.cs + + + + + + + + + + + + + + + + + + + + Designer + + + + + + + + + ParameterForm.cs + + + + + + + + + MainForm.cs + Designer + + + + + + {e73bb233-d88b-44a7-a98f-d71ee158381d} + Aga.Controls + + + {d4554296-094e-4cac-8eae-44eb250666c6} + OxyPlot.WindowsForms + + + {bcc43e58-e473-403e-a84d-63fedc723040} + OxyPlot + + + {B0397530-545A-471D-BB74-027AE456DF1A} + LibreHardwareMonitorLib + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Program.cs b/LibreHardwareMonitor/Program.cs similarity index 90% rename from Program.cs rename to LibreHardwareMonitor/Program.cs index ff63d0b..db6cac8 100644 --- a/Program.cs +++ b/LibreHardwareMonitor/Program.cs @@ -1,63 +1,63 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System; -using System.IO; -using System.Windows.Forms; -using OpenHardwareMonitor.GUI; - -namespace OpenHardwareMonitor -{ - public static class Program - { - [STAThread] - public static void Main() - { - if (!AllRequiredFilesAvailable()) - Environment.Exit(0); - - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - using (MainForm form = new MainForm()) - { - form.FormClosed += delegate - { - Application.Exit(); - }; - Application.Run(); - } - } - - private static bool IsFileAvailable(string fileName) - { - string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar; - if (!File.Exists(path + fileName)) - { - MessageBox.Show("The following file could not be found: " + fileName + - "\nPlease extract all files from the archive.", "Error", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return false; - } - return true; - } - - private static bool AllRequiredFilesAvailable() - { - if (!IsFileAvailable("Aga.Controls.dll")) - return false; - - if (!IsFileAvailable("OpenHardwareMonitorLib.dll")) - return false; - - if (!IsFileAvailable("OxyPlot.dll")) - return false; - - if (!IsFileAvailable("OxyPlot.WindowsForms.dll")) - return false; - - return true; - } - } -} +// Mozilla Public License 2.0 +// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// Copyright (C) LibreHardwareMonitor and Contributors +// All Rights Reserved + +using System; +using System.IO; +using System.Windows.Forms; +using LibreHardwareMonitor.UI; + +namespace LibreHardwareMonitor +{ + public static class Program + { + [STAThread] + public static void Main() + { + if (!AllRequiredFilesAvailable()) + Environment.Exit(0); + + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + using (MainForm form = new MainForm()) + { + form.FormClosed += delegate + { + Application.Exit(); + }; + Application.Run(); + } + } + + private static bool IsFileAvailable(string fileName) + { + string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar; + if (!File.Exists(path + fileName)) + { + MessageBox.Show("The following file could not be found: " + fileName + + "\nPlease extract all files from the archive.", "Error", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + return true; + } + + private static bool AllRequiredFilesAvailable() + { + if (!IsFileAvailable("Aga.Controls.dll")) + return false; + + if (!IsFileAvailable("LibreHardwareMonitorLib.dll")) + return false; + + if (!IsFileAvailable("OxyPlot.dll")) + return false; + + if (!IsFileAvailable("OxyPlot.WindowsForms.dll")) + return false; + + return true; + } + } +} diff --git a/Properties/AssemblyInfo.cs b/LibreHardwareMonitor/Properties/AssemblyInfo.cs similarity index 97% rename from Properties/AssemblyInfo.cs rename to LibreHardwareMonitor/Properties/AssemblyInfo.cs index ddb11a5..2df975d 100644 --- a/Properties/AssemblyInfo.cs +++ b/LibreHardwareMonitor/Properties/AssemblyInfo.cs @@ -1,18 +1,18 @@ -// Mozilla Public License 2.0 -// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -// Copyright (C) LibreHardwareMonitor and Contributors -// All Rights Reserved - -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle("Libre Hardware Monitor")] -[assembly: AssemblyDescription("Libre Hardware Monitor, a fork of Open Hardware Monitor.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Libre Hardware Monitor")] -[assembly: AssemblyCopyright("Copyright © Libre Hardware Monitor contributors")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] +// Mozilla Public License 2.0 +// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// Copyright (C) LibreHardwareMonitor and Contributors +// All Rights Reserved + +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Libre Hardware Monitor")] +[assembly: AssemblyDescription("Libre Hardware Monitor, a fork of Open Hardware Monitor.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Libre Hardware Monitor")] +[assembly: AssemblyCopyright("Copyright © Libre Hardware Monitor contributors")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] diff --git a/Resources/Web/css/custom-theme/images/ui-bg_flat_0_aaaaaa_40x100.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_flat_0_aaaaaa_40x100.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_flat_0_aaaaaa_40x100.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_flat_0_aaaaaa_40x100.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_glass_55_fbf9ee_1x400.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_55_fbf9ee_1x400.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_glass_55_fbf9ee_1x400.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_55_fbf9ee_1x400.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_glass_65_ffffff_1x400.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_65_ffffff_1x400.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_glass_65_ffffff_1x400.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_65_ffffff_1x400.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_glass_75_dadada_1x400.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_dadada_1x400.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_glass_75_dadada_1x400.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_dadada_1x400.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_glass_75_e6e6e6_1x400.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_e6e6e6_1x400.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_glass_75_e6e6e6_1x400.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_e6e6e6_1x400.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_glass_75_ffffff_1x400.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_ffffff_1x400.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_glass_75_ffffff_1x400.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_glass_75_ffffff_1x400.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_highlight-soft_75_cccccc_1x100.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_highlight-soft_75_cccccc_1x100.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_highlight-soft_75_cccccc_1x100.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_highlight-soft_75_cccccc_1x100.png diff --git a/Resources/Web/css/custom-theme/images/ui-bg_inset-soft_95_fef1ec_1x100.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_inset-soft_95_fef1ec_1x100.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-bg_inset-soft_95_fef1ec_1x100.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-bg_inset-soft_95_fef1ec_1x100.png diff --git a/Resources/Web/css/custom-theme/images/ui-icons_222222_256x240.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_222222_256x240.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-icons_222222_256x240.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_222222_256x240.png diff --git a/Resources/Web/css/custom-theme/images/ui-icons_2e83ff_256x240.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_2e83ff_256x240.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-icons_2e83ff_256x240.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_2e83ff_256x240.png diff --git a/Resources/Web/css/custom-theme/images/ui-icons_454545_256x240.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_454545_256x240.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-icons_454545_256x240.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_454545_256x240.png diff --git a/Resources/Web/css/custom-theme/images/ui-icons_888888_256x240.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_888888_256x240.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-icons_888888_256x240.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_888888_256x240.png diff --git a/Resources/Web/css/custom-theme/images/ui-icons_cd0a0a_256x240.png b/LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_cd0a0a_256x240.png similarity index 100% rename from Resources/Web/css/custom-theme/images/ui-icons_cd0a0a_256x240.png rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/images/ui-icons_cd0a0a_256x240.png diff --git a/Resources/Web/css/custom-theme/jquery-ui-1.8.16.custom.css b/LibreHardwareMonitor/Resources/Web/css/custom-theme/jquery-ui-1.8.16.custom.css similarity index 100% rename from Resources/Web/css/custom-theme/jquery-ui-1.8.16.custom.css rename to LibreHardwareMonitor/Resources/Web/css/custom-theme/jquery-ui-1.8.16.custom.css diff --git a/Resources/Web/css/jquery.treeTable.css b/LibreHardwareMonitor/Resources/Web/css/jquery.treeTable.css similarity index 100% rename from Resources/Web/css/jquery.treeTable.css rename to LibreHardwareMonitor/Resources/Web/css/jquery.treeTable.css diff --git a/Resources/Web/css/ohm_web.css b/LibreHardwareMonitor/Resources/Web/css/ohm_web.css similarity index 100% rename from Resources/Web/css/ohm_web.css rename to LibreHardwareMonitor/Resources/Web/css/ohm_web.css diff --git a/Resources/Web/images/toggle-collapse-dark.png b/LibreHardwareMonitor/Resources/Web/images/toggle-collapse-dark.png similarity index 100% rename from Resources/Web/images/toggle-collapse-dark.png rename to LibreHardwareMonitor/Resources/Web/images/toggle-collapse-dark.png diff --git a/Resources/Web/images/toggle-collapse-light.png b/LibreHardwareMonitor/Resources/Web/images/toggle-collapse-light.png similarity index 100% rename from Resources/Web/images/toggle-collapse-light.png rename to LibreHardwareMonitor/Resources/Web/images/toggle-collapse-light.png diff --git a/Resources/Web/images/toggle-expand-dark.png b/LibreHardwareMonitor/Resources/Web/images/toggle-expand-dark.png similarity index 100% rename from Resources/Web/images/toggle-expand-dark.png rename to LibreHardwareMonitor/Resources/Web/images/toggle-expand-dark.png diff --git a/Resources/Web/images/toggle-expand-light.png b/LibreHardwareMonitor/Resources/Web/images/toggle-expand-light.png similarity index 100% rename from Resources/Web/images/toggle-expand-light.png rename to LibreHardwareMonitor/Resources/Web/images/toggle-expand-light.png diff --git a/Resources/Web/images/transparent.png b/LibreHardwareMonitor/Resources/Web/images/transparent.png similarity index 100% rename from Resources/Web/images/transparent.png rename to LibreHardwareMonitor/Resources/Web/images/transparent.png diff --git a/Resources/Web/index.html b/LibreHardwareMonitor/Resources/Web/index.html similarity index 97% rename from Resources/Web/index.html rename to LibreHardwareMonitor/Resources/Web/index.html index cf2aecf..c4be82c 100644 --- a/Resources/Web/index.html +++ b/LibreHardwareMonitor/Resources/Web/index.html @@ -1,61 +1,61 @@ - - - - - Open Hardware Monitor - Web Version - - - - - - - - - - - - - - - - - - - - -
- - - - -  
     -
-
- -
- - - - - - - - - - -
SensorMinValueMax
-
- - + + + + + Open Hardware Monitor - Web Version + + + + + + + + + + + + + + + + + + + + +
+ + + + +  
     +
+
+ +
+ + + + + + + + + + +
SensorMinValueMax
+
+ + diff --git a/Resources/Web/js/jquery-1.7.2.js b/LibreHardwareMonitor/Resources/Web/js/jquery-1.7.2.js similarity index 100% rename from Resources/Web/js/jquery-1.7.2.js rename to LibreHardwareMonitor/Resources/Web/js/jquery-1.7.2.js diff --git a/Resources/Web/js/jquery-1.7.2.min.js b/LibreHardwareMonitor/Resources/Web/js/jquery-1.7.2.min.js similarity index 100% rename from Resources/Web/js/jquery-1.7.2.min.js rename to LibreHardwareMonitor/Resources/Web/js/jquery-1.7.2.min.js diff --git a/Resources/Web/js/jquery-ui-1.8.16.custom.min.js b/LibreHardwareMonitor/Resources/Web/js/jquery-ui-1.8.16.custom.min.js similarity index 100% rename from Resources/Web/js/jquery-ui-1.8.16.custom.min.js rename to LibreHardwareMonitor/Resources/Web/js/jquery-ui-1.8.16.custom.min.js diff --git a/Resources/Web/js/jquery.tmpl.js b/LibreHardwareMonitor/Resources/Web/js/jquery.tmpl.js similarity index 100% rename from Resources/Web/js/jquery.tmpl.js rename to LibreHardwareMonitor/Resources/Web/js/jquery.tmpl.js diff --git a/Resources/Web/js/jquery.tmpl.min.js b/LibreHardwareMonitor/Resources/Web/js/jquery.tmpl.min.js similarity index 100% rename from Resources/Web/js/jquery.tmpl.min.js rename to LibreHardwareMonitor/Resources/Web/js/jquery.tmpl.min.js diff --git a/Resources/Web/js/jquery.treeTable.min.js b/LibreHardwareMonitor/Resources/Web/js/jquery.treeTable.min.js similarity index 100% rename from Resources/Web/js/jquery.treeTable.min.js rename to LibreHardwareMonitor/Resources/Web/js/jquery.treeTable.min.js diff --git a/Resources/Web/js/knockout-2.1.0.js b/LibreHardwareMonitor/Resources/Web/js/knockout-2.1.0.js similarity index 100% rename from Resources/Web/js/knockout-2.1.0.js rename to LibreHardwareMonitor/Resources/Web/js/knockout-2.1.0.js diff --git a/Resources/Web/js/knockout-2.1.0.min.js b/LibreHardwareMonitor/Resources/Web/js/knockout-2.1.0.min.js similarity index 100% rename from Resources/Web/js/knockout-2.1.0.min.js rename to LibreHardwareMonitor/Resources/Web/js/knockout-2.1.0.min.js diff --git a/Resources/Web/js/knockout.mapping-latest.js b/LibreHardwareMonitor/Resources/Web/js/knockout.mapping-latest.js similarity index 97% rename from Resources/Web/js/knockout.mapping-latest.js rename to LibreHardwareMonitor/Resources/Web/js/knockout.mapping-latest.js index 3621fbf..64eb506 100644 --- a/Resources/Web/js/knockout.mapping-latest.js +++ b/LibreHardwareMonitor/Resources/Web/js/knockout.mapping-latest.js @@ -2,686 +2,686 @@ // (c) 2012 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/ // License: MIT (http://www.opensource.org/licenses/mit-license.php) -(function (factory) { - // Module systems magic dance. - - if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { - // CommonJS or Node: hard-coded dependency on "knockout" - factory(require("knockout"), exports); - } else if (typeof define === "function" && define["amd"]) { - // AMD anonymous module with hard-coded dependency on "knockout" - define(["knockout", "exports"], factory); - } else { - //