2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@sns.it>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
11 #include "mainwindow.h"
12 #include <boost/scoped_ptr.hpp>
14 #include <kstandardaction.h>
15 #include <kactioncollection.h>
19 #include <kfiledialog.h>
20 #include <kio/netaccess.h>
21 #include <kmessagebox.h>
23 #include <QKeySequence>
24 #include <QStackedWidget>
25 #include <QDockWidget>
26 #include <QCloseEvent>
27 #include <QTextStream>
29 #include <ktabwidget.h>
30 #include "chesstable.h"
36 #include "controllers/editgame.h"
37 #include "controllers/editposition.h"
38 #include "engineinfo.h"
39 #include "movelist_table.h"
40 #include "icsconnection.h"
42 #include "mastersettings.h"
45 #include "pgnparser.h"
46 #include "pref_highlight.h"
47 #include "pref_preferences.h"
50 using namespace boost
;
52 MainWindow::~MainWindow() {
57 MainWindow::MainWindow(const QString
& variant
)
59 setObjectName("tagua_main");
60 m_main
= new KTabWidget(this);
61 setCentralWidget(m_main
);
63 m_movelist_stack
= new QStackedWidget
;
65 connect(m_main
, SIGNAL(currentChanged(int)),
66 this, SLOT(changeTab(int)));
67 connect(m_main
, SIGNAL(closeTab()),
68 this, SLOT(closeTab()));
70 movelist_dock
= new QDockWidget(this);
71 movelist_dock
->setWidget(m_movelist_stack
);
72 movelist_dock
->setWindowTitle(i18n("Move list"));
73 movelist_dock
->setObjectName("move_list");
74 addDockWidget(Qt::LeftDockWidgetArea
, movelist_dock
, Qt::Vertical
);
75 movelist_dock
->show();
77 ChessTable
* board
= new ChessTable
;
81 console_dock
= new QDockWidget(this);
82 console
= new Console(0, i18n("FICS Connection"));
83 console_dock
->setWidget(console
);
84 console_dock
->setFocusProxy(console
);
85 console_dock
->setWindowTitle(i18n("Console"));
86 console_dock
->setObjectName("console");
87 addDockWidget(Qt::BottomDockWidgetArea
, console_dock
, Qt::Horizontal
);
88 console_dock
->setWindowFlags(console_dock
->windowFlags() & ~Qt::WindowStaysOnTopHint
);
91 connect(board
, SIGNAL(error(ErrorCode
)), this, SLOT(displayErrorMessage(ErrorCode
)));
92 //BROKEN connect(board->clock(), SIGNAL(labelClicked(int)), &ui(), SLOT(setTurn(int)));
94 // start in edit game mode
95 newGame(variant
, AbstractPosition::Ptr());
100 updatePromotionType();
103 ChessTable
* MainWindow::table() {
104 return qobject_cast
<ChessTable
*>(m_main
->currentWidget());
107 KAction
* MainWindow::installRegularAction(const QString
& name
, const KIcon
& icon
, const QString
& text
, QObject
* obj
, const char* slot
) {
108 KAction
* temp
= new KAction(icon
, text
, this);
109 actionCollection()->addAction(name
, temp
);
110 connect(temp
, SIGNAL(triggered(bool)), obj
, slot
);
114 void MainWindow::setupEngineMenu() {
115 QMenu
* engine_menu
= 0;
116 SettingArray engine_settings
= settings().group("engines").array("engine");
117 foreach (Settings s
, engine_settings
) {
119 // this way the menu is created only if there is at least one engine
120 engine_menu
= menuBar()->addMenu(i18n("E&ngines"));
124 EngineDetails engine_details
;
125 s
["name"] >> engine_details
.name
;
126 s
["path"] >> engine_details
.path
;
127 engine_details
.type
= EngineDetails::typeFromName(s
["type"].value
<QString
>());
129 s
["work-path"] >> engine_details
.workPath
;
131 kDebug() << "creating engine " << engine_details
.name
<< endl
;
132 EngineInfo
* engine
= new EngineInfo(engine_details
, ui());
134 m_engines
.push_back(engine
);
136 QMenu
* menu
= engine_menu
->addMenu(engine_details
.name
);
139 KAction
* play_white
= new KAction(i18n("Play as &white"), this);
140 play_white
->setCheckable(true);
141 connect(play_white
, SIGNAL(triggered()), engine
, SLOT(playAsWhite()));
142 menu
->addAction(play_white
);
145 KAction
* play_black
= new KAction(i18n("Play as &black"), this);
146 play_black
->setCheckable(true);
147 connect(play_black
, SIGNAL(triggered()), engine
, SLOT(playAsBlack()));
148 menu
->addAction(play_black
);
150 #if 0 // disable analysis for the moment
152 KAction
* analyze
= new KAction(i18n("&Analyze"), this);
153 analyze
->setCheckable(true);
154 connect(analyze
, SIGNAL(triggered()), engine
, SLOT(analyze()));
155 menu
->addAction(analyze
);
161 void MainWindow::setupActions() {
162 KStandardAction::openNew(this, SLOT(newGame()), actionCollection());
163 KStandardAction::open(this, SLOT(loadGame()), actionCollection());
164 KStandardAction::quit(this, SLOT(quit()), actionCollection());
166 installRegularAction("back", KIcon("go-previous"), i18n("&Back"), &ui(), SLOT(back()));
167 installRegularAction("forward", KIcon("go-next"), i18n("&Forward"), &ui(), SLOT(forward()));
168 installRegularAction("begin", KIcon("go-first"), i18n("Be&gin"), &ui(), SLOT(gotoFirst()));
169 installRegularAction("end", KIcon("go-last"), i18n("&End"), &ui(), SLOT(gotoLast()));
170 installRegularAction("connect", KIcon("connection-established"), i18n("&Connect"), this, SLOT(icsConnect()));
171 installRegularAction("disconnect", KIcon("connect-no"), i18n("&Disconnect"), this, SLOT(icsDisconnect()));
173 KStandardAction::undo(&ui(), SLOT(undo()), actionCollection());
174 KStandardAction::redo(&ui(), SLOT(redo()), actionCollection());
176 installRegularAction("pgnCopy", KIcon("edit-copy"), i18n("Copy PGN"), this, SLOT(pgnCopy()));
177 installRegularAction("pgnPaste", KIcon("edit-paste"), i18n("Paste PGN"), this, SLOT(pgnPaste()));
178 installRegularAction("editPosition", KIcon("edit"), i18n("&Edit position"), this, SLOT(editPosition()));
179 installRegularAction("clearBoard", KIcon("edit-delete"), i18n("&Clear board"), &ui(), SLOT(clearBoard()));
180 installRegularAction("setStartingPosition", KIcon("contents"), i18n("&Set starting position"),
181 &ui(), SLOT(setStartingPosition()));
182 installRegularAction("copyPosition", KIcon(), i18n("&Copy position"), &ui(), SLOT(copyPosition()));
183 installRegularAction("pastePosition", KIcon(), i18n("&Paste position"), &ui(), SLOT(pastePosition()));
184 installRegularAction("flip", KIcon("rotate"), i18n("&Flip view"), this, SLOT(flipView()));
185 installRegularAction("toggleConsole", KIcon("openterm"), i18n("Toggle &console"), this, SLOT(toggleConsole()));
186 installRegularAction("toggleMoveList", KIcon("view_text"), i18n("Toggle &move list"), this, SLOT(toggleMoveList()));
187 installRegularAction("configure", KIcon("configure"), i18n("&Configure Tagua..."), this, SLOT(preferences()));
190 void MainWindow::updatePromotionType() {
191 // TODO: I'm removing this code because it causes a crash
192 // and I don't want to investigate further, since the promotion
193 // stuff needs to be changed completely.
195 int ptype
= m_ui
.promotionType();
197 m_promote_group
->setEnabled(false);
199 m_promote_group
->setEnabled(true);
202 m_promote_queen
->setChecked(true);
205 m_promote_rook
->setChecked(true);
208 m_promote_bishop
->setChecked(true);
211 m_promote_knight
->setChecked(true);
214 m_promote_group
->setEnabled(false);
218 std::cout
<< "do promotion: " << m_ui
.doPromotion() << std::endl
;
219 m_do_promotion
->setChecked(m_ui
.doPromotion());
223 void MainWindow::readSettings() { }
224 void MainWindow::writeSettings() { }
226 void MainWindow::closeEvent(QCloseEvent
* e
) {
233 void MainWindow::keyPressEvent(QKeyEvent
* event
) {
234 if (event
->key() == Qt::Key_F5
) {
235 ui().createCtrlAction();
239 void MainWindow::keyReleaseEvent(QKeyEvent
* event
) {
240 if (event
->key() == Qt::Key_F5
) {
241 ui().destroyCtrlAction();
245 void MainWindow::changeTab(int index
) {
246 m_ui
.setCurrentTab(m_main
->currentWidget());
247 m_movelist_stack
->setCurrentIndex(index
);
248 updatePromotionType();
251 void MainWindow::closeTab() {
252 if (m_main
->count() > 1) {
253 ChessTable
* old_board
= table();
254 m_ui
.removeController(old_board
);
255 m_movelist_stack
->removeWidget(
256 m_movelist_stack
->widget(m_main
->currentIndex()));
257 m_main
->removeTab(m_main
->currentIndex());
261 if (m_main
->count() <= 1) {
262 m_main
->setTabBarHidden(true);
265 // update ui controller (just in case...)
266 m_ui
.setCurrentTab(m_main
->currentWidget());
270 void MainWindow::createTab(ChessTable
* board
, const shared_ptr
<Controller
>& controller
,
271 const QString
& caption
, int index
) {
273 index
= m_main
->addTab(board
, caption
);
275 m_main
->insertTab(index
, board
, caption
);
277 m_main
->setCurrentIndex(index
);
278 m_ui
.addController(board
, controller
);
279 m_ui
.setCurrentTab(board
);
280 m_movelist_stack
->addWidget(board
->moveListTable());
281 m_movelist_stack
->setCurrentIndex(index
);
282 if (m_main
->count() > 1) m_main
->setTabBarHidden(false);
286 void MainWindow::cleanupGame(const QString
& what
, const QString
& result
) {
293 void MainWindow::cleanupGame() {
299 bool MainWindow::newGame(const QString
& variantName
, AbstractPosition::Ptr startingPos
) {
300 VariantPtr variant
= Variants::instance().get(variantName
);
302 WARNING("no variant " << variantName
<< " found");
303 variant
= Variants::instance().get("chess");
307 ChessTable
* board
= new ChessTable
;
308 shared_ptr
<Controller
> controller(new EditGameController(
309 board
, variant
, startingPos
));
310 createTab(board
, controller
,
311 QString("Editing %1 game").arg(variant
->name().toLower()));
315 ERROR("Could not find the chess variant");
322 void MainWindow::editPosition() {
325 shared_ptr
<Controller
> controller(new EditPositionController(table(), ChessVariant::info()));
326 m_main
->setTabText(m_main
->currentIndex(), "Editing chess position");
327 ui().setController(controller
);
331 void MainWindow::setupGame(const GameInfo
* gameInfo
, const PositionInfo
& style12
) {
332 QString variantCode
= gameInfo
->variant();
333 VariantPtr variant
= Variants::instance().get(variantCode
);
334 shared_ptr
<EditGameController
> controller(new EditGameController(
336 Q_ASSERT(style12
.relation
== PositionInfo::NotMyMove
||
337 style12
.relation
== PositionInfo::MyMove
);
340 int side
= (style12
.relation
== PositionInfo::MyMove
^ style12
.turn
== 0) ? 0 : 1;
342 if (controller
->addICSPlayer(side
, style12
.gameNumber
, m_connection
)) {
343 ui().setController(controller
);
344 table()->setPlayers(gameInfo
->white(), gameInfo
->black());
345 m_main
->setTabText(m_main
->currentIndex(),
346 QString("FICS Game - %1 vs %2").arg(style12
.whitePlayer
)
347 .arg(style12
.blackPlayer
));
351 void MainWindow::setupExaminedGame(const GameInfo
* /*gameInfo*/, const PositionInfo
& style12
) {
352 shared_ptr
<EditGameController
> controller(new EditGameController(
353 table(), Variants::instance().get("chess")));
354 if (controller
->setExaminationMode(style12
.gameNumber
, m_connection
)) {
355 table()->setPlayers(Player(style12
.whitePlayer
, -1),
356 Player(style12
.blackPlayer
, -1));
357 ui().setController(controller
);
358 m_main
->setTabText(m_main
->currentIndex(),
359 QString("Examining - %1 vs %2").arg(style12
.whitePlayer
)
360 .arg(style12
.blackPlayer
));
365 void MainWindow::setupObservedGame(const GameInfo
* g
, const PositionInfo
& style12
) {
366 std::auto_ptr
<ChessTable
> board(new ChessTable
);
368 shared_ptr
<EditGameController
> controller(new EditGameController(
369 board
.get(), Variants::instance().get(g
->variant())));
370 if (controller
->setObserveMode(style12
.gameNumber
, m_connection
)) {
371 board
->setPlayers(Player(style12
.whitePlayer
, -1),
372 Player(style12
.blackPlayer
, -1));
373 // ui().setController(controller);
374 //std::cout << "adding tab" << std::endl;
375 createTab(board
.get(), controller
,
376 QString("Observing - %1 vs %2").arg(style12
.whitePlayer
)
377 .arg(style12
.blackPlayer
));
382 void MainWindow::setupPGN(const QString
& s
) {
385 std::map
<QString
, QString
>::const_iterator var
= pgn
.m_tags
.find("Variant");
388 if (var
== pgn
.m_tags
.end()) {
389 variant
= Variants::instance().get("chess");
391 else if (!(variant
= Variants::instance().get(var
->second
))) {
392 std::cout
<< " --> MainWindow::setupPGN: Error, no such variant " << var
->second
<< std::endl
;
396 shared_ptr
<EditGameController
> controller(new EditGameController(
398 ui().setController(controller
);
399 controller
->loadPGN(pgn
);
401 // table()->setPlayers(gameInfo->white(), gameInfo->black());
402 // m_main->setTabText(m_main->currentIndex(),
403 // QString("FICS Game - %1 vs %2").arg(style12.whitePlayer)
404 // .arg(style12.blackPlayer));
407 bool MainWindow::openFile(const QString
& filename
) {
408 QFileInfo
info(filename
);
411 KMessageBox::sorry(this, i18n("You have specified a folder"), i18n("Error"));
415 if(!info
.exists() || !info
.isFile()) {
416 KMessageBox::sorry(this, i18n("The specified file does not exist"), i18n("Error"));
420 QFile
file(filename
);
422 if(!file
.open(QIODevice::ReadOnly
)) {
423 KMessageBox::sorry(this, i18n("You do not have read permission to this file."), i18n("Error"));
427 QTextStream
stream(&file
);
429 codec
= QTextCodec::codecForLocale();
430 stream
.setCodec(codec
);
432 setupPGN(stream
.readAll());
433 //ui().pgnPaste(stream.readAll());
437 void MainWindow::loadGame() {
438 KUrl url
= KFileDialog::getOpenUrl(KUrl(), "*.pgn", this, i18n("Open PGN file"));
444 if (KIO::NetAccess::download(url
, tmp_file
, this)) {
446 KIO::NetAccess::removeTempFile(tmp_file
);
449 KMessageBox::error(this, KIO::NetAccess::lastErrorString());
452 void MainWindow::createConnection(const QString
& username
, const QString
& password
,
453 const QString
& host
, quint16 port
,
454 const QString
& timeseal
, const QString
& timeseal_cmd
) {
455 m_connection
= shared_ptr
<ICSConnection
>(new ICSConnection
);
457 connect(m_connection
.get(), SIGNAL(established()), this, SLOT(onEstablishConnection()));
458 connect(m_connection
.get(), SIGNAL(hostLookup()), this, SLOT(onHostLookup()));
459 connect(m_connection
.get(), SIGNAL(hostFound()), this, SLOT(onHostFound()));
461 connect(m_connection
.get(), SIGNAL(receivedLine(QString
, int)), console
, SLOT(displayText(QString
, int)));
462 connect(m_connection
.get(), SIGNAL(receivedText(QString
, int)), console
, SLOT(displayText(QString
, int)));
464 connect(console
, SIGNAL(receivedInput(const QString
&)), m_connection
.get(), SLOT(sendText(const QString
&)));
465 connect(console
, SIGNAL(notify()), this, SLOT(flash()));
467 connect(m_connection
.get(), SIGNAL(loginPrompt()), this, SLOT(sendLogin()));
468 connect(m_connection
.get(), SIGNAL(registeredNickname()), this, SLOT(sendBlankPassword()));
469 connect(m_connection
.get(), SIGNAL(prompt()), this, SLOT(prompt()));
472 connect(m_connection
.get(), SIGNAL(creatingExaminedGame(const GameInfo
*, const PositionInfo
&)),
473 this, SLOT(setupExaminedGame(const GameInfo
*, const PositionInfo
&)));
474 connect(m_connection
.get(), SIGNAL(endingExaminedGame(int)), this, SLOT(cleanupGame()));
476 connect(m_connection
.get(), SIGNAL(creatingObservedGame(const GameInfo
*, const PositionInfo
&)),
477 this, SLOT(setupObservedGame(const GameInfo
*, const PositionInfo
&)));
478 connect(m_connection
.get(), SIGNAL(endingObservedGame(int)), this, SLOT(cleanupGame()));
481 connect(m_connection
.get(), SIGNAL(creatingGame(const GameInfo
*, const PositionInfo
&)),
482 this, SLOT(setupGame(const GameInfo
*, const PositionInfo
&)));
483 connect(m_connection
.get(), SIGNAL(endingGame(const QString
&, const QString
&)),
484 this, SLOT(cleanupGame(const QString
&, const QString
&)));
485 connect(m_connection
.get(), SIGNAL(notification()), this, SLOT(flash()));
487 m_connection
->establish(host
.toAscii().constData(), port
, timeseal
, timeseal_cmd
);
490 // send username / password combination
491 if (!username
.isEmpty()) {
492 m_connection
->sendText(username
);
493 m_connection
->sendText(password
);
496 quickConnectDialog
.reset();
499 void MainWindow::icsConnect() {
500 quickConnectDialog
= shared_ptr
<QConnect
>(new QConnect(this));
501 connect(quickConnectDialog
.get(),
502 SIGNAL(acceptConnection(const QString
&,
509 SLOT(createConnection(const QString
&,
515 quickConnectDialog
->show();
518 void MainWindow::destroyConnection() {
519 m_connection
.reset();
522 void MainWindow::icsDisconnect() {
528 void MainWindow::testConnect() {
529 Settings s_ics
= settings().group("ics");
530 if (s_ics
["username"]) {
531 QString username
= s_ics
["username"].value
<QString
>();
532 QString password
= (s_ics
["password"] | "");
533 QString host
= (s_ics
["icsHost"] | "freechess.org");
534 quint16 port
= (s_ics
["icsPort"] | 5000);
535 createConnection(username
, password
, host
, port
, QString(), QString() );
541 void MainWindow::onEstablishConnection() {
542 // std::cout << "connection established" << std::endl;
545 void MainWindow::onConnectionError(int ) {
546 // std::cout << "connection error (" << code << ")" << std::endl;
549 void MainWindow::onHostLookup() {
550 // std::cout << "hostLookup..." << std::flush;
553 void MainWindow::onHostFound() {
554 // std::cout << "found" << std::endl;
558 void MainWindow::sendLogin() {
559 // std::cout << "sending username" << std::endl;
560 // connection->sendText(connection->username());
563 void MainWindow::sendBlankPassword() {
564 std::cout
<< "sending blank password" << std::endl
;
565 m_connection
->sendText("");
568 void MainWindow::prompt() {
569 if (!m_connection
->initialized()) {
570 m_connection
->startup();
571 m_connection
->setInitialized();
575 void MainWindow::newGame() {
576 AbstractPosition::Ptr pos
= ui().position();
577 scoped_ptr
<NewGame
> dialog(new NewGame(this, pos
));
578 if (dialog
->exec() == QDialog::Accepted
) {
579 if(dialog
->isCustom()) {
580 VariantPtr vi
= Variants::instance().get(dialog
->variant());
581 std::cout
<< "vi[" << dialog
->variant() << "] = " << vi
<< std::endl
;
582 pos
= vi
->createCustomPosition(dialog
->customOptions());
585 else if (!dialog
->playFromCurrent())
586 pos
= AbstractPosition::Ptr();
587 if (!newGame(dialog
->variant(), pos
))
588 QMessageBox::information(this, tr("Error"), tr("Variant not implemented, yet"));
592 void MainWindow::quit() {
596 void MainWindow::flipView() {
600 void MainWindow::toggleConsole() {
601 if (console_dock
->isVisible())
602 console_dock
->hide();
604 console_dock
->show();
605 console_dock
->setFocus(Qt::MouseFocusReason
606 /*Qt::ActiveWindowFocusReason*/ /*Qt::OtherFocusReason*/);
610 void MainWindow::toggleMoveList() {
611 if (movelist_dock
->isVisible())
612 movelist_dock
->hide();
614 movelist_dock
->show();
615 movelist_dock
->setFocus(Qt::OtherFocusReason
);
620 void MainWindow::displayMessage(const QString
& msg
) {
621 Q_UNUSED(msg
); // TODO
622 // statusBar()->message(msg, 2000);
625 void MainWindow::displayErrorMessage(ErrorCode code
) {
628 displayMessage(tr("Illegal move"));
633 void MainWindow::flash() {
634 if( !isAncestorOf(QApplication::focusWidget()) )
639 void MainWindow::prefHighlight() {
640 PrefHighlight dialog
;
641 int result
= dialog
.exec();
642 if (result
== QDialog::Accepted
) {
648 void MainWindow::preferences() {
649 Preferences
dialog(ui().currentVariant());
650 int result
= dialog
.exec();
651 if (result
== QDialog::Accepted
)