#include "DSingleApplication.h"

#include <QFileInfo>
#include <QWidget>

DSingleApplication::DSingleApplication(int &argc, char **argv)
    :QApplication(argc, argv),
     m_pMainForm(NULL),
     m_isRunning(false),
     m_localServer(NULL)
{
    // 取应用程序名作为LocalServer的名字
    m_serverName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();

    _InitLocalConnection();
}


bool DSingleApplication::IsRunning()
{
    return m_isRunning;
}

void DSingleApplication::SetMainForm(QWidget *pMainForm)
{
    m_pMainForm = pMainForm;
    return;
}

void DSingleApplication::_onNewLocalConnection()
{
    _ActivateWindow();
    return;
}

void DSingleApplication::_InitLocalConnection()
{
   m_isRunning = false;

   QLocalSocket socket;
   socket.connectToServer(m_serverName);
   if(socket.waitForConnected(500))
   {
       m_isRunning = true;
       return;
   }


   //连接不上服务器，就创建一个
   _NewLocalServer();
}

void DSingleApplication::_NewLocalServer()
{
    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()), this, SLOT(_onNewLocalConnection()));
    if(!m_localServer->listen(m_serverName))
    {
        // 此时监听失败，可能是程序崩溃时,残留进程服务导致的,移除之
        if(m_localServer->serverError() == QAbstractSocket::AddressInUseError)
        {
            QLocalServer::removeServer(m_serverName);
            m_localServer->listen(m_serverName); // 再次监听
        }
    }
}

void DSingleApplication::_ActivateWindow()
{
    if(NULL!=m_pMainForm)
    {
        m_pMainForm->show();
        m_pMainForm->raise();
        m_pMainForm->activateWindow();
    }
    return;
}
