Fixed crash when changing tab.
[tagua/yd.git] / src / mainwindow.cpp
blob8074b1cb54620edbf27eef240cdc038f3bc38201
1 /*
2 Copyright (c) 2006-2007 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2006-2007 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.
9 */
11 #include "mainwindow.h"
12 #include <boost/scoped_ptr.hpp>
13 #include <kaction.h>
14 #include <kstandardaction.h>
15 #include <kactioncollection.h>
16 #include <kicon.h>
17 #include <klocale.h>
18 #include <kurl.h>
19 #include <kfiledialog.h>
20 #include <kio/netaccess.h>
21 #include <kmessagebox.h>
22 #include <kmenubar.h>
23 #include <QKeySequence>
24 #include <QStackedWidget>
25 #include <QDockWidget>
26 #include <QCloseEvent>
27 #include <QTextStream>
28 #include <QTextCodec>
29 #include <ktabwidget.h>
31 #include "actioncollection.h"
32 #include "chesstable.h"
33 #include "console.h"
34 #include "clock.h"
35 #include "newgame.h"
36 #include "variants.h"
37 #include "gameinfo.h"
38 #include "controllers/editgame.h"
39 #include "controllers/editposition.h"
40 #include "engineinfo.h"
41 #include "movelist_table.h"
42 #include "icsconnection.h"
43 #include "qconnect.h"
44 #include "mastersettings.h"
45 #include "flash.h"
46 #include "foreach.h"
47 #include "pgnparser.h"
48 #include "pref_highlight.h"
49 #include "pref_preferences.h"
51 using namespace Qt;
52 using namespace boost;
54 MainWindow::~MainWindow() {
55 delete console;
56 qApp->quit();
59 MainWindow::MainWindow(const QString& variant)
60 : KXmlGuiWindow(0) {
61 setObjectName("tagua_main");
62 m_main = new KTabWidget(this);
63 setCentralWidget(m_main);
65 m_movelist_stack = new QStackedWidget;
67 connect(m_main, SIGNAL(currentChanged(int)),
68 this, SLOT(changeTab(int)));
69 connect(m_main, SIGNAL(closeTab()),
70 this, SLOT(closeTab()));
72 movelist_dock = new QDockWidget(this);
73 movelist_dock->setWidget(m_movelist_stack);
74 movelist_dock->setWindowTitle(i18n("Move list"));
75 movelist_dock->setObjectName("move_list");
76 addDockWidget(Qt::LeftDockWidgetArea, movelist_dock, Qt::Vertical);
77 movelist_dock->show();
79 ChessTable* board = new ChessTable;
81 board->setFocus();
83 console_dock = new QDockWidget(this);
84 console = new Console(0, i18n("FICS Connection"));
85 console_dock->setWidget(console);
86 console_dock->setFocusProxy(console);
87 console_dock->setWindowTitle(i18n("Console"));
88 console_dock->setObjectName("console");
89 addDockWidget(Qt::BottomDockWidgetArea, console_dock, Qt::Horizontal);
90 console_dock->setWindowFlags(console_dock->windowFlags() & ~Qt::WindowStaysOnTopHint);
91 console_dock->show();
93 connect(board, SIGNAL(error(ErrorCode)), this, SLOT(displayErrorMessage(ErrorCode)));
94 //BROKEN connect(board->clock(), SIGNAL(labelClicked(int)), &ui(), SLOT(setTurn(int)));
96 // start in edit game mode
97 newGame(variant, AbstractPosition::Ptr());
99 setupActions();
100 setupGUI();
101 setupEngineMenu();
102 updateVariantActions();
105 ChessTable* MainWindow::table() {
106 return qobject_cast<ChessTable*>(m_main->currentWidget());
109 KAction* MainWindow::installRegularAction(const QString& name, const KIcon& icon, const QString& text, QObject* obj, const char* slot) {
110 KAction* temp = new KAction(icon, text, this);
111 actionCollection()->addAction(name, temp);
112 connect(temp, SIGNAL(triggered(bool)), obj, slot);
113 return temp;
116 void MainWindow::setupEngineMenu() {
117 QMenu* engine_menu = 0;
118 SettingArray engine_settings = settings().group("engines").array("engine");
119 foreach (Settings s, engine_settings) {
120 if (!engine_menu) {
121 // this way the menu is created only if there is at least one engine
122 engine_menu = menuBar()->addMenu(i18n("E&ngines"));
125 QString name;
126 EngineDetails engine_details;
127 s["name"] >> engine_details.name;
128 s["path"] >> engine_details.path;
129 engine_details.type = EngineDetails::typeFromName(s["type"].value<QString>());
130 if (s["work-path"])
131 s["work-path"] >> engine_details.workPath;
133 kDebug() << "creating engine " << engine_details.name << endl;
134 EngineInfo* engine = new EngineInfo(engine_details, ui());
136 m_engines.push_back(engine);
138 QMenu* menu = engine_menu->addMenu(engine_details.name);
141 KAction* play_white = new KAction(i18n("Play as &white"), this);
142 play_white->setCheckable(true);
143 connect(play_white, SIGNAL(triggered()), engine, SLOT(playAsWhite()));
144 menu->addAction(play_white);
147 KAction* play_black = new KAction(i18n("Play as &black"), this);
148 play_black->setCheckable(true);
149 connect(play_black, SIGNAL(triggered()), engine, SLOT(playAsBlack()));
150 menu->addAction(play_black);
152 #if 0 // disable analysis for the moment
154 KAction* analyze = new KAction(i18n("&Analyze"), this);
155 analyze->setCheckable(true);
156 connect(analyze, SIGNAL(triggered()), engine, SLOT(analyze()));
157 menu->addAction(analyze);
159 #endif
163 void MainWindow::setupActions() {
164 KStandardAction::openNew(this, SLOT(newGame()), actionCollection());
165 KStandardAction::open(this, SLOT(loadGame()), actionCollection());
166 KStandardAction::quit(this, SLOT(quit()), actionCollection());
168 installRegularAction("back", KIcon("go-previous"), i18n("&Back"), &ui(), SLOT(back()));
169 installRegularAction("forward", KIcon("go-next"), i18n("&Forward"), &ui(), SLOT(forward()));
170 installRegularAction("begin", KIcon("go-first"), i18n("Be&gin"), &ui(), SLOT(gotoFirst()));
171 installRegularAction("end", KIcon("go-last"), i18n("&End"), &ui(), SLOT(gotoLast()));
172 installRegularAction("connect", KIcon("connection-established"), i18n("&Connect"), this, SLOT(icsConnect()));
173 installRegularAction("disconnect", KIcon("connect-no"), i18n("&Disconnect"), this, SLOT(icsDisconnect()));
175 KStandardAction::undo(&ui(), SLOT(undo()), actionCollection());
176 KStandardAction::redo(&ui(), SLOT(redo()), actionCollection());
178 installRegularAction("pgnCopy", KIcon("edit-copy"), i18n("Copy PGN"), this, SLOT(pgnCopy()));
179 installRegularAction("pgnPaste", KIcon("edit-paste"), i18n("Paste PGN"), this, SLOT(pgnPaste()));
180 installRegularAction("editPosition", KIcon("edit"), i18n("&Edit position"), this, SLOT(editPosition()));
181 installRegularAction("clearBoard", KIcon("edit-delete"), i18n("&Clear board"), &ui(), SLOT(clearBoard()));
182 installRegularAction("setStartingPosition", KIcon("contents"), i18n("&Set starting position"),
183 &ui(), SLOT(setStartingPosition()));
184 installRegularAction("copyPosition", KIcon(), i18n("&Copy position"), &ui(), SLOT(copyPosition()));
185 installRegularAction("pastePosition", KIcon(), i18n("&Paste position"), &ui(), SLOT(pastePosition()));
186 installRegularAction("flip", KIcon("rotate"), i18n("&Flip view"), this, SLOT(flipView()));
187 installRegularAction("toggleConsole", KIcon("openterm"), i18n("Toggle &console"), this, SLOT(toggleConsole()));
188 installRegularAction("toggleMoveList", KIcon("view_text"), i18n("Toggle &move list"), this, SLOT(toggleMoveList()));
189 installRegularAction("configure", KIcon("configure"), i18n("&Configure Tagua..."), this, SLOT(preferences()));
192 void MainWindow::updateVariantActions() {
193 ActionCollection* variant_actions = m_ui.variantActions();
194 unplugActionList("variantActions");
195 if (variant_actions) {
196 plugActionList("variantActions", variant_actions->actions());
198 else {
199 WARNING("No variant actions");
203 void MainWindow::readSettings() { }
204 void MainWindow::writeSettings() { }
206 void MainWindow::closeEvent(QCloseEvent* e) {
207 e->accept();
208 writeSettings();
209 delete this;
213 void MainWindow::keyPressEvent(QKeyEvent* event) {
214 if (event->key() == Qt::Key_F5) {
215 ui().createCtrlAction();
219 void MainWindow::keyReleaseEvent(QKeyEvent* event) {
220 if (event->key() == Qt::Key_F5) {
221 ui().destroyCtrlAction();
225 void MainWindow::changeTab(int index) {
226 m_ui.setCurrentTab(m_main->currentWidget());
227 m_movelist_stack->setCurrentIndex(index);
228 updateVariantActions();
231 void MainWindow::closeTab() {
232 if (m_main->count() > 1) {
233 ChessTable* old_board = table();
234 m_ui.removeController(old_board);
235 m_movelist_stack->removeWidget(
236 m_movelist_stack->widget(m_main->currentIndex()));
237 m_main->removeTab(m_main->currentIndex());
239 delete old_board;
241 if (m_main->count() <= 1) {
242 m_main->setTabBarHidden(true);
245 // update ui controller (just in case...)
246 m_ui.setCurrentTab(m_main->currentWidget());
250 void MainWindow::createTab(ChessTable* board, const shared_ptr<Controller>& controller,
251 const QString& caption, int index) {
252 if (index == -1)
253 index = m_main->addTab(board, caption);
254 else
255 m_main->insertTab(index, board, caption);
257 m_ui.addController(board, controller);
258 m_ui.setCurrentTab(board);
259 m_movelist_stack->addWidget(board->moveListTable());
261 m_main->setCurrentIndex(index);
262 m_movelist_stack->setCurrentIndex(index);
264 if (m_main->count() > 1) m_main->setTabBarHidden(false);
268 void MainWindow::cleanupGame(const QString& what, const QString& result) {
269 Q_UNUSED(what);
270 Q_UNUSED(result);
272 cleanupGame();
275 void MainWindow::cleanupGame() {
276 ui().detach();
277 ui().end();
281 bool MainWindow::newGame(const QString& variantName, AbstractPosition::Ptr startingPos) {
282 VariantPtr variant = Variants::instance().get(variantName);
283 if (!variant) {
284 WARNING("no variant " << variantName << " found");
285 variant = Variants::instance().get("chess");
288 if (variant) {
289 ChessTable* board = new ChessTable;
290 shared_ptr<Controller> controller(new EditGameController(
291 board, variant, startingPos));
292 createTab(board, controller,
293 QString("Editing %1 game").arg(variant->name().toLower()));
294 return true;
296 else {
297 ERROR("Could not find the chess variant");
298 exit(1);
299 return false;
304 void MainWindow::editPosition() {
305 //BROKEN
306 #if 0
307 shared_ptr<Controller> controller(new EditPositionController(table(), ChessVariant::info()));
308 m_main->setTabText(m_main->currentIndex(), "Editing chess position");
309 ui().setController(controller);
310 #endif
313 void MainWindow::setupGame(const GameInfo* gameInfo, const PositionInfo& style12) {
314 QString variantCode = gameInfo->variant();
315 VariantPtr variant = Variants::instance().get(variantCode);
316 shared_ptr<EditGameController> controller(new EditGameController(
317 table(), variant));
318 Q_ASSERT(style12.relation == PositionInfo::NotMyMove ||
319 style12.relation == PositionInfo::MyMove);
321 // set opponent side
322 int side = (style12.relation == PositionInfo::MyMove ^ style12.turn == 0) ? 0 : 1;
324 if (controller->addICSPlayer(side, style12.gameNumber, m_connection)) {
325 ui().setController(controller);
326 table()->setPlayers(gameInfo->white(), gameInfo->black());
327 m_main->setTabText(m_main->currentIndex(),
328 QString("FICS Game - %1 vs %2").arg(style12.whitePlayer)
329 .arg(style12.blackPlayer));
333 void MainWindow::setupExaminedGame(const GameInfo* /*gameInfo*/, const PositionInfo& style12) {
334 shared_ptr<EditGameController> controller(new EditGameController(
335 table(), Variants::instance().get("chess")));
336 if (controller->setExaminationMode(style12.gameNumber, m_connection)) {
337 table()->setPlayers(Player(style12.whitePlayer, -1),
338 Player(style12.blackPlayer, -1));
339 ui().setController(controller);
340 m_main->setTabText(m_main->currentIndex(),
341 QString("Examining - %1 vs %2").arg(style12.whitePlayer)
342 .arg(style12.blackPlayer));
347 void MainWindow::setupObservedGame(const GameInfo* g, const PositionInfo& style12) {
348 std::auto_ptr<ChessTable> board(new ChessTable);
350 shared_ptr<EditGameController> controller(new EditGameController(
351 board.get(), Variants::instance().get(g->variant())));
352 if (controller->setObserveMode(style12.gameNumber, m_connection)) {
353 board->setPlayers(Player(style12.whitePlayer, -1),
354 Player(style12.blackPlayer, -1));
355 // ui().setController(controller);
356 //std::cout << "adding tab" << std::endl;
357 createTab(board.get(), controller,
358 QString("Observing - %1 vs %2").arg(style12.whitePlayer)
359 .arg(style12.blackPlayer));
360 board.release();
364 void MainWindow::setupPGN(const QString& s) {
365 PGN pgn(s);
367 std::map<QString, QString>::const_iterator var = pgn.m_tags.find("Variant");
368 VariantPtr variant;
370 if (var == pgn.m_tags.end()) {
371 variant = Variants::instance().get("chess");
373 else if (!(variant = Variants::instance().get(var->second))) {
374 std::cout << " --> MainWindow::setupPGN: Error, no such variant " << var->second << std::endl;
375 return;
378 shared_ptr<EditGameController> controller(new EditGameController(
379 table(), variant));
380 ui().setController(controller);
381 controller->loadPGN(pgn);
383 // table()->setPlayers(gameInfo->white(), gameInfo->black());
384 // m_main->setTabText(m_main->currentIndex(),
385 // QString("FICS Game - %1 vs %2").arg(style12.whitePlayer)
386 // .arg(style12.blackPlayer));
389 bool MainWindow::openFile(const QString& filename) {
390 QFileInfo info(filename);
392 if(info.isDir()) {
393 KMessageBox::sorry(this, i18n("You have specified a folder"), i18n("Error"));
394 return false;
397 if(!info.exists() || !info.isFile()) {
398 KMessageBox::sorry(this, i18n("The specified file does not exist"), i18n("Error"));
399 return false;
402 QFile file(filename);
404 if(!file.open(QIODevice::ReadOnly)) {
405 KMessageBox::sorry(this, i18n("You do not have read permission to this file."), i18n("Error"));
406 return false;
409 QTextStream stream(&file);
410 QTextCodec *codec;
411 codec = QTextCodec::codecForLocale();
412 stream.setCodec(codec);
414 setupPGN(stream.readAll());
415 //ui().pgnPaste(stream.readAll());
416 return true;
419 void MainWindow::loadGame() {
420 KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.pgn", this, i18n("Open PGN file"));
422 if(url.isEmpty())
423 return;
425 QString tmp_file;
426 if (KIO::NetAccess::download(url, tmp_file, this)) {
427 openFile(tmp_file);
428 KIO::NetAccess::removeTempFile(tmp_file);
430 else
431 KMessageBox::error(this, KIO::NetAccess::lastErrorString());
434 void MainWindow::createConnection(const QString& username, const QString& password,
435 const QString& host, quint16 port,
436 const QString& timeseal, const QString& timeseal_cmd) {
437 m_connection = shared_ptr<ICSConnection>(new ICSConnection);
439 connect(m_connection.get(), SIGNAL(established()), this, SLOT(onEstablishConnection()));
440 connect(m_connection.get(), SIGNAL(hostLookup()), this, SLOT(onHostLookup()));
441 connect(m_connection.get(), SIGNAL(hostFound()), this, SLOT(onHostFound()));
443 connect(m_connection.get(), SIGNAL(receivedLine(QString, int)), console, SLOT(displayText(QString, int)));
444 connect(m_connection.get(), SIGNAL(receivedText(QString, int)), console, SLOT(displayText(QString, int)));
446 connect(console, SIGNAL(receivedInput(const QString&)), m_connection.get(), SLOT(sendText(const QString&)));
447 connect(console, SIGNAL(notify()), this, SLOT(flash()));
449 connect(m_connection.get(), SIGNAL(loginPrompt()), this, SLOT(sendLogin()));
450 connect(m_connection.get(), SIGNAL(registeredNickname()), this, SLOT(sendBlankPassword()));
451 connect(m_connection.get(), SIGNAL(prompt()), this, SLOT(prompt()));
454 connect(m_connection.get(), SIGNAL(creatingExaminedGame(const GameInfo*, const PositionInfo&)),
455 this, SLOT(setupExaminedGame(const GameInfo*, const PositionInfo&)));
456 connect(m_connection.get(), SIGNAL(endingExaminedGame(int)), this, SLOT(cleanupGame()));
458 connect(m_connection.get(), SIGNAL(creatingObservedGame(const GameInfo*, const PositionInfo&)),
459 this, SLOT(setupObservedGame(const GameInfo*, const PositionInfo&)));
460 connect(m_connection.get(), SIGNAL(endingObservedGame(int)), this, SLOT(cleanupGame()));
463 connect(m_connection.get(), SIGNAL(creatingGame(const GameInfo*, const PositionInfo&)),
464 this, SLOT(setupGame(const GameInfo*, const PositionInfo&)));
465 connect(m_connection.get(), SIGNAL(endingGame(const QString&, const QString&)),
466 this, SLOT(cleanupGame(const QString&, const QString&)));
467 connect(m_connection.get(), SIGNAL(notification()), this, SLOT(flash()));
469 m_connection->establish(host.toAscii().constData(), port, timeseal, timeseal_cmd);
470 console->show();
472 // send username / password combination
473 if (!username.isEmpty()) {
474 m_connection->sendText(username);
475 m_connection->sendText(password);
478 quickConnectDialog.reset();
481 void MainWindow::icsConnect() {
482 quickConnectDialog = shared_ptr<QConnect>(new QConnect(this));
483 connect(quickConnectDialog.get(),
484 SIGNAL(acceptConnection(const QString&,
485 const QString&,
486 const QString&,
487 quint16,
488 const QString&,
489 const QString&)),
490 this,
491 SLOT(createConnection(const QString&,
492 const QString&,
493 const QString&,
494 quint16,
495 const QString&,
496 const QString&)));
497 quickConnectDialog->show();
500 void MainWindow::destroyConnection() {
501 m_connection.reset();
504 void MainWindow::icsDisconnect() {
505 destroyConnection();
506 console->hide();
507 console->clear();
510 void MainWindow::testConnect() {
511 Settings s_ics = settings().group("ics");
512 if (s_ics["username"]) {
513 QString username = s_ics["username"].value<QString>();
514 QString password = (s_ics["password"] | "");
515 QString host = (s_ics["icsHost"] | "freechess.org");
516 quint16 port = (s_ics["icsPort"] | 5000);
517 createConnection(username, password, host, port, QString(), QString() );
519 else icsConnect();
523 void MainWindow::onEstablishConnection() {
524 // std::cout << "connection established" << std::endl;
527 void MainWindow::onConnectionError(int ) {
528 // std::cout << "connection error (" << code << ")" << std::endl;
531 void MainWindow::onHostLookup() {
532 // std::cout << "hostLookup..." << std::flush;
535 void MainWindow::onHostFound() {
536 // std::cout << "found" << std::endl;
540 void MainWindow::sendLogin() {
541 // std::cout << "sending username" << std::endl;
542 // connection->sendText(connection->username());
545 void MainWindow::sendBlankPassword() {
546 std::cout << "sending blank password" << std::endl;
547 m_connection->sendText("");
550 void MainWindow::prompt() {
551 if (!m_connection->initialized()) {
552 m_connection->startup();
553 m_connection->setInitialized();
557 void MainWindow::newGame() {
558 AbstractPosition::Ptr pos = ui().position();
559 scoped_ptr<NewGame> dialog(new NewGame(this, pos));
560 if (dialog->exec() == QDialog::Accepted) {
561 if(dialog->isCustom()) {
562 VariantPtr vi = Variants::instance().get(dialog->variant());
563 std::cout << "vi[" << dialog->variant() << "] = " << vi << std::endl;
564 pos = vi->createCustomPosition(dialog->customOptions());
565 pos->setup();
567 else if (!dialog->playFromCurrent())
568 pos = AbstractPosition::Ptr();
569 if (!newGame(dialog->variant(), pos))
570 QMessageBox::information(this, tr("Error"), tr("Variant not implemented, yet"));
574 void MainWindow::quit() {
575 delete this;
578 void MainWindow::flipView() {
579 table()->flip();
582 void MainWindow::toggleConsole() {
583 if (console_dock->isVisible())
584 console_dock->hide();
585 else {
586 console_dock->show();
587 console_dock->setFocus(Qt::MouseFocusReason
588 /*Qt::ActiveWindowFocusReason*/ /*Qt::OtherFocusReason*/);
592 void MainWindow::toggleMoveList() {
593 if (movelist_dock->isVisible())
594 movelist_dock->hide();
595 else {
596 movelist_dock->show();
597 movelist_dock->setFocus(Qt::OtherFocusReason);
602 void MainWindow::displayMessage(const QString& msg) {
603 Q_UNUSED(msg); // TODO
604 // statusBar()->message(msg, 2000);
607 void MainWindow::displayErrorMessage(ErrorCode code) {
608 switch(code) {
609 case InvalidMove:
610 displayMessage(tr("Illegal move"));
611 break;
615 void MainWindow::flash() {
616 if( !isAncestorOf(QApplication::focusWidget()) )
617 Flash::flash(this);
620 #if 0
621 void MainWindow::prefHighlight() {
622 PrefHighlight dialog;
623 int result = dialog.exec();
624 if (result == QDialog::Accepted) {
625 dialog.apply();
628 #endif
630 void MainWindow::preferences() {
631 Preferences dialog(ui().currentVariant());
632 int result = dialog.exec();
633 if (result == QDialog::Accepted)
634 dialog.apply();