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
ImageView.cs
1using AForge;
2using AForge.Imaging.Filters;
3using Bio;
4using BioLib;
5using BruTile;
6using Cairo;
7using Gdk;
8using Gtk;
9using OpenSlideGTK;
10using OpenTK;
11using OpenTK.Graphics.OpenGL4;
12using OpenTK.Mathematics;
13using OpenTK.Windowing.Common;
14using OpenTK.Windowing.Desktop;
15using org.python.compiler;
16using SkiaSharp;
17using SkiaSharp.Views.Gtk;
18using System;
19using System.Collections.Generic;
20using System.IO;
21using System.Linq;
22using System.Runtime.InteropServices;
23using static NetVips.Enums;
24using static OpenSlideGTK.Stitch;
25using Color = AForge.Color;
26using PixelFormat = OpenTK.Graphics.OpenGL4.PixelFormat;
27using Point = AForge.Point;
28using PointD = AForge.PointD;
29using PointF = AForge.PointF;
30using Rectangle = AForge.Rectangle;
31using SizeF = AForge.SizeF;
32
33namespace BioGTK
34{
35 public class ImageView : Gtk.Window
36 {
37 #region Properties
38
40 private Builder _builder;
41 public List<BioImage> Images = new List<BioImage>();
42 //public List<SKImage> SKImages = new List<SKImage>();
43 public void SetCoordinate(int z, int c, int t)
44 {
45 if (SelectedImage == null)
46 return;
47 if (z > SelectedImage.SizeZ - 1 && SelectedImage.Type == BioImage.ImageType.well)
48 zBar.Value = zBar.Adjustment.Upper;
49 else
50 zBar.Value = z;
51 if (c > SelectedImage.SizeC - 1)
52 cBar.Value = cBar.Adjustment.Upper;
53 else
54 cBar.Value = c;
55 if (t > SelectedImage.SizeT - 1)
56 tBar.Value = tBar.Adjustment.Upper;
57 else
58 tBar.Value = t;
59 if (SelectedImage.Type == BioImage.ImageType.well)
60 SelectedImage.Coordinate = new ZCT(0, (int)cBar.Value, (int)tBar.Value);
61 else
62 SelectedImage.Coordinate = new ZCT((int)zBar.Value, (int)cBar.Value, (int)tBar.Value);
63 }
67 public ZCT GetCoordinate()
68 {
69 return SelectedImage.Coordinate;
70 }
71
75 public void AddImage(BioImage im)
76 {
77 Images.Add(im);
78 selectedIndex = Images.Count - 1;
79 if (im.Resolutions[0].SizeX < 1920 && im.Resolutions[0].SizeY < 1080)
80 {
81 if (sk != null)
82 {
83 sk.WidthRequest = im.Resolutions[0].SizeX;
84 sk.HeightRequest = im.Resolutions[0].SizeY;
85 }
86 else
87 {
88 glArea.WidthRequest = im.Resolutions[0].SizeX;
89 glArea.HeightRequest = im.Resolutions[0].SizeY;
90 }
91 }
92
93 Initialize();
94 InitPreview();
95 UpdateImages(true);
96 UpdateGUI();
97 GoToImage(Images.Count - 1);
98 }
99 double pxWmicron = 5;
100 double pxHmicron = 5;
101 /* A property of the class. */
102 public double PxWmicron
103 {
104 get
105 {
106 if (SelectedImage.Type == BioImage.ImageType.pyramidal)
107 if (openSlide)
108 {
109 int lev = OpenSlideGTK.TileUtil.GetLevel(_openSlideBase.Schema.Resolutions, Resolution);
110 return _openSlideBase.Schema.Resolutions[lev].UnitsPerPixel * pxWmicron;
111 }
112 else
113 {
114 int lev = OpenSlideGTK.TileUtil.GetLevel(_slideBase.Schema.Resolutions, Resolution);
115 return _slideBase.Schema.Resolutions[lev].UnitsPerPixel * pxWmicron;
116 }
117
118 return pxWmicron;
119 }
120 set
121 {
122 pxWmicron = value;
123 }
124 }
125 public double PxHmicron
126 {
127 get
128 {
129 if (SelectedImage.Type == BioImage.ImageType.pyramidal)
130 if (openSlide)
131 {
132 int lev = OpenSlideGTK.TileUtil.GetLevel(_openSlideBase.Schema.Resolutions, Resolution);
133 return _openSlideBase.Schema.Resolutions[lev].UnitsPerPixel * pxHmicron;
134 }
135 else
136 {
137 int lev = OpenSlideGTK.TileUtil.GetLevel(_slideBase.Schema.Resolutions, Resolution);
138 return _slideBase.Schema.Resolutions[lev].UnitsPerPixel * pxHmicron;
139 }
140 return pxHmicron;
141 }
142 set
143 {
144 pxHmicron = value;
145 }
146 }
147 bool allowNavigation = true;
148 public bool AllowNavigation
149 {
150 get { return allowNavigation; }
151 set { allowNavigation = value; }
152 }
153
154 public bool ShowMasks { get; set; } = true;
155 public bool ShowOverview { get; set; } = true;
156 /* Getting the selected buffer from the selected image. */
157 public static AForge.Bitmap SelectedBuffer
158 {
159 get
160 {
161 int ind = SelectedImage.GetFrameIndex(SelectedImage.Coordinate.Z, SelectedImage.Coordinate.C, SelectedImage.Coordinate.T);
162 return SelectedImage.Buffers[ind];
163 }
164 }
165 int selectedIndex = 0;
166 public int SelectedIndex
167 {
168 get { return selectedIndex; }
169 set
170 {
171 selectedIndex = value;
172 Images[selectedIndex] = SelectedImage;
173 }
174 }
175 Menu imagesMenu;
176 public static List<ROI> selectedAnnotations
177 {
178 get
179 {
180 List<ROI> rois = new List<ROI>();
181 foreach (var item in SelectedImage.Annotations)
182 {
183 if (item.BoundingBox.IntersectsWith(App.viewer.MouseDown))
184 rois.Add(item);
185 }
186 return rois;
187 }
188 }
189#pragma warning disable 649
190 [Builder.Object]
191 private Gtk.Scale zBar;
192 [Builder.Object]
193 private Gtk.Scale tBar;
194 [Builder.Object]
195 private Gtk.Scale cBar;
196 [Builder.Object]
197 private Gtk.Label statusLabel;
198 [Builder.Object]
199 private Gtk.Stack rgbStack;
200 [Builder.Object]
201 private Gtk.Grid grid;
202 [Builder.Object]
203 private Gtk.Box rgbBox;
204 [Builder.Object]
205 private Gtk.Box controlsBox;
206 [Builder.Object]
207 public Gtk.Box mainBox;
208 [Builder.Object]
209 private Gtk.ComboBox rBox;
210 [Builder.Object]
211 private Gtk.ComboBox gBox;
212 [Builder.Object]
213 private Gtk.ComboBox bBox;
214 [Builder.Object]
215 private Gtk.Stack viewStack;
216 [Builder.Object]
217 public Menu contextMenu;
218 [Builder.Object]
219 private MenuItem goToOriginMenu;
220 [Builder.Object]
221 private MenuItem goToImageMenu;
222 [Builder.Object]
223 private MenuItem roi;
224 [Builder.Object]
225 private Menu roiMenu;
226 [Builder.Object]
227 private MenuItem roiDelete;
228 [Builder.Object]
229 private MenuItem roiID;
230 [Builder.Object]
231 private MenuItem copy;
232 [Builder.Object]
233 private MenuItem paste;
234 [Builder.Object]
235 private MenuItem draw;
236 [Builder.Object]
237 private MenuItem fill;
238 [Builder.Object]
239 private Menu barMenu;
240 [Builder.Object]
241 private MenuItem play;
242 [Builder.Object]
243 private MenuItem stop;
244 [Builder.Object]
245 private MenuItem playSpeed;
246 [Builder.Object]
247 private MenuItem setValueRange;
248 [Builder.Object]
249 private MenuItem loop;
250 [Builder.Object]
251#pragma warning restore 649
252 private SKDrawingArea sk;
253 #endregion
254 public SlideGLArea glArea;
255 public SlideRenderer slideRenderer;
256 public SKSlideRenderer sKSlideRenderer;
257 public GLWindow window;
258 public static bool MacOS = false;
259 #region Constructors / Destructors
260
268 public static ImageView Create(BioImage bm)
269 {
270 Console.WriteLine("Creating ImageView for " + bm.file);
271
272 Builder builder = new Builder(new FileStream(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "/" + "Glade/ImageView.glade", FileMode.Open));
273
274 ImageView v = new ImageView(builder, builder.GetObject("imageView").Handle, bm);
275 v.Title = bm.Filename;
276
277 return v;
278 }
279
280 /* The above code is a constructor for the ImageView class in C#. It takes in a Builder object,
281 a handle, and a BioImage object as parameters. */
282 protected ImageView(Builder builder, IntPtr handle, BioImage im) : base(handle)
283 {
284 _builder = builder;
285 App.viewer = this;
286 builder.Autoconnect(this);
287 var gameWindowSettings = new GameWindowSettings()
288 {
289 UpdateFrequency = 60,
290 };
291 NativeWindowSettings nativeSettings;
292
293 if (OperatingSystem.IsMacOS())
294 {
295 MacOS = true;
296 // Create the renderer bridge
297 sk = new SKDrawingArea();
298 sKSlideRenderer = new SKSlideRenderer(sk);
299 }
300 else if (OperatingSystem.IsLinux())
301 {
302 nativeSettings = new NativeWindowSettings()
303 {
304 ClientSize = new Vector2i(600, 400),
305 Location = new Vector2i(0, 0),
306 Title = "OpenGL Context",
307 StartVisible = false, // Window starts hidden
308 API = ContextAPI.OpenGL,
309 Profile = ContextProfile.Core,
310 APIVersion = new Version(3, 3)
311 };
312 //tileCopy = new TileCopyGL(gameWindowSettings, nativeSettings);
313 Environment.SetEnvironmentVariable("GDK_BACKEND", "x11");
314 Environment.SetEnvironmentVariable("GTK_BACKEND", "x11");
315 window = new GLWindow(gameWindowSettings, nativeSettings);
316 // Create the GLArea widget
317 glArea = new SlideGLArea();
318 glArea.OnSkiaRender += RenderSkia;
319 // Create the renderer bridge
320 slideRenderer = new SlideRenderer(glArea);
321 GLFWProvider.SetErrorCallback((error, description) =>
322 {
323 if (description.Contains("Wayland") && description.Contains("window position"))
324 Console.WriteLine($"BioGTK Window Position Error.");
325 Console.WriteLine($"BioGTK GLFW Error {error}: {description}");
326 });
327
328 }
329 else if (OperatingSystem.IsWindows())
330 {
331 nativeSettings = new NativeWindowSettings()
332 {
333 ClientSize = new Vector2i(600, 400),
334 Location = new Vector2i(0, 0),
335 Title = "OpenGL Context",
336 StartVisible = false, // Window starts hidden
337 API = ContextAPI.OpenGL,
338 Profile = ContextProfile.Core,
339 APIVersion = new Version(3, 3)
340 };
341 window = new GLWindow(gameWindowSettings, nativeSettings);
342 // Create the GLArea widget
343 glArea = new SlideGLArea();
344 glArea.OnSkiaRender += RenderSkia;
345 // Create the renderer bridge
346 slideRenderer = new SlideRenderer(glArea);
347 GLFWProvider.SetErrorCallback((error, description) =>
348 {
349 Console.WriteLine($"BioGTK GLFW Error {error}: {description}");
350 });
351 }
352
353 if (MacOS)
354 {
355 if (im.isPyramidal)
356 {
357 // Set the source based on image type
358 if (im.OpenSlideBase != null)
359 {
360 sKSlideRenderer.SetSource(im.OpenSlideBase);
361 }
362 else if (im.SlideBase != null)
363 {
364 sKSlideRenderer.SetSource(im.SlideBase);
365 }
366 }
367 // Add to view
368 viewStack.Add(sk);
369 }
370 else
371 {
372 // Set the source based on image type
373 if (im.OpenSlideBase != null)
374 {
375 slideRenderer.SetSource(im.OpenSlideBase);
376 }
377 else if (im.SlideBase != null)
378 {
379 slideRenderer.SetSource(im.SlideBase);
380 }
381 // Add to view
382 viewStack.Add(glArea);
383 }
384
385 viewStack.ShowAll();
386 if (!MacOS)
387 glArea.Show();
388 this.WidthRequest = 600;
389 this.HeightRequest = 400;
390 roi.Submenu = roiMenu;
391 roi.ShowAll();
392 AddImage(im);
393 ShowMasks = true;
394 pxWmicron = SelectedImage.PhysicalSizeX;
395 pxHmicron = SelectedImage.PhysicalSizeY;
397 //pictureBox.WidthRequest = im.SizeX;
398 //pictureBox.HeightRequest = im.SizeY;
399 Function.InitializeContextMenu();
400 this.Scale = new SizeF(1, 1);
401 // Set the text column to display for comboboxs.
402 var rendererr = new CellRendererText();
403 rBox.PackStart(rendererr, false);
404 rBox.AddAttribute(rendererr, "text", 0);
405 var rendererg = new CellRendererText();
406 gBox.PackStart(rendererg, false);
407 gBox.AddAttribute(rendererg, "text", 0);
408 var rendererb = new CellRendererText();
409 bBox.PackStart(rendererb, false);
410 bBox.AddAttribute(rendererb, "text", 0);
411 App.ApplyStyles(this);
412 }
413 /*
414 GRBackendRenderTarget _renderTarget;
415 GRContext _grContext;
416 SKSurface _skSurface;
417 private void InitializeSkia()
418 {
419 // 1. Get the High-DPI scaling factor for the laptop screen
420 int scale = ScaleFactor;
421 int width = AllocatedWidth * scale;
422 int height = AllocatedHeight * scale;
423
424 if (width <= 0 || height <= 0) return;
425
426 // 2. Query the current GL state for the framebuffer configuration
427 GL.GetInteger(GetPName.FramebufferBinding, out int framebufferId);
428 GL.GetInteger(GetPName.Samples, out int samples); // <--- This fills your 'samples'
429 // Get Stencil Bits with a fallback
430 int stencil;
431 try
432 {
433 // 0x0D57 is the GL constant for STENCIL_BITS
434 GL.GetInteger((GetPName)0x0D57, out stencil);
435 }
436 catch
437 {
438 stencil = 8; // Standard fallback for Skia
439 }
440
441 var glInfo = new GRGlFramebufferInfo(
442 fboId: (uint)framebufferId,
443 format: 0x8058); // GL_RGBA8
444
445 // 4. Create the render target with physical pixel dimensions
446 _renderTarget = new GRBackendRenderTarget(
447 width,
448 height,
449 samples,
450 stencil,
451 glInfo);
452
453 // 5. Create the context and surface
454 _grContext = GRContext.CreateGl();
455 _skSurface = SKSurface.Create(_grContext, _renderTarget, GRSurfaceOrigin.BottomLeft, SKColorType.Rgba8888);
456 }
457 */
462 private void RenderSkia(SKCanvas canvas, int width, int height)
463 {
464 try
465 {
466 canvas.Save();
467 canvas.Scale(ScaleFactor); // Scale coordinates to match High-DPI screen
468
469 var paint = new SKPaint
470 {
471 Color = SKColors.Gray,
472 BlendMode = SKBlendMode.SrcOver,
473 IsAntialias = true,
474 Style = SKPaintStyle.Fill
475 };
476 // Draw annotations (ROIs) - keep existing annotation drawing code
477 int i = 0;
478 foreach (BioImage im in Images)
479 {
480 List<ROI> rois = new List<ROI>();
481 rois.AddRange(im.Annotations);
482 int ri = 0;
483 ZCT co = GetCoordinate();
484 canvas.Translate(width / 2f, height / 2f);
485 RectangleD rp = ToScreenSpace(new RectangleD(im.StageSizeX * im.PhysicalSizeX, im.StageSizeX * im.PhysicalSizeY, im.SizeX * im.PhysicalSizeX, im.SizeY * im.PhysicalSizeY));
486 if (!im.isPyramidal)
487 canvas.DrawImage(SKImages[i], ToRectangle((float)rp.X, (float)rp.Y, (float)rp.W, (float)rp.H), paint);
488 if (rois.Count > 0)
489 {
490 RenderSkiaAnnotations(canvas, width, height);
491 }
492 i++;
493 }
494
495 // Draw overview if enabled
496 if (overviewImage != null && ShowOverview)
497 {
498 var ims = BitmapToSKImage(overviewImage.GetImageRGBA());
499 paint.Style = SKPaintStyle.Fill;
500 // Draw the overview image at the top-left corner
501 canvas.DrawImage(ims, 0, 0, paint);
502 }
503 else if (overviewImage == null && ShowOverview)
504 {
505 paint.Style = SKPaintStyle.Stroke;
506 paint.Color = SKColors.Gray;
507 paint.StrokeWidth = 2;
508 canvas.DrawRect(0, 0, overview.Width, overview.Height, paint);
509 }
510 SKImageInfo inf = new SKImageInfo(width, height);
511 if (SelectedImage.isPyramidal)
512 DrawViewportRectangle(canvas, paint);
513
514 // Plugin rendering hook
515 Plugins.Render(this, new SkiaSharp.Views.Desktop.SKPaintSurfaceEventArgs(canvas.Surface, inf));
516 paint.Dispose();
517 canvas.Restore();
518 }
519 catch (Exception ex)
520 {
521 Console.WriteLine($"Annotation render error: {ex.Message}");
522 }
523 }
524 private void RenderSkiaAnnotations(SKCanvas canvas, int width, int height)
525 {
526 try
527 {
528 canvas.Save();
529 canvas.Scale(ScaleFactor); // Scale coordinates to match High-DPI screen
530
531 var paint = new SKPaint
532 {
533 Color = SKColors.Gray,
534 BlendMode = SKBlendMode.SrcOver,
535 IsAntialias = true,
536 Style = SKPaintStyle.Fill
537 };
538
539 // Draw annotations (ROIs) - keep existing annotation drawing code
540 int i = 0;
541 foreach (BioImage im in Images)
542 {
543 List<ROI> rois = new List<ROI>();
544 rois.AddRange(im.Annotations);
545 int ri = 0;
546 ZCT co = GetCoordinate();
547 if (rois.Count > 0)
548 {
549 if (!SelectedImage.isPyramidal)
550 canvas.Translate(0, 0);
551 else
552 canvas.Translate(-(width / 2f), -(height / 2f));
553 foreach (ROI an in rois)
554 {
555 if (an.coord.Z != GetCoordinate().Z || an.coord.C != GetCoordinate().C || an.coord.T != GetCoordinate().T)
556 continue;
557 if (Mode == ViewMode.RGBImage)
558 {
559 if (!showRROIs && an.coord.C == 0)
560 continue;
561 if (!showGROIs && an.coord.C == 1)
562 continue;
563 if (!showBROIs && an.coord.C == 2)
564 continue;
565 }
566 if (an.Selected)
567 {
568 paint.Color = SKColors.Magenta;
569 }
570 else
571 paint.Color = new SKColor(an.strokeColor.R, an.strokeColor.G, an.strokeColor.B);
572 paint.StrokeWidth = (float)an.strokeWidth;
573 paint.Style = SKPaintStyle.Stroke;
574 PointF pc = new PointF((float)(an.BoundingBox.X + (an.BoundingBox.W / 2)), (float)(an.BoundingBox.Y + (an.BoundingBox.H / 2)));
575 float widths = ROI.selectBoxSize * (float)Resolution;
576
577 if (an.type == ROI.Type.Mask && an.coord == App.viewer.GetCoordinate() && ShowMasks)
578 {
579 paint.Style = SKPaintStyle.Fill;
580 SKImage sim;
581 if (an.Selected)
582 sim = an.roiMask.GetColored(Color.Blue, 10, true).ToSKImage();
583 else
584 sim = an.roiMask.GetColored(Color.FromArgb(1, an.fillColor.R, an.fillColor.G, an.fillColor.B), 1, true).ToSKImage();
585 RectangleD p = ToScreenSpace(new RectangleD(an.roiMask.X * an.roiMask.PhysicalSizeX, an.roiMask.Y * an.roiMask.PhysicalSizeY, an.W, an.H));
586 canvas.DrawImage(sim, ToRectangle((float)p.X, (float)p.Y, (float)p.W, (float)p.H), paint);
587 sim.Dispose();
588 continue;
589 }
590 else
591 if (an.type == ROI.Type.Point)
592 {
593 RectangleD r1 = ToScreenRect(an.Point.X, an.Point.Y, ToViewW(3), ToViewH(3));
594 canvas.DrawCircle((float)r1.X, (float)r1.Y, 3, paint);
595 }
596 else
597 if (an.type == ROI.Type.Line)
598 {
599 for (int p = 0; p < an.Points.Count - 1; p++)
600 {
601 PointD p1 = ToScreenSpace(an.Points[p].X, an.Points[p].Y);
602 PointD p2 = ToScreenSpace(an.Points[p + 1].X, an.Points[p + 1].Y);
603 canvas.DrawLine(new SKPoint((float)p1.X, (float)p1.Y), new SKPoint((float)p2.X, (float)p2.Y), paint);
604 }
605 }
606 else
607 if (an.type == ROI.Type.Rectangle)
608 {
609 RectangleD rectt = ToScreenRect(an.Points[0].X, an.Points[0].Y, Math.Abs(an.Points[0].X - an.Points[1].X), Math.Abs(an.Points[0].Y - an.Points[2].Y));
610 canvas.DrawRect((float)rectt.X, (float)rectt.Y, (float)rectt.W, (float)rectt.H, paint);
611 }
612 else
613 if (an.type == ROI.Type.Ellipse)
614 {
615 RectangleD rect = ToScreenRect(an.X + (an.W / 2), an.Y + (an.H / 2), an.W, an.H);
616 canvas.DrawOval((float)rect.X, (float)rect.Y, (float)rect.W / 2, (float)rect.H / 2, paint);
617 }
618 else
619 if ((an.type == ROI.Type.Polygon && an.closed))
620 {
621 for (int p = 0; p < an.Points.Count - 1; p++)
622 {
623 RectangleD p1 = ToScreenRect(an.Points[p].X, an.Points[p].Y, 1, 1);
624 RectangleD p2 = ToScreenRect(an.Points[p + 1].X, an.Points[p + 1].Y, 1, 1);
625 canvas.DrawLine(new SKPoint((float)p1.X, (float)p1.Y), new SKPoint((float)p2.X, (float)p2.Y), paint);
626 }
627 RectangleD pp1 = ToScreenRect(an.Points[0].X, an.Points[0].Y, 1, 1);
628 RectangleD pp2 = ToScreenRect(an.Points[an.Points.Count - 1].X, an.Points[an.Points.Count - 1].Y, 1, 1);
629 canvas.DrawLine(new SKPoint((float)pp1.X, (float)pp1.Y), new SKPoint((float)pp2.X, (float)pp2.Y), paint);
630 }
631 else
632 if ((an.type == ROI.Type.Polygon && !an.closed) || an.type == ROI.Type.Polyline)
633 {
634 for (int p = 0; p < an.Points.Count - 1; p++)
635 {
636 RectangleD p1 = ToScreenRect(an.Points[p].X, an.Points[p].Y, 1, 1);
637 RectangleD p2 = ToScreenRect(an.Points[p + 1].X, an.Points[p + 1].Y, 1, 1);
638 canvas.DrawLine(new SKPoint((float)p1.X, (float)p1.Y), new SKPoint((float)p2.X, (float)p2.Y), paint);
639 }
640 }
641 else
642 if (an.type == ROI.Type.Freeform)
643 {
644 for (int p = 0; p < an.Points.Count - 1; p++)
645 {
646 RectangleD p1 = ToScreenRect(an.Points[p].X, an.Points[p].Y, 1, 1);
647 RectangleD p2 = ToScreenRect(an.Points[p + 1].X, an.Points[p + 1].Y, 1, 1);
648 canvas.DrawLine(new SKPoint((float)p1.X, (float)p1.Y), new SKPoint((float)p2.X, (float)p2.Y), paint);
649 }
650 RectangleD pp1 = ToScreenRect(an.Points[0].X, an.Points[0].Y, 1, 1);
651 RectangleD pp2 = ToScreenRect(an.Points[an.Points.Count - 1].X, an.Points[an.Points.Count - 1].Y, 1, 1);
652 canvas.DrawLine(new SKPoint((float)pp1.X, (float)pp1.Y), new SKPoint((float)pp2.X, (float)pp2.Y), paint);
653 }
654 else
655 if (an.type == ROI.Type.Label)
656 {
657 RectangleD p = ToScreenRect(an.Point.X, an.Point.Y, 1, 1);
658 canvas.DrawText(an.Text, (float)p.X, (float)p.Y, new SKFont(SKTypeface.Default, an.fontSize, 1, 0), paint);
659 }
660
661 if (ROIManager.showText)
662 {
663 RectangleD p = ToScreenRect(an.Point.X, an.Point.Y, 1, 1);
664 canvas.DrawText(an.Text, (float)p.X, (float)p.Y, new SKFont(SKTypeface.Default, an.fontSize, 1, 0), paint);
665 }
666 if (ROIManager.showBounds && an.type != ROI.Type.Rectangle && an.type != ROI.Type.Mask && an.type != ROI.Type.Label)
667 {
668 RectangleD rrf = ToScreenRect(an.BoundingBox.X, an.BoundingBox.Y, an.BoundingBox.W, an.BoundingBox.H);
669 canvas.DrawRect((float)rrf.X, (float)rrf.Y, (float)rrf.W, (float)rrf.H, paint);
670 }
671 paint.Color = SKColors.Red;
672 if (!(an.type == ROI.Type.Freeform && !an.Selected) && an.type != ROI.Type.Mask)
673 foreach (RectangleD re in an.GetSelectBoxes(1))
674 {
675 RectangleD recd = ToScreenRect(re.X, re.Y, re.W, re.H);
676 canvas.DrawRect((float)recd.X, (float)recd.Y, (float)recd.W, (float)recd.H, paint);
677 }
678 if (an.type != ROI.Type.Mask)
679 {
680 //Lets draw the selection Boxes.
681 List<RectangleD> rects = new List<RectangleD>();
682 RectangleD[] sels = an.GetSelectBoxes(widths);
683 for (int p = 0; p < an.selectedPoints.Count; p++)
684 {
685 if (an.selectedPoints[p] < an.GetPointCount())
686 {
687 rects.Add(sels[an.selectedPoints[p]]);
688 }
689 }
690 //Lets draw selected selection boxes.
691 paint.Color = SKColors.Blue;
692 if (rects.Count > 0)
693 {
694 int ind = 0;
695 foreach (RectangleD re in an.GetSelectBoxes(1))
696 {
697 RectangleD recd = ToScreenRect(re.X, re.Y, re.W, re.H);
698 if (an.selectedPoints.Contains(ind))
699 {
700 canvas.DrawRect((float)recd.X, (float)recd.Y, (float)recd.W, (float)recd.H, paint);
701 }
702 ind++;
703 }
704 }
705 rects.Clear();
706 }
707 ri++;
708 }
709 canvas.Translate(0, 0);
710 }
711 i++;
712 }
713 SKImageInfo inf = new SKImageInfo(width, height);
714 // Plugin rendering hook
715 Plugins.Render(this, new SkiaSharp.Views.Desktop.SKPaintSurfaceEventArgs(canvas.Surface, inf));
716 paint.Dispose();
717 canvas.Restore();
718 }
719 catch (Exception ex)
720 {
721 Console.WriteLine($"Annotation render error: {ex.Message}");
722 }
723 }
724 public static SKImage BitmapToSKImage(Bitmap bmp)
725 {
726 var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
727
728 var data = bmp.LockBits(
729 rect,
730 ImageLockMode.ReadOnly,
731 AForge.PixelFormat.Format32bppArgb); // This is BGRA in memory
732
733 try
734 {
735 var info = new SKImageInfo(
736 bmp.Width,
737 bmp.Height,
738 SKColorType.Bgra8888,
739 SKAlphaType.Premul);
740
741 var pixmap = new SKPixmap(info, data.Scan0, data.Stride);
742
743 return SKImage.FromPixels(pixmap);
744 }
745 finally
746 {
747 bmp.UnlockBits(data);
748 }
749 }
750 /*
754 private void DrawOverview(SKCanvas canvas, SKPaint paint)
755 {
756 var ims = BitmapToSKImage(overviewImage.GetImageRGBA());
757 paint.Style = SKPaintStyle.Fill;
758 canvas.DrawImage(ims, 0, 0, paint);
759
760 paint.Style = SKPaintStyle.Stroke;
761 paint.Color = SKColors.Gray;
762 canvas.DrawRect(overview.X, overview.Y, overview.Width, overview.Height, paint);
763
764 // Draw viewport indicator
765 paint.Color = SKColors.Red;
766 // ... existing viewport rect calculation ...
767
768 ims.Dispose();
769 }
770 */
771 // Immediate render for interactive operations like panning
772 public void RequestImmediateRender()
773 {
774 UpdateView(true);
775 }
776
777 private static SkiaSharp.SKRect ToRectangle(float x1, float y1, float x2, float y2)
778 {
779 return new SkiaSharp.SKRect()
780 {
781 Location = new SKPoint(x1, y1),
782 Size = new SKSize(x2, y2)
783 };
784 }
785 private bool refresh = false;
786 SKImage overviewSKImage;
787 private async Task PrefetchSurroundingTiles(Extent viewportExtent, int level)
788 {
789 // Cancel any pending prefetch operations
790 _tileFetchCancellation?.Cancel();
791 _tileFetchCancellation = new CancellationTokenSource();
792 var token = _tileFetchCancellation.Token;
793
794 // Expand viewport by 1 tile in each direction for prefetching
795 var expandedExtent = new Extent(
796 viewportExtent.MinX - 256,
797 viewportExtent.MinY - 256,
798 viewportExtent.MaxX + 256,
799 viewportExtent.MaxY + 256
800 );
801 IEnumerable<TileInfo> tileInfos;
802 if (SelectedImage.OpenSlideBase != null)
803 tileInfos = SelectedImage.OpenSlideBase.Schema.GetTileInfos(expandedExtent, level);
804 else
805 tileInfos = SelectedImage.SlideBase.Schema.GetTileInfos(expandedExtent, level);
806 // Start fetching tiles asynchronously
807 var fetchTasks = new List<Task>();
808 foreach (var tileInfo in tileInfos)
809 {
810 if (token.IsCancellationRequested) break;
811
812 var info = new Info(SelectedImage.Coordinate, tileInfo.Index, tileInfo.Extent, level);
813 // Check if tile is already in cache
814
815 if (_openSlideBase != null)
816 {
817 if (_openSlideBase.cache.GetTile(info) != null) continue;
818 }
819 else
820 {
821 BioLib.TileInformation tf = new TileInformation(tileInfo.Index, tileInfo.Extent, SelectedImage.Coordinate);
822 if (_slideBase.cache.GetTile(tf) != null) continue;
823 }
824 // Start async fetch if not already pending
825 if (!_pendingTileFetches.ContainsKey(tileInfo.Index))
826 {
827 var fetchTask = Task.Run(async () =>
828 {
829 try
830 {
831 if (_openSlideBase == null)
832 {
833 Info inf = new Info(SelectedImage.Coordinate, tileInfo.Index, tileInfo.Extent, tileInfo.Index.Level);
834 var tile = await _openSlideBase.cache.GetTile(inf);
835 return tile;
836 }
837 else
838 {
839 TileInformation tf = new TileInformation(tileInfo.Index, tileInfo.Extent, SelectedImage.Coordinate);
840 var tile = await _slideBase.cache.GetTile(tf);
841 return tile;
842 }
843 }
844 catch (Exception ex)
845 {
846 Console.WriteLine($"Prefetch error for tile {tileInfo.Index}: {ex.Message}");
847 return null;
848 }
849 }, token);
850
851 _pendingTileFetches[tileInfo.Index] = fetchTask;
852 fetchTasks.Add(fetchTask);
853 }
854 }
855
856 // Don't await - let prefetching happen in background
857 _ = Task.WhenAll(fetchTasks).ContinueWith(t =>
858 {
859 // Clean up completed fetches
860 lock (_pendingTileFetches)
861 {
862 var completed = _pendingTileFetches
863 .Where(kvp => kvp.Value.IsCompleted)
864 .Select(kvp => kvp.Key)
865 .ToList();
866
867 foreach (var key in completed)
868 _pendingTileFetches.Remove(key);
869 }
870
871 // Request a render update if we prefetched any tiles
872 if (fetchTasks.Count > 0 && !token.IsCancellationRequested)
873 RequestDeferredRender();
874 }, token);
875 }
876 public void RequestDeferredRender()
877 {
878 lock (_renderLock)
879 {
880 _pendingRender = true;
881
882 // Reset timer - only render after 50ms of no requests
883 _renderTimer?.Dispose();
884 _renderTimer = new System.Threading.Timer(
885 _ => ExecuteDeferredRender(),
886 null,
887 20, // Delay in milliseconds
888 Timeout.Infinite
889 );
890 }
891 }
892 private void ExecuteDeferredRender()
893 {
894 lock (_renderLock)
895 {
896 if (!_pendingRender) return;
897 _pendingRender = false;
898 }
899
900 // Execute on UI thread
901 Gtk.Application.Invoke((sender, args) =>
902 {
903 UpdateView(true);
904 });
905 }
906 bool initrend = false;
907 #endregion
908 private void DrawViewportRectangle(SKCanvas canvas, SKPaint paint)
909 {
910 if (SelectedImage == null || !SelectedImage.isPyramidal || !ShowOverview)
911 return;
912
913 try
914 {
915 // 1. Get the scale factor of the CURRENT level relative to Full Res (Level 0)
916 // LevelScale is typically: CurrentLevelWidth / FullResWidth
917 double levelScale = (double)SelectedImage.Resolutions[Level].SizeX / SelectedImage.SizeX;
918
919 // 2. Convert PyramidalOrigin (Current Level) to Full Res (Level 0)
920 double fullResX = PyramidalOrigin.X / levelScale;
921 double fullResY = PyramidalOrigin.Y / levelScale;
922 double fullResW = AllocatedWidth / levelScale;
923 double fullResH = AllocatedHeight / levelScale;
924
925 // 3. Project Full Res to Overview Space
926 float ovScaleX = (float)overview.Width / SelectedImage.SizeX;
927 float ovScaleY = (float)overview.Height / SelectedImage.SizeY;
928
929 float ovX = (float)(fullResX * ovScaleX);
930 float ovY = (float)(fullResY * ovScaleY);
931 float ovW = (float)(fullResW * ovScaleX);
932 float ovH = (float)(fullResH * ovScaleY);
933
934 // 4. Clamp to overview bounds
935 float rectLeft = Math.Max(0, ovX);
936 float rectTop = Math.Max(0, ovY);
937 float rectRight = Math.Min((float)overview.Width, ovX + ovW);
938 float rectBottom = Math.Min((float)overview.Height, ovY + ovH);
939
940 // 5. Draw
941 if (rectRight > rectLeft && rectBottom > rectTop)
942 {
943 paint.Style = SKPaintStyle.Stroke;
944 paint.StrokeWidth = 1f;
945 paint.Color = SKColors.Gray;
946 paint.IsAntialias = true;
947
948 canvas.DrawRect(rectLeft, rectTop, rectRight - rectLeft, rectBottom - rectTop, paint);
949 }
950 }
951 catch (Exception ex)
952 {
953 System.Diagnostics.Debug.WriteLine($"Error: {ex.Message}");
954 }
955 }
956 private void SetResolution(double newResolution, PointD mouseScreenPos)
957 {
958 if (newResolution <= 0 || newResolution == Resolution)
959 return;
960
961 double oldResolution = Resolution;
962
963 // 1. Compute image pixel under cursor BEFORE zoom
964 PointD imagePixel = new PointD(
965 PyramidalOrigin.X + mouseScreenPos.X * oldResolution,
966 PyramidalOrigin.Y + mouseScreenPos.Y * oldResolution
967 );
968
969 // 2. Apply zoom
970 Resolution = newResolution;
971
972 // 3. Recompute origin so the same image pixel stays under cursor
973 PyramidalOrigin = new PointD(
974 imagePixel.X - mouseScreenPos.X * Resolution,
975 imagePixel.Y - mouseScreenPos.Y * Resolution
976 );
977 }
978 public void SetTitle(string s)
979 {
980 this.Title = s;
981 }
982 // In your resize handler
983 private void OnViewResized(object sender, EventArgs e)
984 {
985 if (SelectedImage?.isPyramidal == true)
986 {
987 UpdateView(true);
988 UpdateImages();
989 }
990 }
991
992 // Add these fields to ImageView class
993 private System.Threading.Timer _renderTimer;
994 private volatile bool _pendingRender = false;
995 private readonly object _renderLock = new object();
996 private CancellationTokenSource _tileFetchCancellation;
997 private Dictionary<TileIndex, Task<byte[]>> _pendingTileFetches = new Dictionary<TileIndex, Task<byte[]>>();
998 private List<SKImage> SKImages = new List<SKImage>();
999 private List<Bitmap> Bitmaps = new List<Bitmap>();
1001 public void UpdateImages(bool force = false)
1002 {
1003 if (SelectedImage == null)
1004 return;
1005 if (zBar.Adjustment.Upper != SelectedImage.SizeZ - 1 ||
1006 tBar.Adjustment.Upper != SelectedImage.SizeT - 1)
1007 {
1008 UpdateGUI();
1009 }
1010 if (!MacOS)
1011 {
1012 if (SelectedImage.isPyramidal && glArea.AllocatedWidth > 1 && glArea.AllocatedHeight > 1)
1013 {
1014 // Use the new renderer - no more ReadPixels!
1015 _ = slideRenderer.UpdateViewAsync(
1016 PyramidalOrigin,
1017 glArea.AllocatedWidth,
1018 glArea.AllocatedHeight,
1019 Resolution,
1021 );
1022 }
1023 else if (!SelectedImage.isPyramidal)
1024 {
1025 for (int i = 0; i < SKImages.Count; i++)
1026 {
1027 SKImages[i].Dispose();
1028 Bitmaps[i].Dispose();
1029 }
1030 SKImages.Clear();
1031 Bitmaps.Clear();
1032 foreach (BioImage b in Images)
1033 {
1034 ZCT c = GetCoordinate();
1035 AForge.Bitmap bitmap = null;
1036 int index = b.GetFrameIndex(c.Z, c.C, c.T);
1037 if (Mode == ViewMode.Filtered)
1038 {
1039 bitmap = b.GetFiltered(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1040 }
1041 else if (Mode == ViewMode.RGBImage)
1042 {
1043 bitmap = b.GetRGBBitmap(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1044 }
1045 else if (Mode == ViewMode.Raw)
1046 {
1047 bitmap = b.Buffers[index];
1048 }
1049 else
1050 {
1051 bitmap = b.GetEmission(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1052 }
1053 if (bitmap == null)
1054 return;
1055 var bm = bitmap.GetImageRGBA();
1056 SKImage skim = BitmapToSKImage(bm);
1057 SKImages.Add(skim);
1058 Bitmaps.Add(bm);
1059 }
1060 }
1061 }
1062 else
1063 {
1064 if (SelectedImage.isPyramidal && sk.AllocatedWidth > 1 && sk.AllocatedHeight > 1)
1065 {
1066 // Use the new renderer - no more ReadPixels!
1067 _ = sKSlideRenderer.UpdateViewAsync(
1068 PyramidalOrigin,
1069 Resolution,
1070 GetCoordinate(),
1071 sk.AllocatedWidth,
1072 sk.AllocatedHeight
1073 );
1074 }
1075 else if (!SelectedImage.isPyramidal)
1076 {
1077 for (int i = 0; i < SKImages.Count; i++)
1078 {
1079 SKImages[i].Dispose();
1080 Bitmaps[i].Dispose();
1081 }
1082 SKImages.Clear();
1083 Bitmaps.Clear();
1084 foreach (BioImage b in Images)
1085 {
1086 ZCT c = GetCoordinate();
1087 AForge.Bitmap bitmap = null;
1088 int index = b.GetFrameIndex(c.Z, c.C, c.T);
1089 if (Mode == ViewMode.Filtered)
1090 {
1091 bitmap = b.GetFiltered(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1092 }
1093 else if (Mode == ViewMode.RGBImage)
1094 {
1095 bitmap = b.GetRGBBitmap(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1096 }
1097 else if (Mode == ViewMode.Raw)
1098 {
1099 bitmap = b.Buffers[index];
1100 }
1101 else
1102 {
1103 bitmap = b.GetEmission(c, b.RChannel.RangeR, b.GChannel.RangeG, b.BChannel.RangeB);
1104 }
1105 if (bitmap == null)
1106 return;
1107 var bm = bitmap.GetImageRGBA();
1108 SKImage skim = BitmapToSKImage(bm);
1109 SKImages.Add(skim);
1110 Bitmaps.Add(bm);
1111 }
1112 }
1113 }
1114 }
1116 public void UpdateImage()
1117 {
1118 UpdateImages();
1119 }
1120 Rectangle overview;
1121 Bitmap overviewImage;
1122 public int? MacroResolution { get { return SelectedImage.MacroResolution; } }
1123 public int? LabelResolution { get { return SelectedImage.LabelResolution; } }
1124
1129 private void InitPreview()
1130 {
1131 // Only initialize preview for pyramidal images
1132 if (SelectedImage == null || !SelectedImage.isPyramidal)
1133 return;
1134
1135 try
1136 {
1137 refresh = false;
1138
1139 // Default overview size
1140 const int OVERVIEW_SIZE = 160;
1141 const long MAX_SIZE_BYTES = 1500000000; // 1.5GB limit
1142
1143 int resolutionLevel;
1144 BioLib.Resolution targetResolution;
1145
1146 // Determine which resolution level to use
1147 if (MacroResolution.HasValue && MacroResolution.Value >= 2 && MacroResolution.Value <= SelectedImage.Resolutions.Count)
1148 {
1149 // Use macro resolution if available (usually a label or overview image)
1150 resolutionLevel = MacroResolution.Value - 2;
1151 targetResolution = SelectedImage.Resolutions[resolutionLevel];
1152 }
1153 else
1154 {
1155 // Use the lowest resolution pyramid level (highest index)
1156 resolutionLevel = SelectedImage.Resolutions.Count - 1;
1157 targetResolution = SelectedImage.Resolutions[resolutionLevel];
1158 }
1159 Bitmap sourceBitmap = null;
1160 int overviewWidth = 100;
1161 int overviewHeight = 100;
1162 // Check if resolution level is too large to process
1163 if (targetResolution.SizeInBytes > MAX_SIZE_BYTES)
1164 {
1165 Console.WriteLine($"Preview disabled: Resolution level {resolutionLevel} is too large ({targetResolution.SizeInBytes} bytes)");
1166 // Calculate aspect ratio and overview dimensions
1167 double aspectRatio = (double)targetResolution.SizeX / (double)targetResolution.SizeY;
1168 if (aspectRatio >= 1.0)
1169 {
1170 // Landscape or square - width is OVERVIEW_SIZE
1171 overviewWidth = OVERVIEW_SIZE;
1172 overviewHeight = (int)(OVERVIEW_SIZE / aspectRatio);
1173 }
1174 else
1175 {
1176 // Portrait - height is OVERVIEW_SIZE
1177 overviewHeight = OVERVIEW_SIZE;
1178 overviewWidth = (int)(OVERVIEW_SIZE * aspectRatio);
1179 }
1180
1181 // Ensure minimum size
1182 overviewWidth = Math.Max(overviewWidth, 20);
1183 overviewHeight = Math.Max(overviewHeight, 20);
1184
1185 overview = new Rectangle(0, 0, overviewWidth, overviewHeight);
1186
1187 }
1188 else
1189 {
1190 ShowOverview = true;
1191 // Calculate aspect ratio and overview dimensions
1192 double aspectRatio = (double)targetResolution.SizeX / (double)targetResolution.SizeY;
1193 if (aspectRatio >= 1.0)
1194 {
1195 // Landscape or square - width is OVERVIEW_SIZE
1196 overviewWidth = OVERVIEW_SIZE;
1197 overviewHeight = (int)(OVERVIEW_SIZE / aspectRatio);
1198 }
1199 else
1200 {
1201 // Portrait - height is OVERVIEW_SIZE
1202 overviewHeight = OVERVIEW_SIZE;
1203 overviewWidth = (int)(OVERVIEW_SIZE * aspectRatio);
1204 }
1205
1206 // Ensure minimum size
1207 overviewWidth = Math.Max(overviewWidth, 20);
1208 overviewHeight = Math.Max(overviewHeight, 20);
1209
1210 overview = new Rectangle(0, 0, overviewWidth, overviewHeight);
1211
1212 if (openSlide)
1213 {
1214 var sl = new OpenSlideGTK.SliceInfo(0, 0, overviewWidth, overviewHeight, Resolution);
1215 // Get the tile for the entire resolution level
1216 sourceBitmap = new Bitmap(overviewWidth, overviewHeight, AForge.PixelFormat.Format32bppArgb,
1217 SelectedImage.OpenSlideBase.GetSlice(sl, new ZCT(0, 0, 0), Level), GetCoordinate(), "");
1218 }
1219 else
1220 {
1221 var sl = new BioLib.SliceInfo(0, 0, SelectedImage.Resolutions.Last().SizeX, SelectedImage.Resolutions.Last().SizeY,
1222 Resolution, GetCoordinate());
1223 byte[] bt = SelectedImage.SlideBase.GetSlice(sl, new PointD(0, 0), new AForge.Size(overviewWidth, overviewHeight)).Result;
1224 // Get the tile for the entire resolution level
1225 sourceBitmap = new Bitmap(overviewWidth, overviewHeight, AForge.PixelFormat.Format32bppArgb,
1226 bt, GetCoordinate(), "");
1227 }
1228 // Resize to overview dimensions
1229 AForge.Imaging.Filters.ResizeBilinear resizer = new ResizeBilinear(overviewWidth, overviewHeight);
1230 overviewImage = resizer.Apply(sourceBitmap.GetImageRGBA());
1231 sourceBitmap.Dispose();
1232 sourceBitmap = null;
1233 ShowOverview = true;
1234 Console.WriteLine($"Preview initialized: {overviewWidth}x{overviewHeight} from resolution level {resolutionLevel} ({targetResolution.SizeX}x{targetResolution.SizeY})");
1235 }
1236 }
1237 catch (Exception ex)
1238 {
1239 Console.WriteLine($"Error initializing preview: {ex.Message}");
1240 ShowOverview = false;
1241 overviewImage = null;
1242 }
1243 }
1244
1245 #region Handlers
1246
1248 protected void SetupHandlers()
1249 {
1250 zBar.ValueChanged += ValueChangedZ;
1251 cBar.ValueChanged += ValueChangedC;
1252 tBar.ValueChanged += ValueChangedT;
1253 if (MacOS)
1254 {
1255 sk.MotionNotifyEvent += ImageView_MotionNotifyEvent;
1256 sk.ButtonPressEvent += ImageView_ButtonPressEvent;
1257 sk.ButtonReleaseEvent += ImageView_ButtonReleaseEvent;
1258 sk.ScrollEvent += ImageView_ScrollEvent;
1259 sk.ScrollEvent += OnMouseWheel;
1260 sk.PaintSurface += Sk_PaintSurface;
1261 sk.SizeAllocated += PictureBox_SizeAllocated;
1262 sk.SetSizeRequest(600, 400);
1263 sk.AddEvents((int)(EventMask.ButtonPressMask
1264 | EventMask.ButtonReleaseMask
1265 | EventMask.KeyPressMask
1266 | EventMask.PointerMotionMask
1267 | EventMask.ScrollMask));
1268 }
1269 else
1270 {
1271 glArea.MotionNotifyEvent += ImageView_MotionNotifyEvent;
1272 glArea.ButtonPressEvent += ImageView_ButtonPressEvent;
1273 glArea.ButtonReleaseEvent += ImageView_ButtonReleaseEvent;
1274 glArea.ScrollEvent += ImageView_ScrollEvent;
1275 glArea.ScrollEvent += OnMouseWheel;
1276 glArea.Render += GlArea_Render;
1277 glArea.SizeAllocated += PictureBox_SizeAllocated;
1278 glArea.AddEvents((int)(EventMask.ButtonPressMask
1279 | EventMask.ButtonReleaseMask
1280 | EventMask.KeyPressMask
1281 | EventMask.PointerMotionMask
1282 | EventMask.ScrollMask));
1283 }
1284
1285 this.KeyPressEvent += ImageView_KeyPressEvent;
1286 this.DestroyEvent += ImageView_DestroyEvent;
1287 this.DeleteEvent += ImageView_DeleteEvent;
1288 this.FocusInEvent += ImageView_FocusInEvent;
1289 rBox.Changed += RBox_Changed;
1290 gBox.Changed += GBox_Changed;
1291 bBox.Changed += BBox_Changed;
1292 //Context Menu
1293 goToImageMenu.ButtonPressEvent += GoToImageMenu_ButtonPressEvent;
1294 goToOriginMenu.ButtonPressEvent += GoToOriginMenu_ButtonPressEvent;
1295
1296 roiDelete.ButtonPressEvent += RoiDelete_ButtonPressEvent;
1297 roiID.ButtonPressEvent += RoiID_ButtonPressEvent;
1298 copy.ButtonPressEvent += Copy_ButtonPressEvent;
1299 paste.ButtonPressEvent += Paste_ButtonPressEvent;
1300 draw.ButtonPressEvent += Draw_ButtonPressEvent;
1301 fill.ButtonPressEvent += Fill_ButtonPressEvent;
1302
1303 play.ButtonPressEvent += Play_ButtonPressEvent;
1304 stop.ButtonPressEvent += Stop_ButtonPressEvent;
1305 playSpeed.ButtonPressEvent += PlaySpeed_ButtonPressEvent;
1306 setValueRange.ButtonPressEvent += SetValueRange_ButtonPressEvent;
1307 loop.ButtonPressEvent += Loop_ButtonPressEvent;
1308
1309 zBar.ButtonPressEvent += ZBar_ButtonPressEvent;
1310 tBar.ButtonPressEvent += TBar_ButtonPressEvent;
1311 cBar.ButtonPressEvent += CBar_ButtonPressEvent;
1312
1313 }
1314
1315 private void Sk_PaintSurface(object sender, SkiaSharp.Views.Desktop.SKPaintSurfaceEventArgs e)
1316 {
1317 if (MacOS)
1318 {
1319 var canvas = e.Surface.Canvas;
1320 var width = e.Info.Width;
1321 var height = e.Info.Height;
1322 canvas.Clear(SKColors.Black);
1323 if (SelectedImage?.isPyramidal == true && sKSlideRenderer != null)
1324 {
1325 sKSlideRenderer.DrawToCanvas(canvas, width, height);
1326 RenderSkiaAnnotations(canvas, width, height);
1327 }
1328 else
1329 {
1330 // Render non-pyramidal images and annotations
1331 RenderSkia(canvas, width, height);
1332 }
1333 }
1334 }
1335
1336 private void GlArea_Render(object o, RenderArgs args)
1337 {
1338 if (!SelectedImage.isPyramidal)
1339 return;
1340 glArea.MakeCurrent();
1341 if (glArea.Error != 0)
1342 return;
1343 slideRenderer.UpdateViewAsync(
1344 PyramidalOrigin,
1345 glArea.AllocatedWidth,
1346 glArea.AllocatedHeight,
1347 Resolution,
1349 ).Wait();
1350 }
1351
1352 private void ImageView_FocusInEvent(object o, FocusInEventArgs args)
1353 {
1354 //App.SelectWindow(this.Title);
1355 }
1356
1357 private void ImageView_DestroyEvent(object o, DestroyEventArgs args)
1358 {
1359 foreach (var item in this.Images)
1360 {
1361 BioLib.Images.RemoveImage(item);
1362 App.tabsView.RemoveViewer(this);
1363 }
1364 }
1365
1366 int bar = 0;
1367 System.Threading.Thread threadZ = null;
1368 System.Threading.Thread threadC = null;
1369 System.Threading.Thread threadT = null;
1370 static bool playZ = false;
1371 static bool playC = false;
1372 static bool playT = false;
1373 static bool loopZ = true;
1374 static bool loopC = true;
1375 static bool loopT = true;
1376 public static int waitz = 1000;
1377 public static int waitc = 1000;
1378 public static int waitt = 1000;
1379 public static int startz = 0;
1380 public static int startc = 0;
1381 public static int startt = 0;
1382 public static int endz = 0;
1383 public static int endc = 0;
1384 public static int endt = 0;
1388 private static void PlayZ()
1389 {
1390 do
1391 {
1392 ZCT coord = App.viewer.GetCoordinate();
1393 //Update view on main UI thread
1394 Application.Invoke(delegate
1395 {
1396 App.viewer.SetCoordinate(coord.Z + 1, coord.C, coord.T);
1397 });
1398 if (coord.Z == endz)
1399 {
1400 if (loopZ)
1401 {
1402 //Update view on main UI thread
1403 Application.Invoke(delegate
1404 {
1405 App.viewer.SetCoordinate(startz, coord.C, coord.T);
1406 });
1407 }
1408 else
1409 return;
1410 }
1411 System.Threading.Thread.Sleep(waitz);
1412 } while (playZ);
1413 }
1418 private static void PlayC()
1419 {
1420 do
1421 {
1422 ZCT coord = App.viewer.GetCoordinate();
1423 Application.Invoke(delegate
1424 {
1425 App.viewer.SetCoordinate(coord.Z, coord.C + 1, coord.T);
1426 });
1427 if (coord.C == endc)
1428 {
1429 if (loopC)
1430 {
1431 //Update view on main UI thread
1432 Application.Invoke(delegate
1433 {
1434 App.viewer.SetCoordinate(coord.Z, startc, coord.T);
1435 });
1436 }
1437 else
1438 return;
1439 }
1440 System.Threading.Thread.Sleep(waitc);
1441 } while (playC);
1442 }
1447 private static void PlayT()
1448 {
1449 do
1450 {
1451 ZCT coord = App.viewer.GetCoordinate();
1452 Application.Invoke(delegate
1453 {
1454 App.viewer.SetCoordinate(coord.Z, coord.C, coord.T + 1);
1455 });
1456 if (coord.T == endt)
1457 {
1458 if (loopT)
1459 {
1460 //Update view on main UI thread
1461 Application.Invoke(delegate
1462 {
1463 App.viewer.SetCoordinate(coord.Z, coord.C, startt);
1464 });
1465 }
1466 else
1467 return;
1468 }
1469 System.Threading.Thread.Sleep(waitt);
1470 } while (playT);
1471 }
1476 private void CBar_ButtonPressEvent(object o, ButtonPressEventArgs args)
1477 {
1478 bar = 2;
1479 if (args.Event.Button == 3)
1480 barMenu.Popup();
1481 }
1482
1487 private void TBar_ButtonPressEvent(object o, ButtonPressEventArgs args)
1488 {
1489 bar = 1;
1490 if (args.Event.Button == 3)
1491 barMenu.Popup();
1492 }
1493
1498 private void ZBar_ButtonPressEvent(object o, ButtonPressEventArgs args)
1499 {
1500 bar = 0;
1501 if (args.Event.Button == 3)
1502 barMenu.Popup();
1503 }
1504
1509 private void Loop_ButtonPressEvent(object o, ButtonPressEventArgs args)
1510 {
1511 if (bar == 0)
1512 {
1513 if (loopZ)
1514 loopZ = false;
1515 else
1516 loopZ = true;
1517 }
1518 else if (bar == 1)
1519 {
1520 if (loopC)
1521 loopC = false;
1522 else
1523 loopC = true;
1524 }
1525 else if (bar == 2)
1526 {
1527 if (loopT)
1528 loopT = false;
1529 else
1530 loopT = true;
1531 }
1532 }
1533
1539 private void SetValueRange_ButtonPressEvent(object o, ButtonPressEventArgs args)
1540 {
1541 Play play = Play.Create();
1542 play.Show();
1543 }
1544
1549 private void PlaySpeed_ButtonPressEvent(object o, ButtonPressEventArgs args)
1550 {
1551 Play play = Play.Create();
1552 play.Show();
1553 }
1554
1559 private void Stop_ButtonPressEvent(object o, ButtonPressEventArgs args)
1560 {
1561 if (bar == 0)
1562 {
1563 if (playZ)
1564 playZ = false;
1565 else
1566 playZ = true;
1567 }
1568 else if (bar == 1)
1569 {
1570 if (playT)
1571 playT = false;
1572 else
1573 playT = true;
1574 }
1575 else if (bar == 2)
1576 {
1577 if (playC)
1578 playC = false;
1579 else
1580 playC = true;
1581 }
1582 }
1583
1589 private void Play_ButtonPressEvent(object o, ButtonPressEventArgs args)
1590 {
1591 if (bar == 0)
1592 {
1593 if (endz == 0)
1594 endz = SelectedImage.SizeZ - 1;
1595 playZ = true;
1596 threadZ = new System.Threading.Thread(PlayZ);
1597 threadZ.Start();
1598 }
1599 else if (bar == 1)
1600 {
1601 if (endt == 0)
1602 endt = SelectedImage.SizeT - 1;
1603 playT = true;
1604 threadT = new System.Threading.Thread(PlayT);
1605 threadT.Start();
1606 }
1607 else if (bar == 2)
1608 {
1609 if (endc == 0)
1610 endc = SelectedImage.SizeC - 1;
1611 playC = true;
1612 threadC = new System.Threading.Thread(PlayC);
1613 threadC.Start();
1614 }
1615 }
1616
1621 private void Fill_ButtonPressEvent(object o, ButtonPressEventArgs args)
1622 {
1623 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(SelectedBuffer);
1624 List<ROI> rois = new List<ROI>();
1625 rois.AddRange(SelectedImage.AnnotationsR);
1626 rois.AddRange(SelectedImage.AnnotationsG);
1627 rois.AddRange(SelectedImage.AnnotationsB);
1628 foreach (ROI item in rois)
1629 {
1630 Bio.Graphics.Pen p = new Bio.Graphics.Pen(Tools.DrawColor, (int)Tools.StrokeWidth, SelectedBuffer.BitsPerPixel);
1631 if (item.Selected)
1632 {
1633 if (item.type == ROI.Type.Line)
1634 {
1635 PointD pf = SelectedImage.ToImageSpace(item.GetPoint(0));
1636 PointD pf2 = SelectedImage.ToImageSpace(item.GetPoint(1));
1637 g.DrawLine((int)pf.X, (int)pf.Y, (int)pf2.X, (int)pf2.Y);
1638 }
1639 else
1640 if (item.type == ROI.Type.Rectangle)
1641 {
1642 g.FillRectangle(SelectedImage.ToImageSpace(item.BoundingBox), p.color);
1643 }
1644 else
1645 if (item.type == ROI.Type.Ellipse)
1646 {
1647 g.FillEllipse(SelectedImage.ToImageSpace(item.BoundingBox), p.color);
1648 }
1649 else
1650 if (item.type == ROI.Type.Freeform || item.type == ROI.Type.Polygon || item.type == ROI.Type.Polyline)
1651 {
1652 g.FillPolygon(SelectedImage.ToImageSpace(item.GetPointsF()), SelectedImage.ToImageSpace(item.BoundingBox), p.color);
1653 }
1654 }
1655 }
1656 UpdateImage();
1657 UpdateView();
1658 }
1659
1664 private void Draw_ButtonPressEvent(object o, ButtonPressEventArgs args)
1665 {
1666 Bio.Graphics.Graphics g = Bio.Graphics.Graphics.FromImage(SelectedBuffer);
1667 List<ROI> rois = new List<ROI>();
1668 rois.AddRange(SelectedImage.AnnotationsR);
1669 rois.AddRange(SelectedImage.AnnotationsG);
1670 rois.AddRange(SelectedImage.AnnotationsB);
1671 foreach (ROI item in rois)
1672 {
1673 Bio.Graphics.Pen p = new Bio.Graphics.Pen(Tools.DrawColor, (int)Tools.StrokeWidth, SelectedBuffer.BitsPerPixel);
1674 g.pen = p;
1675 if (item.Selected)
1676 {
1677 if (item.type == ROI.Type.Line)
1678 {
1679 PointD pf = SelectedImage.ToImageSpace(item.GetPoint(0));
1680 PointD pf2 = SelectedImage.ToImageSpace(item.GetPoint(1));
1681 g.DrawLine((int)pf.X, (int)pf.Y, (int)pf2.X, (int)pf2.Y);
1682 }
1683 else
1684 if (item.type == ROI.Type.Rectangle)
1685 {
1686 g.DrawRectangle(SelectedImage.ToImageSpace(item.BoundingBox));
1687 }
1688 else
1689 if (item.type == ROI.Type.Ellipse)
1690 {
1691 g.DrawEllipse(SelectedImage.ToImageSpace(item.BoundingBox));
1692 }
1693 else
1694 if (item.type == ROI.Type.Freeform || item.type == ROI.Type.Polygon || item.type == ROI.Type.Polyline)
1695 {
1696 if (item.closed)
1697 {
1698 for (int i = 0; i < item.GetPointCount() - 1; i++)
1699 {
1700 PointD pf = SelectedImage.ToImageSpace(item.GetPoint(i));
1701 PointD pf2 = SelectedImage.ToImageSpace(item.GetPoint(i + 1));
1702 g.DrawLine((int)pf.X, (int)pf.Y, (int)pf2.X, (int)pf2.Y);
1703 }
1704 PointD pp = SelectedImage.ToImageSpace(item.GetPoint(0));
1705 PointD p2 = SelectedImage.ToImageSpace(item.GetPoint(item.GetPointCount() - 1));
1706 g.DrawLine((int)pp.X, (int)pp.Y, (int)p2.X, (int)p2.Y);
1707 }
1708 else
1709 {
1710 for (int i = 0; i < item.GetPointCount() - 1; i++)
1711 {
1712 PointD pf = SelectedImage.ToImageSpace(item.GetPoint(i));
1713 PointD pf2 = SelectedImage.ToImageSpace(item.GetPoint(i + 1));
1714 g.DrawLine((int)pf.X, (int)pf.Y, (int)pf2.X, (int)pf2.Y);
1715 }
1716 }
1717 }
1718 }
1719 }
1720 UpdateImage();
1721 UpdateView();
1722 }
1723
1729 private void Paste_ButtonPressEvent(object o, ButtonPressEventArgs args)
1730 {
1732 }
1733
1739 private void Copy_ButtonPressEvent(object o, ButtonPressEventArgs args)
1740 {
1741 CopySelection();
1742 }
1743
1749 private void ImageView_DeleteEvent(object o, DeleteEventArgs args)
1750 {
1751 for (int i = 0; i < this.Images.Count; i++)
1752 {
1753 var item = this.Images[i];
1754 App.CloseWindow(item.Filename);
1755 }
1756 }
1757
1767 private void RoiID_ButtonPressEvent(object o, ButtonPressEventArgs args)
1768 {
1769 TextInput ti = TextInput.Create();
1770 ti.Show();
1771 UpdateView();
1772 }
1773
1779 private void RoiDelete_ButtonPressEvent(object o, ButtonPressEventArgs args)
1780 {
1781 foreach (var item in selectedAnnotations)
1782 {
1783 SelectedImage.Annotations.Remove(item);
1784 //Tools.selectedROI = null;
1785 }
1786 UpdateView();
1787 }
1788
1795 private void GoToOriginMenu_ButtonPressEvent(object o, ButtonPressEventArgs args)
1796 {
1797 App.viewer.Origin = new PointD(-SelectedImage.Volume.Location.X, -SelectedImage.Volume.Location.Y);
1798 }
1799
1805 private void GoToImageMenu_ButtonPressEvent(object o, ButtonPressEventArgs args)
1806 {
1807 App.viewer.GoToImage();
1808 }
1809
1810 #endregion
1811
1817 private void BBox_Changed(object sender, EventArgs e)
1818 {
1819 SelectedImage.rgbChannels[2] = bBox.Active;
1820 UpdateView();
1821 }
1822
1827 private void GBox_Changed(object sender, EventArgs e)
1828 {
1829 SelectedImage.rgbChannels[1] = gBox.Active;
1830 UpdateView();
1831 }
1832
1838 private void RBox_Changed(object sender, EventArgs e)
1839 {
1840 SelectedImage.rgbChannels[0] = rBox.Active;
1841 UpdateView();
1842 }
1843
1844 bool initialized = false;
1851 private void PictureBox_SizeAllocated(object o, SizeAllocatedArgs args)
1852 {
1853 if (SelectedImage == null) return;
1854 if (!MacOS)
1855 {
1856 if (SelectedImage.isPyramidal)
1857 {
1858 SelectedImage.PyramidalSize = new AForge.Size(glArea.AllocatedWidth, glArea.AllocatedHeight);
1859 UpdateImage();
1860 }
1861 }
1862 else
1863 {
1864 SelectedImage.PyramidalSize = new AForge.Size(sk.AllocatedWidth, sk.AllocatedHeight);
1865 UpdateImage();
1866 }
1867 if (!initialized)
1868 {
1869 GoToImage();
1870 initialized = true;
1871 }
1872 UpdateView();
1873 }
1874
1882 private static void DrawEllipse(Cairo.Context g, double x, double y, double width, double height)
1883 {
1884 g.Save();
1885 g.MoveTo(x + (width / 2), y);
1886 g.Translate(x, y);
1887 g.Scale(width / 2.0, height / 2.0);
1888 g.Arc(0.0, 0.0, 1.0, 0.0, 2 * Math.PI);
1889 g.Restore();
1890 g.Stroke();
1891 g.Stroke();
1892 }
1898 public static Cairo.Color FromColor(Color color)
1899 {
1900 return new Cairo.Color((double)color.R / 255, (double)color.G / 255, (double)color.B / 255);
1901 }
1902
1909 private void TBar_ScrollEvent(object o, ScrollEventArgs args)
1910 {
1911 if (args.Event.Direction == ScrollDirection.Up)
1912 {
1913 if (tBar.Value + 1 <= tBar.Adjustment.Upper)
1914 tBar.Value += 1;
1915 }
1916 else
1917 {
1918 if (tBar.Value - 1 >= 0)
1919 tBar.Value -= 1;
1920 }
1921 UpdateView(true);
1922 }
1929 private void CBar_ScrollEvent(object o, ScrollEventArgs args)
1930 {
1931 if (args.Event.Direction == ScrollDirection.Up)
1932 {
1933 if (cBar.Value + 1 <= cBar.Adjustment.Upper)
1934 cBar.Value += 1;
1935 }
1936 else
1937 {
1938 if (cBar.Value - 1 >= 0)
1939 cBar.Value -= 1;
1940 }
1941 UpdateView(true);
1942 }
1949 private void ZBar_ScrollEvent(object o, ScrollEventArgs args)
1950 {
1951 if (args.Event.Direction == ScrollDirection.Up)
1952 {
1953 if (zBar.Value + 1 <= zBar.Adjustment.Upper)
1954 zBar.Value += 1;
1955 }
1956 else
1957 {
1958 if (zBar.Value - 1 >= 0)
1959 zBar.Value -= 1;
1960 }
1961 UpdateView(true);
1962 }
1963
1964 public static Gdk.Key keyDown = Gdk.Key.Key_3270_Test;
1973 private void ImageView_KeyPressEvent(object o, KeyPressEventArgs e)
1974 {
1975 Plugins.KeyDownEvent(o, e);
1976 keyDown = e.Event.Key;
1977 double moveAmount = 5 * Scale.Width;
1978 double zoom = Level;
1979 double movepyr = 50 * (Level + 1);
1980 if (e.Event.Key == Gdk.Key.c && e.Event.State == ModifierType.ControlMask)
1981 {
1982 CopySelection();
1983 }
1984 if (e.Event.Key == Gdk.Key.v && e.Event.State == ModifierType.ControlMask)
1985 {
1987 }
1988 if (e.Event.Key == Gdk.Key.e)
1989 {
1990 if (SelectedImage.isPyramidal)
1991 {
1992 Resolution--;
1993 }
1994 else
1995 Scale = new SizeF(Scale.Width - 0.1f, Scale.Height - 0.1f);
1996 }
1997 if (e.Event.Key == Gdk.Key.q)
1998 {
1999 if (SelectedImage.isPyramidal)
2000 {
2001 Resolution++;
2002 }
2003 else
2004 Scale = new SizeF(Scale.Width + 0.1f, Scale.Height + 0.1f);
2005 }
2006 if (e.Event.Key == Gdk.Key.s || e.Event.Key == Gdk.Key.S)
2007 {
2008 if (SelectedImage.isPyramidal)
2009 {
2010 PyramidalOrigin = new PointD(PyramidalOrigin.X, PyramidalOrigin.Y + movepyr);
2011 }
2012 else
2013 Origin = new PointD(Origin.X, Origin.Y + moveAmount);
2014 }
2015 if (e.Event.Key == Gdk.Key.w || e.Event.Key == Gdk.Key.W)
2016 {
2017 if (SelectedImage.isPyramidal)
2018 {
2019 PyramidalOrigin = new PointD(PyramidalOrigin.X, PyramidalOrigin.Y - movepyr);
2020 }
2021 else
2022 Origin = new PointD(Origin.X, Origin.Y - moveAmount);
2023 }
2024 if (e.Event.Key == Gdk.Key.a || e.Event.Key == Gdk.Key.A)
2025 {
2026 if (SelectedImage.isPyramidal)
2027 {
2028 PyramidalOrigin = new PointD(PyramidalOrigin.X - movepyr, PyramidalOrigin.Y);
2029 }
2030 else
2031 Origin = new PointD(Origin.X + moveAmount, Origin.Y);
2032 }
2033 if (e.Event.Key == Gdk.Key.d || e.Event.Key == Gdk.Key.D)
2034 {
2035 if (SelectedImage.isPyramidal)
2036 {
2037 PyramidalOrigin = new PointD(PyramidalOrigin.X + movepyr, PyramidalOrigin.Y);
2038 }
2039 else
2040 Origin = new PointD(Origin.X - moveAmount, Origin.Y);
2041 }
2042 if (e.Event.Key == Gdk.Key.e)
2043 {
2044 Resolution += zoom;
2045 }
2046 if (e.Event.Key == Gdk.Key.q)
2047 {
2048 Resolution -= zoom;
2049 }
2050 foreach (Function item in Function.Functions.Values)
2051 {
2052 if (item.Key == e.Event.Key && item.Modifier == e.Event.State)
2053 {
2054 if (item.FuncType == Function.FunctionType.ImageJ)
2055 item.PerformFunction(true);
2056 else
2057 item.PerformFunction(false);
2058 }
2059 }
2060 Scripting.State st = new Scripting.State();
2061 st.key = e.Event.Key;
2062 st.p = mouseDown;
2063 st.type = Scripting.Event.Down;
2064 Scripting.UpdateState(st);
2065 UpdateView(true);
2066 }
2072 private void ImageView_KeyUpEvent(object o, KeyReleaseEventArgs e)
2073 {
2074 Plugins.KeyUpEvent(o, e);
2075 keyDown = Gdk.Key.Key_3270_Test;
2076 Scripting.State st = new Scripting.State();
2077 st.key = e.Event.Key;
2078 st.p = mouseUp;
2079 st.type = Scripting.Event.Up;
2080 Scripting.UpdateState(st);
2081 }
2089 private void ImageView_ScrollEvent(object o, ScrollEventArgs e)
2090 {
2091 Plugins.ScrollEvent(o, e);
2092 if (SelectedImage.isPyramidal)
2093 {
2094 if (e.Event.Direction == ScrollDirection.Up)
2095 SelectedImage.Resolution *= 1.1;
2096 if (e.Event.Direction == ScrollDirection.Down)
2097 SelectedImage.Resolution *= 0.9;
2098 }
2099 }
2100
2105 private void ValueChangedZ(object? sender, EventArgs e)
2106 {
2107 SetCoordinate((int)zBar.Value, (int)cBar.Value, (int)tBar.Value);
2108 UpdateView(true);
2109 }
2114 private void ValueChangedC(object? sender, EventArgs e)
2115 {
2116 SetCoordinate((int)zBar.Value, (int)cBar.Value, (int)tBar.Value);
2117 UpdateView(true);
2118 }
2123 private void ValueChangedT(object? sender, EventArgs e)
2124 {
2125 SetCoordinate((int)zBar.Value, (int)cBar.Value, (int)tBar.Value);
2126 UpdateView(true);
2127 }
2129 public void UpdateGUI()
2130 {
2131 cBar.Adjustment.Lower = 0;
2132 cBar.Adjustment.Upper = Images[selectedIndex].SizeC - 1;
2133 zBar.Adjustment.Lower = 0;
2134 zBar.Adjustment.Upper = Images[selectedIndex].SizeZ - 1;
2135 tBar.Adjustment.Lower = 0;
2136 tBar.Adjustment.Upper = Images[selectedIndex].SizeT - 1;
2137 if (endz == 0 || endz > Images[selectedIndex].SizeZ - 1)
2138 endz = Images[selectedIndex].SizeZ - 1;
2139 if (endc == 0 || endc > Images[selectedIndex].SizeC - 1)
2140 endc = Images[selectedIndex].SizeC - 1;
2141 if (endt == 0 || endt > Images[selectedIndex].SizeT - 1)
2142 endt = Images[selectedIndex].SizeT - 1;
2143 var store = new ListStore(typeof(string));
2144 foreach (Channel c in SelectedImage.Channels)
2145 {
2146 store.AppendValues(c.Name);
2147 }
2148 // Set the model for the ComboBox
2149 rBox.Model = store;
2150 gBox.Model = store;
2151 bBox.Model = store;
2152 if (SelectedImage.Channels.Count > 2)
2153 {
2154 rBox.Active = 0;
2155 gBox.Active = 1;
2156 bBox.Active = 2;
2157 }
2158 else
2159 if (SelectedImage.Channels.Count == 2)
2160 {
2161 rBox.Active = 0;
2162 gBox.Active = 1;
2163 }
2164 imagesMenu = new Menu();
2165 foreach (BioImage b in Images)
2166 {
2167 MenuItem mi = new MenuItem(b.Filename);
2168 mi.ButtonPressEvent += Mi_ButtonPressEvent;
2169 imagesMenu.Append(mi);
2170 }
2171 goToImageMenu.Submenu = imagesMenu;
2172 goToImageMenu.ShowAll();
2173 }
2174
2183 private void Mi_ButtonPressEvent(object o, ButtonPressEventArgs args)
2184 {
2185 MenuItem menuItem = (MenuItem)o;
2186 int i = 0;
2187 foreach (BioImage b in Images)
2188 {
2189 if (b.Filename == menuItem.Label)
2190 {
2191 GoToImage(i);
2192 return;
2193 }
2194 i++;
2195 }
2196 }
2197
2199 public void CopySelection()
2200 {
2201 copys.Clear();
2202 string s = "";
2203 List<ROI> rois = new List<ROI>();
2204 rois.AddRange(SelectedImage.AnnotationsR);
2205 rois.AddRange(SelectedImage.AnnotationsG);
2206 rois.AddRange(SelectedImage.AnnotationsB);
2207 foreach (ROI item in rois)
2208 {
2209 if (item.Selected)
2210 {
2211 copys.Add(item);
2212 s += BioImage.ROIToString(item);
2213 }
2214 }
2215 Clipboard clipboard = Clipboard.Get(Gdk.Selection.Clipboard);
2216 clipboard.Text = s;
2217 }
2220 public void PasteSelection()
2221 {
2222 Clipboard clipboard = Clipboard.Get(Gdk.Selection.Clipboard);
2223 string text = clipboard.WaitForText();
2224 string[] sts = text.Split(BioImage.NewLine);
2225 foreach (string line in sts)
2226 {
2227 if (line.Length > 8)
2228 {
2229 ROI an = BioImage.StringToROI(line);
2230 //We set the coordinates of the ROI's we are pasting
2231 an.coord = GetCoordinate();
2232 SelectedImage.Annotations.Add(an);
2233 }
2234 }
2235 UpdateView();
2236 }
2237
2238 /* Defining an enum. */
2239 public enum ViewMode
2240 {
2241 Raw,
2242 Filtered,
2243 RGBImage,
2244 Emission,
2245 }
2246 bool openSlide = false;
2247 public bool OpenSlide
2248 {
2249 get { return openSlide; }
2250 set { openSlide = value; }
2251 }
2252 public static BioImage SelectedImage
2253 {
2254 get
2255 {
2256 if (App.viewer == null)
2257 return null;
2258 if (App.viewer.Images.Count == 0)
2259 return null;
2260 return App.viewer.Images[App.viewer.SelectedIndex];
2261 }
2262 set
2263 {
2264 App.viewer.Images[App.viewer.SelectedIndex] = value;
2265 }
2266 }
2267 private ViewMode viewMode = ViewMode.Filtered;
2268 /* Setting the view mode of the application. */
2269 public ViewMode Mode
2270 {
2271 get
2272 {
2273 return viewMode;
2274 }
2275 set
2276 {
2277 viewMode = value;
2278 if (viewMode == ViewMode.RGBImage)
2279 {
2280 rgbStack.VisibleChild = rgbStack.Children[1];
2281 }
2282 else
2283 if (viewMode == ViewMode.Filtered)
2284 {
2285 rgbStack.VisibleChild = rgbStack.Children[0];
2286 }
2287 else
2288 if (viewMode == ViewMode.Raw)
2289 {
2290 rgbStack.VisibleChild = rgbStack.Children[0];
2291 }
2292 else
2293 {
2294 rgbStack.VisibleChild = rgbStack.Children[0];
2295 }
2296 }
2297 }
2298 /* A property that returns the R channel of the selected image. */
2299 public Channel RChannel
2300 {
2301 get
2302 {
2303 return SelectedImage.Channels[SelectedImage.rgbChannels[0]];
2304 }
2305 }
2306 /* A property that returns the G channel of the selected image. */
2307 public Channel GChannel
2308 {
2309 get
2310 {
2311 return SelectedImage.Channels[SelectedImage.rgbChannels[1]];
2312 }
2313 }
2314 /* A property that returns the B channel of the selected image. */
2315 public Channel BChannel
2316 {
2317 get
2318 {
2319 return SelectedImage.Channels[SelectedImage.rgbChannels[2]];
2320 }
2321 }
2322 PointD origin = new PointD(0, 0);
2323 /* Origin of the viewer in microns */
2324 public PointD Origin
2325 {
2326 get { return origin; }
2327 set
2328 {
2329 if (AllowNavigation)
2330 origin = value;
2331 if (sk != null)
2332 {
2333 UpdateImages();
2334 sk.QueueDraw();
2335 }
2336 }
2337 }
2338 /* Origin of the viewer in microns */
2339 public PointD TopRightOrigin
2340 {
2341 get
2342 {
2343 return new PointD((Origin.X - ((glArea.AllocatedWidth / 2) * pxWmicron)), (Origin.Y - ((glArea.AllocatedHeight / 2) * pxHmicron)));
2344 }
2345 }
2346 public PointD PyramidalOriginTransformed
2347 {
2348 get { return new PointD(PyramidalOrigin.X * Resolution, PyramidalOrigin.Y * Resolution); }
2349 set { PyramidalOrigin = new PointD(value.X / Resolution, value.Y / Resolution); }
2350 }
2351
2352 /* Setting the origin of a pyramidal image. */
2353 public PointD PyramidalOrigin
2354 {
2355 get
2356 {
2357 return SelectedImage.PyramidalOrigin;
2358 }
2359 set
2360 {
2361 if (!AllowNavigation)
2362 return;
2363 SelectedImage.PyramidalOrigin = value;
2364 if (sk != null)
2365 {
2366 UpdateImages();
2367 sk.QueueDraw();
2368 }
2369 }
2370 }
2371 // Mouse wheel handler
2372 public void OnMouseWheel(object sender, ScrollEventArgs e)
2373 {
2374 if (e.Event.Direction == ScrollDirection.Up)
2375 ZoomAtPoint(PyramidalOrigin.X, PyramidalOrigin.Y, false);
2376 else if (e.Event.Direction == ScrollDirection.Down)
2377 ZoomAtPoint(PyramidalOrigin.X, PyramidalOrigin.Y, true);
2378 }
2379 public void ZoomAtPoint(double mouseX, double mouseY, bool zoomIn)
2380 {
2381 if (SelectedImage == null) return;
2382 float CurrentLevelWidth = SelectedImage.Resolutions[Level].SizeX;
2383 float CurrentLevelHeight = SelectedImage.Resolutions[Level].SizeY;
2384 // 1. Define zoom factor (e.g., 2.0x zoom steps)
2385 float zoomFactor = zoomIn ? 2.0f : 0.5f;
2386
2387 // 2. Get the current level's scale relative to Full Res (Level 0)
2388 // Formula: CurrentLevelWidth / FullResWidth
2389 double currentLevelScale = (double)CurrentLevelWidth / SelectedImage.Resolutions[0].SizeX;
2390
2391 // 3. Find the "World Point" (Full Res Level 0) currently under the mouse
2392 // We add the origin to the mouse offset and then scale up to Level 0
2393 double worldX = (PyramidalOrigin.X + mouseX) / currentLevelScale;
2394 double worldY = (PyramidalOrigin.Y + mouseY) / currentLevelScale;
2395
2396 // 5. Get the NEW level's scale relative to Full Res
2397 double newLevelScale = (double)CurrentLevelWidth / SelectedImage.Resolutions[0].SizeX;
2398
2399 // 6. Calculate the NEW PyramidalOrigin
2400 // To keep the world point at the same mouse position:
2401 // NewOrigin = (WorldPoint * NewScale) - MouseOffset
2402 float newOriginX = (float)(worldX * newLevelScale - mouseX);
2403 float newOriginY = (float)(worldY * newLevelScale - mouseY);
2404
2405 // 7. Apply and Clamp (to ensure we don't scroll past image edges)
2406 PyramidalOrigin = new PointD(
2407 Math.Max(0, Math.Min(newOriginX, CurrentLevelWidth - AllocatedWidth)),
2408 Math.Max(0, Math.Min(newOriginY, CurrentLevelHeight - AllocatedHeight))
2409 );
2410 }
2411 public double Resolution
2412 {
2413 get
2414 {
2415 if (!SelectedImage.isPyramidal)
2416 return 1;
2417 return SelectedImage.Resolution;
2418 }
2419 set
2420 {
2421 if (SelectedImage.isPyramidal)
2422 SelectedImage.Resolution = value;
2423 if (sk != null)
2424 {
2425 UpdateImages();
2426 sk.QueueDraw();
2427 }
2428 }
2429 }
2430
2431 private void UpdateLevel()
2432 {
2433 if (SelectedImage.isPyramidal)
2434 {
2435 if (l != ImageView.SelectedImage.Level)
2436 {
2437 if (openSlide)
2438 for (int j = 0; j < ImageView.SelectedImage.OpenSlideBase.stitch.gpuTiles.Count; j++)
2439 {
2440 var tile = ImageView.SelectedImage.OpenSlideBase.stitch.gpuTiles[j];
2441 if (tile.Index.Level != Level)
2442 {
2443 tile.Dispose();
2444 }
2445 }
2446 else
2447 for (int j = 0; j < ImageView.SelectedImage.SlideBase.stitch.gpuTiles.Count; j++)
2448 {
2449 var tile = ImageView.SelectedImage.SlideBase.stitch.gpuTiles[j];
2450 if (tile.Index.Level != Level)
2451 {
2452 tile.Dispose();
2453 }
2454 }
2455 l = ImageView.SelectedImage.Level;
2456 }
2457 }
2458 }
2459
2460 private int l;
2461 public int Level
2462 {
2463 get
2464 {
2465 if (SelectedImage.Type == BioImage.ImageType.well)
2466 {
2467 return (int)SelectedImage.Level;
2468 }
2469 if (SelectedImage.isPyramidal)
2470 if (!openSlide)
2471 l = OpenSlideGTK.TileUtil.GetLevel(_slideBase.Schema.Resolutions, Resolution);
2472 else
2473 l = OpenSlideGTK.TileUtil.GetLevel(_openSlideBase.Schema.Resolutions, Resolution);
2474 return l;
2475 }
2476 set
2477 {
2478 if (value < 0)
2479 return;
2480 if (l != value)
2481 {
2482 UpdateLevel();
2483 }
2484 l = value;
2485 SelectedImage.Level = l;
2486 if (SelectedImage.Type == BioImage.ImageType.well)
2487 {
2488 SelectedImage.UpdateBuffersWells();
2489 UpdateView();
2490 }
2491 }
2492 }
2493
2494 SizeF scale = new SizeF(1, 1);
2495 /* A property that is used to set the scale of the view. */
2496 public SizeF Scale
2497 {
2498 get
2499 {
2500 return scale;
2501 }
2502 set
2503 {
2504 scale = value;
2505 }
2506 }
2508 public void UpdateStatus()
2509 {
2510 if (SelectedImage.Buffers.Count == 0)
2511 return;
2512 if (SelectedImage.Type == BioImage.ImageType.well)
2513 {
2514 statusLabel.Text = (zBar.Value + 1) + "/" + (zBar.Adjustment.Upper + 1) + ", " + (cBar.Value + 1) + "/" + (cBar.Adjustment.Upper + 1) + ", " + (tBar.Value + 1) + "/" + (tBar.Adjustment.Upper + 1) + ", " +
2515 mousePoint + mouseColor + ", " + SelectedImage.Buffers[0].PixelFormat.ToString() + ", (" + SelectedImage.Volume.Location.X.ToString("N2") + ", " + SelectedImage.Volume.Location.Y.ToString("N2") + ") "
2516 + Origin.X.ToString("N2") + "," + Origin.Y.ToString("N2") + " , Well:" + SelectedImage.Level;
2517 }
2518 else
2519 statusLabel.Text = (zBar.Value + 1) + "/" + (zBar.Adjustment.Upper + 1) + ", " + (cBar.Value + 1) + "/" + (cBar.Adjustment.Upper + 1) + ", " + (tBar.Value + 1) + "/" + (tBar.Adjustment.Upper + 1) + ", " +
2520 mousePoint + mouseColor + ", " + SelectedImage.Buffers[0].PixelFormat.ToString() + ", (" + SelectedImage.Volume.Location.X.ToString("N2") + ", " + SelectedImage.Volume.Location.Y.ToString("N2") + ") "
2521 + Origin.X.ToString("N2") + "," + Origin.Y.ToString("N2") + ", Res:" + Resolution + " Level:" + Level;
2522 }
2524 public void UpdateView(bool updateImages = true)
2525 {
2526 refresh = true;
2527 if (SelectedImage?.isPyramidal == true)
2528 {
2529 if (!MacOS)
2530 {
2531 // Trigger async tile update
2532 _ = slideRenderer.UpdateViewAsync(
2533 PyramidalOrigin,
2534 glArea.AllocatedWidth,
2535 glArea.AllocatedHeight,
2536 Resolution,
2538 );
2539 }
2540 else
2541 {
2542 AForge.Size s = new AForge.Size();
2543 if (sk.AllocatedWidth <= 1 || sk.AllocatedHeight <= 1)
2544 s = new AForge.Size(600, 400);
2545 else
2546 s = new AForge.Size(sk.AllocatedWidth, sk.AllocatedHeight);
2547 // Trigger async tile update
2548 _ = sKSlideRenderer.UpdateViewAsync(
2549 PyramidalOrigin,
2550 Resolution,
2551 GetCoordinate(),
2552 s.Width,
2553 s.Height
2554 );
2555 }
2556 }
2557 else
2558 {
2559 UpdateImages(true);
2560 if (!MacOS)
2561 {
2562 glArea.RequestRedraw();
2563 }
2564 else
2565 sk.QueueDraw();
2566 }
2567 }
2568 private string mousePoint = "";
2569 private string mouseColor = "";
2570
2571 public bool showRROIs = true;
2572 public bool showGROIs = true;
2573 public bool showBROIs = true;
2574
2575 public double GetScale()
2576 {
2577 return ToViewSizeW(ROI.selectBoxSize / Scale.Width);
2578 }
2579 public static bool x1State;
2580 public static bool x2State;
2581 public static bool mouseLeftState;
2582 public static ModifierType Modifiers;
2583 PointD mouseD = new PointD(0, 0);
2584 PointD pd;
2585 PointD mouseDownInt = new PointD(0, 0);
2586 PointD mouseMoveInt = new PointD(0, 0);
2587 PointD mouseUpInt = new PointD(0, 0);
2588 PointD mouseUp = new PointD(0, 0);
2589 PointD mouseDown = new PointD(0, 0);
2590 PointD mouseMove = new PointD(0, 0);
2591 public ROI selectedROI = new ROI();
2592 /* A property that returns the value of the mouseDownInt variable. */
2593 public PointD MouseDownInt
2594 {
2595 get { return mouseDownInt; }
2596 set { mouseDownInt = value; }
2597 }
2598 public PointD MouseMoveInt
2599 {
2600 get { return mouseMoveInt; }
2601 set { mouseMoveInt = value; }
2602 }
2603 public PointD MouseUpInt
2604 {
2605 get { return mouseUpInt; }
2606 set { mouseUpInt = value; }
2607 }
2608 public PointD MouseDown
2609 {
2610 get { return mouseDown; }
2611 set { mouseDown = value; }
2612 }
2613 public PointD MouseUp
2614 {
2615 get { return mouseUp; }
2616 set { mouseUp = value; }
2617 }
2618 public PointD MouseMove
2619 {
2620 get { return mouseMove; }
2621 set { mouseMove = value; }
2622 }
2623
2624 List<ROI> copys = new List<ROI>();
2625 public List<ROI> GetSelectedROIs()
2626 {
2627 List<ROI> roi = new List<ROI>();
2628 List<ROI> rois = new List<ROI>();
2629 rois.AddRange(SelectedImage.AnnotationsR);
2630 rois.AddRange(SelectedImage.AnnotationsG);
2631 rois.AddRange(SelectedImage.AnnotationsB);
2632 foreach (ROI r in rois)
2633 {
2634 if (r.Selected)
2635 {
2636 roi.Add(r);
2637 }
2638 }
2639 return roi;
2640 }
2641 public void ZoomAtPoint(float mouseX, float mouseY, bool zoomIn)
2642 {
2643 if (SelectedImage == null) return;
2644
2645 // 1. Define zoom factor (e.g., 2.0x zoom steps)
2646 float zoomFactor = zoomIn ? 2.0f : 0.5f;
2647
2648 // 2. Get the current level's scale relative to Full Res (Level 0)
2649 // Formula: CurrentLevelWidth / FullResWidth
2650 double currentLevelScale = (double)SelectedImage.Resolutions[SelectedImage.Level].SizeX / SelectedImage.SizeX;
2651
2652 // 3. Find the "World Point" (Full Res Level 0) currently under the mouse
2653 // We add the origin to the mouse offset and then scale up to Level 0
2654 double worldX = (PyramidalOrigin.X + mouseX) / currentLevelScale;
2655 double worldY = (PyramidalOrigin.Y + mouseY) / currentLevelScale;
2656
2657 // 4. Update your Level logic here
2658 // This is where you switch your 'CurrentLevelWidth' to the next level in the pyramid
2659 //UpdateLevel(zoomIn);
2660
2661 // 5. Get the NEW level's scale relative to Full Res
2662 double newLevelScale = (double)SelectedImage.Resolutions[SelectedImage.Level].SizeX / SelectedImage.SizeX;
2663
2664 // 6. Calculate the NEW PyramidalOrigin
2665 // To keep the world point at the same mouse position:
2666 // NewOrigin = (WorldPoint * NewScale) - MouseOffset
2667 float newOriginX = (float)(worldX * newLevelScale - mouseX);
2668 float newOriginY = (float)(worldY * newLevelScale - mouseY);
2669
2670 // 7. Apply and Clamp (to ensure we don't scroll past image edges)
2671 PyramidalOrigin = new PointD(
2672 Math.Max(0, Math.Min(newOriginX, SelectedImage.Resolutions[SelectedImage.Level].SizeX - AllocatedWidth)),
2673 Math.Max(0, Math.Min(newOriginY, SelectedImage.Resolutions[SelectedImage.Level].SizeY - AllocatedHeight))
2674 );
2675 }
2679 private void ImageView_MotionNotifyEvent(object o, MotionNotifyEventArgs e)
2680 {
2681 App.viewer = this;
2682 Modifiers = e.Event.State;
2683 MouseMove = new PointD(e.Event.X, e.Event.Y);
2684 MouseMoveInt = new PointD((int)e.Event.X, (int)e.Event.Y);
2685
2686 // Convert to view space (world coordinates)
2687 PointD p = ImageToViewSpace(e.Event.X, e.Event.Y);
2688 mousePoint = "(" + (p.X.ToString("F")) + ", " + (p.Y.ToString("F")) + ")";
2689
2690 // Handle pyramidal overview navigation
2691 if (SelectedImage.isPyramidal && overview.IntersectsWith(e.Event.X, e.Event.Y) &&
2692 e.Event.State.HasFlag(ModifierType.Button1Mask) && ShowOverview)
2693 {
2694 if (!OpenSlide)
2695 {
2696 double dsx = SelectedImage.SlideBase.Schema.Resolutions[0].UnitsPerPixel / Resolution;
2697 BioLib.Resolution rs = SelectedImage.Resolutions[Level];
2698 double dx = ((double)e.Event.X / overview.Width) * (rs.SizeX);
2699 double dy = ((double)e.Event.Y / overview.Height) * (rs.SizeY);
2700 PyramidalOrigin = new PointD(dx, dy);
2701 }
2702 else
2703 {
2704 double dsx = SelectedImage.OpenSlideBase.Schema.Resolutions[0].UnitsPerPixel / Resolution;
2705 BioLib.Resolution rs = SelectedImage.Resolutions[Level];
2706 double dx = ((double)e.Event.X / overview.Width) * (rs.SizeX);
2707 double dy = ((double)e.Event.Y / overview.Height) * (rs.SizeY);
2708 PyramidalOrigin = new PointD(dx, dy);
2709 }
2710 RequestDeferredRender();
2711 }
2712 else if (overviewImage == null && SelectedImage.isPyramidal && ShowOverview &&
2713 e.Event.State.HasFlag(ModifierType.Button1Mask))
2714 {
2715 if (!OpenSlide)
2716 {
2717 double dsx = SelectedImage.SlideBase.Schema.Resolutions[0].UnitsPerPixel / Resolution;
2718 BioLib.Resolution rs = SelectedImage.Resolutions[Level];
2719 double dx = ((double)e.Event.X / overview.Width) * (rs.SizeX);
2720 double dy = ((double)e.Event.Y / overview.Height) * (rs.SizeY);
2721 PyramidalOrigin = new PointD(dx, dy);
2722 }
2723 else
2724 {
2725 double dsx = SelectedImage.OpenSlideBase.Schema.Resolutions[0].UnitsPerPixel / Resolution;
2726 BioLib.Resolution rs = SelectedImage.Resolutions[Level];
2727 double dx = ((double)e.Event.X / overview.Width) * (rs.SizeX);
2728 double dy = ((double)e.Event.Y / overview.Height) * (rs.SizeY);
2729 PyramidalOrigin = new PointD(dx, dy);
2730 }
2731 RequestDeferredRender();
2732 }
2733 // Delegate all tool logic to Tools.cs
2734 App.tools.ToolMove(p, e);
2735 UpdateStatus();
2736 pd = p;
2737 }
2738
2742 private void ImageView_ButtonReleaseEvent(object o, ButtonReleaseEventArgs e)
2743 {
2744 Modifiers = e.Event.State;
2745 MouseUpInt = new PointD((int)e.Event.X, (int)e.Event.Y);
2746
2747 if (Tools.currentTool.type == Tools.Tool.Type.pan && e.Event.Button == 2)
2748 Tools.currentTool = Tools.GetTool("move");
2749 if (e.Event.Button == 1)
2750 mouseLeftState = false;
2751
2752 App.viewer = this;
2753 PointD pointer = ImageToViewSpace(e.Event.X, e.Event.Y);
2754 mouseUp = pointer;
2755
2756 if (SelectedImage == null)
2757 return;
2758 // Delegate all tool logic to Tools.cs
2759 App.tools.ToolUp(pointer, e);
2760 }
2761
2765 private void ImageView_ButtonPressEvent(object o, ButtonPressEventArgs e)
2766 {
2767 Modifiers = e.Event.State;
2768
2769 if (e.Event.Button == 1)
2770 mouseLeftState = true;
2771 else
2772 mouseLeftState = false;
2773
2774 App.viewer = this;
2775 PointD pointer = ImageToViewSpace(e.Event.X, e.Event.Y);
2776 MouseDownInt = new PointD(e.Event.X, e.Event.Y);
2777 pd = pointer;
2778 mouseDown = pd;
2779 if (Tools.currentTool.type == Tools.Tool.Type.move && e.Event.Button == 2)
2780 Tools.currentTool = Tools.GetTool("pan");
2781 if (SelectedImage == null)
2782 return;
2783
2784 mouseD = SelectedImage.ToImageSpace(pd);
2785
2786 // Handle well plate level navigation
2787 if (ImageView.SelectedImage.Type == BioImage.ImageType.well)
2788 {
2789 if (e.Event.Button == 4)
2790 {
2791 Level = ImageView.SelectedImage.Level - 1;
2792 }
2793 else if (e.Event.Button == 5)
2794 {
2795 Level = ImageView.SelectedImage.Level + 1;
2796 }
2797 }
2798
2799 // Context menu
2800 if (e.Event.Button == 3)
2801 {
2802 contextMenu.Popup();
2803 return; // Don't process tool events for right-click
2804 }
2805
2806 // Mouse wheel scrolling for channel/time navigation
2807 if (e.Event.Button == 4 && Mode != ViewMode.RGBImage)
2808 {
2809 if (cBar.Value < cBar.Adjustment.Upper)
2810 cBar.Value++;
2811 x1State = true;
2812 }
2813 else if (e.Event.Button == 4 && e.Event.State == ModifierType.ControlMask)
2814 {
2815 if (tBar.Value < tBar.Adjustment.Upper)
2816 tBar.Value++;
2817 x1State = true;
2818 }
2819
2820 if (e.Event.State != ModifierType.Button4Mask)
2821 x1State = false;
2822
2823 if (e.Event.Button == 5 && Mode != ViewMode.RGBImage)
2824 {
2825 if (cBar.Value > cBar.Adjustment.Lower)
2826 cBar.Value--;
2827 x2State = true;
2828 }
2829 else if (e.Event.Button == 5 && Modifiers == ModifierType.ControlMask && Mode != ViewMode.RGBImage)
2830 {
2831 if (tBar.Value > cBar.Adjustment.Lower)
2832 tBar.Value--;
2833 x2State = true;
2834 }
2835
2836 if (e.Event.State != ModifierType.Button5Mask)
2837 x2State = false;
2838
2839 // Select which image is clicked (for multi-image views)
2840 int ind = 0;
2841 foreach (BioImage b in Images)
2842 {
2843 RectangleD r = new RectangleD(b.Volume.Location.X, b.Volume.Location.Y,
2844 b.Volume.Width, b.Volume.Height);
2845 if (r.IntersectsWith(pointer))
2846 {
2847 selectedIndex = ind;
2848 UpdateGUI();
2849 break;
2850 }
2851 ind++;
2852 }
2853
2854 // Get pixel value at cursor for display (only for left-click)
2855 if (e.Event.Button == 1)
2856 {
2857 PointD s = new PointD(e.Event.X, e.Event.Y);
2858
2859 // Sample pixel value for status display
2860 if ((s.X < SelectedImage.SizeX && s.Y < SelectedImage.SizeY) ||
2861 (s.X >= 0 && s.Y >= 0))
2862 {
2863 int zc = SelectedImage.Coordinate.Z;
2864 int cc = SelectedImage.Coordinate.C;
2865 int tc = SelectedImage.Coordinate.T;
2866
2867 try
2868 {
2869 if (SelectedImage.isPyramidal)
2870 {
2871 if (SelectedImage.isRGB)
2872 {
2873 float r = SelectedImage.GetValueRGB(zc, RChannel.Index, tc,
2874 (int)s.X, (int)s.Y, 0);
2875 float g = SelectedImage.GetValueRGB(zc, GChannel.Index, tc,
2876 (int)s.X, (int)s.Y, 1);
2877 float b = SelectedImage.GetValueRGB(zc, BChannel.Index, tc,
2878 (int)s.X, (int)s.Y, 2);
2879 mouseColor = ", RGB(" + r + "," + g + "," + b + ")";
2880 }
2881 else
2882 {
2883 float r = SelectedImage.GetValueRGB(zc, (int)cBar.Value, tc,
2884 (int)mouseD.X, (int)mouseD.Y, 0);
2885 mouseColor = ", Val(" + r + ")";
2886 }
2887 }
2888 else
2889 {
2890 if (SelectedImage.isRGB)
2891 {
2892 float r = SelectedImage.GetValueRGB(zc, RChannel.Index, tc,
2893 (int)s.X, (int)s.Y, 0);
2894 float g = SelectedImage.GetValueRGB(zc, GChannel.Index, tc,
2895 (int)s.X, (int)s.Y, 1);
2896 float b = SelectedImage.GetValueRGB(zc, BChannel.Index, tc,
2897 (int)s.X, (int)s.Y, 2);
2898 mouseColor = ", RGB(" + r + "," + g + "," + b + ")";
2899 }
2900 else
2901 {
2902 float r = SelectedImage.GetValueRGB(zc, (int)cBar.Value, tc,
2903 (int)s.X, (int)s.Y, 0);
2904 mouseColor = ", Val(" + r + ")";
2905 }
2906 }
2907 }
2908 catch (Exception ex)
2909 {
2910 mouseColor = "";
2911 Console.WriteLine("Error reading pixel value: " + ex.Message);
2912 }
2913 }
2914 }
2915 UpdateStatus();
2916 App.tools.ToolDown(pointer, e);
2917 UpdateView();
2918 }
2919 protected override void OnDestroyed()
2920 {
2921 base.OnDestroyed();
2922 }
2923
2924
2925 #region Conversion
2926 private int Width
2927 {
2928 get
2929 {
2930 return glArea.AllocatedWidth;
2931 }
2932 }
2933 private int Height
2934 {
2935 get
2936 {
2937 return glArea.AllocatedHeight;
2938 }
2939 }
2940
2941 public static ROI SelectedAnnotation
2942 {
2943 get
2944 {
2945 foreach (var item in SelectedImage.Annotations)
2946 {
2947 if (item.Selected)
2948 return item;
2949 }
2950 return null;
2951 }
2952 }
2953
2954 public double ImageViewWidth
2955 {
2956 get
2957 {
2958 double d = glArea.AllocatedWidth / Resolution;
2959 return d;
2960 }
2961 }
2962 public double ImageViewHeight
2963 {
2964 get
2965 {
2966 double d = glArea.AllocatedHeight / Resolution;
2967 return d;
2968 }
2969 }
2976 public PointD ImageToViewSpace(double x, double y)
2977 {
2978 if (SelectedImage == null)
2979 return ToViewSpace(x, y);
2980 if (SelectedImage.isPyramidal)
2981 {
2982 return new PointD((PyramidalOrigin.X + x) * Resolution, (PyramidalOrigin.Y + y) * Resolution);
2983 }
2984 else
2985 return ToViewSpace(x, y);
2986 }
2992 public PointF ToViewSpace(PointF p)
2993 {
2994 PointD d = ToViewSpace(p.X, p.Y);
2995 return new PointF((float)d.X, (float)d.Y);
2996 }
3002 public PointD ToViewSpace(PointD p)
3003 {
3004 return ToViewSpace(p.X, p.Y); ;
3005 }
3006 public PointD ToViewSpace(double x, double y)
3007 {
3008 if (SelectedImage == null)
3009 {
3010 double dx = (ToViewSizeW(x - (viewStack.AllocatedWidth / 2)) / Scale.Width) - Origin.X;
3011 double dy = (ToViewSizeH(y - (viewStack.AllocatedHeight / 2)) / Scale.Height) - Origin.Y;
3012 return new PointD(dx, dy);
3013 }
3014
3015 if (SelectedImage.isPyramidal)
3016 {
3017 PointD p = new PointD(x / Resolution, y / Resolution);
3018 return new PointD(p.X - PyramidalOrigin.X, p.Y - PyramidalOrigin.Y);
3019 }
3020 else
3021 {
3022 // Handle non-pyramidal case
3023 double dx = (ToViewSizeW(x - (viewStack.AllocatedWidth / 2)) / Scale.Width) - Origin.X;
3024 double dy = (ToViewSizeH(y - (viewStack.AllocatedHeight / 2)) / Scale.Height) - Origin.Y;
3025 return new PointD(dx, dy);
3026 }
3027 }
3028
3034 private double ToViewSizeW(double d)
3035 {
3036 if (SelectedImage != null)
3037 if (SelectedImage.isPyramidal)
3038 {
3039 return d / Resolution;
3040 }
3041 double x = (double)(d / PxWmicron);
3042 return x;
3043 }
3049 public double ToViewSizeH(double d)
3050 {
3051 if (SelectedImage != null)
3052 if (SelectedImage.isPyramidal)
3053 {
3054 return d / Resolution;
3055 }
3056 double y = (double)(d / PxHmicron);
3057 return y;
3058 }
3064 public double ToViewW(double d)
3065 {
3066 if (SelectedImage != null)
3067 if (SelectedImage.isPyramidal)
3068 {
3069 return d / Resolution;
3070 }
3071 double x = (double)(d / PxWmicron) / scale.Width;
3072 return x;
3073 }
3079 public double ToViewH(double d)
3080 {
3081 if (SelectedImage != null)
3082 if (SelectedImage.isPyramidal)
3083 {
3084 return d / Resolution;
3085 }
3086 double y = (double)(d / PxHmicron) / scale.Height;
3087 return y;
3088 }
3095 public PointD ToScreenSpace(double x, double y)
3096 {
3097 RectangleD f = ToScreenRect(x, y, 1, 1);
3098 return new PointD(f.X, f.Y);
3099 }
3105 public PointD ToScreenSpace(PointD p)
3106 {
3107 return ToScreenSpace(p.X, p.Y);
3108 }
3114 public PointF ToScreenSpace(PointF p)
3115 {
3116 PointD pd = ToScreenSpace(p.X, p.Y);
3117 return new PointF((float)pd.X, (float)pd.Y);
3118 }
3124 public PointF[] ToScreenSpace(PointF[] p)
3125 {
3126 PointF[] pf = new PointF[p.Length];
3127 for (int i = 0; i < p.Length; i++)
3128 {
3129 pf[i] = ToScreenSpace(p[i]);
3130 }
3131 return pf;
3132 }
3138 public PointF ToScreenSpace(Point3D p)
3139 {
3140 PointD pd = ToScreenSpace(p.X, p.Y);
3141 return new PointF((float)pd.X, (float)pd.Y);
3142 }
3148 public float ToScreenScaleW(double x)
3149 {
3150 return (float)(-x * PxWmicron * Scale.Width);
3151 }
3157 public float ToScreenScaleH(double y)
3158 {
3159 return (float)(-y * PxHmicron * Scale.Height);
3160 }
3166 public PointF ToScreenScale(PointD p)
3167 {
3168 float x = ToScreenScaleW((float)p.X);
3169 float y = ToScreenScaleH((float)p.Y);
3170 return new PointF(x, y);
3171 }
3180 public RectangleD ToScreenRect(double x, double y, double w, double h)
3181 {
3182 if (SelectedImage == null)
3183 {
3184 double dx = (pxWmicron * (-Origin.X)) * Scale.Width;
3185 double dy = (pxHmicron * (-Origin.Y)) * Scale.Height;
3186 RectangleD rf = new RectangleD((PxWmicron * x * Scale.Width + dx), (PxHmicron * y * Scale.Height + dy), (PxWmicron * w * Scale.Width), (PxHmicron * h * Scale.Height));
3187 return rf;
3188 }
3189 if (SelectedImage.isPyramidal)
3190 {
3191 PointD d = ToViewSpace(x, y);
3192 double dw = ToViewSizeW(w);
3193 double dh = ToViewSizeH(h);
3194 return new RectangleD(d.X, d.Y, dw, dh);
3195 }
3196 else
3197 {
3198 double dx = (pxWmicron * (Origin.X)) * Scale.Width;
3199 double dy = (pxHmicron * (Origin.Y)) * Scale.Height;
3200 RectangleD rf = new RectangleD((PxWmicron * x * Scale.Width + dx), (PxHmicron * y * Scale.Height + dy), (PxWmicron * w * Scale.Width), (PxHmicron * h * Scale.Height));
3201 return rf;
3202 }
3203 }
3204
3210 public RectangleD ToScreenSpace(RectangleD p)
3211 {
3212 return ToScreenRect(p.X, p.Y, p.W, p.H);
3213 }
3219 public RectangleD ToScreenSpace(RectangleF p)
3220 {
3221 return ToScreenRect(p.X, p.Y, p.Width, p.Height);
3222 }
3228 public RectangleD[] ToScreenSpace(RectangleD[] p)
3229 {
3230 RectangleD[] rs = new RectangleD[p.Length];
3231 for (int i = 0; i < p.Length; i++)
3232 {
3233 rs[i] = ToScreenSpace(p[i]);
3234 }
3235 return rs;
3236 }
3237
3243 public PointD[] ToScreenSpace(PointD[] p)
3244 {
3245 PointD[] rs = new PointD[p.Length];
3246 for (int i = 0; i < p.Length; i++)
3247 {
3248 PointD pd = ToScreenSpace(p[i]);
3249 rs[i] = new PointD((float)pd.X, (float)pd.Y);
3250 }
3251 return rs;
3252 }
3258 public double ToScreenW(double x)
3259 {
3260 return (float)(x * PxWmicron);
3261 }
3267 public float ToScreenH(double y)
3268 {
3269 return (float)(y * PxHmicron);
3270 }
3272 public void GoToImage()
3273 {
3274 GoToImage(0);
3275 }
3281 public void GoToImage(int i)
3282 {
3283 if (Images.Count <= i)
3284 return;
3285 if (SelectedImage.Type == BioImage.ImageType.pyramidal)
3286 {
3287 if (SelectedImage.OpenSlideBase != null)
3288 {
3289 if (MacroResolution.HasValue)
3290 {
3291 int lev = MacroResolution.Value - 2;
3292 Resolution = _openSlideBase.Schema.Resolutions[lev].UnitsPerPixel * 0.98;
3293 }
3294 else
3295 {
3296 int lev = 0;
3297 Resolution = _openSlideBase.Schema.Resolutions[lev].UnitsPerPixel * 0.98;
3298 }
3299 }
3300 else
3301 {
3302 if (MacroResolution.HasValue)
3303 {
3304 int lev = MacroResolution.Value - 1;
3305 Resolution = SelectedImage.SlideBase.Schema.Resolutions[lev].UnitsPerPixel * 0.98;
3306 PyramidalOrigin = new PointD(0, 0);
3307 }
3308 else
3309 {
3310 Resolution = SelectedImage.GetUnitPerPixel(SelectedImage.Resolutions.Count - 1) * 0.98;
3311 }
3312 }
3313 }
3314 double dx = Images[i].Volume.Width / 2;
3315 double dy = Images[i].Volume.Height / 2;
3316 Origin = new PointD(-(Images[i].Volume.Location.X + dx), -(Images[i].Volume.Location.Y + dy));
3317 double wx, wy;
3318 wx = viewStack.AllocatedWidth / ToScreenW(SelectedImage.Volume.Width);
3319 wy = viewStack.AllocatedHeight / ToScreenH(SelectedImage.Volume.Height);
3320 Scale = new SizeF((float)wy, (float)wy);
3321 UpdateView();
3322 }
3323
3324 #endregion
3325
3326 #region OpenSlide
3327 private OpenSlideBase _openSlideBase;
3328 private OpenSlideGTK.ISlideSource _openSlideSource;
3329 private BioLib.ISlideSource _slideSource;
3330 private SlideBase _slideBase;
3336 private void Initialize()
3337 {
3338
3339 if (SelectedImage.OpenSlideBase != null)
3340 {
3341 _openSlideSource = SelectedImage.OpenSlideBase;
3342 _openSlideBase = SelectedImage.OpenSlideBase as OpenSlideBase;
3343 openSlide = true;
3344 if (MacroResolution.HasValue)
3345 {
3346 int lev = MacroResolution.Value - 2;
3347 Resolution = _openSlideBase.Schema.Resolutions[lev].UnitsPerPixel;
3348 }
3349 else
3350 {
3351 Resolution = _openSlideBase.Schema.Resolutions[0].UnitsPerPixel;
3352 }
3353 }
3354 else
3355 {
3356 _slideSource = SelectedImage.SlideBase;
3357 _slideBase = SelectedImage.SlideBase;
3358 openSlide = false;
3359 if (MacroResolution.HasValue)
3360 {
3361 int lev = MacroResolution.Value - 2;
3362 double[] ds = SelectedImage.GetLevelDownsamples();
3363 Resolution = ds[lev];
3364 }
3365 else
3366 {
3367 Resolution = SelectedImage.GetLevelDownsamples()[SelectedImage.Resolutions.Count - 1];
3368 }
3369 }
3370 }
3371 #endregion
3372
3373 }
3374}
double ToViewH(double d)
void UpdateView(bool updateImages=true)
It updates the view.
double ToViewSizeH(double d)
void UpdateImage()
It updates the image.
float ToScreenScaleW(double x)
double ToViewW(double d)
RectangleD ToScreenRect(double x, double y, double w, double h)
PointD ToViewSpace(PointD p)
RectangleD[] ToScreenSpace(RectangleD[] p)
ZCT GetCoordinate()
Definition ImageView.cs:67
RectangleD ToScreenSpace(RectangleD p)
void PasteSelection()
PointF ToViewSpace(PointF p)
PointF ToScreenSpace(PointF p)
RectangleD ToScreenSpace(RectangleF p)
void CopySelection()
It takes the selected ROIs and copies them to the clipboard.
void SetupHandlers()
Sets up the handlers.
PointD ToScreenSpace(double x, double y)
PointD ImageToViewSpace(double x, double y)
PointD ToScreenSpace(PointD p)
static ImageView Create(BioImage bm)
Definition ImageView.cs:268
void GoToImage()
This function is used to go to the image at the specified index.
void AddImage(BioImage im)
Definition ImageView.cs:75
PointF ToScreenScale(PointD p)
void UpdateGUI()
It updates the GUI to reflect the current state of the image.
PointF[] ToScreenSpace(PointF[] p)
static Cairo.Color FromColor(Color color)
PointD[] ToScreenSpace(PointD[] p)
void GoToImage(int i)
PointF ToScreenSpace(Point3D p)
void UpdateImages(bool force=false)
It updates the images.
float ToScreenScaleH(double y)
void UpdateStatus()
It updates the status of the user.
float ToScreenH(double y)
double ToScreenW(double x)
Definition ML.cs:17