#include <vcl.h>
#pragma hdrstop

#include "main.h"
#include "ChildFrm.h"
#include "aboutDlg.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

#pragma link "ecActns"
#pragma link "ecAutoReplace"
#pragma link "ecKeyMap"
#pragma link "ecPopupCtrl"
#pragma link "ecPrint"
#pragma link "ecPropManager"
#pragma link "ecSpell"
#pragma link "ecStylesCombo"
#pragma link "ecSyntAnal"
#pragma link "ecSyntDlg"
#pragma link "ecSyntMemo"
#pragma link "ecSyntTree"

TSyntEditMain *SyntEditMain;
//---------------------------------------------------------------------------
__fastcall TSyntEditMain::TSyntEditMain(TComponent* Owner)
		: TForm(Owner)
{
//  TControlHack(Splitter1)->OnMouseDown = SplitterMouseDown;
  FHyperlinkHlt = True;
#ifdef USE_RX_LIB
  FormPlacement = new TFormPlacement(this);
  FormPlacement->Name = "FormPlacement";
  FormPlacement->IniFileName = ChangeFileExt(Application->ExeName, "->ini");
  FormPlacement->IniSection = "MainForm";
  MRU = new TMRUManager(this);
  MRU->Name = "MRU";
  MRU->AccelDelimiter = adSpace;
  MRU->Capacity = 9;
  MRU->RecentMenu = Reopen1;
  MRU->OnClick = MRUClick;
  MRU->IniStorage = FormPlacement;
  Reopen1->Visible = True;
  FormPlacement->RestoreFormPlacement;
#endif
}

//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::LoadTreeImages()
{
  // Loading tree images
  AnsiString s = ExtractFilePath(Application->ExeName) + "ecTreeImg->bmp";
  if( FileExists(s) )
   try
   {
     Graphics::TBitmap *bmp = new Graphics::TBitmap;
     try
     {
       bmp->LoadFromFile(s);
     }
     catch(...)
     {
       delete bmp;
       return;
     }
     if(bmp->Empty) return;
     TColor c = bmp->Canvas->Pixels[0][0];
     delete bmp;
     if(TreeImageList->GetInstRes(0, rtBitmap, s, 16, (TLoadResources() << lrFromFile), c))
       SyntaxTreeView1->Images = TreeImageList;
   }
   catch(...)
   {
   }
}
//---------------------------------------------------------------------------
void __fastcall LoadFile(TLoadableComponent *Comp, const AnsiString AFileName)
{
  if(FileExists(AFileName))
    try
    {
      Comp->LoadFromFile(AFileName);
    }
    catch(...)
    {
      Application->HandleException(SyntEditMain);
    }
}

void __fastcall TSyntEditMain::FormShow(TObject *Sender)
{
  DragAcceptFiles(Handle, True);
  Caption = AnsiString("EControl syntax") +
#ifdef EC_UNICODE
  " (unicode)" +
#endif
  " editor";

  LoadLanguages();
  PropsManager1->LoadProps();
  PropsManager1->UpdateAll();
  PropsManager2->LoadProps();
  LoadFile(SyntaxManager1, ExtractFilePath(Application->ExeName) + "LexLib.LXL");
  LoadFile(SyntStyles1, ChangeFileExt(Application->ExeName, ".ecs"));
  LoadTreeImages();
//  LoadFile(SharedStyles, ChangeFileExt(Application->ExeName, "->ess"));
  AnsiString s = ChangeFileExt(Application->ExeName, ".ari");
  if(FileExists(s))
   SyntAutoReplace1->Items->LoadFromFile(s);

  FReadOnly = (ParamCount() > 1) && SameText(ParamStr(2), "r");
  if(FReadOnly) FileExitAction->ShortCut = VK_ESCAPE;

  ecDictionary1->LoadCfg(ChangeFileExt(Application->ExeName, ".ini"));

  if(ParamCount() > 0) OpenFile(ParamStr(1));
    else CreateFrame("");
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::FormClose(TObject *Sender, TCloseAction &Action)
{
//  CloseAll(False);
  CurrentEditor = 0;
#ifdef USE_RX_LIB
  FormPlacement->SaveFormPlacement();
#endif
  PropsManager1->SaveProps();
  PropsManager2->SaveProps();
  SyntStyles1->SaveToFile(ChangeFileExt(Application->ExeName, ".ecs"));
//  SharedStyles->SaveToFile(ChangeFileExt(Application->ExeName, "->ess"));
  SyntAutoReplace1->Items->SaveToFile(ChangeFileExt(Application->ExeName, ".ari"));
  ecDictionary1->SaveCfg(ChangeFileExt(Application->ExeName, ".ini"));
}
//---------------------------------------------------------------------------
TEditorFrame* __fastcall TSyntEditMain::OpenFile(const AnsiString AFileName)
{

  // Check, if the file is opened
  for(int i = 0; i < FrameCount; i++)
   if(Frames[i]->IsTheFile(AFileName))
    {
      CurrentFrame = Frames[i];
      return Frames[i];
    }
  // Create new frame and load file
  TEditorFrame* Result;
  if(FrameCount == 1 && Frames[0]->IsNewFile() && !Frames[0]->Modified)
    Result = Frames[0];
  else
    Result = CreateFrame(AFileName);
  Result->LoadFile(AFileName);
  Result->TextSource->SyntaxAnalyzer = SyntaxManager1->AnalyzerForFile(AFileName);
  SyntaxManager1->CurrentLexer = Result->TextSource->SyntaxAnalyzer;
  FrameChanged();
//  Result->ecSpellChecker1->Active = True;
  if( !Result->EditorMaster->Focused())
    Result->EditorMaster->SetFocus();
#ifdef USE_RX_LIB
  MRU->Add(AFileName, 0);
#endif
  return Result;
}
//---------------------------------------------------------------------------
// Save specified frame
void __fastcall TSyntEditMain::SaveFrame(TEditorFrame* Frame, bool PromtDialog)
{
  if(Frame == 0) return;
  if(!PromtDialog)
    PromtDialog = Frame->IsNewFile();
  if( PromtDialog )
    {
      SD->Filter = SyntaxManager1->GetFilesFilter();
      SD->FileName = Frame->FileName;
      if( SD->Execute())
       {
        Frame->SaveFile(SD->FileName);
#ifdef USE_RX_LIB
        if( !Frame->IsTheFile(SD->FileName))
          MRU->Add(SD->FileName, 0);
#endif
       }
    }
  else Frame->SaveFile(Frame->FileName);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::FormCloseQuery(TObject *Sender,
  bool& CanClose)
{
  int ModifiedCount = GetModifiedCount();
  if(ModifiedCount > 0)
    {
      int res = IDYES;
      for(int i = 0; i < FrameCount; i++)
        if( Frames[i]->Modified )
          {
            if(res != mrAll)
              res = PromtToSave(Frames[i], ModifiedCount > 1);
            switch( res )
            {
              case mrYes:
              case mrAll: SaveFrame(Frames[i], False);
                          break;
              case mrCancel:
                         CanClose = False;
                         return;
            }
            ModifiedCount--;
          }
    }

  if(SyntaxManager1->Modified)
   switch( MessageDlg("Save changes to LexLib.lxl?", mtConfirmation, mbYesNoCancel, 0))
   {
    case mrYes:  SyntaxManager1->SaveToFile(ExtractFilePath(Application->ExeName) + "LexLib.LXL");
                 break;
    case mrCancel:
               CanClose = False;
               return;
   }
}
//---------------------------------------------------------------------------
TModalResult __fastcall TSyntEditMain::PromtToSave(TEditorFrame* Frame, bool AllowAll)
{
  TMsgDlgButtons Buttons = mbYesNoCancel;
  if(AllowAll)
    Buttons = Buttons << mbAll;
  return MessageDlg("Save changes to " + ExtractFileName(Frame->FileName) + "?",
     mtConfirmation, Buttons, 0);
}
//---------------------------------------------------------------------------
int __fastcall TSyntEditMain::GetModifiedCount()
{
  int Result = 0;
  for(int i = 0; i < FrameCount; i++)
    if(Frames[i]->Modified)
      Result++;
  return Result;
}
//---------------------------------------------------------------------------
#ifdef USE_RX_LIB
void __fastcall TSyntEditMain::MRUClick(TObject *Sender, const AnsiString RecentName,
  const AnsiString Caption, int UserData)
{
  OpenFile(RecentName);
}
#endif
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSaveUpdate(TObject *Sender)
{
  actSave->Enabled = CurrentFrame && CurrentFrame->Modified;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actNewFileExecute(TObject *Sender)
{
  CreateFrame("");
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actOpenExecute(TObject *Sender)
{
  OD->Filter = SyntaxManager1->GetFilesFilter();
  if( OD->Execute() )
    OpenFile(OD->FileName);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSaveExecute(TObject *Sender)
{
  if( CurrentFrame )
    SaveFrame(CurrentFrame, False);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSaveAsExecute(TObject *Sender)
{
  if( CurrentFrame )
    SaveFrame(CurrentFrame, true);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::About1Click(TObject *Sender)
{
  (new TForm1(this))->ShowModal();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::PrintSetupActionExecute(TObject *Sender)
{
  PrinterSetupDialog1->Execute();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::FileExitActionExecute(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSaveAllUpdate(TObject *Sender)
{
  actSaveAll->Enabled = GetModifiedCount() > 0;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actCloseUpdate(TObject *Sender)
{
  actClose->Enabled = CurrentFrame;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actCloseAllUpdate(TObject *Sender)
{
  actCloseAll->Enabled = FrameCount > 0;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSaveAllExecute(TObject *Sender)
{
  for(int i = 0; i < FrameCount; i++)
    if(Frames[i]->Modified)
      SaveFrame(Frames[i], False);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actCloseExecute(TObject *Sender)
{
  TEditorFrame *Frm = CurrentFrame;
  if(Frm->Modified)
   if(PromtToSave(Frm, False) == mrYes)
     SaveFrame(Frm, False);
  CloseFrame(Frm);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::CloseAll(bool DoPromt)
{
  int ModifiedCount = GetModifiedCount();
  int res = IDYES;
  for(int i = FrameCount - 1; i >= 0; i--)
    {
      if(Frames[i]->Modified)
        {
          if(res != mrAll || !DoPromt)
            res = PromtToSave(Frames[i], ModifiedCount > 1);
          if(res == mrCancel) return;
          if(res != mrNo)
            SaveFrame(Frames[i], False);
          ModifiedCount--;
        }
      CloseFrame(Frames[i]);
    }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actCloseAllExecute(TObject *Sender)
{
  CloseAll(True);
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ChildCloseQuery(TObject *Sender,
  bool& CanClose)
{
  TMDIChild *fm = (TMDIChild *)Sender;
  if(fm->ControlCount > 0)
    {
      TEditorFrame *Frm = (TEditorFrame*)(fm->Controls[0]);
      if(Frm->Modified)
       switch( PromtToSave(Frm, False) )
       {
         case mrYes: SaveFrame(Frm, False); break;
         case mrCancel: CanClose = False; break;
       }
    }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ChildClose(TObject *Sender, TCloseAction& Action)
{
  Action = caFree;
  FrameClosed((TEditorFrame*)(((TForm*)Sender)->Controls[0]));
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actMDIViewUpdate(TObject *Sender)
{
  actMDIView->Checked = MDIView;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actMDIViewExecute(TObject *Sender)
{
  MDIView = !MDIView;
}

//==============================================================================
// Editors management
//==============================================================================
TEditorFrame* __fastcall TSyntEditMain::CreateFrame(const AnsiString FileName)
{
  TEditorFrame* Result = new TEditorFrame(this);
  Result->Name = "";
  Result->OnTitleChanged = TitleChanged;
  Result->EditorSlave->KeyMapping = SyntKeyMapping1;
  Result->EditorMaster->KeyMapping = SyntKeyMapping1;
  CreateBind(Result);
  RegisterNewEditorFrame(Result);
  CurrentFrame = Result;
  Result->HyperlinkHighlighter1->Active = FHyperlinkHlt;
  return Result;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::CreateBind(TEditorFrame* Frame)
{
  if( FMDIView )
    {
      TForm *frm = new TMDIChild(this, Frame);
      frm->Caption = Frame->Title;
      frm->OnCloseQuery = ChildCloseQuery;
      frm->OnClose = ChildClose;
    }
  else
    {
      TTabSheet *tab = new TTabSheet(this);
      tab->PageControl = PageControl1;
      tab->Caption = Frame->Title;
      Frame->Parent = tab;
    }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::RegisterNewEditorFrame(TEditorFrame* Frame)
{
  PropsManager1->Add(Frame->EditorSlave);
  PropsManager1->Add(Frame->EditorMaster);

  Frame->EditorMaster->ReadOnly = FReadOnly;
  Frame->EditorMaster->OnIncSearchChange = SyntaxMemo1IncSearchChange;

  Frame->EditorSlave->ReadOnly = FReadOnly;
  Frame->EditorSlave->OnIncSearchChange = SyntaxMemo1IncSearchChange;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetCurrentEditor(TSyntaxMemo *Value)
{
  if(FCurrentEditor == Value) return;
  ecSyntPrinter1->SyntMemo = Value;
  SyntAutoReplace1->SyntMemo = Value;
  TemplatePopup1->SyntMemo = Value;
  SyntFindDialog1->Control = Value;
  SyntReplaceDialog1->Control = Value;
  UserStylesCombo1->Editor = Value;
  ecCustomizeLexerPropertiesAction1->SyntMemo = Value;
  if(SyntaxTreeView1->Width == 0) SyntaxTreeView1->SyntaxMemo = 0; else
   if( !(!SyntaxTreeView1->AutoSynchronize && Value &&
       FCurrentEditor && Value->Parent == FCurrentEditor->Parent))
    SyntaxTreeView1->SyntaxMemo = Value;
  FCurrentEditor = Value;
  if(FCurrentEditor && !FCurrentEditor->Focused())
    FCurrentEditor->SetFocus();
  if(FCurrentEditor)
   {
    UpdateStatusBar(FCurrentEditor);
    if(FCurrentEditor->SyntObj)
      SyntaxManager1->CurrentLexer = FCurrentEditor->SyntObj->Owner;
    else
      SyntaxManager1->CurrentLexer = 0;
   }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetCurrentFrame(TEditorFrame *Value)
{
  if( FMDIView )
    Value->Parent->SetFocus();
  else
    PageControl1->ActivePage = (TTabSheet*)Value->Parent;
  FrameChanged();
}
//---------------------------------------------------------------------------
TEditorFrame* __fastcall TSyntEditMain::GetCurrentFrame()
{
  if(FMDIView)
    {
      if(ActiveMDIChild)
        return (TEditorFrame*)ActiveMDIChild->Controls[0];
    }
  else
    {
      if(PageControl1->ActivePage )
        return (TEditorFrame*)PageControl1->ActivePage->Controls[0];
    }
  return 0;
}
//---------------------------------------------------------------------------
int __fastcall TSyntEditMain::GetFrameCount()
{
  if( FMDIView )
    return MDIChildCount;
  else
    return PageControl1->PageCount;
}
//---------------------------------------------------------------------------
TEditorFrame* __fastcall TSyntEditMain::GetFrames(int Index)
{
  if( FMDIView )
    return (TEditorFrame*)MDIChildren[Index]->Controls[0];
  else
    return (TEditorFrame*)PageControl1->Pages[Index]->Controls[0];
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::FrameChanged()
{
  TEditorFrame *frm = CurrentFrame;
  if( frm )
   {
     SyntaxManager1->CurrentLexer = frm->TextSource->SyntaxAnalyzer;
      if(FMDIView && ((TForm*)frm->Parent)->ActiveControl->InheritsFrom(__classid(TSyntaxMemo)))
        CurrentEditor = (TSyntaxMemo*)((TForm*)frm->Parent)->ActiveControl;
      else
        CurrentEditor = frm->EditorMaster;
     ecSyntPrinter1->Title = frm->Title;
     Application->Title = frm->Title;

      if(TreeImageList->Count > 0 && frm->TextSource->SyntaxAnalyzer)
      {
        TSyntAnalyzer *sa = frm->TextSource->SyntaxAnalyzer;
        for(int i = 0; i < sa->BlockRules->Count; i++)
         if(sa->BlockRules->Items[i]->TreeItemImage != -1 ||
            sa->BlockRules->Items[i]->TreeGroupImage != -1)
          {
            SyntaxTreeView1->Images = TreeImageList;
            return;
          }
      }
      SyntaxTreeView1->Images = 0;
   }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::FrameClosed(TEditorFrame *Frame)
{
  if(CurrentEditor && CurrentEditor->Parent == Frame)
    CurrentEditor = 0;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::PageControl1Change(TObject *Sender)
{
  FrameChanged();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::CloseFrame(TEditorFrame *Frame)
{
  CurrentEditor = 0;
  if(Frame->Parent->InheritsFrom(__classid(TTabSheet)))
   {
//    FrameClosed(Frame);
    TTabSheet *ts = (TTabSheet*)Frame->Parent;
    delete Frame;
    delete ts;
   }
  else
    ((TForm*)Frame->Parent)->Close();
  // Empty new doc after close all
  if(!FMDIView && PageControl1->PageCount == 0)
   CreateFrame("");
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetMDIView(const bool Value)
{
  if(FMDIView != Value)
    {
      FMDIView = Value;
      WindowMenu->Visible = FMDIView;
      if(FMDIView)
        {
          PageControl1->SetFocus();
          PageControl1->Visible = False;
          for(int i = PageControl1->PageCount - 1; i >= 0; i--)
           {
            CreateBind((TEditorFrame*)PageControl1->Pages[i]->Controls[0]);
            delete PageControl1->Pages[i];
           }
          Color = clAppWorkSpace;
        }
      else
        {
          Color = clBtnFace;
          for(int i = MDIChildCount - 1; i >= 0; i--)
            {
              CreateBind((TEditorFrame*)MDIChildren[i]->Controls[0]);
              delete MDIChildren[i];
            }
          PageControl1->Visible = True;
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::TitleChanged(TObject *Sender)
{
  TEditorFrame *frm = CurrentFrame;
  if(frm == Sender)
    {
     ecSyntPrinter1->Title = frm->Title;
     Application->Title = frm->Title;
    }
}
//==============================================================================
// Localization
//==============================================================================
// Loads *->lng files
void __fastcall TSyntEditMain::LoadLanguages()
{
  AnsiString Dir = ExtractFileDir(Application->ExeName);
  TSearchRec F;
  try
  {
    int R = FindFirst(Dir + "\*.lng", faAnyFile, F);
    while( R == 0 )
     {
       AnsiString S = ExtractFileName(F.Name);
       int R = S.Pos(".");
       if( R > 1 ) S = S.SubString(1, R - 1);
       TMenuItem *mi = new TMenuItem(this);
       mi->Caption = "&" + S;
       mi->RadioItem = True;
       mi->OnClick = LocalizeClick;
       Language1->Add(mi);
       R = FindNext(F);
     }
  }
  __finally
  {
    FindClose(F);
  }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::LocalizeClick(TObject *Sender)
{
#ifdef USE_LOCALIZER
  if(FLocalizer)
    FLocalizer = new TecLocalizer(this);

  AnsiString fn = ExtractFilePath(Application->ExeName) +
        RemoveAmpersand(((TMenuItem*)Sender)->Caption) + ".lng";
  FLocalizer->Properties->LoadFromFile(fn);
  if(FLocalizer->Properties->Count > 0)
   try
   {
     FLocalizer->Charset = StrToInt(FLocalizer->Properties->Strings[0]);
   }
   catch(...){ }
  LocalizeObject(this);

  for(int i = 0; i < Language1->Count; i++)
    Language1->Items[i]->Checked = Language1->Items[i] == Sender;
#endif
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ecCustomizeLexerPropertiesAction1ExecuteOK(
  TObject *Sender)
{
  SyntaxManager1->Modified = True;
}
//---------------------------------------------------------------------------
AnsiString __fastcall TSyntEditMain::GetLanguage()
{
  for(int i = 0; i < Language1->Count; i++)
    if( Language1->Items[i]->Checked )
      return RemoveAmpersand(Language1->Items[i]->Caption);
  return "";
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetLanguage(AnsiString Value)
{
  Value = RemoveAmpersand(Value);
  for(int i = 0; i < Language1->Count; i++)
  {
    TMenuItem *mi = Language1->Items[i];
    if(SameText(RemoveAmpersand(mi->Caption), Value))
     {
      LocalizeClick(mi);
      return;
     }
  }
}

//==============================================================================
// Common editor"s event handlers
//==============================================================================
void __fastcall TSyntEditMain::UpdateStatusBar(TObject *Sender)
{
   TSyntaxMemo *m = (TSyntaxMemo *)Sender;
   SB->Panels->Items[0]->Text = "  " + IntToStr((int)m->CaretPos.x)+ ": " + IntToStr((int)m->CaretPos.y);
   if(m->Modified) SB->Panels->Items[1]->Text = "Modified";
             else  SB->Panels->Items[1]->Text = "";
   if(m->ReplaceMode) SB->Panels->Items[2]->Text = "Overwrite";
                 else SB->Panels->Items[2]->Text = "Insert";
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SyntaxMemo1IncSearchChange(TObject *Sender,
  TIncSearchState State)
{
  TSyntaxMemo *m = (TSyntaxMemo *)Sender;
  if( State == isStart)
   {
    m->IncSearchBack = SyntFindDialog1->Flags.Contains(ftBackward);
    m->IncSearchIgnoreCase = !SyntFindDialog1->Flags.Contains(ftCaseSensitive);
   }
  if( State != isStop)
    SB->SimpleText = "Search for: " + m->IncSearchStr;
  else
   SB->SimpleText = "";
  SB->SimplePanel = State != isStop;
}

//==============================================================================
// Other event handlers
//==============================================================================
void __fastcall TSyntEditMain::SyntaxManager1LexerChanged(TObject *Sender)
{
  if (CurrentFrame )
    CurrentFrame->TextSource->SyntaxAnalyzer = SyntaxManager1->CurrentLexer;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::Sharedstyles1Click(TObject *Sender)
{
  if(SharedStyles->Customize())
   ApplySharedStyles();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ApplySharedStyles()
{

  for(int i = 0; i < SyntaxManager1->AnalyzerCount; i++)
  {
    TStylesCollection *sc = SyntaxManager1->Analyzers[i]->Formats;
    for( int j = 0; j < sc->Count; j++)
     {
       TSyntaxFormat *f = (TSyntaxFormat*)SharedStyles->Styles->ItemByName(sc->Items[j]->DisplayName);
       if(f)
        sc->Items[j]->Assign(f);
     }
  }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ActionList1Update(TBasicAction *Action, bool &Handled)
{
  if( Action == FileExitAction)
   {
    bool en = CurrentFrame != 0;
    FormatMenu->Enabled = en;
    EncodingMenu->Enabled = en;
    if(en)
      {
        TSyntTextSource *ts = CurrentFrame->TextSource;
        for(int i = 0; i < FormatMenu->Count; i++)
          FormatMenu->Items[i]->Checked =
            int(ts->Lines->TextFormat) == FormatMenu->Items[i]->Tag;
        for(int i = 0; i < EncodingMenu->Count; i++)
          EncodingMenu->Items[i]->Checked =
            int(ts->Lines->TextCoding) == EncodingMenu->Items[i]->Tag;
      }
   }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetEncoding(TObject *Sender)
{
  TTextCoding te = TTextCoding(((TMenuItem*)Sender)->Tag);
  TEditorFrame *cf = CurrentFrame;
  if( cf && te != cf->TextSource->Lines->TextCoding)
      {
        cf->TextSource->Lines->TextCoding = te;
        cf->Modified = True;
      }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetFormat(TObject *Sender)
{
  Ecstrutils::TTextFormat tf = Ecstrutils::TTextFormat(((TMenuItem*)(Sender))->Tag);
  TEditorFrame *cf = CurrentFrame;
  if( cf )
    if( tf != cf->TextSource->Lines->TextFormat)
      {
        cf->TextSource->Lines->TextFormat = tf;
        cf->Modified = True;
      }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SplitterMouseDown(TObject *Sender,
  TMouseButton Button, TShiftState Shift, int X, int Y)
{
  if(!SyntaxTreeView1->Visible || SyntaxTreeView1->Width == 0)
   {
    SyntaxTreeView1->Left = 0;
    Splitter1->Left = 1;
   }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ecCustomizeEditorOptionsAction1ExecuteOK(TObject *Sender)
{
  PropsManager1->UpdateAll();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ToolbarPopupPopup(TObject *Sender)
{
  ToolbarPopup->Items->Clear();
  int N = ComponentCount;
  for(int i = 0; i < N; i++)
   if(Components[i]->ClassNameIs("TToolBar"))
    {
      TToolBar *t = (TToolBar*)Components[i];
      TMenuItem* mi = new TMenuItem(this);
      mi->Caption = t->Caption;
      mi->Checked = t->Visible;
      mi->Tag = int(t);
      mi->OnClick = ShowToolbar;
      ToolbarPopup->Items->Add(mi);
    }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::ShowToolbar(TObject *Sender)
{
  TToolBar *t = (TToolBar*)(((TComponent*)Sender)->Tag);
  t->Visible = !t->Visible;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSortTreeUpdate(TObject *Sender)
{
  actSortTree->Checked = SyntaxTreeView1->SortType == Comctrls::stText;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actSortTreeExecute(TObject *Sender)
{
  if(SyntaxTreeView1->SortType == Comctrls::stText)
    {
      SyntaxTreeView1->SortType = Comctrls::stNone;
      SyntaxTreeView1->UpdateTree();
    }
  else
    SyntaxTreeView1->SortType = Comctrls::stText;
}
//---------------------------------------------------------------------------
// Processing single instance message
void __fastcall TSyntEditMain::WndProc(TMessage &Message)
{
  char PC[MAX_PATH];
  switch( Message.Msg )
  {
	case WM_DROPFILES:
       {
         int N = DragQueryFile((HDROP)Message.WParam, 0xFFFFFFFF, 0, 0);
         for(int i = 0; i < N - 1; i++)
          if(DragQueryFile((HDROP)Message.WParam, i, PC, MAX_PATH) > 0)
           try
           {
             OpenFile(PC);
           }
           catch(...)
           {
           }
         DragFinish((HDROP)Message.WParam);
         break;
       }
    default: TForm::WndProc(Message);
  }
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actDictionariesExecute(TObject *Sender)
{
  ecDictionary1->Customize();
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::Splitter1Moved(TObject *Sender)
{
  if(SyntaxTreeView1->Width == 0 || CurrentEditor == NULL)
    SyntaxTreeView1->SyntaxMemo = 0;
  else
    SyntaxTreeView1->SyntaxMemo = CurrentEditor;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::SetHyperlinkHlt(const bool Value)
{
  FHyperlinkHlt = Value;
  for(int i = 0; i < FrameCount - 1; i++)
   Frames[i]->HyperlinkHighlighter1->Active = FHyperlinkHlt;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actShowHyperlinksUpdate(TObject *Sender)
{
  actShowHyperlinks->Checked = HyperlinkHlt;
}
//---------------------------------------------------------------------------
void __fastcall TSyntEditMain::actShowHyperlinksExecute(TObject *Sender)
{
  HyperlinkHlt = !HyperlinkHlt;
}
//---------------------------------------------------------------------------

