#region License // Copyright 2005-2019 Paul Kohler (https://github.com/paulkohler/minisqlquery). All rights reserved. // This source code is made available under the terms of the GNU Lesser General Public License v3.0 // https://github.com/paulkohler/minisqlquery/blob/master/LICENSE #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using MiniSqlQuery.Core; using MiniSqlQuery.Core.Commands; using MiniSqlQuery.Properties; using WeifenLuo.WinFormsUI.Docking; namespace MiniSqlQuery { /// The main form. public partial class MainForm : Form, IHostWindow { /// The _services. private readonly IApplicationServices _services; /// The _settings. private readonly IApplicationSettings _settings; /// The _arguements. private string[] _arguements; /// The _db inspector. private IDatabaseInspector _dbInspector; /// The _initialized. private bool _initialized; /// Initializes a new instance of the class. public MainForm() { InitializeComponent(); SetPointerState(Cursors.AppStarting); } /// Initializes a new instance of the class. /// The services. /// The settings. public MainForm(IApplicationServices services, IApplicationSettings settings) : this() { _services = services; _settings = settings; AllowDrop = true; DragEnter += WindowDragEnter; DragDrop += WindowDragDrop; } /// Gets or sets ActiveChildForm. public Form ActiveChildForm { get; internal set; } /// Gets DatabaseInspector. public IDatabaseInspector DatabaseInspector { get { if (_dbInspector == null || ((Form)_dbInspector).IsDisposed) { return null; } return _dbInspector; } } /// Gets Instance. public Form Instance { get { return this; } } /// Gets ToolStrip. [DebuggerNonUserCode] public ToolStrip ToolStrip { get { return toolStripConnection; } } /// The add plugin command. /// public void AddPluginCommand() where TCommand : ICommand, new() { pluginsMenu.DropDownItems.Add(CommandControlBuilder.CreateToolStripMenuItem()); } /// The add tool strip command. /// The index. /// public void AddToolStripCommand(int? index) where TCommand : ICommand, new() { ToolStripButton item = CommandControlBuilder.CreateToolStripButton(); if (index == null) { toolStripConnection.Items.Add(item); } else { toolStripConnection.Items.Insert(index.Value, item); } } /// The add tool strip seperator. /// The index. public void AddToolStripSeperator(int? index) { ToolStripSeparator item = CommandControlBuilder.CreateToolStripMenuItemSeparator(); if (index == null) { toolStripConnection.Items.Add(item); } else { toolStripConnection.Items.Insert(index.Value, item); } } /// The display docked form. /// The frm. public void DisplayDockedForm(DockContent frm) { if (frm != null) { frm.Show(dockPanel, DockState.Document); } } /// The display message box. /// The source. /// The text. /// The caption. /// The buttons. /// The icon. /// The default button. /// The options. /// The help file path. /// The keyword. /// public DialogResult DisplayMessageBox( Form source, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) { if (helpFilePath == null && keyword == null) { return MessageBox.Show(source, text, caption, buttons, icon, defaultButton, options); } return MessageBox.Show(source, text, caption, buttons, icon, defaultButton, options, helpFilePath, keyword); } /// The display simple message box. /// The source. /// The text. /// The caption. /// public DialogResult DisplaySimpleMessageBox(Form source, string text, string caption) { return MessageBox.Show(source, text, caption); } /// The get menu item. /// The name. /// public ToolStripMenuItem GetMenuItem(string name) { ToolStripMenuItem menuItem = null; foreach (ToolStripMenuItem item in MainMenuStrip.Items) { if (item.Text.Replace("&", string.Empty).ToLower() == name.ToLower()) { menuItem = item; break; } } return menuItem; } /// The set arguments. /// The args. public void SetArguments(string[] args) { _arguements = args; } /// The set pointer state. /// The cursor. public void SetPointerState(Cursor cursor) { Cursor = cursor; Application.DoEvents(); } /// The set status. /// The source. /// The text. public void SetStatus(Form source, string text) { if (source == null || ActiveMdiChild == source) { if (text != null) { text = text.Replace("\r", string.Empty).Replace("\n", " "); } toolStripStatusLabel.Text = text; } } public void SetResultCount(Form source, int? count) { if (source == null || ActiveMdiChild == source) { string result = string.Empty; if (count != null) { if (count.Value == 1) { result = "1 row"; } else { result = count.Value + " rows"; } } toolStripStatusLabelResultCount.Text = result; } } /// The show database inspector. /// The database inspector. /// The dock state. /// public void ShowDatabaseInspector(IDatabaseInspector databaseInspector, DockState dockState) { if (_dbInspector != null && _dbInspector != databaseInspector) { _dbInspector.Close(); } _dbInspector = databaseInspector; DockContent frm = _dbInspector as DockContent; if (frm == null) { throw new InvalidOperationException( "The 'databaseInspector' must be a 'WeifenLuo.WinFormsUI.Docking.DockContent' based form."); } frm.Show(dockPanel, dockState); } /// The show tool window. /// The form. /// The dock state. public void ShowToolWindow(DockContent form, DockState dockState) { form.Show(dockPanel, dockState); } /// The app settings connection definitions changed. /// The sender. /// The e. private void AppSettingsConnectionDefinitionsChanged(object sender, EventArgs e) { LoadUpConnections(); } /// The load up connections. private void LoadUpConnections() { DbConnectionDefinitionList definitionList = _settings.GetConnectionDefinitions(); if (_initialized) // if initialized, just sync the lists { // add missing foreach (var connDef in definitionList.Definitions) { if (!toolStripComboBoxConnection.Items.Contains(connDef)) { toolStripComboBoxConnection.Items.Add(connDef); } } // remove if missing var defList = new List(definitionList.Definitions); for (int i = toolStripComboBoxConnection.Items.Count - 1; i >= 0; i--) { var connDef = (DbConnectionDefinition)toolStripComboBoxConnection.Items[i]; if (!defList.Contains(connDef)) { toolStripComboBoxConnection.Items.RemoveAt(i); } } } else { // first populate toolStripComboBoxConnection.Items.Clear(); foreach (var connDef in definitionList.Definitions) { toolStripComboBoxConnection.Items.Add(connDef); } } // Bug fix - don't automatically refresh as it can try to reconnect to a connection you don't have etc. //foreach (var connDef in definitionList.Definitions) //{ // if (connDef.Name == Settings.Default.NammedConnection) // { // toolStripComboBoxConnection.SelectedItem = connDef; // _settings.ConnectionDefinition = connDef; // SetWindowTitle(connDef.Name); // } //} } /// The main form_ form closing. /// The sender. /// The e. private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.Cancel) { return; } if (_settings.ConnectionDefinition != null) { Settings.Default.NammedConnection = _settings.ConnectionDefinition.Name; Settings.Default.Save(); } List plugins = new List(_services.Plugins.Values); plugins.Reverse(); foreach (IPlugIn plugin in plugins) { plugin.UnloadPlugIn(); } _services.Container.Dispose(); } /// The main form_ load. /// The sender. /// The e. private void MainForm_Load(object sender, EventArgs e) { _settings.ConnectionDefinitionsChanged += AppSettingsConnectionDefinitionsChanged; toolStripStatusLabelResultCount.Text = string.Empty; Utility.CreateConnectionStringsIfRequired(); _settings.SetConnectionDefinitions(Utility.LoadDbConnectionDefinitions()); } /// The main form_ mdi child activate. /// The sender. /// The e. private void MainForm_MdiChildActivate(object sender, EventArgs e) { ActiveChildForm = ActiveMdiChild; } /// The main form_ shown. /// The sender. /// The e. private void MainForm_Shown(object sender, EventArgs e) { _services.InitializePlugIns(); DockContent dbInspectorForm = _dbInspector as DockContent; if (dbInspectorForm != null) { // the activate for "DockContent" is different to that of "Form". dbInspectorForm.Activate(); } _initialized = true; SetPointerState(Cursors.Default); SetStatus(null, string.Empty); // now check for command line args that are "command type names" if (_arguements != null && _arguements.Length > 0) { foreach (string arg in _arguements) { if (arg.StartsWith("/cmd:")) { string cmdName = arg.Substring(5); ICommand cmd = CommandManager.GetCommandInstanceByPartialName(cmdName); if (cmd != null) { cmd.Execute(); } } } } else { CommandManager.GetCommandInstance().Execute(); } } /// The set window title. /// The connection name. private void SetWindowTitle(string connectionName) { Text = string.Format("Mini SQL Query [{0}]", connectionName); } /// The window drag drop. /// The sender. /// The e. private void WindowDragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); IFileEditorResolver resolver = _services.Resolve(); foreach (string filename in filePaths) { // todo: check for file exist file in open windows; IEditor editor = resolver.ResolveEditorInstance(filename); editor.FileName = filename; editor.LoadFile(); DisplayDockedForm(editor as DockContent); } } } /// The window drag enter. /// The sender. /// The e. private void WindowDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } /// The exit tool strip menu item_ click. /// The sender. /// The e. private void exitToolStripMenuItem_Click(object sender, EventArgs e) { CommandManager.GetCommandInstance().Execute(); } /// The hide show tool strip menu item_ click. /// The sender. /// The e. private void hideShowToolStripMenuItem_Click(object sender, EventArgs e) { if (WindowState == FormWindowState.Normal) { Hide(); WindowState = FormWindowState.Minimized; } else { Show(); WindowState = FormWindowState.Normal; } } /// The sys icon_ double click. /// The sender. /// The e. private void sysIcon_DoubleClick(object sender, EventArgs e) { if (WindowState == FormWindowState.Normal) { Hide(); WindowState = FormWindowState.Minimized; } else { Show(); WindowState = FormWindowState.Normal; } } /// The tool strip combo box connection_ selected index changed. /// The sender. /// The e. private void toolStripComboBoxConnection_SelectedIndexChanged(object sender, EventArgs e) { if (_initialized) { DbConnectionDefinition dbConnectionDefinition = (DbConnectionDefinition)toolStripComboBoxConnection.SelectedItem; _settings.ConnectionDefinition = dbConnectionDefinition; SetWindowTitle(dbConnectionDefinition.Name); } } private void dockPanel_ActiveContentChanged(object sender, EventArgs e) { } } }