/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */

/*
    Rosegarden
    A MIDI and audio sequencer and musical notation editor.
    Copyright 2000-2026 the Rosegarden development team.
 
    Other copyrights also apply to some parts of this work.  Please
    see the AUTHORS file and individual file headers for details.
 
    This program 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 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/

#define RG_MODULE_STRING "[SegmentTool]"

#include "SegmentTool.h"

#include "misc/Debug.h"
#include "misc/ConfigGroups.h"
#include "CompositionView.h"
#include "document/RosegardenDocument.h"
#include "document/CommandHistory.h"
#include "gui/application/RosegardenMainWindow.h"
#include "gui/general/BaseTool.h"
#include "gui/seqmanager/SequenceManager.h"
#include "SegmentToolBox.h"
#include "document/Command.h"

#include <QMenu>
#include <QMouseEvent>
#include <QSettings>


namespace Rosegarden
{

SegmentTool::SegmentTool(CompositionView* canvas, RosegardenDocument *doc)
        : BaseTool("SegmentTool", canvas),
        m_canvas(canvas),
        m_doc(doc)
{
    //RG_DEBUG << "SegmentTool::SegmentTool()";

    // Set up the actions for the right-click context menu.  Note that
    // all of these end up simply delegating to RosegardenMainWindow.

    createAction("edit_default", &SegmentTool::slotEdit);

    createAction("edit_matrix", &SegmentTool::slotEditInMatrix);
    createAction("edit_percussion_matrix", &SegmentTool::slotEditInPercussionMatrix);
    createAction("edit_notation", &SegmentTool::slotEditAsNotation);
    createAction("edit_event_list", &SegmentTool::slotEditInEventList);
    createAction("edit_pitch_tracker", &SegmentTool::slotEditInPitchTracker);

    // Can we get some of the following connectionless mojo for some
    // of these others too?
    // The undo and redo actions are available globally through
    // CommandHistory.  See ActionFileParser::findStandardAction() which
    // allows them to be found easily.  Since disparate parts of the
    // system need the exact same QAction objects, it might be a good
    // idea to introduce a global QAction repository for all QAction
    // objects.  RosegardenMainWindow might suffice.  This would also
    // simplify the implementation of a shortcut manager.

    //createAction("edit_undo", ...);  // handled by CommandHistory
    //createAction("edit_redo", ...);  // handled by CommandHistory

    createAction("edit_cut", &SegmentTool::slotEditCut);
    createAction("edit_copy", &SegmentTool::slotEditCopy);
    createAction("edit_paste", &SegmentTool::slotEditPaste);

    createAction("delete", &SegmentTool::slotDeleteSelectedSegments);
    createAction("join_segments", &SegmentTool::slotJoinSegments);

    createAction("quantize_selection", &SegmentTool::slotQuantizeSelection);
    createAction("repeat_quantize", &SegmentTool::slotRepeatQuantizeSelection);
    createAction("relabel_segment", &SegmentTool::slotRelabelSegments);
    createAction("transpose", &SegmentTool::slotTransposeSegments);

    createAction("select", &SegmentTool::slotPointerSelected);
    createAction("draw", &SegmentTool::slotDrawSelected);
    createAction("erase", &SegmentTool::slotEraseSelected);
    createAction("move", &SegmentTool::slotMoveSelected);
    createAction("resize", &SegmentTool::slotResizeSelected);
    createAction("split", &SegmentTool::slotSplitSelected);

    // ??? What about join?
    //createAction("join", &RosegardenMainWindow::slotJoinSelected);

}

void SegmentTool::ready()
{
    m_canvas->viewport()->setCursor(Qt::ArrowCursor);
}

void
SegmentTool::mousePressEvent(QMouseEvent *e)
{
    // We only care about the right button for displaying the context
    // menu that is common to all derived tools.
    if (e->button() != Qt::RightButton)
        return;

    if (m_changingSegment) // mouse button is pressed for some tool
        return ;

    // No need to propagate.
    e->accept();

    QPoint pos = m_canvas->viewportToContents(e->pos());

    setChangingSegment(m_canvas->getModel()->getSegmentAt(pos));

    if (m_changingSegment) {
        if (!m_canvas->getModel()->isSelected(m_changingSegment->getSegment())) {

            m_canvas->getModel()->clearSelected();
            m_canvas->getModel()->setSelected(m_changingSegment->getSegment());
            m_canvas->getModel()->selectionHasChanged();
        }
    }

    // Update context menu items before displaying them.

    // ??? Much of this is duplicated from the main window (RMW).  Can we
    //     do better?

    // See RosegardenMainWindow::updateActions().

    QSettings settings;
    settings.beginGroup(GeneralOptionsConfigGroup);
    bool enableEditingDuringPlayback =
            settings.value("enableEditingDuringPlayback", false).toBool();

    bool playing = (RosegardenMainWindow::self()->getSequenceManager()->
                getTransportStatus() == PLAYING);

    bool haveSelection = m_canvas->getModel()->haveSelection();

    findAction("delete")->setEnabled(
            (enableEditingDuringPlayback || !playing)  &&  haveSelection);
    findAction("edit_cut")->setEnabled(
            (enableEditingDuringPlayback || !playing)  &&  haveSelection);

    // RMW's "have_segments" state.
    const bool haveSegments =
            (m_doc->getComposition().getSegments().size() != 0);
    findAction("erase")->setEnabled(haveSegments);
    findAction("move")->setEnabled(haveSegments);
    findAction("resize")->setEnabled(haveSegments);
    findAction("split")->setEnabled(haveSegments);

    // Display the context menu.
    showMenu();

    setChangingSegment(ChangingSegmentPtr());
}

void
SegmentTool::createMenu()
{
    // New version based on the one in MatrixTool.

    //RG_DEBUG << "SegmentTool::createMenu() " << rcFileName << " - " << m_menuName;

    if (!createMenusAndToolbars("segmenttool.rc")) {
        RG_WARNING << "createMenu(): menu creation failed";
        m_menu = nullptr;
        return;
    }

    QMenu *menu = findMenu(m_menuName);
    if (!menu) {
        RG_WARNING << "createMenu(): menu name " << m_menuName << " not created by RC file";
        return;
    }

    m_menu = menu;
}

void SegmentTool::setChangingSegment(ChangingSegmentPtr changingSegment)
{
    if (changingSegment != m_changingSegment)
    {
        m_changingSegment = changingSegment;
    }
}

void SegmentTool::setSnapTime(QMouseEvent *e, timeT snapTime)
{
    SnapGrid &snapGrid = m_canvas->grid();

    // If shift isn't being held down
    if ((e->modifiers() & Qt::ShiftModifier) == 0) {
        snapGrid.setSnapTime(snapTime);
    } else {
        snapGrid.setSnapTime(SnapGrid::NoSnap);
    }
}

void SegmentTool::slotEdit()
{
    RosegardenMainWindow::self()->slotEdit();
}
void SegmentTool::slotEditInMatrix()
{
    RosegardenMainWindow::self()->slotEditInMatrix();
}
void SegmentTool::slotEditInPercussionMatrix()
{
    RosegardenMainWindow::self()->slotEditInPercussionMatrix();
}
void SegmentTool::slotEditAsNotation()
{
    RosegardenMainWindow::self()->slotEditAsNotation();
}
void SegmentTool::slotEditInEventList()
{
    RosegardenMainWindow::self()->slotEditInEventList();
}
void SegmentTool::slotEditInPitchTracker()
{
    RosegardenMainWindow::self()->slotEditInPitchTracker();
}
void SegmentTool::slotEditCut()
{
    RosegardenMainWindow::self()->slotEditCut();
}
void SegmentTool::slotEditCopy()
{
    RosegardenMainWindow::self()->slotEditCopy();
}
void SegmentTool::slotEditPaste()
{
    RosegardenMainWindow::self()->slotEditPaste();
}
void SegmentTool::slotDeleteSelectedSegments()
{
    RosegardenMainWindow::self()->slotDeleteSelectedSegments();
}
void SegmentTool::slotJoinSegments()
{
    RosegardenMainWindow::self()->slotJoinSegments();
}
void SegmentTool::slotQuantizeSelection()
{
    RosegardenMainWindow::self()->slotQuantizeSelection();
}
void SegmentTool::slotRepeatQuantizeSelection()
{
    RosegardenMainWindow::self()->slotRepeatQuantizeSelection();
}
void SegmentTool::slotRelabelSegments()
{
    RosegardenMainWindow::self()->slotRelabelSegments();
}
void SegmentTool::slotTransposeSegments()
{
    RosegardenMainWindow::self()->slotTransposeSegments();
}

void SegmentTool::slotPointerSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("select");
    // Trigger it.
    if (action)
        action->trigger();
}

void SegmentTool::slotDrawSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("draw");
    // Trigger it.
    if (action)
        action->trigger();
}

void SegmentTool::slotEraseSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("erase");
    // Trigger it.
    if (action)
        action->trigger();
}

void SegmentTool::slotMoveSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("move");
    // Trigger it.
    if (action)
        action->trigger();
}

void SegmentTool::slotResizeSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("resize");
    // Trigger it.
    if (action)
        action->trigger();
}

void SegmentTool::slotSplitSelected()
{
    // Since these tool actions can be checked/unchecked, we can't just
    // simply call their slots in RMW.  We have to trigger them or
    // else the toolbar buttons will not be pressed/unpressed properly.

    // Get the action from RMW.
    QAction *action =
            RosegardenMainWindow::self()->findAction("split");
    // Trigger it.
    if (action)
        action->trigger();
}


}

