#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_pUrlEdit = NULL;
    //初始化
    InitAllUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitAllUI()
{
    setWindowTitle("Waiting ......");
    QUrl uHome = QUrl::fromUserInput("www.baidu.com");
    //设置地址栏
    m_pUrlEdit = new QLineEdit(this);
    m_pUrlEdit->setText(uHome.toString());
    //地址栏信号
    connect(m_pUrlEdit, SIGNAL(returnPressed()), this, SLOT(onUrlEdited()));
    connect(ui->webView, SIGNAL(urlChanged(QUrl)), this, SLOT(onUrlChanged(QUrl)));
    //点击网页链接时加载
    connect(ui->webView, SIGNAL(linkClicked(QUrl)), this, SLOT(onLinkClicked(QUrl)));
    //鼠标悬浮在链接上
    connect(ui->webView->page(), SIGNAL(linkHovered(QString,QString,QString)),
            this, SLOT(onLinkHovered(QString,QString,QString)));
    //添加到工具条
    ui->mainToolBar->insertWidget(ui->action_Refresh, m_pUrlEdit);

    //网页链接被点击时，发送 linkClicked(QUrl) 信号
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    //关联信号和槽函数
    connect(ui->action_Refresh, SIGNAL(triggered()), ui->webView, SLOT(reload()));
    connect(ui->action_Stop, SIGNAL(triggered()), ui->webView, SLOT(stop()));
    connect(ui->action_Backward, SIGNAL(triggered()), ui->webView, SLOT(back()));
    connect(ui->action_Forward, SIGNAL(triggered()), ui->webView, SLOT(forward()));
    //退出信号
    connect(ui->action_Quit, SIGNAL(triggered()), qApp, SLOT(quit()));
    //自动更新标题栏
    connect(ui->webView, SIGNAL(titleChanged(QString)), this, SLOT(setWindowTitle(QString)));
    //
    ui->webView->load(uHome);
}
//根据用户输入的网址加载
void MainWindow::onUrlEdited()
{
    QUrl url = QUrl::fromUserInput( m_pUrlEdit->text() );
    ui->webView->load( url );
    qDebug()<<"User Input: " <<url;
}
//更新地址栏
void MainWindow::onUrlChanged(const QUrl &url)
{
    m_pUrlEdit->setText( url.toString() );
    qDebug()<<"Url Changed: "<<url;
}
//点击链接时加载新的网页
void MainWindow::onLinkClicked(const QUrl &url)
{
    m_pUrlEdit->setText( url.toString() );
    ui->webView->load(url);
    qDebug()<<"Link Clicked: "<<url;
}
//鼠标悬浮在链接上
void MainWindow::onLinkHovered(const QString &link, const QString &title, const QString &textContent)
{
    ui->statusBar->showMessage(link);
}
