root/IBBoard.WarFoundry.GUI.WinForms/trunk/FrmMain.cs @ 148

Revision 148, 36.2 KB (checked in by ibboard, 15 months ago)

Re #90: Stop new units showing up twice

  • Pass ArmyCategory to CreateAndAddUnitCommand
Line 
1// This file (FrmMain.cs) is a part of the IBBoard.WarFoundry.GUI.WinForms project and is copyright 2009 IBBoard.
2//
3// The file and the library/program it is in are licensed under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING.LGPL for more information and the full license.
4
5using System;
6using System.Drawing;
7using System.Drawing.Drawing2D;
8using System.Collections;
9using System.ComponentModel;
10using System.Windows.Forms;
11using System.Data;
12using System.IO;
13using System.Threading;
14using log4net;
15using IBBoard;
16using IBBoard.CustomMath;
17using IBBoard.Commands;
18using IBBoard.IO;
19using IBBoard.Lang;
20using IBBoard.Windows.Forms;
21using IBBoard.Windows.Forms.I18N;
22using IBBoard.Xml;
23using IBBoard.WarFoundry.API;
24using IBBoard.WarFoundry.API.Commands;
25using IBBoard.WarFoundry.API.Objects;
26using IBBoard.WarFoundry.API.Savers;
27using IBBoard.WarFoundry.API.Factories;
28using IBBoard.WarFoundry.API.Factories.Xml;
29
30namespace IBBoard.WarFoundry
31{
32    /// <summary>
33    /// Summary description for Form1.
34    /// </summary>
35    public class FrmMain : System.Windows.Forms.Form
36    {
37        private static readonly string AppTitle = "WarFoundry";
38        const string DefaultDataDir = "data";
39
40        private Preferences preferences;
41        protected readonly ILog logger = LogManager.GetLogger(typeof(FrmMain));
42
43        private CommandStack commandStack;
44        private ToolBarButton[] categoryButtons;
45
46        public ObjectAddDelegate UnitAddedMethod;
47        public ObjectRemoveDelegate UnitRemovedMethod;
48        public DoubleValChangedDelegate PointsValueChangedMethod;
49        //public FailedUnitRequirementDelegate FailedUnitRequirementMethod;
50
51        private FrmArmyTree armyTree;
52        private FrmDebugOutput debugWindow;
53        private string loadedFilePath;
54
55        private System.ComponentModel.IContainer components;
56        private System.Windows.Forms.ToolBar toolBar;
57        private IBBoard.Windows.Forms.IBBToolBarButton bttnNewArmy;
58        private System.Windows.Forms.ImageList buttonIcons;
59        private IBBoard.Windows.Forms.IBBToolBarButton bttnSaveArmy;
60        private System.Windows.Forms.OpenFileDialog openArmyDialog;
61        private System.Windows.Forms.SaveFileDialog saveArmyDialog;
62        private IBBoard.Windows.Forms.IBBToolBarButton bttnOpenArmy;
63        private IBBoard.Windows.Forms.IBBToolBarButton bttnSep1;
64        private IBBoard.Windows.Forms.IBBToolBarButton bttnUndo;
65        private IBBoard.Windows.Forms.IBBToolBarButton bttnRedo;
66        private System.Windows.Forms.MainMenu mainMenu;
67        private IBBoard.Windows.Forms.IBBMenuItem menuFile;
68        private IBBoard.Windows.Forms.IBBMenuItem miNewArmy;
69        private IBBoard.Windows.Forms.IBBMenuItem miOpenArmy;
70        private IBBoard.Windows.Forms.IBBMenuItem miCloseArmy;
71        private IBBoard.Windows.Forms.IBBMenuItem miSaveArmy;
72        private IBBoard.Windows.Forms.IBBMenuItem miSaveArmyAs;
73        private System.Windows.Forms.MenuItem miSep2;
74        private IBBoard.Windows.Forms.IBBMenuItem miChangeSystem;
75        private System.Windows.Forms.MenuItem miSep1;
76        private IBBoard.Windows.Forms.IBBMenuItem miReloadFiles;
77        private System.Windows.Forms.MenuItem miSep3;
78        private IBBoard.Windows.Forms.IBBMenuItem miExit;
79        private IBBoard.Windows.Forms.IBBMenuItem menuEdit;
80        private IBBoard.Windows.Forms.IBBMenuItem miUndo;
81        private IBBoard.Windows.Forms.IBBMenuItem miRedo;
82        private IBBoard.Windows.Forms.IBBMenuItem menuHelp;
83        private IBBoard.Windows.Forms.IBBMenuItem miDebugWindow;
84        private IBBoard.Windows.Forms.IBBMenuItem miAbout;
85        private IBBoard.Windows.Forms.ColorableStatusBarPanel sbMainPanel;
86        private IBBoard.Windows.Forms.ColorableStatusBarPanel sbErrorPanel;
87        private IBBoard.Windows.Forms.ColorableStatusBarPanel sbPointsPanel;
88        private System.Windows.Forms.ContextMenu undoMenu;
89        private System.Windows.Forms.ContextMenu redoMenu;
90        private IBBoard.Windows.Forms.ColorableStatusBar statusBar;
91        private System.Windows.Forms.Timer statusBarTimer;
92        private System.Windows.Forms.Panel pnlRight;
93
94        public FrmMain(string[] args)
95        {
96            this.Closing+=new CancelEventHandler(FrmMain_Closing);
97            CommandStack.CommandStackUpdated += new MethodInvoker(commandStack_CommandStackUpdated);
98
99            InitializeComponent();
100
101            Preferences = new Preferences("WarFoundry");
102            try
103            {
104                Translation.InitialiseTranslations(Constants.ExecutablePath, Preferences["language"].ToString());
105            }
106            catch (TranslationLoadException ex)
107            {
108                logger.Error(ex);
109                MessageBox.Show(this, "Translation loading failed for language " + Preferences["language"].ToString(), "Translation failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
110            }
111
112            //pnlRight.Left = ClientSize.Width - pnlRight.Width - 2;
113            //pnlRight.Top = toolBar.Height + 5;
114            //pnlRight.Height = ClientRectangle.Bottom - statusBar.Height - pnlRight.Top - 3;
115
116            foreach (Control ctrl in Controls)
117            {
118                ControlTranslator.TranslateControl(ctrl);
119            }
120
121            foreach(Component comp in components.Components)
122            {
123                ControlTranslator.TranslateComponent(comp);
124            }
125
126            foreach (IBBMenuItem mi in Menu.MenuItems)
127            {
128                ControlTranslator.TranslateComponent(mi);
129            }
130
131            ControlTranslator.TranslateComponent(openArmyDialog);
132            ControlTranslator.TranslateComponent(saveArmyDialog);
133
134            WarFoundryCore.GameSystemChanged+= new GameSystemChangedDelegate(FrmMain_GameSystemChanged);
135            WarFoundryCore.ArmyChanged += new ArmyChangedDelegate(FrmMain_ArmyChanged);
136            UnitAddedMethod = new ObjectAddDelegate(FrmMain_UnitAddedMethod);
137            UnitRemovedMethod = new ObjectRemoveDelegate(FrmMain_UnitRemovedMethod);
138            PointsValueChangedMethod = new DoubleValChangedDelegate(FrmMain_PointsValueChangedMethod);
139            //FailedUnitRequirementMethod = new FailedUnitRequirementDelegate(FrmMain_FailedUnitRequirement);
140
141            sbErrorPanel.Color = Color.Red;
142
143            armyTree = new FrmArmyTree(CommandStack);
144            armyTree.MdiParent = this;
145            armyTree.Show();
146            armyTree.StartPosition = FormStartPosition.Manual;
147            armyTree.Location = new Point(this.DisplayRectangle.Width - armyTree.Width - 10, 10);
148            ControlTranslator.TranslateControl(armyTree);
149
150            // hack to load default files
151            WarFoundryLoader.GetDefault().AddLoadDirectory(new DirectoryInfo(Constants.ExecutablePath + Constants.DirectoryString + DefaultDataDir));
152
153            IWarFoundryFactory factory = WarFoundryFactoryFactory.GetFactoryFactory().GetFactory(typeof(WarFoundryXmlFactory));
154
155            if (factory != null && factory is WarFoundryXmlFactory)
156            {
157                WarFoundryLoader.GetDefault().RegisterFactory((WarFoundryXmlFactory)factory);
158            }
159
160            /*
161            if (args.Length == 1)
162            {
163                logger.Debug("Attempting to load from file");               
164                FileInfo file = new FileInfo(args[0]);
165               
166                try
167                {
168                    if (file.Extension.Equals("."+Factory.GetArmyFileExtension()))
169                    {
170                        WarFoundryCore.CurrentArmy = Factory.CreateArmyFromFile(file);
171                        logger.InfoFormat("Loaded army from {0}", file.FullName);
172                    }
173                    else if (file.Extension.Equals("."+Factory.GetSystemFileExtension()))
174                    {
175                        WarFoundryCore.CurrentGameSystem = Factory.CreateGameSystemFromFile(file);
176                        logger.InfoFormat("Loaded game system from {0}", file.FullName);
177                    }
178                }
179                catch (InvalidFileException ex)
180                {
181                    MessageBox.Show(Translation.GetTranslation("InvalidFileLoadError", "The file loaded ({0}) was not a valid WarFoundry file", file.FullName), Translation.GetTranslation("InvalidFileLoadTitle", "Invalid data file", null), MessageBoxButtons.OK, MessageBoxIcon.Error);
182                    logger.Error(ex);
183                }
184            }
185            else
186            {
187                string gameSystemID = Preferences.GetStringProperty("currSystem");
188
189                if (gameSystemID!=null && !"".Equals(gameSystemID))
190                {
191                    logger.Debug("Attempting to load current game system from properties");
192                    GameSystem sys = Factory.GetGameSystem(gameSystemID);
193                   
194                    if (sys!=null)
195                    {
196                        WarFoundryCore.CurrentGameSystem = sys;
197                        logger.InfoFormat("Loaded game system {0} from properties", gameSystemID);
198                    }
199                }
200            }*/
201        }
202
203        public static string DataPath
204        {
205            get { return Constants.ExecutablePath+Constants.DirectoryChar+"data"; }
206        }
207
208        public static String ArmiesPath
209        {
210            get { return Constants.UserDataPath+Constants.DirectoryChar+"armies"; }
211        }
212
213        public Preferences Preferences
214        {
215            get { return preferences; }
216            set { preferences = value; }
217        }
218
219        public CommandStack CommandStack
220        {
221            get
222            {
223                if (commandStack == null)
224                {                   
225                    commandStack = new CommandStack();
226                }
227
228                return commandStack;
229            }
230        }
231
232        /// <summary>
233        /// Clean up any resources being used.
234        /// </summary>
235        protected override void Dispose( bool disposing )
236        {
237            if( disposing )
238            {
239                if (components != null)
240                {
241                    components.Dispose();
242                }
243            }
244            base.Dispose( disposing );
245        }
246
247        #region Windows Form Designer generated code
248        /// <summary>
249        /// Required method for Designer support - do not modify
250        /// the contents of this method with the code editor.
251        /// </summary>
252        private void InitializeComponent()
253        {
254            this.components = new System.ComponentModel.Container();
255            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
256            this.statusBar = new IBBoard.Windows.Forms.ColorableStatusBar();
257            this.sbMainPanel = new IBBoard.Windows.Forms.ColorableStatusBarPanel();
258            this.sbErrorPanel = new IBBoard.Windows.Forms.ColorableStatusBarPanel();
259            this.sbPointsPanel = new IBBoard.Windows.Forms.ColorableStatusBarPanel();
260            this.toolBar = new System.Windows.Forms.ToolBar();
261            this.bttnNewArmy = new IBBoard.Windows.Forms.IBBToolBarButton();
262            this.bttnOpenArmy = new IBBoard.Windows.Forms.IBBToolBarButton();
263            this.bttnSaveArmy = new IBBoard.Windows.Forms.IBBToolBarButton();
264            this.bttnSep1 = new IBBoard.Windows.Forms.IBBToolBarButton();
265            this.bttnUndo = new IBBoard.Windows.Forms.IBBToolBarButton();
266            this.undoMenu = new System.Windows.Forms.ContextMenu();
267            this.bttnRedo = new IBBoard.Windows.Forms.IBBToolBarButton();
268            this.redoMenu = new System.Windows.Forms.ContextMenu();
269            this.buttonIcons = new System.Windows.Forms.ImageList(this.components);
270            this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
271            this.menuFile = new IBBoard.Windows.Forms.IBBMenuItem();
272            this.miNewArmy = new IBBoard.Windows.Forms.IBBMenuItem();
273            this.miOpenArmy = new IBBoard.Windows.Forms.IBBMenuItem();
274            this.miSaveArmy = new IBBoard.Windows.Forms.IBBMenuItem();
275            this.miSaveArmyAs = new IBBoard.Windows.Forms.IBBMenuItem();
276            this.miCloseArmy = new IBBoard.Windows.Forms.IBBMenuItem();
277            this.miSep1 = new System.Windows.Forms.MenuItem();
278            this.miChangeSystem = new IBBoard.Windows.Forms.IBBMenuItem();
279            this.miSep2 = new System.Windows.Forms.MenuItem();
280            this.miReloadFiles = new IBBoard.Windows.Forms.IBBMenuItem();
281            this.miSep3 = new System.Windows.Forms.MenuItem();
282            this.miExit = new IBBoard.Windows.Forms.IBBMenuItem();
283            this.menuEdit = new IBBoard.Windows.Forms.IBBMenuItem();
284            this.miUndo = new IBBoard.Windows.Forms.IBBMenuItem();
285            this.miRedo = new IBBoard.Windows.Forms.IBBMenuItem();
286            this.menuHelp = new IBBoard.Windows.Forms.IBBMenuItem();
287            this.miAbout = new IBBoard.Windows.Forms.IBBMenuItem();
288            this.miDebugWindow = new IBBoard.Windows.Forms.IBBMenuItem();
289            this.openArmyDialog = new System.Windows.Forms.OpenFileDialog();
290            this.saveArmyDialog = new System.Windows.Forms.SaveFileDialog();
291            this.pnlRight = new System.Windows.Forms.Panel();
292            this.statusBarTimer = new System.Windows.Forms.Timer(this.components);
293            ((System.ComponentModel.ISupportInitialize)(this.sbMainPanel)).BeginInit();
294            ((System.ComponentModel.ISupportInitialize)(this.sbErrorPanel)).BeginInit();
295            ((System.ComponentModel.ISupportInitialize)(this.sbPointsPanel)).BeginInit();
296            this.SuspendLayout();
297            //
298            // statusBar
299            //
300            this.statusBar.Location = new System.Drawing.Point(0, 548);
301            this.statusBar.Name = "statusBar";
302            this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
303            this.sbMainPanel,
304            this.sbErrorPanel,
305            this.sbPointsPanel});
306            this.statusBar.ShowPanels = true;
307            this.statusBar.Size = new System.Drawing.Size(792, 22);
308            this.statusBar.TabIndex = 1;
309            this.statusBar.PanelClick += new System.Windows.Forms.StatusBarPanelClickEventHandler(this.statusBar_PanelClick);
310            this.statusBar.DrawItem += new System.Windows.Forms.StatusBarDrawItemEventHandler(this.statusBar_DrawItem);
311            //
312            // sbMainPanel
313            //
314            this.sbMainPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
315            this.sbMainPanel.Color = System.Drawing.SystemColors.WindowText;
316            this.sbMainPanel.Name = "sbMainPanel";
317            this.sbMainPanel.Style = System.Windows.Forms.StatusBarPanelStyle.OwnerDraw;
318            this.sbMainPanel.Width = 475;
319            //
320            // sbErrorPanel
321            //
322            this.sbErrorPanel.Color = System.Drawing.SystemColors.WindowText;
323            this.sbErrorPanel.Name = "sbErrorPanel";
324            this.sbErrorPanel.Style = System.Windows.Forms.StatusBarPanelStyle.OwnerDraw;
325            this.sbErrorPanel.Width = 150;
326            //
327            // sbPointsPanel
328            //
329            this.sbPointsPanel.Color = System.Drawing.SystemColors.WindowText;
330            this.sbPointsPanel.Name = "sbPointsPanel";
331            this.sbPointsPanel.Style = System.Windows.Forms.StatusBarPanelStyle.OwnerDraw;
332            this.sbPointsPanel.ToolTipText = "Current Points Total";
333            this.sbPointsPanel.Width = 150;
334            //
335            // toolBar
336            //
337            this.toolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
338            this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
339            this.bttnNewArmy,
340            this.bttnOpenArmy,
341            this.bttnSaveArmy,
342            this.bttnSep1,
343            this.bttnUndo,
344            this.bttnRedo});
345            this.toolBar.ButtonSize = new System.Drawing.Size(16, 16);
346            this.toolBar.DropDownArrows = true;
347            this.toolBar.ImageList = this.buttonIcons;
348            this.toolBar.Location = new System.Drawing.Point(0, 0);
349            this.toolBar.Name = "toolBar";
350            this.toolBar.ShowToolTips = true;
351            this.toolBar.Size = new System.Drawing.Size(792, 28);
352            this.toolBar.TabIndex = 2;
353            this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
354            //
355            // bttnNewArmy
356            //
357            this.bttnNewArmy.Enabled = false;
358            this.bttnNewArmy.ImageIndex = 0;
359            this.bttnNewArmy.Name = "bttnNewArmy";
360            //
361            // bttnOpenArmy
362            //
363            this.bttnOpenArmy.ImageIndex = 2;
364            this.bttnOpenArmy.Name = "bttnOpenArmy";
365            //
366            // bttnSaveArmy
367            //
368            this.bttnSaveArmy.Enabled = false;
369            this.bttnSaveArmy.ImageIndex = 1;
370            this.bttnSaveArmy.Name = "bttnSaveArmy";
371            //
372            // bttnSep1
373            //
374            this.bttnSep1.Name = "";
375            this.bttnSep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
376            //
377            // bttnUndo
378            //
379            this.bttnUndo.DropDownMenu = this.undoMenu;
380            this.bttnUndo.Enabled = false;
381            this.bttnUndo.ImageIndex = 3;
382            this.bttnUndo.Name = "bttnUndo";
383            this.bttnUndo.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
384            //
385            // bttnRedo
386            //
387            this.bttnRedo.DropDownMenu = this.redoMenu;
388            this.bttnRedo.Enabled = false;
389            this.bttnRedo.ImageIndex = 4;
390            this.bttnRedo.Name = "bttnRedo";
391            this.bttnRedo.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
392            //
393            // buttonIcons
394            //
395            this.buttonIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("buttonIcons.ImageStream")));
396            this.buttonIcons.TransparentColor = System.Drawing.Color.Transparent;
397            this.buttonIcons.Images.SetKeyName(0, "");
398            this.buttonIcons.Images.SetKeyName(1, "");
399            this.buttonIcons.Images.SetKeyName(2, "");
400            this.buttonIcons.Images.SetKeyName(3, "");
401            this.buttonIcons.Images.SetKeyName(4, "");
402            this.buttonIcons.Images.SetKeyName(5, "");
403            this.buttonIcons.Images.SetKeyName(6, "");
404            //
405            // mainMenu
406            //
407            this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
408            this.menuFile,
409            this.menuEdit,
410            this.menuHelp});
411            //
412            // menuFile
413            //
414            this.menuFile.Index = 0;
415            this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
416            this.miNewArmy,
417            this.miOpenArmy,
418            this.miSaveArmy,
419            this.miSaveArmyAs,
420            this.miCloseArmy,
421            this.miSep1,
422            this.miChangeSystem,
423            this.miSep2,
424            this.miReloadFiles,
425            this.miSep3,
426            this.miExit});
427            this.menuFile.Text = "&file";
428            this.menuFile.Name = "menuFile";
429            //
430            // miNewArmy
431            //
432            this.miNewArmy.Enabled = false;
433            this.miNewArmy.Index = 0;
434            this.miNewArmy.Text = "&new army";
435            this.miNewArmy.Click += new System.EventHandler(this.miNewArmy_Click);
436            this.miNewArmy.Name = "miNewArmy";
437            //
438            // miOpenArmy
439            //
440            this.miOpenArmy.Index = 1;
441            this.miOpenArmy.Text = "&open army";
442            this.miOpenArmy.Click += new System.EventHandler(this.miOpenArmy_Click);
443            this.miOpenArmy.Name = "miOpenArmy";
444            //
445            // miSaveArmy
446            //
447            this.miSaveArmy.Enabled = false;
448            this.miSaveArmy.Index = 2;
449            this.miSaveArmy.Text = "&save army";
450            this.miSaveArmy.Click += new System.EventHandler(this.miSaveArmy_Click);
451            this.miSaveArmy.Name = "miSaveArmy";
452            //
453            // miSaveArmyAs
454            //
455            this.miSaveArmyAs.Enabled = false;
456            this.miSaveArmyAs.Index = 3;
457            this.miSaveArmyAs.Text = "save army &as...";
458            this.miSaveArmyAs.Click += new System.EventHandler(this.miSaveArmyAs_Click);
459            this.miSaveArmyAs.Name = "miSaveArmyAs";
460            //
461            // miCloseArmy
462            //
463            this.miCloseArmy.Enabled = false;
464            this.miCloseArmy.Index = 4;
465            this.miCloseArmy.Text = "&close army";
466            this.miCloseArmy.Click += new System.EventHandler(this.miCloseArmy_Click);
467            this.miCloseArmy.Name = "miCloseArmy";
468            //
469            // miSep1
470            //
471            this.miSep1.Index = 5;
472            this.miSep1.Text = "-";
473            //
474            // miChangeSystem
475            //
476            this.miChangeSystem.Index = 6;
477            this.miChangeSystem.Text = "change &game system";
478            this.miChangeSystem.Click += new System.EventHandler(this.miChangeSystem_Click);
479            this.miChangeSystem.Name = "miChangeSystem";
480            //
481            // miSep2
482            //
483            this.miSep2.Index = 7;
484            this.miSep2.Text = "-";
485            //
486            // miReloadFiles
487            //
488            this.miReloadFiles.Index = 8;
489            this.miReloadFiles.Text = "&reload files";
490            this.miReloadFiles.Click += new System.EventHandler(this.miReloadFiles_Click);
491            this.miReloadFiles.Name = "miReloadFiles";
492            //
493            // miSep3
494            //
495            this.miSep3.Index = 9;
496            this.miSep3.Text = "-";
497            //
498            // miExit
499            //
500            this.miExit.Index = 10;
501            this.miExit.Text = "e&xit";
502            this.miExit.Click += new System.EventHandler(this.miExit_Click);
503            this.miExit.Name = "miExit";
504            //
505            // menuEdit
506            //
507            this.menuEdit.Index = 1;
508            this.menuEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
509            this.miUndo,
510            this.miRedo});
511            this.menuEdit.Text = "&edit";
512            this.menuEdit.Name = "menuEdit";
513            //
514            // miUndo
515            //
516            this.miUndo.Enabled = false;
517            this.miUndo.Index = 0;
518            this.miUndo.Text = "&undo";
519            this.miUndo.Click += new System.EventHandler(this.miUndo_Click);
520            this.miUndo.Name = "miUndo";
521            //
522            // miRedo
523            //
524            this.miRedo.Enabled = false;
525            this.miRedo.Index = 1;
526            this.miRedo.Text = "&redo";
527            this.miRedo.Click += new System.EventHandler(this.miRedo_Click);
528            this.miRedo.Name = "miRedo";
529            //
530            // menuHelp
531            //
532            this.menuHelp.Index = 2;
533            this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
534            this.miAbout,
535            this.miDebugWindow});
536            this.menuHelp.Text = "&help";
537            this.menuHelp.Name = "menuHelp";
538            //
539            // miAbout
540            //
541            this.miAbout.Enabled = false;
542            this.miAbout.Index = 0;
543            this.miAbout.Text = "&about";
544            this.miAbout.Name = "miAbout";
545            //
546            // miDebugWindow
547            //
548            this.miDebugWindow.Index = 1;
549            this.miDebugWindow.Text = "&debug";
550            this.miDebugWindow.Click += new System.EventHandler(this.miDebugWindow_Click);
551            this.miDebugWindow.Name = "miDebugWindow";
552            //
553            // saveArmyDialog
554            //
555            this.saveArmyDialog.Title = "Translatable:saveArmyDialog";
556            //
557            // pnlRight
558            //
559            this.pnlRight.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
560                        | System.Windows.Forms.AnchorStyles.Right)));
561            this.pnlRight.BackColor = System.Drawing.SystemColors.AppWorkspace;
562            this.pnlRight.Location = new System.Drawing.Point(726, 30);
563            this.pnlRight.Name = "pnlRight";
564            this.pnlRight.Size = new System.Drawing.Size(64, 516);
565            this.pnlRight.TabIndex = 4;
566            this.pnlRight.Visible = false;
567            this.pnlRight.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlRight_Paint);
568            //
569            // statusBarTimer
570            //
571            this.statusBarTimer.Interval = 5000;
572            this.statusBarTimer.Tick += new System.EventHandler(this.statusBarTimer_Tick);
573            //
574            // FrmMain
575            //
576            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
577            this.ClientSize = new System.Drawing.Size(792, 570);
578            this.Controls.Add(this.pnlRight);
579            this.Controls.Add(this.toolBar);
580            this.Controls.Add(this.statusBar);
581            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
582            this.IsMdiContainer = true;
583            this.Menu = this.mainMenu;
584            this.Name = "FrmMain";
585            this.Text = "WarFoundry";
586            ((System.ComponentModel.ISupportInitialize)(this.sbMainPanel)).EndInit();
587            ((System.ComponentModel.ISupportInitialize)(this.sbErrorPanel)).EndInit();
588            ((System.ComponentModel.ISupportInitialize)(this.sbPointsPanel)).EndInit();
589            this.ResumeLayout(false);
590            this.PerformLayout();
591
592        }
593        #endregion
594
595        /// <summary>
596        /// The main entry point for the application.
597        /// </summary>
598        [STAThread]
599        static void Main(string[] args)
600        {
601            try
602            {
603                Application.EnableVisualStyles();
604                Application.Run(new FrmMain(args));
605            }
606            catch(Exception ex)
607            {
608                   LogManager.GetLogger(typeof(FrmMain)).Fatal(ex);
609                MessageBox.Show(null, "A major, unexpected and fatal error ocurred while starting the application: \r\n\r\n"+ex.Message+"\r\n\r\n"+ex.StackTrace, "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
610            }
611        }
612
613        private void miExit_Click(object sender, System.EventArgs e)
614        {
615            Application.Exit();
616        }
617
618        private void miNewArmy_Click(object sender, System.EventArgs e)
619        {
620            createNewArmy();
621        }
622
623        private void createNewArmy()
624        {
625            if (closeCurrentArmy())
626            {
627                FrmNewArmy newArmy = new FrmNewArmy(CurrentGameSystem);
628                DialogResult dr = newArmy.ShowDialog();
629
630                if (dr == DialogResult.OK)
631                {
632                    CurrentArmy = new Army(newArmy.SelectedRace, newArmy.ArmyName, newArmy.ArmySize);
633                }
634            }
635        }
636
637        private bool openArmy()
638        {
639            if (closeCurrentArmy())
640            {
641                if (openArmyDialog.Filter=="")
642                {
643                    string savePath = ArmiesPath;
644               
645                    if (!Directory.Exists(savePath))
646                    {
647                        Directory.CreateDirectory(savePath);
648                    }
649
650                    openArmyDialog.InitialDirectory = savePath;
651                    openArmyDialog.Filter = Translation.GetTranslation("armyFileFilter")+"|*.army";
652                    openArmyDialog.Title = Translation.GetTranslation("openArmyDialog");
653
654                }
655
656                DialogResult dr = openArmyDialog.ShowDialog(this);
657
658                if (dr == DialogResult.OK)
659                {
660                    /*
661                    try
662                    {
663                        CurrentArmy = Factory.LoadArmy(openArmyDialog.FileName);
664                        return true;                   
665                    }
666                    catch (InvalidFileException ex)
667                    {
668                        logger.Error(ex);
669                        MessageBox.Show(this, ex.Message, Translation.GetTranslation("InvalidFileBoxTitle", "Invalid data file"), MessageBoxButtons.OK, MessageBoxIcon.Error);
670                        return false;
671                    }
672                     * */
673                    return false;
674                }
675                else
676                {
677                    return false;
678                }
679            }
680            else
681            {
682                return false;
683            }
684        }
685
686        private bool closeCurrentArmy()
687        {
688            if (CurrentArmy!=null)
689            {
690                bool canClose = false;
691
692                if (CommandStack.IsDirty())
693                {
694                    DialogResult dr = MessageBox.Show(this, "The army \""+CurrentArmy.Name+"\" has been modified.\r\nSave changes before closing army?", "Unsaved changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3);
695
696                    if (dr == DialogResult.Yes)
697                    {
698                        canClose = SaveCurrentArmy();
699                    }
700                    else if (dr == DialogResult.No)
701                    {
702                        canClose = true;
703                    }
704                    //else they said cancel and we default to "canClose = false" so do nothing
705                }
706                else
707                {
708                    canClose = true;
709                }
710
711                if (canClose)
712                {
713                    //do close
714                    disableCategoryButtons();
715                    CurrentArmy = null;
716                    return true;
717                }
718                else
719                {
720                    return false;
721                }
722            }
723            else
724            {
725                disableCategoryButtons();
726                //pretend we succeeded
727                return true;
728            }
729        }
730
731        private void undoLastAction()
732        {
733            if (commandStack.CanUndo())
734            {
735                commandStack.Undo();
736            }
737        }
738
739        private void redoAction()
740        {
741            if (commandStack.CanRedo())
742            {
743                commandStack.Redo();
744            }
745        }
746
747        private bool SaveCurrentArmy()
748        {
749            bool saved = false;
750
751            if (loadedFilePath != null || PromptForFilePath())
752            {
753                saved = SaveCurrentArmyToFile();
754            }
755
756            return saved;
757        }
758
759        private bool SaveCurrentArmyAs()
760        {
761            bool saved = false;
762
763            if (PromptForFilePath())
764            {
765                saved = SaveCurrentArmyToFile();
766            }
767           
768            return saved;
769        }
770
771        private bool SaveCurrentArmyToFile()
772        {
773            if (WarFoundrySaver.GetSaver().Save(CurrentArmy, loadedFilePath))
774            {
775                miSaveArmy.Enabled = false;
776                bttnSaveArmy.Enabled = false;
777                CommandStack.setCleanMark();
778                return true;
779            }
780            else
781            {
782                loadedFilePath = null;
783                MessageBox.Show(this, Translation.GetTranslation("SaveFailed"), Translation.GetTranslation("SaveFailedTitle"), MessageBoxButtons.OK, MessageBoxIcon.Error);
784                return false;
785            }
786        }
787
788        private bool PromptForFilePath()
789        {
790            if (saveArmyDialog.Filter == "")
791            {
792                string savePath = ArmiesPath;
793               
794                if (!Directory.Exists(savePath))
795                {
796                    Directory.CreateDirectory(savePath);
797                }
798
799                saveArmyDialog.InitialDirectory = savePath;
800                saveArmyDialog.Filter = Translation.GetTranslation("armyFileFilter")+"|*.army";
801                saveArmyDialog.Title = Translation.GetTranslation("saveArmyDialog");
802            }
803
804            DialogResult dr = saveArmyDialog.ShowDialog(this);
805
806            if (dr == DialogResult.OK)
807            {
808                loadedFilePath = saveArmyDialog.FileName;
809                return true;
810            }
811            else
812            {
813                return false;
814            }
815        }
816
817        private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
818        {
819            if (e.Button == bttnUndo)
820            {
821                undoLastAction();
822            }
823            else if (e.Button == bttnRedo)
824            {
825                redoAction();
826            }
827            else if (e.Button == bttnNewArmy)
828            {
829                createNewArmy();
830            }
831            else if (e.Button == bttnOpenArmy)
832            {
833                openArmy();
834            }
835            else if (e.Button == bttnSaveArmy)
836            {
837                SaveCurrentArmy();
838            }
839            else
840            {
841                //it must be one of our extra buttons for the categories
842                addUnitFromCategory((Category)e.Button.Tag);
843            }
844        }
845
846        private GameSystem CurrentGameSystem
847        {
848            get { return WarFoundryCore.CurrentGameSystem; }
849            set { WarFoundryCore.CurrentGameSystem = value; }
850        }
851
852        private static Army CurrentArmy
853        {
854            get { return WarFoundryCore.CurrentArmy; }
855            set { WarFoundryCore.CurrentArmy = value; }
856        }
857
858        private void SelectGameSystem()
859        {
860            FrmSelectSystem selectSystem = new FrmSelectSystem();
861            DialogResult dr = selectSystem.ShowDialog(this);
862
863            if (dr==DialogResult.OK)
864            {
865                closeCurrentArmy();
866                CurrentGameSystem = selectSystem.GameSystem;
867            }
868        }
869
870        private void miChangeSystem_Click(object sender, System.EventArgs e)
871        {
872            SelectGameSystem();
873        }
874
875        private void FrmMain_GameSystemChanged(GameSystem oldSystem, GameSystem newSystem)
876        {
877            miNewArmy.Enabled = newSystem != null;
878            bttnNewArmy.Enabled = newSystem != null;
879            setAppTitle();
880            removeCategoryButtons();
881            addCategoryButtons();
882        }
883
884        private void FrmMain_ArmyChanged(Army oldArmy, Army newArmy)
885        {       
886            setAppTitle();
887
888            if (oldArmy != null)
889            {
890                oldArmy.UnitAdded += UnitAddedMethod;
891                oldArmy.UnitRemoved += UnitRemovedMethod;
892                oldArmy.PointsValueChanged += PointsValueChangedMethod;
893            }
894
895            if (CurrentArmy==null)
896            {
897                miSaveArmyAs.Enabled = false;
898                miCloseArmy.Enabled = false;
899                disableCategoryButtons();
900            }
901            else
902            {
903                newArmy.UnitAdded += UnitAddedMethod;
904                newArmy.UnitRemoved += UnitRemovedMethod;
905                newArmy.PointsValueChanged += PointsValueChangedMethod;
906                //TODO: Clear all buttons
907                miSaveArmyAs.Enabled = true;
908                miCloseArmy.Enabled = true;
909                enableCategoryButtons();
910
911                if (newArmy.Race.HasCategoryOverrides())
912                {
913                    removeCategoryButtons();
914                    addCategoryButtons(newArmy.Race.Categories);
915                }
916            }
917
918            CommandStack.Reset();
919
920            miSaveArmy.Enabled = false;
921            bttnSaveArmy.Enabled = false;
922
923            setPointsPanelText();
924        }
925
926        private void addCategoryButtons()
927        {
928            if (CurrentGameSystem!=null)
929            {
930                addCategoryButtons(CurrentGameSystem.Categories);
931            }
932        }
933
934        private void addCategoryButtons(Category[] cats)
935        {
936            int catCount = cats.Length;
937            Category cat;
938            categoryButtons = new ToolBarButton[catCount+1];
939
940            ToolBarButton sep = new ToolBarButton();
941            sep.Style = ToolBarButtonStyle.Separator;
942            categoryButtons[0] = sep;
943
944            IBBToolBarButton button;
945
946            for (int i = 0; i<catCount; i++)
947            {
948                cat = cats[i];
949                button = new IBBToolBarButton();
950                ///button.Name = "bttnAddCategory" + cat.Name[0].ToString();
951                button.Text = cat.Name.ToString();//String.Format(Translation.GetTranslation("bttnAddCategory"), cat.Name);
952                button.Tag = cat;
953                button.ImageIndex = 6;
954                button.Enabled = false;
955                categoryButtons[i+1] = button;
956            }
957
958            this.Invoke(new ToolBarButtonRangeDelegate(toolBar.Buttons.AddRange), new object[]{categoryButtons});
959        }
960
961        private void removeCategoryButtons()
962        {
963            if (categoryButtons!=null)
964            {
965                for (int i = 0; i<categoryButtons.Length; i++)
966                {
967                    this.Invoke(new ToolBarButtonDelegate(toolBar.Buttons.Remove), new object[]{categoryButtons[i]});
968                }
969            }
970        }
971
972        private void enableCategoryButtons()
973        {
974            setCategoryButtonState(true);
975        }
976
977        private void disableCategoryButtons()
978        {
979            setCategoryButtonState(false);
980        }
981
982        private void setCategoryButtonState(bool state)
983        {
984            if (categoryButtons!=null)
985            {
986                for (int i = 0; i<categoryButtons.Length; i++)
987                {
988                    categoryButtons[i].Enabled = state;
989                }
990            }
991        }
992
993        private void miSaveArmyAs_Click(object sender, System.EventArgs e)
994        {
995            SaveCurrentArmyAs();
996        }
997
998        private void commandStack_CommandStackUpdated()
999        {
1000            bttnUndo.Enabled = commandStack.CanUndo();
1001            miUndo.Enabled = bttnUndo.Enabled;
1002            bttnRedo.Enabled = commandStack.CanRedo();
1003            miRedo.Enabled = bttnRedo.Enabled;
1004            MenuItem[] menuItems = null;
1005            int redoLength = commandStack.RedoLength;
1006            int maxRedo = Math.Min(10, redoLength);
1007           
1008            if (redoLength > 0)
1009            {
1010                menuItems = new MenuItem[maxRedo];
1011                Command com;
1012                MenuItem mi;
1013
1014                for (int i = 0; i < maxRedo; i++)
1015                {
1016                    com = commandStack.PeekRedoCommand(i+1);
1017
1018                    if (com == null)
1019                    {
1020                        break;
1021                    }
1022
1023                    mi = new MenuItem(com.Description);
1024                    mi.Click+=new EventHandler(redoMenu_Click);
1025                    menuItems[i] = mi;
1026                }
1027            }
1028
1029            redoMenu.MenuItems.Clear();
1030
1031            if (menuItems!=null && menuItems[0]!=null)
1032            {
1033                bttnRedo.ToolTipText = menuItems[0].Text;
1034                redoMenu.MenuItems.AddRange(menuItems);
1035            }
1036
1037            int undoLength = commandStack.UndoLength;
1038            int maxUndo = Math.Min(10, undoLength);
1039            MenuItem[] menuItemsUndo = null;
1040           
1041            if (undoLength > 0)
1042            {
1043                menuItemsUndo = new MenuItem[maxUndo];
1044                Command com;
1045                MenuItem mi;
1046
1047                for (int i = 0; i < maxUndo; i++)
1048                {
1049                    com = commandStack.PeekUndoCommand(i+1);
1050
1051                    if (com == null)
1052                    {
1053                        break;
1054                    }
1055
1056                    mi = new MenuItem(com.UndoDescription);
1057                    mi.Click+=new EventHandler(undoMenu_Click);
1058                    menuItemsUndo[i] = mi;
1059                }
1060            }
1061
1062            undoMenu.MenuItems.Clear();
1063
1064            if (menuItemsUndo!=null && menuItemsUndo[0]!=null)
1065            {
1066                bttnUndo.ToolTipText = menuItemsUndo[0].Text;
1067                undoMenu.MenuItems.AddRange(menuItemsUndo);
1068            }
1069
1070            bool canSave = loadedFilePath != null;
1071            bttnSaveArmy.Enabled = commandStack.IsDirty() && CurrentArmy!=null && canSave;
1072            miSaveArmy.Enabled = commandStack.IsDirty() && CurrentArmy!=null && canSave;
1073        }
1074
1075        private void miSaveArmy_Click(object sender, System.EventArgs e)
1076        {
1077            SaveCurrentArmy();
1078        }
1079
1080        private void setAppTitle()
1081        {
1082            string str = AppTitle;
1083
1084            if (CurrentGameSystem!=null)
1085            {
1086                str+= " - "+CurrentGameSystem.Name;
1087            }
1088
1089            if (CurrentArmy!=null)
1090            {
1091                str+= " - "+CurrentArmy.Name;
1092            }
1093
1094            this.Text = str;
1095        }
1096
1097        private void addUnitFromCategory(Category cat)
1098        {
1099            FrmNewUnit newUnit = new FrmNewUnit(CurrentArmy.Race, cat, CurrentArmy);
1100            DialogResult dr = newUnit.ShowDialog(this);
1101
1102            if (dr == DialogResult.OK)
1103            {
1104                CreateAndAddUnitCommand cmd = new CreateAndAddUnitCommand(newUnit.SelectedUnit, CurrentArmy.GetCategory(cat));
1105                commandStack.Execute(cmd);
1106            }
1107        }
1108
1109        private void FrmMain_UnitAddedMethod(object unitObj)
1110        {
1111            if (unitObj is Unit)
1112            {
1113                Unit unit = (Unit)unitObj;
1114                sbErrorPanel.Text = "";
1115            }
1116        }
1117
1118        private void FrmMain_UnitRemovedMethod(object unitObj)
1119        {
1120            if (unitObj is Unit)
1121            {
1122                Unit unit = (Unit)unitObj;
1123                sbErrorPanel.Text = "";
1124
1125                //check if window is open, and close it if it is
1126                foreach (Form frm in this.MdiChildren)
1127                {
1128                    if (frm is FrmUnit)
1129                    {
1130                        if (((FrmUnit)frm).Unit == unit)
1131                        {
1132                            frm.Close();
1133                            break;
1134                        }
1135                    }
1136                }
1137            }
1138        }
1139
1140        /*private void FrmMain_FailedUnitRequirement(FailedUnitRequirement failedRequirement)
1141        {
1142            sbErrorPanel.Text = Translation.GetTranslation("UnitRequirementFailed", "Unit Requirement Failed");
1143            sbErrorPanel.Tag = failedRequirement.Description;
1144        }*/
1145
1146        /*public void MdiChildMoved()
1147        {
1148            Point mouseAt = PointToClient(ActiveMdiChild.Location);
1149
1150            if (Comparisons.ValueWithinAmount(pnlRight.Right, ActiveMdiChild.Right, 10))
1151            {
1152                pnlRight.Visible = true;
1153                //pnlRight.Container.Add(ActiveMdiChild);
1154            }
1155            else
1156            {
1157                pnlRight.Visible = false;
1158            }
1159        }*/
1160
1161        public void pnlRight_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
1162        {
1163            HatchBrush dockCueBrush = new HatchBrush(HatchStyle.LightDownwardDiagonal, Color.White, Color.Gray);
1164            Pen dockCuePen = new Pen(dockCueBrush, 10);
1165            e.Graphics.DrawRectangle(dockCuePen, new Rectangle(pnlRight.Left, pnlRight.Top, pnlRight.Width, pnlRight.Height));
1166        }
1167
1168        private void miUndo_Click(object sender, System.EventArgs e)
1169        {
1170            undoLastAction();
1171        }
1172
1173        private void miRedo_Click(object sender, System.EventArgs e)
1174        {
1175            redoAction();
1176        }
1177
1178        private void miCloseArmy_Click(object sender, EventArgs e)
1179        {
1180            closeCurrentArmy();
1181        }
1182
1183        private void miOpenArmy_Click(object sender, EventArgs e)
1184        {
1185            openArmy();
1186        }
1187
1188        private void FrmMain_PointsValueChangedMethod(WarFoundryObject obj, double oldVal, double newVal)
1189        {
1190            if (obj is Army)
1191            {
1192                setPointsPanelText();
1193            }
1194        }
1195
1196        private void setPointsPanelText()
1197        {   
1198            if (CurrentArmy==null)
1199            {
1200                sbPointsPanel.Text = "";
1201                sbPointsPanel.ResetColor();
1202            }
1203            else
1204            {
1205                sbPointsPanel.Text = String.Format(Translation.GetTranslation("statusPanelPoints"), CurrentArmy.PointsTotal, CurrentArmy.MaxPoints);
1206
1207                if (CurrentArmy.PointsTotal>CurrentArmy.MaxPoints)
1208                {
1209                    sbPointsPanel.Color = Color.Red;
1210                }
1211                else
1212                {
1213                    sbPointsPanel.ResetColor();
1214                }
1215            }
1216        }
1217
1218        private void redoMenu_Click(object sender, EventArgs e)
1219        {
1220            if (sender is MenuItem)
1221            {
1222                MenuItem mi = (MenuItem)sender;
1223
1224                if (mi.Parent == redoMenu)
1225                {
1226                    //we know it's an redo menu item so find it's index and redo everything                 
1227                    int max = mi.Index;
1228
1229                    for (int i = 0; i <= max; i++)
1230                    {
1231                        commandStack.Redo();
1232                    }
1233                }
1234            }
1235        }
1236
1237        private void undoMenu_Click(object sender, EventArgs e)
1238        {
1239            if (sender is MenuItem)
1240            {
1241                MenuItem mi = (MenuItem)sender;
1242
1243                if (mi.Parent == undoMenu)
1244                {
1245                    //we know it's an undo menu item so find it's index and undo everything
1246                    int max = mi.Index;
1247                    for (int i = 0; i <= max; i++)
1248                    {
1249                        commandStack.Undo();
1250                    }
1251                }
1252            }
1253        }
1254
1255        private void statusBar_DrawItem(object sender, System.Windows.Forms.StatusBarDrawItemEventArgs sbdevent)
1256        {
1257            statusBar.ColorableStatusBarDrawItem(sender, sbdevent);
1258        }
1259
1260        private void miDebugWindow_Click(object sender, EventArgs e)
1261        {
1262            if (debugWindow == null || debugWindow.IsDisposed)
1263            {
1264                debugWindow = new FrmDebugOutput();
1265            }
1266
1267            debugWindow.Show();
1268            debugWindow.Focus();
1269        }
1270
1271        private void FrmMain_Closing(object sender, CancelEventArgs e)
1272        {
1273            if (!closeCurrentArmy())
1274            {
1275                e.Cancel = true;
1276            }
1277        }
1278
1279        private void miReloadFiles_Click(object sender, System.EventArgs e)
1280        {
1281            WarFoundryLoader.GetDefault().LoadFiles();
1282            sbMainPanel.Text = Translation.GetTranslation("GameSystemFilesReloaded", "Game system and race files reloaded");
1283            statusBarTimer.Enabled = true;
1284        }
1285
1286        private void statusBarTimer_Tick(object sender, System.EventArgs e)
1287        {
1288            sbMainPanel.Text = "";
1289            statusBarTimer.Enabled = false;
1290        }
1291
1292        private void statusBar_PanelClick(object sender, StatusBarPanelClickEventArgs e)
1293        {
1294            if (e.StatusBarPanel == sbErrorPanel && sbErrorPanel.Text!="")
1295            {
1296                MessageBox.Show(this, sbErrorPanel.TagString, Translation.GetTranslation("FailedRequirementMessage"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
1297            }
1298        }
1299    }
1300}
Note: See TracBrowser for help on using the browser.