OSDN Git Service

570775518df87336106d1db33510c757e5b66651
[wptscs/wpts.git] / Wptscs / ConfigForm.cs
1 // ================================================================================================
2 // <summary>
3 //      Wikipedia翻訳支援ツール設定画面クラスソース</summary>
4 //
5 // <copyright file="ConfigForm.cs" company="honeplusのメモ帳">
6 //      Copyright (C) 2012 Honeplus. All rights reserved.</copyright>
7 // <author>
8 //      Honeplus</author>
9 // ================================================================================================
10
11 namespace Honememo.Wptscs
12 {
13     using System;
14     using System.Collections.Generic;
15     using System.ComponentModel;
16     using System.Data;
17     using System.Drawing;
18     using System.Linq;
19     using System.Reflection;
20     using System.Text;
21     using System.Windows.Forms;
22     using Honememo.Utilities;
23     using Honememo.Wptscs.Models;
24     using Honememo.Wptscs.Properties;
25     using Honememo.Wptscs.Utilities;
26     using Honememo.Wptscs.Websites;
27
28     /// <summary>
29     /// Wikipedia翻訳支援ツール設定画面のクラスです。
30     /// </summary>
31     public partial class ConfigForm : Form
32     {
33         #region private変数
34
35         /// <summary>
36         /// 現在設定中のアプリケーションの設定。
37         /// </summary>
38         /// <remarks>設定画面を閉じた後は再読み込みされるので、必要に応じて随時更新してよい。</remarks>
39         private Config config;
40
41         /// <summary>
42         /// <seealso cref="comboBoxLanguage"/>で選択していたアイテムのバックアップ。
43         /// </summary>
44         private string comboBoxLanguageSelectedText;
45
46         #endregion
47
48         #region コンストラクタ
49
50         /// <summary>
51         /// コンストラクタ。
52         /// </summary>
53         /// <param name="config">設定対象のConfig。</param>
54         /// <remarks>configは設定画面の操作により随時更新される。呼び出し元では再読み込みすること。</remarks>
55         public ConfigForm(Config config)
56         {
57             this.InitializeComponent();
58
59             // 設定対象のConfigを受け取る
60             this.config = Honememo.Utilities.Validate.NotNull(config, "config");
61         }
62
63         #endregion
64         
65         #region フォームの各イベントのメソッド
66
67         /// <summary>
68         /// フォームロード時の処理。
69         /// </summary>
70         /// <param name="sender">イベント発生オブジェクト。</param>
71         /// <param name="e">発生したイベント。</param>
72         private void ConfigForm_Load(object sender, EventArgs e)
73         {
74             try
75             {
76                 // 各タブの内容を初期化する
77
78                 // 記事の置き換えタブの初期化
79                 this.ImportTranslationDictionaryView(this.dataGridViewItems, this.config.ItemTables);
80
81                 // 見出しの置き換えタブの初期化
82                 this.ImportTranslationTableView(this.dataGridViewHeading, this.config.HeadingTable);
83
84                 // サーバー/言語タブの初期化
85                 foreach (Website site in this.config.Websites)
86                 {
87                     this.comboBoxLanguage.Items.Add(site.Language.Code);
88                 }
89
90                 // その他タブの初期化
91                 this.textBoxCacheExpire.Text = Settings.Default.CacheExpire.Days.ToString();
92                 this.textBoxUserAgent.Text = Settings.Default.UserAgent;
93                 this.textBoxReferer.Text = Settings.Default.Referer;
94                 this.textBoxMaxConnectRetries.Text = Settings.Default.MaxConnectRetries.ToString();
95                 this.textBoxConnectRetryTime.Text = Settings.Default.ConnectRetryTime.ToString();
96                 this.checkBoxIgnoreError.Checked = Settings.Default.IgnoreError;
97                 this.labelApplicationName.Text = FormUtils.ApplicationName();
98                 AssemblyCopyrightAttribute copyright = Attribute.GetCustomAttribute(
99                     Assembly.GetExecutingAssembly(),
100                     typeof(AssemblyCopyrightAttribute)) as AssemblyCopyrightAttribute;
101                 if (copyright != null)
102                 {
103                     this.labelCopyright.Text = copyright.Copyright;
104                 }
105             }
106             catch (Exception ex)
107             {
108                 // 通常この処理では例外は発生しないはず(Configに読めているので)。想定外のエラー用
109                 FormUtils.ErrorDialog(Resources.ErrorMessageDevelopmentError, ex.Message, ex.StackTrace);
110             }
111         }
112
113         /// <summary>
114         /// OKボタン押下時の処理。
115         /// </summary>
116         /// <param name="sender">イベント発生オブジェクト。</param>
117         /// <param name="e">発生したイベント。</param>
118         private void ButtonOk_Click(object sender, EventArgs e)
119         {
120             try
121             {
122                 // 各タブの内容を設定ファイルに保存する
123
124                 // 記事の置き換えタブの保存
125                 this.config.ItemTables = this.ExportTranslationDictionaryView(this.dataGridViewItems);
126
127                 // 見出しの置き換えタブの保存
128                 this.config.HeadingTable = this.ExportTranslationTableView(this.dataGridViewHeading);
129
130                 // サーバー/言語タブの保存
131                 // ※ このタブはコンボボックス変更のタイミングで保存されるので、そのメソッドを呼ぶ
132                 this.ComboBoxLanguuage_SelectedIndexChanged(sender, e);
133
134                 // その他タブの保存
135                 Settings.Default.CacheExpire = new TimeSpan(int.Parse(this.textBoxCacheExpire.Text), 0, 0, 0);
136                 Settings.Default.UserAgent = this.textBoxUserAgent.Text;
137                 Settings.Default.Referer = this.textBoxReferer.Text;
138                 Settings.Default.MaxConnectRetries = int.Parse(this.textBoxMaxConnectRetries.Text);
139                 Settings.Default.ConnectRetryTime = int.Parse(this.textBoxConnectRetryTime.Text);
140                 Settings.Default.IgnoreError = this.checkBoxIgnoreError.Checked;
141
142                 // 設定をファイルに保存
143                 Settings.Default.Save();
144                 try
145                 {
146                     this.config.Save();
147
148                     // 全部成功なら画面を閉じる
149                     // ※ エラーの場合、どうしても駄目ならキャンセルボタンで閉じてもらう
150                     this.Close();
151                 }
152                 catch (Exception ex)
153                 {
154                     // 異常時はエラーメッセージを表示
155                     System.Diagnostics.Debug.WriteLine(ex.ToString());
156                     FormUtils.ErrorDialog(Resources.ErrorMessageConfigSaveFailed, ex.Message);
157                 }
158             }
159             catch (Exception ex)
160             {
161                 // 通常ファイル保存以外では例外は発生しないはず。想定外のエラー用
162                 FormUtils.ErrorDialog(Resources.ErrorMessageDevelopmentError, ex.Message, ex.StackTrace);
163             }
164         }
165
166         #endregion
167
168         #region 記事の置き換えタブのイベントのメソッド
169
170         /// <summary>
171         /// 記事の置き換え対訳表への行追加時の処理。
172         /// </summary>
173         /// <param name="sender">イベント発生オブジェクト。</param>
174         /// <param name="e">発生したイベント。</param>
175         private void DataGridViewItems_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
176         {
177             for (int i = e.RowIndex - 1; i < this.dataGridViewItems.Rows.Count; i++)
178             {
179                 // プログラムから追加された場合は現在のインデックス、画面から追加した場合は+1したインデックスが来る
180                 if (i >= 0)
181                 {
182                     this.dataGridViewItems.Rows[i].Cells["ColumnArrow"].Value = Resources.RightArrow;
183                 }
184             }
185         }
186
187         /// <summary>
188         /// 記事の置き換え対訳表のセル編集時のバリデート処理。
189         /// </summary>
190         /// <param name="sender">イベント発生オブジェクト。</param>
191         /// <param name="e">発生したイベント。</param>
192         private void DataGridViewItems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
193         {
194             // 取得日時列のみチェック
195             if (this.dataGridViewItems.Columns[e.ColumnIndex].Name != "ColumnTimestamp")
196             {
197                 return;
198             }
199
200             // 空または日付として認識可能な値の場合OK
201             string value = e.FormattedValue.ToString();
202             DateTime dummy;
203             if (String.IsNullOrWhiteSpace(value) || DateTime.TryParse(value, out dummy))
204             {
205                 return;
206             }
207
208             // 不許可値の場合、NGメッセージを表示
209             this.dataGridViewItems.Rows[e.RowIndex].ErrorText = Resources.WarningMessageUnformatedTimestamp;
210             e.Cancel = true;
211         }
212
213         /// <summary>
214         /// 記事の置き換え対訳表のセル編集時のバリデート成功時の処理。
215         /// </summary>
216         /// <param name="sender">イベント発生オブジェクト。</param>
217         /// <param name="e">発生したイベント。</param>
218         private void DataGridViewItems_CellValidated(object sender, DataGridViewCellEventArgs e)
219         {
220             // 取得日時列の場合、バリデートNGメッセージを消す
221             // ※ 他の列で消さないのは、エラーを出しているのがRowValidatingの場合もあるから
222             if (this.dataGridViewItems.Columns[e.ColumnIndex].Name == "ColumnTimestamp")
223             {
224                 this.dataGridViewItems.Rows[e.RowIndex].ErrorText = String.Empty;
225             }
226         }
227
228         /// <summary>
229         /// 記事の置き換え対訳表のセル変更時の処理。
230         /// </summary>
231         /// <param name="sender">イベント発生オブジェクト。</param>
232         /// <param name="e">発生したイベント。</param>
233         private void DataGridViewItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
234         {
235             // 取得日時列が空の場合、有効期限が無期限として背景色を変更
236             // ※ ただし全列が空(新規行など)の場合は無視
237             if (e.RowIndex >= 0)
238             {
239                 DataGridViewRow row = this.dataGridViewItems.Rows[e.RowIndex];
240                 if (String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnTimestamp"]))
241                     && !this.IsEmptyDataGridViewItemsRow(row))
242                 {
243                     // 背景色を変更
244                     row.DefaultCellStyle.BackColor = Color.Bisque;
245                 }
246                 else if (row.InheritedStyle.BackColor != this.dataGridViewItems.DefaultCellStyle.BackColor)
247                 {
248                     // 背景色を戻す
249                     // ※ DefaultCellStyleプロパティにアクセスしたタイミングでインスタンスが
250                     //    作成されてしまうため、InheritedStyleを調べて変更が必要な場合だけアクセス
251                     row.DefaultCellStyle.BackColor = this.dataGridViewItems.DefaultCellStyle.BackColor;
252                 }
253             }
254         }
255
256         /// <summary>
257         /// 記事の置き換え対訳表の行編集時のバリデート処理。
258         /// </summary>
259         /// <param name="sender">イベント発生オブジェクト。</param>
260         /// <param name="e">発生したイベント。</param>
261         private void DataGridViewItems_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
262         {
263             // 翻訳元、記事名、翻訳先が未入力の場合、バリデートNGメッセージを表示
264             // ※ ただし全列が空(新規行など)の場合は無視
265             DataGridViewRow row = this.dataGridViewItems.Rows[e.RowIndex];
266             if ((String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnFromCode"]))
267                 || String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnToCode"]))
268                 || String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnFromTitle"])))
269                 && !this.IsEmptyDataGridViewItemsRow(row))
270             {
271                 row.ErrorText = Resources.WarningMessageEmptyTranslationDictionary;
272                 e.Cancel = true;
273             }
274         }
275
276         /// <summary>
277         /// 記事の置き換え対訳表を使用する<see cref="DataGridView"/>の値設定を行う。
278         /// </summary>
279         /// <param name="view">対訳表を表示するビュー。</param>
280         /// <param name="dictionaries">対訳表データ。</param>
281         private void ImportTranslationDictionaryView(DataGridView view, IList<TranslationDictionary> dictionaries)
282         {
283             // 初期設定以外の場合も想定して最初にクリア
284             view.Rows.Clear();
285             foreach (TranslationDictionary dic in dictionaries)
286             {
287                 foreach (KeyValuePair<string, TranslationDictionary.Item> item in dic)
288                 {
289                     // 行を追加しその行を取得
290                     DataGridViewRow row = view.Rows[view.Rows.Add()];
291
292                     // 1行分の初期値を設定。右矢印は別途イベントで追加すること
293                     row.Cells["ColumnFromCode"].Value = dic.From;
294                     row.Cells["ColumnFromTitle"].Value = item.Key;
295                     row.Cells["ColumnAlias"].Value = item.Value.Alias;
296                     row.Cells["ColumnToCode"].Value = dic.To;
297                     row.Cells["ColumnToTitle"].Value = item.Value.Word;
298                     if (item.Value.Timestamp.HasValue)
299                     {
300                         row.Cells["ColumnTimestamp"].Value = item.Value.Timestamp.Value.ToLocalTime().ToString("G");
301                     }
302                 }
303             }
304
305             // 取得日時の降順でソート、空の列は先頭にする
306             this.dataGridViewItems.Sort(new TranslationDictionaryViewComparer());
307
308             // 列幅をデータ長に応じて自動調整
309             // ※ 常に行ってしまうと、読み込みに非常に時間がかかるため
310             view.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
311         }
312
313         /// <summary>
314         /// 記事の置き換え対訳表を使用する<see cref="DataGridView"/>からデータを抽出する。
315         /// </summary>
316         /// <param name="view">対訳表を表示するビュー。</param>
317         /// <returns>対訳表データ。</returns>
318         private IList<TranslationDictionary> ExportTranslationDictionaryView(DataGridView view)
319         {
320             IList<TranslationDictionary> dictionaries = new List<TranslationDictionary>();
321             foreach (DataGridViewRow row in view.Rows)
322             {
323                 // 画面での追加用の最終行が空で渡されてくるので無視
324                 if (this.IsEmptyDataGridViewItemsRow(row))
325                 {
326                     continue;
327                 }
328
329                 // その行で対象とする言語を探索、無ければ新規作成
330                 string from = FormUtils.ToString(row.Cells["ColumnFromCode"]);
331                 string to = FormUtils.ToString(row.Cells["ColumnToCode"]);
332                 TranslationDictionary dic
333                     = TranslationDictionary.GetDictionaryNeedCreate(dictionaries, from, to);
334
335                 // 値を格納
336                 TranslationDictionary.Item item = new TranslationDictionary.Item
337                 {
338                     Word = FormUtils.ToString(row.Cells["ColumnToTitle"]),
339                     Alias = FormUtils.ToString(row.Cells["ColumnAlias"])
340                 };
341
342                 string timestamp = FormUtils.ToString(row.Cells["ColumnTimestamp"]);
343                 if (!String.IsNullOrWhiteSpace(timestamp))
344                 {
345                     item.Timestamp = DateTime.Parse(timestamp);
346
347                     // UTCでもなくタイムゾーンでも無い場合、ローカル時刻として設定する
348                     if (item.Timestamp.Value.Kind == DateTimeKind.Unspecified)
349                     {
350                         item.Timestamp = DateTime.SpecifyKind(item.Timestamp.Value, DateTimeKind.Local);
351                     }
352                 }
353
354                 dic[FormUtils.ToString(row.Cells["ColumnFromTitle"])] = item;
355             }
356
357             return dictionaries;
358         }
359         
360         /// <summary>
361         /// 記事の置き換え対訳表の行が空かを判定する。
362         /// </summary>
363         /// <param name="row">対訳表の1行。</param>
364         /// <returns>空の場合<c>true</c>。</returns>
365         private bool IsEmptyDataGridViewItemsRow(DataGridViewRow row)
366         {
367             return String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnFromCode"]))
368                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnFromTitle"]))
369                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnAlias"]))
370                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnToCode"]))
371                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnToTitle"]))
372                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnTimestamp"]));
373         }
374
375         #endregion
376
377         #region 見出しの置き換えタブのイベントのメソッド
378
379         /// <summary>
380         /// 見出しの置き換え対訳表を使用する<see cref="DataGridView"/>の値設定を行う。
381         /// </summary>
382         /// <param name="view">対訳表を表示するビュー。</param>
383         /// <param name="table">対訳表データ。</param>
384         private void ImportTranslationTableView(DataGridView view, TranslationTable table)
385         {
386             // 初期設定以外の場合も想定して最初にクリア
387             view.Columns.Clear();
388
389             // 言語コードを列、語句を行とする。登録されている全言語分の列を作成する
390             foreach (Website site in this.config.Websites)
391             {
392                 this.AddTranslationTableColumn(view.Columns, site.Language.Code, this.GetHeaderLanguage(site.Language));
393             }
394
395             // 各行にデータを取り込み
396             foreach (IDictionary<string, string> record in table)
397             {
398                 // 行を追加しその行を取得
399                 DataGridViewRow row = view.Rows[view.Rows.Add()];
400
401                 foreach (KeyValuePair<string, string> cell in record)
402                 {
403                     // 上で登録した列では足りなかった場合、その都度生成する
404                     if (!view.Columns.Contains(cell.Key))
405                     {
406                         this.AddTranslationTableColumn(view.Columns, cell.Key, cell.Key);
407                     }
408
409                     row.Cells[cell.Key].Value = cell.Value;
410                 }
411             }
412
413             // 列幅をデータ長に応じて自動調整
414             // ※ 常に行ってしまうと、読み込みに時間がかかるため
415             view.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
416         }
417
418         /// <summary>
419         /// 見出しの置き換え対訳表を使用する<see cref="DataGridView"/>からデータを抽出する。
420         /// </summary>
421         /// <param name="view">対訳表を表示するビュー。</param>
422         /// <returns>対訳表データ。</returns>
423         private TranslationTable ExportTranslationTableView(DataGridView view)
424         {
425             TranslationTable table = new TranslationTable();
426             foreach (DataGridViewRow row in view.Rows)
427             {
428                 IDictionary<string, string> record = new SortedDictionary<string, string>();
429                 foreach (DataGridViewCell cell in row.Cells)
430                 {
431                     // 空のセルは格納しない、該当の組み合わせは消える
432                     string value = FormUtils.ToString(cell);
433                     if (!String.IsNullOrWhiteSpace(value))
434                     {
435                         record[cell.OwningColumn.Name] = value;
436                     }
437                 }
438
439                 // 1件もデータが無い行は丸々カットする
440                 if (record.Count > 0)
441                 {
442                     table.Add(record);
443                 }
444             }
445
446             return table;
447         }
448
449         /// <summary>
450         /// 指定された情報を元に見出しの置き換え対訳表の列を追加する。
451         /// </summary>
452         /// <param name="columns">列コレクション。</param>
453         /// <param name="columnName">列名。</param>
454         /// <param name="headerText">列見出し。</param>
455         private void AddTranslationTableColumn(DataGridViewColumnCollection columns, string columnName, string headerText)
456         {
457             columns.Add(columnName, headerText);
458         }
459
460         /// <summary>
461         /// 指定された言語用の表示名を返す。
462         /// </summary>
463         /// <param name="lang">表示言語コード。</param>
464         /// <returns>表示名、無ければ言語コード。</returns>
465         private string GetHeaderLanguage(Language lang)
466         {
467             Language.LanguageName name;
468             if (lang.Names.TryGetValue(
469                 System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName, out name))
470             {
471                 if (!String.IsNullOrEmpty(name.Name))
472                 {
473                     return String.Format(Resources.HeadingViewHeaderText, name.Name, lang.Code);
474                 }
475             }
476
477             return lang.Code;
478         }
479
480         #endregion
481
482         #region 言語/サーバータブのイベントのメソッド
483
484         /// <summary>
485         /// 言語コンボボックス変更時の処理。
486         /// </summary>
487         /// <param name="sender">イベント発生オブジェクト。</param>
488         /// <param name="e">発生したイベント。</param>
489         private void ComboBoxLanguuage_SelectedIndexChanged(object sender, EventArgs e)
490         {
491             try
492             {
493                 // 変更前の設定を保存
494                 if (!String.IsNullOrEmpty(this.comboBoxLanguageSelectedText))
495                 {
496                     // 設定が存在しなければ自動生成される
497                     this.SaveChangedValue(this.GetMediaWikiNeedCreate(this.config.Websites, this.comboBoxLanguageSelectedText));
498                 }
499
500                 // 変更後の値に応じて、画面表示を更新
501                 if (!String.IsNullOrEmpty(this.comboBoxLanguage.Text))
502                 {
503                     // 設定が存在しなければ基本的に自動生成されるのでそのまま使用
504                     this.LoadCurrentValue(this.GetMediaWikiNeedCreate(this.config.Websites, this.comboBoxLanguage.Text));
505
506                     // 各入力欄を有効に
507                     this.buttonLanguageRemove.Enabled = true;
508                     this.groupBoxServer.Enabled = true;
509                     this.groupBoxLanguage.Enabled = true;
510
511                     // 現在の選択値を更新
512                     this.comboBoxLanguageSelectedText = this.comboBoxLanguage.Text;
513                 }
514                 else
515                 {
516                     // 各入力欄を無効に
517                     this.buttonLanguageRemove.Enabled = false;
518                     this.groupBoxServer.Enabled = false;
519                     this.groupBoxLanguage.Enabled = false;
520
521                     // 現在の選択値を更新
522                     this.comboBoxLanguageSelectedText = String.Empty;
523                 }
524             }
525             catch (Exception ex)
526             {
527                 // 通常この処理では例外は発生しないはず。想定外のエラー用
528                 FormUtils.ErrorDialog(Resources.ErrorMessageDevelopmentError, ex.Message, ex.StackTrace);
529             }
530         }
531
532         /// <summary>
533         /// 言語の追加ボタン押下時の処理。
534         /// </summary>
535         /// <param name="sender">イベント発生オブジェクト。</param>
536         /// <param name="e">発生したイベント。</param>
537         private void ButtonLunguageAdd_Click(object sender, EventArgs e)
538         {
539             // 言語追加用ダイアログを表示
540             InputLanguageCodeDialog form = new InputLanguageCodeDialog(this.config);
541             form.ShowDialog();
542
543             // 値が登録された場合
544             if (!String.IsNullOrWhiteSpace(form.LanguageCode))
545             {
546                 // 値を一覧・見出しの対訳表に追加、登録した値を選択状態に変更
547                 this.comboBoxLanguage.Items.Add(form.LanguageCode);
548                 this.dataGridViewHeading.Columns.Add(form.LanguageCode, form.LanguageCode);
549                 this.comboBoxLanguage.SelectedItem = form.LanguageCode;
550             }
551         }
552
553         /// <summary>
554         /// 言語の削除ボタン押下時の処理。
555         /// </summary>
556         /// <param name="sender">イベント発生オブジェクト。</param>
557         /// <param name="e">発生したイベント。</param>
558         private void ButtonLanguageRemove_Click(object sender, EventArgs e)
559         {
560             // 表示されている言語を設定から削除する
561             for (int i = this.config.Websites.Count - 1; i >= 0; i--)
562             {
563                 if (this.config.Websites[i].Language.Code == this.comboBoxLanguage.Text)
564                 {
565                     // 万が一複数あれば全て削除
566                     this.config.Websites.RemoveAt(i);
567                 }
568             }
569
570             // コンボボックスからも削除し、表示を更新する
571             this.comboBoxLanguageSelectedText = null;
572             this.comboBoxLanguage.Items.Remove(this.comboBoxLanguage.Text);
573             this.ComboBoxLanguuage_SelectedIndexChanged(sender, e);
574         }
575
576         /// <summary>
577         /// 各名前空間のIDボックスバリデート処理。
578         /// </summary>
579         /// <param name="sender">イベント発生オブジェクト。</param>
580         /// <param name="e">発生したイベント。</param>
581         private void TextBoxNamespace_Validating(object sender, CancelEventArgs e)
582         {
583             // 空か数値のみ許可
584             TextBox box = (TextBox)sender;
585             box.Text = StringUtils.DefaultString(box.Text).Trim();
586             int value;
587             if (!String.IsNullOrEmpty(box.Text) && !int.TryParse(box.Text, out value))
588             {
589                 this.errorProvider.SetError(box, Resources.WarningMessageIgnoreNumericNamespace);
590                 e.Cancel = true;
591             }
592         }
593
594         /// <summary>
595         /// 括弧のスタイルボックスバリデート処理。
596         /// </summary>
597         /// <param name="sender">イベント発生オブジェクト。</param>
598         /// <param name="e">発生したイベント。</param>
599         private void TextBoxBracket_Validating(object sender, CancelEventArgs e)
600         {
601             // 空か$1が含まれる文字列のみ許可
602             TextBox box = (TextBox)sender;
603             if (!String.IsNullOrEmpty(box.Text) && !box.Text.Contains("$1"))
604             {
605                 this.errorProvider.SetError(box, Resources.WarningMessageUnformatedBracket);
606                 e.Cancel = true;
607             }
608         }
609
610         /// <summary>
611         /// 言語の設定表の行編集時のバリデート処理。
612         /// </summary>
613         /// <param name="sender">イベント発生オブジェクト。</param>
614         /// <param name="e">発生したイベント。</param>
615         private void DataGridViewLanguageName_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
616         {
617             DataGridViewRow row = this.dataGridViewLanguageName.Rows[e.RowIndex];
618
619             // 空行(新規行など)の場合無視
620             if (FormUtils.IsEmptyRow(row))
621             {
622                 return;
623             }
624
625             // 言語コードは必須、またトリムして小文字に変換
626             string code = FormUtils.ToString(row.Cells["ColumnCode"]).Trim().ToLower();
627             row.Cells["ColumnCode"].Value = code;
628             if (String.IsNullOrEmpty(code))
629             {
630                 row.ErrorText = Resources.WarningMessageEmptyCodeColumn;
631                 e.Cancel = true;
632                 return;
633             }
634
635             // 略称を設定する場合、呼称を必須とする
636             if (!String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnShortName"]))
637                 && String.IsNullOrWhiteSpace(FormUtils.ToString(row.Cells["ColumnName"])))
638             {
639                 row.ErrorText = Resources.WarningMessageShortNameColumnOnly;
640                 e.Cancel = true;
641             }
642         }
643
644         /// <summary>
645         /// 言語の設定表バリデート処理。
646         /// </summary>
647         /// <param name="sender">イベント発生オブジェクト。</param>
648         /// <param name="e">発生したイベント。</param>
649         private void DataGridViewLanguageName_Validating(object sender, CancelEventArgs e)
650         {
651             // 言語コードの重複チェック
652             IDictionary<string, int> codeMap = new Dictionary<string, int>();
653             for (int i = 0; i < this.dataGridViewLanguageName.RowCount - 1; i++)
654             {
655                 string code = FormUtils.ToString(this.dataGridViewLanguageName["ColumnCode", i]);
656                 int y;
657                 if (codeMap.TryGetValue(code, out y))
658                 {
659                     // 重複の場合、両方の行にエラーを設定
660                     this.dataGridViewLanguageName.Rows[i].ErrorText = Resources.WarningMessageDuplicateCodeColumn;
661                     this.dataGridViewLanguageName.Rows[y].ErrorText = Resources.WarningMessageDuplicateCodeColumn;
662                     e.Cancel = true;
663                 }
664                 else
665                 {
666                     // それ以外はマップに出現行とともに追加
667                     codeMap[code] = i;
668                 }
669             }
670         }
671
672         #region イベント実装支援用メソッド
673
674         /// <summary>
675         /// コレクションから指定された言語のMediaWikiを取得する。
676         /// 存在しない場合は空のインスタンスを生成、コレクションに追加して返す。
677         /// </summary>
678         /// <param name="collection">翻訳元言語。</param>
679         /// <param name="lang">言語コード。</param>
680         /// <returns>翻訳パターン。存在しない場合は新たに作成した翻訳パターンを返す。</returns>
681         private MediaWiki GetMediaWikiNeedCreate(ICollection<Website> collection, string lang)
682         {
683             // 設定が存在すれば取得した値を返す
684             foreach (Website s in collection)
685             {
686                 if (s.Language.Code == lang)
687                 {
688                     if (s is MediaWiki)
689                     {
690                         return s as MediaWiki;
691                     }
692
693                     // 万が一同じ言語コードで違う型の値があったら上書き
694                     collection.Remove(s);
695                     break;
696                 }
697             }
698
699             // 存在しないか上書きの場合、作成した翻訳パターンをコレクションに追加し、返す
700             MediaWiki site = new MediaWiki(new Language(lang));
701             collection.Add(site);
702             return site;
703         }
704
705         /// <summary>
706         /// 指定されたLanguage設定を画面表示/編集用に読み込む。
707         /// </summary>
708         /// <param name="lang">読込元Language設定。</param>
709         /// <remarks>一部パラメータには初期値が存在するが、格納時に対処するため全て読み込む。</remarks>
710         private void LoadCurrentValue(Language lang)
711         {
712             // 言語情報を読み込み
713             // ※ Bracketは初期値があるパラメータのため、必ず値が返る
714             this.textBoxBracket.Text = lang.Bracket;
715
716             // 呼称の情報を表に設定
717             this.dataGridViewLanguageName.Rows.Clear();
718             foreach (KeyValuePair<string, Language.LanguageName> name in lang.Names)
719             {
720                 int index = this.dataGridViewLanguageName.Rows.Add();
721                 this.dataGridViewLanguageName["ColumnCode", index].Value = name.Key;
722                 this.dataGridViewLanguageName["ColumnName", index].Value = name.Value.Name;
723                 this.dataGridViewLanguageName["ColumnShortName", index].Value = name.Value.ShortName;
724             }
725         }
726
727         /// <summary>
728         /// 指定されたWebsite設定を画面表示/編集用に読み込む。
729         /// </summary>
730         /// <param name="site">読込元Website設定。</param>
731         private void LoadCurrentValue(Website site)
732         {
733             // Languageクラス分の読み込みを行う
734             this.LoadCurrentValue(site.Language);
735
736             // サイト情報を読み込み
737             this.textBoxLocation.Text = site.Location;
738         }
739
740         /// <summary>
741         /// 指定されたMediaWiki設定を画面表示/編集用に読み込む。
742         /// </summary>
743         /// <param name="site">読込元MediaWiki設定。</param>
744         /// <remarks>一部パラメータには初期値が存在するが、格納時に対処するため全て読み込む。</remarks>
745         private void LoadCurrentValue(MediaWiki site)
746         {
747             // Websiteクラス分の読み込みを行う
748             this.LoadCurrentValue((Website)site);
749
750             // MediaWikiクラス分の読み込み
751             this.textBoxExportPath.Text = StringUtils.DefaultString(site.ExportPath);
752             this.textBoxMetaApi.Text = StringUtils.DefaultString(site.MetaApi);
753             this.textBoxTemplateNamespace.Text = site.TemplateNamespace.ToString();
754             this.textBoxCategoryNamespace.Text = site.CategoryNamespace.ToString();
755             this.textBoxFileNamespace.Text = site.FileNamespace.ToString();
756             this.textBoxRedirect.Text = StringUtils.DefaultString(site.Redirect);
757
758             // Template:Documentionは改行区切りのマルチテキストとして扱う
759             StringBuilder b = new StringBuilder();
760             foreach (string s in site.DocumentationTemplates)
761             {
762                 b.Append(s).Append(Environment.NewLine);
763             }
764
765             this.textBoxDocumentationTemplate.Text = b.ToString();
766             this.textBoxDocumentationTemplateDefaultPage.Text = StringUtils.DefaultString(site.DocumentationTemplateDefaultPage);
767             this.textBoxLinkInterwikiFormat.Text = StringUtils.DefaultString(site.LinkInterwikiFormat);
768             this.textBoxLangFormat.Text = StringUtils.DefaultString(site.LangFormat);
769         }
770
771         /// <summary>
772         /// 指定されたLanguage設定に画面上で変更された値の格納を行う。
773         /// </summary>
774         /// <param name="lang">格納先Language設定。</param>
775         /// <remarks>一部パラメータには初期値が存在するため、変更がある場合のみ格納する。</remarks>
776         private void SaveChangedValue(Language lang)
777         {
778             // Bracketは初期値を持つパラメータのため、変更された場合のみ格納する。
779             // ※ この値は前後の空白に意味があるため、Trimしてはいけない
780             string str = StringUtils.DefaultString(this.textBoxBracket.Text);
781             if (str != lang.Bracket)
782             {
783                 lang.Bracket = str;
784             }
785
786             // 表から呼称の情報も保存
787             this.dataGridViewLanguageName.Sort(this.dataGridViewLanguageName.Columns["ColumnCode"], ListSortDirection.Ascending);
788             lang.Names.Clear();
789             for (int y = 0; y < this.dataGridViewLanguageName.RowCount - 1; y++)
790             {
791                 // 値が入ってないとかはガードしているはずだが、一応チェック
792                 string code = FormUtils.ToString(this.dataGridViewLanguageName["ColumnCode", y]).Trim();
793                 if (!String.IsNullOrEmpty(code))
794                 {
795                     Language.LanguageName name = new Language.LanguageName();
796                     name.Name = FormUtils.ToString(this.dataGridViewLanguageName["ColumnName", y]).Trim();
797                     name.ShortName = FormUtils.ToString(this.dataGridViewLanguageName["ColumnShortName", y]).Trim();
798                     lang.Names[code] = name;
799                 }
800             }
801         }
802
803         /// <summary>
804         /// 指定されたWebsite設定に画面上で変更された値の格納を行う。
805         /// </summary>
806         /// <param name="site">格納先Website設定。</param>
807         /// <remarks>Websiteについては特に特殊な処理は無いため全て上書きする。</remarks>
808         private void SaveChangedValue(Website site)
809         {
810             // Languageクラス分の設定を行う
811             this.SaveChangedValue(site.Language);
812
813             // サイト情報を格納
814             site.Location = StringUtils.DefaultString(this.textBoxLocation.Text).Trim();
815         }
816
817         /// <summary>
818         /// 指定されたMediaWiki設定に画面上で変更された値の格納を行う。
819         /// </summary>
820         /// <param name="site">格納先MediaWiki設定。</param>
821         /// <remarks>一部パラメータには初期値が存在するため、変更がある場合のみ格納する。</remarks>
822         private void SaveChangedValue(MediaWiki site)
823         {
824             // Websiteクラス分の設定を行う
825             this.SaveChangedValue((Website)site);
826
827             // 初期値を持つパラメータがあるため、全て変更された場合のみ格納する。
828             // ※ もうちょっと綺麗に書きたかったが、うまい手が思いつかなかったので力技
829             //    MediaWikiクラス側で行わないのは、場合によっては意図的に初期値と同じ値を設定すること
830             //    もありえるから(初期値が変わる可能性がある場合など)。
831             string str = StringUtils.DefaultString(this.textBoxExportPath.Text).Trim();
832             if (str != site.ExportPath)
833             {
834                 site.ExportPath = str;
835             }
836             
837             str = StringUtils.DefaultString(this.textBoxMetaApi.Text).Trim();
838             if (str != site.MetaApi)
839             {
840                 site.MetaApi = str;
841             }
842
843             str = StringUtils.DefaultString(this.textBoxRedirect.Text).Trim();
844             if (str != site.Redirect)
845             {
846                 site.Redirect = str;
847             }
848
849             // Template:Documentionの設定は行ごとに格納
850             // ※ この値は初期値を持たないパラメータ
851             site.DocumentationTemplates.Clear();
852             foreach (string s in StringUtils.DefaultString(this.textBoxDocumentationTemplate.Text).Split('\n'))
853             {
854                 if (!String.IsNullOrWhiteSpace(s))
855                 {
856                     site.DocumentationTemplates.Add(s.Trim());
857                 }
858             }
859
860             str = StringUtils.DefaultString(this.textBoxDocumentationTemplateDefaultPage.Text).Trim();
861             if (str != site.DocumentationTemplateDefaultPage)
862             {
863                 site.DocumentationTemplateDefaultPage = str;
864             }
865
866             str = StringUtils.DefaultString(this.textBoxLinkInterwikiFormat.Text).Trim();
867             if (str != site.LinkInterwikiFormat)
868             {
869                 site.LinkInterwikiFormat = str;
870             }
871
872             str = StringUtils.DefaultString(this.textBoxLangFormat.Text).Trim();
873             if (str != site.LangFormat)
874             {
875                 site.LangFormat = str;
876             }
877
878             // 以下、数値へのparseは事前にチェックしてあるので、ここではチェックしない
879             if (!String.IsNullOrWhiteSpace(this.textBoxTemplateNamespace.Text))
880             {
881                 int num = int.Parse(this.textBoxTemplateNamespace.Text);
882                 if (site.TemplateNamespace != num)
883                 {
884                     site.TemplateNamespace = num;
885                 }
886             }
887
888             if (!String.IsNullOrWhiteSpace(this.textBoxCategoryNamespace.Text))
889             {
890                 int num = int.Parse(this.textBoxCategoryNamespace.Text);
891                 if (site.CategoryNamespace != num)
892                 {
893                     site.CategoryNamespace = num;
894                 }
895             }
896
897             if (!String.IsNullOrWhiteSpace(this.textBoxFileNamespace.Text))
898             {
899                 int num = int.Parse(this.textBoxFileNamespace.Text);
900                 if (site.FileNamespace != num)
901                 {
902                     site.FileNamespace = num;
903                 }
904             }
905         }
906
907         #endregion
908
909         #endregion
910
911         #region その他タブのイベントのメソッド
912         
913         /// <summary>
914         /// キャッシュ有効期限ボックスバリデート処理。
915         /// </summary>
916         /// <param name="sender">イベント発生オブジェクト。</param>
917         /// <param name="e">発生したイベント。</param>
918         private void TextBoxCacheExpire_Validating(object sender, CancelEventArgs e)
919         {
920             // 値が0以上の数値かをチェック
921             this.TextBoxGreaterThanValidating((TextBox)sender, e, 0, Resources.WarningMessageIgnoreCacheExpire);
922         }
923
924         /// <summary>
925         /// リトライ回数ボックスバリデート処理。
926         /// </summary>
927         /// <param name="sender">イベント発生オブジェクト。</param>
928         /// <param name="e">発生したイベント。</param>
929         private void TextBoxMaxConnectRetries_Validating(object sender, CancelEventArgs e)
930         {
931             // 値が0以上の数値かをチェック
932             this.TextBoxGreaterThanValidating((TextBox)sender, e, 0, Resources.WarningMessageIgnoreMaxConnectRetries);
933         }
934
935         /// <summary>
936         /// ウェイト時間ボックスバリデート処理。
937         /// </summary>
938         /// <param name="sender">イベント発生オブジェクト。</param>
939         /// <param name="e">発生したイベント。</param>
940         private void TextBoxConnectRetryTime_Validating(object sender, CancelEventArgs e)
941         {
942             // 値が0以上の数値かをチェック
943             this.TextBoxGreaterThanValidating((TextBox)sender, e, 0, Resources.WarningMessageIgnoreConnectRetryTime);
944         }
945
946         /// <summary>
947         /// ウェブサイトURLクリック時の処理。
948         /// </summary>
949         /// <param name="sender">イベント発生オブジェクト。</param>
950         /// <param name="e">発生したイベント。</param>
951         private void LinkLabelWebsite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
952         {
953             // リンクを開く
954             System.Diagnostics.Process.Start(((LinkLabel)sender).Text);
955         }
956
957         #region イベント実装支援用メソッド
958
959         /// <summary>
960         /// メッセージのみ差し替え可能なテキストボックス用の値がxx以上の数値か、のバリデート処理。
961         /// </summary>
962         /// <param name="box">イベント発生テキストボックス。</param>
963         /// <param name="e">発生したイベント。</param>
964         /// <param name="num">比較対象の数値。</param>
965         /// <param name="message">バリデートメッセージ。</param>
966         private void TextBoxGreaterThanValidating(TextBox box, CancelEventArgs e, int num, string message)
967         {
968             box.Text = StringUtils.DefaultString(box.Text).Trim();
969             int value;
970             if (!int.TryParse(box.Text, out value) || value < num)
971             {
972                 this.errorProvider.SetError(box, message);
973                 e.Cancel = true;
974             }
975         }
976
977         #endregion
978
979         #endregion
980
981         #region 共通のイベントメソッド
982
983         /// <summary>
984         /// 汎用のエラープロバイダ初期化処理。
985         /// </summary>
986         /// <param name="sender">イベント発生オブジェクト。</param>
987         /// <param name="e">発生したイベント。</param>
988         private void ResetErrorProvider_Validated(object sender, EventArgs e)
989         {
990             this.errorProvider.SetError((Control)sender, null);
991         }
992
993         /// <summary>
994         /// 汎用の行編集時のエラーテキスト初期化処理。
995         /// </summary>
996         /// <param name="sender">イベント発生オブジェクト。</param>
997         /// <param name="e">発生したイベント。</param>
998         private void ResetErrorText_RowValidated(object sender, DataGridViewCellEventArgs e)
999         {
1000             ((DataGridView)sender).Rows[e.RowIndex].ErrorText = String.Empty;
1001         }
1002
1003         /// <summary>
1004         /// 汎用のテーブルエラーテキスト初期化処理。
1005         /// </summary>
1006         /// <param name="sender">イベント発生オブジェクト。</param>
1007         /// <param name="e">発生したイベント。</param>
1008         private void ResetErrorText_Validated(object sender, EventArgs e)
1009         {
1010             // 全行のエラーメッセージを解除
1011             foreach (DataGridViewRow row in ((DataGridView)sender).Rows)
1012             {
1013                 row.ErrorText = String.Empty;
1014             }
1015         }
1016
1017         #endregion
1018
1019         #region 内部クラス
1020
1021         /// <summary>
1022         /// 記事の置き換え対訳表の日付並び替え用クラスです。
1023         /// </summary>
1024         /// <remarks>取得日時の降順でソート、空の列は先頭にします。</remarks>
1025         public class TranslationDictionaryViewComparer : System.Collections.IComparer
1026         {
1027             /// <summary>
1028             /// 2行を比較し、一方が他方より小さいか、等しいか、大きいかを示す値を返します。
1029             /// </summary>
1030             /// <param name="y">比較する最初の行です。</param>
1031             /// <param name="x">比較する 2 番目の行。</param>
1032             /// <returns>1以下:xはyより小さい, 0:等しい, 1以上:xはyより大きい</returns>
1033             public int Compare(object y, object x)
1034             {
1035                 string xstr = ObjectUtils.ToString(((DataGridViewRow)x).Cells["ColumnTimestamp"].Value);
1036                 string ystr = ObjectUtils.ToString(((DataGridViewRow)y).Cells["ColumnTimestamp"].Value);
1037                 if (String.IsNullOrWhiteSpace(xstr) && String.IsNullOrWhiteSpace(ystr))
1038                 {
1039                     return 0;
1040                 }
1041                 else if (String.IsNullOrWhiteSpace(xstr))
1042                 {
1043                     return 1;
1044                 }
1045                 else if (String.IsNullOrWhiteSpace(ystr))
1046                 {
1047                     return -1;
1048                 }
1049
1050                 return xstr.CompareTo(ystr);
1051             }
1052         }
1053
1054         #endregion
1055     }
1056 }