Update style to (almost) conform to ndn-cxx style using clang-format
diff --git a/gui/chronosharegui.cpp b/gui/chronosharegui.cpp
index d9c4409..781127e 100644
--- a/gui/chronosharegui.cpp
+++ b/gui/chronosharegui.cpp
@@ -21,12 +21,12 @@
#include "chronosharegui.hpp"
#include "core/chronoshare-config.hpp"
-#include "logging.hpp"
#include "ccnx-wrapper.hpp"
-#include <QValidator>
+#include "logging.hpp"
+#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
-#include <QDesktopServices>
+#include <QValidator>
#include <boost/make_shared.hpp>
@@ -43,35 +43,36 @@
static const QString ICON_BIG_FILE(":/images/chronoshare-big.png");
static const QString ICON_TRAY_FILE(":/images/" TRAY_ICON);
-INIT_LOGGER ("Gui");
+INIT_LOGGER("Gui");
-ChronoShareGui::ChronoShareGui(QWidget *parent)
+ChronoShareGui::ChronoShareGui(QWidget* parent)
: QDialog(parent)
, m_watcher(0)
, m_dispatcher(0)
, m_httpServer(0)
#ifdef ADHOC_SUPPORTED
- , m_executor (1)
+ , m_executor(1)
#endif
#ifdef SPARKLE_SUPPORTED
- , m_autoUpdate(new SparkleAutoUpdate(tr("http://irl.cs.ucla.edu/~zhenkai/chronoshare_dist/chronoshare.xml")))
+ , m_autoUpdate(
+ new SparkleAutoUpdate(tr("http://irl.cs.ucla.edu/~zhenkai/chronoshare_dist/chronoshare.xml")))
#endif
{
setWindowTitle("Settings");
- setMinimumWidth (600);
+ setMinimumWidth(600);
labelUsername = new QLabel("Username (hint: /<username>)");
labelSharedFolder = new QLabel("Shared Folder Name");
labelSharedFolderPath = new QLabel("Shared Folder Path");
QRegExp regex("(/[^/]+)+$");
- QValidator *prefixValidator = new QRegExpValidator(regex, this);
+ QValidator* prefixValidator = new QRegExpValidator(regex, this);
editUsername = new QLineEdit();
editUsername->setValidator(prefixValidator);
QRegExp noPureWhiteSpace("^\\S+.*$");
- QValidator *wsValidator = new QRegExpValidator(noPureWhiteSpace, this);
+ QValidator* wsValidator = new QRegExpValidator(noPureWhiteSpace, this);
editSharedFolder = new QLineEdit();
editSharedFolder->setValidator(wsValidator);
@@ -111,109 +112,100 @@
m_trayIcon->show();
// load settings
- if(!loadSettings())
- {
- // prompt user to choose folder
- openMessageBox("First Time Setup", "Please enter a username, shared folder name and choose the shared folder path on your local filesystem.");
- viewSettings();
- openFileDialog();
+ if (!loadSettings()) {
+ // prompt user to choose folder
+ openMessageBox("First Time Setup",
+ "Please enter a username, shared folder name and choose the shared folder path on your local filesystem.");
+ viewSettings();
+ openFileDialog();
+ viewSettings();
+ }
+ else {
+ if (m_username.isNull() || m_username == "" || m_sharedFolderName.isNull() ||
+ m_sharedFolderName == "") {
+ openMessageBox("First Time Setup",
+ "To activate ChronoShare, please configure your username and shared folder name.");
viewSettings();
}
- else
- {
- if (m_username.isNull () || m_username == "" ||
- m_sharedFolderName.isNull () || m_sharedFolderName == "")
- {
- openMessageBox("First Time Setup", "To activate ChronoShare, please configure your username and shared folder name.");
- viewSettings();
- }
- else
- {
- startBackend();
- }
+ else {
+ startBackend();
}
+ }
#ifdef ADHOC_SUPPORTED
- m_executor.start ();
+ m_executor.start();
#endif
}
void
-ChronoShareGui::startBackend (bool restart/*=false*/)
+ChronoShareGui::startBackend(bool restart /*=false*/)
{
- if (m_username.isNull () || m_username=="" ||
- m_sharedFolderName.isNull () || m_sharedFolderName=="" ||
- m_dirPath.isNull () || m_dirPath=="")
- {
- _LOG_DEBUG ("Don't start backend, because settings are in progress or incomplete");
+ if (m_username.isNull() || m_username == "" || m_sharedFolderName.isNull() ||
+ m_sharedFolderName == "" || m_dirPath.isNull() || m_dirPath == "") {
+ _LOG_DEBUG("Don't start backend, because settings are in progress or incomplete");
+ return;
+ }
+
+ if (m_watcher != 0 && m_dispatcher != 0) {
+ if (!restart) {
return;
}
- if (m_watcher != 0 && m_dispatcher != 0)
- {
- if (!restart)
- {
- return;
- }
-
- _LOG_DEBUG ("Restarting Dispatcher and FileWatcher for the new location or new username");
+ _LOG_DEBUG("Restarting Dispatcher and FileWatcher for the new location or new username");
delete m_watcher; // stop filewatching ASAP
delete m_dispatcher; // stop dispatcher ASAP, but after watcher (to prevent triggering callbacks on deleted object)
}
- filesystem::path realPathToFolder (m_dirPath.toStdString ());
- realPathToFolder /= m_sharedFolderName.toStdString ();
+ filesystem::path realPathToFolder(m_dirPath.toStdString());
+ realPathToFolder /= m_sharedFolderName.toStdString();
- m_dispatcher = new Dispatcher (m_username.toStdString (), m_sharedFolderName.toStdString (),
- realPathToFolder, make_shared<NdnxWrapper> ());
+ m_dispatcher = new Dispatcher(m_username.toStdString(), m_sharedFolderName.toStdString(),
+ realPathToFolder, make_shared<CcnxWrapper>());
// Alex: this **must** be here, otherwise m_dirPath will be uninitialized
- m_watcher = new FsWatcher (realPathToFolder.string ().c_str (),
- bind (&Dispatcher::Did_LocalFile_AddOrModify, m_dispatcher, _1),
- bind (&Dispatcher::Did_LocalFile_Delete, m_dispatcher, _1));
+ m_watcher = new FsWatcher(realPathToFolder.string().c_str(),
+ bind(&Dispatcher::Did_LocalFile_AddOrModify, m_dispatcher, _1),
+ bind(&Dispatcher::Did_LocalFile_Delete, m_dispatcher, _1));
- if (m_httpServer != 0)
- {
- // no need to restart webserver if it already exists
- return;
- }
+ if (m_httpServer != 0) {
+ // no need to restart webserver if it already exists
+ return;
+ }
QFileInfo indexHtmlInfo(":/html/index.html");
- if (indexHtmlInfo.exists())
- {
- try
- {
+ if (indexHtmlInfo.exists()) {
+ try {
m_httpServer = new http::server::server(HTTP_SERVER_ADDRESS, HTTP_SERVER_PORT, DOC_ROOT);
m_httpServerThread = boost::thread(&http::server::server::run, m_httpServer);
}
- catch (std::exception &e)
- {
- _LOG_ERROR ("Start http server failed");
+ catch (std::exception& e) {
+ _LOG_ERROR("Start http server failed");
m_httpServer = 0; // just to make sure
QMessageBox msgBox;
- msgBox.setText ("WARNING: Cannot start http server!");
- msgBox.setIcon (QMessageBox::Warning);
- msgBox.setInformativeText(QString("Starting http server failed. You will not be able to check history from web brower. Exception caused: %1").arg(e.what()));
+ msgBox.setText("WARNING: Cannot start http server!");
+ msgBox.setIcon(QMessageBox::Warning);
+ msgBox.setInformativeText(
+ QString(
+ "Starting http server failed. You will not be able to check history from web brower. Exception caused: %1")
+ .arg(e.what()));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
}
}
- else
- {
- _LOG_ERROR ("Http server doc root dir does not exist!");
+ else {
+ _LOG_ERROR("Http server doc root dir does not exist!");
}
}
ChronoShareGui::~ChronoShareGui()
{
#ifdef ADHOC_SUPPORTED
- m_executor.shutdown ();
+ m_executor.shutdown();
#endif
delete m_watcher; // stop filewatching ASAP
delete m_dispatcher; // stop dispatcher ASAP, but after watcher (to prevent triggering callbacks on deleted object)
- if (m_httpServer != 0)
- {
+ if (m_httpServer != 0) {
m_httpServer->handle_stop();
m_httpServerThread.join();
delete m_httpServer;
@@ -243,7 +235,8 @@
delete mainLayout;
}
-void ChronoShareGui::openMessageBox(QString title, QString text)
+void
+ChronoShareGui::openMessageBox(QString title, QString text)
{
QMessageBox messageBox(this);
messageBox.setWindowTitle(title);
@@ -254,7 +247,8 @@
messageBox.exec();
}
-void ChronoShareGui::openMessageBox(QString title, QString text, QString infotext)
+void
+ChronoShareGui::openMessageBox(QString title, QString text, QString infotext)
{
QMessageBox messageBox(this);
messageBox.setWindowTitle(title);
@@ -266,9 +260,10 @@
messageBox.exec();
}
-void ChronoShareGui::createActionsAndMenu()
+void
+ChronoShareGui::createActionsAndMenu()
{
- _LOG_DEBUG ("Create actions");
+ _LOG_DEBUG("Create actions");
// create the "open folder" action
m_openFolder = new QAction(tr("&Open Folder"), this);
@@ -278,8 +273,7 @@
connect(m_openWeb, SIGNAL(triggered()), this, SLOT(openInWebBrowser()));
m_recentFilesMenu = new QMenu(tr("Recently Changed Files"), this);
- for (int i = 0; i < 5; i++)
- {
+ for (int i = 0; i < 5; i++) {
m_fileActions[i] = new QAction(this);
m_fileActions[i]->setVisible(false);
connect(m_fileActions[i], SIGNAL(triggered()), this, SLOT(openFile()));
@@ -297,15 +291,15 @@
#ifdef ADHOC_SUPPORTED
// create "AdHoc Wifi" action
- m_wifiAction = new QAction (tr("Enable AdHoc &WiFI"), m_trayIconMenu);
- m_wifiAction->setChecked (false);
- m_wifiAction->setCheckable (true);
- connect (m_wifiAction, SIGNAL (toggled(bool)), this, SLOT(onAdHocChange(bool)));
+ m_wifiAction = new QAction(tr("Enable AdHoc &WiFI"), m_trayIconMenu);
+ m_wifiAction->setChecked(false);
+ m_wifiAction->setCheckable(true);
+ connect(m_wifiAction, SIGNAL(toggled(bool)), this, SLOT(onAdHocChange(bool)));
#endif
#ifdef SPARKLE_SUPPORTED
- m_checkForUpdates = new QAction (tr("Check For Updates"), this);
- connect (m_checkForUpdates, SIGNAL(triggered()), this, SLOT(onCheckForUpdates()));
+ m_checkForUpdates = new QAction(tr("Check For Updates"), this);
+ connect(m_checkForUpdates, SIGNAL(triggered()), this, SLOT(onCheckForUpdates()));
#endif
// create the "quit program" action
@@ -313,7 +307,8 @@
connect(m_quitProgram, SIGNAL(triggered()), qApp, SLOT(quit()));
}
-void ChronoShareGui::createTrayIcon()
+void
+ChronoShareGui::createTrayIcon()
{
// create a new icon menu
m_trayIconMenu = new QMenu(this);
@@ -346,45 +341,42 @@
m_trayIcon->setContextMenu(m_trayIconMenu);
// handle left click of icon
- connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClicked(QSystemTrayIcon::ActivationReason)));
+ connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
+ SLOT(trayIconClicked(QSystemTrayIcon::ActivationReason)));
}
void
-ChronoShareGui::onAdHocChange (bool state)
+ChronoShareGui::onAdHocChange(bool state)
{
#ifdef ADHOC_SUPPORTED
- if (m_wifiAction->isChecked ())
- {
- QMessageBox msgBox;
- msgBox.setText ("WARNING: your WiFi will be disconnected");
- msgBox.setIcon (QMessageBox::Warning);
- msgBox.setInformativeText("AdHoc WiFi will disconnect your current WiFi.\n Are you sure that you are OK with that?");
- msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
- msgBox.setDefaultButton(QMessageBox::Cancel);
- int ret = msgBox.exec();
+ if (m_wifiAction->isChecked()) {
+ QMessageBox msgBox;
+ msgBox.setText("WARNING: your WiFi will be disconnected");
+ msgBox.setIcon(QMessageBox::Warning);
+ msgBox.setInformativeText(
+ "AdHoc WiFi will disconnect your current WiFi.\n Are you sure that you are OK with that?");
+ msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
+ msgBox.setDefaultButton(QMessageBox::Cancel);
+ int ret = msgBox.exec();
- if (ret == QMessageBox::Cancel)
- {
- m_wifiAction->setChecked (false);
- }
- else
- {
-
- m_wifiAction->setText (tr("Disable AdHoc WiFI"));
-
- // create adhoc
- m_executor.execute (Adhoc::CreateAdhoc);
- }
+ if (ret == QMessageBox::Cancel) {
+ m_wifiAction->setChecked(false);
}
- else
- {
- m_wifiAction->setText (tr("Enable AdHoc WiFI"));
+ else {
+ m_wifiAction->setText(tr("Disable AdHoc WiFI"));
- // disable adhoc
- m_executor.execute (Adhoc::DestroyAdhoc);
-
- // a trick in DestroyAdhoc ensures that WiFi will be reconnected to a default WiFi
+ // create adhoc
+ m_executor.execute(Adhoc::CreateAdhoc);
}
+ }
+ else {
+ m_wifiAction->setText(tr("Enable AdHoc WiFI"));
+
+ // disable adhoc
+ m_executor.execute(Adhoc::DestroyAdhoc);
+
+ // a trick in DestroyAdhoc ensures that WiFi will be reconnected to a default WiFi
+ }
#endif
}
@@ -398,38 +390,43 @@
#endif
}
-void ChronoShareGui::setIcon()
+void
+ChronoShareGui::setIcon()
{
// set the icon image
m_trayIcon->setIcon(QIcon(ICON_TRAY_FILE));
}
-void ChronoShareGui::openSharedFolder()
+void
+ChronoShareGui::openSharedFolder()
{
- filesystem::path realPathToFolder (m_dirPath.toStdString ());
- realPathToFolder /= m_sharedFolderName.toStdString ();
+ filesystem::path realPathToFolder(m_dirPath.toStdString());
+ realPathToFolder /= m_sharedFolderName.toStdString();
QString path = QDir::toNativeSeparators(realPathToFolder.string().c_str());
QDesktopServices::openUrl(QUrl("file:///" + path));
}
-void ChronoShareGui::openInWebBrowser()
+void
+ChronoShareGui::openInWebBrowser()
{
- QUrl url ("http://localhost:9001/");
- url.setFragment ("folderHistory&"
- "user=" + QUrl::toPercentEncoding (m_username) + "&"
- "folder=" + QUrl::toPercentEncoding (m_sharedFolderName));
+ QUrl url("http://localhost:9001/");
+ url.setFragment("folderHistory&"
+ "user=" +
+ QUrl::toPercentEncoding(m_username) + "&"
+ "folder=" +
+ QUrl::toPercentEncoding(m_sharedFolderName));
// i give up. there is double encoding and I have no idea how to fight it...
- QDesktopServices::openUrl (url);
+ QDesktopServices::openUrl(url);
}
-void ChronoShareGui::openFile()
+void
+ChronoShareGui::openFile()
{
// figure out who sent the signal
- QAction *pAction = qobject_cast<QAction*>(sender());
- if (pAction->isEnabled())
- {
- // we stored full path of the file in this toolTip field
+ QAction* pAction = qobject_cast<QAction*>(sender());
+ if (pAction->isEnabled()) {
+// we stored full path of the file in this toolTip field
#ifdef Q_WS_MAC
// we do some hack so we could show the file in Finder highlighted
QStringList args;
@@ -449,30 +446,31 @@
}
}
-void ChronoShareGui::updateRecentFilesMenu()
+void
+ChronoShareGui::updateRecentFilesMenu()
{
- for (int i = 0; i < 5; i++)
- {
+ for (int i = 0; i < 5; i++) {
m_fileActions[i]->setVisible(false);
}
- m_dispatcher->LookupRecentFileActions(boost::bind(&ChronoShareGui::checkFileAction, this, _1, _2, _3), 5);
+ m_dispatcher->LookupRecentFileActions(boost::bind(&ChronoShareGui::checkFileAction, this, _1, _2,
+ _3),
+ 5);
}
-void ChronoShareGui::checkFileAction (const std::string &filename, int action, int index)
+void
+ChronoShareGui::checkFileAction(const std::string& filename, int action, int index)
{
- filesystem::path realPathToFolder (m_dirPath.toStdString ());
- realPathToFolder /= m_sharedFolderName.toStdString ();
+ filesystem::path realPathToFolder(m_dirPath.toStdString());
+ realPathToFolder /= m_sharedFolderName.toStdString();
realPathToFolder /= filename;
- QString fullPath = realPathToFolder.string().c_str();
+ QString fullPath = realPathToFolder.string().c_str();
QFileInfo fileInfo(fullPath);
- if (fileInfo.exists())
- {
+ if (fileInfo.exists()) {
// This is a hack, we just use some field to store the path
m_fileActions[index]->setToolTip(fileInfo.absolutePath());
m_fileActions[index]->setEnabled(true);
}
- else
- {
+ else {
// after half an hour frustrating test and search around,
// I think it's the problem of Qt.
// According to the Qt doc, the action cannot be clicked
@@ -483,8 +481,7 @@
// Give up at least for now
m_fileActions[index]->setEnabled(false);
// UPDATE, file not fetched yet
- if (action == 0)
- {
+ if (action == 0) {
QFont font;
// supposed by change the font, didn't happen
font.setWeight(QFont::Light);
@@ -492,8 +489,7 @@
m_fileActions[index]->setToolTip(tr("Fetching..."));
}
// DELETE
- else
- {
+ else {
QFont font;
// supposed by change the font, didn't happen
font.setStrikeOut(true);
@@ -505,100 +501,95 @@
m_fileActions[index]->setVisible(true);
}
-void ChronoShareGui::changeSettings()
+void
+ChronoShareGui::changeSettings()
{
QString oldUsername = m_username;
QString oldSharedFolderName = m_sharedFolderName;
- if(!editUsername->text().isEmpty())
+ if (!editUsername->text().isEmpty())
m_username = editUsername->text().trimmed();
else
editUsername->setText(m_username);
- if(!editSharedFolder->text().isEmpty())
+ if (!editSharedFolder->text().isEmpty())
m_sharedFolderName = editSharedFolder->text().trimmed();
else
editSharedFolder->setText(m_sharedFolderName);
- if (m_username.isNull () || m_username=="" ||
- m_sharedFolderName.isNull () || m_sharedFolderName=="")
- {
- openMessageBox ("Error",
- "Username and shared folder name cannot be empty");
- }
- else
- {
- saveSettings();
- this->hide();
+ if (m_username.isNull() || m_username == "" || m_sharedFolderName.isNull() ||
+ m_sharedFolderName == "") {
+ openMessageBox("Error", "Username and shared folder name cannot be empty");
+ }
+ else {
+ saveSettings();
+ this->hide();
- if (m_username != oldUsername ||
- oldSharedFolderName != m_sharedFolderName)
- {
- startBackend (true); // restart dispatcher/fswatcher
- }
+ if (m_username != oldUsername || oldSharedFolderName != m_sharedFolderName) {
+ startBackend(true); // restart dispatcher/fswatcher
}
+ }
}
-void ChronoShareGui::openFileDialog()
+void
+ChronoShareGui::openFileDialog()
{
- while (true)
- {
- // prompt user for new directory
- QString tempPath = QFileDialog::getExistingDirectory(this, tr("Choose ChronoShare folder"),
- m_dirPath, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
- if (tempPath.isNull ())
- {
- if (m_dirPath.isNull ())
- {
- openMessageBox ("Notice", "ChronoShare will use [" + QDir::homePath () + "/ChronoShare]. \n\nYou can change it later selecting \"Change Folder\" menu.");
+ while (true) {
+ // prompt user for new directory
+ QString tempPath =
+ QFileDialog::getExistingDirectory(this, tr("Choose ChronoShare folder"), m_dirPath,
+ QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
+ if (tempPath.isNull()) {
+ if (m_dirPath.isNull()) {
+ openMessageBox("Notice",
+ "ChronoShare will use [" + QDir::homePath() +
+ "/ChronoShare]. \n\nYou can change it later selecting \"Change Folder\" menu.");
- m_dirPath = QDir::homePath () + "/ChronoShare";
- editSharedFolderPath->setText (m_dirPath);
- break;
- }
- else
- {
- // user just cancelled, no need to do anything else
- return;
- }
- }
-
- QFileInfo qFileInfo (tempPath);
-
- if (!qFileInfo.isDir())
- {
- openMessageBox ("Error", "Please select an existing folder or create a new one.");
- continue;
- }
-
- if (m_dirPath == tempPath)
- {
- // user selected the same directory, no need to do anything
- return;
- }
-
- m_dirPath = tempPath;
- editSharedFolderPath->setText(m_dirPath);
- break;
+ m_dirPath = QDir::homePath() + "/ChronoShare";
+ editSharedFolderPath->setText(m_dirPath);
+ break;
+ }
+ else {
+ // user just cancelled, no need to do anything else
+ return;
+ }
}
- _LOG_DEBUG ("Selected path: " << m_dirPath.toStdString ());
- // save settings
- saveSettings ();
+ QFileInfo qFileInfo(tempPath);
- startBackend (true); // restart dispatcher/fswatcher
+ if (!qFileInfo.isDir()) {
+ openMessageBox("Error", "Please select an existing folder or create a new one.");
+ continue;
+ }
+
+ if (m_dirPath == tempPath) {
+ // user selected the same directory, no need to do anything
+ return;
+ }
+
+ m_dirPath = tempPath;
+ editSharedFolderPath->setText(m_dirPath);
+ break;
+ }
+
+ _LOG_DEBUG("Selected path: " << m_dirPath.toStdString());
+ // save settings
+ saveSettings();
+
+ startBackend(true); // restart dispatcher/fswatcher
}
-void ChronoShareGui::trayIconClicked (QSystemTrayIcon::ActivationReason reason)
+void
+ChronoShareGui::trayIconClicked(QSystemTrayIcon::ActivationReason reason)
{
// if double clicked, open shared folder
- if(reason == QSystemTrayIcon::DoubleClick)
- {
- openSharedFolder();
- }
+ if (reason == QSystemTrayIcon::DoubleClick) {
+ openSharedFolder();
+ }
}
-void ChronoShareGui::viewSettings()
+void
+ChronoShareGui::viewSettings()
{
//simple for now
this->show();
@@ -606,80 +597,77 @@
this->activateWindow();
}
-bool ChronoShareGui::loadSettings()
+bool
+ChronoShareGui::loadSettings()
{
bool successful = true;
// Load Settings
// QSettings settings(m_settingsFilePath, QSettings::NativeFormat);
- QSettings settings (QSettings::NativeFormat, QSettings::UserScope, "irl.cs.ucla.edu", "ChronoShare");
+ QSettings settings(QSettings::NativeFormat, QSettings::UserScope, "irl.cs.ucla.edu", "ChronoShare");
// _LOG_DEBUG (lexical_cast<string> (settings.allKeys()));
- if(settings.contains("username"))
- {
- m_username = settings.value("username", "admin").toString();
- }
- else
- {
- successful = false;
- }
+ if (settings.contains("username")) {
+ m_username = settings.value("username", "admin").toString();
+ }
+ else {
+ successful = false;
+ }
editUsername->setText(m_username);
- if(settings.contains("sharedfoldername"))
- {
- m_sharedFolderName = settings.value("sharedfoldername", "shared").toString();
- }
- else
- {
- successful = false;
- }
+ if (settings.contains("sharedfoldername")) {
+ m_sharedFolderName = settings.value("sharedfoldername", "shared").toString();
+ }
+ else {
+ successful = false;
+ }
editSharedFolder->setText(m_sharedFolderName);
- if(settings.contains("dirPath"))
- {
- m_dirPath = settings.value("dirPath", QDir::homePath()).toString();
- }
- else
- {
- successful = false;
- }
+ if (settings.contains("dirPath")) {
+ m_dirPath = settings.value("dirPath", QDir::homePath()).toString();
+ }
+ else {
+ successful = false;
+ }
editSharedFolderPath->setText(m_dirPath);
- _LOG_DEBUG ("Found configured path: " << (successful ? m_dirPath.toStdString () : std::string("no")));
+ _LOG_DEBUG("Found configured path: " << (successful ? m_dirPath.toStdString() : std::string("no")));
return successful;
}
-void ChronoShareGui::saveSettings()
+void
+ChronoShareGui::saveSettings()
{
// Save Settings
// QSettings settings(m_settingsFilePath, QSettings::NativeFormat);
- QSettings settings (QSettings::NativeFormat, QSettings::UserScope, "irl.cs.ucla.edu", "ChronoShare");
+ QSettings settings(QSettings::NativeFormat, QSettings::UserScope, "irl.cs.ucla.edu", "ChronoShare");
settings.setValue("dirPath", m_dirPath);
settings.setValue("username", m_username);
settings.setValue("sharedfoldername", m_sharedFolderName);
}
-void ChronoShareGui::closeEvent(QCloseEvent* event)
+void
+ChronoShareGui::closeEvent(QCloseEvent* event)
{
- _LOG_DEBUG ("Close Event");
+ _LOG_DEBUG("Close Event");
- if (m_username.isNull () || m_username == "" ||
- m_sharedFolderName.isNull () || m_sharedFolderName == "")
- {
- openMessageBox ("ChronoShare is not active", "Username and/or shared folder name are not set.\n\n To activate ChronoShare, open Settings menu and configure your username and shared folder name");
- }
+ if (m_username.isNull() || m_username == "" || m_sharedFolderName.isNull() ||
+ m_sharedFolderName == "") {
+ openMessageBox("ChronoShare is not active",
+ "Username and/or shared folder name are not set.\n\n To activate ChronoShare, open Settings menu and configure your username and shared folder name");
+ }
this->hide();
event->ignore(); // don't let the event propagate to the base class
}
#if WAF
-#include "chronosharegui.moc"
#include "chronosharegui.cpp.moc"
+#include "chronosharegui.moc"
#endif
diff --git a/gui/chronosharegui.hpp b/gui/chronosharegui.hpp
index 9721b39..755c633 100644
--- a/gui/chronosharegui.hpp
+++ b/gui/chronosharegui.hpp
@@ -28,21 +28,21 @@
#include "sparkle-auto-update.hpp"
#endif
-#include <QtGui>
-#include <QWidget>
-#include <QSystemTrayIcon>
-#include <QMenu>
+#include <QApplication>
+#include <QCloseEvent>
#include <QDebug>
-#include <QProcess>
-#include <QSettings>
#include <QDir>
#include <QFileDialog>
-#include <QCloseEvent>
+#include <QMenu>
#include <QMessageBox>
-#include <QApplication>
+#include <QProcess>
+#include <QSettings>
+#include <QSystemTrayIcon>
+#include <QWidget>
+#include <QtGui>
-#include "fs-watcher.hpp"
#include "dispatcher.hpp"
+#include "fs-watcher.hpp"
#include "server.hpp"
#include <boost/thread/thread.hpp>
@@ -50,7 +50,7 @@
{
Q_OBJECT
- public:
+public:
// constructor
explicit ChronoShareGui(QWidget* parent = 0);
@@ -59,83 +59,102 @@
private slots:
// open the shared folder
- void openSharedFolder();
+ void
+ openSharedFolder();
- void openFile();
+ void
+ openFile();
- void openInWebBrowser();
+ void
+ openInWebBrowser();
- void updateRecentFilesMenu();
+ void
+ updateRecentFilesMenu();
// open file dialog
- void openFileDialog();
+ void
+ openFileDialog();
// handle left click of tray icon
- void trayIconClicked(QSystemTrayIcon::ActivationReason reason);
+ void
+ trayIconClicked(QSystemTrayIcon::ActivationReason reason);
// view chronoshare settings
- void viewSettings();
+ void
+ viewSettings();
// change chronoshare settings
- void changeSettings();
+ void
+ changeSettings();
// click on adhoc button
- void onAdHocChange (bool state); // cannot be protected with #ifdef. otherwise something fishy with QT
+ void
+ onAdHocChange(bool state); // cannot be protected with #ifdef. otherwise something fishy with QT
- void onCheckForUpdates();
+ void
+ onCheckForUpdates();
private:
- void checkFileAction(const std::string &, int, int);
+ void
+ checkFileAction(const std::string&, int, int);
// create actions that result from clicking a menu option
- void createActionsAndMenu();
+ void
+ createActionsAndMenu();
// create tray icon
- void createTrayIcon();
+ void
+ createTrayIcon();
// set icon image
- void setIcon();
+ void
+ setIcon();
// load persistent settings
- bool loadSettings();
+ bool
+ loadSettings();
// save persistent settings
- void saveSettings();
+ void
+ saveSettings();
// prompt user dialog box
- void openMessageBox(QString title, QString text);
+ void
+ openMessageBox(QString title, QString text);
// overload
- void openMessageBox(QString title, QString text, QString infotext);
+ void
+ openMessageBox(QString title, QString text, QString infotext);
// capture close event
- void closeEvent(QCloseEvent* event);
+ void
+ closeEvent(QCloseEvent* event);
// starts/restarts fs watcher and dispatcher
void
- startBackend(bool restart=false);
+ startBackend(bool restart = false);
private:
QSystemTrayIcon* m_trayIcon; // tray icon
- QMenu* m_trayIconMenu; // tray icon menu
+ QMenu* m_trayIconMenu; // tray icon menu
- QAction* m_openFolder; // open the shared folder action
+ QAction* m_openFolder; // open the shared folder action
QAction* m_viewSettings; // chronoShare settings
QAction* m_changeFolder; // change the shared folder action
- QAction* m_quitProgram; // quit program action
- QAction *m_checkForUpdates;
- QAction *m_openWeb;
- QMenu *m_recentFilesMenu;
- QAction *m_fileActions[5];
+ QAction* m_quitProgram; // quit program action
+ QAction* m_checkForUpdates;
+ QAction* m_openWeb;
+ QMenu* m_recentFilesMenu;
+ QAction* m_fileActions[5];
- QAction *m_wifiAction;
+ QAction* m_wifiAction;
- QString m_dirPath; // shared directory
- QString m_username; // username
+ QString m_dirPath; // shared directory
+ QString m_username; // username
QString m_sharedFolderName; // shared folder name
- FsWatcher *m_watcher;
- Dispatcher *m_dispatcher;
- http::server::server *m_httpServer;
+ FsWatcher* m_watcher;
+ Dispatcher* m_dispatcher;
+ http::server::server* m_httpServer;
boost::thread m_httpServerThread;
QLabel* labelUsername;
@@ -145,15 +164,15 @@
QLineEdit* editUsername;
QLineEdit* editSharedFolder;
QLineEdit* editSharedFolderPath;
- QLabel *label;
- QVBoxLayout *mainLayout;
+ QLabel* label;
+ QVBoxLayout* mainLayout;
#ifdef ADHOC_SUPPORTED
Executor m_executor;
#endif
#ifdef SPARKLE_SUPPORTED
- AutoUpdate *m_autoUpdate;
+ AutoUpdate* m_autoUpdate;
#endif
// QString m_settingsFilePath; // settings file path
// QString m_settings;
diff --git a/gui/html/chronoshare-helpers.js b/gui/html/chronoshare-helpers.js
index b13c767..f1e9aa1 100644
--- a/gui/html/chronoshare-helpers.js
+++ b/gui/html/chronoshare-helpers.js
@@ -1,39 +1,47 @@
-function number_format( number, decimals, dec_point, thousands_sep ) {
- // http://kevin.vanzonneveld.net
- // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + bugfix by: Michael White (http://crestidg.com)
- // + bugfix by: Benjamin Lupton
- // + bugfix by: Allan Jensen (http://www.winternet.no)
- // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
- // * example 1: number_format(1234.5678, 2, '.', '');
- // * returns 1: 1234.57
+function number_format(number, decimals, dec_point, thousands_sep)
+{
+ // http://kevin.vanzonneveld.net
+ // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
+ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+ // + bugfix by: Michael White (http://crestidg.com)
+ // + bugfix by: Benjamin Lupton
+ // + bugfix by: Allan Jensen (http://www.winternet.no)
+ // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
+ // * example 1: number_format(1234.5678, 2, '.', '');
+ // * returns 1: 1234.57
- var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
- var d = dec_point == undefined ? "," : dec_point;
- var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
- var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
+ var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
+ var d = dec_point == undefined ? "," : dec_point;
+ var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
+ var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
+ j = (j = i.length) > 3 ? j % 3 : 0;
- return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
+ return s + (j ? i.substr(0, j) + t : "") +
+ i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
+ (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
-function SegNumToFileSize (segNum) {
- filesize = segNum * 1024;
+function SegNumToFileSize(segNum)
+{
+ filesize = segNum * 1024;
- if (filesize >= 1073741824) {
- filesize = number_format(filesize / 1073741824, 2, '.', '') + ' Gb';
- } else {
- if (filesize >= 1048576) {
- filesize = number_format(filesize / 1048576, 2, '.', '') + ' Mb';
- } else {
- if (filesize > 1024) {
- filesize = number_format(filesize / 1024, 0) + ' Kb';
- } else {
- filesize = '< 1 Kb';
- };
- };
+ if (filesize >= 1073741824) {
+ filesize = number_format(filesize / 1073741824, 2, '.', '') + ' Gb';
+ }
+ else {
+ if (filesize >= 1048576) {
+ filesize = number_format(filesize / 1048576, 2, '.', '') + ' Mb';
+ }
+ else {
+ if (filesize > 1024) {
+ filesize = number_format(filesize / 1024, 0) + ' Kb';
+ }
+ else {
+ filesize = '< 1 Kb';
+ };
};
- return filesize;
+ };
+ return filesize;
};
/**
@@ -42,107 +50,115 @@
*
* Note that if string length is odd, null will be returned
*/
-StringHashToUint8Array = function (str) {
- if (str.length % 2 != 0) {
- return null;
- }
+StringHashToUint8Array = function(str) {
+ if (str.length % 2 != 0) {
+ return null;
+ }
- var buf = new Uint8Array (str.length / 2);
+ var buf = new Uint8Array(str.length / 2);
- for (var i = 0; i < str.length; i+=2) {
- value = parseInt (str.substring (i, i+2), 16);
- buf[i/2] = value;
- }
+ for (var i = 0; i < str.length; i += 2) {
+ value = parseInt(str.substring(i, i + 2), 16);
+ buf[i / 2] = value;
+ }
- return buf;
+ return buf;
};
-imgFullPath = function (imgName) {
- return "images/" + imgName + ".png";
+imgFullPath =
+ function(imgName) {
+ return "images/" + imgName + ".png";
}
-fileExtension = function (fileName) {
- defaultExtension = "file";
- knownExtensions = ["ai", "aiff", "bib", "bz2", "c", "chm", "conf", "cpp", "css", "csv", "deb", "divx", "doc", "file", "gif", "gz", "hlp", "htm", "html", "iso", "jpeg", "jpg", "js", "mov", "mp3", "mpg", "odc", "odf", "odg", "odi", "odp", "ods", "odt", "ogg", "pdf", "pgp", "php", "pl", "png", "ppt", "pptx", "ps", "py", "ram", "rar", "rb", "rm", "rpm", "rtf", "sql", "swf", "sxc", "sxd", "sxi", "sxw", "tar", "tex", "tgz", "txt", "vcf", "wav", "wma", "wmv", "xls", "xml", "xpi", "xvid", "zip"];
+fileExtension = function(fileName) {
+ defaultExtension = "file";
+ knownExtensions = [
+ "ai", "aiff", "bib", "bz2", "c", "chm", "conf", "cpp", "css", "csv",
+ "deb", "divx", "doc", "file", "gif", "gz", "hlp", "htm", "html", "iso",
+ "jpeg", "jpg", "js", "mov", "mp3", "mpg", "odc", "odf", "odg", "odi",
+ "odp", "ods", "odt", "ogg", "pdf", "pgp", "php", "pl", "png", "ppt",
+ "pptx", "ps", "py", "ram", "rar", "rb", "rm", "rpm", "rtf", "sql",
+ "swf", "sxc", "sxd", "sxi", "sxw", "tar", "tex", "tgz", "txt", "vcf",
+ "wav", "wma", "wmv", "xls", "xml", "xpi", "xvid", "zip"
+ ];
- extStart = fileName.lastIndexOf('.');
- if (extStart < 0) {
- return imgFullPath (defaultExtension);
- }
+ extStart = fileName.lastIndexOf('.');
+ if (extStart < 0) {
+ return imgFullPath(defaultExtension);
+ }
- extension = fileName.substr (extStart+1);
- // return imgFullPath (extension);
- if ($.inArray(extension, knownExtensions) >= 0) {
- return extension;
- }
- else {
- return defaultExtension;
- }
+ extension = fileName.substr(extStart + 1);
+ // return imgFullPath (extension);
+ if ($.inArray(extension, knownExtensions) >= 0) {
+ return extension;
+ }
+ else {
+ return defaultExtension;
+ }
};
-openHistoryForItem = function (fileName) {
- url = new HistoryClosure (null).base_no_item_url ("fileHistory")
- url += "&item=" + encodeURIComponent (encodeURIComponent (fileName));
- document.location = url;
+openHistoryForItem = function(fileName) {
+ url = new HistoryClosure(null).base_no_item_url("fileHistory")
+ url += "&item=" + encodeURIComponent(encodeURIComponent(fileName));
+ document.location = url;
};
-displayContent = function (newcontent, more, baseUrl) {
+displayContent = function(newcontent, more, baseUrl) {
- $("#content").fadeOut ("fast", function () {
- $(this).replaceWith (newcontent);
- $("#content").fadeIn ("fast");
- });
+ $("#content").fadeOut("fast", function() {
+ $(this).replaceWith(newcontent);
+ $("#content").fadeIn("fast");
+ });
- $("#content-nav").fadeOut ("fast", function () {
- $("#content-nav a").hide ();
+ $("#content-nav").fadeOut("fast", function() {
+ $("#content-nav a").hide();
- if (PARAMS.offset !== undefined || more !== undefined) {
- $("#content-nav").fadeIn ("fast");
+ if (PARAMS.offset !== undefined || more !== undefined) {
+ $("#content-nav").fadeIn("fast");
- if (more !== undefined) {
- $("#get-more").show ();
+ if (more !== undefined) {
+ $("#get-more").show();
- $("#get-more").unbind ('click').click (function () {
- url = baseUrl;
- url += "&offset="+more;
+ $("#get-more").unbind('click').click(function() {
+ url = baseUrl;
+ url += "&offset=" + more;
- document.location = url;
- });
- }
- if (PARAMS.offset > 0) {
- $("#get-less").show ();
+ document.location = url;
+ });
+ }
+ if (PARAMS.offset > 0) {
+ $("#get-less").show();
- $("#get-less").unbind ('click').click (function () {
- url = baseUrl;
- if (PARAMS.offset > 5) {
- url += "&offset="+(PARAMS.offset - 5);
- }
+ $("#get-less").unbind('click').click(function() {
+ url = baseUrl;
+ if (PARAMS.offset > 5) {
+ url += "&offset=" + (PARAMS.offset - 5);
+ }
- document.location = url;
- });
- }
- }
- });
+ document.location = url;
+ });
+ }
+ }
+ });
};
-function custom_alert (output_msg, title_msg)
+function custom_alert(output_msg, title_msg)
{
- if (!title_msg)
- title_msg = 'Alert';
+ if (!title_msg)
+ title_msg = 'Alert';
- if (!output_msg)
- output_msg = 'No Message to Display';
+ if (!output_msg)
+ output_msg = 'No Message to Display';
- $("<div></div>").html(output_msg).dialog({
- title: title_msg,
- resizable: false,
- modal: true,
- buttons: {
- "Ok": function()
- {
- $( this ).dialog( "close" );
- }
- }
- });
+ $("<div></div>").html(output_msg).dialog({
+ title: title_msg,
+ resizable: false,
+ modal: true,
+ buttons: {
+ "Ok": function() {
+ $(this).dialog("close");
+ }
+ }
+ });
}
\ No newline at end of file
diff --git a/gui/html/chronoshare-navigation.js b/gui/html/chronoshare-navigation.js
index 8856ec0..8fdd12b 100644
--- a/gui/html/chronoshare-navigation.js
+++ b/gui/html/chronoshare-navigation.js
@@ -1,83 +1,81 @@
var CHRONOSHARE;
var PAGE; // no default page anymore (no reason to have)
-var PARAMS = [ ];
+var PARAMS = [];
var URIPARAMS = "";
-function nav_anchor (aurl) {
- aurl = aurl.split('#');
- if (aurl[1])
- {
- aurl_split = aurl[1].split ('&');
- page = aurl_split[0];
+function nav_anchor(aurl)
+{
+ aurl = aurl.split('#');
+ if (aurl[1]) {
+ aurl_split = aurl[1].split('&');
+ page = aurl_split[0];
- vars = [ ];
- for (var i = 1; i < aurl_split.length; i++)
- {
- hash = aurl_split[i].split('=');
- vars.push(hash[0]);
- // there is strange double-encoding problem...
- vars[hash[0]] = decodeURIComponent (decodeURIComponent (hash[1]));
- }
-
- // if (page != PAGE)
- // {
- // PAGE = page;
- // PARAMS = vars;
- // URIPARAMS = aurl[1];
-
- // if (CHRONOSHARE) {
- // CHRONOSHARE.run ();
- // }
- // }
- // else if (aurl[1] != URIPARAMS)
- // {
- // PARAMS = vars;
- // URIPARAMS = aurl[1];
-
- // if (CHRONOSHARE) {
- // CHRONOSHARE.run ();
- // }
- // }
-
- // this way we can reload by just clicking on the same link
- PAGE = page;
- PARAMS = vars;
- URIPARAMS = aurl[1];
-
- if (CHRONOSHARE) {
- CHRONOSHARE.run ();
- }
+ vars = [];
+ for (var i = 1; i < aurl_split.length; i++) {
+ hash = aurl_split[i].split('=');
+ vars.push(hash[0]);
+ // there is strange double-encoding problem...
+ vars[hash[0]] = decodeURIComponent(decodeURIComponent(hash[1]));
}
+
+ // if (page != PAGE)
+ // {
+ // PAGE = page;
+ // PARAMS = vars;
+ // URIPARAMS = aurl[1];
+
+ // if (CHRONOSHARE) {
+ // CHRONOSHARE.run ();
+ // }
+ // }
+ // else if (aurl[1] != URIPARAMS)
+ // {
+ // PARAMS = vars;
+ // URIPARAMS = aurl[1];
+
+ // if (CHRONOSHARE) {
+ // CHRONOSHARE.run ();
+ // }
+ // }
+
+ // this way we can reload by just clicking on the same link
+ PAGE = page;
+ PARAMS = vars;
+ URIPARAMS = aurl[1];
+
+ if (CHRONOSHARE) {
+ CHRONOSHARE.run();
+ }
+ }
}
-$(document).ready (function () {
- nav_anchor (window.location.href);
+$(document).ready(function() {
+ nav_anchor(window.location.href);
- if (!PARAMS.user || !PARAMS.folder)
- {
- $("#error").html ("user and folder must be be specified in the URL");
- $("#error").removeClass ("hidden");
- return;
- }
- else {
- // update in-page URLs
- $(".needs-get-url").each (function (index,element) {
- this.href += "&user="+encodeURIComponent (encodeURIComponent (PARAMS.user))
- + "&folder="+encodeURIComponent (encodeURIComponent (PARAMS.folder));
- });
- $(".needs-get-url").removeClass ("needs-get-url");
- }
-
- CHRONOSHARE = new ChronoShare (PARAMS.user, PARAMS.folder);
- CHRONOSHARE.run ();
-
- $(window).on('hashchange', function() {
- nav_anchor (window.location.href);
+ if (!PARAMS.user || !PARAMS.folder) {
+ $("#error").html("user and folder must be be specified in the URL");
+ $("#error").removeClass("hidden");
+ return;
+ }
+ else {
+ // update in-page URLs
+ $(".needs-get-url").each(function(index, element) {
+ this.href +=
+ "&user=" + encodeURIComponent(encodeURIComponent(PARAMS.user)) +
+ "&folder=" + encodeURIComponent(encodeURIComponent(PARAMS.folder));
});
+ $(".needs-get-url").removeClass("needs-get-url");
+ }
- $("#reload-button").click (function() {
- nav_anchor (window.location.href);
- });
+ CHRONOSHARE = new ChronoShare(PARAMS.user, PARAMS.folder);
+ CHRONOSHARE.run();
+
+ $(window).on('hashchange', function() {
+ nav_anchor(window.location.href);
+ });
+
+ $("#reload-button").click(function() {
+ nav_anchor(window.location.href);
+ });
});
-
diff --git a/gui/html/chronoshare.js b/gui/html/chronoshare.js
index 1c91c84..38743ad 100644
--- a/gui/html/chronoshare.js
+++ b/gui/html/chronoshare.js
@@ -1,476 +1,570 @@
-$.Class ("ChronoShare", { },
- {
- init: function (username, foldername) {
- $("#folder-name").text (foldername);
- $("#user-name").text (username);
+$.Class("ChronoShare", {}, {
+ init: function(username, foldername) {
+ $("#folder-name").text(foldername);
+ $("#user-name").text(username);
- this.username = new Name (username);
- this.files = new Name ("/localhost").add (this.username).add ("chronoshare").add (foldername).add ("info").add ("files").add ("folder");
+ this.username = new Name(username);
+ this.files = new Name("/localhost")
+ .add(this.username)
+ .add("chronoshare")
+ .add(foldername)
+ .add("info")
+ .add("files")
+ .add("folder");
- this.actions = new Name ("/localhost").add (this.username).add ("chronoshare").add (foldername).add ("info").add ("actions");
+ this.actions = new Name("/localhost")
+ .add(this.username)
+ .add("chronoshare")
+ .add(foldername)
+ .add("info")
+ .add("actions");
- this.restore = new Name ("/localhost").add (this.username).add ("chronoshare").add (foldername).add ("cmd").add ("restore").add ("file");
+ this.restore = new Name("/localhost")
+ .add(this.username)
+ .add("chronoshare")
+ .add(foldername)
+ .add("cmd")
+ .add("restore")
+ .add("file");
- this.ndn = new NDN ({host:"127.0.0.1"});
- this.ndn.verify = false; //disable content verification, works WAAAAY faster
- },
+ this.ndn = new NDN({host: "127.0.0.1"});
+ this.ndn.verify = false; // disable content verification, works WAAAAY faster
+ },
- run: function () {
- console.log ("RUN page: " + PAGE);
- $("#loader").fadeIn (500);
- $("#error").addClass ("hidden");
+ run: function() {
+ console.log("RUN page: " + PAGE);
+ $("#loader").fadeIn(500);
+ $("#error").addClass("hidden");
- cmd = {};
- if (PAGE == "fileList") {
- cmd = this.info_files (PARAMS.item);
- }
- else if (PAGE == "folderHistory") {
- cmd = this.info_actions ("folder", PARAMS.item);
- }
- else if (PAGE == "fileHistory") {
- cmd = this.info_actions ("file", PARAMS.item);
- }
+ cmd = {};
+ if (PAGE == "fileList") {
+ cmd = this.info_files(PARAMS.item);
+ }
+ else if (PAGE == "folderHistory") {
+ cmd = this.info_actions("folder", PARAMS.item);
+ }
+ else if (PAGE == "fileHistory") {
+ cmd = this.info_actions("file", PARAMS.item);
+ }
- if (cmd.request && cmd.callback) {
- console.log (cmd.request.to_uri ());
- this.ndn.expressInterest (cmd.request, cmd.callback);
- }
- else {
- $("#loader").fadeOut (500); // ("hidden");
- $("#content").empty ();
- if (cmd.error) {
- $("#error").html (cmd.error);
- }
- else {
- $("#error").html ("Unknown error with " + PAGE);
- }
- $("#error").removeClass ("hidden");
- }
- },
+ if (cmd.request && cmd.callback) {
+ console.log(cmd.request.to_uri());
+ this.ndn.expressInterest(cmd.request, cmd.callback);
+ }
+ else {
+ $("#loader").fadeOut(500); // ("hidden");
+ $("#content").empty();
+ if (cmd.error) {
+ $("#error").html(cmd.error);
+ }
+ else {
+ $("#error").html("Unknown error with " + PAGE);
+ }
+ $("#error").removeClass("hidden");
+ }
+ },
- info_files: function(folder) {
- request = new Name ().add (this.files)./*add (folder_in_question).*/addSegment (PARAMS.offset?PARAMS.offset:0);
- return { request:request, callback: new FilesClosure (this) };
- },
+ info_files: function(folder) {
+ request = new Name()
+ .add(this.files)
+ ./*add (folder_in_question).*/ addSegment(
+ PARAMS.offset ? PARAMS.offset : 0);
+ return {request: request, callback: new FilesClosure(this)};
+ },
- info_actions: function (type/*"file" or "folder"*/, fileOrFolder /*file or folder name*/) {
- if (type=="file" && !fileOrFolder) {
- return { error: "info_actions: fileOrFolder parameter is missing" };
- }
+ info_actions: function(type /*"file" or "folder"*/,
+ fileOrFolder /*file or folder name*/) {
+ if (type == "file" && !fileOrFolder) {
+ return {error: "info_actions: fileOrFolder parameter is missing"};
+ }
- request = new Name ().add (this.actions).add (type);
- if (fileOrFolder) {
- request.add (fileOrFolder);
- }
- request.addSegment (PARAMS.offset?PARAMS.offset:0);
- return { request: request, callback: new HistoryClosure (this) };
- },
+ request = new Name().add(this.actions).add(type);
+ if (fileOrFolder) {
+ request.add(fileOrFolder);
+ }
+ request.addSegment(PARAMS.offset ? PARAMS.offset : 0);
+ return {request: request, callback: new HistoryClosure(this)};
+ },
- cmd_restore_file: function (filename, version, hash, callback/*function (bool <- data received, status <- returned status)*/) {
- request = new Name ().add (this.restore)
- .add (filename)
- .addSegment (version)
- .add (hash);
- console.log (request.to_uri ());
- this.ndn.expressInterest (request, new CmdRestoreFileClosure (this, callback));
- },
-
- get_file: function (modifiedBy, hash, segments, callback/*function (bool <- data received, data <- returned data)*/) {
- baseName = new Name (modifiedBy)
- .add ("chronoshare").add ("file")
- .add (hash);
-
- new FileGetter (this.ndn, baseName, segments, callback)
- .start ();
- }
- });
-
-$.Class ("CmdRestoreFileClosure", {}, {
- init: function (chronoshare, callback) {
- this.chronoshare = chronoshare;
- this.callback = callback;
+ cmd_restore_file:
+ function(filename, version, hash,
+ callback /*function (bool <- data received, status <- returned status)*/) {
+ request =
+ new Name().add(this.restore).add(filename).addSegment(version).add(hash);
+ console.log(request.to_uri());
+ this.ndn.expressInterest(request,
+ new CmdRestoreFileClosure(this, callback));
},
- upcall: function(kind, upcallInfo) {
- if (kind == Closure.UPCALL_CONTENT || kind == Closure.UPCALL_CONTENT_UNVERIFIED) { //disable content verification
- convertedData = DataUtils.toString (upcallInfo.contentObject.content);
- this.callback (true, convertedData);
- }
- else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
- this.callback (false, "Interest timed out");
- }
- else {
- this.callback (false, "Unknown error happened");
- }
+
+ get_file:
+ function(modifiedBy, hash, segments,
+ callback /*function (bool <- data received, data <- returned data)*/) {
+ baseName = new Name(modifiedBy).add("chronoshare").add("file").add(hash);
+
+ new FileGetter(this.ndn, baseName, segments, callback).start();
}
});
-$.Class ("FileGetter", {}, {
- init: function (ndn, baseName, segments, callback) {
- this.ndn = ndn;
- this.callback = callback;
- this.baseName = baseName;
- this.segments = segments;
- this.lastSegmentRequested = -1;
-
- this.data = "";
- },
-
- start: function () {
- this.lastSegmentRequested ++;
-
- request = new Name ()
- .add (this.baseName)
- .addSegment (this.lastSegmentRequested);
-
- console.log (request.to_uri ());
- this.ndn.expressInterest (request, this);
- },
-
- upcall: function(kind, upcallInfo) {
- if (kind == Closure.UPCALL_CONTENT || kind == Closure.UPCALL_CONTENT_UNVERIFIED) { //disable content verification
- convertedData = DataUtils.toString (upcallInfo.contentObject.content);
-
- this.data += convertedData;
-
- if (this.lastSegmentRequested+1 == this.segments) {
- this.callback (true, this.data);
- }
- else {
- this.start ();
- }
- }
- else {
- this.callback (false, "Interest timed out");
- }
+$.Class("CmdRestoreFileClosure", {}, {
+ init: function(chronoshare, callback) {
+ this.chronoshare = chronoshare;
+ this.callback = callback;
+ },
+ upcall: function(kind, upcallInfo) {
+ if (kind == Closure.UPCALL_CONTENT ||
+ kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
+ convertedData = DataUtils.toString(upcallInfo.contentObject.content);
+ this.callback(true, convertedData);
}
+ else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
+ this.callback(false, "Interest timed out");
+ }
+ else {
+ this.callback(false, "Unknown error happened");
+ }
+ }
});
-$.Class ("RestPipelineClosure", {}, {
- init: function (collectionName, moreName) {
- this.collectionName = collectionName;
- this.moreName = moreName;
- $("#json").empty ();
+$.Class("FileGetter", {}, {
+ init: function(ndn, baseName, segments, callback) {
+ this.ndn = ndn;
+ this.callback = callback;
+ this.baseName = baseName;
+ this.segments = segments;
+ this.lastSegmentRequested = -1;
- this.collection = [];
- this.counter = 0;
- },
+ this.data = "";
+ },
- upcall: function(kind, upcallInfo) {
- if (kind == Closure.UPCALL_CONTENT || kind == Closure.UPCALL_CONTENT_UNVERIFIED) { //disable content verification
+ start: function() {
+ this.lastSegmentRequested++;
- convertedData = DataUtils.toString (upcallInfo.contentObject.content);
- if (PARAMS.debug) {
- $("#json").append ($(document.createTextNode(convertedData)));
- $("#json").removeClass ("hidden");
- }
- data = JSON.parse (convertedData);
+ request =
+ new Name().add(this.baseName).addSegment(this.lastSegmentRequested);
- this.collection = this.collection.concat (data[this.collectionName]);
- if (data[this.moreName] !== undefined) {
- nextSegment = upcallInfo.interest.name.cut (1).addSegment (data[this.moreName]);
- this.counter ++;
+ console.log(request.to_uri());
+ this.ndn.expressInterest(request, this);
+ },
- if (this.counter < 5) {
- console.log ("MORE: " +nextSegment.to_uri ());
- CHRONOSHARE.ndn.expressInterest (nextSegment, this);
- }
- else {
- $("#loader").fadeOut (500); // ("hidden");
- this.onData (this.collection, data[this.moreName]);
- }
- }
- else {
- $("#loader").fadeOut (500); // ("hidden");
- this.onData (this.collection, undefined);
- }
- }
- else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
- $("#loader").fadeOut (500); // ("hidden");
- this.onTimeout (upcallInfo.interest);
+ upcall: function(kind, upcallInfo) {
+ if (kind == Closure.UPCALL_CONTENT ||
+ kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
+ convertedData = DataUtils.toString(upcallInfo.contentObject.content);
+
+ this.data += convertedData;
+
+ if (this.lastSegmentRequested + 1 == this.segments) {
+ this.callback(true, this.data);
+ }
+ else {
+ this.start();
+ }
+ }
+ else {
+ this.callback(false, "Interest timed out");
+ }
+ }
+});
+
+$.Class("RestPipelineClosure", {}, {
+ init: function(collectionName, moreName) {
+ this.collectionName = collectionName;
+ this.moreName = moreName;
+ $("#json").empty();
+
+ this.collection = [];
+ this.counter = 0;
+ },
+
+ upcall: function(kind, upcallInfo) {
+ if (kind == Closure.UPCALL_CONTENT ||
+ kind == Closure.UPCALL_CONTENT_UNVERIFIED) { // disable content verification
+
+ convertedData = DataUtils.toString(upcallInfo.contentObject.content);
+ if (PARAMS.debug) {
+ $("#json").append($(document.createTextNode(convertedData)));
+ $("#json").removeClass("hidden");
+ }
+ data = JSON.parse(convertedData);
+
+ this.collection = this.collection.concat(data[this.collectionName]);
+ if (data[this.moreName] !== undefined) {
+ nextSegment =
+ upcallInfo.interest.name.cut(1).addSegment(data[this.moreName]);
+ this.counter++;
+
+ if (this.counter < 5) {
+ console.log("MORE: " + nextSegment.to_uri());
+ CHRONOSHARE.ndn.expressInterest(nextSegment, this);
}
else {
- $("#loader").fadeOut (500); // ("hidden");
- this.onUnknownError (upcallInfo.interest);
+ $("#loader").fadeOut(500); // ("hidden");
+ this.onData(this.collection, data[this.moreName]);
}
-
- return Closure.RESULT_OK; // make sure we never re-express the interest
- },
-
- onData: function(data, more) {
- },
-
- onTimeout: function () {
- $("#error").html ("Interest timed out");
- $("#error").removeClass ("hidden");
- },
-
- onUnknownError: function () {
- $("#error").html ("Unknown error happened");
- $("#error").removeClass ("hidden");
+ }
+ else {
+ $("#loader").fadeOut(500); // ("hidden");
+ this.onData(this.collection, undefined);
+ }
}
+ else if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
+ $("#loader").fadeOut(500); // ("hidden");
+ this.onTimeout(upcallInfo.interest);
+ }
+ else {
+ $("#loader").fadeOut(500); // ("hidden");
+ this.onUnknownError(upcallInfo.interest);
+ }
+
+ return Closure.RESULT_OK; // make sure we never re-express the interest
+ },
+
+ onData: function(data, more) {},
+
+ onTimeout: function() {
+ $("#error").html("Interest timed out");
+ $("#error").removeClass("hidden");
+ },
+
+ onUnknownError: function() {
+ $("#error").html("Unknown error happened");
+ $("#error").removeClass("hidden");
+ }
});
// $.Class ("FilesClosure", {}, {
-RestPipelineClosure ("FilesClosure", {}, {
- init: function (chronoshare) {
- this._super("files", "more");
- this.chronoshare = chronoshare;
- },
+RestPipelineClosure("FilesClosure", {}, {
+ init: function(chronoshare) {
+ this._super("files", "more");
+ this.chronoshare = chronoshare;
+ },
- onData: function(data, more) {
- tbody = $("<tbody />", { "id": "file-list-files" });
+ onData: function(data, more) {
+ tbody = $("<tbody />", {"id": "file-list-files"});
- /// @todo Eventually set title for other pages
- $("title").text ("ChronoShare - List of files" + (PARAMS.item?" - "+PARAMS.item:""));
+ /// @todo Eventually set title for other pages
+ $("title").text("ChronoShare - List of files" +
+ (PARAMS.item ? " - " + PARAMS.item : ""));
- // error handling?
- newcontent = $("<div />", { "id": "content" }).append (
- $("<h2 />").append ($(document.createTextNode("List of files ")), $("<green />").text (PARAMS.item)),
- $("<table />", { "class": "item-list" })
- .append ($("<thead />")
- .append ($("<tr />")
- .append ($("<th />", { "class": "filename border-left", "scope": "col" }).text ("Filename"))
- .append ($("<th />", { "class": "version", "scope": "col" }).text ("Version"))
- .append ($("<th />", { "class": "size", "scope": "col" }).text ("Size"))
- .append ($("<th />", { "class": "modified", "scope": "col" }).text ("Modified"))
- .append ($("<th />", { "class": "modified-by border-right", "scope": "col" }).text ("Modified By"))))
- .append (tbody)
- .append ($("<tfoot />")
- .append ($("<tr />")
- .append ($("<td />", { "colspan": "5", "class": "border-right border-left" })))));
- newcontent.hide ();
+ // error handling?
+ newcontent =
+ $("<div />", {"id": "content"})
+ .append($("<h2 />").append($(document.createTextNode("List of files ")),
+ $("<green />").text(PARAMS.item)),
+ $("<table />", {"class": "item-list"})
+ .append(
+ $("<thead />")
+ .append($("<tr />")
+ .append($("<th />", {
+ "class": "filename border-left",
+ "scope": "col"
+ }).text("Filename"))
+ .append($("<th />",
+ {"class": "version", "scope": "col"})
+ .text("Version"))
+ .append($("<th />",
+ {"class": "size", "scope": "col"})
+ .text("Size"))
+ .append($("<th />", {
+ "class": "modified",
+ "scope": "col"
+ }).text("Modified"))
+ .append($("<th />", {
+ "class": "modified-by border-right",
+ "scope": "col"
+ }).text("Modified By"))))
+ .append(tbody)
+ .append($("<tfoot />").append($("<tr />").append($("<td />", {
+ "colspan": "5",
+ "class": "border-right border-left"
+ })))));
+ newcontent.hide();
- for (var i = 0; i < data.length; i++) {
- file = data[i];
+ for (var i = 0; i < data.length; i++) {
+ file = data[i];
- row = $("<tr />", { "class": "with-context-menu" } );
- if (i%2) { row.addClass ("odd"); }
+ row = $("<tr />", {"class": "with-context-menu"});
+ if (i % 2) {
+ row.addClass("odd");
+ }
- row.bind('mouseenter mouseleave', function() {
- $(this).toggleClass('highlighted');
- });
+ row.bind('mouseenter mouseleave', function() {
+ $(this).toggleClass('highlighted');
+ });
- row.attr ("filename", file.filename); //encodeURIComponent(encodeURIComponent(file.filename)));
- row.bind('click', function (e) { openHistoryForItem ($(this).attr ("filename")) });
+ row.attr("filename",
+ file.filename); // encodeURIComponent(encodeURIComponent(file.filename)));
+ row.bind('click', function(e) {
+ openHistoryForItem($(this).attr("filename"))
+ });
- row.append ($("<td />", { "class": "filename border-left" })
- .text (file.filename)
- .prepend ($("<img />", { "src": imgFullPath(fileExtension(file.filename)) })));
- row.append ($("<td />", { "class": "version" }).text (file.version));
- row.append ($("<td />", { "class": "size" }).text (SegNumToFileSize (file.segNum)));
- row.append ($("<td />", { "class": "modified" }).text (new Date (file.timestamp+"+00:00"))); // convert from UTC
- row.append ($("<td />", { "class": "modified-by border-right"})
- .append ($("<userName />").text (file.owner.userName))
- .append ($("<seqNo> /").text (file.owner.seqNo)));
+ row.append(
+ $("<td />", {"class": "filename border-left"})
+ .text(file.filename)
+ .prepend(
+ $("<img />", {"src": imgFullPath(fileExtension(file.filename))})));
+ row.append($("<td />", {"class": "version"}).text(file.version));
+ row.append(
+ $("<td />", {"class": "size"}).text(SegNumToFileSize(file.segNum)));
+ row.append($("<td />", {
+ "class": "modified"
+ }).text(new Date(file.timestamp + "+00:00"))); // convert from UTC
+ row.append($("<td />", {"class": "modified-by border-right"})
+ .append($("<userName />").text(file.owner.userName))
+ .append($("<seqNo> /").text(file.owner.seqNo)));
- tbody = tbody.append (row);
- }
-
- displayContent (newcontent, more, this.base_url ());
-
- $.contextMenu( 'destroy', ".with-context-menu" ); // cleanup
- $.contextMenu({
- selector: ".with-context-menu",
- items: {
- "info": {name: "x", type: "html", html: "<b>File operations</b>"},
- "sep1": "---------",
- history: {name: "View file history",
- icon: "quit", // need a better icon
- callback: function(key, opt) {
- openHistoryForItem (opt.$trigger.attr ("filename"));
- }},
- }
- });
- },
-
- base_url: function () {
- url = "#fileList"+
- "&user="+encodeURIComponent (encodeURIComponent (PARAMS.user)) +
- "&folder="+encodeURIComponent (encodeURIComponent (PARAMS.folder));
- if (PARAMS.item !== undefined) {
- url += "&item="+encodeURIComponent (encodeURIComponent (PARAMS.item));
- }
- return url;
+ tbody = tbody.append(row);
}
+
+ displayContent(newcontent, more, this.base_url());
+
+ $.contextMenu('destroy', ".with-context-menu"); // cleanup
+ $.contextMenu({
+ selector: ".with-context-menu",
+ items: {
+ "info": {name: "x", type: "html", html: "<b>File operations</b>"},
+ "sep1": "---------",
+ history: {
+ name: "View file history",
+ icon: "quit", // need a better icon
+ callback: function(key, opt) {
+ openHistoryForItem(opt.$trigger.attr("filename"));
+ }
+ },
+ }
+ });
+ },
+
+ base_url: function() {
+ url = "#fileList" +
+ "&user=" + encodeURIComponent(encodeURIComponent(PARAMS.user)) +
+ "&folder=" + encodeURIComponent(encodeURIComponent(PARAMS.folder));
+ if (PARAMS.item !== undefined) {
+ url += "&item=" + encodeURIComponent(encodeURIComponent(PARAMS.item));
+ }
+ return url;
+ }
});
+RestPipelineClosure("HistoryClosure", {}, {
+ init: function(chronoshare) {
+ this._super("actions", "more");
+ this.chronoshare = chronoshare;
+ },
-RestPipelineClosure ("HistoryClosure", {}, {
- init: function (chronoshare) {
- this._super("actions", "more");
- this.chronoshare = chronoshare;
- },
-
- previewFile: function (file) {
- if (fileExtension(file.attr ("filename")) == "txt") {
- CHRONOSHARE.get_file (file.attr ("file_modified_by"),
- DataUtils.toNumbers (file.attr ("file_hash")),
- file.attr ("file_seg_num"),
- function (status, data) {
- $("<div />", { "title": "Preview of " + file.attr ("filename") + " version " + file.attr ("file_version") })
- .append ($("<pre />").text (data))
- .dialog ({
- resizable: true,
- width: $(window).width() * 0.8,
- maxHeight: $(window).height() * 0.8,
- show: "blind",
- hide: "fold",
- modal: true,
- });
- });
- }
- else {
- custom_alert ("Preview is not support for this type of file");
- }
- },
-
- onData: function(data, more) {
- tbody = $("<tbody />", { "id": "history-list-actions" });
-
- /// @todo Eventually set title for other pages
- $("title").text ("ChronoShare - Recent actions" + (PARAMS.item?" - "+PARAMS.item:""));
-
- newcontent = $("<div />", { "id": "content" }).append (
- $("<h2 />").append ($(document.createTextNode("Recent actions ")), $("<green />").text (PARAMS.item)),
- $("<table />", { "class": "item-list" })
- .append ($("<thead />")
- .append ($("<tr />")
- .append ($("<th />", { "class": "filename border-left", "scope": "col" }).text ("Filename"))
- .append ($("<th />", { "class": "version", "scope": "col" }).text ("Version"))
- .append ($("<th />", { "class": "size", "scope": "col" }).text ("Size"))
- .append ($("<th />", { "class": "modified", "scope": "col" }).text ("Modified"))
- .append ($("<th />", { "class": "modified-by border-right", "scope": "col" }).text ("Modified By"))))
- .append (tbody)
- .append ($("<tfoot />")
- .append ($("<tr />")
- .append ($("<td />", { "colspan": "5", "class": "border-right border-left" })))));
-
- for (var i = 0; i < data.length; i++) {
- action = data[i];
-
- row = $("<tr />");
- if (i%2) { row.addClass ("odd"); }
- if (action.action=="DELETE") {
- row.addClass ("delete");
- }
- else {
- row.addClass ("with-context-menu");
- row.attr ("file_version", action.version);
- row.attr ("file_hash", action.update.hash);
- row.attr ("file_seg_num", action.update.segNum);
- row.attr ("file_modified_by", action.id.userName);
- }
-
- row.attr ("filename", action.filename);
-
- self = this;
- if (PARAMS.item != action.filename) {
- row.bind('click', function (e) { openHistoryForItem ($(this).attr ("filename")) });
- }
- else {
- row.bind('click', function (e) {
- self.previewFile ($(this));
- });
- }
-
- row.bind('mouseenter mouseleave', function() {
- $(this).toggleClass('highlighted');
- });
-
- row.append ($("<td />", { "class": "filename border-left" })
- .text (action.filename)
- .prepend ($("<img />", { "src": imgFullPath(fileExtension(action.filename)) })));
- row.append ($("<td />", { "class": "version" }).text (action.version));
- row.append ($("<td />", { "class": "size" }).text (action.update?SegNumToFileSize (action.update.segNum):""));
- row.append ($("<td />", { "class": "timestamp" }).text (new Date (action.timestamp+"+00:00"))); // conversion from UTC timezone (we store action time in UTC)
- row.append ($("<td />", { "class": "modified-by border-right" })
- .append ($("<userName />").text (action.id.userName))
- .append ($("<seqNo> /").text (action.id.seqNo)));
-
- tbody = tbody.append (row);
- }
-
- displayContent (newcontent, more, this.base_url (PAGE));
-
- self = this;
- $.contextMenu( 'destroy', ".with-context-menu" ); // cleanup
- $.contextMenu({
- selector: ".with-context-menu",
- items: {
- "sep1": "---------",
- preview: {name: "Preview revision",
- icon: "edit", // ned a better icon
- callback: function(key, opt) {
- self.previewFile (opt.$trigger);
- }},
- "sep3": "---------",
- restore: {name: "Restore this revision",
- icon: "cut", // need a better icon
- callback: function(key, opt) {
- filename = opt.$trigger.attr ("filename");
- version = opt.$trigger.attr ("file_version");
- hash = DataUtils.toNumbers (opt.$trigger.attr ("file_hash"));
- console.log (hash);
- modified_by = opt.$trigger.attr ("file_modified_by");
-
- $("<div />", { "title": "Restore version " + version + "?" })
- .append ($("<p />")
- .append ($("<span />", { "class": "ui-icon ui-icon-alert",
- "style": "float: left; margin: 0 7px 50px 0;" }),
- $(document.createTextNode ("Are you sure you want restore version ")),
- $("<green/>").text (version),
- $(document.createTextNode (" by ")),
- $("<green/>").text (modified_by)))
- .dialog ({
- resizable: true,
- height:200,
- width:300,
- modal: true,
- show: "blind",
- hide: "fold",
- buttons: {
- "Restore": function() {
- self = $(this);
- CHRONOSHARE.cmd_restore_file (filename, version, hash, function(didGetData, response) {
- if (!didGetData || response != "OK") {
- custom_alert (response);
- }
- console.log (response);
- self.dialog ("close");
-
- $.timer (function() {CHRONOSHARE.run ();}).once (1000);
- });
- },
- Cancel: function() {
- $(this).dialog ("close");
- }
- }
- });
- // openHistoryForItem (opt.$trigger.attr ("filename"));
- }},
- "sep2": "---------",
- }
- });
- },
-
- base_no_item_url: function (page) {
- url = "#"+page+
- "&user="+encodeURIComponent (encodeURIComponent (PARAMS.user)) +
- "&folder="+encodeURIComponent (encodeURIComponent (PARAMS.folder));
- return url;
- },
-
- base_url: function (page) {
- url = "#"+page+
- "&user="+encodeURIComponent (encodeURIComponent (PARAMS.user)) +
- "&folder="+encodeURIComponent (encodeURIComponent (PARAMS.folder));
- if (PARAMS.item !== undefined) {
- url += "&item="+encodeURIComponent (encodeURIComponent (PARAMS.item));
- }
- return url;
+ previewFile: function(file) {
+ if (fileExtension(file.attr("filename")) == "txt") {
+ CHRONOSHARE.get_file(file.attr("file_modified_by"),
+ DataUtils.toNumbers(file.attr("file_hash")),
+ file.attr("file_seg_num"), function(status, data) {
+ $("<div />", {
+ "title": "Preview of " + file.attr("filename") +
+ " version " + file.attr("file_version")
+ })
+ .append($("<pre />").text(data))
+ .dialog({
+ resizable: true,
+ width: $(window).width() * 0.8,
+ maxHeight: $(window).height() * 0.8,
+ show: "blind",
+ hide: "fold",
+ modal: true,
+ });
+ });
}
+ else {
+ custom_alert("Preview is not support for this type of file");
+ }
+ },
+
+ onData: function(data, more) {
+ tbody = $("<tbody />", {"id": "history-list-actions"});
+
+ /// @todo Eventually set title for other pages
+ $("title").text("ChronoShare - Recent actions" +
+ (PARAMS.item ? " - " + PARAMS.item : ""));
+
+ newcontent =
+ $("<div />", {"id": "content"})
+ .append($("<h2 />").append($(document.createTextNode("Recent actions ")),
+ $("<green />").text(PARAMS.item)),
+ $("<table />", {"class": "item-list"})
+ .append(
+ $("<thead />")
+ .append($("<tr />")
+ .append($("<th />", {
+ "class": "filename border-left",
+ "scope": "col"
+ }).text("Filename"))
+ .append($("<th />",
+ {"class": "version", "scope": "col"})
+ .text("Version"))
+ .append($("<th />",
+ {"class": "size", "scope": "col"})
+ .text("Size"))
+ .append($("<th />", {
+ "class": "modified",
+ "scope": "col"
+ }).text("Modified"))
+ .append($("<th />", {
+ "class": "modified-by border-right",
+ "scope": "col"
+ }).text("Modified By"))))
+ .append(tbody)
+ .append($("<tfoot />").append($("<tr />").append($("<td />", {
+ "colspan": "5",
+ "class": "border-right border-left"
+ })))));
+
+ for (var i = 0; i < data.length; i++) {
+ action = data[i];
+
+ row = $("<tr />");
+ if (i % 2) {
+ row.addClass("odd");
+ }
+ if (action.action == "DELETE") {
+ row.addClass("delete");
+ }
+ else {
+ row.addClass("with-context-menu");
+ row.attr("file_version", action.version);
+ row.attr("file_hash", action.update.hash);
+ row.attr("file_seg_num", action.update.segNum);
+ row.attr("file_modified_by", action.id.userName);
+ }
+
+ row.attr("filename", action.filename);
+
+ self = this;
+ if (PARAMS.item != action.filename) {
+ row.bind('click', function(e) {
+ openHistoryForItem($(this).attr("filename"))
+ });
+ }
+ else {
+ row.bind('click', function(e) {
+ self.previewFile($(this));
+ });
+ }
+
+ row.bind('mouseenter mouseleave', function() {
+ $(this).toggleClass('highlighted');
+ });
+
+ row.append(
+ $("<td />", {"class": "filename border-left"})
+ .text(action.filename)
+ .prepend($("<img />",
+ {"src": imgFullPath(fileExtension(action.filename))})));
+ row.append($("<td />", {"class": "version"}).text(action.version));
+ row.append(
+ $("<td />", {
+ "class": "size"
+ }).text(action.update ? SegNumToFileSize(action.update.segNum) : ""));
+ row.append($("<td />", {
+ "class": "timestamp"
+ }).text(new Date(action.timestamp + "+00:00"))); // conversion
+ // from UTC
+ // timezone (we
+ // store action
+ // time in UTC)
+ row.append($("<td />", {"class": "modified-by border-right"})
+ .append($("<userName />").text(action.id.userName))
+ .append($("<seqNo> /").text(action.id.seqNo)));
+
+ tbody = tbody.append(row);
+ }
+
+ displayContent(newcontent, more, this.base_url(PAGE));
+
+ self = this;
+ $.contextMenu('destroy', ".with-context-menu"); // cleanup
+ $.contextMenu({
+ selector: ".with-context-menu",
+ items: {
+ "sep1": "---------",
+ preview: {
+ name: "Preview revision",
+ icon: "edit", // ned a better icon
+ callback: function(key, opt) {
+ self.previewFile(opt.$trigger);
+ }
+ },
+ "sep3": "---------",
+ restore: {
+ name: "Restore this revision",
+ icon: "cut", // need a better icon
+ callback: function(key, opt) {
+ filename = opt.$trigger.attr("filename");
+ version = opt.$trigger.attr("file_version");
+ hash = DataUtils.toNumbers(opt.$trigger.attr("file_hash"));
+ console.log(hash);
+ modified_by = opt.$trigger.attr("file_modified_by");
+
+ $("<div />", {"title": "Restore version " + version + "?"})
+ .append(
+ $("<p />").append($("<span />", {
+ "class": "ui-icon ui-icon-alert",
+ "style": "float: left; margin: 0 7px 50px 0;"
+ }),
+ $(document.createTextNode(
+ "Are you sure you want restore version ")),
+ $("<green/>").text(version),
+ $(document.createTextNode(" by ")),
+ $("<green/>").text(modified_by)))
+ .dialog({
+ resizable: true,
+ height: 200,
+ width: 300,
+ modal: true,
+ show: "blind",
+ hide: "fold",
+ buttons: {
+ "Restore": function() {
+ self = $(this);
+ CHRONOSHARE.cmd_restore_file(filename, version, hash,
+ function(didGetData, response) {
+ if (!didGetData ||
+ response != "OK") {
+ custom_alert(response);
+ }
+ console.log(response);
+ self.dialog("close");
+
+ $.timer(function() {
+ CHRONOSHARE.run();
+ })
+ .once(1000);
+ });
+ },
+ Cancel: function() {
+ $(this).dialog("close");
+ }
+ }
+ });
+ // openHistoryForItem (opt.$trigger.attr ("filename"));
+ }
+ },
+ "sep2": "---------",
+ }
+ });
+ },
+
+ base_no_item_url: function(page) {
+ url = "#" + page + "&user=" +
+ encodeURIComponent(encodeURIComponent(PARAMS.user)) + "&folder=" +
+ encodeURIComponent(encodeURIComponent(PARAMS.folder));
+ return url;
+ },
+
+ base_url: function(page) {
+ url = "#" + page + "&user=" +
+ encodeURIComponent(encodeURIComponent(PARAMS.user)) + "&folder=" +
+ encodeURIComponent(encodeURIComponent(PARAMS.folder));
+ if (PARAMS.item !== undefined) {
+ url += "&item=" + encodeURIComponent(encodeURIComponent(PARAMS.item));
+ }
+ return url;
+ }
});
-
-
-
-
diff --git a/gui/html/content.js b/gui/html/content.js
index 5042478..9a98648 100644
--- a/gui/html/content.js
+++ b/gui/html/content.js
@@ -1,77 +1,87 @@
-function prefix() {
- var tmp = document.getElementById("prefixcontent").innerHTML;
- var data = tmp.split("END");
- var odd = "odd";
+function prefix()
+{
+ var tmp = document.getElementById("prefixcontent").innerHTML;
+ var data = tmp.split("END");
+ var odd = "odd";
- for (var i in data) {
- // Parse the JSON data.
- var obj = jQuery.parseJSON(data[i]);
+ for (var i in data) {
+ // Parse the JSON data.
+ var obj = jQuery.parseJSON(data[i]);
- if (i % 2 == 0) {
- odd = "";
- } else {
- odd = "odd";
- }
+ if (i % 2 == 0) {
+ odd = "";
+ }
+ else {
+ odd = "odd";
+ }
- // Create the HTML for each prefix.
- var output = '<tr class="' + odd + '">\n';
+ // Create the HTML for each prefix.
+ var output = '<tr class="' + odd + '">\n';
- output += '<td rowspan="' + obj.prefixes.length + '">' + obj.router + '</td>';
+ output +=
+ '<td rowspan="' + obj.prefixes.length + '">' + obj.router + '</td>';
- for (var i in obj.prefixes) {
- output += '<td class="' + odd + '">' + obj.prefixes[i].timestamp + '</td>';
- output += '<td class="' + odd + '">' + obj.prefixes[i].prefix + '</td>';
-
- if (obj.prefixes[i].status == "notintopology") {
- output += '<td id="' + obj.prefixes[i].status + '">NPT</td>';
- } else {
- output += '<td id="' + obj.prefixes[i].status + '">' + obj.prefixes[i].status + '</td>';
- }
-
- output += '</tr>';
- }
+ for (var i in obj.prefixes) {
+ output += '<td class="' + odd + '">' + obj.prefixes[i].timestamp + '</td>';
+ output += '<td class="' + odd + '">' + obj.prefixes[i].prefix + '</td>';
- // Append the data to the prefix table.
- $('.one > tbody:last').append(output);
- }
+ if (obj.prefixes[i].status == "notintopology") {
+ output += '<td id="' + obj.prefixes[i].status + '">NPT</td>';
+ }
+ else {
+ output += '<td id="' + obj.prefixes[i].status + '">' +
+ obj.prefixes[i].status + '</td>';
+ }
+
+ output += '</tr>';
+ }
+
+ // Append the data to the prefix table.
+ $('.one > tbody:last').append(output);
+ }
}
-function link() {
- var tmp = document.getElementById("linkcontent").innerHTML;
- var data = tmp.split("END");
- var odd = "odd";
+function link()
+{
+ var tmp = document.getElementById("linkcontent").innerHTML;
+ var data = tmp.split("END");
+ var odd = "odd";
- for (var i in data) {
- // Parse the JSON data.
- var obj = jQuery.parseJSON(data[i]);
+ for (var i in data) {
+ // Parse the JSON data.
+ var obj = jQuery.parseJSON(data[i]);
- if (i % 2 == 0) {
- odd = "";
- } else {
- odd = "odd";
- }
-
- // Create the HTML for each prefix.
- var output = '<tr class="' + odd + '">\n';
+ if (i % 2 == 0) {
+ odd = "";
+ }
+ else {
+ odd = "odd";
+ }
- output += '<td rowspan="' + obj.links.length + '">' + obj.router + '</td>';
- output += '<td rowspan="' + obj.links.length + '">' + obj.timestamp + '</td>';
+ // Create the HTML for each prefix.
+ var output = '<tr class="' + odd + '">\n';
- for (var i in obj.links) {
- output += '<td id="' + obj.links[i].status + '">' + obj.links[i].link + '</td>';
+ output += '<td rowspan="' + obj.links.length + '">' + obj.router + '</td>';
+ output +=
+ '<td rowspan="' + obj.links.length + '">' + obj.timestamp + '</td>';
- if (obj.links[i].status == "notintopology") {
- output += '<td id="' + obj.links[i].status + '">NPT</td>';
- } else {
- output += '<td id="' + obj.links[i].status + '">' + obj.links[i].status + '</td>';
- }
+ for (var i in obj.links) {
+ output +=
+ '<td id="' + obj.links[i].status + '">' + obj.links[i].link + '</td>';
- output += '</tr>';
- }
+ if (obj.links[i].status == "notintopology") {
+ output += '<td id="' + obj.links[i].status + '">NPT</td>';
+ }
+ else {
+ output += '<td id="' + obj.links[i].status + '">' +
+ obj.links[i].status + '</td>';
+ }
- // Append the data to the prefix table.
- $('.two > tbody:last').append(output);
- }
+ output += '</tr>';
+ }
+
+ // Append the data to the prefix table.
+ $('.two > tbody:last').append(output);
+ }
}
-
diff --git a/gui/html/detect.js b/gui/html/detect.js
index f5f0f64..48a15fc 100644
--- a/gui/html/detect.js
+++ b/gui/html/detect.js
@@ -1,60 +1,66 @@
-function detect() {
+function detect()
+{
+ var nVer = navigator.appVersion;
+ var nAgt = navigator.userAgent;
+ var browserName = navigator.appName;
+ var fullVersion = '' + parseFloat(navigator.appVersion);
+ var majorVersion = parseInt(navigator.appVersion, 10);
+ var nameOffset, verOffset, ix;
- var nVer = navigator.appVersion;
- var nAgt = navigator.userAgent;
- var browserName = navigator.appName;
- var fullVersion = '' + parseFloat(navigator.appVersion);
- var majorVersion = parseInt(navigator.appVersion, 10);
- var nameOffset, verOffset, ix;
+ // In Opera, the true version is after "Opera" or after "Version"
+ if ((verOffset = nAgt.indexOf("Opera")) != -1) {
+ browserName = "Opera";
+ fullVersion = nAgt.substring(verOffset + 6);
+ if ((verOffset = nAgt.indexOf("Version")) != -1)
+ fullVersion = nAgt.substring(verOffset + 8);
+ }
+ // In MSIE, the true version is after "MSIE" in userAgent
+ else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
+ browserName = "Microsoft Internet Explorer";
+ fullVersion = nAgt.substring(verOffset + 5);
+ }
+ // In Chrome, the true version is after "Chrome"
+ else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
+ browserName = "Chrome";
+ fullVersion = nAgt.substring(verOffset + 7);
+ }
+ // In Safari, the true version is after "Safari" or after "Version"
+ else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
+ browserName = "Safari";
+ fullVersion = nAgt.substring(verOffset + 7);
+ if ((verOffset = nAgt.indexOf("Version")) != -1)
+ fullVersion = nAgt.substring(verOffset + 8);
+ }
+ // In Firefox, the true version is after "Firefox"
+ else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
+ browserName = "Firefox";
+ fullVersion = nAgt.substring(verOffset + 8);
+ }
+ // In most other browsers, "name/version" is at the end of userAgent
+ else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) <
+ (verOffset = nAgt.lastIndexOf('/'))) {
+ browserName = nAgt.substring(nameOffset, verOffset);
+ fullVersion = nAgt.substring(verOffset + 1);
+ if (browserName.toLowerCase() == browserName.toUpperCase()) {
+ browserName = navigator.appName;
+ }
+ }
+ // trim the fullVersion string at semicolon/space if present
+ if ((ix = fullVersion.indexOf(";")) != -1)
+ fullVersion = fullVersion.substring(0, ix);
+ if ((ix = fullVersion.indexOf(" ")) != -1)
+ fullVersion = fullVersion.substring(0, ix);
- // In Opera, the true version is after "Opera" or after "Version"
- if ((verOffset = nAgt.indexOf("Opera")) != -1) {
- browserName = "Opera";
- fullVersion = nAgt.substring(verOffset + 6);
- if ((verOffset = nAgt.indexOf("Version")) != -1) fullVersion = nAgt.substring(verOffset + 8);
- }
- // In MSIE, the true version is after "MSIE" in userAgent
- else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
- browserName = "Microsoft Internet Explorer";
- fullVersion = nAgt.substring(verOffset + 5);
- }
- // In Chrome, the true version is after "Chrome"
- else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
- browserName = "Chrome";
- fullVersion = nAgt.substring(verOffset + 7);
- }
- // In Safari, the true version is after "Safari" or after "Version"
- else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
- browserName = "Safari";
- fullVersion = nAgt.substring(verOffset + 7);
- if ((verOffset = nAgt.indexOf("Version")) != -1) fullVersion = nAgt.substring(verOffset + 8);
- }
- // In Firefox, the true version is after "Firefox"
- else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
- browserName = "Firefox";
- fullVersion = nAgt.substring(verOffset + 8);
- }
- // In most other browsers, "name/version" is at the end of userAgent
- else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
- browserName = nAgt.substring(nameOffset, verOffset);
- fullVersion = nAgt.substring(verOffset + 1);
- if (browserName.toLowerCase() == browserName.toUpperCase()) {
- browserName = navigator.appName;
- }
- }
- // trim the fullVersion string at semicolon/space if present
- if ((ix = fullVersion.indexOf(";")) != -1) fullVersion = fullVersion.substring(0, ix);
- if ((ix = fullVersion.indexOf(" ")) != -1) fullVersion = fullVersion.substring(0, ix);
+ majorVersion = parseInt('' + fullVersion, 10);
+ if (isNaN(majorVersion)) {
+ fullVersion = '' + parseFloat(navigator.appVersion);
+ majorVersion = parseInt(navigator.appVersion, 10);
+ }
- majorVersion = parseInt('' + fullVersion, 10);
- if (isNaN(majorVersion)) {
- fullVersion = '' + parseFloat(navigator.appVersion);
- majorVersion = parseInt(navigator.appVersion, 10);
- }
-
- if (browserName == "Safari" && fullVersion == "5.1.7") {
- return false;
- } else {
- return true;
- }
+ if (browserName == "Safari" && fullVersion == "5.1.7") {
+ return false;
+ }
+ else {
+ return true;
+ }
}
diff --git a/gui/main.cpp b/gui/main.cpp
index eab8e1a..29246e5 100644
--- a/gui/main.cpp
+++ b/gui/main.cpp
@@ -22,9 +22,10 @@
#include "logging.hpp"
#include <QApplication>
-int main(int argc, char *argv[])
+int
+main(int argc, char* argv[])
{
- INIT_LOGGERS ();
+ INIT_LOGGERS();
QApplication app(argc, argv);