blob: 0f5b062dbb7894b7887db6975d81705c7716be35 [file] [log] [blame]
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -07001#include <QtGui>
2#include "chatdialog.h"
Zhenkai Zhu85845d22012-06-01 23:10:43 -07003#include "settingdialog.h"
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -07004#include <ctime>
Zhenkai Zhub6338822012-05-31 13:27:24 -07005#include <iostream>
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -07006#include <QTimer>
Zhenkai Zhu10ccb5a2012-06-04 21:55:14 -07007#include <QMetaType>
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -07008#include <QMessageBox>
Zhenkai Zhu59245aa2012-09-26 16:07:04 -07009#include <boost/random/random_device.hpp>
10#include <boost/random/uniform_int_distribution.hpp>
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -070011#include <boost/lexical_cast.hpp>
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -070012#include <stdio.h>
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -070013
Zhenkai Zhu0b3fa332012-09-27 21:58:43 -070014#define BROADCAST_PREFIX_FOR_SYNC_DEMO "/ndn/broadcast/chronos"
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -070015#define LOCAL_PREFIX_QUERY "/local/ndn/prefix"
16#define DEFAULT_LOCAL_PREFIX "/private/local"
Zhenkai Zhu756666a2012-10-07 00:24:35 -070017#define CCN_EXEC "/usr/local/bin/ccnpeek"
Zhenkai Zhu82a62752012-06-04 17:11:04 -070018
Zhenkai Zhuc61dbc22012-10-08 11:36:37 -070019static const int HELLO_INTERVAL = FRESHNESS * 3 / 4; // seconds
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -070020
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -070021ChatDialog::ChatDialog(QWidget *parent)
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -070022 : QDialog(parent), m_sock(NULL), m_lastMsgTime(0), m_historyInitialized(false), m_joined(false)
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -070023{
Zhenkai Zhu10ccb5a2012-06-04 21:55:14 -070024 // have to register this, otherwise
25 // the signal-slot system won't recognize this type
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -070026 qRegisterMetaType<std::vector<Sync::MissingDataInfo> >("std::vector<Sync::MissingDataInfo>");
27 qRegisterMetaType<size_t>("size_t");
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -070028 setupUi(this);
Zhenkai Zhu82a62752012-06-04 17:11:04 -070029 m_session = time(NULL);
Zhenkai Zhu716fe852012-10-08 18:27:55 -070030 m_scene = new DigestTreeScene(this);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -070031
32 readSettings();
Zhenkai Zhu82a62752012-06-04 17:11:04 -070033
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -070034 updateLabels();
35
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -070036 lineEdit->setFocusPolicy(Qt::StrongFocus);
Zhenkai Zhub45e38a2012-06-01 15:44:36 -070037
Zhenkai Zhu82a62752012-06-04 17:11:04 -070038 treeViewer->setScene(m_scene);
39 m_scene->plot("Empty");
40 QRectF rect = m_scene->itemsBoundingRect();
41 m_scene->setSceneRect(rect);
42
Zhenkai Zhu9036e032012-09-27 20:59:33 -070043 listView->setStyleSheet("QListView { alternate-background-color: white; background: #F0F0F0; color: darkGreen; font: bold large; }");
Zhenkai Zhuf55f4382012-09-28 10:58:54 -070044 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
45 listView->setDragDropMode(QAbstractItemView::NoDragDrop);
46 listView->setSelectionMode(QAbstractItemView::NoSelection);
Zhenkai Zhu6082ede2012-09-27 17:28:46 -070047 m_rosterModel = new QStringListModel(this);
48 listView->setModel(m_rosterModel);
49
Zhenkai Zhu4b953d92012-10-08 13:09:40 -070050 refreshButton->setIcon(QIcon(QPixmap(":images/refresh.png")));
Zhenkai Zhu22c7d4d2012-10-09 12:29:32 -070051 reapButton->hide();
Zhenkai Zhu4b953d92012-10-08 13:09:40 -070052
Zhenkai Zhu86df7412012-09-27 16:30:20 -070053 createActions();
54 createTrayIcon();
55 m_timer = new QTimer(this);
56 connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
57 connect(setButton, SIGNAL(pressed()), this, SLOT(buttonPressed()));
Zhenkai Zhub60b7e12012-09-28 11:34:21 -070058 connect(treeButton, SIGNAL(pressed()), this, SLOT(treeButtonPressed()));
Zhenkai Zhu7f52e1b2012-10-09 11:45:36 -070059 connect(reapButton, SIGNAL(pressed()), this, SLOT(summonReaper()));
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -070060 connect(refreshButton, SIGNAL(pressed()), this, SLOT(updateLocalPrefix()));
Zhenkai Zhu24ec4722012-10-07 17:56:38 -070061 connect(this, SIGNAL(dataReceived(QString, const char *, size_t, bool, bool)), this, SLOT(processData(QString, const char *, size_t, bool, bool)));
Zhenkai Zhu86df7412012-09-27 16:30:20 -070062 connect(this, SIGNAL(treeUpdated(const std::vector<Sync::MissingDataInfo>)), this, SLOT(processTreeUpdate(const std::vector<Sync::MissingDataInfo>)));
Zhenkai Zhu86df7412012-09-27 16:30:20 -070063 connect(m_timer, SIGNAL(timeout()), this, SLOT(replot()));
64 connect(m_scene, SIGNAL(replot()), this, SLOT(replot()));
65 connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(showNormal()));
66 connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
Zhenkai Zhu25e33e52012-09-28 13:00:07 -070067 connect(m_scene, SIGNAL(rosterChanged(QStringList)), this, SLOT(updateRosterList(QStringList)));
Zhenkai Zhu86df7412012-09-27 16:30:20 -070068
Zhenkai Zhu82a62752012-06-04 17:11:04 -070069 // create sync socket
70 if(!m_user.getChatroom().isEmpty()) {
71 std::string syncPrefix = BROADCAST_PREFIX_FOR_SYNC_DEMO;
72 syncPrefix += "/";
73 syncPrefix += m_user.getChatroom().toStdString();
Zhenkai Zhua4fb1242012-06-05 20:26:05 -070074 try
75 {
Alexander Afanasyev288edd82012-10-04 17:07:56 -070076 m_sock = new Sync::SyncAppSocket(syncPrefix,
77 bind(&ChatDialog::processTreeUpdateWrapper, this, _1, _2),
78 bind(&ChatDialog::processRemoveWrapper, this, _1));
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -070079 Sync::CcnxWrapperPtr handle = Sync::CcnxWrapper::Create();
80 handle->setInterestFilter(m_user.getPrefix().toStdString(), bind(&ChatDialog::respondHistoryRequest, this, _1));
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -070081 //QTimer::singleShot(100, this, SLOT(getLocalPrefix()));
82 if (!getLocalPrefix())
83 {
84 // if getLocalPrefix indicates no prefix change
85 // this sock is going to be used
86 QTimer::singleShot(600, this, SLOT(sendJoin()));
87 m_timer->start(FRESHNESS * 1000);
88 disableTreeDisplay();
89 QTimer::singleShot(2200, this, SLOT(enableTreeDisplay()));
90 }
91 else
92 {
93 // this socket is going to be destroyed anyway
94 // why bother doing the following steps
Alexander Afanasyevebe118d2012-10-08 08:56:34 -070095
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -070096 // the same steps would be performed for another socket
97 // in settingUpdated
98 }
Zhenkai Zhua4fb1242012-06-05 20:26:05 -070099 }
100 catch (Sync::CcnxOperationException ex)
101 {
Zhenkai Zhu0b3fa332012-09-27 21:58:43 -0700102 QMessageBox::critical(this, tr("Chronos"), tr("Canno connect to ccnd.\n Have you started your ccnd?"), QMessageBox::Ok);
Zhenkai Zhua4fb1242012-06-05 20:26:05 -0700103 std::exit(1);
104 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700105 }
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700106
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700107}
108
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700109ChatDialog::~ChatDialog()
110{
111 if (m_sock != NULL)
112 {
Zhenkai Zhucf024442012-10-05 10:33:08 -0700113 sendLeave();
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700114 delete m_sock;
115 m_sock = NULL;
116 }
117}
118
Zhenkai Zhu86df7412012-09-27 16:30:20 -0700119void
Zhenkai Zhucf024442012-10-05 10:33:08 -0700120ChatDialog::sendLeave()
121{
122 SyncDemo::ChatMessage msg;
123 formControlMessage(msg, SyncDemo::ChatMessage::LEAVE);
124 sendMsg(msg);
125 usleep(500000);
126 m_sock->remove(m_user.getPrefix().toStdString());
127 usleep(5000);
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700128 m_joined = false;
Zhenkai Zhucf024442012-10-05 10:33:08 -0700129#ifdef __DEBUG
130 std::cout << "Sync REMOVE signal sent" << std::endl;
131#endif
132}
133
134void
Zhenkai Zhu86df7412012-09-27 16:30:20 -0700135ChatDialog::replot()
136{
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700137 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu86df7412012-09-27 16:30:20 -0700138 m_scene->plot(m_sock->getRootDigest().c_str());
Zhenkai Zhuc9e4e3c2012-10-02 11:47:31 -0700139 fitView();
Zhenkai Zhu86df7412012-09-27 16:30:20 -0700140}
141
Zhenkai Zhu6082ede2012-09-27 17:28:46 -0700142void
Zhenkai Zhu7f52e1b2012-10-09 11:45:36 -0700143ChatDialog::summonReaper()
144{
145 Sync::SyncLogic &logic = m_sock->getLogic ();
146 std::map<std::string, bool> branches = logic.getBranchPrefixes();
147 QMap<QString, DisplayUserPtr> roster = m_scene->getRosterFull();
148
149 m_zombieList.clear();
150
151 QMapIterator<QString, DisplayUserPtr> it(roster);
152 std::map<std::string, bool>::iterator mapIt;
153 while(it.hasNext())
154 {
155 it.next();
156 DisplayUserPtr p = it.value();
157 if (p != DisplayUserNullPtr)
158 {
159 mapIt = branches.find(p->getPrefix().toStdString());
160 if (mapIt != branches.end())
161 {
162 mapIt->second = true;
163 }
164 }
165 }
166
167 for (mapIt = branches.begin(); mapIt != branches.end(); ++mapIt)
168 {
169 // this is zombie. all active users should have been marked true
170 if (! mapIt->second)
171 {
172 m_zombieList.append(mapIt->first.c_str());
173 }
174 }
175
176 m_zombieIndex = 0;
177
178 // start reaping
179 reap();
180}
181
182void
183ChatDialog::reap()
184{
185 if (m_zombieIndex < m_zombieList.size())
186 {
187 std::string prefix = m_zombieList.at(m_zombieIndex).toStdString();
188 m_sock->remove(prefix);
189 std::cout << "Reaped: prefix = " << prefix << std::endl;
190 m_zombieIndex++;
191 // reap again in 10 seconds
192 QTimer::singleShot(10000, this, SLOT(reap()));
193 }
194}
195
196void
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700197ChatDialog::updateRosterList(QStringList staleUserList)
Zhenkai Zhu6082ede2012-09-27 17:28:46 -0700198{
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700199 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu6082ede2012-09-27 17:28:46 -0700200 QStringList rosterList = m_scene->getRosterList();
201 m_rosterModel->setStringList(rosterList);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700202 QString user;
203 QStringListIterator it(staleUserList);
204 while(it.hasNext())
205 {
Zhenkai Zhu32cbdce2012-10-02 11:09:38 -0700206 std::string nick = it.next().toStdString();
207 if (nick.empty())
208 continue;
209
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700210 SyncDemo::ChatMessage msg;
Zhenkai Zhub5b78462012-09-28 14:10:37 -0700211 formControlMessage(msg, SyncDemo::ChatMessage::LEAVE);
Zhenkai Zhu32cbdce2012-10-02 11:09:38 -0700212 msg.set_from(nick);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700213 appendMessage(msg);
214 }
Zhenkai Zhu6082ede2012-09-27 17:28:46 -0700215}
216
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700217void
218ChatDialog::setVisible(bool visible)
219{
220 minimizeAction->setEnabled(visible);
221 maximizeAction->setEnabled(!isMaximized());
222 restoreAction->setEnabled(isMaximized() || !visible);
223 QDialog::setVisible(visible);
224}
225
226void
227ChatDialog::closeEvent(QCloseEvent *e)
228{
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700229 if (trayIcon->isVisible() && !m_minimaniho)
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700230 {
Zhenkai Zhu0b3fa332012-09-27 21:58:43 -0700231 QMessageBox::information(this, tr("Chronos"),
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700232 tr("The program will keep running in the "
233 "system tray. To terminate the program"
234 "choose <b>Quit</b> in the context memu"
235 "of the system tray entry."));
236 hide();
237 e->ignore();
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700238 m_minimaniho = true;
239 writeSettings();
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700240 }
241}
242
243void
244ChatDialog::changeEvent(QEvent *e)
245{
246 switch(e->type())
247 {
248 case QEvent::ActivationChange:
249 if (isActiveWindow())
250 {
251 trayIcon->setIcon(QIcon(":/images/icon_small.png"));
252 }
253 break;
254 default:
255 break;
256 }
257}
258
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700259void
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700260ChatDialog::appendMessage(const SyncDemo::ChatMessage msg, bool isHistory)
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700261{
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700262 boost::recursive_mutex::scoped_lock lock(m_msgMutex);
Zhenkai Zhub6338822012-05-31 13:27:24 -0700263
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700264 if (msg.type() == SyncDemo::ChatMessage::CHAT)
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700265 {
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700266
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700267 if (!msg.has_data())
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700268 {
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700269 return;
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700270 }
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700271
272 if (msg.from().empty() || msg.data().empty())
273 {
274 return;
275 }
276
277 if (!msg.has_timestamp())
278 {
279 return;
280 }
281
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700282 if (m_history.size() == MAX_HISTORY_ENTRY)
283 {
284 m_history.dequeue();
285 }
286
287 m_history.enqueue(msg);
288
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700289 QTextCharFormat nickFormat;
290 nickFormat.setForeground(Qt::darkGreen);
291 nickFormat.setFontWeight(QFont::Bold);
292 nickFormat.setFontUnderline(true);
293 nickFormat.setUnderlineColor(Qt::gray);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700294
295 QTextCursor cursor(textEdit->textCursor());
296 cursor.movePosition(QTextCursor::End);
297 QTextTableFormat tableFormat;
298 tableFormat.setBorder(0);
299 QTextTable *table = cursor.insertTable(1, 2, tableFormat);
300 QString from = QString("%1 ").arg(msg.from().c_str());
301 QTextTableCell fromCell = table->cellAt(0, 0);
302 fromCell.setFormat(nickFormat);
303 fromCell.firstCursorPosition().insertText(from);
Zhenkai Zhu560ef1b2012-09-28 14:23:33 -0700304
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700305 time_t timestamp = msg.timestamp();
Zhenkai Zhu560ef1b2012-09-28 14:23:33 -0700306 printTimeInCell(table, timestamp);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700307
308 QTextCursor nextCursor(textEdit->textCursor());
309 nextCursor.movePosition(QTextCursor::End);
310 table = nextCursor.insertTable(1, 1, tableFormat);
Zhenkai Zhu767eac72012-10-08 11:20:57 -0700311 table->cellAt(0, 0).firstCursorPosition().insertText(QString::fromUtf8(msg.data().c_str()));
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700312 if (!isHistory)
313 {
Zhenkai Zhu767eac72012-10-08 11:20:57 -0700314 showMessage(from, QString::fromUtf8(msg.data().c_str()));
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700315 }
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700316 }
317
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700318 if (msg.type() == SyncDemo::ChatMessage::JOIN || msg.type() == SyncDemo::ChatMessage::LEAVE)
319 {
320 QTextCharFormat nickFormat;
321 nickFormat.setForeground(Qt::gray);
322 nickFormat.setFontWeight(QFont::Bold);
323 nickFormat.setFontUnderline(true);
324 nickFormat.setUnderlineColor(Qt::gray);
Zhenkai Zhub98e6022012-09-27 13:48:23 -0700325
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700326 QTextCursor cursor(textEdit->textCursor());
327 cursor.movePosition(QTextCursor::End);
328 QTextTableFormat tableFormat;
329 tableFormat.setBorder(0);
330 QTextTable *table = cursor.insertTable(1, 2, tableFormat);
331 QString action;
332 if (msg.type() == SyncDemo::ChatMessage::JOIN)
333 {
334 action = "enters room";
335 }
336 else
337 {
338 action = "leaves room";
339 }
340
341 QString from = QString("%1 %2 ").arg(msg.from().c_str()).arg(action);
342 QTextTableCell fromCell = table->cellAt(0, 0);
343 fromCell.setFormat(nickFormat);
344 fromCell.firstCursorPosition().insertText(from);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700345
Zhenkai Zhu560ef1b2012-09-28 14:23:33 -0700346 time_t timestamp = msg.timestamp();
347 printTimeInCell(table, timestamp);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700348 }
349
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700350 QScrollBar *bar = textEdit->verticalScrollBar();
351 bar->setValue(bar->maximum());
352}
353
Zhenkai Zhu560ef1b2012-09-28 14:23:33 -0700354void
355ChatDialog::printTimeInCell(QTextTable *table, time_t timestamp)
356{
357 QTextCharFormat timeFormat;
358 timeFormat.setForeground(Qt::gray);
359 timeFormat.setFontUnderline(true);
360 timeFormat.setUnderlineColor(Qt::gray);
361 QTextTableCell timeCell = table->cellAt(0, 1);
362 timeCell.setFormat(timeFormat);
363 timeCell.firstCursorPosition().insertText(formatTime(timestamp));
364}
365
366QString
367ChatDialog::formatTime(time_t timestamp)
368{
369 struct tm *tm_time = localtime(&timestamp);
370 int hour = tm_time->tm_hour;
371 QString amOrPM;
372 if (hour > 12)
373 {
374 hour -= 12;
375 amOrPM = "PM";
376 }
377 else
378 {
379 amOrPM = "AM";
380 if (hour == 0)
381 {
382 hour = 12;
383 }
384 }
385
386 char textTime[12];
387 sprintf(textTime, "%d:%02d:%02d %s", hour, tm_time->tm_min, tm_time->tm_sec, amOrPM.toStdString().c_str());
388 return QString(textTime);
389}
390
Zhenkai Zhu85845d22012-06-01 23:10:43 -0700391void
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -0700392ChatDialog::processTreeUpdateWrapper(const std::vector<Sync::MissingDataInfo> v, Sync::SyncAppSocket *sock)
393{
394 emit treeUpdated(v);
Zhenkai Zhud1c5a972012-06-05 14:07:41 -0700395#ifdef __DEBUG
396 std::cout << "<<< Tree update signal emitted" << std::endl;
397#endif
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -0700398}
399
400void
401ChatDialog::processTreeUpdate(const std::vector<Sync::MissingDataInfo> v)
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700402{
Zhenkai Zhud1c5a972012-06-05 14:07:41 -0700403#ifdef __DEBUG
404 std::cout << "<<< processing Tree Update" << std::endl;
405#endif
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700406 if (v.empty())
407 {
408 return;
409 }
410
411 // reflect the changes on digest tree
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700412 {
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700413 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700414 m_scene->processUpdate(v, m_sock->getRootDigest().c_str());
415 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700416
417 int n = v.size();
418 int totalMissingPackets = 0;
419 for (int i = 0; i < n; i++)
420 {
421 totalMissingPackets += v[i].high.getSeq() - v[i].low.getSeq() + 1;
422 }
423
Zhenkai Zhubb198112012-09-27 11:31:42 -0700424 for (int i = 0; i < n; i++)
425 {
426 if (totalMissingPackets < 4)
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700427 {
428 for (Sync::SeqNo seq = v[i].low; seq <= v[i].high; ++seq)
429 {
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -0700430 m_sock->fetchRaw(v[i].prefix, seq, bind(&ChatDialog::processDataWrapper, this, _1, _2, _3), 2);
Zhenkai Zhud1c5a972012-06-05 14:07:41 -0700431#ifdef __DEBUG
432 std::cout << "<<< Fetching " << v[i].prefix << "/" <<seq.getSession() <<"/" << seq.getSeq() << std::endl;
433#endif
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700434 }
435 }
Zhenkai Zhubb198112012-09-27 11:31:42 -0700436 else
437 {
438 m_sock->fetchRaw(v[i].prefix, v[i].high, bind(&ChatDialog::processDataNoShowWrapper, this, _1, _2, _3), 2);
439 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700440 }
441
442 // adjust the view
443 fitView();
444
445}
446
447void
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -0700448ChatDialog::processDataWrapper(std::string name, const char *buf, size_t len)
449{
Zhenkai Zhuae29f5a2012-10-05 17:28:04 -0700450 char *tempBuf = new char[len];
451 memcpy(tempBuf, buf, len);
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700452 emit dataReceived(name.c_str(), tempBuf, len, true, false);
Zhenkai Zhud1c5a972012-06-05 14:07:41 -0700453#ifdef __DEBUG
454 std::cout <<"<<< " << name << " fetched" << std::endl;
455#endif
Zhenkai Zhu64f9ede2012-06-05 11:32:00 -0700456}
457
458void
Zhenkai Zhubb198112012-09-27 11:31:42 -0700459ChatDialog::processDataNoShowWrapper(std::string name, const char *buf, size_t len)
460{
Zhenkai Zhuae29f5a2012-10-05 17:28:04 -0700461 char *tempBuf = new char[len];
462 memcpy(tempBuf, buf, len);
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700463 emit dataReceived(name.c_str(), tempBuf, len, false, false);
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700464
465 if (!m_historyInitialized)
466 {
467 fetchHistory(name);
468 m_historyInitialized = true;
469 }
470}
471
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700472void
473ChatDialog::processDataHistoryWrapper(std::string name, const char *buf, size_t len)
474{
475 char *tempBuf = new char[len];
476 memcpy(tempBuf, buf, len);
477 emit dataReceived(name.c_str(), tempBuf, len, true, true);
478}
479
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700480void
481ChatDialog::fetchHistory(std::string name)
482{
483 std::string nameWithoutSeq = name.substr(0, name.find_last_of('/'));
484 std::string prefix = nameWithoutSeq.substr(0, nameWithoutSeq.find_last_of('/'));
485 prefix += "/history";
486 Sync::CcnxWrapperPtr handle = Sync::CcnxWrapper::Create();
487 QString randomString = getRandomString();
488 for (int i = 0; i < MAX_HISTORY_ENTRY; i++)
489 {
490 QString interest = QString("%1/%2/%3").arg(prefix.c_str()).arg(randomString).arg(i);
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700491 handle->sendInterest(interest.toStdString(), bind(&ChatDialog::processDataHistoryWrapper, this, _1, _2, _3));
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700492 }
493}
494
495void
496ChatDialog::respondHistoryRequest(std::string interest)
497{
498 std::string seqStr = interest.substr(interest.find_last_of('/') + 1);
499 int seq = boost::lexical_cast<int>(seqStr);
500 if (seq >= 0 && seq < m_history.size())
501 {
502 Sync::CcnxWrapperPtr handle = Sync::CcnxWrapper::Create();
503 SyncDemo::ChatMessage msg = m_history.at(seq);
504 size_t size = msg.ByteSize();
505 char *buf = new char[size];
506 msg.SerializeToArray(buf, size);
507 handle->publishRawData(interest, buf, size, 1);
508 delete buf;
509 }
Zhenkai Zhubb198112012-09-27 11:31:42 -0700510}
511
512void
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700513ChatDialog::processData(QString name, const char *buf, size_t len, bool show, bool isHistory)
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700514{
515 SyncDemo::ChatMessage msg;
Zhenkai Zhuef8d0632012-10-05 10:24:55 -0700516 bool corrupted = false;
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700517 if (!msg.ParseFromArray(buf, len))
518 {
Zhenkai Zhubb198112012-09-27 11:31:42 -0700519 std::cerr << "Errrrr.. Can not parse msg with name: " << name.toStdString() << ". what is happening?" << std::endl;
Zhenkai Zhuef8d0632012-10-05 10:24:55 -0700520 // nasty stuff: as a remedy, we'll form some standard msg for inparsable msgs
521 msg.set_from("inconnu");
522 msg.set_type(SyncDemo::ChatMessage::OTHER);
523 corrupted = true;
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700524 }
525
Zhenkai Zhuae29f5a2012-10-05 17:28:04 -0700526 delete [] buf;
527 buf = NULL;
528
Zhenkai Zhu10ccb5a2012-06-04 21:55:14 -0700529 // display msg received from network
530 // we have to do so; this function is called by ccnd thread
531 // so if we call appendMsg directly
532 // Qt crash as "QObject: Cannot create children for a parent that is in a different thread"
533 // the "cannonical" way to is use signal-slot
Zhenkai Zhuef8d0632012-10-05 10:24:55 -0700534 if (show && !corrupted)
Zhenkai Zhubb198112012-09-27 11:31:42 -0700535 {
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700536 appendMessage(msg, isHistory);
Zhenkai Zhubb198112012-09-27 11:31:42 -0700537 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700538
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700539 if (!isHistory)
540 {
541 // update the tree view
542 std::string stdStrName = name.toStdString();
543 std::string stdStrNameWithoutSeq = stdStrName.substr(0, stdStrName.find_last_of('/'));
544 std::string prefix = stdStrNameWithoutSeq.substr(0, stdStrNameWithoutSeq.find_last_of('/'));
Zhenkai Zhu097bfe72012-06-05 14:30:17 -0700545#ifdef __DEBUG
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700546 std::cout <<"<<< updating scene for" << prefix << ": " << msg.from() << std::endl;
Zhenkai Zhu097bfe72012-06-05 14:30:17 -0700547#endif
Zhenkai Zhu24ec4722012-10-07 17:56:38 -0700548 if (msg.type() == SyncDemo::ChatMessage::LEAVE)
549 {
550 processRemove(prefix.c_str());
551 }
552 else
553 {
554 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
555 m_scene->msgReceived(prefix.c_str(), msg.from().c_str());
556 }
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700557 }
Zhenkai Zhuc5470612012-06-05 12:28:59 -0700558 fitView();
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700559}
560
561void
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700562ChatDialog::processRemoveWrapper(std::string prefix)
563{
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700564#ifdef __DEBUG
565 std::cout << "Sync REMOVE signal received for prefix: " << prefix << std::endl;
566#endif
567 //emit removeReceived(prefix.c_str());
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700568}
569
570void
571ChatDialog::processRemove(QString prefix)
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700572{
Zhenkai Zhu591e8c32012-09-26 11:57:50 -0700573#ifdef __DEBUG
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700574 std::cout << "<<< remove node for prefix" << prefix.toStdString() << std::endl;
Zhenkai Zhu591e8c32012-09-26 11:57:50 -0700575#endif
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700576 bool removed = m_scene->removeNode(prefix);
Zhenkai Zhu591e8c32012-09-26 11:57:50 -0700577 if (removed)
578 {
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700579 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu591e8c32012-09-26 11:57:50 -0700580 m_scene->plot(m_sock->getRootDigest().c_str());
581 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700582}
583
584void
Zhenkai Zhu85845d22012-06-01 23:10:43 -0700585ChatDialog::formChatMessage(const QString &text, SyncDemo::ChatMessage &msg) {
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700586 msg.set_from(m_user.getNick().toStdString());
587 msg.set_to(m_user.getChatroom().toStdString());
Zhenkai Zhu767eac72012-10-08 11:20:57 -0700588 msg.set_data(text.toUtf8().constData());
Zhenkai Zhu85845d22012-06-01 23:10:43 -0700589 time_t seconds = time(NULL);
590 msg.set_timestamp(seconds);
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700591 msg.set_type(SyncDemo::ChatMessage::CHAT);
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700592}
593
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700594void
Zhenkai Zhub5b78462012-09-28 14:10:37 -0700595ChatDialog::formControlMessage(SyncDemo::ChatMessage &msg, SyncDemo::ChatMessage::ChatMessageType type)
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700596{
597 msg.set_from(m_user.getNick().toStdString());
598 msg.set_to(m_user.getChatroom().toStdString());
599 time_t seconds = time(NULL);
600 msg.set_timestamp(seconds);
Zhenkai Zhub5b78462012-09-28 14:10:37 -0700601 msg.set_type(type);
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700602}
603
Zhenkai Zhu59245aa2012-09-26 16:07:04 -0700604static std::string chars("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789");
605
606QString
607ChatDialog::getRandomString()
608{
609 std::string randStr;
610 boost::random::random_device rng;
611 boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
612 for (int i = 0; i < 10; i ++)
613 {
614 randStr += chars[index_dist(rng)];
615 }
616 return randStr.c_str();
617}
618
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700619bool
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -0700620ChatDialog::getLocalPrefix()
621{
Zhenkai Zhu86581412012-10-08 16:58:39 -0700622// /*
623// * this method tries to use ccncat
624// * however, it does not work in Mac OS X app bundle
625// * it works well in command line though
626// */
627
628// std::string cmd = CCN_EXEC;
629// cmd += " -c -v ";
630// cmd += LOCAL_PREFIX_QUERY;
631// QString localPrefix;
632// #define MAX_PREFIX_LEN 100
633// FILE *fp = popen(cmd.c_str(), "r");
634// if (fp != NULL)
635// {
636// char prefix[MAX_PREFIX_LEN];
637// if (fgets(prefix, MAX_PREFIX_LEN, fp) != NULL)
638// {
639// localPrefix = prefix;
640// localPrefix.remove('\n');
641// }
642// else
643// {
644// localPrefix = DEFAULT_LOCAL_PREFIX;
645// }
646// pclose(fp);
647// }
648// else
649// {
650// localPrefix = DEFAULT_LOCAL_PREFIX;
651// }
652// return localPrefix;
Alexander Afanasyevebe118d2012-10-08 08:56:34 -0700653 std::cerr << "trying to get local prefix" << std::endl;
654
Zhenkai Zhu86581412012-10-08 16:58:39 -0700655 if (m_sock != NULL)
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700656 {
657 QString originPrefix = QString::fromStdString (m_sock->getLocalPrefix()).trimmed ();
658 std::cerr << "got: " << originPrefix.toStdString () << std::endl;
Zhenkai Zhuba707342012-10-08 16:20:15 -0700659
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700660 if (originPrefix != "" && m_user.getOriginPrefix () != originPrefix)
Zhenkai Zhu86581412012-10-08 16:58:39 -0700661 {
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700662 emit settingUpdated(m_user.getNick (), m_user.getChatroom (), originPrefix);
663 // prefix updated
664 return true;
Zhenkai Zhu86581412012-10-08 16:58:39 -0700665 }
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700666 }
667
668 // prefix not changed
669 return false;
670}
671
672void
673ChatDialog::updateLocalPrefix()
674{
675 getLocalPrefix();
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -0700676}
677
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700678bool
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700679ChatDialog::readSettings()
680{
681 QSettings s(ORGANIZATION, APPLICATION);
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700682 QString nick = s.value("nick", "").toString();
683 QString chatroom = s.value("chatroom", "").toString();
Zhenkai Zhu86581412012-10-08 16:58:39 -0700684 // QString originPrefix = s.value("originPrefix", "").toString();
Alexander Afanasyev5ddc68b2012-10-08 00:21:40 -0700685
Zhenkai Zhu86581412012-10-08 16:58:39 -0700686 // Sync::CcnxWrapperPtr wrapper = Sync::CcnxWrapper::Create ();
687 // QString originPrefix = QString::fromStdString (wrapper->getLocalPrefix());
688 // Sync::CcnxWrapper::Destroy ();
Alexander Afanasyev5ddc68b2012-10-08 00:21:40 -0700689
Zhenkai Zhu86581412012-10-08 16:58:39 -0700690 QString originPrefix = DEFAULT_LOCAL_PREFIX;
Alexander Afanasyev5ddc68b2012-10-08 00:21:40 -0700691
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700692 m_minimaniho = s.value("minimaniho", false).toBool();
693 if (nick == "" || chatroom == "" || originPrefix == "") {
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700694 QTimer::singleShot(500, this, SLOT(buttonPressed()));
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700695 return false;
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700696 }
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700697 else {
698 m_user.setNick(nick);
699 m_user.setChatroom(chatroom);
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700700 m_user.setOriginPrefix(originPrefix);
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700701 m_user.setPrefix(originPrefix + "/" + chatroom + "/" + getRandomString());
Zhenkai Zhu716fe852012-10-08 18:27:55 -0700702 m_scene->setCurrentPrefix(originPrefix + "/" + chatroom + "/" + getRandomString());
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700703 return true;
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700704 }
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700705
706// QTimer::singleShot(500, this, SLOT(buttonPressed()));
707 // return false;
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700708}
709
710void
711ChatDialog::writeSettings()
712{
713 QSettings s(ORGANIZATION, APPLICATION);
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700714 s.setValue("nick", m_user.getNick());
715 s.setValue("chatroom", m_user.getChatroom());
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -0700716 //s.setValue("originPrefix", m_user.getOriginPrefix());
Zhenkai Zhu3974a492012-09-28 14:39:45 -0700717 s.setValue("minimaniho", m_minimaniho);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700718}
719
720void
721ChatDialog::updateLabels()
722{
Zhenkai Zhu76ff02b2012-09-27 21:11:03 -0700723 QString settingDisp = QString("Chatroom: %1").arg(m_user.getChatroom());
724 infoLabel->setStyleSheet("QLabel {color: #630; font-size: 16px; font: bold \"Verdana\";}");
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700725 infoLabel->setText(settingDisp);
Zhenkai Zhu6bda0bd2012-10-06 23:50:39 -0700726 QString prefixDisp;
727 if (m_user.getPrefix().startsWith(DEFAULT_LOCAL_PREFIX))
728 {
729 prefixDisp = QString("<Warning: Auto config prefix failed.>\n <Prefix = %1>").arg(m_user.getPrefix());
730 prefixLabel->setStyleSheet("QLabel {color: red; font-size: 12px; font: bold \"Verdana\";}");
731 }
732 else
733 {
734 prefixDisp = QString("<Prefix = %1>").arg(m_user.getPrefix());
735 prefixLabel->setStyleSheet("QLabel {color: Green; font-size: 12px; font: bold \"Verdana\";}");
736 }
737 prefixLabel->setText(prefixDisp);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700738}
739
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700740void
741ChatDialog::returnPressed()
742{
743 QString text = lineEdit->text();
744 if (text.isEmpty())
745 return;
746
Zhenkai Zhub6338822012-05-31 13:27:24 -0700747 lineEdit->clear();
748
Zhenkai Zhu22c7d4d2012-10-09 12:29:32 -0700749 if (text.startsWith("boruoboluomi"))
750 {
751 reapButton->show();
752 fitView();
753 return;
754 }
755
756 if (text.startsWith("minimanihong"))
757 {
758 reapButton->hide();
759 fitView();
760 return;
761 }
762
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700763 SyncDemo::ChatMessage msg;
764 formChatMessage(text, msg);
765
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700766 appendMessage(msg);
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700767
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700768 sendMsg(msg);
769
770 fitView();
771}
772
773void
774ChatDialog::sendMsg(SyncDemo::ChatMessage &msg)
775{
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700776 // send msg
777 size_t size = msg.ByteSize();
778 char *buf = new char[size];
779 msg.SerializeToArray(buf, size);
780 if (!msg.IsInitialized())
781 {
782 std::cerr << "Errrrr.. msg was not probally initialized "<<__FILE__ <<":"<<__LINE__<<". what is happening?" << std::endl;
783 abort();
784 }
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700785 m_sock->publishRaw(m_user.getPrefix().toStdString(), m_session, buf, size, FRESHNESS);
Zhenkai Zhuc5470612012-06-05 12:28:59 -0700786
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700787 delete buf;
788
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700789 m_lastMsgTime = time(NULL);
790
Zhenkai Zhuc5470612012-06-05 12:28:59 -0700791 int nextSequence = m_sock->getNextSeq(m_user.getPrefix().toStdString(), m_session);
Zhenkai Zhud1c5a972012-06-05 14:07:41 -0700792 Sync::MissingDataInfo mdi = {m_user.getPrefix().toStdString(), Sync::SeqNo(0), Sync::SeqNo(nextSequence - 1)};
Zhenkai Zhuc5470612012-06-05 12:28:59 -0700793 std::vector<Sync::MissingDataInfo> v;
794 v.push_back(mdi);
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700795 {
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700796 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700797 m_scene->processUpdate(v, m_sock->getRootDigest().c_str());
798 m_scene->msgReceived(m_user.getPrefix(), m_user.getNick());
799 }
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700800}
801
802void
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700803ChatDialog::sendJoin()
804{
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700805 m_joined = true;
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700806 SyncDemo::ChatMessage msg;
Zhenkai Zhub5b78462012-09-28 14:10:37 -0700807 formControlMessage(msg, SyncDemo::ChatMessage::JOIN);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700808 sendMsg(msg);
Zhenkai Zhuc61dbc22012-10-08 11:36:37 -0700809 boost::random::random_device rng;
810 boost::random::uniform_int_distribution<> uniform(1, FRESHNESS / 5 * 1000);
811 m_randomizedInterval = HELLO_INTERVAL * 1000 + uniform(rng);
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700812 QTimer::singleShot(m_randomizedInterval, this, SLOT(sendHello()));
813}
814
815void
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700816ChatDialog::sendHello()
817{
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700818 time_t now = time(NULL);
819 int elapsed = now - m_lastMsgTime;
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700820 if (elapsed >= m_randomizedInterval / 1000)
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700821 {
822 SyncDemo::ChatMessage msg;
Zhenkai Zhub5b78462012-09-28 14:10:37 -0700823 formControlMessage(msg, SyncDemo::ChatMessage::HELLO);
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700824 sendMsg(msg);
Zhenkai Zhuc61dbc22012-10-08 11:36:37 -0700825 boost::random::random_device rng;
826 boost::random::uniform_int_distribution<> uniform(1, FRESHNESS / 5 * 1000);
827 m_randomizedInterval = HELLO_INTERVAL * 1000 + uniform(rng);
Zhenkai Zhuee5c90f2012-09-27 14:05:41 -0700828 QTimer::singleShot(m_randomizedInterval, this, SLOT(sendHello()));
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700829 }
830 else
831 {
Zhenkai Zhuee5c90f2012-09-27 14:05:41 -0700832 QTimer::singleShot((m_randomizedInterval - elapsed * 1000), this, SLOT(sendHello()));
Zhenkai Zhu3e26bb42012-09-27 11:04:09 -0700833 }
Zhenkai Zhu5a8d5aa2012-05-30 21:25:23 -0700834}
835
836void
Zhenkai Zhu85845d22012-06-01 23:10:43 -0700837ChatDialog::buttonPressed()
838{
Alexander Afanasyev5ddc68b2012-10-08 00:21:40 -0700839 Sync::SyncLogic &logic = m_sock->getLogic ();
840 logic.printState ();
841
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700842 SettingDialog dialog(this, m_user.getNick(), m_user.getChatroom(), m_user.getOriginPrefix());
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700843 connect(&dialog, SIGNAL(updated(QString, QString, QString)), this, SLOT(settingUpdated(QString, QString, QString)));
Zhenkai Zhu85845d22012-06-01 23:10:43 -0700844 dialog.exec();
Zhenkai Zhue837f792012-06-05 20:47:54 -0700845 QTimer::singleShot(100, this, SLOT(checkSetting()));
846}
847
Zhenkai Zhub60b7e12012-09-28 11:34:21 -0700848void ChatDialog::treeButtonPressed()
849{
850 if (treeViewer->isVisible())
851 {
852 treeViewer->hide();
853 treeButton->setText("Show Sync Tree");
854 }
855 else
856 {
857 treeViewer->show();
858 treeButton->setText("Hide Sync Tree");
859 }
Zhenkai Zhu25e33e52012-09-28 13:00:07 -0700860
861 fitView();
Zhenkai Zhub60b7e12012-09-28 11:34:21 -0700862}
863
Zhenkai Zhu0e7a9b22012-10-05 17:55:17 -0700864void ChatDialog::enableTreeDisplay()
865{
866 treeButton->setEnabled(true);
867 treeViewer->show();
868 fitView();
869}
870
871void ChatDialog::disableTreeDisplay()
872{
873 treeButton->setEnabled(false);
874 treeViewer->hide();
875 fitView();
876}
877
Zhenkai Zhue837f792012-06-05 20:47:54 -0700878void
879ChatDialog::checkSetting()
880{
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700881 if (m_user.getOriginPrefix().isEmpty() || m_user.getNick().isEmpty() || m_user.getChatroom().isEmpty())
Zhenkai Zhue837f792012-06-05 20:47:54 -0700882 {
883 buttonPressed();
884 }
Zhenkai Zhu6d589aa2012-05-29 17:34:35 -0700885}
Zhenkai Zhue08afe02012-05-31 15:49:07 -0700886
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700887void
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700888ChatDialog::settingUpdated(QString nick, QString chatroom, QString originPrefix)
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700889{
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700890 QString randString = getRandomString();
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700891 bool needWrite = false;
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700892 bool needFresh = false;
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700893 if (!nick.isEmpty() && nick != m_user.getNick()) {
894 m_user.setNick(nick);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700895 needWrite = true;
896 }
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700897 QString oldPrefix = m_user.getPrefix();
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700898 if (!originPrefix.isEmpty() && originPrefix != m_user.getOriginPrefix()) {
899 m_user.setOriginPrefix(originPrefix);
900 m_user.setPrefix(originPrefix + "/" + m_user.getChatroom() + "/" + randString);
Zhenkai Zhu716fe852012-10-08 18:27:55 -0700901 m_scene->setCurrentPrefix(originPrefix + "/" + m_user.getChatroom() + "/" + randString);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700902 needWrite = true;
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700903 needFresh = true;
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700904 }
Zhenkai Zhu71b42cb2012-06-04 09:42:53 -0700905 if (!chatroom.isEmpty() && chatroom != m_user.getChatroom()) {
906 m_user.setChatroom(chatroom);
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700907 m_user.setPrefix(m_user.getOriginPrefix() + "/" + chatroom + "/" + randString);
Zhenkai Zhu716fe852012-10-08 18:27:55 -0700908 m_scene->setCurrentPrefix(m_user.getOriginPrefix() + "/" + chatroom + "/" + randString);
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700909 needWrite = true;
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700910 needFresh = true;
911 }
912
913 if (needFresh)
914 {
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700915
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700916 {
Zhenkai Zhu9036e032012-09-27 20:59:33 -0700917 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu44b43752012-06-05 21:18:37 -0700918 m_scene->clearAll();
919 m_scene->plot("Empty");
920 }
Zhenkai Zhucc4c2c02012-09-27 21:24:37 -0700921
922 textEdit->clear();
923
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700924 if (m_sock != NULL)
925 {
Zhenkai Zhu77fc8f22012-10-08 15:12:56 -0700926 // keep the new prefix
927 QString newPrefix = m_user.getPrefix();
928 // send leave for the old
929 m_user.setPrefix(oldPrefix);
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700930 // there is no point to send leave if we haven't joined yet
931 if (m_joined)
932 {
933 sendLeave();
934 }
Zhenkai Zhu77fc8f22012-10-08 15:12:56 -0700935 // resume new prefix
936 m_user.setPrefix(newPrefix);
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700937 Sync::CcnxWrapperPtr handle = Sync::CcnxWrapper::Create();
938 handle->clearInterestFilter(oldPrefix.toStdString());
939 m_history.clear();
940 m_historyInitialized = false;
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700941 delete m_sock;
942 m_sock = NULL;
943 }
944 std::string syncPrefix = BROADCAST_PREFIX_FOR_SYNC_DEMO;
945 syncPrefix += "/";
946 syncPrefix += m_user.getChatroom().toStdString();
Zhenkai Zhua4fb1242012-06-05 20:26:05 -0700947 try
948 {
Zhenkai Zhu2425b6a2012-09-26 17:11:44 -0700949 m_sock = new Sync::SyncAppSocket(syncPrefix, bind(&ChatDialog::processTreeUpdateWrapper, this, _1, _2), bind(&ChatDialog::processRemoveWrapper, this, _1));
Zhenkai Zhu6c4fc112012-10-07 17:07:43 -0700950 Sync::CcnxWrapperPtr handle = Sync::CcnxWrapper::Create();
951 handle->setInterestFilter(m_user.getPrefix().toStdString(), bind(&ChatDialog::respondHistoryRequest, this, _1));
Zhenkai Zhu0fe2b8c2012-10-09 04:49:28 -0700952 QTimer::singleShot(600, this, SLOT(sendJoin()));
Zhenkai Zhu78799ea2012-10-08 11:51:56 -0700953 m_timer->start(FRESHNESS * 1000);
Zhenkai Zhu0e7a9b22012-10-05 17:55:17 -0700954 disableTreeDisplay();
955 QTimer::singleShot(2200, this, SLOT(enableTreeDisplay()));
Zhenkai Zhua4fb1242012-06-05 20:26:05 -0700956 }
957 catch (Sync::CcnxOperationException ex)
958 {
Zhenkai Zhu0b3fa332012-09-27 21:58:43 -0700959 QMessageBox::critical(this, tr("Chronos"), tr("Canno connect to ccnd.\n Have you started your ccnd?"), QMessageBox::Ok);
Zhenkai Zhua4fb1242012-06-05 20:26:05 -0700960 std::exit(1);
961 }
Zhenkai Zhu82a62752012-06-04 17:11:04 -0700962
963 fitView();
964
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700965 }
Zhenkai Zhue95c64a2012-09-27 21:46:44 -0700966
Zhenkai Zhu7e9b06d2012-06-02 00:44:42 -0700967 if (needWrite) {
968 writeSettings();
969 updateLabels();
970 }
971}
Zhenkai Zhud13acd02012-06-04 15:25:20 -0700972
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -0700973void
974ChatDialog::iconActivated(QSystemTrayIcon::ActivationReason reason)
975{
976 switch (reason)
977 {
978 case QSystemTrayIcon::Trigger:
979 case QSystemTrayIcon::DoubleClick:
980 break;
981 case QSystemTrayIcon::MiddleClick:
982 // showMessage();
983 break;
984 default:;
985 }
986}
987
988void
989ChatDialog::showMessage(QString from, QString data)
990{
991 // std::cout <<"Showing Message: " << from.toStdString() << ": " << data.toStdString() << std::endl;
992 if (!isActiveWindow())
993 {
994 trayIcon->showMessage(QString("Chatroom %1 has a new message").arg(m_user.getChatroom()), QString("<%1>: %2").arg(from).arg(data), QSystemTrayIcon::Information, 20000);
995 trayIcon->setIcon(QIcon(":/images/note.png"));
996 }
997}
998
999void
1000ChatDialog::messageClicked()
1001{
1002 this->showMaximized();
1003}
1004
1005void
1006ChatDialog::createActions()
1007{
1008 minimizeAction = new QAction(tr("Mi&nimize"), this);
1009 connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
1010
1011 maximizeAction = new QAction(tr("Ma&ximize"), this);
1012 connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
1013
1014 restoreAction = new QAction(tr("&Restore"), this);
1015 connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
1016
1017 quitAction = new QAction(tr("Quit"), this);
1018 connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
1019}
1020
1021void
1022ChatDialog::createTrayIcon()
1023{
1024 trayIconMenu = new QMenu(this);
1025 trayIconMenu->addAction(minimizeAction);
1026 trayIconMenu->addAction(maximizeAction);
1027 trayIconMenu->addAction(restoreAction);
1028 trayIconMenu->addSeparator();
1029 trayIconMenu->addAction(quitAction);
1030
1031 trayIcon = new QSystemTrayIcon(this);
1032 trayIcon->setContextMenu(trayIconMenu);
1033
1034 QIcon icon(":/images/icon_small.png");
1035 trayIcon->setIcon(icon);
1036 setWindowIcon(icon);
Zhenkai Zhu0b3fa332012-09-27 21:58:43 -07001037 trayIcon->setToolTip("Chronos System Tray Icon");
Zhenkai Zhu3a008fc2012-06-08 17:36:39 -07001038 trayIcon->setVisible(true);
1039}
1040
Zhenkai Zhud13acd02012-06-04 15:25:20 -07001041void
1042ChatDialog::resizeEvent(QResizeEvent *e)
1043{
1044 fitView();
1045}
1046
1047void
1048ChatDialog::showEvent(QShowEvent *e)
1049{
1050 fitView();
1051}
1052
1053void
1054ChatDialog::fitView()
1055{
Zhenkai Zhu9036e032012-09-27 20:59:33 -07001056 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
Zhenkai Zhu21d75f92012-06-04 21:23:34 -07001057 QRectF rect = m_scene->itemsBoundingRect();
1058 m_scene->setSceneRect(rect);
Zhenkai Zhu82a62752012-06-04 17:11:04 -07001059 treeViewer->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio);
Zhenkai Zhud13acd02012-06-04 15:25:20 -07001060}