This repository has been archived by the owner on May 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
frmMain.cs
1697 lines (1522 loc) · 61.5 KB
/
frmMain.cs
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using Note_Profiler.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
namespace Note_Profiler
{
public partial class frmMain : Form
{
/// <summary>
/// The four different modes of the GUI.
/// Determines how the mouse aces uppon dragging it accross an image.
/// </summary>
enum SelectionMode { Default, Select, Create, Zoom }
#region Global Variables
BindingList<Note> noteList; //The list of notes detected within the current image
List<Note> selectedNotes; //The list of notes currently highlighted
Page currentPage; //The current loaded page - which includes the photo of the page and its name.
private SelectionMode currentMode = SelectionMode.Default; //The current selection mode.
Cursor curPen = Utilities.CreateCursor(Properties.Resources.pen, 0, 0); //A pen cursor object - used for creating new notes.
Cursor groupSelect = Utilities.CreateCursor(Properties.Resources.GroupSelectCursor_16x, 0, 0); //The group selection cursor.
List<ToolStripItem> imageTools; //A tool of objects related to image editing. Grouped in a list to allow fast endabling/disabling
frmProgress progressDialog; //A progress dialog form - instance created dynamically.
bool isListBoxUpdating = false; //A boolean that while true indicates that the note listbox might be updating and its gui shouldn't be changed
Session currentSession; //A session object representing the current session - which includes open files, save states, etc.
DBAdapter db; //A database adapter through which all the DB operations will be performed. Must be initialized!
BindingList<Author> authorList; //A list of all the authors currently loaded - should be populated from the DB.
BindingList<Note.NoteType> noteTypeList; //A list of all the note types currently loaded - should be populated from the DB.
#endregion
/// <summary>
/// Loads the initial interface elements, instantiates the database and ties the different global variables to their initial values.
/// </summary>
public frmMain()
{
InitializeComponent();
if (Properties.Settings.Default.UpgradeRequired) //Upgrades the settings in case the version was upgraded. Required so settings aren't lost between sessions.
{
Settings.Default.Upgrade();
Settings.Default.UpgradeRequired = false;
Settings.Default.Save();
}
db = new DBAdapter(); //Creates a new DB instance.
selectedNotes = new List<Note>();
noteList = new BindingList<Note>();
noteList.ListChanged += NoteList_ListChanged;
comboAuthor.ComboBox.SelectionChangeCommitted += comboAuthor_SelectionChangeCommitted;
comboNoteType.ComboBox.SelectionChangeCommitted += comboNoteType_SelectionChangeCommitted;
listBoxFoundNotes.DataSource = noteList;
InvalidateDatabase(); //Makes sure the database is fresh.
//Create the list of interface elemnts to be tied to image editing and populate it:
imageTools = new List<ToolStripItem>();
imageTools.Add(btnAddNote);
imageTools.Add(btnDelete);
imageTools.Add(btnMerge);
imageTools.Add(btnSelectMultiple);
imageTools.Add(btnRescan);
imageTools.Add(btnSave);
imageTools.Add(btnClear);
imageTools.Add(comboAuthor);
imageTools.Add(comboNoteType);
imageTools.Add(btnSaveReadyToDB);
imageTools.Add(btnPan);
setMode(SelectionMode.Default);
}
#region File Operations
/// <summary>
/// Loads an image (creates a new session for it too) to work on.
/// Then scans it for notes, and eventually loads any pre-profiled notes from the Database.
/// </summary>
/// <param name="address"></param>
private void LoadImage(string address)
{
if (currentSession != null)
currentSession.EndSession();
currentPage = new Page(address);
currentSession = new Session(this, currentPage);
imageboxMain.Image = currentPage.Working.Bitmap;
setMode(SelectionMode.Default);
ScanNotes();
LoadNotesFromDB();
}
/// <summary>
/// Save the current session (directly if already opened or saved, prompts for target if not).
/// </summary>
private void FileSave()
{
if (currentSession.ProfilePath == null)
{
FileSaveAs();
}
else
SaveProfile(currentSession.ProfilePath);
}
/// <summary>
/// Save current session to a new file determined by the user.
/// </summary>
private void FileSaveAs()
{
SaveFileDialog ofd = new SaveFileDialog();
ofd.Filter = "Note Profiler|*.npf";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
SaveProfile(ofd.FileName);
}
}
/// <summary>
/// Start a new profileing session by clearing all the settings and lists.
/// </summary>
private void NewProfile()
{
if (currentSession != null)
currentSession.EndSession();
currentSession = null;
noteList.Clear();
selectedNotes.Clear();
imageboxMain.Image = null;
currentPage = null;
setMode(SelectionMode.Default);
InvalidateButtons();
InvalidateDatabase();
}
/// <summary>
/// Saves the current profile work to a file.
/// Firstly it stores any detected notes to the database.
/// The profile is then saved by serializing the currently detected notes and their values to an xml file.
/// The names of the image and the session values are saved to respective files, as is the image itself.
/// Those files are then zipped and the zipped file is renamed to whatever to user chose.
/// </summary>
/// <param name="fileName">What filename to save to</param>
private void SaveProfile(string fileName)
{
SaveCompleted();
File.WriteAllText(currentSession.WorkingDirectyory + "\\session", currentSession.Name);
File.WriteAllText(currentSession.WorkingDirectyory + "\\imagename", currentPage.FileName);
Serialize(noteList.ToList(), currentSession.WorkingDirectyory + "\\notes.xml");
if (File.Exists(fileName))
File.Delete(fileName);
ZipFile.CreateFromDirectory(currentSession.WorkingDirectyory, fileName);
currentSession.ProfilePath = fileName;
currentSession.Dirty = false; //Indicate that the current session is saved and no longer requires saving.
}
/// <summary>
/// Load a presaved file
/// </summary>
private void FileLoad()
{
if (!VerifySave())
return;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Note Profiler|*.npf";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
if (imageboxMain.Image != null)
NewProfile();
LoadProfile(ofd.FileName);
}
}
/// <summary>
/// The reverse of saving a profile:
/// First the file is unzipped, then the data in the xml is deserialized into the notelist.
/// The session and image values are restored from the respective files, and the image is copied to a temp working directory.
/// Finally - the interface is updated to reflect the loaded notes.
/// </summary>
/// <param name="address"></param>
private void LoadProfile(string address)
{
string tempExtractDir = Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(address);
if (Directory.Exists(tempExtractDir))
Directory.Delete(tempExtractDir, true);
ZipFile.ExtractToDirectory(address, tempExtractDir);
string sessionName = File.ReadAllText(tempExtractDir + "\\session");
string imagename = File.ReadAllText(tempExtractDir + "\\imagename");
currentPage = new Page(tempExtractDir + "\\" + imagename);
currentSession = new Session(this, currentPage, address);
noteList = DeSerialize(tempExtractDir + "\\notes.xml");
Directory.Delete(tempExtractDir, true);
listBoxFoundNotes.DataSource = noteList;
selectedNotes.Clear();
SyncSelection(true, false);
currentSession.Dirty = false;
}
/// <summary>
/// Load a new image to work on.
/// This will prompt the user to save their work, then load the image and start a new session for it.
/// </summary>
private void ImageLoad()
{
if (!VerifySave())
return;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images|*.jpg;*.png;*.gif;*.jpeg";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
if (imageboxMain.Image != null)
NewProfile();
LoadImage(ofd.FileName);
}
}
/// <summary>
/// Serializes notes into an XML file.
/// </summary>
/// <param name="list">The list of notes to serialize</param>
/// <param name="fileName">Where to save the results</param>
public void Serialize(List<Note> list, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Note>));
using (TextWriter writer = new StreamWriter(fileName))
{
serializer.Serialize(writer, list);
}
}
/// <summary>
/// Deserializes notes from XML
/// </summary>
/// <param name="fileName">File to read from</param>
/// <returns></returns>
public BindingList<Note> DeSerialize(string fileName)
{
List<Note> returnList = new List<Note>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Note>));
using (XmlReader reader = XmlReader.Create(fileName))
{
returnList = (List<Note>)serializer.Deserialize(reader);
}
return new BindingList<Note>(returnList);
}
#endregion
#region Interface Functions
#region Handlers
#region Menus
#region File
private void menuLoadImage_Click(object sender, EventArgs e)
{
ImageLoad();
}
private void menuNew_Click(object sender, EventArgs e)
{
if (!VerifySave())
return;
NewProfile();
}
private void menuOpen_Click(object sender, EventArgs e)
{
FileLoad();
}
private void mnuLoadImage_Click(object sender, EventArgs e)
{
ImageLoad();
}
private void menuSave_Click(object sender, EventArgs e)
{
FileSave();
}
private void menuSaveAs_Click(object sender, EventArgs e)
{
FileSaveAs();
}
private void menuExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Notes
private void mnuMultiSelect_Click(object sender, EventArgs e)
{
if (currentMode == SelectionMode.Select)
{
setMode(SelectionMode.Default);
}
else
{
setMode(SelectionMode.Select);
}
}
private void menuNewNote_Click(object sender, EventArgs e)
{
StartCreate();
}
private void menuMergeNotes_Click(object sender, EventArgs e)
{
MergeSelectedNotes();
}
private void menuDelete_Click(object sender, EventArgs e)
{
DeleteSelectedNotes();
}
#endregion
#region Database
private void menuDBBrowser_Click(object sender, EventArgs e)
{
frmPictureDB newForm = new frmPictureDB();
newForm.ShowDialog();
}
private void menuSaveReady_Click(object sender, EventArgs e)
{
SaveCompleted();
}
private void mnuEditAuthors_Click(object sender, EventArgs e)
{
frmDBEditor manageForm = new frmDBEditor(db, frmDBEditor.EditType.Author);
manageForm.ShowDialog(this);
}
private void menuEditNoteTypes_Click(object sender, EventArgs e)
{
frmDBEditor manageForm = new frmDBEditor(db, frmDBEditor.EditType.NoteType);
manageForm.ShowDialog(this);
}
private void menuRestoreDB_Click(object sender, EventArgs e)
{
DialogResult warning = MessageBox.Show(this, "This will overwrite the current database!\nAre you sure?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (warning == DialogResult.Yes)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "SQLite Database File|*.db";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
File.Copy(ofd.FileName, db.DatabasePath, true);
}
db = new DBAdapter();
InvalidateDatabase();
}
}
private void menuBackupDB_Click(object sender, EventArgs e)
{
BackupDatabase();
}
private void menuClearDB_Click(object sender, EventArgs e)
{
DialogResult warning = MessageBox.Show(this, "This will overwrite the current database!\nAre you sure?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (warning == DialogResult.Yes)
{
File.Copy(Application.StartupPath + "\\Database\\ProfiledNotes.db", db.DatabasePath, true);
db = new DBAdapter();
InvalidateDatabase();
}
}
#endregion
private void menuAbout_Click(object sender, EventArgs e)
{
frmAbout about = new frmAbout();
about.ShowDialog();
}
#endregion
#region Toolbar
/// <summary>
/// This is used to set the authors of selected note(s).
/// The list is populated whenever the database is invalidated directly from the database.
/// </summary>
/// <param name="sender">The combobox</param>
/// <param name="e">The parameters</param>
private void comboAuthor_SelectionChangeCommitted(object sender, EventArgs e)
{
List<Note> backup = new List<Note>(selectedNotes);
Author which = comboAuthor.SelectedIndex == 0 ? null : (Author)comboAuthor.SelectedItem;
foreach (Note selected in selectedNotes.ToList()) //Allows multiple selection
{
selected.Author = which;
selected.MarkedUpdate = true;
}
if (currentSession != null)
currentSession.Dirty = true;
selectedNotes = new List<Note>(backup);
SyncSelection(false, false);
}
/// <summary>
/// This is used to set the note type of selected note(s).
/// The list is populated whenever the database is invalidated directly from the database.
/// </summary>
/// <param name="sender">The combobox</param>
/// <param name="e">The parameters</param>
private void comboNoteType_SelectionChangeCommitted(object sender, EventArgs e)
{
List<Note> backup = new List<Note>(selectedNotes);
Note.NoteType which = comboNoteType.SelectedIndex == 0 ? null : (Note.NoteType)comboNoteType.SelectedItem;
foreach (Note selected in selectedNotes.ToList())
{
selected.Type = which;
selected.MarkedUpdate = true;
}
if (currentSession != null)
currentSession.Dirty = true;
selectedNotes = new List<Note>(backup);
SyncSelection(false, false);
}
/// <summary>
/// Saves completed notes to the database.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveReadyToDB_Click(object sender, EventArgs e)
{
SaveCompleted();
}
private void btnOpen_Click(object sender, EventArgs e)
{
FileLoad();
}
/// <summary>
/// Handler for the "Open Image" button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoad_Click(object sender, EventArgs e)
{
ImageLoad();
}
/// <summary>
/// Handle the "Select Multiple" button selection (toggle).
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectMultiple_Click(object sender, EventArgs e)
{
if (currentMode == SelectionMode.Select)
{
setMode(SelectionMode.Default);
}
else
{
setMode(SelectionMode.Select);
}
}
/// <summary>
/// Starts the "Add new Note" proceedure
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddNote_Click(object sender, EventArgs e)
{
StartCreate();
}
private void btnMerge_Click(object sender, EventArgs e)
{
MergeSelectedNotes();
}
private void btnDelete_Click(object sender, EventArgs e)
{
DeleteSelectedNotes();
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearAllDetected();
}
private void btnSave_Click(object sender, EventArgs e)
{
FileSave();
}
/// <summary>
/// Syncs the min and max values
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void numMin_TextChanged(object sender, EventArgs e)
{
if (numMin.Value > numMax.Value)
numMax.Value = numMin.Value;
}
/// <summary>
/// Syncs the min and max values
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void numMax_Click(object sender, EventArgs e)
{
if (numMax.Value < numMin.Value)
numMin.Value = numMax.Value;
}
/// <summary>
/// Rescans notes with the current min and max parameters.
/// It does NOT erase any previously detected notes.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRescan_Click(object sender, EventArgs e)
{
ScanNotes();
}
/// <summary>
/// Loads the DB editor for authors
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnManageAuthors_Click(object sender, EventArgs e)
{
frmDBEditor manageForm = new frmDBEditor(db, frmDBEditor.EditType.Author);
manageForm.ShowDialog(this);
}
/// <summary>
/// Toggles the "Pan" / "Select Multiple" mode.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPan_Click(object sender, EventArgs e)
{
if (currentMode == SelectionMode.Select)
{
setMode(SelectionMode.Default);
}
else
{
setMode(SelectionMode.Select);
}
}
/// <summary>
/// Loads the note type DB editor.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnEditNoteTypes_Click(object sender, EventArgs e)
{
frmDBEditor manageForm = new frmDBEditor(db, frmDBEditor.EditType.NoteType);
manageForm.ShowDialog(this);
}
#endregion
#region Imagebox
/// <summary>
/// Handles clicks on the imagebox.
/// If a note was clicked - selects or unselects it.
/// Also handles modifiers (shift) for multiple selections.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imageboxMain_clicked(object sender, EventArgs e)
{
if (imageboxMain.Image == null)
return;
Point clickedPoint = imageboxMain.PointToImage(((MouseEventArgs)e).Location);
Note clickedNote = noteList.FirstOrDefault(s => s.Rectangle.Contains(clickedPoint));
if (clickedNote != null) //If the user clicked a note
{
if (!selectedNotes.Contains(clickedNote)) //If we clicked a note that was previously unselected
{
if (ModifierKeys != Keys.Shift) //If the SHIFT key is not pressed or multiple notes selected - clear first.
{
ClearSelection();
}
SelectNote(clickedNote);
}
else //If we pressed a note that was already selected
{
if (selectedNotes.Count > 1) //If there is more than one note currently selected
{
if (ModifierKeys != Keys.Shift) //Shift is not pressed
{
ClearSelection();
SelectNote(clickedNote);
}
else //SHIFT is pressed
{
DeselectNote(clickedNote);
}
}
else //Only one note selected
{
DeselectNote(clickedNote);
}
}
}
}
/// <summary>
/// Makes sure that while selecting notes, the listbox goes into sleep mode so it doesn't slow down the interface.
/// The listbox will be updated after selection is finished.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imageboxMain_Selecting(object sender, Cyotek.Windows.Forms.ImageBoxCancelEventArgs e)
{
isListBoxUpdating = true;
listBoxFoundNotes.BeginUpdate();
}
/// <summary>
/// When an area is FINISHED being selected on the image.
/// Depending on the mode - either selects or creates notes.
/// Afterwards, allows the listbox to be updated with the new state.
/// </summary>
/// <param name="sender">The imagebox sending the event</param>
/// <param name="e">Eventargs</param>
private void imageboxMain_Selected(object sender, EventArgs e)
{
switch (currentMode)
{
case SelectionMode.Select:
if (ModifierKeys != Keys.Shift) //If not shift, clear first.
ClearSelection();
selectedNotes.AddRange(noteList.Where(x => imageboxMain.SelectionRegion.Contains(x.Rectangle)));
SyncSelection(true, false);
break;
case SelectionMode.Create:
Note newNote = new Note(currentPage.Hash);
newNote.Rectangle = Rectangle.Round(imageboxMain.SelectionRegion);
noteList.Add(newNote);
DrawRectangle(currentPage.Working, newNote.Rectangle, McvColor.Green);
SyncSelection(false, false);
break;
default:
//this should not happen!
break;
}
imageboxMain.SelectNone();
listBoxFoundNotes.EndUpdate();
isListBoxUpdating = false;
}
/// <summary>
/// If control is double clicked without an image, show open file dialog.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imageboxMain_DoubleClick(object sender, EventArgs e)
{
if (imageboxMain.Image == null)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images|*.jpg;*.png;*.gif;*.jpeg";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
LoadImage(ofd.FileName);
}
}
}
/// <summary>
/// Make sure the correct curser is showing depending on what's under it.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imageboxMain_MouseMove(object sender, MouseEventArgs e)
{
InvalidateCursor(e.Location);
}
private void imageboxMain_KeyUp(object sender, KeyEventArgs e)
{
InvalidateCursor(Cursor.Position);
}
private void imageboxMain_KeyDown(object sender, KeyEventArgs e)
{
InvalidateCursor(Cursor.Position);
}
/// <summary>
/// Update the selection on the image if selection of the listbox changes.
/// </summary>
/// <param name="sender">The sending listbox</param>
/// <param name="e">The Event Arguments</param>
private void listBoxFoundNotes_SelectedIndexChanged(object sender, EventArgs e)
{
if (isListBoxUpdating)
return;
selectedNotes.Clear();
selectedNotes = listBoxFoundNotes.SelectedItems.Cast<Note>().ToList();
SyncSelection(true, true);
}
#endregion
#region Form
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (!VerifyExit())
e.Cancel = true;
}
#endregion
#endregion
/// <summary>
/// Sets the current interface mode for what happens when you drag the mouse on the image.
/// </summary>
/// <param name="newMode">The mode to set</param>
private void setMode(SelectionMode newMode)
{
currentMode = newMode;
switch (newMode)
{
case SelectionMode.Default:
imageboxMain.SelectNone();
imageboxMain.SelectionMode = Cyotek.Windows.Forms.ImageBoxSelectionMode.None;
break;
case SelectionMode.Select:
imageboxMain.SelectionMode = Cyotek.Windows.Forms.ImageBoxSelectionMode.Rectangle;
imageboxMain.SelectionColor = Color.Red;
break;
case SelectionMode.Create:
imageboxMain.SelectionMode = Cyotek.Windows.Forms.ImageBoxSelectionMode.Rectangle;
imageboxMain.SelectionColor = Color.Green;
break;
case SelectionMode.Zoom:
throw new NotImplementedException(); //It was eventually not needed, as the ImageBox control supports zooming by scrolling.
}
InvalidateButtons(); //Refresh button states to match current modes
}
/// <summary>
/// Sets the cursor to contextually match what's under it and what mode it's in.
/// The function recieves global coordinates, so we use the ImageBox controller's helper function to convert it to image coordinates.
/// </summary>
/// <param name="mouseLocation">What are the cursor coordinates</param>
private void InvalidateCursor(Point mouseLocation)
{
if (imageboxMain.Image != null)
{
switch (currentMode)
{
case SelectionMode.Default:
if (ModifierKeys == Keys.Shift)
{
imageboxMain.Cursor = groupSelect;
}
else
{
Note highlightedNote = noteList.FirstOrDefault(s => s.Rectangle.Contains(imageboxMain.PointToImage(mouseLocation)));
if (highlightedNote != null)
imageboxMain.Cursor = Cursors.Hand;
else
imageboxMain.Cursor = DefaultCursor;
}
break;
case SelectionMode.Create:
imageboxMain.Cursor = curPen;
break;
case SelectionMode.Select:
imageboxMain.Cursor = Cursors.Cross;
break;
}
}
}
/// <summary>
/// Syncs between the selection on the image and the selection in the listbox.
/// </summary>
private void SyncSelection(bool redraw, bool sentFromListBox)
{
imageboxMain.Image = currentPage.Working.Bitmap;
lblSelectedCount.Text = "Number of selected notes: " + selectedNotes.Count;
isListBoxUpdating = true;
if (!sentFromListBox)
{
listBoxFoundNotes.ClearSelected();
}
List<Author> commonAuthors = new List<Author>();
List<Note.NoteType> commonTypes = new List<Note.NoteType>();
foreach (Note item in selectedNotes)
{
if (!sentFromListBox)
listBoxFoundNotes.SelectedItems.Add(item);
if (item.Author != null && commonAuthors.FirstOrDefault(a => a.ID == item.Author.ID && a.Name.Equals(item.Author.Name)) == null)
commonAuthors.Add(item.Author);
if (item.Type != null && commonTypes.FirstOrDefault(t => t.ID == item.Type.ID && t.Description.Equals(item.Type.Description)) == null)
commonTypes.Add(item.Type);
}
if (commonAuthors.Count == 1 && commonAuthors[0] != null)
comboAuthor.ComboBox.SelectedItem = authorList.FirstOrDefault(l => l.ID == commonAuthors[0].ID);
else
{
comboAuthor.ComboBox.SelectedIndex = 0;
comboAuthor.Text = "Set Author...";
}
if (commonTypes.Count == 1 && commonTypes[0] != null)
comboNoteType.ComboBox.SelectedItem = noteTypeList.FirstOrDefault(t => t.ID == commonTypes[0].ID);
else
{
comboNoteType.ComboBox.SelectedIndex = 0;
comboNoteType.Text = "Set Note Type...";
}
isListBoxUpdating = false;
if (redraw)
RedrawAllRectangles();
InvalidateButtons();
}
/// <summary>
/// Sets all butotn states (highlighted, enabled, etc.) to match the current state of the form.
/// </summary>
private void InvalidateButtons()
{
bool isLoaded = (imageboxMain.Image != null);
if (!isLoaded)
{
foreach (ToolStripItem item in imageTools)
{
item.Enabled = false;
if (item is ToolStripButton)
{
((ToolStripButton)item).Checked = false;
}
else if (item is ToolStripComboBox)
{
((ToolStripComboBox)item).ComboBox.SelectedIndex = 0;
}
}
}
else
{
foreach (ToolStripItem item in imageTools)
{
item.Enabled = true;
if (item is ToolStripComboBox)
{
item.Enabled = (selectedNotes.Count > 0);
}
}
btnDelete.Enabled = (selectedNotes.Count > 0);
menuDelete.Enabled = (selectedNotes.Count > 0);
btnMerge.Enabled = (selectedNotes.Count > 1);
menuMergeNotes.Enabled = (selectedNotes.Count > 1);
btnAddNote.Checked = (currentMode == SelectionMode.Create);
menuAddNote.Checked = (currentMode == SelectionMode.Create);
btnSelectMultiple.Checked = (currentMode == SelectionMode.Select);
mnuMultiSelect.Checked = (currentMode == SelectionMode.Select);
btnPan.Checked = (currentMode == SelectionMode.Default);
}
btnSave.Enabled = (currentSession != null && currentSession.Dirty);
menuNotes.Enabled = isLoaded;
menuSaveReady.Enabled = isLoaded;
}
#endregion
#region Note Operations
#region Selection
/// <summary>
/// Select a note by making its bounding rectangle red and adding it to the relevant lists.
/// Also highlights it in the listbox if neccesary
/// </summary>
/// <param name="which">Note object to select</param>
private void SelectNote(Note which)
{
DrawRectangle(currentPage.Working, which.Rectangle, McvColor.Red);
selectedNotes.Add(which);
SyncSelection(false, false);
}
/// <summary>
/// Un-Select a note by making its bounding rectangle green and removing it from the relevant lists.
/// Also un-highlights it in the listbox if neccesary
/// </summary>
/// <param name="which">A Note object to deselect</param>
private void DeselectNote(Note which)
{
DrawRectangle(currentPage.Working, which.Rectangle, which.isComplete() ? McvColor.Blue : McvColor.Green);
selectedNotes.Remove(which); //This HAS to come before changing the listbox selection to avoid looping
SyncSelection(false, false);
}
/// <summary>
/// Resets the selection of any notes both graphically and logically
/// </summary>
private void ClearSelection()
{
selectedNotes.Clear();
SyncSelection(true, false);
}
/// <summary>
/// A "Last Resort" function - goes over all the notes and redraws them according whether or not they're in the selected list.
/// </summary>
private void RedrawAllRectangles()
{
currentPage.Working = currentPage.Original.Clone();
foreach (Note note in noteList)
{
if (selectedNotes.Contains(note))
DrawRectangle(currentPage.Working, note.Rectangle, McvColor.Red);
else if (note.isComplete())
DrawRectangle(currentPage.Working, note.Rectangle, McvColor.Blue);
else
DrawRectangle(currentPage.Working, note.Rectangle, McvColor.Green);
}
imageboxMain.Image = currentPage.Working.Bitmap;
}
/// <summary>
/// Draws a rectengle on an image
/// </summary>
/// <param name="img">What image to draw on</param>
/// <param name="rect">The rectangle to draw</param>
/// <param name="color">The color to draw in</param>
private void DrawRectangle(Mat img, Rectangle rect, MCvScalar color)
{
CvInvoke.Rectangle(img, rect, color, 2);
}
#endregion
#region Note Editing
/// <summary>
/// When creating a note - first sets the correct mode.
/// The actual creation will be handled by the Selecting method.
/// </summary>
public void StartCreate()
{
if (currentMode != SelectionMode.Create)
{
setMode(SelectionMode.Create);
}
else
{
setMode(SelectionMode.Default);
}
}
/// <summary>
/// Deletes whatever notes are currently selected.
/// </summary>
public void DeleteSelectedNotes()
{
if (selectedNotes.Count <= 0) //Shouldn't happen
return;
string message = "Are you sure you want to delete the selected note(s)?\nTHIS CAN NOT BE UNDONE!";