RectangleF?getFieldActualRectangle(Template.Field field) { if (!field.IsSet()) { throw new Exception("Field is not set."); } if (field.Rectangle.Width <= Settings.Constants.CoordinateDeviationMargin || field.Rectangle.Height <= Settings.Constants.CoordinateDeviationMargin) { throw new Exception("Rectangle is malformed."); } RectangleF r = field.Rectangle.GetSystemRectangleF(); if (field.LeftAnchor != null) { Page.AnchorActualInfo aai = GetAnchorActualInfo(field.LeftAnchor.Id); if (!aai.Found) { return(null); } float right = r.Right; r.X += aai.Shift.Width - field.LeftAnchor.Shift; r.Width = right - r.X; } if (field.TopAnchor != null) { Page.AnchorActualInfo aai = GetAnchorActualInfo(field.TopAnchor.Id); if (!aai.Found) { return(null); } float bottom = r.Bottom; r.Y += aai.Shift.Height - field.TopAnchor.Shift; r.Height = bottom - r.Y; } if (field.RightAnchor != null) { Page.AnchorActualInfo aai = GetAnchorActualInfo(field.RightAnchor.Id); if (!aai.Found) { return(null); } r.Width += aai.Shift.Width - field.RightAnchor.Shift; } if (field.BottomAnchor != null) { Page.AnchorActualInfo aai = GetAnchorActualInfo(field.BottomAnchor.Id); if (!aai.Found) { return(null); } r.Height += aai.Shift.Height - field.BottomAnchor.Shift; } if (r.Width <= 0 || r.Height <= 0) { return(null); } return(r); }
//Sample expression: "1 | (2 & 3)" static public bool Parse(string expression, Page p) { expression = Regex.Replace(expression, @"\d+", (Match m) => { Page.AnchorActualInfo aai = p.GetAnchorActualInfo(int.Parse(m.Value)); return(aai.Found ? "T" : "F"); }); return(parseWithSubstitutedAnchorIds(expression)); }
void _setAnchorStatus(int anchorId) { Template.Anchor a = getAnchor(anchorId, out DataGridViewRow row); if (a == null || row == null) { return; } if (pages == null) { return; } pages.ActiveTemplate = getTemplateFromUI(false); a = pages.ActiveTemplate.Anchors.FirstOrDefault(x => x.Id == anchorId); if (a == null) { throw new Exception("Anchor[Id=" + a.Id + "] does not exist."); } bool set = true; for (Template.Anchor a_ = a; a_ != null; a_ = pages.ActiveTemplate.Anchors.FirstOrDefault(x => x.Id == a_.ParentAnchorId)) { if (!a_.IsSet()) { set = false; getAnchor(a_.Id, out DataGridViewRow r_); setRowStatus(statuses.WARNING, r_, "Not set"); } } if (!set) { return; } Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(a.Id); getAnchor(a.Id, out DataGridViewRow r); if (!aai.Found) { setRowStatus(statuses.ERROR, r, "Not found"); } else { setRowStatus(statuses.SUCCESS, r, "Found"); } }
void initializeFieldsTable() { LeftAnchorId.ValueType = typeof(int); LeftAnchorId.ValueMember = "Id"; LeftAnchorId.DisplayMember = "Name"; TopAnchorId.ValueType = typeof(int); TopAnchorId.ValueMember = "Id"; TopAnchorId.DisplayMember = "Name"; RightAnchorId.ValueType = typeof(int); RightAnchorId.ValueMember = "Id"; RightAnchorId.DisplayMember = "Name"; BottomAnchorId.ValueType = typeof(int); BottomAnchorId.ValueMember = "Id"; BottomAnchorId.DisplayMember = "Name"; Type.ValueType = typeof(Template.Field.Types); Type.DataSource = Enum.GetValues(typeof(Template.Field.Types)); fields.EnableHeadersVisualStyles = false;//needed to set row headers fields.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { DataGridViewRow r = fields.Rows[e.RowIndex]; Message.Error("fields[" + r.Index + "] has unacceptable value of " + fields.Columns[e.ColumnIndex].HeaderText + ":\r\n" + e.Exception.Message); }; fields.UserDeletingRow += delegate(object sender, DataGridViewRowCancelEventArgs e) { if (fields.Rows.Count < 3 && fields.SelectedRows.Count > 0) { fields.SelectedRows[0].Selected = false;//to avoid auto-creating row } }; fields.RowsAdded += delegate(object sender, DataGridViewRowsAddedEventArgs e) { }; fields.CellValueChanged += delegate(object sender, DataGridViewCellEventArgs e) { try { if (loadingTemplate) { return; } if (e.ColumnIndex < 0)//row's header { return; } DataGridViewRow row = fields.Rows[e.RowIndex]; var cs = row.Cells; Template.Field f = (Template.Field)row.Tag; switch (fields.Columns[e.ColumnIndex].Name) { //case "Rectangle": // { // cs["Value"].Value = extractValueAndDrawSelectionBox(f.AnchorId, f.Rectangle, f.Type); // break; // } case "Type": { Template.Field.Types t2 = (Template.Field.Types)row.Cells["Type"].Value; if (t2 == f.Type) { break; } Template.Field f2; switch (t2) { case Template.Field.Types.PdfText: f2 = new Template.Field.PdfText(); break; case Template.Field.Types.OcrText: f2 = new Template.Field.OcrText(); break; case Template.Field.Types.ImageData: f2 = new Template.Field.ImageData(); break; default: throw new Exception("Unknown option: " + t2); } f2.Name = f.Name; f2.LeftAnchor = f.LeftAnchor; f2.TopAnchor = f.TopAnchor; f2.RightAnchor = f.RightAnchor; f2.BottomAnchor = f.BottomAnchor; f2.Rectangle = f.Rectangle; f = f2; setFieldRow(row, f); break; } case "LeftAnchorId": { int?ai = (int?)cs["LeftAnchorId"].Value; if (ai == null) { f.LeftAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.LeftAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Width, }; } setFieldRow(row, f); } break; case "TopAnchorId": { int?ai = (int?)cs["TopAnchorId"].Value; if (ai == null) { f.TopAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.TopAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Height, }; } setFieldRow(row, f); } break; case "RightAnchorId": { int?ai = (int?)cs["RightAnchorId"].Value; if (ai == null) { f.RightAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.RightAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Width, }; } setFieldRow(row, f); } break; case "BottomAnchorId": { int?ai = (int?)cs["BottomAnchorId"].Value; if (ai == null) { f.BottomAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.BottomAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Height, }; } setFieldRow(row, f); } break; case "Name_": f.Name = (string)row.Cells["Name_"].Value; break; } } catch (Exception ex) { Message.Error2(ex); } }; fields.CurrentCellDirtyStateChanged += delegate { if (fields.IsCurrentCellDirty) { fields.CommitEdit(DataGridViewDataErrorContexts.Commit); } }; fields.RowValidating += delegate(object sender, DataGridViewCellCancelEventArgs e) { DataGridViewRow r = fields.Rows[e.RowIndex]; try { if (r.Tag != null) { string n = FieldPreparation.Normalize((string)r.Cells["Name_"].Value); if (string.IsNullOrWhiteSpace(n)) { throw new Exception("Name cannot be empty!"); } //foreach (DataGridViewRow rr in fields.Rows) //{ // if (r == rr) // continue; // Template.Field f = (Template.Field)rr.Tag; // if (f != null && n == f.Name) // throw new Exception("Name '" + n + "' is duplicated!"); //} r.Cells["Name_"].Value = n; } } catch (Exception ex) { //Log.Message.Error("Name", ex); Message.Error2(ex); e.Cancel = true; } }; fields.DefaultValuesNeeded += delegate(object sender, DataGridViewRowEventArgs e) { }; fields.CellContentClick += delegate(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex < 0)//row's header { return; } switch (fields.Columns[e.ColumnIndex].Name) { case "Ocr": fields.EndEdit(); break; } }; fields.SelectionChanged += delegate(object sender, EventArgs e) { try { if (loadingTemplate) { return; } if (settingCurrentFieldRow) { return; } if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow row = fields.SelectedRows[0]; Template.Field f = (Template.Field)row.Tag; if (f == null)//hacky forcing commit a newly added row and display the blank row { int i = fields.Rows.Add(); row = fields.Rows[i]; f = templateManager.CreateDefaultField(); setFieldRow(row, f); row.Selected = true; return; } setCurrentFieldRow(row); } catch (Exception ex) { Log.Message.Error(ex); } }; copy2ClipboardField.LinkClicked += delegate { if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r = fields.SelectedRows[fields.SelectedRows.Count - 1]; if (r.Tag == null) { return; } Template.Field f = (Template.Field)r.Tag; object o = pages[currentPageI].GetValue(f.Name); switch (f.Type) { case Template.Field.Types.ImageData: Clipboard.SetData(f.Type.ToString(), (Image)o); break; case Template.Field.Types.PdfText: case Template.Field.Types.OcrText: Clipboard.SetText((string)o); break; default: throw new Exception("Unknown option: " + f.Type); } }; duplicateField.LinkClicked += delegate { try { if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; if (r0.Tag == null) { return; } Template.Field f0 = (Template.Field)r0.Tag; List <DataGridViewRow> cloningFieldRows = new List <DataGridViewRow> { r0 }; //if((f0 as Template.Field.PdfText)?.ColumnOfTable!=null) //{ // Message.Exclaim("This field is a column of "+ (f0 as Template.Field.PdfText)?.ColumnOfTable + " so you should create a new definition of it."); // return; //} //foreach (DataGridViewRow r in fields.Rows) // if ((r.Tag as Template.Field.PdfText)?.ColumnOfTable == f0.Name) // cloningFieldRows.Add(r); if (f0.ColumnOfTable != null) { if (!Message.YesNo("This field is a column of table " + f0.ColumnOfTable + " and so new definions will be added to the rest column fields as well. Proceed?")) { return; } foreach (DataGridViewRow r in fields.Rows) { if (r != r0 && (r.Tag as Template.Field)?.ColumnOfTable == f0.ColumnOfTable) { string fn = (r.Tag as Template.Field)?.Name; if (cloningFieldRows.Find(x => (x.Tag as Template.Field)?.Name == fn) == null) { cloningFieldRows.Add(r); } } } } settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes foreach (DataGridViewRow row in cloningFieldRows) { Template.Field f = (Template.Field)Serialization.Json.Clone(((Template.Field)row.Tag).GetType(), row.Tag); f.LeftAnchor = null; f.TopAnchor = null; f.RightAnchor = null; f.BottomAnchor = null; int i = fields.Rows.Add(); DataGridViewRow r = fields.Rows[i]; setFieldRow(r, f); fields.Rows.Remove(r); fields.Rows.Insert(row.Index + 1, r); } } catch (Exception e) { Log.Message.Error(e); } finally { settingCurrentFieldRow = false; } }; //duplicateField.LinkClicked += delegate //{ // if (fields.SelectedRows.Count < 1) // return; // DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; // if (r0.Tag == null) // return; // Template.Field f0 = (Template.Field)r0.Tag; // if (f0.ColumnOfTable != null) // { // Message.Exclaim("This field is a column of table " + f0.ColumnOfTable + " so you should create a new definition of it."); // return; // } // List<DataGridViewRow> cloningFieldRows = new List<DataGridViewRow> { r0 }; // //foreach (DataGridViewRow r in fields.Rows) // // if (r != r0 && (r.Tag as Template.Field)?.ColumnOfTable == f0.Name) // // { // // string fn = (r.Tag as Template.Field)?.Name; // // if (cloningFieldRows.Find(x => (x.Tag as Template.Field)?.Name == fn) == null) // // cloningFieldRows.Add(r); // // } // settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes // foreach (DataGridViewRow row in cloningFieldRows) // { // Template.Field f = (Template.Field)Serialization.Json.Clone(((Template.Field)row.Tag).GetType(), row.Tag); // f.LeftAnchor = null; // f.TopAnchor = null; // f.RightAnchor = null; // f.BottomAnchor = null; // int i = fields.Rows.Add(); // DataGridViewRow r = fields.Rows[i]; // setFieldRow(r, f); // fields.Rows.Remove(r); // fields.Rows.Insert(row.Index + 1, r); // } // settingCurrentFieldRow = false; //}; deleteField.LinkClicked += delegate { try { if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; if (r0.Tag == null) { return; } Template.Field f0 = (Template.Field)r0.Tag; bool unique = true; foreach (DataGridViewRow rr in fields.Rows) { if (rr != r0 && rr.Tag != null && ((Template.Field)rr.Tag).Name == f0.Name) { unique = false; break; } } if (unique) { Message.Inform("This field definition cannot be deleted because it is the last of the field."); return; } List <DataGridViewRow> deletingFieldRows = new List <DataGridViewRow> { r0 }; if (f0.ColumnOfTable != null) { if (!Message.YesNo("This field is a column of table " + f0.ColumnOfTable + " and so the respective definitions of the rest column fields will be deleted as well. Proceed?")) { return; } Dictionary <string, List <DataGridViewRow> > fieldName2orderedRows = new Dictionary <string, List <DataGridViewRow> >(); foreach (DataGridViewRow r in fields.Rows) { if ((r.Tag as Template.Field.PdfText)?.ColumnOfTable == f0.ColumnOfTable) { List <DataGridViewRow> rs; string fn = (r.Tag as Template.Field)?.Name; if (!fieldName2orderedRows.TryGetValue(fn, out rs)) { rs = new List <DataGridViewRow>(); fieldName2orderedRows[fn] = rs; } rs.Add(r); } } int definitionIndex = fieldName2orderedRows[f0.Name].IndexOf(r0); fieldName2orderedRows.Remove(f0.Name); foreach (List <DataGridViewRow> rs in fieldName2orderedRows.Values) { deletingFieldRows.Add(rs[definitionIndex]); } } settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes foreach (DataGridViewRow row in deletingFieldRows) { fields.Rows.Remove(row); } } catch (Exception e) { Log.Message.Error(e); } finally { settingCurrentFieldRow = false; } }; //deleteField.LinkClicked += delegate //{ // if (fields.SelectedRows.Count < 1) // return; // DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; // if (r0.Tag == null) // return; // Template.Field f0 = (Template.Field)r0.Tag; // bool unique = true; // foreach (DataGridViewRow rr in fields.Rows) // if (rr != r0 && rr.Tag != null && ((Template.Field)rr.Tag).Name == f0.Name) // { // unique = false; // break; // } // if (unique) // { // Message.Inform("This field definition cannot be deleted because it is the last of the field."); // return; // } // if (f0.ColumnOfTable != null) // { // Message.Exclaim("This field is a column of table " + f0.ColumnOfTable + " so you should delete the respectivea definition of it."); // return; // } // Dictionary<string, List<DataGridViewRow>> fieldName2orderedRows = new Dictionary<string, List<DataGridViewRow>>(); // foreach (DataGridViewRow r in fields.Rows) // if ((r.Tag as Template.Field.PdfText)?.ColumnOfTable == f0.Name) // { // List<DataGridViewRow> rs; // string fn = (r.Tag as Template.Field)?.Name; // if (!fieldName2orderedRows.TryGetValue(fn, out rs)) // { // rs = new List<DataGridViewRow>(); // fieldName2orderedRows[fn] = rs; // } // rs.Add(r); // } // int definitionIndex = fieldName2orderedRows[f0.Name].IndexOf(r0); // fieldName2orderedRows.Remove(f0.Name); // List<DataGridViewRow> deletingFieldRows = new List<DataGridViewRow> { r0 }; // foreach (List<DataGridViewRow> rs in fieldName2orderedRows.Values) // deletingFieldRows.Add(rs[definitionIndex]); // settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes // foreach (DataGridViewRow row in deletingFieldRows) // fields.Rows.Remove(row); // settingCurrentFieldRow = false; //}; moveUpField.LinkClicked += delegate { try { if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r = fields.SelectedRows[fields.SelectedRows.Count - 1]; int i2 = r.Index - 1; if (i2 < 0) { return; } int minI = int.MaxValue; foreach (DataGridViewRow rr in fields.Rows) { if (rr != r && rr.Tag != null && ((Template.Field)rr.Tag).Name == ((Template.Field)r.Tag).Name && rr.Index < minI) { minI = rr.Index; } } if (i2 < minI) { return; } settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes fields.Rows.Remove(r); fields.Rows.Insert(i2, r); settingCurrentFieldRow = false; r.Selected = true; } catch (Exception e) { Log.Message.Error(e); } finally { settingCurrentFieldRow = false; } }; moveDownField.LinkClicked += delegate { try { if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r = fields.SelectedRows[fields.SelectedRows.Count - 1]; int i2 = r.Index + 1; if (i2 > fields.Rows.Count - 1) { return; } int maxI = 0; foreach (DataGridViewRow rr in fields.Rows) { if (rr != r && rr.Tag != null && ((Template.Field)rr.Tag).Name == ((Template.Field)r.Tag).Name && rr.Index > maxI) { maxI = rr.Index; } } if (i2 > maxI + 1) { return; } settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes fields.Rows.Remove(r); fields.Rows.Insert(i2, r); settingCurrentFieldRow = false; r.Selected = true; } catch (Exception e) { Log.Message.Error(e); } finally { settingCurrentFieldRow = false; } }; }
bool findAndDrawAnchor(int anchorId) { if (pages == null) { return(false); } pages.ActiveTemplate = GetTemplateFromUI(false); Template.Anchor a = pages.ActiveTemplate.Anchors.FirstOrDefault(x => x.Id == anchorId); if (a == null) { throw new Exception("Anchor[Id=" + a.Id + "] does not exist."); } bool set = true; for (Template.Anchor a_ = a; a_ != null; a_ = pages.ActiveTemplate.Anchors.FirstOrDefault(x => x.Id == a_.ParentAnchorId)) { if (a != a_) { showAnchorRowAs(a_.Id, rowStates.Parent, false); } if (!a_.IsSet()) { set = false; getAnchor(a_.Id, out DataGridViewRow r_); setRowStatus(statuses.WARNING, r_, "Not set"); } } if (!set) { return(false); } getAnchor(a.Id, out DataGridViewRow r); Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(a.Id); if (!aai.Found) { setRowStatus(statuses.ERROR, r, "Not found"); return(false); } setRowStatus(statuses.SUCCESS, r, "Found"); for (Page.AnchorActualInfo aai_ = aai; aai_ != null; aai_ = aai_.ParentAnchorActualInfo) { RectangleF r_ = aai_.Anchor.Rectangle(); r_.X += aai_.Shift.Width; r_.Y += aai_.Shift.Height; if (aai_ == aai) { if (currentAnchorControl != null) { drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <RectangleF> { r_ }); owners2resizebleBox[aai_.Anchor] = new ResizebleBox(aai_.Anchor, r_, Settings.Appearance.SelectionBoxBorderWidth); } else { drawBoxes(Settings.Appearance.AnchorBoxColor, Settings.Appearance.AnchorBoxBorderWidth, new List <RectangleF> { r_ }); } } else { drawBoxes(Settings.Appearance.AscendantAnchorBoxColor, Settings.Appearance.AscendantAnchorBoxBorderWidth, new List <RectangleF> { r_ }); } List <RectangleF> bs = null; switch (aai_.Anchor.Type) { case Template.Anchor.Types.PdfText: { var pt = (Template.Anchor.PdfText)aai_.Anchor; bs = pt.CharBoxs.Select(x => new RectangleF(x.Rectangle.X + aai_.Shift.Width, x.Rectangle.Y + aai_.Shift.Height, x.Rectangle.Width, x.Rectangle.Height)).ToList(); } break; case Template.Anchor.Types.OcrText: { var ot = (Template.Anchor.OcrText)aai_.Anchor; bs = ot.CharBoxs.Select(x => new RectangleF(x.Rectangle.X + aai_.Shift.Width, x.Rectangle.Y + aai_.Shift.Height, x.Rectangle.Width, x.Rectangle.Height)).ToList(); } break; case Template.Anchor.Types.ImageData: //bs = new List<System.Drawing.RectangleF> { rs[0] }; break; case Template.Anchor.Types.CvImage: //bs = new List<System.Drawing.RectangleF> { rs[0] }; break; default: throw new Exception("Unknown option: " + aai_.Anchor.Type); } if (bs != null) { if (aai_.Anchor == a) { drawBoxes(Settings.Appearance.AnchorBoxColor, Settings.Appearance.AnchorBoxBorderWidth, bs); } else { drawBoxes(Settings.Appearance.AscendantAnchorBoxColor, Settings.Appearance.AscendantAnchorBoxBorderWidth, bs); } } } return(true); }
public TemplateForm(TemplateManager templateManager) { InitializeComponent(); Icon = Win.AssemblyRoutines.GetAppIcon(); Text = Program.FullName + " - Template Editor"; templateManager.TemplateForm = this; this.templateManager = templateManager; this.bitmapPreparationForm = new ScanTemplateForm(this); initializeAnchorsTable(); initializeConditionsTable(); initializeFieldsTable(); TesseractPageSegMode.DataSource = Enum.GetValues(typeof(Tesseract.PageSegMode)); picture.MouseDown += delegate(object sender, MouseEventArgs e) { if (pages == null) { return; } Point p = new Point((int)(e.X / (float)pictureScale.Value), (int)(e.Y / (float)pictureScale.Value)); ResizebleBox rb = findResizebleBox(p, out ResizebleBoxSides resizebleBoxSide); if (rb != null) { drawingMode = resizebleBoxSide == ResizebleBoxSides.Left || resizebleBoxSide == ResizebleBoxSides.Right ? DrawingModes.resizingSelectionBoxV : DrawingModes.resizingSelectionBoxH; Cursor.Current = drawingMode == DrawingModes.resizingSelectionBoxV ? Cursors.VSplit : Cursors.HSplit; selectionBoxPoint0 = rb.R.Location; selectionBoxPoint1 = rb.R.Location; selectionBoxPoint2 = new Point(rb.R.Right, rb.R.Bottom); } else { if (ModifierKeys.HasFlag(Keys.Shift)) { drawingMode = DrawingModes.movingImage; Cursor.Current = Cursors.SizeAll; screenMousePosition0 = Control.MousePosition; imageScrollPostion0 = new Point(splitContainer1.Panel2.HorizontalScroll.Value, splitContainer1.Panel2.VerticalScroll.Value);//to avoid jerking } else { drawingMode = DrawingModes.drawingSelectionBox; selectionBoxPoint0 = p; selectionBoxPoint1 = p; selectionBoxPoint2 = p; } } showSelectionCoordinates(selectionBoxPoint1); }; picture.MouseWheel += delegate(object sender, MouseEventArgs e) { if (pages == null) { return; } }; picture.MouseMove += delegate(object sender, MouseEventArgs e) { if (pages == null) { return; } Point p; if (drawingMode == DrawingModes.movingImage) { p = Control.MousePosition; int h = imageScrollPostion0.X + screenMousePosition0.X - p.X; if (h < splitContainer1.Panel2.HorizontalScroll.Minimum) { h = splitContainer1.Panel2.HorizontalScroll.Minimum; } else if (h > splitContainer1.Panel2.HorizontalScroll.Maximum) { h = splitContainer1.Panel2.HorizontalScroll.Maximum; } splitContainer1.Panel2.HorizontalScroll.Value = h; int v = imageScrollPostion0.Y + screenMousePosition0.Y - p.Y; if (v < splitContainer1.Panel2.VerticalScroll.Minimum) { v = splitContainer1.Panel2.VerticalScroll.Minimum; } else if (v > splitContainer1.Panel2.VerticalScroll.Maximum) { v = splitContainer1.Panel2.VerticalScroll.Maximum; } splitContainer1.Panel2.VerticalScroll.Value = v; return; } p = new Point((int)(e.X / (float)pictureScale.Value), (int)(e.Y / (float)pictureScale.Value)); switch (drawingMode) { case DrawingModes.NULL: showSelectionCoordinates(p); if (findResizebleBox(p, out ResizebleBoxSides resizebleBoxSide) != null) { Cursor.Current = resizebleBoxSide == ResizebleBoxSides.Left || resizebleBoxSide == ResizebleBoxSides.Right ? Cursors.VSplit : Cursors.HSplit; } else { Cursor.Current = Cursors.Default; } return; case DrawingModes.drawingSelectionBox: if (selectionBoxPoint0.X < p.X) { selectionBoxPoint1.X = selectionBoxPoint0.X; selectionBoxPoint2.X = p.X; } else { selectionBoxPoint1.X = p.X; selectionBoxPoint2.X = selectionBoxPoint0.X; } if (selectionBoxPoint0.Y < p.Y) { selectionBoxPoint1.Y = selectionBoxPoint0.Y; selectionBoxPoint2.Y = p.Y; } else { selectionBoxPoint1.Y = p.Y; selectionBoxPoint2.Y = selectionBoxPoint0.Y; } break; case DrawingModes.resizingSelectionBoxV: if (Math.Abs(selectionBoxPoint2.X - p.X) < Math.Abs(p.X - selectionBoxPoint1.X)) { selectionBoxPoint2.X = p.X; } else { selectionBoxPoint1.X = p.X; } break; case DrawingModes.resizingSelectionBoxH: if (Math.Abs(selectionBoxPoint2.Y - p.Y) < Math.Abs(p.Y - selectionBoxPoint1.Y)) { selectionBoxPoint2.Y = p.Y; } else { selectionBoxPoint1.Y = p.Y; } break; } showSelectionCoordinates(selectionBoxPoint1, selectionBoxPoint2); RectangleF r = new RectangleF(selectionBoxPoint1.X, selectionBoxPoint1.Y, selectionBoxPoint2.X - selectionBoxPoint1.X, selectionBoxPoint2.Y - selectionBoxPoint1.Y); clearImageFromBoxes(); drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <System.Drawing.RectangleF> { r }); }; picture.MouseUp += delegate(object sender, MouseEventArgs e) { try { if (pages == null) { return; } if (drawingMode == DrawingModes.NULL) { return; } if (drawingMode == DrawingModes.movingImage) { Cursor.Current = Cursors.Default; } drawingMode = DrawingModes.NULL; Template.RectangleF r = new Template.RectangleF(selectionBoxPoint1.X, selectionBoxPoint1.Y, selectionBoxPoint2.X - selectionBoxPoint1.X, selectionBoxPoint2.Y - selectionBoxPoint1.Y); if (r.Width == 0 || r.Y == 0)//accidental tap { return; } switch (settingMode) { case SettingModes.SetAnchor: { if (currentAnchorControl == null) { break; } //currentAnchorControl.SetTagFromControl();??? Template.Anchor a = (Template.Anchor)currentAnchorControl.Row.Tag; if (pages[currentPageI].DetectedImageScale >= 0 && pages[currentPageI].DetectedImageScale < 1 && a.Id == GetTemplateFromUI(false).ScalingAnchorId) { Message.Exclaim("When the detected image scale is not 1, changing coordinates of the scaling anchor must not be done. Either switch off scaling by anchor and reload the page or open a page where the detected image scale is 1.", this); break; } a.Position = new Template.PointF { X = r.X, Y = r.Y }; try { switch (a.Type) { case Template.Anchor.Types.PdfText: { Template.Anchor.PdfText pt = (Template.Anchor.PdfText)a; pt.CharBoxs = new List <Template.Anchor.PdfText.CharBox>(); foreach (Pdf.CharBox cb in Pdf.GetCharBoxsSurroundedByRectangle(pages[currentPageI].PdfCharBoxs, r.GetSystemRectangleF(), true)) { pt.CharBoxs.Add(new Template.Anchor.PdfText.CharBox { Char = cb.Char, Rectangle = new Template.RectangleF(cb.R.X, cb.R.Y, cb.R.Width, cb.R.Height), }); } pt.Size = new Template.SizeF { Width = r.Width, Height = r.Height }; } break; case Template.Anchor.Types.OcrText: { Template.Anchor.OcrText ot = (Template.Anchor.OcrText)a; ot.CharBoxs = new List <Template.Anchor.OcrText.CharBox>(); var selectedOcrCharBoxs = new List <Ocr.CharBox>(); if (ot.OcrEntirePage) { selectedOcrCharBoxs.AddRange(Ocr.GetCharBoxsSurroundedByRectangle(pages[currentPageI].ActiveTemplateOcrCharBoxs, r.GetSystemRectangleF())); } else { using (Bitmap b = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Pdf2ImageResolutionRatio, r.Y / Settings.Constants.Pdf2ImageResolutionRatio, r.Width / Settings.Constants.Pdf2ImageResolutionRatio, r.Height / Settings.Constants.Pdf2ImageResolutionRatio)) { if (b == null) { throw new Exception("Selected image is empty."); } foreach (Ocr.CharBox cb in Ocr.This.GetCharBoxs(b, pages.ActiveTemplate.TesseractPageSegMode)) { cb.R.X += r.X; cb.R.Y += r.Y; selectedOcrCharBoxs.Add(cb); } } } foreach (Ocr.CharBox cb in selectedOcrCharBoxs) { ot.CharBoxs.Add(new Template.Anchor.OcrText.CharBox { Char = cb.Char, Rectangle = new Template.RectangleF(cb.R.X, cb.R.Y, cb.R.Width, cb.R.Height), }); } ot.Size = new Template.SizeF { Width = r.Width, Height = r.Height }; } break; case Template.Anchor.Types.ImageData: { Template.Anchor.ImageData id = (Template.Anchor.ImageData)a; using (Bitmap b = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Pdf2ImageResolutionRatio, r.Y / Settings.Constants.Pdf2ImageResolutionRatio, r.Width / Settings.Constants.Pdf2ImageResolutionRatio, r.Height / Settings.Constants.Pdf2ImageResolutionRatio)) { if (b == null) { throw new Exception("Selected image is empty."); } id.Image = new ImageData(b); } } break; case Template.Anchor.Types.CvImage: { Template.Anchor.CvImage ci = (Template.Anchor.CvImage)a; using (Bitmap b = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Pdf2ImageResolutionRatio, r.Y / Settings.Constants.Pdf2ImageResolutionRatio, r.Width / Settings.Constants.Pdf2ImageResolutionRatio, r.Height / Settings.Constants.Pdf2ImageResolutionRatio)) { if (b == null) { throw new Exception("Selected image is empty."); } ci.Image = new CvImage(b); } } break; default: throw new Exception("Unknown option: " + a.Type); } setAnchorRow(currentAnchorControl.Row, a); clearImageFromBoxes(); findAndDrawAnchor(a.Id); } finally { anchors.EndEdit(); } } break; case SettingModes.SetField: { if (fields.SelectedRows.Count < 1) { break; } var row = fields.SelectedRows[0]; Template.Field f = (Template.Field)row.Tag; f.Rectangle = r; if (f.LeftAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.LeftAnchor.Id); f.LeftAnchor.Shift = aai.Shift.Width; } if (f.TopAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.TopAnchor.Id); f.TopAnchor.Shift = aai.Shift.Height; } if (f.RightAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.RightAnchor.Id); f.RightAnchor.Shift = aai.Shift.Width; } if (f.BottomAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.BottomAnchor.Id); f.BottomAnchor.Shift = aai.Shift.Height; } setFieldRow(row, f); } break; case SettingModes.NULL: break; default: throw new Exception("Unknown option: " + settingMode); } } catch (Exception ex) { Message.Error2(ex, this); } }; Shown += delegate { Application.DoEvents();//make form be drawn completely setUIFromTemplate(templateManager.Template); }; this.EnumControls((Control c) => { if (c is SplitContainer s) { s.BackColor = Color.FromArgb(80, 70, 0); s.SplitterWidth = 2; s.Panel1.BackColor = SystemColors.Control; s.Panel2.BackColor = SystemColors.Control; } }, true); testFile.TextChanged += delegate { try { dispose(false); if (string.IsNullOrWhiteSpace(testFile.Text)) { return; } templateManager.LastTestFile = testFile.Text; testFile.SelectionStart = testFile.Text.Length; testFile.ScrollToCaret(); if (!File.Exists(testFile.Text)) { string m = "File '" + testFile.Text + "' does not exist!"; Log.Error(m); Message.Error(m, this); return; } pages = new PageCollection(testFile.Text, true); totalPageNumber = pages.TotalCount; lTotalPages.Text = " / " + totalPageNumber; showPage(1); } catch (Exception ex) { Log.Error(ex); Message.Error(ex, this); } }; pictureScale.ValueChanged += delegate { if (!loadingTemplate) { setScaledImage(); } }; Load += delegate { //Application.DoEvents();//make form be drawn completely //BeginInvoke((Action<Template>)setUIFromTemplate, templateManager.Template); }; FormClosed += delegate { bitmapPreparationForm.Close(); }; bSave.Click += Save_Click; bOK.Click += OK_Click; bCancel.Click += delegate { Close(); }; Help.LinkClicked += Help_LinkClicked; Configure.LinkClicked += Configure_LinkClicked; About.LinkClicked += About_LinkClicked; bTestFile.Click += delegate(object sender, EventArgs e) { OpenFileDialog d = new OpenFileDialog(); if (!string.IsNullOrWhiteSpace(testFile.Text)) { d.InitialDirectory = PathRoutines.GetFileDir(testFile.Text); } else if (!string.IsNullOrWhiteSpace(templateManager.TestFileDefaultFolder)) { d.InitialDirectory = templateManager.TestFileDefaultFolder; } d.Filter = "PDF|*.pdf|" + "All files (*.*)|*.*"; if (d.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } testFile.Text = d.FileName; }; ShowPdfText.LinkClicked += ShowPdfText_LinkClicked; ShowOcrText.LinkClicked += ShowOcrText_LinkClicked; ShowAsJson.LinkClicked += showAsJson_LinkClicked; tCurrentPage.Leave += delegate { changeCurrentPage(); }; tCurrentPage.KeyDown += delegate(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { changeCurrentPage(); } }; }
void initializeFieldsTable() { LeftAnchorId.ValueType = typeof(int); LeftAnchorId.ValueMember = "Id"; LeftAnchorId.DisplayMember = "Name"; TopAnchorId.ValueType = typeof(int); TopAnchorId.ValueMember = "Id"; TopAnchorId.DisplayMember = "Name"; RightAnchorId.ValueType = typeof(int); RightAnchorId.ValueMember = "Id"; RightAnchorId.DisplayMember = "Name"; BottomAnchorId.ValueType = typeof(int); BottomAnchorId.ValueMember = "Id"; BottomAnchorId.DisplayMember = "Name"; Type.ValueType = typeof(Template.Field.Types); Type.DataSource = Enum.GetValues(typeof(Template.Field.Types)); Value.DefaultCellStyle.NullValue = null; //to avoid error when changing cell type to image fields.EnableHeadersVisualStyles = false; //needed to set row headers fields.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { DataGridViewRow r = fields.Rows[e.RowIndex]; Message.Error("Field[row=" + r.Index + "] has unacceptable value of " + fields.Columns[e.ColumnIndex].HeaderText + ":\r\n" + e.Exception.Message, this); }; fields.UserDeletingRow += delegate(object sender, DataGridViewRowCancelEventArgs e) { if (fields.Rows.Count < 3 && fields.SelectedRows.Count > 0) { fields.SelectedRows[0].Selected = false;//to avoid auto-creating row } }; fields.UserDeletedRow += delegate(object sender, DataGridViewRowEventArgs e) { }; fields.PreviewKeyDown += delegate(object sender, PreviewKeyDownEventArgs e) { switch (e.KeyCode) { case Keys.Add: case Keys.Oemplus: duplicateSelectedField(); break; case Keys.Delete: case Keys.OemMinus: deleteSelectedField(); break; case Keys.Up: if (e.Modifiers == Keys.Control) { moveUpSelectedField(); } break; case Keys.Down: if (e.Modifiers == Keys.Control) { moveDownSelectedField(); } break; } }; fields.RowsAdded += delegate(object sender, DataGridViewRowsAddedEventArgs e) { }; fields.CellValueChanged += delegate(object sender, DataGridViewCellEventArgs e) { try { if (loadingTemplate) { return; } if (e.ColumnIndex < 0)//row's header { return; } DataGridViewRow row = fields.Rows[e.RowIndex]; var cs = row.Cells; Template.Field f = (Template.Field)row.Tag; switch (fields.Columns[e.ColumnIndex].Name) { case "Type": { Template.Field.Types t2 = (Template.Field.Types)row.Cells["Type"].Value; if (t2 == f.Type) { break; } string s = Serialization.Json.Serialize(f); switch (t2) { case Template.Field.Types.PdfText: f = Serialization.Json.Deserialize <Template.Field.PdfText>(s); break; case Template.Field.Types.PdfTextLines: f = Serialization.Json.Deserialize <Template.Field.PdfTextLines>(s); break; case Template.Field.Types.PdfCharBoxs: f = Serialization.Json.Deserialize <Template.Field.PdfCharBoxs>(s); break; case Template.Field.Types.OcrText: f = Serialization.Json.Deserialize <Template.Field.OcrText>(s); break; case Template.Field.Types.OcrTextLines: f = Serialization.Json.Deserialize <Template.Field.OcrTextLines>(s); break; case Template.Field.Types.OcrCharBoxs: f = Serialization.Json.Deserialize <Template.Field.OcrCharBoxs>(s); break; case Template.Field.Types.OcrTextLineImages: f = Serialization.Json.Deserialize <Template.Field.OcrTextLineImages>(s); break; case Template.Field.Types.Image: f = Serialization.Json.Deserialize <Template.Field.Image>(s); break; default: throw new Exception("Unknown option: " + t2); } setFieldRow(row, f); foreach (DataGridViewRow rr in fields.Rows) { if (rr != row && rr.Tag != null && ((Template.Field)rr.Tag).Name == f.Name) { rr.Cells["Type"].Value = t2; } } break; } case "LeftAnchorId": { int?ai = (int?)cs["LeftAnchorId"].Value; if (ai == null) { f.LeftAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.LeftAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Width, }; } setFieldRow(row, f); } break; case "TopAnchorId": { int?ai = (int?)cs["TopAnchorId"].Value; if (ai == null) { f.TopAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.TopAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Height, }; } setFieldRow(row, f); } break; case "RightAnchorId": { int?ai = (int?)cs["RightAnchorId"].Value; if (ai == null) { f.RightAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.RightAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Width, }; } setFieldRow(row, f); } break; case "BottomAnchorId": { int?ai = (int?)cs["BottomAnchorId"].Value; if (ai == null) { f.BottomAnchor = null; } else { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo((int)ai); f.BottomAnchor = new Template.Field.SideAnchor { Id = (int)ai, Shift = aai.Shift.Height, }; } setFieldRow(row, f); } break; case "Name_": f.Name = (string)row.Cells["Name_"].Value; break; } } catch (Exception ex) { Message.Error2(ex, this); } }; fields.CurrentCellDirtyStateChanged += delegate { if (fields.IsCurrentCellDirty) { fields.CommitEdit(DataGridViewDataErrorContexts.Commit); } }; fields.RowValidating += delegate(object sender, DataGridViewCellCancelEventArgs e) { DataGridViewRow r = fields.Rows[e.RowIndex]; try { if (r.Tag != null) { string n = FieldPreparation.Normalize((string)r.Cells["Name_"].Value); if (string.IsNullOrWhiteSpace(n)) { throw new Exception("Field name cannot be empty!"); } //foreach (DataGridViewRow rr in fields.Rows) //{ // if (r == rr) // continue; // Template.Field f = (Template.Field)rr.Tag; // if (f != null && n == f.Name) // throw new Exception("Name '" + n + "' is duplicated!"); //} r.Cells["Name_"].Value = n; } } catch (Exception ex) { Message.Error2(ex, this); e.Cancel = true; } }; fields.DefaultValuesNeeded += delegate(object sender, DataGridViewRowEventArgs e) { }; fields.CellContentClick += delegate(object sender, DataGridViewCellEventArgs e) { }; fields.SelectionChanged += delegate(object sender, EventArgs e) { try { if (loadingTemplate) { return; } if (settingCurrentFieldRow) { return; } if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow row = fields.SelectedRows[0]; Template.Field f = (Template.Field)row.Tag; if (f == null)//hacky forcing to commit a newly added row and display the blank row { int i = fields.Rows.Add(); row = fields.Rows[i]; f = templateManager.CreateDefaultField(); setFieldRow(row, f); row.Selected = true; return; } setCurrentFieldRow(row); } catch (Exception ex) { Log.Error(ex); Message.Error(ex, this); } }; copy2ClipboardField.LinkClicked += delegate { if (pages == null) { return; } if (fields.SelectedRows.Count < 1) { return; } DataGridViewRow r = fields.SelectedRows[fields.SelectedRows.Count - 1]; if (r.Tag == null) { return; } Template.Field f = (Template.Field)r.Tag; Type type = f.GetType(); switch (type) { case Type _ when f is Template.Field.Text: Clipboard.SetText(pages[currentPageI].GetText(f.Name)); break; case Type _ when f is Template.Field.TextLines: Clipboard.SetText(string.Join("\r\n", pages[currentPageI].GetTextLines(f.Name))); break; case Type _ when f is Template.Field.CharBoxs: Clipboard.SetText(Serialization.Json.Serialize(pages[currentPageI].GetCharBoxes(f.Name))); break; case Type _ when f is Template.Field.Image: Clipboard.SetData(DataFormats.Bitmap, pages[currentPageI].GetImage(f.Name)); break; case Type _ when f is Template.Field.OcrTextLineImages: Clipboard.SetData(typeof(List <Bitmap>).ToString(), pages[currentPageI].GetOcrTextLineImages(f.Name)); break; default: throw new Exception("Unknown option: " + f.Type); } }; duplicateField.LinkClicked += delegate { duplicateSelectedField(); }; //duplicateField.LinkClicked += delegate //{ // if (fields.SelectedRows.Count < 1) // return; // DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; // if (r0.Tag == null) // return; // Template.Field f0 = (Template.Field)r0.Tag; // if (f0.ColumnOfTable != null) // { // Message.Exclaim("This field is a column of table " + f0.ColumnOfTable + " so you should create a new definition of it."); // return; // } // List<DataGridViewRow> cloningFieldRows = new List<DataGridViewRow> { r0 }; // //foreach (DataGridViewRow r in fields.Rows) // // if (r != r0 && (r.Tag as Template.Field)?.ColumnOfTable == f0.Name) // // { // // string fn = (r.Tag as Template.Field)?.Name; // // if (cloningFieldRows.Find(x => (x.Tag as Template.Field)?.Name == fn) == null) // // cloningFieldRows.Add(r); // // } // settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes // foreach (DataGridViewRow row in cloningFieldRows) // { // Template.Field f = (Template.Field)Serialization.Json.Clone(((Template.Field)row.Tag).GetType(), row.Tag); // f.LeftAnchor = null; // f.TopAnchor = null; // f.RightAnchor = null; // f.BottomAnchor = null; // int i = fields.Rows.Add(); // DataGridViewRow r = fields.Rows[i]; // setFieldRow(r, f); // fields.Rows.Remove(r); // fields.Rows.Insert(row.Index + 1, r); // } // settingCurrentFieldRow = false; //}; deleteField.LinkClicked += delegate { deleteSelectedField(); }; //deleteField.LinkClicked += delegate //{ // if (fields.SelectedRows.Count < 1) // return; // DataGridViewRow r0 = fields.SelectedRows[fields.SelectedRows.Count - 1]; // if (r0.Tag == null) // return; // Template.Field f0 = (Template.Field)r0.Tag; // bool unique = true; // foreach (DataGridViewRow rr in fields.Rows) // if (rr != r0 && rr.Tag != null && ((Template.Field)rr.Tag).Name == f0.Name) // { // unique = false; // break; // } // if (unique) // { // Message.Inform("This field definition cannot be deleted because it is the last of the field."); // return; // } // if (f0.ColumnOfTable != null) // { // Message.Exclaim("This field is a column of table " + f0.ColumnOfTable + " so you should delete the respectivea definition of it."); // return; // } // Dictionary<string, List<DataGridViewRow>> fieldName2orderedRows = new Dictionary<string, List<DataGridViewRow>>(); // foreach (DataGridViewRow r in fields.Rows) // if ((r.Tag as Template.Field.PdfText)?.ColumnOfTable == f0.Name) // { // List<DataGridViewRow> rs; // string fn = (r.Tag as Template.Field)?.Name; // if (!fieldName2orderedRows.TryGetValue(fn, out rs)) // { // rs = new List<DataGridViewRow>(); // fieldName2orderedRows[fn] = rs; // } // rs.Add(r); // } // int definitionIndex = fieldName2orderedRows[f0.Name].IndexOf(r0); // fieldName2orderedRows.Remove(f0.Name); // List<DataGridViewRow> deletingFieldRows = new List<DataGridViewRow> { r0 }; // foreach (List<DataGridViewRow> rs in fieldName2orderedRows.Values) // deletingFieldRows.Add(rs[definitionIndex]); // settingCurrentFieldRow = true;//required due to fields-column error calculation when selected row changes // foreach (DataGridViewRow row in deletingFieldRows) // fields.Rows.Remove(row); // settingCurrentFieldRow = false; //}; moveUpField.LinkClicked += delegate { moveUpSelectedField(); }; moveDownField.LinkClicked += delegate { moveDownSelectedField(); }; newField.LinkClicked += delegate { createNewField(); }; }
public TemplateForm(TemplateManager templateManager) { InitializeComponent(); Icon = Win.AssemblyRoutines.GetAppIcon(); Text = Program.FullName + ": Template Editor"; this.templateManager = templateManager; initializeAnchorsTable(); initializeConditionsTable(); initializeFieldsTable(); picture.MouseDown += delegate(object sender, MouseEventArgs e) { if (pages == null) { return; } Point p = new Point((int)(e.X / (float)pictureScale.Value), (int)(e.Y / (float)pictureScale.Value)); ResizebleBox rb = findResizebleBox(p, out ResizebleBoxSides resizebleBoxSide); if (rb != null) { drawingMode = resizebleBoxSide == ResizebleBoxSides.Left || resizebleBoxSide == ResizebleBoxSides.Right ? DrawingModes.resizingSelectionBoxV : DrawingModes.resizingSelectionBoxH; Cursor.Current = drawingMode == DrawingModes.resizingSelectionBoxV ? Cursors.VSplit : Cursors.HSplit; selectionBoxPoint0 = rb.R.Location; selectionBoxPoint1 = rb.R.Location; selectionBoxPoint2 = new Point(rb.R.Right, rb.R.Bottom); } else { drawingMode = DrawingModes.drawingSelectionBox; selectionBoxPoint0 = p; selectionBoxPoint1 = p; selectionBoxPoint2 = p; } selectionCoordinates.Text = selectionBoxPoint1.ToString(); }; picture.MouseMove += delegate(object sender, MouseEventArgs e) { if (pages == null) { return; } Point p = new Point((int)(e.X / (float)pictureScale.Value), (int)(e.Y / (float)pictureScale.Value)); switch (drawingMode) { case DrawingModes.NULL: selectionCoordinates.Text = p.ToString(); if (findResizebleBox(p, out ResizebleBoxSides resizebleBoxSide) != null) { Cursor.Current = resizebleBoxSide == ResizebleBoxSides.Left || resizebleBoxSide == ResizebleBoxSides.Right ? Cursors.VSplit : Cursors.HSplit; } else { Cursor.Current = Cursors.Default; } return; case DrawingModes.drawingSelectionBox: if (selectionBoxPoint0.X < p.X) { selectionBoxPoint1.X = selectionBoxPoint0.X; selectionBoxPoint2.X = p.X; } else { selectionBoxPoint1.X = p.X; selectionBoxPoint2.X = selectionBoxPoint0.X; } if (selectionBoxPoint0.Y < p.Y) { selectionBoxPoint1.Y = selectionBoxPoint0.Y; selectionBoxPoint2.Y = p.Y; } else { selectionBoxPoint1.Y = p.Y; selectionBoxPoint2.Y = selectionBoxPoint0.Y; } break; case DrawingModes.resizingSelectionBoxV: if (Math.Abs(selectionBoxPoint2.X - p.X) < Math.Abs(p.X - selectionBoxPoint1.X)) { selectionBoxPoint2.X = p.X; } else { selectionBoxPoint1.X = p.X; } break; case DrawingModes.resizingSelectionBoxH: if (Math.Abs(selectionBoxPoint2.Y - p.Y) < Math.Abs(p.Y - selectionBoxPoint1.Y)) { selectionBoxPoint2.Y = p.Y; } else { selectionBoxPoint1.Y = p.Y; } break; } selectionCoordinates.Text = selectionBoxPoint1.ToString() + ":" + selectionBoxPoint2.ToString(); RectangleF r = new RectangleF(selectionBoxPoint1.X, selectionBoxPoint1.Y, selectionBoxPoint2.X - selectionBoxPoint1.X, selectionBoxPoint2.Y - selectionBoxPoint1.Y); clearImageFromBoxes(); drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <System.Drawing.RectangleF> { r }); }; picture.MouseUp += delegate(object sender, MouseEventArgs e) { try { if (pages == null) { return; } if (drawingMode == DrawingModes.NULL) { return; } drawingMode = DrawingModes.NULL; Template.RectangleF r = new Template.RectangleF(selectionBoxPoint1.X, selectionBoxPoint1.Y, selectionBoxPoint2.X - selectionBoxPoint1.X, selectionBoxPoint2.Y - selectionBoxPoint1.Y); if (r.Width == 0 || r.Y == 0)//accidental tap { return; } switch (settingMode) { case SettingModes.SetAnchor: { if (currentAnchorControl == null) { break; } currentAnchorControl.SetTagFromControl(); Template.Anchor a = (Template.Anchor)currentAnchorControl.Row.Tag; a.Position = new Template.PointF { X = r.X, Y = r.Y }; try { switch (a.Type) { case Template.Anchor.Types.PdfText: { Template.Anchor.PdfText pt = (Template.Anchor.PdfText)a; pt.CharBoxs = new List <Template.Anchor.PdfText.CharBox>(); List <Pdf.Line> lines = Pdf.GetLines(Pdf.GetCharBoxsSurroundedByRectangle(pages[currentPageI].PdfCharBoxs, r.GetSystemRectangleF(), true), null); foreach (Pdf.Line l in lines) { foreach (Pdf.CharBox cb in l.CharBoxs) { pt.CharBoxs.Add(new Template.Anchor.PdfText.CharBox { Char = cb.Char, Rectangle = new Template.RectangleF(cb.R.X, cb.R.Y, cb.R.Width, cb.R.Height), }); } } pt.Size = new Template.SizeF { Width = r.Width, Height = r.Height }; } break; case Template.Anchor.Types.OcrText: { Template.Anchor.OcrText ot = (Template.Anchor.OcrText)a; ot.CharBoxs = new List <Template.Anchor.OcrText.CharBox>(); var selectedOcrCharBoxs = new List <Ocr.CharBox>(); if (ot.OcrEntirePage) { selectedOcrCharBoxs.AddRange(Ocr.GetCharBoxsSurroundedByRectangle(pages[currentPageI].ActiveTemplateOcrCharBoxs, r.GetSystemRectangleF())); } else { foreach (Ocr.CharBox cb in Ocr.This.GetCharBoxs(pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Image2PdfResolutionRatio, r.Y / Settings.Constants.Image2PdfResolutionRatio, r.Width / Settings.Constants.Image2PdfResolutionRatio, r.Height / Settings.Constants.Image2PdfResolutionRatio))) { cb.R.X += r.X; cb.R.Y += r.Y; selectedOcrCharBoxs.Add(cb); } } foreach (Ocr.Line l in Ocr.GetLines(selectedOcrCharBoxs, null)) { foreach (Ocr.CharBox cb in l.CharBoxs) { ot.CharBoxs.Add(new Template.Anchor.OcrText.CharBox { Char = cb.Char, Rectangle = new Template.RectangleF(cb.R.X, cb.R.Y, cb.R.Width, cb.R.Height), }); } } ot.Size = new Template.SizeF { Width = r.Width, Height = r.Height }; } break; case Template.Anchor.Types.ImageData: { Template.Anchor.ImageData id = (Template.Anchor.ImageData)a; using (Bitmap b = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Image2PdfResolutionRatio, r.Y / Settings.Constants.Image2PdfResolutionRatio, r.Width / Settings.Constants.Image2PdfResolutionRatio, r.Height / Settings.Constants.Image2PdfResolutionRatio)) { id.Image = new ImageData(b); } } break; case Template.Anchor.Types.CvImage: { Template.Anchor.CvImage ci = (Template.Anchor.CvImage)a; using (Bitmap b = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Image2PdfResolutionRatio, r.Y / Settings.Constants.Image2PdfResolutionRatio, r.Width / Settings.Constants.Image2PdfResolutionRatio, r.Height / Settings.Constants.Image2PdfResolutionRatio)) { ci.Image = new CvImage(b); } } break; default: throw new Exception("Unknown option: " + a.Type); } setAnchorRow(currentAnchorControl.Row, a); clearImageFromBoxes(); findAndDrawAnchor(a.Id); } finally { anchors.EndEdit(); } } break; case SettingModes.SetField: { if (fields.SelectedRows.Count < 1) { break; } var row = fields.SelectedRows[0]; Template.Field f = (Template.Field)row.Tag; f.Rectangle = r; if (f.LeftAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.LeftAnchor.Id); f.LeftAnchor.Shift = aai.Shift.Width; } if (f.TopAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.TopAnchor.Id); f.TopAnchor.Shift = aai.Shift.Height; } if (f.RightAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.RightAnchor.Id); f.RightAnchor.Shift = aai.Shift.Width; } if (f.BottomAnchor != null) { Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(f.BottomAnchor.Id); f.BottomAnchor.Shift = aai.Shift.Height; } setFieldRow(row, f); extractFieldAndDrawSelectionBox(f); //owners2resizebleBox[f] = new ResizebleBox(f, f.Rectangle.GetSystemRectangleF(), Settings.Appearance.SelectionBoxBorderWidth); } break; case SettingModes.NULL: break; default: throw new Exception("Unknown option: " + settingMode); } } catch (Exception ex) { Message.Error2(ex); } }; Shown += delegate { Application.DoEvents();//make form be drawn completely setUIFromTemplate(templateManager.Template); }; FormClosed += delegate { if (scaledCurrentPageBitmap != null) { scaledCurrentPageBitmap.Dispose(); scaledCurrentPageBitmap = null; } if (pages != null) { pages.Dispose(); pages = null; } templateManager.LastTestFile = testFile.Text; }; this.EnumControls((Control c) => { if (c is SplitContainer s) { s.BackColor = Color.FromArgb(80, 70, 0); s.SplitterWidth = 2; s.Panel1.BackColor = SystemColors.Control; s.Panel2.BackColor = SystemColors.Control; } }, true); testFile.TextChanged += delegate { try { if (picture.Image != null) { picture.Image.Dispose(); picture.Image = null; } if (scaledCurrentPageBitmap != null) { scaledCurrentPageBitmap.Dispose(); scaledCurrentPageBitmap = null; } if (pages != null) { pages.Dispose(); pages = null; } if (string.IsNullOrWhiteSpace(testFile.Text)) { return; } testFile.SelectionStart = testFile.Text.Length; testFile.ScrollToCaret(); if (!File.Exists(testFile.Text)) { Win.LogMessage.Error("File '" + testFile.Text + "' does not exist!"); return; } pages = new PageCollection(testFile.Text); totalPageNumber = pages.PdfReader.NumberOfPages; lTotalPages.Text = " / " + totalPageNumber; showPage(1); } catch (Exception ex) { Win.LogMessage.Error(ex); } }; pictureScale.ValueChanged += delegate { if (!loadingTemplate) { setScaledImage(); } }; pageRotation.SelectedIndexChanged += delegate { reloadPageBitmaps(); //showPage(currentPageI); }; autoDeskew.CheckedChanged += delegate { reloadPageBitmaps(); //showPage(currentPageI); }; Load += delegate { }; save.Click += Save_Click; cancel.Click += delegate { Close(); }; Help.LinkClicked += Help_LinkClicked; Configure.LinkClicked += Configure_LinkClicked; About.LinkClicked += About_LinkClicked; bTestFile.Click += delegate(object sender, EventArgs e) { OpenFileDialog d = new OpenFileDialog(); if (!string.IsNullOrWhiteSpace(testFile.Text)) { d.InitialDirectory = PathRoutines.GetFileDir(testFile.Text); } else if (!string.IsNullOrWhiteSpace(templateManager.TestFileDefaultFolder)) { d.InitialDirectory = templateManager.TestFileDefaultFolder; } d.Filter = "PDF|*.pdf|" + "All files (*.*)|*.*"; if (d.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } testFile.Text = d.FileName; }; ShowPdfText.LinkClicked += ShowPdfText_LinkClicked; ShowOcrText.LinkClicked += ShowOcrText_LinkClicked; ShowAsJson.LinkClicked += showAsJson_LinkClicked; tCurrentPage.Leave += delegate { changeCurrentPage(); }; tCurrentPage.KeyDown += delegate(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { changeCurrentPage(); } }; }
object extractFieldAndDrawSelectionBox(Template.Field field) { try { if (pages == null) { return(null); } if (field.Rectangle == null) { return(null); } pages.ActiveTemplate = getTemplateFromUI(false); RectangleF r = field.Rectangle.GetSystemRectangleF(); if (field.LeftAnchor != null) { if (!findAndDrawAnchor(field.LeftAnchor.Id)) { return(null); } Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(field.LeftAnchor.Id); float right = r.Right; r.X += aai.Shift.Width - field.LeftAnchor.Shift; r.Width = right - r.X; } if (field.TopAnchor != null) { if (!findAndDrawAnchor(field.TopAnchor.Id)) { return(null); } Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(field.TopAnchor.Id); float bottom = r.Bottom; r.Y += aai.Shift.Height - field.TopAnchor.Shift; r.Height = bottom - r.Y; } if (field.RightAnchor != null) { if (!findAndDrawAnchor(field.RightAnchor.Id)) { return(null); } Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(field.RightAnchor.Id); r.Width += aai.Shift.Width - field.RightAnchor.Shift; } if (field.BottomAnchor != null) { if (!findAndDrawAnchor(field.BottomAnchor.Id)) { return(null); } Page.AnchorActualInfo aai = pages[currentPageI].GetAnchorActualInfo(field.BottomAnchor.Id); r.Height += aai.Shift.Height - field.BottomAnchor.Shift; } if (r.Width <= 0 || r.Height <= 0) { return(null); } owners2resizebleBox[field] = new ResizebleBox(field, r, Settings.Appearance.SelectionBoxBorderWidth); switch (field.Type) { case Template.Field.Types.PdfText: string s; if (field.ColumnOfTable != null) { //RectangleF? tr = pages[currentPageI].GetTableActualRectangle((Template.Field.PdfText)field); int fieldDefinitionIndex = pages.ActiveTemplate.Fields.Where(x => x.Name == field.Name).TakeWhile(x => x != field).Count(); Template.Field tableField; try { tableField = pages.ActiveTemplate.Fields.Where(x => x.Name == field.ColumnOfTable).ElementAt(fieldDefinitionIndex); } catch (Exception e) { Message.Error("Field " + field.ColumnOfTable + " does not have enough definitions to respect definition " + field.Name + "[" + fieldDefinitionIndex + "]"); return(null); } RectangleF?tr = pages[currentPageI].GetFieldActualRectange(tableField); if (tr == null) { return(null); } drawBoxes(Settings.Appearance.TableBoxColor, Settings.Appearance.TableBoxBorderWidth, new List <RectangleF> { (RectangleF)tr }); //return Page.NormalizeText(Pdf.GetTextSurroundedByRectangle(pages[currentPageI].PdfCharBoxs, r, pages.ActiveTemplate.TextAutoInsertSpaceThreshold, pages.ActiveTemplate.TextAutoInsertSpaceSubstitute)); s = string.Join("\r\n", pages[currentPageI].GetTextLinesAsTableColumn(field, r)); } else { s = Pdf.GetTextSurroundedByRectangle(pages[currentPageI].PdfCharBoxs, r, pages.ActiveTemplate.TextAutoInsertSpace); } drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <RectangleF> { r }); return(Page.NormalizeText(s)); case Template.Field.Types.OcrText: drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <RectangleF> { r }); return(Page.NormalizeText(Ocr.This.GetTextSurroundedByRectangle(pages[currentPageI].ActiveTemplateBitmap, r))); case Template.Field.Types.ImageData: drawBoxes(Settings.Appearance.SelectionBoxColor, Settings.Appearance.SelectionBoxBorderWidth, new List <RectangleF> { r }); using (Bitmap rb = pages[currentPageI].GetRectangleFromActiveTemplateBitmap(r.X / Settings.Constants.Image2PdfResolutionRatio, r.Y / Settings.Constants.Image2PdfResolutionRatio, r.Width / Settings.Constants.Image2PdfResolutionRatio, r.Height / Settings.Constants.Image2PdfResolutionRatio)) { return(ImageData.GetScaled(rb, Settings.Constants.Image2PdfResolutionRatio)); } default: throw new Exception("Unknown option: " + field.Type); } } catch (Exception ex) { //Log.Message.Error("Rectangle", ex); Log.Message.Error(ex); } return(null); }