BohemianBuddha

source

PaintControl.cs

from Visual Toolbar Icons

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VisualToolBarImageViewer
{
    public partial class PaintControl : UserControl
    {
        public PaintControl()
        {
            InitializeComponent();
            this.SetStyle(
                            ControlStyles.AllPaintingInWmPaint |
                            ControlStyles.UserPaint |
                            ControlStyles.DoubleBuffer,
                            true);
        }

        public event EventHandler<string> ImageSaved; // string = file path that was saved

        private void RaiseImageSaved(string filePath)
        {
            ImageSaved?.Invoke(this, filePath);
        }

        private const int SliceSize = 22;                 // Each state is 22x22
        private static readonly Color MaskColor = Color.Magenta; // VISUAL's transparency key

        private Bitmap _bitmap;           // The image being edited
        private Color _selectedColor = Color.Black;  // Currently selected color
        private int _pixelSize = 12;      // How many screen pixels each image pixel takes up

        private int _paletteSwatchSize = 20;   // Size of each color swatch
        private int _paletteColumns = 5;       // How many swatches per row

        private string _sourceFilePath = null;   // Original BMP file path
        private int _sourceStripOffset = 0;      // Y offset in the strip (0, 23, or 46)

        public enum PaintTool { Brush, Eyedropper, Bucket }
        private PaintTool _currentTool = PaintTool.Brush;

        public PaintTool CurrentTool
        {
            get { return _currentTool; }
            set { _currentTool = value; UpdateCursor(); }
        }

        private void UpdateCursor()
        {
            if (_currentTool == PaintTool.Eyedropper)
                this.Cursor = Cursors.Cross;
            else if (_currentTool == PaintTool.Bucket)
                this.Cursor = Cursors.Hand;
            else
                this.Cursor = Cursors.Default;
        }

        // Compare by ARGB value, not Color struct equality.
        // Color.Red (named) != GetPixel's (255,255,0,0) under ==, which made the
        // "same colour" guard in FloodFill miss and loop forever.
        // All fully/mostly transparent pixels count as the same colour.
        private static bool SameColor(Color a, Color b)
        {
            bool aClear = a.A < 128, bClear = b.A < 128;
            if (aClear || bClear) return aClear && bClear;
            return a.R == b.R && a.G == b.G && a.B == b.B;
        }

        private void FloodFill(int startX, int startY, Color targetColor, Color fillColor)
        {
            // Don't fill if the target and fill color are the same
            if (SameColor(targetColor, fillColor)) return;

            bool[,] visited = new bool[_bitmap.Width, _bitmap.Height];
            Queue<Point> queue = new Queue<Point>();
            queue.Enqueue(new Point(startX, startY));

            while (queue.Count > 0)
            {
                Point p = queue.Dequeue();

                if (p.X < 0 || p.X >= _bitmap.Width) continue;
                if (p.Y < 0 || p.Y >= _bitmap.Height) continue;
                if (visited[p.X, p.Y]) continue;
                visited[p.X, p.Y] = true;
                if (!SameColor(_bitmap.GetPixel(p.X, p.Y), targetColor)) continue;

                _bitmap.SetPixel(p.X, p.Y, fillColor);

                queue.Enqueue(new Point(p.X + 1, p.Y));
                queue.Enqueue(new Point(p.X - 1, p.Y));
                queue.Enqueue(new Point(p.X, p.Y + 1));
                queue.Enqueue(new Point(p.X, p.Y - 1));
            }
        }

        private readonly Color[] _palette = new Color[]
        {
            Color.Black,      Color.White,      Color.Gray,       Color.Silver,
            Color.Red,        Color.DarkRed,    Color.Orange,     Color.OrangeRed,
            Color.Yellow,     Color.YellowGreen,Color.Green,      Color.DarkGreen,
            Color.Cyan,       Color.DarkCyan,   Color.Blue,       Color.DarkBlue,
            Color.Magenta,    Color.Purple,     Color.Brown,      Color.SaddleBrown,
            Color.Pink,       Color.HotPink,    Color.LightBlue,  Color.LightGreen,
            Color.Transparent
        };

        public Bitmap GetCurrentBitmap()
        {
            return _bitmap;
        }

        public Bitmap EditingBitmap
        {
            get { return _bitmap; }
        }

        // ------------------------------------------------------------------
        // Writing back to the strip file
        //
        // The old code did:  strip = new Bitmap(temp); ... strip.Save(filePath);
        // A Bitmap copied that way has RawFormat = MemoryBmp, and Save(path)
        // with no ImageFormat falls back to the PNG encoder. So the ".BMP" on
        // disk was really a PNG (32-bit ARGB). GDI+ and MS Paint read it fine;
        // VISUAL's toolbar only reads real BMPs. Paint "fixed" it by re-saving
        // as a genuine 24-bit BMP.
        //
        // This version always writes a 24-bit BMP with ImageFormat.Bmp, and
        // converts transparent pixels back to magenta (VISUAL's mask colour).
        // ------------------------------------------------------------------

        private static Color ToStripColor(Color c)
        {
            return c.A < 128 ? MaskColor : Color.FromArgb(255, c.R, c.G, c.B);
        }

        private void WriteSliceToStrip(string filePath, int stripOffset)
        {
            // Detached copy so the file handle is released before we overwrite it
            Bitmap strip;
            using (Bitmap temp = new Bitmap(filePath))
                strip = new Bitmap(temp);

            using (strip)
            using (Bitmap output = new Bitmap(strip.Width, strip.Height, PixelFormat.Format24bppRgb))
            {
                for (int y = 0; y < strip.Height; y++)
                {
                    for (int x = 0; x < strip.Width; x++)
                    {
                        bool inSlice = x < SliceSize && y >= stripOffset && y < stripOffset + SliceSize;
                        Color c = inSlice ? _bitmap.GetPixel(x, y - stripOffset) : strip.GetPixel(x, y);
                        output.SetPixel(x, y, ToStripColor(c));
                    }
                }

                output.Save(filePath, ImageFormat.Bmp);
            }
        }

        public void Save()
        {
            if (_bitmap == null || _sourceFilePath == null) return;

            // Ask which state to save to
            using (frmSaveStrip dlg = new frmSaveStrip(_sourceStripOffset))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        WriteSliceToStrip(_sourceFilePath, dlg.SelectedOffset);
                        RaiseImageSaved(_sourceFilePath);   // Form shows the result in the status bar
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error saving:" + Environment.NewLine + ex.Message,
                            "Save", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }
            }
        }

        public void SaveAs()
        {
            if (_bitmap == null) return;

            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Title = "Save Strip As";
                sfd.Filter = "Bitmap Files (*.bmp)|*.bmp";
                sfd.DefaultExt = "bmp";
                if (_sourceFilePath != null)
                    sfd.FileName = System.IO.Path.GetFileName(_sourceFilePath);

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    // Start from a copy of the original strip
                    if (_sourceFilePath != null && System.IO.File.Exists(_sourceFilePath)
                        && !string.Equals(_sourceFilePath, sfd.FileName, StringComparison.OrdinalIgnoreCase))
                        System.IO.File.Copy(_sourceFilePath, sfd.FileName, overwrite: true);

                    using (frmSaveStrip dlg = new frmSaveStrip(_sourceStripOffset))
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                WriteSliceToStrip(sfd.FileName, dlg.SelectedOffset);
                                _sourceFilePath = sfd.FileName; // Update tracked path
                                RaiseImageSaved(_sourceFilePath);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error saving:" + Environment.NewLine + ex.Message,
                                    "Save As", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            }
                        }
                    }
                }
            }
        }

        public void LoadImage(Image source, string filePath, int stripOffset)
        {
            _bitmap?.Dispose();
            _bitmap = new Bitmap(source);
            _sourceFilePath = filePath;
            _sourceStripOffset = stripOffset;

            // No longer resizes itself: the control fills the Editor card.
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (_bitmap == null) return;

            Color bodyColor = Color.FromArgb(29, 42, 46);
            Color gridColor = Color.FromArgb(232, 229, 222);
            Color accent = Color.FromArgb(15, 110, 106);

            using (Pen gridPen = new Pen(gridColor))
            using (SolidBrush checkLight = new SolidBrush(Color.White))
            using (SolidBrush checkDark = new SolidBrush(Color.FromArgb(236, 234, 227)))
            {
                for (int y = 0; y < _bitmap.Height; y++)
                {
                    for (int x = 0; x < _bitmap.Width; x++)
                    {
                        Color pixelColor = _bitmap.GetPixel(x, y);
                        Rectangle r = new Rectangle(x * _pixelSize, y * _pixelSize, _pixelSize, _pixelSize);

                        if (pixelColor.A < 128)
                        {
                            // Transparent (= magenta on disk): checkerboard so it's visible
                            e.Graphics.FillRectangle(((x + y) % 2 == 0) ? checkLight : checkDark, r);
                        }
                        else
                        {
                            using (SolidBrush brush = new SolidBrush(pixelColor))
                                e.Graphics.FillRectangle(brush, r);
                        }

                        e.Graphics.DrawRectangle(gridPen, r);
                    }
                }
            }

            // Draw the color palette
            Rectangle pb = GetPaletteBounds();
            using (Pen selectedPen = new Pen(accent, 2))
            using (Pen swatchPen = new Pen(Color.FromArgb(201, 197, 187)))
            {
                for (int i = 0; i < _palette.Length; i++)
                {
                    int col = i % _paletteColumns;
                    int row = i / _paletteColumns;
                    Rectangle swatchRect = new Rectangle(
                        pb.X + col * _paletteSwatchSize,
                        pb.Y + row * _paletteSwatchSize,
                        _paletteSwatchSize,
                        _paletteSwatchSize);

                    using (SolidBrush brush = new SolidBrush(_palette[i]))
                        e.Graphics.FillRectangle(brush, swatchRect);

                    // Teal border on the selected swatch (white was invisible on the white card)
                    if (_palette[i].ToArgb() == _selectedColor.ToArgb())
                        e.Graphics.DrawRectangle(selectedPen, swatchRect);
                    else
                        e.Graphics.DrawRectangle(swatchPen, swatchRect);
                }
            }

            // Selected color preview
            int previewTop = pb.Bottom + 8;

            using (Font labelFont = new Font("Segoe UI Semibold", 8.25F, FontStyle.Bold))
            using (SolidBrush labelBrush = new SolidBrush(Color.FromArgb(78, 86, 84)))
                e.Graphics.DrawString("SELECTED", labelFont, labelBrush, 0, previewTop);

            Rectangle previewRect = new Rectangle(0, previewTop + 18, _paletteColumns * _paletteSwatchSize, 24);

            using (SolidBrush brush = new SolidBrush(_selectedColor))
                e.Graphics.FillRectangle(brush, previewRect);

            using (Pen previewPen = new Pen(Color.FromArgb(201, 197, 187)))
                e.Graphics.DrawRectangle(previewPen, previewRect);

            string colorName = _selectedColor.IsNamedColor ? _selectedColor.Name :
                               $"R:{_selectedColor.R} G:{_selectedColor.G} B:{_selectedColor.B}";

            // Black or white text depending on background brightness (transparent -> dark text)
            float brightness = _selectedColor.A < 128 ? 1f : _selectedColor.GetBrightness();
            Brush textBrush = brightness < 0.5f ? Brushes.White : new SolidBrush(bodyColor);

            e.Graphics.DrawString(colorName, this.Font, textBrush,
                previewRect.X + 4, previewRect.Y + 5);

            if (textBrush != Brushes.White) textBrush.Dispose();
        }

        private Rectangle GetPaletteBounds()
        {
            int paletteTop = _bitmap != null ? _bitmap.Height * _pixelSize + 12 : 12;
            int paletteWidth = _paletteColumns * _paletteSwatchSize;
            int paletteHeight = (int)Math.Ceiling((double)_palette.Length / _paletteColumns) * _paletteSwatchSize;
            return new Rectangle(0, paletteTop, paletteWidth, paletteHeight);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            if (_bitmap == null) return;

            if (e.Button == MouseButtons.Right)
            {
                _currentTool = PaintTool.Brush;
                UpdateCursor();
                return;
            }

            // Check palette FIRST before anything else
            Rectangle pb = GetPaletteBounds();
            if (pb.Contains(e.X, e.Y))
            {
                int col = (e.X - pb.X) / _paletteSwatchSize;
                int row = (e.Y - pb.Y) / _paletteSwatchSize;
                int index = row * _paletteColumns + col;

                if (index >= 0 && index < _palette.Length)
                {
                    _selectedColor = _palette[index];
                    this.Invalidate();
                }
                return; // Stop here - don't paint a pixel
            }

            // Only reach here if click was NOT in the palette
            int x = e.X / _pixelSize;
            int y = e.Y / _pixelSize;

            if (x < 0 || x >= _bitmap.Width || y < 0 || y >= _bitmap.Height) return;

            if (e.Button == MouseButtons.Left)
            {
                if (_currentTool == PaintTool.Eyedropper)
                {
                    _selectedColor = _bitmap.GetPixel(x, y);
                    _currentTool = PaintTool.Brush;
                    UpdateCursor();
                    this.Invalidate();
                }
                else if (_currentTool == PaintTool.Bucket)
                {
                    Color targetColor = _bitmap.GetPixel(x, y);
                    FloodFill(x, y, targetColor, _selectedColor);
                    this.Invalidate();
                }
                else
                {
                    _bitmap.SetPixel(x, y, _selectedColor);
                    this.Invalidate();
                }
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            if (_bitmap == null) return;
            if (e.Button != MouseButtons.Left) return;
            if (_currentTool != PaintTool.Brush) return;

            // Check it's not in the palette area
            Rectangle pb = GetPaletteBounds();
            if (pb.Contains(e.X, e.Y)) return;

            int x = e.X / _pixelSize;
            int y = e.Y / _pixelSize;

            if (x < 0 || x >= _bitmap.Width || y < 0 || y >= _bitmap.Height) return;

            _bitmap.SetPixel(x, y, _selectedColor);
            this.Invalidate();
        }

        public void ReloadFromFile()
        {
            if (_sourceFilePath == null || !System.IO.File.Exists(_sourceFilePath))
            {
                MessageBox.Show("No source file to reload from.", "Reload",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            DialogResult result = MessageBox.Show(
                "Reload from file? Any unsaved changes will be lost.",
                "Reload",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result != DialogResult.Yes) return;

            try
            {
                using (Bitmap strip = new Bitmap(_sourceFilePath))
                {
                    Bitmap slice = new Bitmap(SliceSize, SliceSize);
                    using (Graphics g = Graphics.FromImage(slice))
                    {
                        g.DrawImage(strip,
                            new Rectangle(0, 0, SliceSize, SliceSize),
                            new Rectangle(0, _sourceStripOffset, SliceSize, SliceSize),
                            GraphicsUnit.Pixel);
                    }
                    slice.MakeTransparent(MaskColor);
                    _bitmap?.Dispose();
                    _bitmap = slice;
                }
                this.Invalidate();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error reloading file:" + Environment.NewLine + ex.Message,
                    "Reload", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        public void CopyStateToState()
        {
            if (_bitmap == null || _sourceFilePath == null)
            {
                MessageBox.Show("No icon loaded.", "Copy State",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            using (frmCopyState dlg = new frmCopyState(_sourceStripOffset))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        WriteSliceToStrip(_sourceFilePath, dlg.TargetOffset);
                        RaiseImageSaved(_sourceFilePath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error copying state:" + Environment.NewLine + ex.Message,
                            "Copy State", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }
            }
        }
    }
}
← back to Visual Toolbar Icons