BioGTK  6.5.0
A .NET library & program for annotating, editing various microscopy imaging formats using Bioformats supported images. Including whole slide, pyramidal, and series.
Loading...
Searching...
No Matches
Tools.cs
1using AForge;
2using AForge.Imaging;
3using AForge.Imaging.Filters;
4using Bio;
5using Bio.Graphics;
6using Cairo;
7using CSScripting;
8using Gdk;
9using Gtk;
10using ScottPlot.Rendering;
11using System;
12using System.Collections.Generic;
13using System.Linq;
14using Color = Cairo.Color;
15using PointD = AForge.PointD;
16using Rectangle = AForge.Rectangle;
17namespace BioGTK
18{
22 public class Tools : Gtk.Window
23 {
24
25#pragma warning disable 649
26
27 [Builder.Object]
28 private Gtk.DrawingArea view;
29#pragma warning restore 649
30 private AForge.Color selectColor;
31 private Builder _builder;
36 public static Tools Create()
37 {
38 Builder builder = new Builder(new FileStream(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "/" + "Glade/Tools.glade", FileMode.Open));
39 return new Tools(builder, builder.GetObject("tools").Handle);
40 }
41 /* Initializing the tools. */
42 protected Tools(Builder builder, IntPtr handle) : base(handle)
43 {
44 selectColor = AForge.Color.FromArgb(0, 0, 150, 255);
45 AForge.Color white = AForge.Color.FromArgb(255, 255, 255, 255);
46 _builder = builder;
47 builder.Autoconnect(this);
49 Tool.Init();
50 ColorS col = new ColorS(ushort.MaxValue);
51 //We initialize the tools
52 currentTool = GetTool(Tool.Type.move.ToString());
53 floodFiller = new QueueLinearFloodFiller(floodFiller);
54 magicSelect = MagicSelect.Create(0);
55 App.ApplyStyles(this);
56 }
57 public static bool applyToStack = false;
58 public static ColorTool colorTool;
59 public static bool rEnabled = true;
60 public static bool gEnabled = true;
61 public static bool bEnabled = true;
62 public static ColorS drawColor = new ColorS(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue);
63 public static ColorS eraseColor = new ColorS(0, 0, 0);
64 public static ColorS tolerance = new ColorS(0, 0, 0);
65 private static MagicSelect magicSelect;
66 private static int width = 5;
67 private static ROI roi;
68 public static ROI selectedROI
69 {
70 get
71 {
72 List<ROI> rs = new List<ROI>();
73 foreach (var item in ImageView.SelectedImage.Annotations)
74 {
75 if (item.Selected)
76 rs.Add(item);
77 }
78 if (rs.Count > 0)
79 roi = rs[0];
80 return roi;
81 }
82 set
83 {
84 roi = value;
85 }
86 }
87 public static Rectangle selectionRectangle;
88 public static Dictionary<string, Tool> tools = new Dictionary<string, Tool>();
89 private static AbstractFloodFiller floodFiller = null;
90 static List<ROI> rois = new List<ROI>();
91 /* Creating a new ROI object called selectedROI. */
92 public static List<ROI> selectedROIs
93 {
94 get
95 {
96 rois.Clear();
97 for (int i = 0; i < Images.images.Count; i++)
98 {
99 for (int r = 0; r < Images.images[i].Annotations.Count; r++)
100 {
101 if (Images.images[i].Annotations[r].Selected)
102 rois.Add(Images.images[i].Annotations[r]);
103 }
104 }
105 return rois;
106 }
107 set
108 {
109 rois.Clear();
110 rois.AddRange(value);
111 }
112 }
113 void AddROI(ROI roi)
114 {
115 if (ImageView.SelectedImage.isPyramidal)
116 roi.serie = App.viewer.Level;
117 else
118 roi.serie = ImageView.SelectedImage.series;
119 roi.coord = App.viewer.GetCoordinate();
120 ImageView.SelectedImage.Annotations.Add(roi);
121 }
124 protected void SetupHandlers()
125 {
126 this.ButtonPressEvent += Tools_ButtonPressEvent;
127 ti = TextInput.Create();
128 view.Drawn += View_Drawn;
129 view.DeleteEvent += View_DeleteEvent;
130 }
131 private void View_DeleteEvent(object o, DeleteEventArgs args)
132 {
133 this.Hide();
134 args.RetVal = true;
135 }
136
137 static int gridW = 2;
138 static int gridH = 11;
139
140 static List<Rectangle> rects = new List<Rectangle>();
145 private void View_Drawn(object o, DrawnArgs e)
146 {
147 int w = 33;
148 int h = 33;
149 int x = 0;
150 int y = 0;
151 foreach (Tool item in tools.Values)
152 {
153 if (item.image != null)
154 {
155 e.Cr.LineWidth = 2;
156 Pixbuf pf = item.image.ScaleSimple(w, h, InterpType.Bilinear);
157 if (item.selected)
158 {
159 e.Cr.SetSourceRGB(item.color.Rf, item.color.Gf, item.color.Bf);
160 e.Cr.Rectangle(x * w, y * h, w, h);
161 e.Cr.Stroke();
162 }
163 Gdk.CairoHelper.SetSourcePixbuf(e.Cr, pf, w * x, h * y);
164 e.Cr.Paint();
165 e.Cr.Stroke();
166
167 }
168 else
169 {
170 e.Cr.SetSourceRGB(item.color.Rf, item.color.Gf, item.color.Bf);
171 e.Cr.Rectangle(x * w, y * h, w, h);
172 e.Cr.Fill();
173 e.Cr.Stroke();
174 }
175 if (x < gridW - 1)
176 {
177 x += 1;
178 }
179 else
180 {
181 y += 1;
182 x = 0;
183 }
184 }
185
186 }
187
193 private void Tools_ButtonPressEvent(object o, ButtonPressEventArgs args)
194 {
195 Gdk.Rectangle r = new Gdk.Rectangle((int)args.Event.X, (int)args.Event.Y, 1, 1);
196 Tool tool = null;
197 foreach (Tool t in tools.Values)
198 {
199 if (t.bounds.IntersectsWith(new AForge.PointD(args.Event.X, args.Event.Y)))
200 {
201 tool = t;
202 //if (selectedROI != null)
203 // selectedROI.Selected = false;
204 t.selected = true;
205 }
206 else
207 t.selected = false;
208 }
209 if (tool == null)
210 return;
211 currentTool = tool;
212 if (tool.type == Tool.Type.color1)
213 Color1Click();
214 if (tool.type == Tool.Type.color2)
215 Color2Click();
216 if (tool.type == Tool.Type.switchColors)
217 SwitchClick();
218 view.QueueDraw();
219 }
220 public static bool colorOne = true;
224 private void Color1Click()
225 {
226 if (App.color != null)
227 if (App.color.Visible)
228 return;
229 colorOne = true;
230 App.color = ColorTool.Create(false);
231 App.color.Show();
232 }
234 private void Color2Click()
235 {
236 if (App.color != null)
237 if (App.color.Visible)
238 return;
239 colorOne = false;
240 App.color = ColorTool.Create(true);
241 App.color.Show();
242 }
244 private void SwitchClick()
245 {
246 ColorS s = DrawColor;
247 DrawColor = EraseColor;
248 EraseColor = s;
249 }
250 private void UpdateView()
251 {
252 App.viewer.UpdateView();
253 }
254
255 // Normalize bounding box (makes W/H >= 0) and update ROI.Points to match corners
256 private void SyncPointsFromBoundingBox(ROI roi)
257 {
258 if (roi == null) return;
259 RectangleD r = roi.BoundingBox;
260
261 double left = Math.Min(r.X, r.X + r.W);
262 double top = Math.Min(r.Y, r.Y + r.H);
263 double right = Math.Max(r.X, r.X + r.W);
264 double bottom = Math.Max(r.Y, r.Y + r.H);
265
266 // update normalized bounding box
267 roi.BoundingBox = new RectangleD(left, top, right - left, bottom - top);
268
269 // Ensure Points list exists & has 4 corner points for rectangle/ellipse
270 if (roi.Points == null) roi.Points = new List<PointD>();
271
272 if (roi.Points.Count < 4)
273 {
274 roi.Points.Clear();
275 roi.Points.Add(new PointD(left, top)); // 0: TL
276 roi.Points.Add(new PointD(right, top)); // 1: TR
277 roi.Points.Add(new PointD(right, bottom)); // 2: BR
278 roi.Points.Add(new PointD(left, bottom)); // 3: BL
279 }
280 else
281 {
282 // Keep the index mapping consistent
283 roi.UpdatePoint(new PointD(left, top), 0);
284 roi.UpdatePoint(new PointD(right, top), 1);
285 roi.UpdatePoint(new PointD(right, bottom), 2);
286 roi.UpdatePoint(new PointD(left, bottom), 3);
287 }
288 }
289
290 // Recompute bounding box from the ROI points (useful after moving points)
291 private void SyncBoundingBoxFromPoints(ROI roi)
292 {
293 if (roi == null || roi.Points == null || roi.Points.Count == 0) return;
294
295 double minx = double.MaxValue, miny = double.MaxValue;
296 double maxx = double.MinValue, maxy = double.MinValue;
297
298 foreach (var p in roi.Points)
299 {
300 if (p.X < minx) minx = p.X;
301 if (p.Y < miny) miny = p.Y;
302 if (p.X > maxx) maxx = p.X;
303 if (p.Y > maxy) maxy = p.Y;
304 }
305
306 roi.BoundingBox = new RectangleD(minx, miny, maxx - minx, maxy - miny);
307 }
308
309
310 // -----------------------------
311 // Fixed tool implementations
312 // -----------------------------
313 public void ToolDown(PointD e, ButtonPressEventArgs buts)
314 {
315 if (App.viewer == null || currentTool == null || ImageView.SelectedImage == null)
316 return;
317
318 Plugins.MouseDown(ImageView.SelectedImage, e, buts);
319 Scripting.UpdateState(Scripting.State.GetDown(e, buts.Event.Button));
320
321 switch (currentTool.type)
322 {
323 case Tool.Type.pan:
324 ToolDown_Pan(e, buts);
325 break;
326 case Tool.Type.magic:
327 ToolDown_Magic(e, buts);
328 break;
329 case Tool.Type.point:
330 ToolDown_Point(e, buts);
331 break;
332 case Tool.Type.move:
333 ToolDown_Move(e, buts);
334 break;
335 case Tool.Type.line:
336 ToolDown_Line(e, buts);
337 break;
338 case Tool.Type.rect:
339 ToolDown_Rectangle(e, buts);
340 break;
341 case Tool.Type.ellipse:
342 ToolDown_Ellipse(e, buts);
343 break;
344 case Tool.Type.polygon:
345 ToolDown_Polygon(e, buts);
346 break;
347 case Tool.Type.text:
348 ToolDown_Text(e, buts);
349 break;
350 case Tool.Type.delete:
351 ToolDown_Delete(e, buts);
352 break;
353 case Tool.Type.freeform:
354 ToolDown_Freeform(e, buts);
355 break;
356 default:
357 break;
358 }
359 }
360
361 public void ToolUp(PointD e, ButtonReleaseEventArgs buts)
362 {
363 if (App.viewer == null || currentTool == null || ImageView.SelectedImage == null)
364 return;
365
366 Plugins.MouseUp(ImageView.SelectedImage, e, buts);
367 Scripting.UpdateState(Scripting.State.GetUp(e, buts.Event.Button));
368
369 switch (currentTool.type)
370 {
371 case Tool.Type.pan:
372 ToolUp_Pan(e, buts);
373 break;
374 case Tool.Type.move:
375 ToolUp_Move(e, buts);
376 break;
377 case Tool.Type.magic:
378 ToolUp_Magic(e, buts);
379 break;
380 case Tool.Type.line:
381 ToolUp_Line(e, buts);
382 break;
383 case Tool.Type.rect:
384 ToolUp_Rectangle(e, buts);
385 break;
386 case Tool.Type.ellipse:
387 ToolUp_Ellipse(e, buts);
388 break;
389 case Tool.Type.polygon:
390 ToolUp_Polygon(e, buts);
391 break;
392 case Tool.Type.text:
393 //ToolUp_Text(e, buts);
394 break;
395 case Tool.Type.delete:
396 //
397 break;
398 case Tool.Type.freeform:
399 ToolUp_Freeform(e, buts);
400 break;
401 case Tool.Type.bucket:
402 ToolUp_Bucket(e, buts);
403 break;
404 case Tool.Type.dropper:
405 ToolUp_Dropper(e, buts);
406 break;
407 default:
408 break;
409 }
410 }
411
412 public void ToolMove(PointD e, MotionNotifyEventArgs buts)
413 {
414 if (App.viewer == null)
415 return;
416
417 Plugins.MouseMove(ImageView.SelectedImage, e, buts);
418
419 // Update scripting state using available button masks
420 if (buts.Event.State.HasFlag(ModifierType.Button1Mask))
421 Scripting.UpdateState(Scripting.State.GetMove(e, 1));
422 else if (buts.Event.State.HasFlag(ModifierType.Button2Mask))
423 Scripting.UpdateState(Scripting.State.GetMove(e, 2));
424 else if (buts.Event.State.HasFlag(ModifierType.Button3Mask))
425 Scripting.UpdateState(Scripting.State.GetMove(e, 3));
426 else if (buts.Event.State.HasFlag(ModifierType.Button4Mask))
427 Scripting.UpdateState(Scripting.State.GetMove(e, 4));
428 else if (buts.Event.State.HasFlag(ModifierType.Button5Mask))
429 Scripting.UpdateState(Scripting.State.GetMove(e, 5));
430 else
431 Scripting.UpdateState(Scripting.State.GetMove(e, 0));
432
433 switch (currentTool.type)
434 {
435 case Tool.Type.pan:
436 ToolMove_Pan(e, buts);
437 break;
438 case Tool.Type.move:
439 ToolMove_Move(e, buts);
440 break;
441 case Tool.Type.magic:
442 ToolMove_Magic(e, buts);
443 break;
444 case Tool.Type.line:
445 ToolMove_Line(e, buts);
446 break;
447 case Tool.Type.rect:
448 ToolMove_Rectangle(e, buts);
449 break;
450 case Tool.Type.ellipse:
451 ToolMove_Ellipse(e, buts);
452 break;
453 case Tool.Type.polygon:
454 ToolMove_Polygon(e, buts);
455 break;
456 case Tool.Type.text:
457 //ToolMove_Text(e, buts);
458 break;
459 case Tool.Type.freeform:
460 ToolMove_Freeform(e, buts);
461 break;
462 case Tool.Type.brush:
463 ToolMove_Brush(e, buts);
464 break;
465 case Tool.Type.eraser:
466 ToolMove_Eraser(e, buts);
467 break;
468 default:
469 break;
470 }
471 }
472
473 // ============================================================================
474 // 1. MOVE TOOL - Selection and Dragging (fixed)
475 // ============================================================================
476 public void ToolDown_Move(PointD e, ButtonPressEventArgs buts)
477 {
478 if (currentTool.type != Tool.Type.move || buts.Event.Button != 1)
479 return;
480
481 App.viewer.MouseDown = e;
482 bool ctrl = buts.Event.State.HasFlag(ModifierType.ControlMask);
483
484 selectedROI = null;
485
486 // 1 — Vertex hit test on selected ROIs
487 foreach (var ann in ImageView.SelectedImage.Annotations)
488 {
489 if (ann == null || !ann.Selected) continue;
490
491 var boxes = ann.GetSelectBoxes(ROI.selectBoxSize * ImageView.SelectedImage.PhysicalSizeX);
492 if (boxes == null) continue;
493
494 for (int i = 0; i < boxes.Length; i++)
495 {
496 if (boxes[i].Contains(ann.coord, e))
497 {
498 selectedROI = ann;
499 if (ctrl)
500 {
501 if (ann.selectedPoints.Contains(i)) ann.selectedPoints.Remove(i);
502 else ann.selectedPoints.Add(i);
503 }
504 else
505 {
506 ann.selectedPoints.Clear();
507 ann.selectedPoints.Add(i);
508 }
509 UpdateView();
510 return;
511 }
512 }
513 }
514
515 // 2 — Click on body of already-selected ROI
516 foreach (var ann in ImageView.SelectedImage.Annotations)
517 {
518 if (ann != null && ann.Selected && ann.BoundingBox.Contains(ann.coord, e))
519 {
520 selectedROI = ann;
521 UpdateView();
522 return;
523 }
524 }
525
526 // 3 — Click on any ROI (select it)
527 foreach (var ann in ImageView.SelectedImage.Annotations)
528 {
529 if (ann != null && ann.BoundingBox.Contains(ann.coord, e))
530 {
531 if (!ctrl)
532 {
533 foreach (var other in ImageView.SelectedImage.Annotations)
534 {
535 if (other != ann)
536 {
537 other.Selected = false;
538 other.selectedPoints?.Clear();
539 }
540 }
541 }
542
543 ann.Selected = true;
544 ann.selectedPoints?.Clear();
545 selectedROI = ann;
546 UpdateView();
547 return;
548 }
549 }
550
551 // 4 — Start selection rectangle
552 if (!ctrl)
553 {
554 foreach (var ann in ImageView.SelectedImage.Annotations)
555 {
556 if (ann != null)
557 {
558 ann.Selected = false;
559 ann.selectedPoints?.Clear();
560 }
561 }
562 selectedROI = null;
563 }
564
565 Tools.GetTool(Tools.Tool.Type.move).Rectangle = new RectangleD(e.X, e.Y, 0, 0);
566 UpdateView();
567 }
568 public void ToolMove_Move(PointD e, MotionNotifyEventArgs buts)
569 {
570 if (currentTool.type != Tool.Type.move ||
571 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
572 return;
573
574 // Moving selected vertices/control points or ROIs
575 if (selectedROI != null && selectedROI.Selected && selectedROI.selectedPoints != null)
576 {
577 PointD delta = new PointD(e.X - App.viewer.MouseDown.X, e.Y - App.viewer.MouseDown.Y);
578
579 // Rectangle / Ellipse special handling
580 if (selectedROI.type == ROI.Type.Rectangle || selectedROI.type == ROI.Type.Ellipse)
581 {
582 // If exactly one corner is selected -> resize by that corner
583 if (selectedROI.selectedPoints.Count == 1)
584 {
585 int pointIndex = selectedROI.selectedPoints[0];
586 RectangleD rect = selectedROI.BoundingBox;
587
588 // Work with normalized copy to make logic clearer
589 double left = rect.X;
590 double top = rect.Y;
591 double right = rect.X + rect.W;
592 double bottom = rect.Y + rect.H;
593
594 switch (pointIndex)
595 {
596 case 0: // Top-Left
597 left += delta.X;
598 top += delta.Y;
599 break;
600 case 1: // Top-Right
601 right += delta.X;
602 top += delta.Y;
603 break;
604 case 2: // Bottom-Right
605 right += delta.X;
606 bottom += delta.Y;
607 break;
608 case 3: // Bottom-Left
609 left += delta.X;
610 bottom += delta.Y;
611 break;
612 default:
613 break;
614 }
615
616 // Build and assign normalized bounding box
617 RectangleD newRect = new RectangleD(
618 Math.Min(left, right),
619 Math.Min(top, bottom),
620 Math.Abs(right - left),
621 Math.Abs(bottom - top)
622 );
623
624 selectedROI.BoundingBox = newRect;
625
626 // Important: keep points and bbox in sync
627 SyncPointsFromBoundingBox(selectedROI);
628 selectedROI.UpdateBoundingBox(); // if your ROI uses this to recalc derived fields
629
630 App.viewer.MouseDown = new PointD(e.X, e.Y);
631 App.viewer.UpdateView();
632 return;
633 }
634 else
635 {
636 // No corner selected -> move entire ROI by delta
637 for (int i = 0; i < selectedROI.Points.Count; i++)
638 {
639 selectedROI.UpdatePoint(
640 new PointD(selectedROI.Points[i].X + delta.X,
641 selectedROI.Points[i].Y + delta.Y), i);
642 }
643
644 // Keep bounding box in sync with points
645 SyncBoundingBoxFromPoints(selectedROI);
646 selectedROI.UpdateBoundingBox();
647
648 App.viewer.MouseDown = new PointD(e.X, e.Y);
649 App.viewer.UpdateView();
650 return;
651 }
652 }
653 else
654 {
655 // Other shapes: polygons, polylines, freeforms, lines, points
656 if (selectedROI.selectedPoints.Count == 0)
657 {
658 // Move all points
659 for (int i = 0; i < selectedROI.Points.Count; i++)
660 {
661 selectedROI.UpdatePoint(
662 new PointD(selectedROI.Points[i].X + delta.X,
663 selectedROI.Points[i].Y + delta.Y), i);
664 }
665 }
666 else
667 {
668 // Move only selected points
669 foreach (int pointIndex in selectedROI.selectedPoints.ToArray())
670 {
671 if (pointIndex >= 0 && pointIndex < selectedROI.Points.Count)
672 {
673 PointD pt = selectedROI.Points[pointIndex];
674 selectedROI.UpdatePoint(
675 new PointD(pt.X + delta.X, pt.Y + delta.Y), pointIndex);
676 }
677 }
678 }
679
680 // Keep bbox updated
681 SyncBoundingBoxFromPoints(selectedROI);
682 selectedROI.UpdateBoundingBox();
683
684 App.viewer.MouseDown = new PointD(e.X, e.Y);
685 App.viewer.UpdateView();
686 return;
687 }
688 }
689 // Dragging entire selected ROI (no selectedPoints list)
690 else if (selectedROI != null && selectedROI.Selected)
691 {
692 PointD delta = new PointD(e.X - App.viewer.MouseDown.X, e.Y - App.viewer.MouseDown.Y);
693
694 for (int i = 0; i < selectedROI.Points.Count; i++)
695 {
696 selectedROI.UpdatePoint(
697 new PointD(selectedROI.Points[i].X + delta.X,
698 selectedROI.Points[i].Y + delta.Y), i);
699 }
700
701 SyncBoundingBoxFromPoints(selectedROI);
702 selectedROI.UpdateBoundingBox();
703
704 App.viewer.MouseDown = new PointD(e.X, e.Y);
705 App.viewer.UpdateView();
706 return;
707 }
708 // Drawing / updating selection rectangle
709 else
710 {
711 PointD d = new PointD(e.X - App.viewer.MouseDown.X, e.Y - App.viewer.MouseDown.Y);
712 RectangleD selRect = new RectangleD(
713 Math.Min(App.viewer.MouseDown.X, e.X),
714 Math.Min(App.viewer.MouseDown.Y, e.Y),
715 Math.Abs(d.X), Math.Abs(d.Y));
716
717 Tools.GetTool(Tools.Tool.Type.move).Rectangle = selRect;
718
719 bool controlHeld = buts.Event.State.HasFlag(ModifierType.ControlMask);
720
721 // Select ROIs intersecting with rectangle
722 foreach (ROI an in ImageView.SelectedImage.Annotations)
723 {
724 if (an == null) continue;
725
726 RectangleD selBound = an.GetSelectBound(
727 ROI.selectBoxSize * ImageView.SelectedImage.PhysicalSizeX,
728 ROI.selectBoxSize * ImageView.SelectedImage.PhysicalSizeY);
729
730 if (selBound.IntersectsWith(selRect))
731 {
732 an.Selected = true;
733
734 if (!controlHeld)
735 an.selectedPoints?.Clear();
736
737 // Select points within rectangle
738 RectangleD[] sels = an.GetSelectBoxes(
739 ROI.selectBoxSize * ImageView.SelectedImage.PhysicalSizeX);
740 if (sels != null)
741 {
742 for (int i = 0; i < sels.Length; i++)
743 {
744 if (sels[i].IntersectsWith(selRect))
745 {
746 if (an.selectedPoints == null) an.selectedPoints = new List<int>();
747 if (!an.selectedPoints.Contains(i))
748 an.selectedPoints.Add(i);
749 }
750 }
751 }
752 }
753 else if (!controlHeld)
754 {
755 an.Selected = false;
756 an.selectedPoints?.Clear();
757 }
758 }
759
760 if (selectedROI != null)
761 selectedROI.UpdateBoundingBox();
762
763 App.viewer.UpdateView();
764 }
765 }
766 public void ToolUp_Move(PointD e, ButtonReleaseEventArgs buts)
767 {
768 if (currentTool.type != Tool.Type.move || buts.Event.Button != 1)
769 return;
770
771 // Clear selection rectangle
772 Tools.GetTool(Tools.Tool.Type.move).Rectangle = new RectangleD(0, 0, 0, 0);
773 selectedROI?.UpdateBoundingBox();
774 App.viewer.UpdateView();
775 }
776
777
778 // ============================================================================
779 // 2. POINT TOOL
780 // ============================================================================
781 public void ToolDown_Point(PointD e, ButtonPressEventArgs buts)
782 {
783 if (currentTool.type != Tool.Type.point || buts.Event.Button != 1)
784 return;
785
786 ROI an = new ROI();
787 an.type = ROI.Type.Point;
788 an.Points.Clear();
789 an.Points.Add(new PointD(e.X, e.Y));
790 an.coord = App.viewer.GetCoordinate();
791 an.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
792 an.Selected = true;
793 selectedROI = an;
794 AddROI(selectedROI);
795 UpdateView();
796 }
797
798 // ============================================================================
799 // 3. LINE TOOL
800 // ============================================================================
801 public void ToolDown_Line(PointD e, ButtonPressEventArgs buts)
802 {
803 if (currentTool.type != Tool.Type.line || buts.Event.Button != 1)
804 return;
805
806 selectedROI = new ROI();
807 selectedROI.type = ROI.Type.Line;
808 selectedROI.AddPoint(new PointD(e.X, e.Y));
809 selectedROI.AddPoint(new PointD(e.X + ImageView.SelectedImage.PhysicalSizeX * ROI.selectBoxSize,
810 e.Y + ImageView.SelectedImage.PhysicalSizeX * ROI.selectBoxSize));
811 selectedROI.coord = App.viewer.GetCoordinate();
812 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
813 AddROI(selectedROI);
814 }
815
816 public void ToolMove_Line(PointD e, MotionNotifyEventArgs buts)
817 {
818 if (currentTool.type != Tool.Type.line ||
819 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
820 return;
821
822 if (selectedROI != null)
823 {
824 if (selectedROI.selectedPoints.Count == 1)
825 {
826 selectedROI.UpdatePoint(new PointD(e.X, e.Y), selectedROI.selectedPoints[0]);
827 selectedROI.UpdateBoundingBox();
828 UpdateView();
829 }
830 else
831 {
832 selectedROI.UpdatePoint(new PointD(e.X, e.Y), 1);
833 selectedROI.UpdateBoundingBox();
834 UpdateView();
835 }
836 }
837 }
838
839 public void ToolUp_Line(PointD e, ButtonReleaseEventArgs buts)
840 {
841 if (currentTool.type != Tool.Type.line || buts.Event.Button != 1)
842 return;
843
844 if (selectedROI != null && selectedROI.GetPointCount() >= 2)
845 {
846 selectedROI.UpdatePoint(new PointD(e.X, e.Y), 1);
847 selectedROI.UpdateBoundingBox();
848 selectedROI = null;
849 UpdateView();
850 }
851 }
852
853 public void ToolDown_Rectangle(PointD e, ButtonPressEventArgs buts)
854 {
855 if (currentTool.type != Tool.Type.rect || buts.Event.Button != 1)
856 return;
857
858 selectedROI = new ROI();
859 selectedROI.type = ROI.Type.Rectangle;
860 selectedROI.BoundingBox = new RectangleD(e.X, e.Y, 0, 0); // Start with 0 size
861 selectedROI.coord = App.viewer.GetCoordinate();
862 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
863 AddROI(selectedROI);
864 }
865
866 public void ToolMove_Rectangle(PointD e, MotionNotifyEventArgs buts)
867 {
868 if (currentTool.type != Tool.Type.rect ||
869 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
870 return;
871
872 if (selectedROI != null && selectedROI.type == ROI.Type.Rectangle)
873 {
874 selectedROI.BoundingBox = RectangleDExtensions.FromCorners(
875 new PointD(selectedROI.BoundingBox.X, selectedROI.BoundingBox.Y),
876 new PointD(e.X, e.Y));
877 UpdateView();
878 }
879 }
880
881 public void ToolUp_Rectangle(PointD e, ButtonReleaseEventArgs buts)
882 {
883 if (currentTool.type != Tool.Type.rect || buts.Event.Button != 1)
884 return;
885
886 if (selectedROI != null && selectedROI.type == ROI.Type.Rectangle)
887 {
888 // Update final rectangle bounds
889 selectedROI.BoundingBox = RectangleDExtensions.FromCorners(
890 new PointD(selectedROI.BoundingBox.X, selectedROI.BoundingBox.Y),
891 new PointD(e.X, e.Y));
892
893 // Validate the ROI (might reject if too small)
894 selectedROI.Validate();
895 selectedROI = null;
896 UpdateView();
897 }
898 }
899
900 // ============================================================================
901 // 5. ELLIPSE TOOL
902 // ============================================================================
903 public void ToolDown_Ellipse(PointD e, ButtonPressEventArgs buts)
904 {
905 if (currentTool.type != Tool.Type.ellipse || buts.Event.Button != 1)
906 return;
907
908 selectedROI = new ROI();
909 selectedROI.type = ROI.Type.Ellipse;
910 selectedROI.BoundingBox = new RectangleD(e.X, e.Y, 0, 0); // Start with 0 size
911 selectedROI.coord = App.viewer.GetCoordinate();
912 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
913 AddROI(selectedROI);
914 }
915
916 public void ToolMove_Ellipse(PointD e, MotionNotifyEventArgs buts)
917 {
918 if (currentTool.type != Tool.Type.ellipse ||
919 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
920 return;
921
922 if (selectedROI != null && selectedROI.type == ROI.Type.Ellipse)
923 {
924 selectedROI.BoundingBox = RectangleDExtensions.FromCorners(
925 new PointD(selectedROI.BoundingBox.X, selectedROI.BoundingBox.Y),
926 new PointD(e.X, e.Y));
927 UpdateView();
928 }
929 }
930
931 public void ToolUp_Ellipse(PointD e, ButtonReleaseEventArgs buts)
932 {
933 if (currentTool.type != Tool.Type.ellipse || buts.Event.Button != 1)
934 return;
935
936 if (selectedROI != null && selectedROI.type == ROI.Type.Ellipse)
937 {
938 // Update final ellipse bounds
939 selectedROI.BoundingBox = RectangleDExtensions.FromCorners(
940 new PointD(selectedROI.BoundingBox.X, selectedROI.BoundingBox.Y),
941 new PointD(e.X, e.Y));
942
943 // Validate the ROI (might reject if too small)
944 selectedROI.Validate();
945 selectedROI = null;
946 UpdateView();
947 }
948 }
949
950 // ============================================================================
951 // 6. POLYGON TOOL
952 // ============================================================================
953 public void ToolDown_Polygon(PointD e, ButtonPressEventArgs buts)
954 {
955 if (currentTool.type != Tool.Type.polygon || buts.Event.Button != 1)
956 return;
957
958 if (selectedROI == null || selectedROI.type != ROI.Type.Polygon)
959 {
960 // Start new polygon
961 selectedROI = new ROI();
962 selectedROI.type = ROI.Type.Polygon;
963 selectedROI.closed = false;
964 selectedROI.AddPoint(new PointD(e.X, e.Y));
965 selectedROI.coord = App.viewer.GetCoordinate();
966 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
967 AddROI(selectedROI);
968 UpdateView();
969 }
970 else if (!selectedROI.closed)
971 {
972 // Check if clicking near first point to close polygon
973 if (selectedROI.Points.Count >= 3)
974 {
975 PointD firstPoint = selectedROI.Points[0];
976 double distance = Math.Sqrt(Math.Pow(e.X - firstPoint.X, 2) + Math.Pow(e.Y - firstPoint.Y, 2));
977 double threshold = 10.0; // Adjust based on your zoom/scale
978
979 if (distance < threshold)
980 {
981 // Close polygon
982 selectedROI.closed = true;
983 selectedROI.Selected = false;
984 selectedROI.UpdateBoundingBox();
985 selectedROI.Validate();
986 selectedROI = null;
987 UpdateView();
988 return;
989 }
990 }
991
992
993 }
994 // Add new point to polygon
995 selectedROI.AddPoint(new PointD(e.X, e.Y));
996 selectedROI.UpdateBoundingBox();
997 UpdateView();
998 }
999
1000 private void ToolMove_Polygon(PointD e, MotionNotifyEventArgs buts)
1001 {
1002 if (currentTool.type != Tool.Type.polygon)
1003 return;
1004
1005 // Update preview of next point while drawing polygon
1006 if (selectedROI != null && selectedROI.type == ROI.Type.Polygon && !selectedROI.closed)
1007 {
1008 // Store current mouse position for preview rendering
1009 // (Assuming you have a way to render a preview line from last point to cursor)
1010 UpdateView();
1011 }
1012 }
1013 private void ToolUp_Polygon(PointD e, ButtonReleaseEventArgs buts)
1014 {
1015 // Polygon tool doesn't need mouse up handling since it works on clicks
1016 // The tool completes either by clicking near the first point or by double-clicking
1017 }
1018
1019 // ============================================================================
1020 // 7. FREEFORM TOOL
1021 // ============================================================================
1022 public void ToolDown_Freeform(PointD e, ButtonPressEventArgs buts)
1023 {
1024 if (currentTool.type != Tool.Type.freeform || buts.Event.Button != 1)
1025 return;
1026
1027 if (selectedROI == null || selectedROI.type != ROI.Type.Polygon)
1028 {
1029 // Start new freeform
1030 selectedROI = new ROI();
1031 selectedROI.type = ROI.Type.Polygon;
1032 selectedROI.closed = false;
1033 selectedROI.AddPoint(new PointD(e.X, e.Y));
1034 selectedROI.coord = App.viewer.GetCoordinate();
1035 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
1036 AddROI(selectedROI);
1037 UpdateView();
1038 }
1039 else if (!selectedROI.closed)
1040 {
1041 // Check if clicking near first point to close freeform
1042 if (selectedROI.Points.Count >= 3)
1043 {
1044 PointD firstPoint = selectedROI.Points[0];
1045 double distance = Math.Sqrt(Math.Pow(e.X - firstPoint.X, 2) + Math.Pow(e.Y - firstPoint.Y, 2));
1046 double threshold = 10.0; // Adjust based on your zoom/scale
1047
1048 if (distance < threshold)
1049 {
1050 // Close freeform
1051 selectedROI.closed = true;
1052 selectedROI.Selected = false;
1053 selectedROI.UpdateBoundingBox();
1054 selectedROI.Validate();
1055 selectedROI = null;
1056 UpdateView();
1057 return;
1058 }
1059 }
1060
1061
1062 }
1063 // Add new point to polygon
1064 selectedROI.AddPoint(new PointD(e.X, e.Y));
1065 selectedROI.UpdateBoundingBox();
1066 UpdateView();
1067 }
1068
1069 public void ToolMove_Freeform(PointD e, MotionNotifyEventArgs buts)
1070 {
1071 if (selectedROI != null)
1072 if (currentTool.type == Tool.Type.freeform && buts.Event.State.HasFlag(ModifierType.Button1Mask))
1073 {
1074 selectedROI.AddPoint(new PointD(e.X, e.Y));
1075 selectedROI.coord = App.viewer.GetCoordinate();
1076 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
1077 }
1078 }
1079
1080 public void ToolUp_Freeform(PointD e, ButtonReleaseEventArgs buts)
1081 {
1082 if (currentTool.type != Tool.Type.freeform || buts.Event.Button != 1)
1083 return;
1084
1085 if (selectedROI != null)
1086 {
1087 selectedROI.UpdateBoundingBox();
1088 //selectedROI = null;
1089 UpdateView();
1090 }
1091 }
1092
1093 // ============================================================================
1094 // 8. TEXT/LABEL TOOL
1095 // ============================================================================
1096 public void ToolDown_Text(PointD e, ButtonPressEventArgs buts)
1097 {
1098 if (currentTool.type != Tool.Type.text || buts.Event.Button != 1)
1099 return;
1100
1101 selectedROI = new ROI();
1102 selectedROI.type = ROI.Type.Label;
1103 selectedROI.AddPoint(new PointD(e.X, e.Y));
1104 selectedROI.coord = App.viewer.GetCoordinate();
1105 selectedROI.serie = ImageView.SelectedImage.isPyramidal ? App.viewer.Level : ImageView.SelectedImage.series;
1106
1107 // Show text input dialog
1108 ti = TextInput.Create();
1109 ti.ShowAll();
1110 ti.Run();
1111
1112 AddROI(selectedROI);
1113 selectedROI.UpdateBoundingBox();
1114 UpdateView();
1115 }
1116
1117 // ============================================================================
1118 // 9. DELETE TOOL
1119 // ============================================================================
1120 public void ToolDown_Delete(PointD e, ButtonPressEventArgs buts)
1121 {
1122 if (currentTool.type != Tool.Type.delete || buts.Event.Button != 1)
1123 return;
1124
1125 for (int i = ImageView.SelectedImage.Annotations.Count - 1; i >= 0; i--)
1126 {
1127 ROI an = ImageView.SelectedImage.Annotations[i];
1128 if (an == null) continue;
1129
1130 if (an.BoundingBox.IntersectsWith(new RectangleD(e.X, e.Y, 1, 1)))
1131 {
1132 if (an.selectedPoints == null || an.selectedPoints.Count == 0)
1133 {
1134 // Delete entire ROI
1135 ImageView.SelectedImage.Annotations.RemoveAt(i);
1136 break;
1137 }
1138 else if (an.selectedPoints.Count == 1 &&
1139 !(an.type == ROI.Type.Polygon ||
1140 an.type == ROI.Type.Polyline ||
1141 an.type == ROI.Type.Freeform))
1142 {
1143 // Delete ROI with single selected point (for non multi-point types)
1144 ImageView.SelectedImage.Annotations.RemoveAt(i);
1145 break;
1146 }
1147 else
1148 {
1149 // Delete selected points from polygon/polyline/freeform
1150 if (an.type == ROI.Type.Polygon ||
1151 an.type == ROI.Type.Polyline ||
1152 an.type == ROI.Type.Freeform)
1153 {
1154 an.closed = false;
1155 an.RemovePoints(an.selectedPoints.ToArray());
1156 an.UpdateBoundingBox();
1157 break;
1158 }
1159 }
1160 }
1161 }
1162 UpdateView();
1163 }
1164
1165 // ============================================================================
1166 // 10. BRUSH TOOL
1167 // ============================================================================
1168 public void ToolDown_Brush(PointD e, ButtonPressEventArgs buts)
1169 {
1170 if (currentTool.type != Tool.Type.brush || buts.Event.Button != 1)
1171 return;
1172
1173 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1174 if (ImageView.SelectedImage.isPyramidal)
1175 ip = new PointD(e.X, e.Y);
1176
1177 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(ImageView.SelectedBuffer);
1178 g.pen = new Bio.Graphics.Pen(DrawColor, (int)StrokeWidth, ImageView.SelectedImage.bitsPerPixel);
1179 g.FillEllipse(new Rectangle((int)ip.X, (int)ip.Y, (int)StrokeWidth, (int)StrokeWidth), g.pen.color);
1180
1181 App.viewer.UpdateImage();
1182 App.viewer.UpdateView();
1183 }
1184
1185 public void ToolMove_Brush(PointD e, MotionNotifyEventArgs buts)
1186 {
1187 if (currentTool.type != Tool.Type.brush ||
1188 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
1189 return;
1190
1191 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1192 if (ImageView.SelectedImage.isPyramidal)
1193 ip = new PointD(e.X, e.Y);
1194
1195 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(ImageView.SelectedBuffer);
1196 g.pen = new Bio.Graphics.Pen(DrawColor, (int)StrokeWidth, ImageView.SelectedImage.bitsPerPixel);
1197 g.FillEllipse(new Rectangle((int)ip.X, (int)ip.Y, (int)StrokeWidth, (int)StrokeWidth), g.pen.color);
1198
1199 App.viewer.UpdateImages();
1200 App.viewer.UpdateView();
1201 }
1202
1203 // ============================================================================
1204 // 11. ERASER TOOL
1205 // ============================================================================
1206 public void ToolDown_Eraser(PointD e, ButtonPressEventArgs buts)
1207 {
1208 if (currentTool.type != Tool.Type.eraser || buts.Event.Button != 1)
1209 return;
1210
1211 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1212 if (ImageView.SelectedImage.isPyramidal)
1213 ip = new PointD(e.X, e.Y);
1214
1215 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(ImageView.SelectedBuffer);
1216 Bio.Graphics.Pen pen = new Bio.Graphics.Pen(EraseColor, (int)StrokeWidth, ImageView.SelectedBuffer.BitsPerPixel);
1217 g.FillEllipse(new Rectangle((int)ip.X, (int)ip.Y, (int)StrokeWidth, (int)StrokeWidth), pen.color);
1218
1219 App.viewer.UpdateImages();
1220 App.viewer.UpdateView();
1221 }
1222
1223 public void ToolMove_Eraser(PointD e, MotionNotifyEventArgs buts)
1224 {
1225 if (currentTool.type != Tool.Type.eraser ||
1226 !buts.Event.State.HasFlag(ModifierType.Button1Mask))
1227 return;
1228
1229 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1230 if (ImageView.SelectedImage.isPyramidal)
1231 ip = new PointD(e.X, e.Y);
1232
1233 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(ImageView.SelectedBuffer);
1234 Bio.Graphics.Pen pen = new Bio.Graphics.Pen(EraseColor, (int)StrokeWidth, ImageView.SelectedBuffer.BitsPerPixel);
1235 g.FillEllipse(new Rectangle((int)ip.X, (int)ip.Y, (int)StrokeWidth, (int)StrokeWidth), pen.color);
1236
1237 App.viewer.UpdateImages();
1238 App.viewer.UpdateView();
1239 }
1240
1241 // ============================================================================
1242 // 12. BUCKET/FILL TOOL
1243 // ============================================================================
1244 public void ToolUp_Bucket(PointD e, ButtonReleaseEventArgs buts)
1245 {
1246 if (currentTool.type != Tool.Type.bucket || buts.Event.Button != 1)
1247 return;
1248
1249 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1250
1251 if (ip.X >= ImageView.SelectedImage.SizeX || ip.Y >= ImageView.SelectedImage.SizeY)
1252 return;
1253
1254 floodFiller.FillColor = DrawColor;
1255 floodFiller.Tolerance = tolerance;
1256 floodFiller.Bitmap = ImageView.SelectedBuffer;
1257 floodFiller.FloodFill(new AForge.Point((int)ip.X, (int)ip.Y));
1258
1259 App.viewer.UpdateImages();
1260 App.viewer.UpdateView();
1261 }
1262
1263 // ============================================================================
1264 // 13. DROPPER/COLOR PICKER TOOL
1265 // ============================================================================
1266 public void ToolUp_Dropper(PointD e, ButtonReleaseEventArgs buts)
1267 {
1268 if (currentTool.type != Tool.Type.dropper || buts.Event.Button != 1)
1269 return;
1270
1271 PointD ip = ImageView.SelectedImage.ToImageSpace(e);
1272
1273 if (ip.X >= 0 && ip.Y >= 0 && ip.X < ImageView.SelectedImage.SizeX && ip.Y < ImageView.SelectedImage.SizeY)
1274 {
1275 DrawColor = ImageView.SelectedBuffer.GetPixel((int)ip.X, (int)ip.Y);
1276 App.viewer.UpdateView();
1277 }
1278 }
1279
1280 // ============================================================================
1281 // 14. PAN TOOL
1282 // ============================================================================
1283 // --------------------------------------------------------------------
1284 // PAN STATE
1285 // --------------------------------------------------------------------
1286 private bool isPanning;
1287 private double panStartX;
1288 private double panStartY;
1289
1290 private PointD initialPanOrigin;
1291 private double initialPanScale;
1292
1293 // Velocity (world units / second)
1294 private PointD panVelocity;
1295 private DateTime lastMoveTime;
1296
1297 // Kinetic settings
1298 private const double PanFriction = 50.0; // world units / s²
1299 private const double VelocityEpsilon = 0.0001;
1300
1301 // DPI normalization
1302 private double dpiScale = 1.0;
1303
1304 // Animation
1305 private bool kineticActive = true;
1306 // Pan speed multiplier (user configurable)
1307
1308 public static double PanSpeed = 0.75; // Default to 0.75 for more controlled panning
1309 // --------------------------------------------------------------------
1310 // Mouse Down
1311 // --------------------------------------------------------------------
1312 public void ToolDown_Pan(PointD e, ButtonPressEventArgs buts)
1313 {
1314 if (buts.Event.Button != 1 && buts.Event.Button != 2)
1315 return;
1316
1317 currentTool = GetTool(Tool.Type.pan);
1318 panStartX = buts.Event.X;
1319 panStartY = buts.Event.Y;
1320 initialPanScale = App.viewer.Resolution;
1321
1322 if (ImageView.SelectedImage.isPyramidal)
1323 {
1324 initialPanOrigin = new PointD(
1325 App.viewer.PyramidalOrigin.X,
1326 App.viewer.PyramidalOrigin.Y);
1327 }
1328 else
1329 {
1330 initialPanOrigin = new PointD(
1331 App.viewer.Origin.X,
1332 App.viewer.Origin.Y);
1333 }
1334 }
1335
1336 // --------------------------------------------------------------------
1337 // Mouse Move
1338 // --------------------------------------------------------------------
1339 public void ToolMove_Pan(PointD e, MotionNotifyEventArgs buts)
1340 {
1341 if (currentTool.type != Tool.Type.pan)
1342 return;
1343
1344 if (!buts.Event.State.HasFlag(ModifierType.Button1Mask) &&
1345 !buts.Event.State.HasFlag(ModifierType.Button2Mask))
1346 return;
1347
1348 double dx = buts.Event.X - panStartX;
1349 double dy = buts.Event.Y - panStartY;
1350 // Apply pan speed multiplier for user-controlled panning sensitivity
1351
1352 double deltaX = (dx / initialPanScale) * PanSpeed;
1353 double deltaY = (dy / initialPanScale) * PanSpeed;
1354
1355 if (ImageView.SelectedImage.isPyramidal)
1356 {
1357 App.viewer.PyramidalOrigin = new PointD(
1358 initialPanOrigin.X - deltaX,
1359 initialPanOrigin.Y - deltaY);
1360 App.viewer.UpdateView(true);
1361 }
1362 else
1363 {
1364 App.viewer.Origin = new PointD(
1365 initialPanOrigin.X - deltaX,
1366 initialPanOrigin.Y - deltaY);
1367 // Non-pyramidal can still use normal update
1368 App.viewer.UpdateView();
1369 }
1370 }
1371
1372
1373 // --------------------------------------------------------------------
1374 // Mouse Up
1375 // --------------------------------------------------------------------
1376 public void ToolUp_Pan(PointD e, ButtonReleaseEventArgs buts)
1377 {
1378 if (currentTool.type == Tool.Type.pan &&
1379 (buts.Event.Button == 1 || buts.Event.Button == 2))
1380 {
1381 currentTool = GetTool(Tool.Type.move);
1382 }
1383 }
1384 private void StartKineticLoop()
1385 {
1386 DateTime last = DateTime.UtcNow;
1387
1388 GLib.Timeout.Add(16, () =>
1389 {
1390 if (!kineticActive)
1391 return false;
1392
1393 DateTime now = DateTime.UtcNow;
1394 double dt = (now - last).TotalSeconds;
1395 last = now;
1396
1397 double speed = Math.Sqrt(
1398 panVelocity.X * panVelocity.X +
1399 panVelocity.Y * panVelocity.Y);
1400
1401 if (speed < VelocityEpsilon)
1402 {
1403 kineticActive = false;
1404 return false;
1405 }
1406
1407 // Apply friction
1408 double decel = PanFriction * dt;
1409 double scale = Math.Max(0, (speed - decel) / speed);
1410
1411 panVelocity = new PointD(
1412 panVelocity.X * scale,
1413 panVelocity.Y * scale);
1414
1415 PointD origin = GetOrigin();
1416 origin = new PointD(
1417 origin.X + panVelocity.X * dt,
1418 origin.Y + panVelocity.Y * dt);
1419
1420 origin = ClampOrigin(origin);
1421 SetOrigin(origin);
1422
1423 return true;
1424 });
1425 }
1426 private PointD ClampOrigin(PointD origin)
1427 {
1428 var img = ImageView.SelectedImage;
1429 var res0 = img.Resolutions[0];
1430
1431 double viewW = App.viewer.ImageViewWidth / App.viewer.Resolution;
1432 double viewH = App.viewer.ImageViewHeight / App.viewer.Resolution;
1433
1434 double minX = 0;
1435 double minY = 0;
1436 double maxX = res0.SizeX - viewW;
1437 double maxY = res0.SizeY - viewH;
1438
1439 return new PointD(
1440 Math.Clamp(origin.X, minX, Math.Abs(maxX)),
1441 Math.Clamp(origin.Y, minY, Math.Abs(maxY)));
1442 }
1443 private PointD GetOrigin()
1444 {
1445 return ImageView.SelectedImage.isPyramidal
1446 ? App.viewer.PyramidalOrigin
1447 : App.viewer.Origin;
1448 }
1449
1450 private void SetOrigin(PointD p)
1451 {
1452 if (ImageView.SelectedImage.isPyramidal)
1453 App.viewer.PyramidalOrigin = p;
1454 else
1455 App.viewer.Origin = p;
1456 }
1457
1458 // ============================================================================
1459 // 14. Magic Wand TOOL
1460 // ============================================================================
1461 public void ToolDown_Magic(PointD e, ButtonPressEventArgs buts)
1462 {
1463 if (selectedROI == null)
1464 {
1465 selectedROI = new ROI();
1466 selectedROI.type = ROI.Type.Freeform;
1467 selectedROI.AddPoint(new PointD(e.X, e.Y));
1468 selectedROI.coord = App.viewer.GetCoordinate();
1469 if (ImageView.SelectedImage.isPyramidal)
1470 selectedROI.serie = App.viewer.Level;
1471 else
1472 selectedROI.serie = ImageView.SelectedImage.series;
1473 AddROI(selectedROI);
1474 }
1475 else
1476 {
1477 selectedROI.AddPoint(new PointD(e.X, e.Y));
1478 }
1479 }
1480
1481 public void ToolMove_Magic(PointD e, MotionNotifyEventArgs buts)
1482 {
1483 //First we draw the selection rectangle
1484 PointD d = new PointD(e.X - App.viewer.MouseDown.X, e.Y - App.viewer.MouseDown.Y);
1485 Tools.GetTool(Tools.Tool.Type.move).Rectangle = new RectangleD(App.viewer.MouseDown.X, App.viewer.MouseDown.Y, d.X, d.Y);
1486 UpdateView();
1487 }
1488
1489 public void ToolUp_Magic(PointD e, ButtonReleaseEventArgs buts)
1490 {
1491 if (!buts.Event.State.HasFlag(ModifierType.Button1Mask))
1492 return;
1493 // Define the rectangle from mouse coordinates
1494 RectangleD rectangle = new RectangleD(
1495 App.viewer.MouseDown.X,
1496 App.viewer.MouseDown.Y,
1497 Math.Abs(App.viewer.MouseUp.X - App.viewer.MouseDown.X),
1498 Math.Abs(App.viewer.MouseUp.Y - App.viewer.MouseDown.Y)
1499 );
1500
1501 // Convert to image space coordinates
1502 AForge.RectangleF rectInImageSpace = ImageView.SelectedImage.ToImageSpace(rectangle);
1503 ZCT coord = App.viewer.GetCoordinate();
1504 Bitmap bitmap;
1505
1506 // Check the number of RGB channels to choose filtering method
1507 if (ImageView.SelectedImage.Buffers[0].RGBChannelsCount > 1)
1508 {
1509 bitmap = ImageView.SelectedImage.GetFiltered(
1510 coord,
1511 new IntRange((int)ImageView.SelectedBuffer.Stats[0].Min, (int)ImageView.SelectedBuffer.Stats[0].Max),
1512 new IntRange((int)ImageView.SelectedBuffer.Stats[1].Min, (int)ImageView.SelectedBuffer.Stats[1].Max),
1513 new IntRange((int)ImageView.SelectedBuffer.Stats[2].Min, (int)ImageView.SelectedBuffer.Stats[2].Max)
1514 );
1515 }
1516 else
1517 {
1518 bitmap = ImageView.SelectedImage.GetFiltered(
1519 coord,
1520 new IntRange((int)ImageView.SelectedBuffer.Stats[0].Min, (int)ImageView.SelectedBuffer.Stats[0].Max),
1521 new IntRange((int)ImageView.SelectedBuffer.Stats[0].Min, (int)ImageView.SelectedBuffer.Stats[0].Max),
1522 new IntRange((int)ImageView.SelectedBuffer.Stats[0].Min, (int)ImageView.SelectedBuffer.Stats[0].Max)
1523 );
1524 }
1525
1526 // Crop the image to the selected rectangle
1527 bitmap.Crop(rectInImageSpace.ToRectangleInt());
1528 // Determine the threshold based on magicSelect settings
1529 Statistics[] st = Statistics.FromBytes(bitmap.Bytes, bitmap.SizeX, bitmap.Height, bitmap.RGBChannelsCount, bitmap.BitsPerPixel, bitmap.Stride, bitmap.PixelFormat);
1530 int threshold = magicSelect.Numeric ? magicSelect.Threshold : CalculateThreshold(magicSelect.Index, st[0]);
1531 BlobCounter blobCounter = new BlobCounter();
1532 OtsuThreshold th = new OtsuThreshold();
1533 bitmap.To8Bit();
1534 th.ApplyInPlace(bitmap);
1535 blobCounter.FilterBlobs = true;
1536 blobCounter.MinWidth = 2;
1537 blobCounter.MinHeight = 2;
1538 blobCounter.ProcessImage(bitmap);
1539 // Retrieve detected blobs
1540 Blob[] blobs = blobCounter.GetObjectsInformation();
1541 double pixelSizeX = ImageView.SelectedImage.PhysicalSizeX;
1542 double pixelSizeY = ImageView.SelectedImage.PhysicalSizeY;
1543 // Annotate detected blobs in the original image
1544 foreach (Blob blob in blobs)
1545 {
1546 AForge.RectangleD blobRectangle = new AForge.RectangleD(
1547 blob.Rectangle.X * pixelSizeX,
1548 blob.Rectangle.Y * pixelSizeY,
1549 blob.Rectangle.Width * pixelSizeX,
1550 blob.Rectangle.Height * pixelSizeY
1551 );
1552 // Calculate the location of the detected blob
1553 PointD location = new PointD(rectangle.X + blobRectangle.X, rectangle.Y + blobRectangle.Y);
1554 // Create and add ROI annotation
1555 ROI annotation = ROI.CreateRectangle(coord, location.X, location.Y, blobRectangle.W, blobRectangle.H);
1556 ImageView.SelectedImage.Annotations.Add(annotation);
1557 }
1558 App.viewer.UpdateView(true);
1559 }
1560
1561 /* It's a class that defines a tool */
1562 public class Tool
1563 {
1564 static int gridW = 2;
1565 static int gridH = 11;
1566 /* Defining an enum. */
1567 public enum ToolType
1568 {
1569 color,
1570 annotation,
1571 select,
1572 function
1573 }
1574 public enum Type
1575 {
1576 pan,
1577 move,
1578 point,
1579 line,
1580 rect,
1581 ellipse,
1582 polygon,
1583 text,
1584 delete,
1585 freeform,
1586 magic,
1587 brush,
1588 bucket,
1589 eraser,
1590 dropper,
1591 switchColors,
1592 color1,
1593 color2,
1594 script,
1595 }
1596
1598 public static void Init()
1599 {
1600 int w = 33;
1601 int h = 33;
1602 string s = System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "/";
1603 tools.Clear();
1604 if (tools.Count == 0)
1605 {
1606 int x = 0; int y = 0;
1607 foreach (Tool.Type t in (Tool.Type[])Enum.GetValues(typeof(Tool.Type)))
1608 {
1609 if (t != Type.script)
1610 if (t != Type.color1 && t != Type.color2)
1611 {
1612 Tool tool = new Tool(t, new ColorS(0, 0, 0));
1613 tool.bounds = new Rectangle(x * w, y * h, w, h);
1614 tool.image = new Pixbuf(s + "Images/" + tool.type.ToString() + ".png");
1615 tools.Add(tool.ToString(), tool);
1616 }
1617 else
1618 {
1619 Tool tool = new Tool(t, new ColorS(0, 0, 0));
1620 tool.bounds = new Rectangle(x * w, y * h, w, h);
1621 tools.Add(tool.ToString(), tool);
1622 }
1623 x++;
1624 if (x > Tools.gridW - 1)
1625 {
1626 x = 0;
1627 y++;
1628 }
1629 }
1630 }
1631 DrawColor = new ColorS(ushort.MaxValue, ushort.MaxValue, ushort.MaxValue);
1632 }
1633 public List<AForge.Point> Points;
1634 public ToolType toolType;
1635 public bool selected;
1636 public Pixbuf image;
1637 public Rectangle bounds;
1638 private RectangleD rect;
1639 public RectangleD Rectangle
1640 {
1641 get { return rect; }
1642 set { rect = value; }
1643 }
1644 public RectangleF RectangleF
1645 {
1646 get { return new RectangleF((float)rect.X, (float)rect.Y, (float)rect.W, (float)rect.H); }
1647 }
1648 public string script;
1649 public Type type;
1650 public ColorS tolerance;
1651 public ColorS color;
1652 public Tool()
1653 {
1654 tolerance = new ColorS(0, 0, 0);
1655 }
1656 public Tool(Type t)
1657 {
1658 type = t;
1659 tolerance = new ColorS(0, 0, 0);
1660 }
1661 public Tool(Type t, ColorS col)
1662 {
1663 type = t;
1664 color = col;
1665 tolerance = new ColorS(0, 0, 0);
1666 }
1667 public Tool(Type t, RectangleD r)
1668 {
1669 type = t;
1670 rect = r;
1671 tolerance = new ColorS(0, 0, 0);
1672 }
1673 public Tool(Type t, string sc)
1674 {
1675 type = t;
1676 script = sc;
1677 tolerance = new ColorS(0, 0, 0);
1678 }
1679 public override string ToString()
1680 {
1681 return type.ToString();
1682 }
1683
1684 }
1685
1686 public static Tool currentTool;
1687 /* Setting the color of the drawing tool. */
1688 public static ColorS DrawColor
1689 {
1690 get
1691 {
1692 return drawColor;
1693 }
1694 set
1695 {
1696 drawColor = value;
1697 tools[Tool.Type.color1.ToString()].color = drawColor;
1698 }
1699 }
1700 /* Setting the color of the eraser. */
1701 public static ColorS EraseColor
1702 {
1703 get
1704 {
1705 return eraseColor;
1706 }
1707 set
1708 {
1709 eraseColor = value;
1710 tools[Tool.Type.color2.ToString()].color = eraseColor;
1711 }
1712 }
1713
1714 /* A property that is used to set the width of the stroke. */
1715 public static int StrokeWidth
1716 {
1717 get
1718 {
1719 return width;
1720 }
1721 set
1722 {
1723 width = value;
1724 }
1725 }
1726
1727 public bool IsPanning { get; set; }
1728
1729 public static RectangleD selectionRect;
1730 public static TextInput ti = null;
1731
1738 public static Tool GetTool(string name)
1739 {
1740 if (tools.ContainsKey(name))
1741 return (Tool)tools[name];
1742 else return tools[Tool.Type.move.ToString()];
1743 }
1744 public static Tool GetTool(Tool.Type t)
1745 {
1746 if (tools.ContainsKey(t.ToString()))
1747 return (Tool)tools[t.ToString()];
1748 else return tools.FirstOrDefault().Value;
1749 }
1753 public static int CalculateThreshold(int index, Statistics stat)
1754 {
1755 return index switch
1756 {
1757 2 => (int)(stat.Min + stat.Mean),
1758 1 => (int)stat.Median,
1759 _ => (int)stat.Min
1760 };
1761 }
1762 }
1763 // -----------------------------
1764 // RectangleD extensions / helpers
1765 // -----------------------------
1766 public static class RectangleDExtensions
1767 {
1768 // Handles negative width/height gracefully
1769 public static bool Contains(this RectangleD r, ZCT coord, PointD p)
1770 {
1771 if (App.viewer.GetCoordinate() == coord)
1772 {
1773 double left = Math.Min(r.X, r.X + r.W);
1774 double right = Math.Max(r.X, r.X + r.W);
1775 double top = Math.Min(r.Y, r.Y + r.H);
1776 double bottom = Math.Max(r.Y, r.Y + r.H);
1777 return p.X >= left && p.X <= right && p.Y >= top && p.Y <= bottom;
1778 }
1779 return false;
1780 }
1781
1782 public static RectangleD FromCorners(PointD a, PointD b)
1783 {
1784 double x = Math.Min(a.X, b.X);
1785 double y = Math.Min(a.Y, b.Y);
1786 double w = Math.Abs(b.X - a.X);
1787 double h = Math.Abs(b.Y - a.Y);
1788 return new RectangleD(x, y, w, h);
1789 }
1790 }
1791
1792}
static MagicSelect Create(int index)
static TextInput Create(bool ROItype=true)
Definition TextInput.cs:36
static void Init()
It adds all the tools to the tools list.
Definition Tools.cs:1598
Implementations for all tool types defined in Tools.cs.
Definition Tools.cs:23
static Tool GetTool(string name)
Definition Tools.cs:1738
static Tools Create()
Definition Tools.cs:36
static int CalculateThreshold(int index, Statistics stat)
Helper method to calculate threshold for magic select.
Definition Tools.cs:1753
void SetupHandlers()
Sets up the handlers.
Definition Tools.cs:124
Definition ML.cs:17