/////////////////////////////////////////////////////////////////////////////
// Name:        minimal.cpp
// Purpose:     Minimal wxWindows sample
// Author:      Julian Smart
// Modified by:
// Created:     04/01/98
// RCS-ID:      $Id: minimal.cpp,v 1.1 2001/04/22 20:02:11 aleksandras Exp $
// Copyright:   (c) Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#ifdef __GNUG__
    #pragma implementation "minimal.cpp"
    #pragma interface "minimal.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWindows headers
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif

// ----------------------------------------------------------------------------
// ressources
// ----------------------------------------------------------------------------
// the application icon
#if defined(__WXGTK__) || defined(__WXMOTIF__)
    #include "mondrian.xpm"
#endif

#include "tdefs.h"

// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------

// Define a new application type, each program should derive a class from wxApp
class MyApp : public wxApp
{
public:
    // override base class virtuals
    // ----------------------------

    // this one is called on application startup and is a good place for the app
    // initialization (doing it here and not in the ctor allows to have an error
    // return: if OnInit() returns false, the application terminates)
    virtual bool OnInit();
};

enum
{
	ID_EDIT_UNDO = 3300,
	ID_EDIT_REDO,		  
	ID_EDIT_FIND,		  
 	ID_EDIT_FIND_NEXT,
	ID_EDIT_GOTO,		  
	ID_EDIT_TOGGLE_BM,  
	ID_EDIT_NEXT_BM,	  
	ID_EDIT_PREV_BM,	  
 	ID_EDIT_TOGGLE_BRKPNT,
	ID_OPEN,
	ID_SAVE
};

// Define a new frame type: this is going to be our main frame
class MyFrame : public wxFrame
{
public:
    // ctor(s)
    MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
	~MyFrame();

    // event handlers (these functions should _not_ be virtual)
    void OnQuit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);

	void OnUndo( wxCommandEvent& event );
	void OnUndoUI( wxUpdateUIEvent& event );

	void OnToggleBookmark( wxCommandEvent& event );
	void OnNextBookmark( wxCommandEvent& event );
	void OnPreviousBookmark( wxCommandEvent& event );
	void OnToggleBreakpoint( wxCommandEvent& event );
	void OnFind( wxCommandEvent& event );
	void OnFindNext( wxCommandEvent& event );
	void OnGotoLine( wxCommandEvent& event );
	void OnSave( wxCommandEvent& event );
	void OnOpen( wxCommandEvent& event );


private:
    // any class wishing to process wxWindows events must use this macro
    DECLARE_EVENT_TABLE()

protected:

	wxTextEditorModel* mpModel;
	wxTextEditorView*  mpView;
	wxString           mFname;
};

// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------

// IDs for the controls and the menu commands
enum
{
    // menu items
    Minimal_Quit = 1,
    Minimal_About,
    Minimal_Test1,
    Minimal_Test2,

	Minimal_Undo,

    // controls start here (the numbers are, of course, arbitrary)
    Minimal_Text = 1000,
};

// ----------------------------------------------------------------------------
// event tables and other macros for wxWindows
// ----------------------------------------------------------------------------

// the event tables connect the wxWindows events with the functions (event
// handlers) which process them. It can be also done at run-time, but for the
// simple menu events like this the static method is much simpler.
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
    EVT_MENU(Minimal_Quit,  MyFrame::OnQuit)
    EVT_MENU(Minimal_About, MyFrame::OnAbout)

	EVT_MENU(Minimal_Undo,   MyFrame::OnUndo)
	EVT_UPDATE_UI(Minimal_Undo, MyFrame::OnUndoUI)


	EVT_MENU( ID_EDIT_TOGGLE_BM, MyFrame::OnToggleBookmark )
	EVT_MENU( ID_EDIT_NEXT_BM,   MyFrame::OnNextBookmark   )
	EVT_MENU( ID_EDIT_PREV_BM,   MyFrame::OnPreviousBookmark   )
	EVT_MENU( ID_EDIT_FIND,      MyFrame::OnFind )
	EVT_MENU( ID_EDIT_FIND_NEXT, MyFrame::OnFindNext )
	EVT_MENU( ID_EDIT_GOTO,      MyFrame::OnGotoLine )

	EVT_MENU( ID_EDIT_TOGGLE_BRKPNT, MyFrame::OnToggleBreakpoint )

	EVT_MENU( ID_OPEN,  MyFrame::OnOpen  )
	EVT_MENU( ID_SAVE,  MyFrame::OnSave  )

	
END_EVENT_TABLE()

// Create a new application object: this macro will allow wxWindows to create
// the application object during program execution (it's better than using a
// static object for many reasons) and also declares the accessor function
// wxGetApp() which will return the reference of the right type (i.e. MyApp and
// not wxApp)
IMPLEMENT_APP(MyApp)

// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// the application class
// ----------------------------------------------------------------------------

// `Main program' equivalent: the program execution "starts" here
bool MyApp::OnInit()
{
    // Create the main application window
    MyFrame *frame = new MyFrame("Minimal wxWindows App",
                                 wxPoint(50, 50), wxSize(450, 340));

    // Show it and tell the application that it's our main window
    // @@@ what does it do exactly, in fact? is it necessary here?
    frame->Show(TRUE);
    SetTopWindow(frame);

    // success: wxApp::OnRun() will be called which will enter the main message
    // loop and the application will run. If we returned FALSE here, the
    // application would exit immediately.
    return TRUE;
}

// ----------------------------------------------------------------------------
// main frame
// ----------------------------------------------------------------------------

// frame constructor
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
       : wxFrame((wxFrame *)NULL, -1, title, pos, size),
	     mFname( "untitled.txt" )
{
    // set the frame icon
    SetIcon(wxICON(mondrian));

    // create a menu bar
    wxMenu* menuFile = new wxMenu;
	wxMenu*	editMenu = new wxMenu;

    menuFile->Append(Minimal_About, "&About...", "Show about dialog", "Alt+A" );
	menuFile->Append( ID_OPEN, "&Open...");
	menuFile->Append( ID_SAVE, "&Save...");
    menuFile->AppendSeparator();
    menuFile->Append(Minimal_Quit, "E&xit", "Quit this program");


	/////// edit menu ////////

	editMenu->Append( Minimal_Undo, "&Undo\tAlt+Backspace or Ctrl+Z" );
	editMenu->AppendSeparator();
	editMenu->Append( ID_EDIT_TOGGLE_BM, "&Toggle Bookmark" );
	editMenu->Append( ID_EDIT_NEXT_BM,   "&Next Bookmark" );
	editMenu->Append( ID_EDIT_PREV_BM,   "&Previous Bookmark" );
	editMenu->AppendSeparator();
	editMenu->Append( ID_EDIT_FIND,      "&Find..."      );
	editMenu->Append( ID_EDIT_FIND_NEXT, "Find N&ext"        );
	editMenu->Append( ID_EDIT_GOTO,      "&Goto Line..." );
	editMenu->AppendSeparator();
	editMenu->Append( ID_EDIT_TOGGLE_BRKPNT,      "Toggle &Breakpoint" );



    // now append the freshly created menu to the menu bar...
    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
	menuBar->Append(editMenu, "&Edit");

    // ... and attach this menu bar to the frame
    SetMenuBar(menuBar);

    // create a status bar just for fun (by default with 1 pane only)
    CreateStatusBar(2);
    SetStatusText("Welcome to wxWindows!");

	
	// wxWin-2.0 does not propagate Alt+key storkes, thus we
	//  define accelerators to catch them!

	wxAcceleratorEntry entries[1];

	entries[0].Set( wxACCEL_ALT, WXK_BACK,  Minimal_Undo );

	wxAcceleratorTable accel(1, entries);
	SetAcceleratorTable(accel);

	////// creating sample editor ///////

	mpModel = new wxTextEditorModel();
	mpView  = new wxTextEditorView( this, -1, mpModel, wxSUNKEN_BORDER, 
									TRUE // destroys model when view is destroyed
								  );

	mpModel->AddView( mpView );
	mpView->Activate();

	// optional...
	mpView->AddPinPainter( new TBreakpointPainter() );
	mpView->AddPinPainter( new TBookmarkPainter()   );

	mpView->LoadBgImage( "gnome_bg.bmp" );

	mpModel->AppendText( "Hello\nWorld of\nText!" );

	// should be called after creating editor window
	// or modifying it's content non-interactively

	mpView->SyncScrollbars();
}

MyFrame::~MyFrame()
{
	delete mpView;
}

void MyFrame::OnUndo( wxCommandEvent& event )
{
	mpModel->OnUndo();
}

void MyFrame::OnUndoUI( wxUpdateUIEvent& event )
{
	event.Enable( mpModel->CanUndo() );
}

// event handlers

void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
    // TRUE is to force the frame to close
    Close(TRUE);
}

void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
    wxString msg;
    msg.Printf("This is a sample demo of wx-based text editor.\n"
               "CurrentVersion is %d.%d", 
			   WXTEXTEDITOR_VERSION_MAJOR,
			   WXTEXTEDITOR_VERSION_MINOR );

    wxMessageBox(msg, "About cross-platfrom text editor widget!", wxOK | wxICON_INFORMATION, this);
}

void MyFrame::OnToggleBookmark( wxCommandEvent& event )
{
	mpModel->OnToggleBookmark();
}

void MyFrame::OnNextBookmark( wxCommandEvent& event )
{
	mpModel->OnNextBookmark();
}

void MyFrame::OnPreviousBookmark( wxCommandEvent& event )
{
	mpModel->OnPreviousBookmark();
}

void MyFrame::OnToggleBreakpoint( wxCommandEvent& event )
{
	// FOR NOW:: just to show off breakpoint-pins

	size_t curRow = mpModel->GetCursor().mRow;

	if ( mpModel->GetPinAt( curRow, TBreakpointPin::GetPinTypeCode() ) != NULL )

		mpModel->RemovePinAt( curRow, TBreakpointPin::GetPinTypeCode() );
	else
		mpModel->AddPin( new TBreakpointPin( curRow ) );

	mpView->Refresh();
}

void MyFrame::OnSave( wxCommandEvent& event )
{
	if ( mFname == "untitled.txt" )
	{
		wxFileDialog dialog( NULL, "Save as...", "", mFname,
							 "",
							 wxSAVE|wxOVERWRITE_PROMPT );

		dialog.Center( wxBOTH );

		if ( dialog.ShowModal() == wxID_OK )
		
			mFname = dialog.GetFilename();
		else
			return;
	}

	mpModel->SaveTextToFile( mFname );

	SetTitle( mFname );
	SetStatusText( mFname + " saved" );
}

void MyFrame::OnOpen( wxCommandEvent& event )
{
	// TBD:: save modifications of current file

	wxFileDialog dialog( NULL, "Open...", "", "", "*.*" );
	dialog.Center( wxBOTH );

	if ( dialog.ShowModal() == wxID_OK )
	{
		mFname = dialog.GetFilename();
		mpModel->LoadTextFromFile( mFname );

		SetTitle( mFname );
	}
}

void MyFrame::OnFind( wxCommandEvent& event )
{
	mpModel->OnFind();
}

void MyFrame::OnFindNext( wxCommandEvent& event )
{
	mpModel->OnFindNext();
}

void MyFrame::OnGotoLine( wxCommandEvent& event )
{
	mpModel->OnGotoLine();
}

#ifdef __HACK_MY_MSDEV40__

char wxDummyChar;

#endif
