Esempio n. 1
0
Playlist::Playlist(Session* session, Settings* settings, WContainerWidget* parent)
: WPanel(parent), d(this, session)
{
  setCentralWidget(d->container = new WContainerWidget);
  setTitleBar(true);
  addStyleClass("playlist");
  setHeaderCollapsible(this);
  titleBarWidget()->addStyleClass("playtlist-titlebar");
  setCollapsible(false);

  d->container->hide();
  d->container->setList(true);
  d->container->addStyleClass("nav nav-pills nav-stacked");
  d->container->setMargin(5, Side::Bottom);
  WText *showHideButtonText = WW<WText>();
  
  d->setPlaylistVisible = [=](bool visible) {
    if(!visible) {
      showHideButtonText->setText(wtr("playlist.show"));
      settings->animateHide(Settings::PlaylistAnimation, d->container);
    }
    else {
      showHideButtonText->setText(wtr("playlist.hide"));
      settings->animateShow(Settings::PlaylistAnimation, d->container);
    }
  };
  
  d->playSignal.connect([=](PlaylistItem*,_n5){ d->setPlaylistVisible(false); });

  WContainerWidget *firstGroup = WW<WContainerWidget>().css("btn-group");
  firstGroup->addWidget(WW<WAnchor>().css("btn btn-xs")
    .setImage(WW<WImage>(Settings::staticPath("/icons/actions/playlist.png")).setMargin(5, Side::Right))
    .add(showHideButtonText)
    .onClick([=](WMouseEvent){
      d->setPlaylistVisible(!d->container->isVisible());
    }));
  firstGroup->addWidget(WW<WAnchor>().css("btn btn-xs")
    .setImage(WW<WImage>(Settings::staticPath("/icons/actions/playlist.clear.png")).setMargin(5, Side::Right))
    .setText(wtr("playlist.clear"))
    .onClick([=](WMouseEvent){
    for(auto item: d->internalQueue)
      delete item;
    d->internalQueue.clear();
  }));

  WContainerWidget *secondGroup = WW<WContainerWidget>().css("btn-group");
  WWidget *prev = WW<WAnchor>(secondGroup).css("btn btn-xs")
    .add(new WImage{Settings::staticPath("/icons/actions/previous.png")}).onClick(boost::bind(&Playlist::previous, this));
  WWidget *next = WW<WAnchor>(secondGroup).css("btn btn-xs")
    .add(new WImage{Settings::staticPath("/icons/actions/next.png")}).onClick(boost::bind(&Playlist::next, this));
  WContainerWidget *playlistButtonsContainer = WW<WContainerWidget>(titleBarWidget()).css("btn-toolbar")
  .add(firstGroup).add(secondGroup);
  d->setPlaylistVisible(false);
}
Esempio n. 2
0
void DensityApp::plot() {
    const char *kernelstr[] = { "gaussian", "epanechnikov", "rectangular", "triangular", "cosine" };
    greeting_->setText("Starting R call");
    R_["tfile"]  = tempfile_;
    R_["bw"]     = bw_;
    R_["kernel"] = kernelstr[kernel_]; 			// passes the string to R
    R_["y"]      = Yvec_;
    std::string cmd0 = "png(filename=tfile,width=600,height=400); plot(density(y, bw=bw/100, kernel=kernel), xlim=range(y)+c(-2,2), main=\"Kernel: ";
    std::string cmd1 = "\"); points(y, rep(0, length(y)), pch=16, col=rgb(0,0,0,1/4));  dev.off()";
    std::string cmd = cmd0 + kernelstr[kernel_] + cmd1; // stick the selected kernel in the middle
    R_.parseEvalQ(cmd);				     	// evaluate command -- generates new density plot
    imgfile_->setChanged();				// important: tells consumer that image has changed, forces refresh
    greeting_->setText("Finished request from " + this->environment().clientAddress() + " using " + this->environment().userAgent()) ;
}
Esempio n. 3
0
  /*! \brief Change repository and/or revision
   */
  void loadGitModel() {
    sourceView_->setIndex(WModelIndex());
    repositoryError_->setText("");
    revisionError_->setText("");
    try {
      gitModel_->setRepositoryPath(repositoryEdit_->text().toUTF8());
      try {
	gitModel_->loadRevision(revisionEdit_->text().toUTF8());
      } catch (const Git::Exception& e) {
	revisionError_->setText(e.what());
      }
    } catch (const Git::Exception& e) {
      repositoryError_->setText(e.what());
    }
  }
Esempio n. 4
0
void UpdatePasswordWidget::updateView(const std::string& var,
				      RegistrationModel::Field field)
{
  WFormWidget *edit = resolve<WFormWidget *>(var);
  WText *info = resolve<WText *>(var + "-info");
  
  const WValidator::Result& v = model_->validationResult(field);
  info->setText(v.message());

  switch (v.state()) {
  case WValidator::InvalidEmpty:
  case WValidator::Invalid:
    edit->removeStyleClass("Wt-valid");
    if (validated_)
      edit->addStyleClass("Wt-invalid");
    info->addStyleClass("Wt-error");

    break;
  case WValidator::Valid:
    edit->removeStyleClass("Wt-invalid");
    if (validated_)
      edit->addStyleClass("Wt-valid");
    info->removeStyleClass("Wt-error");
  }
}
Esempio n. 5
0
void WBootstrapTheme::apply(WWidget *widget, WWidget *child, int widgetRole)
  const
{
  switch (widgetRole) {
  case MenuItemIconRole:
    child->addStyleClass("Wt-icon");
    break;
  case MenuItemCheckBoxRole:
    child->addStyleClass("Wt-chkbox");
    break;
  case DialogCoverRole:
    child->addStyleClass("modal-backdrop");
    break;
  case DialogTitleBarRole:
    child->addStyleClass("modal-header");
    break;
  case DialogBodyRole:
    child->addStyleClass("modal-body");
    break;
  case DialogFooterRole:
    child->addStyleClass("modal-footer");
    break;
  case DialogCloseIconRole:
    {
      child->addStyleClass("close");
      WText *t = dynamic_cast<WText *>(child);
      t->setText("&times;");
      break;
    }

  case TableViewRowContainerRole:
    {
      WAbstractItemView *view = dynamic_cast<WAbstractItemView *>(widget);
      child->toggleStyleClass("Wt-striped", view->alternatingRowColors());
      break;
    }

  case DatePickerPopupRole:
    child->addStyleClass("Wt-datepicker");
    break;

  case PanelTitleBarRole:
    child->addStyleClass("accordion-heading");
    break;

  case PanelCollapseButtonRole:
  case PanelTitleRole:
    child->addStyleClass("accordion-toggle");
    break;

  case PanelBodyRole:
    child->addStyleClass("accordion-inner");
    break;
  case AuthWidgets:
    WApplication *app = WApplication::instance();
    app->builtinLocalizedStrings().useBuiltin
      (skeletons::AuthBootstrapTheme_xml1);
    break;
  }
}
Esempio n. 6
0
void HelloApplication::greet()
{
  /*
   * Update the text, using text input into the nameEdit_ field.
   */
  greeting_->setText("Hello there, " + nameEdit_->text());
}
Esempio n. 7
0
void WSuggestionPopup::modelDataChanged(const WModelIndex& topLeft,
					const WModelIndex& bottomRight)
{
  if (topLeft.parent().isValid())
    return;

  if (modelColumn_ < topLeft.column() || modelColumn_ > bottomRight.column())
    return;

  for (int i = topLeft.row(); i <= bottomRight.row(); ++i) {
    WContainerWidget *w = dynamic_cast<WContainerWidget *>(impl_->widget(i));
    WAnchor *anchor = dynamic_cast<WAnchor *>(w->widget(0));
    WText *value = dynamic_cast<WText *>(anchor->widget(0));

    WModelIndex index = model_->index(i, modelColumn_);

    boost::any d = index.data();
    value->setText(asString(d));

    TextFormat format = index.flags() & ItemIsXHTMLText ? XHTMLText : PlainText;
    value->setTextFormat(format);

    boost::any d2 = model_->data(i, modelColumn_, UserRole);
    if (d2.empty())
      d2 = d;

    value->setAttributeValue("sug", asString(d2));
  }
}
Esempio n. 8
0
void Example::get_search(MapViewer::GeoNode node) {
    Coordinate& pos = node.first;
    click_search_->setText(
        "You have chosen: " + node.second + " <br />Position: " +
        str(boost::format("%.4f %.4f") % pos.longitude() % pos.latitude()));
    mv_->time_zone(pos).connect(this, &Example::get_time_zone);
}
Esempio n. 9
0
void WTemplateFormView::updateViewField(WFormModel *model,
					WFormModel::Field field)
{
  const std::string var = field;

  if (model->isVisible(field)) {
    setCondition("if:" + var, true);
    WWidget *edit = resolveWidget(var);
    if (!edit) {
      edit = createFormWidget(field);
      if (!edit) {
	LOG_ERROR("updateViewField: createFormWidget('"
		  << field << "') returned 0");
	return;
      }
      bindWidget(var, edit);
    }

    WFormWidget *fedit = dynamic_cast<WFormWidget *>(edit);
    if (fedit) {
      if (fedit->validator() != model->validator(field) &&
	  model->validator(field))
	fedit->setValidator(model->validator(field));
      updateViewValue(model, field, fedit);
    } else
      updateViewValue(model, field, edit);

    WText *info = resolve<WText *>(var + "-info");
    if (!info) {
      info = new WText();
      bindWidget(var + "-info", info);
    }

    bindString(var + "-label", model->label(field));

    const WValidator::Result& v = model->validation(field);
    info->setText(v.message());
    indicateValidation(field, model->isValidated(field),
		       info, edit, v);
    edit->setDisabled(model->isReadOnly(field));
  } else {
    setCondition("if:" + var, false);
    bindEmpty(var);
    bindEmpty(var + "-info");    
  }
}
Esempio n. 10
0
WWidget* WCalendar::renderCell(WWidget* widget, const WDate& date)
{
  WText* t = dynamic_cast<WText*>(widget);

  if (!t) {
    t = new WText();
    t->setInline(false);
    t->setTextFormat(PlainText);
  }

#ifndef WT_TARGET_JAVA
    char buf[30];
#else
    char *buf;
#endif // WT_TARGET_JAVA
  Utils::itoa(date.day(), buf);
  t->setText(WString::fromUTF8(buf));

  std::string styleClass;

  if (isInvalid(date))
    styleClass += " Wt-cal-oor";
  else if (date.month() != currentMonth())
    styleClass += " Wt-cal-oom";

  if (isSelected(date))
    styleClass += " Wt-cal-sel";

  WDate currentDate = WDate::currentDate();
  if (date.day() == currentDate.day() && date.month() == currentDate.month() &&
      date.year() == currentDate.year()) {
    if (!isSelected(date))
      styleClass += " Wt-cal-now";
    t->setToolTip(WString::tr("Wt.WCalendar.today"));
  } else
    t->setToolTip("");

  t->setStyleClass(styleClass.c_str());

  return t;
}
Esempio n. 11
0
void WsTwitterStream::load()
{
  Wt::WApplication::instance()->require("//platform.twitter.com/widgets.js");
  WContainerWidget::load();
  std::string width = Wt::asString(option("width")).toUTF8();
  std::string url = Wt::asString(option("url")).toUTF8();
  std::string widgetId = Wt::asString(option("widgetId")).toUTF8();
  std::string text = Wt::asString(option("text")).toUTF8();
  setId("twitterstream");
  //resize(WLength(25, WLength::Percentage), WLength(25, WLength::Percentage));
  setOverflow(WContainerWidget::OverflowAuto);
  std::string html = "<a class=\"twitter-timeline\"";
  if (width!="")
    html+=" width=\""+width+"\"";
  html+=" data-dnt=\"true\" href=\""+url+"\" data-widget-id=\""+widgetId+"\">"+text+"</a>";
  wApp->log("notice") << "WsModTwitterStream::load() "+html;
  WText* textField = new WText(this);
  textField->setTextFormat(Wt::XHTMLUnsafeText);
  textField->setText(html);
  addWidget(textField);
}
Esempio n. 12
0
void WSuggestionPopup::modelDataChanged(const WModelIndex& topLeft,
					const WModelIndex& bottomRight)
{
  if (topLeft.parent().isValid())
    return;

  if (modelColumn_ < topLeft.column() || modelColumn_ > bottomRight.column())
    return;

  for (int i = topLeft.row(); i <= bottomRight.row(); ++i) {
    WContainerWidget *w = dynamic_cast<WContainerWidget *>(content_->widget(i));
    WText *value = dynamic_cast<WText *>(w->widget(0));

    boost::any d = model_->data(i, modelColumn_);
    value->setText(asString(d));

    boost::any d2 = model_->data(i, modelColumn_, UserRole);
    if (d2.empty())
      d2 = d;

    value->setAttributeValue("sug", asString(d2));
  }
}
Esempio n. 13
0
void Example::get_pos(const Coordinate& pos) {
    click_pos_->setText("You clicked near: " +
                        str(boost::format("%.4f %.4f")
                            % pos.longitude() % pos.latitude()));
    mv_->time_zone(pos).connect(this, &Example::get_time_zone);
}
Esempio n. 14
0
void SimpleChatWidget::processChatEvent(const ChatEvent& event)
{
  WApplication *app = WApplication::instance();

  /*
   * This is where the "server-push" happens. The chat server posts to this
   * event from other sessions, see SimpleChatServer::postChatEvent()
   */

  /*
   * Format and append the line to the conversation.
   *
   * This is also the step where the automatic XSS filtering will kick in:
   * - if another user tried to pass on some JavaScript, it is filtered away.
   * - if another user did not provide valid XHTML, the text is automatically
   *   interpreted as PlainText
   */

  /*
   * If it is not a plain message, also update the user list.
   */
  if (event.type() != ChatEvent::Message) {
    if (event.type() == ChatEvent::Rename && event.user() == user_)
      user_ = event.data();

    updateUsers();
  }

  /*
   * This is the server call: we (schedule to) propagate the updated UI to
   * the client.
   *
   * This schedules an update and returns immediately
   */
  app->triggerUpdate();

  newMessage();

  /*
   * Anything else doesn't matter if we are not logged in.
   */
  if (!loggedIn())
    return;

  bool display = event.type() != ChatEvent::Message
    || !userList_
    || (users_.find(event.user()) != users_.end() && users_[event.user()]);

  if (display) {
    WText *w = new WText(messages_);

    /*
     * If it fails, it is because the content wasn't valid XHTML
     */
    if (!w->setText(event.formattedHTML(user_, XHTMLText))) {
      w->setText(event.formattedHTML(user_, PlainText));
      w->setTextFormat(XHTMLText);
    }

    w->setInline(false);
    w->setStyleClass("chat-msg");

    /*
     * Leave no more than 100 messages in the back-log
     */
    if (messages_->count() > 100)
      delete messages_->children()[0];

    /*
     * Little javascript trick to make sure we scroll along with new content
     */
    app->doJavaScript(messages_->jsRef() + ".scrollTop += "
		       + messages_->jsRef() + ".scrollHeight;");

    /* If this message belongs to another user, play a received sound */
    if (event.user() != user_ && messageReceived_)
      messageReceived_->play();
  }
}
Esempio n. 15
0
void WsContent::selectWidget(std::string path)
{
  std::string             sysPath(m_sDocumentRoot + path);
  boost::filesystem::path p(path);
  std::string             strExt (p.extension().string());
  std::string             strName(p.stem().string());
  std::string             strFileName(strName + strExt);
  std::string             fileContent;
  if ( m_bLogContent )
    wApp->log("notice") << "WsContent::selectWidget :  path = " << path << " name = " << strName << " extension = " << strExt << " system path = " << sysPath;
  // This extension is mainly created for allowing text in a image without a link
  if ( strExt == ".nolink" ) {
    addWidget(new WsErrorPage(WsErrorPage::Error, path, 0, "Extension not allowed", true));
    return;
  }
  // .html
  if ( strExt == ".html" ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render a html file : " << sysPath;
    if ( !m_bAllowHtmlRendering ) {
      addWidget(new WsErrorPage(WsErrorPage::Error, path, 0, "Rendering a html file is not allowed"));
      return;
    }
    clear();
    WsApp->hideImages(false);
    WText* pIFrame = new WText();
    pIFrame->setTextFormat(XHTMLUnsafeText);
    pIFrame->setText("<iframe src='" + m_sRelativeDocumentRoot + path + "' height='98%' width='100%' frameborder='0'></iframe>");
    addWidget(pIFrame);
    return;
  }
  // .form
  if ( strExt == ".form" ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render a form : " << sysPath;
    clear();
    m_curWForm = new gdWForm(sysPath);
    addWidget(m_curWForm);
    return;
  }
  // .itpl, Inside template : Extension that create a template in the content.
  if ( strExt == ".itpl" ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render an inside template : " << sysPath;
    clear();
    WsTemplate* pTemplate = new WsTemplate(strFileName);
    addWidget(pTemplate);
    return;
  }
  // directory
  if ( gdcore_isPathDirectory(sysPath) ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render a directory : " << sysPath;
    viewDirectory(path);
    return;
  }
  /*
  Koen : mmm this is a tricky problem. you could do this using an internal path so that you can first let the user authenticate, if necessary, and then you redirect to a static resource with some randomly generated token in the URL so that you can serve the file
  so the permalink is clean, like /cms/folder1/folder2/file.doc
  if your app is deployed at / or /cms, you handle the internal path, authenticate, etc...
  then finally, you create a random ID, and redirect to /resource/folder1/folder2/file.doc?auth=randomid
  and this is handled by a WResource which checks the path and serves the file
  if you prefer I can create a small example ...
  ooops ! must run !
  */
  if ( strExt == ".rss" ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render a " << strExt << " file : " << sysPath;
    clear();
    WsApp->hideImages(false);
    addWidget(new WText("Download file : " + path + " ..."));
    return wApp->redirect(m_sRelativeDocumentRoot + path);
  }
  for (int iModule = 0; iModule < WsApp->WsModules().modules().size(); iModule++) {
    WsModule* curModule = WsApp->WsModules().modules()[iModule]->module;
    if ( curModule->isLoaded() ) continue;
    if ( (strExt.size() == 0  && strName == curModule->fileName()) || (strExt.size() > 0 && strExt == curModule->extension(strExt))  ) {
      if ( m_bLogContent )
        if ( strExt == curModule->extension(strExt) )
          wApp->log("notice") << "WsContent::selectWidget : module, render a " << strExt << " file extension : " << sysPath;
        else
          wApp->log("notice") << "WsContent::selectWidget : module, render " << strName << " file name: " << sysPath;
      clear();
      WsApp->hideImages(curModule->hideImages());
      curModule->setSysPath(sysPath);
      curModule->setDiffPath(m_sRelativeDocumentRoot);
      WWidget* w = curModule->createContents();
      if ( w ) {
        if ( asString(curModule->option("useLayout")) == "true" ) {
          WVBoxLayout* vbox = new WVBoxLayout();
          vbox->addWidget(w, 1);
          setLayout(vbox);
        } else {
          addWidget(w);
        }
      } else {
        wApp->log("notice") << "WsContent::selectWidget : module, render " << curModule->moduleName() << " CANNOT call create content: ";
      }
      return;
    }
  }

  if ( strExt == ".pdf" ) {
    if ( m_bLogContent )
      wApp->log("notice") << "WsContent::selectWidget : render a " << strExt << " file : " << sysPath;
    //     if ( !allowedPath(userUID, syspath) ) return;
    clear();
    WsApp->hideImages(false);
    addWidget(new WText("Download file : " + path + " ..."));
    return wApp->redirect(m_sRelativeDocumentRoot + path);
  }
  clear();
  addWidget(new WsErrorPage(WsErrorPage::Error, path, 0, "Unknown extension", false));
}
Esempio n. 16
0
 void handlePathChange() {
   if (internalPathMatches("/drinks/")) {
     std::string drink = internalPathNextPart("/drinks/");
     aboutDrink_->setText(WString::tr("drink-" + drink));
   }
 }
Esempio n. 17
0
void SVSEView::addSVSEList(string &szName, string &szIndex)
{
    if(m_pSEList)
    {
        int nRow = m_pSEList->numRows();

        SVTableCell cell;

        sv_group_state groupState = getSVSEState(szIndex, m_pSVUser, m_szIDCUser, m_szIDCPwd);
        bool bHasEditRight = true;
        bool bHasDelRight = true;
        if(m_pSVUser)
        {
            bHasEditRight = m_pSVUser->haveUserRight(szIndex, "se_edit");
            bHasDelRight = m_pSVUser->haveUserRight(szIndex, "se_delse");
        }
        else
        {
            bHasEditRight = false;
            bHasDelRight = false;
        }
        // Ñ¡Ôñ
        //if(szIndex.compare("1") != 0)
        //{
        //    WCheckBox * pCheck = NULL;
        //    if(bHasEditRight || bHasDelRight) pCheck = new WCheckBox("", (WContainerWidget *)m_pSEList->elementAt(nRow, 0));
        //    if(pCheck)
        //    {
        //        cell.setType(adCheckBox);
        //        cell.setValue(pCheck);
        //        m_svSEList.WriteCell(szIndex, 0, cell);
        //    }
        //}
        // ÃèÊö
        WText *pDesc = new WText("", (WContainerWidget *)m_pSEList->elementAt(nRow, 0));
        if(pDesc)
        {
            char szState[512] = {0};
            sprintf(szState, "%s%d<BR>%s%d<BR>%s%d<BR>%s%d<BR>%s%d", 
                SVResString::getResString("IDS_Device_Count").c_str(), groupState.nDeviceCount,
                SVResString::getResString("IDS_Monitor_Count").c_str(), groupState.nMonitorCount, 
                SVResString::getResString("IDS_Monitor_Disable_Count").c_str(), groupState.nDisableCount,
                SVResString::getResString("IDS_Monitor_Error_Count").c_str(), groupState.nErrorCount, 
                SVResString::getResString("IDS_Monitor_Warn_Count").c_str(), groupState.nWarnCount);
            pDesc->setText(szState);
        }
        // Ãû³Æ
        WText *pName = new WText(szName, (WContainerWidget *)m_pSEList->elementAt(nRow, 1));
        if ( pName )
        {
            sprintf(pName->contextmenu_, "style='color:#669;cursor:pointer;' onmouseover='" \
                "this.style.textDecoration=\"underline\"' " \
                "onmouseout='this.style.textDecoration=\"none\"'");
            pName->setToolTip(szName);
            WObject::connect(pName, SIGNAL(clicked()), "showbar();", &m_wNameMapper, SLOT(map()), WObject::ConnectionType::JAVASCRIPTDYNAMIC);
            m_wNameMapper.setMapping(pName, szIndex);

            cell.setType(adText);
            cell.setValue(pName);

            m_svSEList.WriteCell(szIndex, 2, cell);
            SVTableRow *pRow = m_svSEList.Row(szIndex);
            if(pRow)
                pRow->setProperty(szIndex.c_str());
        }
        // ±à¼­
        WImage * pEdit = NULL;
        if(bHasEditRight) pEdit = new WImage("../icons/edit.gif", (WContainerWidget *)m_pSEList->elementAt(nRow, 2));
        if (pEdit)
        {
            pEdit->setToolTip(SVResString::getResString("IDS_Edit"));
            pEdit->setStyleClass("imgbutton");
            WObject::connect(pEdit, SIGNAL(clicked()), "showbar();", &m_wEditMapper, SLOT(map()), WObject::ConnectionType::JAVASCRIPTDYNAMIC);
            m_wEditMapper.setMapping(pEdit,szIndex);
        }

        if((nRow + 1) % 2 == 0)
            m_pSEList->GetRow(nRow)->setStyleClass("tr1");
        else
            m_pSEList->GetRow(nRow)->setStyleClass("tr2");
    }

}
Esempio n. 18
0
WWidget *WItemDelegate::update(WWidget *widget, const WModelIndex& index,
			       WFlags<ViewItemRenderFlag> flags)
{
  bool editing = widget && widget->find("t") == 0;

  if (flags & RenderEditing) {
    if (!editing) {
      widget = createEditor(index, flags);
      WInteractWidget *iw = dynamic_cast<WInteractWidget *>(widget);
      if (iw) {
	// Disable drag & drop and selection behaviour
	iw->mouseWentDown().preventPropagation();
	iw->clicked().preventPropagation();
      }
    }
  } else {
    if (editing)
      widget = 0;
  }

  WidgetRef widgetRef(widget);

  bool isNew = false;

  if (!(flags & RenderEditing)) {
    if (!widgetRef.w) {
      isNew = true;
      WText *t = new WText();
      t->setObjectName("t");
      if (index.isValid() && !(index.flags() & ItemIsXHTMLText))
	t->setTextFormat(PlainText);
      t->setWordWrap(true);
      widgetRef.w = t;
    }

    if (!index.isValid())
      return widgetRef.w;

    bool haveCheckBox = false;

    if (index.flags() & ItemIsUserCheckable) {
      boost::any checkedData = index.data(CheckStateRole);
      CheckState state = checkedData.empty() ? Unchecked
	: (checkedData.type() == typeid(bool) ?
	   (boost::any_cast<bool>(checkedData) ? Checked : Unchecked)
	   : (checkedData.type() == typeid(CheckState) ?
	      boost::any_cast<CheckState>(checkedData) : Unchecked));
      checkBox(widgetRef, index, true, index.flags() & ItemIsTristate)
	->setCheckState(state);
      haveCheckBox = true;
    } else if (!isNew)
      delete checkBox(widgetRef, index, false);

    boost::any linkData = index.data(LinkRole);
    if (!linkData.empty()) {
      WLink link = boost::any_cast<WLink>(linkData);
      WAnchor *a = anchorWidget(widgetRef);
      a->setLink(link);
      if (link.type() == WLink::Resource)
	a->setTarget(TargetNewWindow);
    }

    WText *t = textWidget(widgetRef);

    WString label = asString(index.data(), textFormat_);
    if (label.empty() && haveCheckBox)
      label = WString::fromUTF8(" ");
    t->setText(label);

    std::string iconUrl = asString(index.data(DecorationRole)).toUTF8();
    if (!iconUrl.empty()) {
      iconWidget(widgetRef, true)->setImageLink(WLink(iconUrl));
    } else if (!isNew)
      delete iconWidget(widgetRef, false);
  }

  WString tooltip = asString(index.data(ToolTipRole));
  if (!tooltip.empty() || !isNew)
    widgetRef.w->setToolTip(tooltip);

  WT_USTRING sc = asString(index.data(StyleClassRole));

  if (flags & RenderSelected)
    sc += WT_USTRING::fromUTF8
      (" " + WApplication::instance()->theme()->activeClass());

  if (flags & RenderEditing)
    sc += WT_USTRING::fromUTF8(" Wt-delegate-edit");

  widgetRef.w->setStyleClass(sc);

  if (index.flags() & ItemIsDropEnabled)
    widgetRef.w->setAttributeValue("drop", WString::fromUTF8("true"));
  else
    if (!widgetRef.w->attributeValue("drop").empty())
      widgetRef.w->setAttributeValue("drop", WString::fromUTF8("f"));

  return widgetRef.w;
}
Esempio n. 19
0
UpdatePasswordWidget::UpdatePasswordWidget(const User& user,
					   const AbstractPasswordService& auth,
					   Login& login,
					   bool promptPassword,
					   WContainerWidget *parent)
  : WTemplate(tr("Wt.Auth.template.update-password"), parent),
    user_(user),
    promptPassword_(promptPassword),
    validated_(false),
    enterPasswordFields_(0)
{
  addFunction("id", &WTemplate::Functions::id);
  addFunction("tr", &WTemplate::Functions::tr);

  WLineEdit *nameEdit = new WLineEdit(user.identity(Identity::LoginName));
  nameEdit->disable();
  nameEdit->addStyleClass("Wt-disabled");
  bindWidget("user-name", nameEdit);

  WPushButton *okButton = new WPushButton(tr("Wt.WMessageBox.Ok"));
  WPushButton *cancelButton = new WPushButton(tr("Wt.WMessageBox.Cancel"));

  if (promptPassword_) {
    setCondition("if:old-password", true);
    WLineEdit *oldPasswd = new WLineEdit();
    WText *oldPasswdInfo = new WText();

    enterPasswordFields_ = new EnterPasswordFields(auth,
						   oldPasswd, oldPasswdInfo,
						   okButton, this);

    oldPasswd->setFocus();

    bindWidget("old-password", oldPasswd);
    bindWidget("old-password-info", oldPasswdInfo);
  }

  WLineEdit *password = new WLineEdit();
  password->setEchoMode(WLineEdit::Password);
  password->keyWentUp().connect
    (boost::bind(&UpdatePasswordWidget::checkPassword, this));
  password->changed().connect
    (boost::bind(&UpdatePasswordWidget::checkPassword, this));

  WText *passwordInfo = new WText();

  WLineEdit *password2 = new WLineEdit();
  password2->setEchoMode(WLineEdit::Password);
  password2->changed().connect
    (boost::bind(&UpdatePasswordWidget::checkPassword2, this));

  WText *password2Info = new WText();

  bindWidget("choose-password", password);
  bindWidget("choose-password-info", passwordInfo);

  bindWidget("repeat-password", password2);
  bindWidget("repeat-password-info", password2Info);

  model_ = new RegistrationModel(auth.baseAuth(), *user.database(),
				 login, this);

  model_->addPasswordAuth(&auth);

  model_->setValue(RegistrationModel::LoginName,
		   user.identity(Identity::LoginName));
  model_->setValue(RegistrationModel::Email,
		   WT_USTRING::fromUTF8(user.email() + " "
					+ user.unverifiedEmail()));

  model_->validatePasswordsMatchJS(password, password2, password2Info);

  passwordInfo->setText(model_->validationResult
			(RegistrationModel::Password).message());
  password2Info->setText(model_->validationResult
			 (RegistrationModel::Password2).message());

  okButton->clicked().connect(this, &UpdatePasswordWidget::doUpdate);
  cancelButton->clicked().connect(this, &UpdatePasswordWidget::close);

  bindWidget("ok-button", okButton);
  bindWidget("cancel-button", cancelButton);

  if (!promptPassword_)
    password->setFocus();
}
Esempio n. 20
0
void WBootstrapTheme::apply(WWidget *widget, WWidget *child, int widgetRole)
  const
{
  if (!widget->isThemeStyleEnabled())
    return;

  switch (widgetRole) {
  case MenuItemIcon:
    child->addStyleClass("Wt-icon");
    break;
  case MenuItemCheckBox:
    child->setStyleClass("Wt-chkbox");
    ((WFormWidget *)child)->label()->addStyleClass("checkbox-inline");
    break;
  case MenuItemClose:
    {
      child->addStyleClass("close");
      WText *t = dynamic_cast<WText *>(child);
      t->setText("&times;");
      break;
    }
  case DialogContent:
    if (version_ == BootstrapVersion::v3)
      child->addStyleClass("modal-content");
    break;
  case DialogCoverWidget:
    if (version_ == BootstrapVersion::v3)
      child->addStyleClass("modal-backdrop in");
    else
      child->addStyleClass("modal-backdrop Wt-bootstrap2");
    break;
  case DialogTitleBar:
       child->addStyleClass("modal-header");
    break;
  case DialogBody:
      child->addStyleClass("modal-body");
    break;
  case DialogFooter:
    child->addStyleClass("modal-footer");
    break;
  case DialogCloseIcon:
    {
      child->addStyleClass("close");
      WText *t = dynamic_cast<WText *>(child);
      t->setText("&times;");
      break;
    }

  case TableViewRowContainer:
    {
      WAbstractItemView *view = dynamic_cast<WAbstractItemView *>(widget);
      child->toggleStyleClass("Wt-striped", view->alternatingRowColors());
      break;
    }

  case DatePickerPopup:
    child->addStyleClass("Wt-datepicker");
    break;

  case TimePickerPopup:
    child->addStyleClass("Wt-timepicker");
    break;

  case PanelTitleBar:
    child->addStyleClass(classAccordionHeading());
    break;

  case PanelCollapseButton:
  case PanelTitle:
    child->addStyleClass("accordion-toggle");
    break;

  case PanelBody:
    child->addStyleClass(classAccordionInner());
    break;
  case InPlaceEditing:
    if (version_ == BootstrapVersion::v2)
      child->addStyleClass("input-append");
    else
      child->addStyleClass("input-group");
    break;
  case NavCollapse:
    child->addStyleClass(classNavCollapse());
    break;
  case NavBrand:
    child->addStyleClass(classBrand());
    break;
  case NavbarSearch:
    child->addStyleClass(classNavbarSearch());
    break;
  case NavbarAlignLeft:
    child->addStyleClass(classNavbarLeft());
    break;
  case NavbarAlignRight:
    child->addStyleClass(classNavbarRight());
    break;
  case NavbarMenu:
    child->addStyleClass(classNavbarMenu());
    break;
  case NavbarBtn:
    child->addStyleClass(classNavbarBtn());
    break;
  }
}