// Copyright (C) 2003, 2004 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2005, 2007, 2008, 2010 panacoran <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: MainForm.cs 461 2013-06-16 12:55:25Z panacoran $

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using Protra.Lib;
using Protra.Lib.Config;
using Protra.Lib.Data;
using Protra.Lib.Dialogs;
using Protra.Lib.Lang;
using Protra.Lib.Lang.Builtins;
using PtSim.Dialogs;

namespace PtSim
{
    /// <summary>
    /// アプリケーションのメインフォームです。
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.MainMenu mainMenu;
        private System.Windows.Forms.MenuItem menuItemLog;
        private System.Windows.Forms.MenuItem menuItemLogDelete;
        private System.Windows.Forms.MenuItem menuItemLogAllDelete;
        private System.Windows.Forms.MenuItem menuItemBrandList;
        private System.Windows.Forms.MenuItem menuItemBrandListEdit;
        private System.Windows.Forms.MenuItem menuItemHelp;
        private System.Windows.Forms.MenuItem menuItemMan;
        private System.Windows.Forms.MenuItem menuItemVersion;
        private System.Windows.Forms.Panel panelLeft;
        private System.Windows.Forms.Panel panelSelect;
        private System.Windows.Forms.Label labelMode;
        private System.Windows.Forms.Label labelBrandList;
        private System.Windows.Forms.RadioButton radioButtonDaily;
        private System.Windows.Forms.RadioButton radioButtonWeekly;
        private System.Windows.Forms.ComboBox comboBoxBrandList;
        private System.Windows.Forms.Splitter splitterLeft;
        private System.Windows.Forms.TabControl tabControl;
        private System.Windows.Forms.TabPage tabPageExecute;
        private System.Windows.Forms.TabPage tabPagePerformance;
        private System.Windows.Forms.TabPage tabPageHistory;
        private System.Windows.Forms.ImageList imageListTab;
        private PtSim.Controls.PtFileTreeView ptFileTreeView;
        private System.Windows.Forms.Button buttonExecute;
        private System.Windows.Forms.ProgressBar progressBarExecute;
        private System.Windows.Forms.TabControl tabControlPerformance;
        private System.Windows.Forms.TabPage tabPagePerformanceSummery;
        private System.Windows.Forms.TabPage tabPagePerformanceProfitGraph;
        private System.Windows.Forms.RichTextBox richTextBoxPerformanceSummery;
        private PtSim.Controls.ProfitGraphBox profitGraphBox;
        private System.Windows.Forms.Button buttonPerformance;
        private System.Windows.Forms.ProgressBar progressBarPerformance;
        private PtSim.Controls.ListViewEx listViewHistory;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryDate;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryCode;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryName;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryPrice;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryNumber;
        private System.Windows.Forms.ColumnHeader columnHeaderHistoryOrder;
        private System.Windows.Forms.Label labelDateRange;
        private System.Windows.Forms.Button buttonHistory;
        private System.Windows.Forms.DateTimePicker dateTimePickerHistoryDateMax;
        private System.Windows.Forms.DateTimePicker dateTimePickerHistoryDateMin;
        private System.Windows.Forms.ContextMenu historyContextMenu;
        private System.Windows.Forms.MenuItem copyHistory;
        private BackgroundWorker backgroundWorkerPerformance;
        private BackgroundWorker backgroundWorkerExecute;
        private TextBox textBoxExecute;
        private System.ComponentModel.IContainer components;
        private CheckBox checkBoxEmpty;

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainForm()
        {
            //
            // Windows フォーム デザイナ サポートに必要です。
            //
            InitializeComponent();

            (GlobalEnv.PtSimConfig = new PtSimConfig()).Load();
            (GlobalEnv.UpdateConfig = new UpdateConfig()).Load();
            (GlobalEnv.BrandData = new BrandData()).Load();
            (GlobalEnv.BrandListConfig = new BrandListConfig()).Load();

            BrandListInit();
            foreach (var bl in GlobalEnv.BrandListConfig.List)
                if (GlobalEnv.PtSimConfig.BrandListName == bl.Name)
                {
                    comboBoxBrandList.SelectedItem = bl;
                    break;
                }
            if (GlobalEnv.PtSimConfig.Mode == 1)
                radioButtonWeekly.PerformClick();

            dateTimePickerHistoryDateMin.Value = DateTime.Now.AddMonths(-1); //履歴の開始を1ヶ月前に設定する。
            ptFileTreeView.RootDirectory = Global.DirSystem; // システム一覧を更新する。

            GlobalEnv.BrandListConfig.BrandListInit = BrandListInit;
        }

        /// <summary>
        /// 使用されているリソースに後処理を実行します。
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// デザイナ サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディタで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
            this.menuItemLog = new System.Windows.Forms.MenuItem();
            this.menuItemLogDelete = new System.Windows.Forms.MenuItem();
            this.menuItemLogAllDelete = new System.Windows.Forms.MenuItem();
            this.menuItemBrandList = new System.Windows.Forms.MenuItem();
            this.menuItemBrandListEdit = new System.Windows.Forms.MenuItem();
            this.menuItemHelp = new System.Windows.Forms.MenuItem();
            this.menuItemMan = new System.Windows.Forms.MenuItem();
            this.menuItemVersion = new System.Windows.Forms.MenuItem();
            this.panelLeft = new System.Windows.Forms.Panel();
            this.ptFileTreeView = new PtSim.Controls.PtFileTreeView();
            this.panelSelect = new System.Windows.Forms.Panel();
            this.checkBoxEmpty = new System.Windows.Forms.CheckBox();
            this.labelMode = new System.Windows.Forms.Label();
            this.labelBrandList = new System.Windows.Forms.Label();
            this.comboBoxBrandList = new System.Windows.Forms.ComboBox();
            this.radioButtonDaily = new System.Windows.Forms.RadioButton();
            this.radioButtonWeekly = new System.Windows.Forms.RadioButton();
            this.splitterLeft = new System.Windows.Forms.Splitter();
            this.tabControl = new System.Windows.Forms.TabControl();
            this.tabPageExecute = new System.Windows.Forms.TabPage();
            this.textBoxExecute = new System.Windows.Forms.TextBox();
            this.progressBarExecute = new System.Windows.Forms.ProgressBar();
            this.buttonExecute = new System.Windows.Forms.Button();
            this.tabPagePerformance = new System.Windows.Forms.TabPage();
            this.progressBarPerformance = new System.Windows.Forms.ProgressBar();
            this.buttonPerformance = new System.Windows.Forms.Button();
            this.tabControlPerformance = new System.Windows.Forms.TabControl();
            this.tabPagePerformanceSummery = new System.Windows.Forms.TabPage();
            this.richTextBoxPerformanceSummery = new System.Windows.Forms.RichTextBox();
            this.tabPagePerformanceProfitGraph = new System.Windows.Forms.TabPage();
            this.profitGraphBox = new PtSim.Controls.ProfitGraphBox();
            this.tabPageHistory = new System.Windows.Forms.TabPage();
            this.buttonHistory = new System.Windows.Forms.Button();
            this.labelDateRange = new System.Windows.Forms.Label();
            this.dateTimePickerHistoryDateMax = new System.Windows.Forms.DateTimePicker();
            this.dateTimePickerHistoryDateMin = new System.Windows.Forms.DateTimePicker();
            this.listViewHistory = new PtSim.Controls.ListViewEx();
            this.columnHeaderHistoryDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeaderHistoryCode = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeaderHistoryName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeaderHistoryPrice = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeaderHistoryNumber = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeaderHistoryOrder = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.historyContextMenu = new System.Windows.Forms.ContextMenu();
            this.copyHistory = new System.Windows.Forms.MenuItem();
            this.imageListTab = new System.Windows.Forms.ImageList(this.components);
            this.backgroundWorkerPerformance = new System.ComponentModel.BackgroundWorker();
            this.backgroundWorkerExecute = new System.ComponentModel.BackgroundWorker();
            this.panelLeft.SuspendLayout();
            this.panelSelect.SuspendLayout();
            this.tabControl.SuspendLayout();
            this.tabPageExecute.SuspendLayout();
            this.tabPagePerformance.SuspendLayout();
            this.tabControlPerformance.SuspendLayout();
            this.tabPagePerformanceSummery.SuspendLayout();
            this.tabPagePerformanceProfitGraph.SuspendLayout();
            this.tabPageHistory.SuspendLayout();
            this.SuspendLayout();
            // 
            // mainMenu
            // 
            this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemLog,
            this.menuItemBrandList,
            this.menuItemHelp});
            // 
            // menuItemLog
            // 
            this.menuItemLog.Index = 0;
            this.menuItemLog.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemLogDelete,
            this.menuItemLogAllDelete});
            this.menuItemLog.Text = "システムログ(&L)";
            // 
            // menuItemLogDelete
            // 
            this.menuItemLogDelete.Index = 0;
            this.menuItemLogDelete.Shortcut = System.Windows.Forms.Shortcut.Del;
            this.menuItemLogDelete.Text = "削除(&D)";
            this.menuItemLogDelete.Click += new System.EventHandler(this.menuItemLogDelete_Click);
            // 
            // menuItemLogAllDelete
            // 
            this.menuItemLogAllDelete.Index = 1;
            this.menuItemLogAllDelete.Text = "全システムログを削除(&A)";
            this.menuItemLogAllDelete.Click += new System.EventHandler(this.menuItemLogAllDelete_Click);
            // 
            // menuItemBrandList
            // 
            this.menuItemBrandList.Index = 1;
            this.menuItemBrandList.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemBrandListEdit});
            this.menuItemBrandList.Text = "銘柄リスト(&L)";
            // 
            // menuItemBrandListEdit
            // 
            this.menuItemBrandListEdit.Index = 0;
            this.menuItemBrandListEdit.Text = "編集(&E)";
            this.menuItemBrandListEdit.Click += new System.EventHandler(this.menuItemBrandListEdit_Click);
            // 
            // menuItemHelp
            // 
            this.menuItemHelp.Index = 2;
            this.menuItemHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemMan,
            this.menuItemVersion});
            this.menuItemHelp.Text = "ヘルプ(&H)";
            // 
            // menuItemMan
            // 
            this.menuItemMan.Index = 0;
            this.menuItemMan.Shortcut = System.Windows.Forms.Shortcut.F1;
            this.menuItemMan.Text = "マニュアル(&M)";
            this.menuItemMan.Click += new System.EventHandler(this.menuItemMan_Click);
            // 
            // menuItemVersion
            // 
            this.menuItemVersion.Index = 1;
            this.menuItemVersion.Text = "バージョン情報(&V)";
            this.menuItemVersion.Click += new System.EventHandler(this.menuItemVersion_Click);
            // 
            // panelLeft
            // 
            this.panelLeft.Controls.Add(this.ptFileTreeView);
            this.panelLeft.Controls.Add(this.panelSelect);
            this.panelLeft.Dock = System.Windows.Forms.DockStyle.Left;
            this.panelLeft.Location = new System.Drawing.Point(0, 0);
            this.panelLeft.Name = "panelLeft";
            this.panelLeft.Size = new System.Drawing.Size(208, 403);
            this.panelLeft.TabIndex = 0;
            // 
            // ptFileTreeView
            // 
            this.ptFileTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
            this.ptFileTreeView.HideSelection = false;
            this.ptFileTreeView.ImageIndex = 0;
            this.ptFileTreeView.Location = new System.Drawing.Point(0, 0);
            this.ptFileTreeView.Name = "ptFileTreeView";
            this.ptFileTreeView.RootDirectory = null;
            this.ptFileTreeView.SelectedImageIndex = 0;
            this.ptFileTreeView.Size = new System.Drawing.Size(208, 281);
            this.ptFileTreeView.TabIndex = 0;
            this.ptFileTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.ptFileTreeView_AfterSelect);
            // 
            // panelSelect
            // 
            this.panelSelect.Controls.Add(this.checkBoxEmpty);
            this.panelSelect.Controls.Add(this.labelMode);
            this.panelSelect.Controls.Add(this.labelBrandList);
            this.panelSelect.Controls.Add(this.comboBoxBrandList);
            this.panelSelect.Controls.Add(this.radioButtonDaily);
            this.panelSelect.Controls.Add(this.radioButtonWeekly);
            this.panelSelect.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panelSelect.Location = new System.Drawing.Point(0, 281);
            this.panelSelect.Name = "panelSelect";
            this.panelSelect.Size = new System.Drawing.Size(208, 122);
            this.panelSelect.TabIndex = 1;
            // 
            // checkBoxEmpty
            // 
            this.checkBoxEmpty.AutoSize = true;
            this.checkBoxEmpty.Location = new System.Drawing.Point(14, 84);
            this.checkBoxEmpty.Name = "checkBoxEmpty";
            this.checkBoxEmpty.Size = new System.Drawing.Size(149, 16);
            this.checkBoxEmpty.TabIndex = 4;
            this.checkBoxEmpty.Text = "実行対象を空データにする";
            this.checkBoxEmpty.UseVisualStyleBackColor = true;
            // 
            // labelMode
            // 
            this.labelMode.Location = new System.Drawing.Point(12, 24);
            this.labelMode.Name = "labelMode";
            this.labelMode.Size = new System.Drawing.Size(60, 16);
            this.labelMode.TabIndex = 3;
            this.labelMode.Text = "期間モード";
            // 
            // labelBrandList
            // 
            this.labelBrandList.Location = new System.Drawing.Point(12, 56);
            this.labelBrandList.Name = "labelBrandList";
            this.labelBrandList.Size = new System.Drawing.Size(60, 16);
            this.labelBrandList.TabIndex = 2;
            this.labelBrandList.Text = "銘柄リスト";
            // 
            // comboBoxBrandList
            // 
            this.comboBoxBrandList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxBrandList.Location = new System.Drawing.Point(72, 52);
            this.comboBoxBrandList.Name = "comboBoxBrandList";
            this.comboBoxBrandList.Size = new System.Drawing.Size(104, 20);
            this.comboBoxBrandList.TabIndex = 1;
            this.comboBoxBrandList.SelectedIndexChanged += new System.EventHandler(this.comboBoxBrandList_SelectedIndexChanged);
            // 
            // radioButtonDaily
            // 
            this.radioButtonDaily.Checked = true;
            this.radioButtonDaily.Location = new System.Drawing.Point(72, 20);
            this.radioButtonDaily.Name = "radioButtonDaily";
            this.radioButtonDaily.Size = new System.Drawing.Size(52, 20);
            this.radioButtonDaily.TabIndex = 0;
            this.radioButtonDaily.TabStop = true;
            this.radioButtonDaily.Text = "日足";
            // 
            // radioButtonWeekly
            // 
            this.radioButtonWeekly.Location = new System.Drawing.Point(124, 20);
            this.radioButtonWeekly.Name = "radioButtonWeekly";
            this.radioButtonWeekly.Size = new System.Drawing.Size(52, 20);
            this.radioButtonWeekly.TabIndex = 1;
            this.radioButtonWeekly.Text = "週足";
            // 
            // splitterLeft
            // 
            this.splitterLeft.Enabled = false;
            this.splitterLeft.Location = new System.Drawing.Point(208, 0);
            this.splitterLeft.Name = "splitterLeft";
            this.splitterLeft.Size = new System.Drawing.Size(3, 403);
            this.splitterLeft.TabIndex = 0;
            this.splitterLeft.TabStop = false;
            // 
            // tabControl
            // 
            this.tabControl.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
            this.tabControl.Controls.Add(this.tabPageExecute);
            this.tabControl.Controls.Add(this.tabPagePerformance);
            this.tabControl.Controls.Add(this.tabPageHistory);
            this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl.ImageList = this.imageListTab;
            this.tabControl.Location = new System.Drawing.Point(211, 0);
            this.tabControl.Name = "tabControl";
            this.tabControl.SelectedIndex = 0;
            this.tabControl.Size = new System.Drawing.Size(363, 403);
            this.tabControl.TabIndex = 1;
            // 
            // tabPageExecute
            // 
            this.tabPageExecute.AutoScroll = true;
            this.tabPageExecute.Controls.Add(this.textBoxExecute);
            this.tabPageExecute.Controls.Add(this.progressBarExecute);
            this.tabPageExecute.Controls.Add(this.buttonExecute);
            this.tabPageExecute.ImageIndex = 0;
            this.tabPageExecute.Location = new System.Drawing.Point(4, 26);
            this.tabPageExecute.Name = "tabPageExecute";
            this.tabPageExecute.Size = new System.Drawing.Size(355, 373);
            this.tabPageExecute.TabIndex = 0;
            this.tabPageExecute.Text = "実行";
            // 
            // textBoxExecute
            // 
            this.textBoxExecute.BackColor = System.Drawing.SystemColors.Window;
            this.textBoxExecute.ForeColor = System.Drawing.SystemColors.WindowText;
            this.textBoxExecute.Location = new System.Drawing.Point(0, 0);
            this.textBoxExecute.Multiline = true;
            this.textBoxExecute.Name = "textBoxExecute";
            this.textBoxExecute.ReadOnly = true;
            this.textBoxExecute.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBoxExecute.Size = new System.Drawing.Size(355, 320);
            this.textBoxExecute.TabIndex = 3;
            // 
            // progressBarExecute
            // 
            this.progressBarExecute.Location = new System.Drawing.Point(92, 340);
            this.progressBarExecute.Name = "progressBarExecute";
            this.progressBarExecute.Size = new System.Drawing.Size(248, 16);
            this.progressBarExecute.TabIndex = 2;
            // 
            // buttonExecute
            // 
            this.buttonExecute.Location = new System.Drawing.Point(8, 336);
            this.buttonExecute.Name = "buttonExecute";
            this.buttonExecute.Size = new System.Drawing.Size(75, 23);
            this.buttonExecute.TabIndex = 1;
            this.buttonExecute.Text = "実行";
            this.buttonExecute.Click += new System.EventHandler(this.buttonExecute_Click);
            // 
            // tabPagePerformance
            // 
            this.tabPagePerformance.AutoScroll = true;
            this.tabPagePerformance.Controls.Add(this.progressBarPerformance);
            this.tabPagePerformance.Controls.Add(this.buttonPerformance);
            this.tabPagePerformance.Controls.Add(this.tabControlPerformance);
            this.tabPagePerformance.ImageIndex = 1;
            this.tabPagePerformance.Location = new System.Drawing.Point(4, 26);
            this.tabPagePerformance.Name = "tabPagePerformance";
            this.tabPagePerformance.Size = new System.Drawing.Size(355, 373);
            this.tabPagePerformance.TabIndex = 1;
            this.tabPagePerformance.Text = "成績計算";
            // 
            // progressBarPerformance
            // 
            this.progressBarPerformance.Location = new System.Drawing.Point(92, 340);
            this.progressBarPerformance.Name = "progressBarPerformance";
            this.progressBarPerformance.Size = new System.Drawing.Size(248, 16);
            this.progressBarPerformance.TabIndex = 2;
            // 
            // buttonPerformance
            // 
            this.buttonPerformance.Location = new System.Drawing.Point(8, 336);
            this.buttonPerformance.Name = "buttonPerformance";
            this.buttonPerformance.Size = new System.Drawing.Size(75, 23);
            this.buttonPerformance.TabIndex = 1;
            this.buttonPerformance.Text = "計算";
            this.buttonPerformance.Click += new System.EventHandler(this.buttonPerformance_Click);
            // 
            // tabControlPerformance
            // 
            this.tabControlPerformance.Controls.Add(this.tabPagePerformanceSummery);
            this.tabControlPerformance.Controls.Add(this.tabPagePerformanceProfitGraph);
            this.tabControlPerformance.Dock = System.Windows.Forms.DockStyle.Top;
            this.tabControlPerformance.Location = new System.Drawing.Point(0, 0);
            this.tabControlPerformance.Name = "tabControlPerformance";
            this.tabControlPerformance.SelectedIndex = 0;
            this.tabControlPerformance.Size = new System.Drawing.Size(355, 320);
            this.tabControlPerformance.TabIndex = 0;
            // 
            // tabPagePerformanceSummery
            // 
            this.tabPagePerformanceSummery.Controls.Add(this.richTextBoxPerformanceSummery);
            this.tabPagePerformanceSummery.Location = new System.Drawing.Point(4, 22);
            this.tabPagePerformanceSummery.Name = "tabPagePerformanceSummery";
            this.tabPagePerformanceSummery.Size = new System.Drawing.Size(347, 294);
            this.tabPagePerformanceSummery.TabIndex = 0;
            this.tabPagePerformanceSummery.Text = "サマリー";
            // 
            // richTextBoxPerformanceSummery
            // 
            this.richTextBoxPerformanceSummery.BackColor = System.Drawing.SystemColors.Window;
            this.richTextBoxPerformanceSummery.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBoxPerformanceSummery.Location = new System.Drawing.Point(0, 0);
            this.richTextBoxPerformanceSummery.Name = "richTextBoxPerformanceSummery";
            this.richTextBoxPerformanceSummery.ReadOnly = true;
            this.richTextBoxPerformanceSummery.Size = new System.Drawing.Size(347, 294);
            this.richTextBoxPerformanceSummery.TabIndex = 0;
            this.richTextBoxPerformanceSummery.Text = "";
            // 
            // tabPagePerformanceProfitGraph
            // 
            this.tabPagePerformanceProfitGraph.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.tabPagePerformanceProfitGraph.Controls.Add(this.profitGraphBox);
            this.tabPagePerformanceProfitGraph.Location = new System.Drawing.Point(4, 22);
            this.tabPagePerformanceProfitGraph.Name = "tabPagePerformanceProfitGraph";
            this.tabPagePerformanceProfitGraph.Size = new System.Drawing.Size(347, 294);
            this.tabPagePerformanceProfitGraph.TabIndex = 1;
            this.tabPagePerformanceProfitGraph.Text = "利益曲線";
            // 
            // profitGraphBox
            // 
            this.profitGraphBox.BackColor = System.Drawing.SystemColors.Window;
            this.profitGraphBox.Dock = System.Windows.Forms.DockStyle.Fill;
            this.profitGraphBox.Location = new System.Drawing.Point(0, 0);
            this.profitGraphBox.Name = "profitGraphBox";
            this.profitGraphBox.ProfitList = null;
            this.profitGraphBox.Size = new System.Drawing.Size(343, 290);
            this.profitGraphBox.TabIndex = 0;
            // 
            // tabPageHistory
            // 
            this.tabPageHistory.AutoScroll = true;
            this.tabPageHistory.Controls.Add(this.buttonHistory);
            this.tabPageHistory.Controls.Add(this.labelDateRange);
            this.tabPageHistory.Controls.Add(this.dateTimePickerHistoryDateMax);
            this.tabPageHistory.Controls.Add(this.dateTimePickerHistoryDateMin);
            this.tabPageHistory.Controls.Add(this.listViewHistory);
            this.tabPageHistory.ImageIndex = 2;
            this.tabPageHistory.Location = new System.Drawing.Point(4, 26);
            this.tabPageHistory.Name = "tabPageHistory";
            this.tabPageHistory.Size = new System.Drawing.Size(355, 373);
            this.tabPageHistory.TabIndex = 2;
            this.tabPageHistory.Text = "履歴検索";
            // 
            // buttonHistory
            // 
            this.buttonHistory.Location = new System.Drawing.Point(260, 336);
            this.buttonHistory.Name = "buttonHistory";
            this.buttonHistory.Size = new System.Drawing.Size(75, 23);
            this.buttonHistory.TabIndex = 4;
            this.buttonHistory.Text = "検索";
            this.buttonHistory.Click += new System.EventHandler(this.buttonHistory_Click);
            // 
            // labelDateRange
            // 
            this.labelDateRange.Location = new System.Drawing.Point(120, 340);
            this.labelDateRange.Name = "labelDateRange";
            this.labelDateRange.Size = new System.Drawing.Size(20, 16);
            this.labelDateRange.TabIndex = 2;
            this.labelDateRange.Text = "〜";
            // 
            // dateTimePickerHistoryDateMax
            // 
            this.dateTimePickerHistoryDateMax.Location = new System.Drawing.Point(140, 336);
            this.dateTimePickerHistoryDateMax.Name = "dateTimePickerHistoryDateMax";
            this.dateTimePickerHistoryDateMax.Size = new System.Drawing.Size(108, 19);
            this.dateTimePickerHistoryDateMax.TabIndex = 3;
            // 
            // dateTimePickerHistoryDateMin
            // 
            this.dateTimePickerHistoryDateMin.Location = new System.Drawing.Point(12, 336);
            this.dateTimePickerHistoryDateMin.Name = "dateTimePickerHistoryDateMin";
            this.dateTimePickerHistoryDateMin.Size = new System.Drawing.Size(108, 19);
            this.dateTimePickerHistoryDateMin.TabIndex = 1;
            // 
            // listViewHistory
            // 
            this.listViewHistory.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeaderHistoryDate,
            this.columnHeaderHistoryCode,
            this.columnHeaderHistoryName,
            this.columnHeaderHistoryPrice,
            this.columnHeaderHistoryNumber,
            this.columnHeaderHistoryOrder});
            this.listViewHistory.ContextMenu = this.historyContextMenu;
            this.listViewHistory.Dock = System.Windows.Forms.DockStyle.Top;
            this.listViewHistory.FullRowSelect = true;
            this.listViewHistory.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
            this.listViewHistory.Location = new System.Drawing.Point(0, 0);
            this.listViewHistory.Name = "listViewHistory";
            this.listViewHistory.OwnerDraw = true;
            this.listViewHistory.Size = new System.Drawing.Size(355, 320);
            this.listViewHistory.TabIndex = 0;
            this.listViewHistory.UseCompatibleStateImageBehavior = false;
            this.listViewHistory.View = System.Windows.Forms.View.Details;
            // 
            // columnHeaderHistoryDate
            // 
            this.columnHeaderHistoryDate.Text = "日付";
            // 
            // columnHeaderHistoryCode
            // 
            this.columnHeaderHistoryCode.Text = "コード";
            this.columnHeaderHistoryCode.Width = 40;
            // 
            // columnHeaderHistoryName
            // 
            this.columnHeaderHistoryName.Text = "銘柄名";
            this.columnHeaderHistoryName.Width = 70;
            // 
            // columnHeaderHistoryPrice
            // 
            this.columnHeaderHistoryPrice.Text = "値段(円)";
            // 
            // columnHeaderHistoryNumber
            // 
            this.columnHeaderHistoryNumber.Text = "株数";
            this.columnHeaderHistoryNumber.Width = 50;
            // 
            // columnHeaderHistoryOrder
            // 
            this.columnHeaderHistoryOrder.Text = "注文";
            this.columnHeaderHistoryOrder.Width = 40;
            // 
            // historyContextMenu
            // 
            this.historyContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.copyHistory});
            // 
            // copyHistory
            // 
            this.copyHistory.Index = 0;
            this.copyHistory.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
            this.copyHistory.ShowShortcut = false;
            this.copyHistory.Text = "コピー(&C)";
            this.copyHistory.Click += new System.EventHandler(this.copyHistory_Click);
            // 
            // imageListTab
            // 
            this.imageListTab.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListTab.ImageStream")));
            this.imageListTab.TransparentColor = System.Drawing.Color.Transparent;
            this.imageListTab.Images.SetKeyName(0, "");
            this.imageListTab.Images.SetKeyName(1, "");
            this.imageListTab.Images.SetKeyName(2, "");
            // 
            // backgroundWorkerPerformance
            // 
            this.backgroundWorkerPerformance.WorkerReportsProgress = true;
            this.backgroundWorkerPerformance.WorkerSupportsCancellation = true;
            this.backgroundWorkerPerformance.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerPerformance_DoWork);
            this.backgroundWorkerPerformance.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerPerformance_ProgressChanged);
            this.backgroundWorkerPerformance.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerPerformance_RunWorkerCompleted);
            // 
            // backgroundWorkerExecute
            // 
            this.backgroundWorkerExecute.WorkerReportsProgress = true;
            this.backgroundWorkerExecute.WorkerSupportsCancellation = true;
            this.backgroundWorkerExecute.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerExecute_DoWork);
            this.backgroundWorkerExecute.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerExecute_ProgressChanged);
            this.backgroundWorkerExecute.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerExecute_RunWorkerCompleted);
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(574, 403);
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.splitterLeft);
            this.Controls.Add(this.panelLeft);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.MaximizeBox = false;
            this.Menu = this.mainMenu;
            this.Name = "MainForm";
            this.Text = "PtSim";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown);
            this.panelLeft.ResumeLayout(false);
            this.panelSelect.ResumeLayout(false);
            this.panelSelect.PerformLayout();
            this.tabControl.ResumeLayout(false);
            this.tabPageExecute.ResumeLayout(false);
            this.tabPageExecute.PerformLayout();
            this.tabPagePerformance.ResumeLayout(false);
            this.tabControlPerformance.ResumeLayout(false);
            this.tabPagePerformanceSummery.ResumeLayout(false);
            this.tabPagePerformanceProfitGraph.ResumeLayout(false);
            this.tabPageHistory.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// 設定ファイルを書き込む。
        /// </summary>
        private void ConfigWrite()
        {
            var p = GlobalEnv.PtSimConfig;
            p.Mode = (int)TimeFrame;
            var item = (BrandList)comboBoxBrandList.SelectedItem;
            p.BrandListName = item != null ? item.Name : null;
            p.Save();
        }

        /// <summary>
        /// 成績を計算します。
        /// </summary>
        private string Performance(BackgroundWorker worker, DoWorkEventArgs e)
        {
            var system = (string)((object[])e.Argument)[0];
            var timeFrame = (TimeFrame)((object[])e.Argument)[1];
            var bl = (BrandList)((object[])e.Argument)[2];

            var profitList = new ProfitList();
            var allTradeNum = 0;			// 全トレード数
            var winTradeNum = 0;			// 勝ちトレード数
            float allTradeAveRatio = 0;		// 全トレード平均利率
            float winTradeAveRatio = 0;		// 勝ちトレード平均利率
            float winTradeMaxRatio = 0;		// 勝ちトレード最大利率
            float loseTradeMinRatio = 0;	// 負けトレード最大損率
            float allTradeAveSpan = 0;		// 全トレード平均期間
            float winTradeAveSpan = 0;		// 勝ちトレード平均期間
            float allTradeProfit = 0;		// 純利益
            float winTradeProfit = 0;		// 勝ちトレード総利益
            float winTradeMaxProfit = 0;	// 勝ちトレード最大利益
            float loseTradeMinProfit = 0;	// 負けトレード最大損失
            int currentTradeNum = 0;		// 現在進行中のトレード数

            for (int i = 0; i < bl.List.Count; i++)
            {
                var brand = GlobalEnv.BrandData[bl.List[i]];
                var prices = PriceData.GetPrices(brand.Code, timeFrame);
                var logs = LogData.GetLog(system, timeFrame, bl.List[i]);
                int index = 0;
                var beginDate = new DateTime(); // トレード開始日
                bool isHolding = false; // 保有しているか？
                int holdingNum = 0;     // 保有株数
                float buySum = 0;       // 買いの総和
                float sellSum = 0;      // 売りの総和
                int prePrice = 0;       // 前日の価格
                for (var j = 0; j < prices.Count; j++)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return null;
                    }
                    var profit = profitList[prices[j].Date];
                    int price = prices[j].Close;
                    if (isHolding && price > 0 && prePrice > 0)
                    {
                        profit.MarketProfit += holdingNum * (price - prePrice);
                        prePrice = price;
                    }
                    else if (price > 0)
                    {
                        prePrice = price;
                    }

                    if (index < logs.Count && logs[index].Date == prices[j].Date)
                    {
                        var log = logs[index++];
                        if (log.Quantity == 0) // 0株の売買は無視する。
                            continue;
                        if (log.Order == Order.Buy)
                        {
                            holdingNum += log.Quantity;
                            buySum += log.Quantity * log.Price;
                            profit.MarketProfit += log.Quantity * (prePrice - log.Price);
                        }
                        else
                        {
                            holdingNum -= log.Quantity;
                            sellSum += log.Quantity * log.Price;
                            profit.MarketProfit -= log.Quantity * (prePrice - log.Price);
                        }

                        if (!isHolding) // トレードの開始
                        {
                            beginDate = log.Date;
                            isHolding = true;
                        }
                        else if (holdingNum == 0) // トレードの終了
                        {
                            allTradeNum++;
                            var ratio = sellSum / buySum - 1;
                            allTradeAveRatio += ratio;
                            var span = (log.Date - beginDate).Days;
                            allTradeAveSpan += span;
                            var p = sellSum - buySum;
                            profit.BookProfit += p;
                            allTradeProfit += p;
                            if (buySum < sellSum) // 勝ち
                            {
                                winTradeNum++;
                                winTradeAveRatio += ratio;
                                if (ratio > winTradeMaxRatio)
                                    winTradeMaxRatio = ratio;
                                winTradeAveSpan += span;
                                winTradeProfit += p;
                                if (p > winTradeMaxProfit)
                                    winTradeMaxProfit = p;
                            }
                            else // 負け
                            {
                                if (ratio < loseTradeMinRatio)
                                    loseTradeMinRatio = ratio;
                                if (p < loseTradeMinProfit)
                                    loseTradeMinProfit = p;
                            }

                            isHolding = false;
                            buySum = sellSum = 0;
                        }
                    }
                }

                if (isHolding)
                    currentTradeNum++;

                worker.ReportProgress(100 * (i + 1) / bl.List.Count);
            }

            var loseTradeNum = allTradeNum - winTradeNum;
            var winProb = allTradeNum == 0 ? 0 : (float)100 * winTradeNum / allTradeNum;
            var loseProb = allTradeNum == 0 ? 0 : 100 - winProb;
            var loseTradeAveRatio = 100 * (allTradeAveRatio - winTradeAveRatio) / loseTradeNum;
            allTradeAveRatio = 100 * allTradeAveRatio / allTradeNum;
            winTradeAveRatio = 100 * winTradeAveRatio / winTradeNum;
            var loseTradeAveSpan = (allTradeAveSpan - winTradeAveSpan) / loseTradeNum;
            winTradeMaxRatio = 100 * winTradeMaxRatio;
            loseTradeMinRatio = 100 * loseTradeMinRatio;
            allTradeAveSpan = allTradeAveSpan / allTradeNum;
            winTradeAveSpan = winTradeAveSpan / winTradeNum;
            var loseTradeProfit = allTradeProfit - winTradeProfit;
            var allTradeAveProfit = allTradeProfit / allTradeNum;
            var winTradeAveProfit = winTradeProfit / winTradeNum;
            var loseTradeAveProfit = loseTradeProfit / loseTradeNum;
            var pf = -winTradeProfit / loseTradeProfit;
            // 累積利益に変換
            profitList.Accumulate();
            var dd = profitList.MaxDrawDown();
            var ddBook = dd.BookProfit;
            var ddMarket = dd.MarketProfit;
            profitGraphBox.ProfitList = profitList;

            var msg = "ファイル: " + system + "\r\n" +
                "期間モード: " + TimeFrameName + "\r\n" +
                "対象銘柄: " + bl.Name + "\r\n" +
                profitList.MinDate.ToShortDateString() + "〜" + profitList.MaxDate.ToShortDateString() + "における成績です。\r\n" +
                "----------------------------------------\r\n" +
                "全トレード数\t\t" + allTradeNum + "\r\n" +
                "勝ちトレード数(勝率)\t" + winTradeNum + "(" + winProb.ToString("N") + "%)\r\n" +
                "負けトレード数(負率)\t" + loseTradeNum + "(" + loseProb.ToString("N") + "%)\r\n\r\n" +
                "全トレード平均利率\t" + allTradeAveRatio.ToString("N") + "%\r\n" +
                "勝ちトレード平均利率\t" + winTradeAveRatio.ToString("N") + "%\r\n" +
                "負けトレード平均損率\t" + loseTradeAveRatio.ToString("N") + "%\r\n\r\n" +
                "勝ちトレード最大利率\t" + winTradeMaxRatio.ToString("N") + "%\r\n" +
                "負けトレード最大損率\t" + loseTradeMinRatio.ToString("N") + "%\r\n\r\n" +
                "全トレード平均期間\t" + allTradeAveSpan.ToString("N") + "日\r\n" +
                "勝ちトレード平均期間\t" + winTradeAveSpan.ToString("N") + "日\r\n" +
                "負けトレード平均期間\t" + loseTradeAveSpan.ToString("N") + "日\r\n" +
                "----------------------------------------\r\n" +
                "純利益\t\t\t" + allTradeProfit.ToString("C") + "\r\n" +
                "勝ちトレード総利益\t\t" + winTradeProfit.ToString("C") + "\r\n" +
                "負けトレード総損失\t\t" + loseTradeProfit.ToString("C") + "\r\n\r\n" +
                "全トレード平均利益\t" + allTradeAveProfit.ToString("C") + "\r\n" +
                "勝ちトレード平均利益\t" + winTradeAveProfit.ToString("C") + "\r\n" +
                "負けトレード平均損失\t" + loseTradeAveProfit.ToString("C") + "\r\n\r\n" +
                "勝ちトレード最大利益\t" + winTradeMaxProfit.ToString("C") + "\r\n" +
                "負けトレード最大損失\t" + loseTradeMinProfit.ToString("C") + "\r\n\r\n" +
                "プロフィットファクター\t\t" + pf.ToString("N") + "\r\n\r\n" +
                "最大ドローダウン(簿価)\t" + ddBook.ToString("C") + "\r\n" +
                "最大ドローダウン(時価)\t" + ddMarket.ToString("C") + "\r\n" +
                "----------------------------------------\r\n" +
                "現在進行中のトレード数\t" + currentTradeNum + "\r\n";
            return msg;
        }

        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (Win32API.ProcessAlreadyExists())
                return;
            Application.Run(new MainForm());
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigWrite();
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5 || (e.KeyCode == Keys.R && e.Control))
                ptFileTreeView.RootDirectory = Global.DirSystem;
        }

        private void menuItemLogDelete_Click(object sender, EventArgs e)
        {
            var system = ptFileTreeView.SelectedFile;
            if (system == null)
                return;
            string msg = string.Format("ファイル: {0}\n期間モード: {1}\nのシステムログを削除します。よろしいですか？", system, TimeFrameName);
            var result = MessageBox.Show(
                this, msg, "確認", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            if (result == DialogResult.OK)
            {
                LogData.Delete(system, TimeFrame);
                GlobalData.Delete(system, TimeFrame);
            }
        }

        private string TimeFrameName
        {
            get { return TimeFrame == TimeFrame.Daily ? "日足" : "週足"; }
        }

        private TimeFrame TimeFrame
        {
            get { return radioButtonDaily.Checked ? TimeFrame.Daily : TimeFrame.Weekly; }
        }

        private void menuItemLogAllDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this,
                "システムログをすべて削除します。よろしいですか？",
                "確認", MessageBoxButtons.OKCancel,
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.OK)
            {
                LogData.DeleteAll();
                GlobalData.DeleteAll();
            }
        }

        private void menuItemBrandListEdit_Click(object sender, EventArgs e)
        {
            using (var dialog = new EditBrandListDialog())
                dialog.ShowDialog(this);
            BrandListInit();
        }

        private void BrandListInit()
        {
            var item = (BrandList)comboBoxBrandList.SelectedItem;
            SuspendLayout();
            comboBoxBrandList.Items.Clear();
            foreach (var bl in GlobalEnv.BrandListConfig.List)
            {
                comboBoxBrandList.Items.Add(bl);
                if (item != null && item.Name == bl.Name)
                    comboBoxBrandList.SelectedItem = bl;
            }
            if (comboBoxBrandList.SelectedItem == null &&
                comboBoxBrandList.Items.Count > 0)
                comboBoxBrandList.SelectedIndex = 0;
            ResumeLayout();
        }

        private void menuItemMan_Click(object sender, EventArgs e)
        {
            Process.Start(Global.PathMan);
        }

        private void menuItemVersion_Click(object sender, EventArgs e)
        {
            Form dialog = new VersionDialog();
            dialog.ShowDialog(this);
        }

        private void ptFileTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            comboBoxBrandList_SelectedIndexChanged(sender, e);
        }

        private void comboBoxBrandList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ptFileTreeView.SelectedFile != null
                && comboBoxBrandList.SelectedItem != null)
            {
                if (!backgroundWorkerExecute.IsBusy && !backgroundWorkerPerformance.IsBusy)
                {
                    buttonExecute.Enabled = true;
                    buttonPerformance.Enabled = true;
                    menuItemLogDelete.Enabled = true;
                }
                buttonHistory.Enabled = true;
            }
            else
            {
                if (!backgroundWorkerExecute.IsBusy && !backgroundWorkerPerformance.IsBusy)
                {
                    buttonExecute.Enabled = false;
                    buttonPerformance.Enabled = false;
                    menuItemLogDelete.Enabled = false;
                }
                buttonHistory.Enabled = false;
            }
        }

        private void buttonExecute_Click(object sender, EventArgs e)
        {
            if (backgroundWorkerExecute.IsBusy)
            {
                backgroundWorkerExecute.CancelAsync();
                Cursor = Cursors.WaitCursor;
                buttonExecute.Enabled = false;
                return;
            }

            var system = ptFileTreeView.SelectedFile;
            var brandList = (BrandList)comboBoxBrandList.SelectedItem;
            if (system == null || brandList == null)
                return;

            // 各種操作を無効化
            buttonExecute.Text = "中断";
            buttonPerformance.Enabled = false;
            menuItemLogDelete.Enabled = false;
            menuItemLogAllDelete.Enabled = false;
            menuItemBrandListEdit.Enabled = false;
            // TextBoxを初期化。
            textBoxExecute.Clear();

            backgroundWorkerExecute.RunWorkerAsync(new object[] { system, brandList, TimeFrame, LoopType });
        }

        private LoopType LoopType
        {
            get { return checkBoxEmpty.Checked ? LoopType.DateOnly : LoopType.BrandAndDate; }
        }

        private void backgroundWorkerExecute_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = (BackgroundWorker)sender;
            var args = (Object[])e.Argument;
            var executor = new SystemExecutor((string)args[0], (BrandList)args[1], (TimeFrame)args[2], (LoopType)args[3]);
            executor.Execute(worker, WrapInvoke(textBoxExecute.AppendText));
            if (worker.CancellationPending)
                e.Cancel = true;
        }

        private AppendTextDelegate WrapInvoke(AppendTextDelegate appendText)
        {
            return text => Invoke(appendText, text);
        }

        private void backgroundWorkerExecute_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBarExecute.Value = e.ProgressPercentage;
        }

        private void backgroundWorkerExecute_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                textBoxExecute.AppendText(e.Error.Message + "\r\nエラーが発生したので実行を中断します。");
            else if (e.Cancelled)
                textBoxExecute.AppendText("中断されました。");
            else
                textBoxExecute.AppendText("正常に終了しました。\r\n");

            // 各種操作を復旧する。
            Cursor = Cursors.Arrow;
            buttonExecute.Enabled = true;
            buttonExecute.Text = "実行";
            progressBarExecute.Value = 0;
            menuItemLogAllDelete.Enabled = true;
            if (ptFileTreeView.SelectedFile != null
                && comboBoxBrandList.SelectedItem != null)
            {
                buttonPerformance.Enabled = true;
                menuItemLogDelete.Enabled = true;
                menuItemBrandListEdit.Enabled = true;
            }
            else
            {
                buttonExecute.Enabled = false;
            }
            progressBarPerformance.Value = 0;
        }

        private void buttonPerformance_Click(object sender, EventArgs e)
        {
            if (backgroundWorkerPerformance.IsBusy)
            {
                backgroundWorkerPerformance.CancelAsync();
                return;
            }

            var system = ptFileTreeView.SelectedFile;
            if (system == null)
                return;
            var bl = comboBoxBrandList.SelectedItem;
            if (bl == null)
                return;

            // 各種操作を無効にする。
            buttonPerformance.Text = "中断";
            buttonExecute.Enabled = false;
            menuItemLogDelete.Enabled = false;
            menuItemLogAllDelete.Enabled = false;
            menuItemBrandListEdit.Enabled = false;
            richTextBoxPerformanceSummery.Clear();

            // profitGraphBoxを初期化する。
            profitGraphBox.ProfitList = null;

            backgroundWorkerPerformance.RunWorkerAsync(new[] { system, TimeFrame, bl });
        }

        private void backgroundWorkerPerformance_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            e.Result = Performance(worker, e);
        }

        private void backgroundWorkerPerformance_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBarPerformance.Value = e.ProgressPercentage;
        }

        private void backgroundWorkerPerformance_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                richTextBoxPerformanceSummery.AppendText(e.Error.Message + "\r\nエラーが発生したので計算を中断します。");
            else if (e.Cancelled)
                richTextBoxPerformanceSummery.AppendText("中断されました。");
            else
                richTextBoxPerformanceSummery.AppendText((string)e.Result);

            // 各種操作を復旧する。
            buttonPerformance.Text = "計算";
            menuItemLogAllDelete.Enabled = true;
            if (ptFileTreeView.SelectedFile != null
                && comboBoxBrandList.SelectedItem != null)
            {
                buttonExecute.Enabled = true;
                menuItemLogDelete.Enabled = true;
                menuItemBrandListEdit.Enabled = true;
            }
            else
            {
                buttonPerformance.Enabled = false;
            }
            progressBarPerformance.Value = 0;
        }

        private void buttonHistory_Click(object sender, EventArgs e)
        {
            string system = ptFileTreeView.SelectedFile;
            if (system == null)
                return;
            var brands = (BrandList)comboBoxBrandList.SelectedItem;
            if (brands == null)
                return;
            List<Log> logs = LogData.GetLog(system, TimeFrame,
                    dateTimePickerHistoryDateMin.Value,
                    dateTimePickerHistoryDateMax.Value);
            var brandIdTable = new Dictionary<string, Object>();
            foreach (var id in brands.List)
                brandIdTable.Add(id, null);

            listViewHistory.Items.Clear();
            listViewHistory.BeginUpdate();
            foreach (var log in logs)
            {
                if (brandIdTable.ContainsKey(log.Code))
                {
                    var brand = GlobalEnv.BrandData[log.Code];
                    var listViewItem = new ListViewItem(new[]{
						log.Date.ToString("yy/MM/dd"),
						brand.Code.ToString(CultureInfo.InvariantCulture),
						brand.Name,
						log.Price.ToString(CultureInfo.InvariantCulture),
						log.Quantity.ToString(CultureInfo.InvariantCulture),
						log.Order == 0 ? "買" : "売" }) { BackColor = log.Order == 0 ? Color.LightBlue : Color.LightPink };
                    listViewHistory.Items.Add(listViewItem);
                }
            }
            listViewHistory.EndUpdate();
        }

        private void copyHistory_Click(object sender, EventArgs e)
        {
            var builder = new System.Text.StringBuilder();
            foreach (ListViewItem item in listViewHistory.SelectedItems)
            {
                for (int n = 0; n < item.SubItems.Count; n++)
                {
                    builder.Append(item.SubItems[n].Text);
                    if (n < item.SubItems.Count - 1)
                        builder.Append(",");
                }
                builder.Append("\n");
            }
            if (builder.Length == 0)
                return;
            Clipboard.SetDataObject(builder.ToString());
        }
    }
}
