/// <summary>
 /// This method handles the OnComponentChanged event to display a notification.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="ce"></param>
 private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
 {
     if (ce.Component != null && ((IComponent)ce.Component).Site != null && ce.Member != null)
     {
         if ("LanguageKey".Equals(ce.Member.Name))
         {
             Control control = ce.Component as Control;
             if (control != null)
             {
                 LOG.InfoFormat("Changing LanguageKey for {0} to {1}", control.Name, ce.NewValue);
                 ApplyLanguage(control, (string)ce.NewValue);
             }
             else
             {
                 ToolStripItem item = ce.Component as ToolStripItem;
                 if (item != null)
                 {
                     LOG.InfoFormat("Changing LanguageKey for {0} to {1}", item.Name, ce.NewValue);
                     ApplyLanguage(item, (string)ce.NewValue);
                 }
                 else
                 {
                     LOG.InfoFormat("Not possible to changing LanguageKey for {0} to {1}", ce.Component.GetType(), ce.NewValue);
                 }
             }
         }
     }
 }
Beispiel #2
0
 /// <summary>
 /// Load the resources from the language file
 /// </summary>
 /// <param name="languageFile">File to load from</param>
 private static void LoadResources(LanguageFile languageFile)
 {
     LOG.InfoFormat("Loading language file {0}", languageFile.Filepath);
     try
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.Load(languageFile.Filepath);
         XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource");
         foreach (XmlNode resourceNode in resourceNodes)
         {
             string key = resourceNode.Attributes["name"].Value;
             if (!string.IsNullOrEmpty(languageFile.Prefix))
             {
                 key = languageFile.Prefix + "." + key;
             }
             string text = resourceNode.InnerText;
             if (!string.IsNullOrEmpty(text))
             {
                 text = text.Trim();
             }
             if (!resources.ContainsKey(key))
             {
                 resources.Add(key, text);
             }
             else
             {
                 resources[key] = text;
             }
         }
     }
     catch (Exception e)
     {
         LOG.Error("Could not load language file " + languageFile.Filepath, e);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Try to find the best match for the supplied IETF
        /// </summary>
        /// <param name="inputIETF"></param>
        /// <returns>IETF</returns>
        private static string FindBestIETFMatch(string inputIETF)
        {
            string returnIETF = inputIETF;

            if (string.IsNullOrEmpty(returnIETF))
            {
                returnIETF = DEFAULT_LANGUAGE;
            }
            returnIETF = ReformatIETF(returnIETF);
            if (!languageFiles.ContainsKey(returnIETF))
            {
                LOG.WarnFormat("Unknown language {0}, trying best match!", returnIETF);
                if (returnIETF.Length == 5)
                {
                    returnIETF = returnIETF.Substring(0, 2);
                }
                foreach (string availableIETF in languageFiles.Keys)
                {
                    if (availableIETF.StartsWith(returnIETF))
                    {
                        LOG.InfoFormat("Found language {0}, best match for {1}!", availableIETF, returnIETF);
                        returnIETF = availableIETF;
                        break;
                    }
                }
            }
            return(returnIETF);
        }
Beispiel #4
0
        /// <summary>
        /// Helper method to try to get an image in the specified format from the dataObject
        /// </summary>
        /// <param name="format">string with the format</param>
        /// <param name="dataObject">IDataObject</param>
        /// <returns>Image or null</returns>
        private static Image GetImageFormat(string format, IDataObject dataObject)
        {
            MemoryStream imageStream = GetFromDataObject(dataObject, format) as MemoryStream;

            if (isValidStream(imageStream))
            {
                try
                {
                    using (FileStream fs = new FileStream(@"C:\Localdata\test.png", FileMode.OpenOrCreate))
                    {
                        imageStream.WriteTo(fs);
                    }
                    imageStream.Seek(0, SeekOrigin.Begin);
                    using (Image tmpImage = Image.FromStream(imageStream, true, true))
                    {
                        if (tmpImage != null)
                        {
                            LOG.InfoFormat("Got image with clipboard format {0} from the clipboard.", format);
                            return(ImageHelper.Clone(tmpImage));
                        }
                    }
                }
                catch (Exception streamImageEx)
                {
                    LOG.Error(string.Format("Problem retrieving {0} from clipboard.", format), streamImageEx);
                }
            }
            return(null);
        }
Beispiel #5
0
        private void SessionFileTransferProgress(object sender, FileTransferProgressEventArgs e)
        {
            // Print transfer progress
            LOG.InfoFormat("\r{0} ({1:P0} CPS = {2})", e.FileName, e.FileProgress, e.CPS);

            // Remember a name of the last file reported
            m_lastFileName = e.FileName;
        }
Beispiel #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="webRequest"></param>
        /// <returns></returns>
        public static string GetResponseAsString(HttpWebRequest webRequest, bool alsoReturnContentOnError)
        {
            string          responseData = null;
            HttpWebResponse response     = null;
            bool            isHttpError  = false;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
                LOG.InfoFormat("Response status: {0}", response.StatusCode);
                isHttpError = (int)response.StatusCode >= 300;
                if (isHttpError)
                {
                    LOG.ErrorFormat("HTTP error {0}", response.StatusCode);
                }
                DebugHeaders(response);
                responseData = GetResponseAsString(response);
                if (isHttpError)
                {
                    LOG.ErrorFormat("HTTP response {0}", responseData);
                }
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                HttpStatusCode statusCode = HttpStatusCode.Unused;
                if (response != null)
                {
                    statusCode = response.StatusCode;
                    LOG.ErrorFormat("HTTP error {0}", statusCode);
                    string errorContent = GetResponseAsString(response);
                    if (alsoReturnContentOnError)
                    {
                        return(errorContent);
                    }
                    LOG.ErrorFormat("Content: {0}", errorContent);
                }
                LOG.Error("WebException: ", e);
                if (statusCode == HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedAccessException(e.Message);
                }
                throw;
            }
            finally
            {
                if (response != null)
                {
                    if (isHttpError)
                    {
                        LOG.ErrorFormat("HTTP error {0} with content: {1}", response.StatusCode, responseData);
                    }
                    response.Close();
                }
            }
            return(responseData);
        }
        /// <summary>
        /// Load a Greenshot surface
        /// </summary>
        /// <param name="fullPath"></param>
        /// <returns></returns>
        public static ISurface LoadGreenshotSurface(string fullPath, ISurface returnSurface)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                return(null);
            }
            Image fileImage = null;

            LOG.InfoFormat("Loading image from file {0}", fullPath);
            // Fixed lock problem Bug #3431881
            using (Stream surfaceFileStream = File.OpenRead(fullPath))
            {
                // And fixed problem that the bitmap stream is disposed... by Cloning the image
                // This also ensures the bitmap is correctly created

                // We create a copy of the bitmap, so everything else can be disposed
                surfaceFileStream.Position = 0;
                using (Image tmpImage = Image.FromStream(surfaceFileStream, true, true))
                {
                    LOG.DebugFormat("Loaded {0} with Size {1}x{2} and PixelFormat {3}", fullPath, tmpImage.Width, tmpImage.Height, tmpImage.PixelFormat);
                    fileImage = ImageHelper.Clone(tmpImage);
                }
                // Start at -14 read "GreenshotXX.YY" (XX=Major, YY=Minor)
                const int markerSize = 14;
                surfaceFileStream.Seek(-markerSize, SeekOrigin.End);
                string greenshotMarker;
                using (StreamReader streamReader = new StreamReader(surfaceFileStream))
                {
                    greenshotMarker = streamReader.ReadToEnd();
                    if (greenshotMarker == null || !greenshotMarker.StartsWith("Greenshot"))
                    {
                        throw new ArgumentException(string.Format("{0} is not a Greenshot file!", fullPath));
                    }
                    LOG.InfoFormat("Greenshot file format: {0}", greenshotMarker);
                    const int filesizeLocation = 8 + markerSize;
                    surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End);
                    long bytesWritten = 0;
                    using (BinaryReader reader = new BinaryReader(surfaceFileStream))
                    {
                        bytesWritten = reader.ReadInt64();
                        surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End);
                        returnSurface.LoadElementsFromStream(surfaceFileStream);
                    }
                }
            }
            if (fileImage != null)
            {
                returnSurface.Image = fileImage;
                LOG.InfoFormat("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", fullPath, fileImage.Width, fileImage.Height, fileImage.PixelFormat, fileImage.HorizontalResolution, fileImage.VerticalResolution);
            }
            return(returnSurface);
        }
Beispiel #8
0
 /// <summary>
 /// Default init
 /// </summary>
 public static void Init(string configFolder)
 {
     AssemblyProductAttribute[] assemblyProductAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false) as AssemblyProductAttribute[];
     if (assemblyProductAttributes.Length > 0)
     {
         string productName = assemblyProductAttributes[0].Product;
         LOG.InfoFormat("Using ProductName {0}", productName);
         Init(productName, "GreenshotImageEditor", configFolder);
     }
     else
     {
         throw new InvalidOperationException("Assembly ProductName not set.");
     }
 }
Beispiel #9
0
        public override void OnInit()
        {
            CSVOrders csvOrders = CSVOrders.getInstance();

            fixedDollarRiskProfile = new FixedDollarRiskProfile(this, 150, 10);

            foreach (var csvOrder in csvOrders)
            {
                LOG.InfoFormat("{0} on:{1} at:{2} stop:{3} tp1:{4} tp2:{5}",
                               csvOrder.TradeOperation.ToString(),
                               csvOrder.Pair,
                               csvOrder.Entry,
                               csvOrder.Stop,
                               csvOrder.TakeProfit1,
                               csvOrder.TakeProfit2
                               );

                bool tradeExists = false;
                for (int i = 0; i < this.OrdersTotal(); i++)
                {
                    if (OrderSelect(i, (int)SELECTION_TYPE.SELECT_BY_POS, (int)SELECTION_POOL.MODE_TRADES) && OrderMagicNumber() == magicnumber && csvOrder.Pair == OrderSymbol())
                    {
                        if ((OrderType() == (int)TRADE_OPERATION.OP_SELL || OrderType() == (int)TRADE_OPERATION.OP_SELLLIMIT) &&
                            csvOrder.TradeOperation == TRADE_OPERATION.OP_SELLLIMIT)
                        {
                            tradeExists = true;
                            break;
                        }
                        if ((OrderType() == (int)TRADE_OPERATION.OP_BUY || OrderType() == (int)TRADE_OPERATION.OP_BUYLIMIT) &&
                            csvOrder.TradeOperation == TRADE_OPERATION.OP_BUYLIMIT)
                        {
                            tradeExists = true;
                            break;
                        }
                    }
                }

                if (!tradeExists)
                {
                    // Place the trade
                    LOG.InfoFormat("Placing trade on {0}", csvOrder.Pair);
                    executeTrade(csvOrder, true);
                    executeTrade(csvOrder, false);
                }
            }
        }
Beispiel #10
0
 /// <summary>
 /// Internal method to add a path to the paths that will be scanned for language files!
 /// </summary>
 /// <param name="path"></param>
 /// <returns>true if the path exists and is added</returns>
 private static bool AddPath(string path)
 {
     if (!languagePaths.Contains(path))
     {
         if (Directory.Exists(path))
         {
             LOG.DebugFormat("Adding language path {0}", path);
             languagePaths.Add(path);
             return(true);
         }
         else
         {
             LOG.InfoFormat("Not adding non existing language path {0}", path);
         }
     }
     return(false);
 }
Beispiel #11
0
        /// <summary>
        /// Read the ini file into the Dictionary
        /// </summary>
        /// <param name="iniLocation">Path & Filename of ini file</param>
        private static Dictionary <string, Dictionary <string, string> > Read(string iniLocation)
        {
            if (!File.Exists(iniLocation))
            {
                LOG.Info("Can't find file: " + iniLocation);
                return(null);
            }
            LOG.InfoFormat("Loading ini-file: {0}", iniLocation);
            //LOG.Info("Reading ini-properties from file: " + iniLocation);
            Dictionary <string, Dictionary <string, string> > newSections = IniReader.read(iniLocation, Encoding.UTF8);

            // Merge the newly loaded properties to the already available
            foreach (string section in newSections.Keys)
            {
                Dictionary <string, string> newProperties = newSections[section];
                if (!sections.ContainsKey(section))
                {
                    // This section is not yet loaded, simply add the complete section
                    sections.Add(section, newProperties);
                }
                else
                {
                    // Overwrite or add every property from the newly loaded section to the available one
                    Dictionary <string, string> currentProperties = sections[section];
                    foreach (string propertyName in newProperties.Keys)
                    {
                        string propertyValue = newProperties[propertyName];
                        if (currentProperties.ContainsKey(propertyName))
                        {
                            // Override current value as we are loading in a certain order which insures the default, current and fixed
                            currentProperties[propertyName] = propertyValue;
                        }
                        else
                        {
                            // Add "new" value
                            currentProperties.Add(propertyName, propertyValue);
                        }
                    }
                }
            }
            return(newSections);
        }
Beispiel #12
0
        /// <summary>
        /// Get an Image from the IDataObject, don't check for FileDrop
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>Image or null</returns>
        private static Image GetImage(IDataObject dataObject)
        {
            Image returnImage = null;

            if (dataObject != null)
            {
                IList <string> formats = GetFormats(dataObject);
                string[]       retrieveFormats;

                // Found a weird bug, where PNG's from Outlook 2010 are clipped
                // So I build some special logik to get the best format:
                if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
                {
                    // Outlook ??
                    LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
                    retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF };
                }
                else
                {
                    retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF };
                }
                foreach (string currentFormat in retrieveFormats)
                {
                    if (formats.Contains(currentFormat))
                    {
                        LOG.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
                        returnImage = GetImageForFormat(currentFormat, dataObject);
                    }
                    else
                    {
                        LOG.DebugFormat("Couldn't find format {0}.", currentFormat);
                    }
                    if (returnImage != null)
                    {
                        ImageHelper.Orientate(returnImage);
                        return(returnImage);
                    }
                }
            }
            return(null);
        }
 /// <summary>
 /// Dump the Type-Information for the Type to the log, this uses reflection
 /// </summary>
 /// <param name="type">Type to inspect</param>
 public static void DumpTypeInfo(Type type)
 {
     LOG.InfoFormat("Type information for Type with name: {0}", type.Name);
     try
     {
         foreach (MemberInfo memberInfo in type.GetMembers())
         {
             LOG.InfoFormat("Member: {0};", memberInfo.ToString());
         }
     }
     catch (Exception memberException)
     {
         LOG.Error(memberException);
     }
     try
     {
         foreach (PropertyInfo propertyInfo in type.GetProperties())
         {
             LOG.InfoFormat("Property: {0};", propertyInfo.ToString());
         }
     }
     catch (Exception propertyException)
     {
         LOG.Error(propertyException);
     }
     try
     {
         foreach (FieldInfo fieldInfo in type.GetFields())
         {
             LOG.InfoFormat("Field: {0};", fieldInfo.ToString());
         }
     }
     catch (Exception fieldException)
     {
         LOG.Error(fieldException);
     }
     LOG.InfoFormat("Type information end.");
 }
Beispiel #14
0
        /// <summary>
        /// Get all images (multiple if filenames are available) from the dataObject
        /// Returned images must be disposed by the calling code!
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>IEnumerable<Image></returns>
        public static IEnumerable <Image> GetImages(IDataObject dataObject)
        {
            // Get single image, this takes the "best" match
            Image singleImage = GetImage(dataObject);

            if (singleImage != null)
            {
                LOG.InfoFormat("Got image from clipboard with size {0} and format {1}", singleImage.Size, singleImage.PixelFormat);
                yield return(singleImage);
            }
            else
            {
                // check if files are supplied
                List <string> imageFiles = GetImageFilenames(dataObject);
                if (imageFiles != null)
                {
                    foreach (string imageFile in imageFiles)
                    {
                        Image returnImage = null;
                        try
                        {
                            returnImage = ImageHelper.LoadImage(imageFile);
                        }
                        catch (Exception streamImageEx)
                        {
                            LOG.Error("Problem retrieving Image from clipboard.", streamImageEx);
                        }
                        if (returnImage != null)
                        {
                            LOG.InfoFormat("Got image from clipboard with size {0} and format {1}", returnImage.Size, returnImage.PixelFormat);
                            yield return(returnImage);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets a COM object and returns the transparent proxy which intercepts all calls to the object
        /// </summary>
        /// <param name="type">Interface which defines the method and properties to intercept</param>
        /// <returns>Transparent proxy to the real proxy for the object</returns>
        /// <remarks>The <paramref name="type"/> must be an interface decorated with the <see cref="ComProgIdAttribute"/>attribute.</remarks>
        public static T GetInstance <T>()
        {
            Type type = typeof(T);

            if (null == type)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsInterface)
            {
                throw new ArgumentException("The specified type must be an interface.", "type");
            }

            ComProgIdAttribute progIDAttribute = ComProgIdAttribute.GetAttribute(type);

            if (null == progIDAttribute || null == progIDAttribute.Value || 0 == progIDAttribute.Value.Length)
            {
                throw new ArgumentException("The specified type must define a ComProgId attribute.", "type");
            }
            string progId = progIDAttribute.Value;

            object comObject = null;

            // Convert from clsid to Prog ID, if needed
            if (progId.StartsWith("clsid:"))
            {
                Guid guid   = new Guid(progId.Substring(6));
                int  result = ProgIDFromCLSID(ref guid, out progId);
                if (result != 0)
                {
                    // Restore progId, as it's overwritten
                    progId = progIDAttribute.Value;

                    try
                    {
                        GetActiveObject(ref guid, IntPtr.Zero, out comObject);
                    }
                    catch (Exception)
                    {
                        LOG.WarnFormat("Error {0} getting instance for class id {1}", result, progIDAttribute.Value);
                    }
                    if (comObject == null)
                    {
                        LOG.WarnFormat("Error {0} getting progId {1}", result, progIDAttribute.Value);
                    }
                }
                else
                {
                    LOG.InfoFormat("Mapped {0} to progId {1}", progIDAttribute.Value, progId);
                }
            }

            if (comObject == null)
            {
                try
                {
                    comObject = Marshal.GetActiveObject(progId);
                }
                catch (COMException comE)
                {
                    if (comE.ErrorCode == MK_E_UNAVAILABLE)
                    {
                        LOG.DebugFormat("No current instance of {0} object available.", progId);
                    }
                    else if (comE.ErrorCode == CO_E_CLASSSTRING)
                    {
                        LOG.WarnFormat("Unknown progId {0}", progId);
                    }
                    else
                    {
                        LOG.Warn("Error getting active object for " + progIDAttribute.Value, comE);
                    }
                }
                catch (Exception e)
                {
                    LOG.Warn("Error getting active object for " + progIDAttribute.Value, e);
                }
            }

            if (comObject != null)
            {
                if (comObject is IDispatch)
                {
                    COMWrapper wrapper = new COMWrapper(comObject, type, progIDAttribute.Value);
                    return((T)wrapper.GetTransparentProxy());
                }
                else
                {
                    return((T)comObject);
                }
            }
            return(default(T));
        }
Beispiel #16
0
        /// <summary>
        /// the DIB readed should solve the issue reported here: https://sourceforge.net/projects/greenshot/forums/forum/676083/topic/6354353/index/page/1
        /// </summary>
        /// <returns>Image</returns>
        private static Image GetDIBImage(IDataObject dataObejct)
        {
            try
            {
                // If the EnableSpecialDIBClipboardReader flag in the config is set, use the code from:
                // http://www.thomaslevesque.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/
                // to read the DeviceIndependentBitmap from the clipboard, this might fix bug 3576125
                if (config.EnableSpecialDIBClipboardReader)
                {
                    MemoryStream dibStream = GetFromDataObject(dataObejct, DataFormats.Dib) as MemoryStream;
                    if (isValidStream(dibStream))
                    {
                        LOG.Info("Found valid DIB stream, trying to process it.");
                        byte[] dibBuffer = new byte[dibStream.Length];
                        dibStream.Read(dibBuffer, 0, dibBuffer.Length);
                        BitmapInfoHeader infoHeader = BinaryStructHelper.FromByteArray <BitmapInfoHeader>(dibBuffer);
                        // Only use this code, when the biCommpression != 0 (BI_RGB)
                        if (infoHeader.biCompression != 0)
                        {
                            LOG.InfoFormat("Using special DIB format reader for biCompression {0}", infoHeader.biCompression);
                            int  fileHeaderSize = Marshal.SizeOf(typeof(BitmapFileHeader));
                            uint infoHeaderSize = infoHeader.biSize;
                            int  fileSize       = (int)(fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage);

                            BitmapFileHeader fileHeader = new BitmapFileHeader();
                            fileHeader.bfType      = BitmapFileHeader.BM;
                            fileHeader.bfSize      = fileSize;
                            fileHeader.bfReserved1 = 0;
                            fileHeader.bfReserved2 = 0;
                            fileHeader.bfOffBits   = (int)(fileHeaderSize + infoHeaderSize + infoHeader.biClrUsed * 4);

                            byte[] fileHeaderBytes = BinaryStructHelper.ToByteArray <BitmapFileHeader>(fileHeader);

                            using (MemoryStream bitmapStream = new MemoryStream())
                            {
                                bitmapStream.Write(fileHeaderBytes, 0, fileHeaderSize);
                                bitmapStream.Write(dibBuffer, 0, dibBuffer.Length);
                                bitmapStream.Seek(0, SeekOrigin.Begin);
                                using (Image tmpImage = Image.FromStream(bitmapStream))
                                {
                                    if (tmpImage != null)
                                    {
                                        return(ImageHelper.Clone(tmpImage));
                                    }
                                }
                            }
                        }
                        else
                        {
                            LOG.InfoFormat("Skipping special DIB format reader for biCompression {0}", infoHeader.biCompression);
                        }
                    }
                }
                else
                {
                    LOG.Info("Skipping special DIB format reader as it's disabled in the configuration.");
                }
            }
            catch (Exception dibEx)
            {
                LOG.Error("Problem retrieving DIB from clipboard.", dibEx);
            }
            return(null);
        }
Beispiel #17
0
        /// <summary>
        /// Get an Image from the IDataObject, don't check for FileDrop
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>Image or null</returns>
        private static Image GetImage(IDataObject dataObject)
        {
            Image returnImage = null;

            if (dataObject != null)
            {
                IList <string> formats = GetFormats(dataObject);
                string[]       retrieveFormats;

                // Found a weird bug, where PNG's from Outlook 2010 are clipped
                // So I build some special logik to get the best format:
                if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
                {
                    // Outlook ??
                    LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
                    retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF };
                }
                else
                {
                    retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP_PLACEHOLDER, FORMAT_FILECONTENTS, FORMAT_GIF };
                }
                foreach (string currentFormat in retrieveFormats)
                {
                    if (FORMAT_BITMAP_PLACEHOLDER.Equals(currentFormat))
                    {
                        LOG.Info("Using default .NET Clipboard.GetImage()");
                        try
                        {
                            returnImage = Clipboard.GetImage();
                            if (returnImage != null)
                            {
                                return(returnImage);
                            }
                            else
                            {
                                LOG.Info("Clipboard.GetImage() didn't return an image.");
                            }
                        }
                        catch (Exception ex)
                        {
                            LOG.Error("Problem retrieving Image via Clipboard.GetImage(): ", ex);
                        }
                    }
                    else if (formats.Contains(currentFormat))
                    {
                        LOG.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
                        if (currentFormat == DataFormats.Dib)
                        {
                            returnImage = GetDIBImage(dataObject);
                        }
                        else
                        {
                            returnImage = GetImageFormat(currentFormat, dataObject);
                        }
                        if (returnImage != null)
                        {
                            return(returnImage);
                        }
                    }
                    else
                    {
                        LOG.DebugFormat("Couldn't find format {0}.", currentFormat);
                    }
                }
            }
            return(null);
        }
Beispiel #18
0
        /// <summary>
        /// Helper method to try to get an image in the specified format from the dataObject
        /// the DIB readed should solve the issue reported here: https://sourceforge.net/projects/greenshot/forums/forum/676083/topic/6354353/index/page/1
        /// It also supports Format17/DibV5, by using the following information: http://stackoverflow.com/a/14335591
        /// </summary>
        /// <param name="format">string with the format</param>
        /// <param name="dataObject">IDataObject</param>
        /// <returns>Image or null</returns>
        private static Image GetImageForFormat(string format, IDataObject dataObject)
        {
            object       clipboardObject = GetFromDataObject(dataObject, format);
            MemoryStream imageStream     = clipboardObject as MemoryStream;

            if (!isValidStream(imageStream))
            {
                // TODO: add "HTML Format" support here...
                return(clipboardObject as Image);
            }
            else
            {
                if (config.EnableSpecialDIBClipboardReader)
                {
                    if (format == FORMAT_17 || format == DataFormats.Dib)
                    {
                        LOG.Info("Found DIB stream, trying to process it.");
                        try
                        {
                            byte[] dibBuffer = new byte[imageStream.Length];
                            imageStream.Read(dibBuffer, 0, dibBuffer.Length);
                            BITMAPINFOHEADER infoHeader = BinaryStructHelper.FromByteArray <BITMAPINFOHEADER>(dibBuffer);
                            if (!infoHeader.IsDibV5)
                            {
                                LOG.InfoFormat("Using special DIB <v5 format reader with biCompression {0}", infoHeader.biCompression);
                                int  fileHeaderSize = Marshal.SizeOf(typeof(BITMAPFILEHEADER));
                                uint infoHeaderSize = infoHeader.biSize;
                                int  fileSize       = (int)(fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage);

                                BITMAPFILEHEADER fileHeader = new BITMAPFILEHEADER();
                                fileHeader.bfType      = BITMAPFILEHEADER.BM;
                                fileHeader.bfSize      = fileSize;
                                fileHeader.bfReserved1 = 0;
                                fileHeader.bfReserved2 = 0;
                                fileHeader.bfOffBits   = (int)(fileHeaderSize + infoHeaderSize + infoHeader.biClrUsed * 4);

                                byte[] fileHeaderBytes = BinaryStructHelper.ToByteArray <BITMAPFILEHEADER>(fileHeader);

                                using (MemoryStream bitmapStream = new MemoryStream())
                                {
                                    bitmapStream.Write(fileHeaderBytes, 0, fileHeaderSize);
                                    bitmapStream.Write(dibBuffer, 0, dibBuffer.Length);
                                    bitmapStream.Seek(0, SeekOrigin.Begin);
                                    using (Image tmpImage = Image.FromStream(bitmapStream))
                                    {
                                        if (tmpImage != null)
                                        {
                                            return(ImageHelper.Clone(tmpImage));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                LOG.Info("Using special DIBV5 / Format17 format reader");
                                // CF_DIBV5
                                IntPtr gcHandle = IntPtr.Zero;
                                try
                                {
                                    GCHandle handle = GCHandle.Alloc(dibBuffer, GCHandleType.Pinned);
                                    gcHandle = GCHandle.ToIntPtr(handle);
                                    return(new Bitmap(infoHeader.biWidth, infoHeader.biHeight, -(int)(infoHeader.biSizeImage / infoHeader.biHeight),
                                                      infoHeader.biBitCount == 32 ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb,
                                                      new IntPtr(handle.AddrOfPinnedObject().ToInt32() + infoHeader.OffsetToPixels + (infoHeader.biHeight - 1) * (int)(infoHeader.biSizeImage / infoHeader.biHeight))));
                                }
                                catch (Exception ex)
                                {
                                    LOG.Error("Problem retrieving Format17 from clipboard.", ex);
                                }
                                finally
                                {
                                    if (gcHandle == IntPtr.Zero)
                                    {
                                        GCHandle.FromIntPtr(gcHandle).Free();
                                    }
                                }
                            }
                        }
                        catch (Exception dibEx)
                        {
                            LOG.Error("Problem retrieving DIB from clipboard.", dibEx);
                        }
                    }
                }
                else
                {
                    LOG.Info("Skipping special DIB format reader as it's disabled in the configuration.");
                }
                try
                {
                    imageStream.Seek(0, SeekOrigin.Begin);
                    using (Image tmpImage = Image.FromStream(imageStream, true, true))
                    {
                        if (tmpImage != null)
                        {
                            LOG.InfoFormat("Got image with clipboard format {0} from the clipboard.", format);
                            return(ImageHelper.Clone(tmpImage));
                        }
                    }
                }
                catch (Exception streamImageEx)
                {
                    LOG.Error(string.Format("Problem retrieving {0} from clipboard.", format), streamImageEx);
                }
            }
            return(null);
        }
Beispiel #19
0
        /// <summary>
        /// Scan the files in all directories
        /// </summary>
        private static void ScanFiles()
        {
            languageFiles.Clear();
            helpFiles.Clear();
            foreach (string languagePath in languagePaths)
            {
                if (!Directory.Exists(languagePath))
                {
                    LOG.InfoFormat("Skipping non existing language path {0}", languagePath);
                    continue;
                }
                LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN);
                try
                {
                    foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        //LOG.DebugFormat("Found language file: {0}", languageFilepath);
                        LanguageFile languageFile = LoadFileInfo(languageFilepath);
                        if (languageFile == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(languageFile.Ietf))
                        {
                            LOG.WarnFormat("Fixing missing ietf in language-file {0}", languageFilepath);
                            string languageFilename = Path.GetFileName(languageFilepath);
                            if (IETF_REGEXP.IsMatch(languageFilename))
                            {
                                string replacementIETF = IETF_REGEXP.Replace(languageFilename, "$1");
                                languageFile.Ietf = ReformatIETF(replacementIETF);
                                LOG.InfoFormat("Fixed IETF to {0}", languageFile.Ietf);
                            }
                            else
                            {
                                LOG.ErrorFormat("Missing ietf , no recover possible... skipping language-file {0}!", languageFilepath);
                                continue;
                            }
                        }

                        // Check if we can display the file
                        if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup))
                        {
                            LOG.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath);
                            continue;
                        }

                        // build prefix, based on the filename, but only if it's not set in the file itself.
                        if (string.IsNullOrEmpty(languageFile.Prefix))
                        {
                            string languageFilename = Path.GetFileNameWithoutExtension(languageFilepath);
                            if (PREFIX_REGEXP.IsMatch(languageFilename))
                            {
                                languageFile.Prefix = PREFIX_REGEXP.Replace(languageFilename, "$1");
                                if (!string.IsNullOrEmpty(languageFile.Prefix))
                                {
                                    languageFile.Prefix = languageFile.Prefix.Replace("plugin", "").ToLower();
                                }
                            }
                        }
                        List <LanguageFile> currentFiles = null;
                        if (languageFiles.ContainsKey(languageFile.Ietf))
                        {
                            currentFiles = languageFiles[languageFile.Ietf];
                            bool needToAdd = true;
                            List <LanguageFile> deleteList = new List <LanguageFile>();
                            foreach (LanguageFile compareWithLangfile in currentFiles)
                            {
                                if ((languageFile.Prefix == null && compareWithLangfile.Prefix == null) || (languageFile.Prefix != null && languageFile.Prefix.Equals(compareWithLangfile.Prefix)))
                                {
                                    if (compareWithLangfile.Version > languageFile.Version)
                                    {
                                        LOG.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        needToAdd = false;
                                        break;
                                    }
                                    else
                                    {
                                        LOG.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version);
                                        deleteList.Add(compareWithLangfile);
                                    }
                                }
                            }
                            if (needToAdd)
                            {
                                foreach (LanguageFile deleteFile in deleteList)
                                {
                                    currentFiles.Remove(deleteFile);
                                }
                                LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                                currentFiles.Add(languageFile);
                            }
                        }
                        else
                        {
                            currentFiles = new List <LanguageFile>();
                            currentFiles.Add(languageFile);
                            languageFiles.Add(languageFile.Ietf, currentFiles);
                            LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }

                // Now find the help files
                LOG.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HELP_FILENAME_PATTERN);
                try
                {
                    foreach (string helpFilepath in Directory.GetFiles(languagePath, HELP_FILENAME_PATTERN, SearchOption.AllDirectories))
                    {
                        LOG.DebugFormat("Found help file: {0}", helpFilepath);
                        string helpFilename = Path.GetFileName(helpFilepath);
                        string ietf         = ReformatIETF(helpFilename.Replace(".html", "").Replace("help-", ""));
                        if (!helpFiles.ContainsKey(ietf))
                        {
                            helpFiles.Add(ietf, helpFilepath);
                        }
                        else
                        {
                            LOG.WarnFormat("skipping help file {0}, already a file with the same IETF {1} found!", helpFilepath, ietf);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    LOG.InfoFormat("Non existing language directory: {0}", languagePath);
                }
                catch (Exception e)
                {
                    LOG.Error("Error trying for read directory " + languagePath, e);
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// This method will set the ini value to the supplied value or use the default if non supplied
        /// </summary>
        /// <param name="propertyValue"></param>
        public void UseValueOrDefault(string propertyValue)
        {
            Type   valueType              = ValueType;
            string propertyName           = attributes.Name;
            string defaultValue           = attributes.DefaultValue;
            bool   defaultUsed            = false;
            object defaultValueFromConfig = containingIniSection.GetDefault(propertyName);

            if (string.IsNullOrEmpty(propertyValue))
            {
                if (defaultValue != null && defaultValue.Trim().Length != 0)
                {
                    propertyValue = defaultValue;
                    defaultUsed   = true;
                }
                else if (defaultValueFromConfig != null)
                {
                    LOG.DebugFormat("Default for Property {0} implemented!", propertyName);
                }
                else
                {
                    if (attributes.ExcludeIfNull)
                    {
                        Value = null;
                        return;
                    }
                    LOG.DebugFormat("Property {0} has no value or default value!", propertyName);
                }
            }
            // Now set the value
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                // Logic for Dictionary<,>
                Type type1 = valueType.GetGenericArguments()[0];
                Type type2 = valueType.GetGenericArguments()[1];
                //LOG.Info(String.Format("Found Dictionary<{0},{1}>", type1.Name, type2.Name));
                object     dictionary    = Activator.CreateInstance(valueType);
                MethodInfo addMethodInfo = valueType.GetMethod("Add");
                bool       addedElements = false;
                Dictionary <string, string> properties = IniConfig.PropertiesForSection(containingIniSection);
                foreach (string key in properties.Keys)
                {
                    if (key != null && key.StartsWith(propertyName + "."))
                    {
                        // What "key" do we need to store it under?
                        string subPropertyName = key.Substring(propertyName.Length + 1);
                        string stringValue     = properties[key];
                        object newValue1       = null;
                        object newValue2       = null;
                        try
                        {
                            newValue1 = ConvertStringToValueType(type1, subPropertyName, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + subPropertyName + " to type " + type1.FullName, e);
                        }
                        try
                        {
                            newValue2 = ConvertStringToValueType(type2, stringValue, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e);
                        }
                        addMethodInfo.Invoke(dictionary, new[] { newValue1, newValue2 });
                        addedElements = true;
                    }
                }
                // No need to return something that isn't filled!
                if (addedElements)
                {
                    Value = dictionary;
                    return;
                }
                else if (defaultValueFromConfig != null)
                {
                    Value = defaultValueFromConfig;
                    return;
                }
            }
            else if (!string.IsNullOrEmpty(propertyValue))
            {
                if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                {
                    // We are dealing with a generic type that is nullable
                    valueType = Nullable.GetUnderlyingType(valueType);
                }
                object newValue = null;
                try
                {
                    newValue = ConvertStringToValueType(valueType, propertyValue, attributes.Separator);
                }
                catch (Exception ex1)
                {
                    newValue = null;
                    if (!defaultUsed)
                    {
                        try
                        {
                            LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName);
                            newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator);
                            ContainingIniSection.IsDirty = true;
                            LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName);
                        }
                        catch (Exception ex2)
                        {
                            LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2);
                        }
                    }
                    else
                    {
                        LOG.Warn("Problem converting " + propertyValue + " to type " + valueType.FullName, ex1);
                    }
                }
                Value = newValue;
                return;
            }

            // If nothing is set, we can use the default value from the config (if we habe one)
            if (defaultValueFromConfig != null)
            {
                Value = defaultValueFromConfig;
                return;
            }
            if (ValueType != typeof(string))
            {
                try
                {
                    Value = Activator.CreateInstance(ValueType);
                }
                catch (Exception)
                {
                    LOG.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, attributes.Name);
                    Value = default(ValueType);
                }
            }
            else
            {
                Value = default(ValueType);
            }
        }
        /// <summary>
        /// Create an image from a surface with the settings from the output settings applied
        /// </summary>
        /// <param name="surface"></param>
        /// <param name="outputSettings"></param>
        /// <param name="imageToSave"></param>
        /// <returns>true if the image must be disposed</returns>
        public static bool CreateImageFromSurface(ISurface surface, SurfaceOutputSettings outputSettings, out Image imageToSave)
        {
            bool        disposeImage = false;
            ImageFormat imageFormat  = null;

            switch (outputSettings.Format)
            {
            case OutputFormat.bmp:
                imageFormat = ImageFormat.Bmp;
                break;

            case OutputFormat.gif:
                imageFormat = ImageFormat.Gif;
                break;

            case OutputFormat.jpg:
                imageFormat = ImageFormat.Jpeg;
                break;

            case OutputFormat.tiff:
                imageFormat = ImageFormat.Tiff;
                break;

            case OutputFormat.greenshot:
            case OutputFormat.png:
            default:
                imageFormat = ImageFormat.Png;
                break;
            }

            if (outputSettings.Format == OutputFormat.greenshot || outputSettings.SaveBackgroundOnly)
            {
                // We save the image of the surface, this should not be disposed
                imageToSave = surface.Image;
            }
            else
            {
                // We create the export image of the surface to save
                imageToSave  = surface.GetImageForExport();
                disposeImage = true;
            }

            // The following block of modifications should be skipped when saving the greenshot format, no effects or otherwise!
            if (outputSettings.Format != OutputFormat.greenshot)
            {
                Image tmpImage;
                if (outputSettings.Effects != null && outputSettings.Effects.Count > 0)
                {
                    // apply effects, if there are any
                    Point ignoreOffset;
                    tmpImage = ImageHelper.ApplyEffects((Bitmap)imageToSave, outputSettings.Effects, out ignoreOffset);
                    if (tmpImage != null)
                    {
                        if (disposeImage)
                        {
                            imageToSave.Dispose();
                        }
                        imageToSave  = tmpImage;
                        disposeImage = true;
                    }
                }

                // check for color reduction, forced or automatically, only when the DisableReduceColors is false
                if (!outputSettings.DisableReduceColors && (conf.OutputFileAutoReduceColors || outputSettings.ReduceColors))
                {
                    bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat);
                    if (outputSettings.ReduceColors || (!isAlpha && conf.OutputFileAutoReduceColors))
                    {
                        using (WuQuantizer quantizer = new WuQuantizer((Bitmap)imageToSave))
                        {
                            int colorCount = quantizer.GetColorCount();
                            LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
                            if (outputSettings.ReduceColors || colorCount < 256)
                            {
                                try
                                {
                                    LOG.Info("Reducing colors on bitmap to 256.");
                                    tmpImage = quantizer.GetQuantizedImage(256);
                                    if (disposeImage)
                                    {
                                        imageToSave.Dispose();
                                    }
                                    imageToSave = tmpImage;
                                    // Make sure the "new" image is disposed
                                    disposeImage = true;
                                }
                                catch (Exception e)
                                {
                                    LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
                                }
                            }
                        }
                    }
                    else if (isAlpha && !outputSettings.ReduceColors)
                    {
                        LOG.Info("Skipping 'optional' color reduction as the image has alpha");
                    }
                }
            }
            return(disposeImage);
        }