//
// This File contains the definition of the MGCoordinates-class
//
//   Author: Thomas Bretz
//   Version: V1.0 (1-8-2000)

#include "MGEmbeddedCanvas.h"

#include <iostream>

#include <TList.h>
#include <TCanvas.h>

#undef DEBUG

ClassImp(MGEmbeddedCanvas);

using namespace std;

MGEmbeddedCanvas::MGEmbeddedCanvas(const char *name, const TGWindow* p,
                                   UInt_t width, Double_t range)
    : TRootEmbeddedCanvas(name, p, width+1, width+1, 0/*kRaisedFrame*/),
      fModified(kFALSE), fWidth(width), fRange(fabs(range)), fPix(2.*fabs(range)/width)
{
#ifdef DEBUG
    cout << "MGEmbeddedCanvas: Initializing." << endl;
#endif

    fCanvas = GetCanvas();

#ifdef DEBUG
    cout << "MGEmbeddedCanvas: fCanvas = 0x" << fCanvas << endl;

    cout << "MGEmbeddedCanvas: SetFillColor." << endl;
#endif
    fCanvas->SetFillColor(39); // s. TAttFill
#ifdef DEBUG
    cout << "MGEmbeddedCanvas." << endl;
#endif

    fCanvas->Range(-fRange, -fRange, fRange, fRange);

    fList = new TList;
    fList->SetOwner();

#ifdef DEBUG
    cout << "MGEmbeddedCanvas: Initializing done." << endl;
#endif
}

MGEmbeddedCanvas::~MGEmbeddedCanvas()
{
    delete fList;
}

void MGEmbeddedCanvas::Resize(TGDimension size)
{
    fWidth = size.fWidth;
    fPix = 2.*fRange/size.fWidth;
    TRootEmbeddedCanvas::Resize(size);
}

void MGEmbeddedCanvas::Resize(UInt_t w, UInt_t h)
{
    fWidth = w;
    fPix = 2.*fRange/w;
    TRootEmbeddedCanvas::Resize(w, h);
}

void MGEmbeddedCanvas::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)
{
    fWidth = w;
    fPix = 2.*fRange/w;
    TRootEmbeddedCanvas::MoveResize(x, y, w, h);
}

// ------------------------------------------------------------------------
//
// Map the subwindows, resize to its quadratic size, map the window itself
// and set it to Non-Editable.
//
void MGEmbeddedCanvas::InitCanvas()
{
    MapSubwindows();

    Resize(fWidth, fWidth); //GetDefaultSize()); // ???
    MapWindow();

    fCanvas->SetEditable(kFALSE);
}

void MGEmbeddedCanvas::UpdateCanvas()
{
    if (!fModified)
        return;

    //
    // FIXME: Sometimes (if the canvas couldn't be created correctly:
    // X11 Pixmap error) Update hangs the Gui system.
    //
    // Fixed: By using root 3.01/06 and doing the update from within the
    // mainthread.
    //

    fCanvas->Modified();
    fCanvas->Update();

    fModified = kFALSE;
}

// ------------------------------------------------------------------------
//
//  Set's the kNoContextMenu bit for all primitives in the embedded canvas
//  and the canvas itself, so that no context menu is displayed.
//
void MGEmbeddedCanvas::SetNoContextMenu()
{
    TList &list = *fCanvas->GetListOfPrimitives();
    list.ForEach(TObject, SetBit)(kNoContextMenu);

    fCanvas->SetBit(kNoContextMenu);
}
