private void SyncChildrenToRibbonGroupItems() { // Remove all child elements Clear(); ItemToView regenerate = new ItemToView(); // Add a view element for each group item foreach (IRibbonGroupItem item in _ribbonTriple.Items) { ViewBase itemView; // Do we already have a view for this item definition if (_itemToView.ContainsKey(item)) { itemView = _itemToView[item]; // Remove from lookup as we do not want to delete this view _itemToView.Remove(item); } else { // Ask the item definition to return an appropriate view itemView = item.CreateView(_ribbon, _needPaint); } // Update the visible state of the item itemView.Visible = _ribbon.InDesignHelperMode || item.Visible; // We need to keep this association regenerate.Add(item, itemView); Add(itemView); } // When in design time help mode and there is room for another item if (_ribbon.InDesignHelperMode && (Count < 3)) { // Create the design time 'Add Tab' first time it is needed if (_viewAddItem == null) { _viewAddItem = new ViewDrawRibbonDesignGroupTriple(_ribbon, _ribbonTriple, _currentSize, _needPaint); } // Always add at end of the list of items Add(_viewAddItem); } // Dispose of all the items no longer needed foreach (ViewBase view in _itemToView.Values) { view.Dispose(); } // Use the latest hashtable _itemToView = regenerate; }
/// <summary> /// Initialize a new instance of the ViewLayoutRibbonGroupCluster class. /// </summary> /// <param name="ribbon">Owning ribbon control instance.</param> /// <param name="ribbonCluster">Reference to cluster definition.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewLayoutRibbonGroupCluster(KryptonRibbon ribbon, KryptonRibbonGroupCluster ribbonCluster, NeedPaintHandler needPaint) { Debug.Assert(ribbon != null); Debug.Assert(ribbonCluster != null); Debug.Assert(needPaint != null); // Cache references _ribbon = ribbon; _ribbonCluster = ribbonCluster; _needPaint = needPaint; _currentSize = GroupItemSize.Medium; // Associate the component with this view element for design time selection Component = _ribbonCluster; // Create the start and end separators _startSep = new ViewDrawRibbonGroupClusterSeparator(_ribbon, true); _endSep = new ViewDrawRibbonGroupClusterSeparator(_ribbon, false); _startSepVisible = false; _endSepVisible = false; // Create palette used to supply a width to a border edge view PaletteBorderEdgeRedirect borderEdgeRedirect = new PaletteBorderEdgeRedirect(_ribbon.StateCommon.RibbonGroupClusterButton.Border, needPaint); _paletteBorderEdge = new PaletteBorderEdge(borderEdgeRedirect, needPaint); _lastShape = PaletteRibbonShape.Office2007; // Use hashtable to store relationships _itemToView = new ItemToView(); _viewToEdge = new ViewToEdge(); _viewToSizeMedium = new ViewToSize(); _viewToSizeSmall = new ViewToSize(); // Hook into changes in the ribbon cluster definition _ribbonCluster.PropertyChanged += new PropertyChangedEventHandler(OnClusterPropertyChanged); _ribbonCluster.ClusterView = this; // At design time we want to track the mouse and show feedback if (_ribbon.InDesignMode) { ViewHightlightController controller = new ViewHightlightController(this, needPaint); controller.ContextClick += new MouseEventHandler(OnContextClick); MouseController = controller; } }
/// <summary> /// Initialize a new instance of the ViewLayoutRibbonGroupLines class. /// </summary> /// <param name="ribbon">Owning ribbon control instance.</param> /// <param name="ribbonLines">Reference to lines definition.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewLayoutRibbonGroupLines(KryptonRibbon ribbon, KryptonRibbonGroupLines ribbonLines, NeedPaintHandler needPaint) { Debug.Assert(ribbon != null); Debug.Assert(ribbonLines != null); Debug.Assert(needPaint != null); // Cache references _ribbon = ribbon; _ribbonLines = ribbonLines; _needPaint = needPaint; // Associate the component with this view element for design time selection Component = _ribbonLines; // Use hashtable to store relationships _itemToView = new ItemToView(); _viewToItem = new ViewToItem(); _sizeLargeList = new SizeList(); _sizeMediumList = new SizeList(); _sizeSmallList = new SizeList(); _viewLargeList = new ViewList(); _viewMediumList = new ViewList(); _viewSmallList = new ViewList(); _viewToLargeGap = new ViewToGap(); _viewToMediumGap = new ViewToGap(); _viewToSmallGap = new ViewToGap(); // Get the initial size used for sizing and positioning ApplySize(ribbonLines.ItemSizeCurrent); // Hook into changes in the ribbon triple definition _ribbonLines.PropertyChanged += new PropertyChangedEventHandler(OnLinesPropertyChanged); _ribbonLines.LinesView = this; // At design time we want to track the mouse and show feedback if (_ribbon.InDesignMode) { ViewHightlightController controller = new ViewHightlightController(this, needPaint); controller.ContextClick += new MouseEventHandler(OnContextClick); MouseController = controller; } }
/// <summary> /// Initialize a new instance of the ViewLayoutRibbonGroupTriple class. /// </summary> /// <param name="ribbon">Owning ribbon control instance.</param> /// <param name="ribbonTriple">Reference to triple definition.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewLayoutRibbonGroupTriple(KryptonRibbon ribbon, KryptonRibbonGroupTriple ribbonTriple, NeedPaintHandler needPaint) { Debug.Assert(ribbon != null); Debug.Assert(ribbonTriple != null); Debug.Assert(needPaint != null); // Cache references _ribbon = ribbon; _ribbonTriple = ribbonTriple; _needPaint = needPaint; // Associate the component with this view element for design time selection Component = _ribbonTriple; // Use hashtables to store relationships _itemToView = new ItemToView(); _smallCache = new ViewToSize(); _mediumCache = new ViewToSize(); _largeCache = new ViewToSize(); // Get the initial size used for sizing and positioning SetCurrentSize(ribbonTriple.ItemSizeCurrent); // Hook into changes in the ribbon triple definition _ribbonTriple.PropertyChanged += new PropertyChangedEventHandler(OnTriplePropertyChanged); _ribbonTriple.TripleView = this; // At design time we want to track the mouse and show feedback if (_ribbon.InDesignMode) { ViewHightlightController controller = new ViewHightlightController(this, needPaint); controller.ContextClick += new MouseEventHandler(OnContextClick); MouseController = controller; } }
private void SyncChildrenToRibbonGroupItems() { // Grab the shape of the ribbon _lastShape = _ribbon.RibbonShape; bool itemEdgeVisible = (_lastShape != PaletteRibbonShape.Office2010); bool itemEdgeIgnoreNormal = (_lastShape == PaletteRibbonShape.Office2010); bool itemConstantBorder = (_lastShape != PaletteRibbonShape.Office2010); bool itemDrawNonTrackingAreas = (_lastShape != PaletteRibbonShape.Office2010); // Remove all child elements Clear(); // Always add the start separator as the first view element Add(_startSep); // Create new lookups which are up to date ItemToView regenView = new ItemToView(); ViewToEdge regenEdge = new ViewToEdge(); // Cache the first and last visible children ViewBase viewFirst = null; ViewBase viewLast = null; // Add a view element for each group item foreach (IRibbonGroupItem item in _ribbonCluster.Items) { ViewBase itemView; ViewDrawRibbonGroupClusterEdge itemEdge; // Do we already have a view for this item definition if (_itemToView.ContainsKey(item)) { itemView = _itemToView[item]; itemEdge = _viewToEdge[itemView]; // Remove from lookups _itemToView.Remove(item); _viewToEdge.Remove(itemView); } else { // Ask the item definition to return an appropriate view itemView = item.CreateView(_ribbon, _needPaint); // Create a border edge to go with the item view itemEdge = new ViewDrawRibbonGroupClusterEdge(_ribbon, _paletteBorderEdge); } // Update the visible state itemView.Visible = _ribbon.InDesignHelperMode || item.Visible; itemEdge.Visible = itemEdgeVisible && (_ribbon.InDesignHelperMode || item.Visible); // We need to remember associations regenView.Add(item, itemView); regenEdge.Add(itemView, itemEdge); Add(itemView); Add(itemEdge); // Update the cached first/last items if (itemView.Visible && (viewFirst == null)) { viewFirst = itemView; } if (itemView.Visible) { viewLast = itemView; } } // Update the display borders for the visible items foreach (ViewBase item in regenView.Values) { // Only interested in visible items if (item.Visible) { if ((item is ViewDrawRibbonGroupClusterButton) || (item is ViewDrawRibbonGroupClusterColorButton)) { // By default each button shows only the top and bottom PaletteDrawBorders maxBorders = PaletteDrawBorders.TopBottom; switch (_lastShape) { default: case PaletteRibbonShape.Office2007: maxBorders = PaletteDrawBorders.TopBottom; // First and last items have extra borders if (item == viewFirst) { // If first and last, it needs all borders if (item == viewLast) { maxBorders = PaletteDrawBorders.All; } else { maxBorders = PaletteDrawBorders.TopBottomLeft; } } else if (item == viewLast) { maxBorders = PaletteDrawBorders.TopBottomRight; } break; case PaletteRibbonShape.Office2010: maxBorders = PaletteDrawBorders.All; break; } // Remove the border edge after the last button if (item == viewLast) { Remove(regenEdge[item]); } // Cast to correct type ViewDrawRibbonGroupClusterButton clusterButton = item as ViewDrawRibbonGroupClusterButton; ViewDrawRibbonGroupClusterColorButton clusterColorButton = item as ViewDrawRibbonGroupClusterColorButton; if (clusterButton != null) { clusterButton.MaxBorderEdges = maxBorders; clusterButton.BorderIgnoreNormal = itemEdgeIgnoreNormal; clusterButton.ConstantBorder = itemConstantBorder; clusterButton.DrawNonTrackingAreas = itemDrawNonTrackingAreas; } if (clusterColorButton != null) { clusterColorButton.MaxBorderEdges = maxBorders; clusterColorButton.BorderIgnoreNormal = itemEdgeIgnoreNormal; clusterColorButton.ConstantBorder = itemConstantBorder; clusterColorButton.DrawNonTrackingAreas = itemDrawNonTrackingAreas; } } } } // Dispose of all the items no longer needed foreach (ViewBase view in _itemToView.Values) { view.Dispose(); } foreach (ViewBase view in _viewToEdge.Values) { view.Dispose(); } // Always add the end separator as the last view element (excluding any desing time additions) Add(_endSep); // Define visible state of the separators _startSep.Visible = (_lastShape == PaletteRibbonShape.Office2010); _endSep.Visible = (_lastShape == PaletteRibbonShape.Office2010); // When in design time help mode if (_ribbon.InDesignHelperMode) { // Create the design time 'Item' first time it is needed if (_viewAddItem == null) { _viewAddItem = new ViewDrawRibbonDesignCluster(_ribbon, _ribbonCluster, _needPaint); } // Always add at end of the list of items Add(_viewAddItem); } // Use the latest tables _itemToView = regenView; _viewToEdge = regenEdge; }
private void SyncChildrenToRibbonGroupItems() { // Remove all child elements Clear(); ItemToView regenItemToView = new ItemToView(); ViewToItem regenViewToItem = new ViewToItem(); // Add a view element for each group item foreach (IRibbonGroupItem item in _ribbonLines.Items) { ViewBase itemView; // Do we already have a view for this item definition if (_itemToView.ContainsKey(item)) { itemView = _itemToView[item]; // Remove from lookup to prevent it being deleted _itemToView.Remove(item); } else { // Ask the item definition to return an appropriate view itemView = item.CreateView(_ribbon, _needPaint); } // Update the visible state of the item itemView.Visible = _ribbon.InDesignHelperMode || item.Visible; // We need to keep this association regenItemToView.Add(item, itemView); regenViewToItem.Add(itemView, item); Add(itemView); } // When in design time help mode if (_ribbon.InDesignHelperMode) { // Create the design time 'Add Tab' first time it is needed if (_viewAddItem == null) { _viewAddItem = new ViewDrawRibbonDesignGroupLines(_ribbon, _ribbonLines, _currentSize, _needPaint); } // Always add at end of the list of items Add(_viewAddItem); } // Dispose of all the items no longer needed foreach (ViewBase view in _itemToView.Values) { view.Dispose(); } // Use the latest hashtable _itemToView = regenItemToView; _viewToItem = regenViewToItem; }
public List <ItemToView> recognizeIt(string FileToRecognize) { // string subscriptionKey = Environment.GetEnvironmentVariable("COMPUTER_VISION_SUBSCRIPTION_KEY"); // string endpoint = Environment.GetEnvironmentVariable("COMPUTER_VISION_ENDPOINT"); string subscriptionKey = "b3e46781e1e648c9bc8452b124b73c31"; string endpoint = "https://westcentralus.api.cognitive.microsoft.com/vision"; string uriBase = endpoint + "/v2.1/read/core/asyncBatchAnalyze"; string imageFile = FileToRecognize; ReadText(imageFile).Wait(); async Task ReadText(string imageFilePath) { try { HttpClient client = new HttpClient(); // Request headers. client.DefaultRequestHeaders.Add( "Ocp-Apim-Subscription-Key", subscriptionKey); // Assemble the URI for the REST API method. string uri = uriBase; HttpResponseMessage response; string operationLocation; // Reads the contents of the specified local image // into a byte array. byte[] byteData = GetImageAsByteArray(imageFilePath); // Adds the byte array as an octet stream to the request body. using (ByteArrayContent content = new ByteArrayContent(byteData)) { // This example uses the "application/octet-stream" content type. // The other content types you can use are "application/json" // and "multipart/form-data". content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // The first REST API method, Batch Read, starts // the async process to analyze the written text in the image. response = await client.PostAsync(uri, content); } // The response header for the Batch Read method contains the URI // of the second method, Read Operation Result, which // returns the results of the process in the response body. // The Batch Read operation does not return anything in the response body. if (response.IsSuccessStatusCode) { operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault(); } else { // Display the JSON error data. string errorString = await response.Content.ReadAsStringAsync(); Console.WriteLine("\n\nResponse:\n{0}\n", JToken.Parse(errorString).ToString()); return; } // If the first REST API method completes successfully, the second // REST API method retrieves the text written in the image. // // Note: The response may not be immediately available. Text // recognition is an asynchronous operation that can take a variable // amount of time depending on the length of the text. // You may need to wait or retry this operation. // // This example checks once per second for ten seconds. string contentString; int i = 0; do { System.Threading.Thread.Sleep(1000); response = await client.GetAsync(operationLocation); contentString = await response.Content.ReadAsStringAsync(); ++i; }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1); if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1) { Console.WriteLine("\nTimeout error.\n"); return; } //JToken.Parse(contentString).ToString()); File.WriteAllText("output.json", JToken.Parse(contentString).ToString()); } catch (Exception e) { Console.WriteLine("\n" + e.Message); } } byte[] GetImageAsByteArray(string imageFilePath) { // Open a read-only file stream for the specified file. using (FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read)) { // Read the file's contents into a byte array. BinaryReader binaryReader = new BinaryReader(fileStream); return(binaryReader.ReadBytes((int)fileStream.Length)); } } List <Word> CreateListOfWords(ResRoot rslt) { List <Word> All_Words = new List <Word>(); for (int i = 0; i < rslt.recognitionResults.Count; i++) { foreach (Line l in rslt.recognitionResults[i].lines) { foreach (Word w in l.words) { All_Words.Add(w); } } } return(All_Words); } List <List <Word> > WordsInLines(List <Word> _AllWords) { _AllWords = _AllWords.OrderBy(w => Tuple.Create(w.boundingBox[1], w.boundingBox[0])).ToList(); List <List <Word> > WordsInLine = new List <List <Word> >(); List <Word> Line = new List <Word>(); int lineHeight = _AllWords[0].boundingBox[5] - _AllWords[0].boundingBox[3]; int prev = _AllWords[0].boundingBox[3]; for (int i = 0; i < _AllWords.Count; i++) { if ((Math.Abs(_AllWords[i].boundingBox[3] - prev) < lineHeight)) { Line.Add(_AllWords[i]); } else { WordsInLine.Add(Line.OrderBy(l => l.boundingBox[0]).ToList()); Line = new List <Word>(); Line.Add(_AllWords[i]); lineHeight = _AllWords[i].boundingBox[5] - _AllWords[i].boundingBox[3]; prev = _AllWords[i].boundingBox[3]; } } if (Line.Count > 0) { WordsInLine.Add(Line.OrderBy(l => l.boundingBox[0]).ToList()); } return(WordsInLine); } List <List <string> > WordsToStrings(List <List <Word> > WordsInLine) { List <List <string> > _Lines = new List <List <string> >(); foreach (var l in WordsInLine) { List <string> Line = new List <string>(); foreach (var w in l) { Line.Add(w.text); } _Lines.Add(Line); } return(_Lines); } ItemToView ParseLine(List <string> Line) { ItemToView item = new ItemToView(); item.ItemName = ""; item.ItemPrice = 0; if (Line.Count > 0) { string path = "./results/result.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter outputFile = File.CreateText(path)) { outputFile.WriteLine("Results: "); } } using (StreamWriter outputFile = File.AppendText(path)) { outputFile.WriteLine("****************************"); foreach (string s in Line) { if (s.Length > 2 && Char.IsLetter(s, 0)) { string ItemName = s; outputFile.WriteLine($"Name probably is {ItemName}"); item.ItemName = item.ItemName + " " + s; } else if (Char.IsDigit(s, 0) && s.Contains(".")) { try { double ItemPrice = Double.Parse(s); outputFile.WriteLine($"Price probably is {ItemPrice}"); item.ItemPrice = Double.Parse(s); } catch (FormatException) { outputFile.WriteLine($"Unable to parse {s}'"); } } else if (Char.IsDigit(s, 0) && s.Contains("/") && s.Count() > 5) { DateTime date; if (DateTime.TryParse(s, out date)) { outputFile.WriteLine($"Date probably is {date}"); } else { outputFile.WriteLine($"Unable to parse {s}'"); } } else { outputFile.WriteLine($"Unable to parse '{s}"); } } } } return(item); } ResRoot res = JsonConvert.DeserializeObject <ResRoot>(File.ReadAllText("output.json")); List <Word> AllWords = CreateListOfWords(res); List <List <Word> > AllWordsInLines = WordsInLines(AllWords); List <ItemToView> resultList = new List <ItemToView>(); List <List <string> > Lines = WordsToStrings(AllWordsInLines); foreach (var l in Lines) { resultList.Add(ParseLine(l)); } return(resultList); }