示例#1
0
OBJECT_PTR throw_reg_fn(reg_closure_t *cls, OBJECT_PTR val)
{
  return list(2, THROW, val);
}
示例#2
0
SExpr* ALFContext::load(unsigned BitWidth, const Twine& Fref, unsigned Offset) {
    return list("load")->append(BitWidth)->append(address(Fref,Offset));
}
示例#3
0
dspSubLedger::dspSubLedger(QWidget* parent, const char*, Qt::WFlags fl)
  : display(parent, "dspSubLedger", fl)
{
  setWindowTitle(tr("Subledger Transactions"));
  setListLabel(tr("Transactions"));
  setReportName("Subledger");
  setMetaSQLOptions("subledger", "detail");
  setParameterWidgetVisible(true);

  QString qryType = QString( "SELECT  1, '%1' UNION "
                             "SELECT  2, '%2' UNION "
                             "SELECT  3, '%3' UNION "
                             "SELECT  4, '%4' UNION "
                             "SELECT  5, '%5'")
      .arg(tr("Asset"))
      .arg(tr("Expense"))
      .arg(tr("Liability"))
      .arg(tr("Equity"))
      .arg(tr("Revenue"));

  QString qrySubType = QString("SELECT subaccnttype_id, "
                               "       (subaccnttype_code || '-' || subaccnttype_descrip) "
                               "FROM subaccnttype "
                               "ORDER BY subaccnttype_code;");

  QString qrySource = QString("SELECT 1 AS id, 'A/P' AS source  UNION "
                              "SELECT 2 AS id, 'A/R' AS source  UNION "
                              "SELECT 3 AS id, 'G/L' AS source  UNION "
                              "SELECT 4 AS id, 'I/M' AS source  UNION "
                              "SELECT 5 AS id, 'P/D' AS source  UNION "
                              "SELECT 6 AS id, 'P/O' AS source  UNION "
                              "SELECT 7 AS id, 'S/O' AS source  UNION "
                              "SELECT 8 AS id, 'S/R' AS source  UNION "
                              "SELECT 9 AS id, 'W/O' AS source;");

  QString qryAccNum = QString("SELECT min(accnt_id) as num_id,"
                              "       accnt_number AS num_number "
                              "FROM accnt "
                              "GROUP BY accnt_number "
                              "ORDER BY accnt_number;");
 
  list()->addColumn(tr("Date"),      _dateColumn,    Qt::AlignCenter, true, "sltrans_date");
  list()->addColumn(tr("Source"),    _orderColumn,   Qt::AlignCenter, true, "sltrans_source");
  list()->addColumn(tr("Doc. Type"), _docTypeColumn, Qt::AlignCenter, true, "sltrans_doctype");
  list()->addColumn(tr("Doc. #"),    _orderColumn,   Qt::AlignCenter, true, "docnumber");
  list()->addColumn(tr("Reference"), -1,             Qt::AlignLeft,   true, "notes");
  list()->addColumn(tr("Journal#"),  _orderColumn,   Qt::AlignLeft,   false,"sltrans_journalnumber");
  list()->addColumn(tr("Account"),   -1,             Qt::AlignLeft,   true, "account");
  list()->addColumn(tr("Debit"),     _moneyColumn,   Qt::AlignRight,  true, "debit");
  list()->addColumn(tr("Credit"),    _moneyColumn,   Qt::AlignRight,  true, "credit");
  list()->addColumn(tr("Posted"),    _ynColumn,      Qt::AlignCenter, true, "sltrans_posted");
  list()->addColumn(tr("GL Journal #"),_orderColumn,   Qt::AlignLeft,   false, "sltrans_gltrans_journalnumber");
  list()->addColumn(tr("Username"),  _userColumn,    Qt::AlignLeft,   false, "sltrans_username");

  parameterWidget()->append(tr("Start Date"), "startDate", ParameterWidget::Date, QDate::currentDate(), true);
  parameterWidget()->append(tr("End Date"),   "endDate",   ParameterWidget::Date, QDate::currentDate(), true);
  parameterWidget()->append(tr("GL Account"), "accnt_id",  ParameterWidget::GLAccount);
  parameterWidget()->append(tr("Document #"), "docnum",    ParameterWidget::Text);
  parameterWidget()->appendComboBox(tr("Source"), "source_id",    qrySource);
  parameterWidget()->append(tr("Source Pattern"), "source_pattern", ParameterWidget::Text);
  if (_metrics->value("GLCompanySize").toInt() > 0)
  parameterWidget()->appendComboBox(tr("Company"), "company_id", XComboBox::Companies);
  if (_metrics->value("GLProfitSize").toInt() >  0)
    parameterWidget()->appendComboBox(tr("Profit Center"), "prfcntr_id", XComboBox::ProfitCenters);
  parameterWidget()->appendComboBox(tr("Main Segment"), "num_id", qryAccNum);
  if (_metrics->value("GLSubaccountSize").toInt() > 0)
    parameterWidget()->appendComboBox(tr("Sub Account"), "subaccnt_id", XComboBox::Subaccounts);
  parameterWidget()->appendComboBox(tr("Account Type"), "accnttype_id", qryType);
  parameterWidget()->appendComboBox(tr("Sub Type"), "subType",   qrySubType);
  parameterWidget()->append(tr("Posted"), "posted", ParameterWidget::CheckBox);
  parameterWidget()->append(tr("GL Journal"), "journalnumber",    ParameterWidget::Text);

  parameterWidget()->applyDefaultFilterSet();

  _sources << "None" << "A/P" << "A/R" << "G/L" << "I/M" << "P/D" << "P/O" << "S/O" << "S/R" << "W/O";
}
示例#4
0
//**********************************************************************************************************************
int GetSeqsCommand::readList(){
	try {
		string thisOutputDir = outputDir;
		if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
		string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(listfile)) + "pick" +  m->getExtension(listfile);
		ofstream out;
		m->openOutputFile(outputFileName, out);
		
		ifstream in;
		m->openInputFile(listfile, in);
		
		bool wroteSomething = false;
		int selectedCount = 0;
		
		while(!in.eof()){
			
			selectedCount = 0;
			
			if (m->control_pressed) { in.close(); out.close(); m->mothurRemove(outputFileName);  return 0; }

			//read in list vector
			ListVector list(in);
			
			//make a new list vector
			ListVector newList;
			newList.setLabel(list.getLabel());
			
			//for each bin
			for (int i = 0; i < list.getNumBins(); i++) {
			
				//parse out names that are in accnos file
				string binnames = list.get(i);
				
				string newNames = "";
				while (binnames.find_first_of(',') != -1) { 
					string name = binnames.substr(0,binnames.find_first_of(','));
					binnames = binnames.substr(binnames.find_first_of(',')+1, binnames.length());
					
					//if that name is in the .accnos file, add it
					if (names.count(name) != 0) {  newNames += name + ",";  selectedCount++; }
				}
			
				//get last name
				if (names.count(binnames) != 0) {  newNames += binnames + ",";  selectedCount++; }

				//if there are names in this bin add to new list
				if (newNames != "") { 
					newNames = newNames.substr(0, newNames.length()-1); //rip off extra comma
					newList.push_back(newNames);	
				}
			}
				
			//print new listvector
			if (newList.getNumBins() != 0) {
				wroteSomething = true;
				newList.print(out);
			}
			
			m->gobble(in);
		}
		in.close();	
		out.close();
		
		if (wroteSomething == false) { m->mothurOut("Your file does not contain any sequence from the .accnos file."); m->mothurOutEndLine();  }
		outputNames.push_back(outputFileName); outputTypes["list"].push_back(outputFileName);
		
		m->mothurOut("Selected " + toString(selectedCount) + " sequences from your list file."); m->mothurOutEndLine();
		
		return 0;

	}
	catch(exception& e) {
		m->errorOut(e, "GetSeqsCommand", "readList");
		exit(1);
	}
}
dspGLTransactions::dspGLTransactions(QWidget* parent, const char*, Qt::WFlags fl)
  : display(parent, "dspGLTransactions", fl)
{
  setupUi(optionsWidget());
  setWindowTitle(tr("General Ledger Transactions"));
  setListLabel(tr("Transactions"));
  setReportName("GLTransactions");
  setMetaSQLOptions("gltransactions", "detail");
  setUseAltId(true);
  setParameterWidgetVisible(true);

  QString qryType = QString( "SELECT  1, '%1' UNION "
                             "SELECT  2, '%2' UNION "
                             "SELECT  3, '%3' UNION "
                             "SELECT  4, '%4' UNION "
                             "SELECT  5, '%5'")
      .arg(tr("Asset"))
      .arg(tr("Expense"))
      .arg(tr("Liability"))
      .arg(tr("Equity"))
      .arg(tr("Revenue"));

  QString qrySubType = QString("SELECT subaccnttype_id, "
                               "       (subaccnttype_code || '-' || subaccnttype_descrip) "
                               "FROM subaccnttype "
                               "ORDER BY subaccnttype_code;");

  QString qrySource = QString("SELECT 1 AS id, 'A/P' AS source  UNION "
                              "SELECT 2 AS id, 'A/R' AS source  UNION "
                              "SELECT 3 AS id, 'G/L' AS source  UNION "
                              "SELECT 4 AS id, 'I/M' AS source  UNION "
                              "SELECT 5 AS id, 'P/D' AS source  UNION "
                              "SELECT 6 AS id, 'P/O' AS source  UNION "
                              "SELECT 7 AS id, 'S/O' AS source  UNION "
                              "SELECT 8 AS id, 'S/R' AS source  UNION "
                              "SELECT 9 AS id, 'W/O' AS source;");

  QString qryAccNum = QString("SELECT min(accnt_id) as num_id,"
                              "       accnt_number AS num_number "
                              "FROM accnt "
                              "GROUP BY accnt_number "
                              "ORDER BY accnt_number;");
 
  connect(parameterWidget(), SIGNAL(filterChanged()), this, SLOT(handleTotalCheckbox()));
  connect(_showRunningTotal, SIGNAL(toggled(bool)), this, SLOT(handleTotalCheckbox()));

  list()->addColumn(tr("Date"),      _dateColumn,    Qt::AlignCenter, true, "gltrans_date");
  list()->addColumn(tr("Date Created"), _timeDateColumn, Qt::AlignCenter, true, "gltrans_created");
  list()->addColumn(tr("Source"),    _orderColumn,   Qt::AlignCenter, true, "gltrans_source");
  list()->addColumn(tr("Doc. Type"), _docTypeColumn, Qt::AlignCenter, !_metrics->boolean("UseJournals"), "gltrans_doctype");
  list()->addColumn(tr("Doc. #"),    _orderColumn,   Qt::AlignCenter, true, "docnumber");
  list()->addColumn(tr("Reference"), -1,             Qt::AlignLeft,   !_metrics->boolean("UseJournals"), "notes");
  list()->addColumn(tr("Journal #"),  _orderColumn,   Qt::AlignLeft,   false,"gltrans_journalnumber");
  list()->addColumn(tr("Account"),   -1,             Qt::AlignLeft,   true, "account");
  list()->addColumn(tr("Debit"),     _moneyColumn,   Qt::AlignRight,  true, "debit");
  list()->addColumn(tr("Credit"),    _moneyColumn,   Qt::AlignRight,  true, "credit");
  list()->addColumn(tr("Posted"),    _ynColumn,      Qt::AlignCenter, false, "gltrans_posted");
  list()->addColumn(tr("Username"),  _userColumn,    Qt::AlignLeft,   false, "gltrans_username");
  list()->addColumn(tr("Running Total"), _moneyColumn, Qt::AlignRight,false,"running");

  _beginningBalance->setPrecision(omfgThis->moneyVal());

  _beginningBalanceLit->setVisible(_showRunningTotal->isChecked());
  _beginningBalance->setVisible(_showRunningTotal->isChecked());
  if (_showRunningTotal->isChecked())
    list()->showColumn("running");
  else
    list()->hideColumn("running");

  parameterWidget()->append(tr("Start Date"), "startDate", ParameterWidget::Date, QDate::currentDate(), true);
  parameterWidget()->append(tr("End Date"),   "endDate",   ParameterWidget::Date, QDate::currentDate(), true);
  parameterWidget()->append(tr("GL Account"), "accnt_id",  ParameterWidget::GLAccount);
  parameterWidget()->append(tr("Document #"), "docnum",    ParameterWidget::Text);
  parameterWidget()->appendComboBox(tr("Source"), "source_id",    qrySource);
  if (_metrics->value("GLCompanySize").toInt() > 0)
  parameterWidget()->appendComboBox(tr("Company"), "company_id", XComboBox::Companies);
  if (_metrics->value("GLProfitSize").toInt() >  0)
    parameterWidget()->appendComboBox(tr("Profit Center"), "prfcntr_id", XComboBox::ProfitCenters);
  parameterWidget()->appendComboBox(tr("Main Segment"), "num_id", qryAccNum);
  if (_metrics->value("GLSubaccountSize").toInt() > 0)
    parameterWidget()->appendComboBox(tr("Sub Account"), "subaccnt_id", XComboBox::Subaccounts);
  parameterWidget()->appendComboBox(tr("Account Type"), "accnttype_id", qryType);
  parameterWidget()->appendComboBox(tr("Sub Type"), "subType",   qrySubType);
  parameterWidget()->append(tr("Show Deleted"), "showDeleted", ParameterWidget::Exists);

  parameterWidget()->applyDefaultFilterSet();

  _sources << "None" << "A/P" << "A/R" << "G/L" << "I/M" << "P/D" << "P/O" << "S/O" << "S/R" << "W/O";
}
示例#6
0
void dspPoItemsByVendor::sSearch( const QString &pTarget )
{
  list()->clearSelection();
  int i;
  for (i = 0; i < list()->topLevelItemCount(); i++)
  {
    if ( list()->topLevelItem(i)->text(list()->column("itemnumber")).startsWith(pTarget, Qt::CaseInsensitive) ||
         list()->topLevelItem(i)->text(list()->column("itemdescrip")).contains(pTarget, Qt::CaseInsensitive) ||
         list()->topLevelItem(i)->text(list()->column("poitem_vend_item_number")).startsWith(pTarget, Qt::CaseInsensitive) )
      break;
  }

  if (i < list()->topLevelItemCount())
  {
    list()->setCurrentItem(list()->topLevelItem(i));
    list()->scrollToItem(list()->topLevelItem(i));
  }
}
int Notepad_plus::setFileOpenSaveDlgFilters(FileDialog & fDlg, int langType)
{
	NppParameters *pNppParam = NppParameters::getInstance();
	NppGUI & nppGUI = (NppGUI & )pNppParam->getNppGUI();

	int i = 0;
	Lang *l = NppParameters::getInstance()->getLangFromIndex(i++);

    int ltIndex = 0;
    bool ltFound = false;
	while (l)
	{
		LangType lid = l->getLangID();

		bool inExcludedList = false;
		
		for (size_t j = 0 ; j < nppGUI._excludedLangList.size() ; j++)
		{
			if (lid == nppGUI._excludedLangList[j]._langType)
			{
				inExcludedList = true;
				break;
			}
		}

		if (!inExcludedList)
		{
			const TCHAR *defList = l->getDefaultExtList();
			const TCHAR *userList = NULL;

			LexerStylerArray &lsa = (NppParameters::getInstance())->getLStylerArray();
			const TCHAR *lName = l->getLangName();
			LexerStyler *pLS = lsa.getLexerStylerByName(lName);
			
			if (pLS)
				userList = pLS->getLexerUserExt();

			generic_string list(TEXT(""));
			if (defList)
				list += defList;
			if (userList)
			{
				list += TEXT(" ");
				list += userList;
			}
			
			generic_string stringFilters = exts2Filters(list);
			const TCHAR *filters = stringFilters.c_str();
			if (filters[0])
			{
				fDlg.setExtsFilter(getLangDesc(lid, false).c_str(), filters);

                //
                // Get index of lang type to find
                //
                if (langType != -1 && !ltFound)
                {
                    ltFound = langType == lid;
                }

                if (langType != -1 && !ltFound)
                {
                    ltIndex++;
                }
			}
		}
		l = (NppParameters::getInstance())->getLangFromIndex(i++);
	}

    if (!ltFound)
        return -1;
    return ltIndex;
}
示例#8
0
void dspSalesHistoryByItem::sHandleParams()
{
  if (_showPrices->isChecked())
  {
    list()->showColumn(list()->column("cohist_unitprice"));
    list()->showColumn(list()->column("extprice"));
    list()->showColumn(list()->column("currAbbr"));
    list()->showColumn(list()->column("baseunitprice"));
    list()->showColumn(list()->column("baseextprice"));
  }
  else
  {
    list()->hideColumn(list()->column("cohist_unitprice"));
    list()->hideColumn(list()->column("extprice"));
    list()->hideColumn(list()->column("currAbbr"));
    list()->hideColumn(list()->column("baseunitprice"));
    list()->hideColumn(list()->column("baseextprice"));
  }

  if (_showCosts->isChecked())
  {
    list()->showColumn(list()->column("cohist_unitcost"));
    list()->showColumn(list()->column("extcost"));
  }
  else
  {
    list()->hideColumn(list()->column("cohist_unitcost"));
    list()->hideColumn(list()->column("extcost"));
  }
}
示例#9
0
dspSalesHistoryByItem::dspSalesHistoryByItem(QWidget* parent, const char*, Qt::WFlags fl)
  : display(parent, "dspSalesHistoryByItem", fl)
{
  setupUi(optionsWidget());
  setWindowTitle(tr("Sales History by Item"));
  setListLabel(tr("Sales History"));
  setReportName("SalesHistoryByItem");
  setMetaSQLOptions("salesHistory", "detail");

  connect(_showCosts, SIGNAL(toggled(bool)), this, SLOT(sHandleParams()));
  connect(_showPrices, SIGNAL(toggled(bool)), this, SLOT(sHandleParams()));

  _item->setType(ItemLineEdit::cSold);
  _customerType->setType(ParameterGroup::CustomerType);

  list()->addColumn(tr("Customer"),            -1,              Qt::AlignLeft,   true,  "cust_name"   );
  list()->addColumn(tr("Doc. #"),              _orderColumn,    Qt::AlignLeft,   true,  "cohist_ordernumber"   );
  list()->addColumn(tr("Ord. Date"),           _dateColumn,     Qt::AlignCenter, true,  "cohist_orderdate" );
  list()->addColumn(tr("Invoice #"),           _orderColumn,    Qt::AlignLeft,   true,  "invoicenumber"   );
  list()->addColumn(tr("Invc. Date"),          _dateColumn,     Qt::AlignCenter, true,  "cohist_invcdate" );
  list()->addColumn(tr("Shipped"),             _qtyColumn,      Qt::AlignRight,  true,  "cohist_qtyshipped"  );
  if (_privileges->check("ViewCustomerPrices"))
  {
    list()->addColumn( tr("Unit Price"),       _priceColumn,    Qt::AlignRight,  true,  "cohist_unitprice" );
    list()->addColumn( tr("Ext. Price"),       _bigMoneyColumn, Qt::AlignRight,  true,  "extprice" );
    list()->addColumn(tr("Currency"),          _currencyColumn, Qt::AlignRight,  true,  "currAbbr" );
    list()->addColumn(tr("Base Unit Price"),   _bigMoneyColumn, Qt::AlignRight,  true,  "baseunitprice" );
    list()->addColumn(tr("Base Ext. Price"),   _bigMoneyColumn, Qt::AlignRight,  true,  "baseextprice" );
  }
  if (_privileges->check("ViewCosts"))
  {
    list()->addColumn( tr("Unit Cost"),        _costColumn,     Qt::AlignRight,  true,  "cohist_unitcost" );
    list()->addColumn( tr("Ext. Cost"),        _bigMoneyColumn, Qt::AlignRight,  true,  "extcost" );
  }

  _showCosts->setEnabled(_privileges->check("ViewCosts"));
  _showPrices->setEnabled(_privileges->check("ViewCustomerPrices"));

  sHandleParams();

  _item->setFocus();
}
示例#10
0
STATIC union node *
command() {
      union node *n1, *n2;
      union node *ap, **app;
      union node *cp, **cpp;
      union node *redir, **rpp;
      int t;

      checkkwd();
      switch (readtoken()) {
      case TIF:
	    n1 = (union node *)stalloc(sizeof (struct nif));
	    n1->type = NIF;
	    n1->nif.test = list(0);
	    if (readtoken() != TTHEN)
		  synexpect(TTHEN);
	    n1->nif.ifpart = list(0);
	    n2 = n1;
	    while (readtoken() == TELIF) {
		  n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
		  n2 = n2->nif.elsepart;
		  n2->type = NIF;
		  n2->nif.test = list(0);
		  if (readtoken() != TTHEN)
			synexpect(TTHEN);
		  n2->nif.ifpart = list(0);
	    }
	    if (lasttoken == TELSE)
		  n2->nif.elsepart = list(0);
	    else {
		  n2->nif.elsepart = NULL;
		  tokpushback++;
	    }
	    if (readtoken() != TFI)
		  synexpect(TFI);
	    break;
      case TWHILE:
      case TUNTIL:
	    n1 = (union node *)stalloc(sizeof (struct nbinary));
	    n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
	    n1->nbinary.ch1 = list(0);
	    if (readtoken() != TDO)
		  synexpect(TDO);
	    n1->nbinary.ch2 = list(0);
	    if (readtoken() != TDONE)
		  synexpect(TDONE);
	    break;
      case TFOR:
	    if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
		  synerror("Bad for loop variable");
	    n1 = (union node *)stalloc(sizeof (struct nfor));
	    n1->type = NFOR;
	    n1->nfor.var = wordtext;
	    if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
		  app = &ap;
		  while (readtoken() == TWORD) {
			n2 = (union node *)stalloc(sizeof (struct narg));
			n2->type = NARG;
			n2->narg.text = wordtext;
			n2->narg.backquote = backquotelist;
			*app = n2;
			app = &n2->narg.next;
		  }
		  *app = NULL;
		  n1->nfor.args = ap;
	    } else {
#ifndef GDB_HACK
		  static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
						  '@', '=', '\0'};
#endif
		  n2 = (union node *)stalloc(sizeof (struct narg));
		  n2->type = NARG;
		  n2->narg.text = (char *)argvars;
		  n2->narg.backquote = NULL;
		  n2->narg.next = NULL;
		  n1->nfor.args = n2;
	    }
	    if (lasttoken != TNL && lasttoken != TSEMI)
		  synexpect(-1);
	    checkkwd();
	    if ((t = readtoken()) == TDO)
		  t = TDONE;
	    else if (t == TBEGIN)
		  t = TEND;
	    else
		  synexpect(-1);
	    n1->nfor.body = list(0);
	    if (readtoken() != t)
		  synexpect(t);
	    break;
      case TCASE:
	    n1 = (union node *)stalloc(sizeof (struct ncase));
	    n1->type = NCASE;
	    if (readtoken() != TWORD)
		  synexpect(TWORD);
	    n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
	    n2->type = NARG;
	    n2->narg.text = wordtext;
	    n2->narg.backquote = backquotelist;
	    n2->narg.next = NULL;
	    while (readtoken() == TNL);
	    if (lasttoken != TWORD || ! equal(wordtext, "in"))
		  synerror("expecting \"in\"");
	    cpp = &n1->ncase.cases;
	    while (checkkwd(), readtoken() == TWORD) {
		  *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
		  cp->type = NCLIST;
		  app = &cp->nclist.pattern;
		  for (;;) {
			*app = ap = (union node *)stalloc(sizeof (struct narg));
			ap->type = NARG;
			ap->narg.text = wordtext;
			ap->narg.backquote = backquotelist;
			if (readtoken() != TPIPE)
			      break;
			app = &ap->narg.next;
			if (readtoken() != TWORD)
			      synexpect(TWORD);
		  }
		  ap->narg.next = NULL;
		  if (lasttoken != TRP)
			synexpect(TRP);
		  cp->nclist.body = list(0);
		  if ((t = readtoken()) == TESAC)
			tokpushback++;
		  else if (t != TENDCASE)
			synexpect(TENDCASE);
		  cpp = &cp->nclist.next;
	    }
	    *cpp = NULL;
	    if (lasttoken != TESAC)
		  synexpect(TESAC);
	    break;
      case TLP:
	    n1 = (union node *)stalloc(sizeof (struct nredir));
	    n1->type = NSUBSHELL;
	    n1->nredir.n = list(0);
	    n1->nredir.redirect = NULL;
	    if (readtoken() != TRP)
		  synexpect(TRP);
	    break;
      case TBEGIN:
	    n1 = list(0);
	    if (readtoken() != TEND)
		  synexpect(TEND);
	    break;
      case TWORD:
      case TREDIR:
	    tokpushback++;
	    return simplecmd();
      default:
	    synexpect(-1);
      }

      /* Now check for redirection which may follow command */
      rpp = &redir;
      while (readtoken() == TREDIR) {
	    *rpp = n2 = redirnode;
	    rpp = &n2->nfile.next;
	    parsefname();
      }
      tokpushback++;
      *rpp = NULL;
      if (redir) {
	    if (n1->type != NSUBSHELL) {
		  n2 = (union node *)stalloc(sizeof (struct nredir));
		  n2->type = NREDIR;
		  n2->nredir.n = n1;
		  n1 = n2;
	    }
	    n1->nredir.redirect = redir;
      }
      return n1;
}
示例#11
0
void
top_level_eval(void)
{
	save();

	trigmode = 0;

	p1 = symbol(AUTOEXPAND);

	if (iszero(get_binding(p1)))
		expanding = 0;
	else
		expanding = 1;

	p1 = pop();
	push(p1);
	eval();
	p2 = pop();

	// "draw", "for" and "setq" return "nil", there is no result to print

	if (p2 == symbol(NIL)) {
		push(p2);
		restore();
		return;
	}

	// update "last"

	set_binding(symbol(LAST), p2);

	if (!iszero(get_binding(symbol(BAKE)))) {
		push(p2);
		bake();
		p2 = pop();
	}

	// If we evaluated the symbol "i" or "j" and the result was sqrt(-1)

	// then don't do anything.

	// Otherwise if "j" is an imaginary unit then subst.

	// Otherwise if "i" is an imaginary unit then subst.

	if ((p1 == symbol(SYMBOL_I) || p1 == symbol(SYMBOL_J))
	&& isimaginaryunit(p2))
		;
	else if (isimaginaryunit(get_binding(symbol(SYMBOL_J)))) {
		push(p2);
		push(imaginaryunit);
		push_symbol(SYMBOL_J);
		subst();
		p2 = pop();
	} else if (isimaginaryunit(get_binding(symbol(SYMBOL_I)))) {
		push(p2);
		push(imaginaryunit);
		push_symbol(SYMBOL_I);
		subst();
		p2 = pop();
	}

#ifndef LINUX

	// if we evaluated the symbol "a" and got "b" then print "a=b"

	// do not print "a=a"

	if (issymbol(p1) && !iskeyword(p1) && p1 != p2 && test_flag == 0) {
		push_symbol(SETQ);
		push(p1);
		push(p2);
		list(3);
		p2 = pop();
	}
#endif
	push(p2);

	restore();
}
void dspInvalidBillsOfMaterials::sEditItem()
{
  item::editItem(list()->altId());
}
示例#13
0
OBJECT_PTR break_metacont_fn(metacont_closure_t *mcls, reg_closure_t *cls)
{
  return list(2, SAVE_CONTINUATION_TO_RESUME, mc_to_exp(cls));
}
示例#14
0
OBJECT_PTR call_cc_reg_fn(reg_closure_t *cls, OBJECT_PTR val)
{
  OBJECT_PTR mc_exp = mc_to_exp((reg_closure_t *)cls->data);
  
  return list(3, val, mc_exp, mc_exp);
}
示例#15
0
QString KRecentDirs::dir(const QString &fileClass)
{
   QStringList result = list(fileClass);
   return result[0];
}
示例#16
0
int
main(int argc, char *argv[])
{
	const char *tmpdir;
	size_t tdlen;

	(void) setlocale(LC_ALL, "");
	listf = stderr;
	/*
	 * Keep a reference to cwd, so we can always come back home.
	 */
	cwdfd = open(".", O_RDONLY);
	if (cwdfd < 0) {
		syswarn(0, errno, "Can't open current working directory.");
		return(exit_val);
	}

	/*
	 * Where should we put temporary files?
	 */
	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
		tmpdir = _PATH_TMP;
	tdlen = strlen(tmpdir);
	while(tdlen > 0 && tmpdir[tdlen - 1] == '/')
		tdlen--;
	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
	if (tempfile == NULL) {
		paxwarn(1, "Cannot allocate memory for temp file name.");
		return(exit_val);
	}
	if (tdlen)
		memcpy(tempfile, tmpdir, tdlen);
	tempbase = tempfile + tdlen;
	*tempbase++ = '/';

	/*
	 * parse options, determine operational mode, general init
	 */
	options(argc, argv);
	if ((gen_init() < 0) || (tty_init() < 0))
		return(exit_val);

	/*
	 * select a primary operation mode
	 */
	switch(act) {
	case EXTRACT:
		extract();
		break;
	case ARCHIVE:
		archive();
		break;
	case APPND:
		if (gzip_program != NULL)
			err(1, "can not gzip while appending");
		append();
		break;
	case COPY:
		copy();
		break;
	default:
	case LIST:
		list();
		break;
	}
	return(exit_val);
}
示例#17
0
dspPoItemsByVendor::dspPoItemsByVendor(QWidget* parent, const char*, Qt::WFlags fl)
  : display(parent, "dspPoItemsByVendor", fl)
{
  setupUi(optionsWidget());
  setWindowTitle(tr("Purchase Order Items by Vendor"));
  setListLabel(tr("Purchase Order Items"));
  setReportName("POLineItemsByVendor");
  setMetaSQLOptions("poItems", "detail");
  setUseAltId(true);

  connect(_vendor, SIGNAL(updated()), this, SLOT(sPopulatePo()));
  connect(_searchFor, SIGNAL(textChanged(const QString&)), this, SLOT(sSearch(const QString&)));
  connect(_next, SIGNAL(clicked()), this, SLOT(sSearchNext()));

  _agent->setText(omfgThis->username());

  list()->addColumn(tr("P/O #"),       _orderColumn, Qt::AlignRight,  true,  "pohead_number"  );
  list()->addColumn(tr("Site"),        _whsColumn,   Qt::AlignCenter, true,  "warehous_code"  );
  list()->addColumn(tr("Status"),      _dateColumn,  Qt::AlignCenter, true,  "poitem_status" );
  list()->addColumn(tr("Vendor"),      _itemColumn,  Qt::AlignLeft,   true,  "vend_name"   );
  list()->addColumn(tr("Due Date"),    _dateColumn,  Qt::AlignCenter, true,  "poitem_duedate" );
  list()->addColumn(tr("Item Number"), _itemColumn,  Qt::AlignLeft,   true,  "itemnumber"   );
  list()->addColumn(tr("Description"), -1,           Qt::AlignLeft,   true,  "itemdescrip"   );
  list()->addColumn(tr("Vend. Item #"), _itemColumn, Qt::AlignLeft,   true,  "poitem_vend_item_number");
  list()->addColumn(tr("UOM"),         _uomColumn,   Qt::AlignCenter, true,  "itemuom" );
  list()->addColumn(tr("Vend. UOM"),   _uomColumn,   Qt::AlignCenter, true,  "poitem_vend_uom" );
  list()->addColumn(tr("Ordered"),     _qtyColumn,   Qt::AlignRight,  true,  "poitem_qty_ordered"  );
  list()->addColumn(tr("Received"),    _qtyColumn,   Qt::AlignRight,  true,  "poitem_qty_received"  );
  list()->addColumn(tr("Returned"),    _qtyColumn,   Qt::AlignRight,  true,  "poitem_qty_returned"  );

  _vendor->setFocus();
}
示例#18
0
/*
 * Parse (define-library ...) form into given environment, with the
 * following format:
 *
 * (define-library <library name>
 *   <library declaration> ...)
 *
 * where <library declaration> is any of:
 *
 * - (export <export spec> ...)
 * - (import <import set> ...)
 * - (begin <command or definition> ...)
 * - (include <filename1> <filename2> ...)
 * - (include-ci <filename1> <filename2> ...)
 * - (cond-expand <cond-expand clause> ...)
 */
static library_t* define_library(cons_t* p, const char* file)
{
  library_t *r = new library_t();
  cons_t *exports = nil();

  // find current dir for resolving include and include-ci
  std::string curdir = sdirname(file);

  // define-library
  if ( symbol_name(caar(p)) != "define-library" )
    raise(syntax_error(format(
      "Imported file does not begin with define-library: %s", file)));

  // <library name>
  r->name = verify_library_name(cadar(p));

  // A <library declaration> can be either ...
  for ( p = cdr(cdar(p)); !nullp(p); p = cdr(p) ) {
    cons_t *id   = caar(p);
    cons_t *body = cdar(p);
    std::string s = symbol_name(id);

    if ( s == "export" ) {
      exports = body;
      continue;
    }

    if ( s == "import" ) {
      // TODO: Make sure that proc_import does not override
      //       r->internals->outer
      proc_import(body, r->internals);
      continue;
    }

    if ( s == "begin" ) {
      eval(car(p), r->internals);
      continue;
    }

    if ( s == "include" ) {
      eval(splice(list(symbol("begin")),
                  include(body, r->internals, curdir.c_str())),
           r->internals);
      continue;
    }

    if ( s == "include-ci" ) {
      eval(splice(list(symbol("begin")),
                  include_ci(body, r->internals, curdir.c_str())),
           r->internals);
      continue;
    }

    if ( s == "cond-expand" ) {
      eval(cond_expand(body, r->internals), r->internals);
      continue;
    }
  }

  // copy exports into exports-environemnt
  for ( p = exports; !nullp(p); p = cdr(p) ) {

    // handle renaming
    if ( listp(car(p)) && length(car(p))==3 &&
         symbol_name(caar(p))=="rename" )
    {
      assert_type(SYMBOL, cadar(p));
      assert_type(SYMBOL, caddar(p));

      std::string internal_name = symbol_name(cadar(p));
      std::string external_name = symbol_name(caddar(p));

      r->exports->define(external_name,
                         r->internals->lookup(internal_name));
    } else if ( listp(car(p)) )
      raise(syntax_error("(export <spec> ...) only allows (rename x y)"));
    else if ( type_of(car(p)) == SYMBOL ) {
      r->exports->define(symbol_name(car(p)),
                         r->internals->lookup(symbol_name(car(p))));
    } else
      raise(syntax_error(
        "(export <spec> ...) requires <spec> to be "
        "either an identifier or a pair of them."));
  }

  return r;
}
示例#19
0
void dspPoItemsByVendor::sSearchNext()
{
  QString target = _searchFor->text();
  int i;
  int currentIndex = list()->indexOfTopLevelItem(list()->currentItem()) + 1;
  if(currentIndex < 0 || currentIndex > list()->topLevelItemCount())
    currentIndex = 0;
  for (i = currentIndex; i < list()->topLevelItemCount(); i++)
  {
    if ( list()->topLevelItem(i)->text(list()->column("itemnumber")).startsWith(target, Qt::CaseInsensitive) ||
         list()->topLevelItem(i)->text(list()->column("itemdescrip")).contains(target, Qt::CaseInsensitive) ||
         list()->topLevelItem(i)->text(list()->column("poitem_vend_item_number")).startsWith(target, Qt::CaseInsensitive) )
      break;
  }

  if (i < list()->topLevelItemCount())
  {
    list()->setCurrentItem(list()->topLevelItem(i));
    list()->scrollToItem(list()->topLevelItem(i));
  }
}
示例#20
0
dspCountTagsBase::dspCountTagsBase(QWidget* parent, const char* name, Qt::WFlags fl)
  : display(parent, name, fl)
{
  setupUi(optionsWidget());
  setListLabel(tr("Count Tags"));
  setMetaSQLOptions("countTags", "detail");

  _dates->setStartNull(tr("Earliest"), omfgThis->startOfTime(), true);
  _dates->setEndNull(tr("Latest"), omfgThis->endOfTime(), true);

  list()->addColumn(tr("Tag #"),               -1, Qt::AlignLeft,  true, "invcnt_tagnumber");
  list()->addColumn(tr("Site"),        _whsColumn, Qt::AlignCenter,true, "warehous_code");
  list()->addColumn(tr("Item"),       _itemColumn, Qt::AlignLeft,  true, "item_number");
  list()->addColumn(tr("Created"),    _dateColumn, Qt::AlignCenter,true, "invcnt_tagdate");
  list()->addColumn(tr("Created By"), _dateColumn, Qt::AlignCenter,true, "creator");
  list()->addColumn(tr("Entered"),    _dateColumn, Qt::AlignCenter,true, "invcnt_cntdate");
  list()->addColumn(tr("Entered By"), _dateColumn, Qt::AlignCenter,true, "counter");
  list()->addColumn(tr("Posted"),     _dateColumn, Qt::AlignCenter,true, "invcnt_postdate");
  list()->addColumn(tr("Posted By"),  _dateColumn, Qt::AlignCenter,true, "poster");
  list()->addColumn(tr("QOH Before"),  _qtyColumn, Qt::AlignRight, true, "qohbefore");
  list()->addColumn(tr("Qty. Counted"),_qtyColumn, Qt::AlignRight, true, "invcnt_qoh_after");
  list()->addColumn(tr("Variance"),    _qtyColumn, Qt::AlignRight, true, "variance");
  list()->addColumn(tr("%"),         _prcntColumn, Qt::AlignRight, true, "percent");

  if (_preferences->boolean("XCheckBox/forgetful"))
    _showUnposted->setChecked(true);
  
  sFillList();
}
示例#21
0
文件: pcpd.c 项目: zixia/nospam
static int doline(struct PCP *pcp, char *p, int acl_flags)
{
	char *q=strtok(p, " ");

	if (!q)
	{
		printf("500 Syntax error\n");
		return (0);
	}

	if (strcasecmp(q, "QUIT") == 0)
	{
		printf("200 Bye.\n");
		return (-1);
	}

	if (strcasecmp(q, "NOOP") == 0)
	{
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "CAPABILITY") == 0)
	{
		printf("100-ACL\n");
		printf("100 PCP1\n");
		return (0);
	}

	if (strcasecmp(q, "LIST") == 0)
	{
		if (check_acl(acl_flags, PCP_ACL_LIST))
			return (0);

		if (list(pcp))
			printf("500 Syntax error\n");
		return (0);
	}

	if (strcasecmp(q, "RETR") == 0)
	{
		if (check_acl(acl_flags, PCP_ACL_RETR))
			return (0);

		if (retr(pcp))
			printf("500 Syntax error\n");
		return (0);
	}


	if (strcasecmp(q, "ACL") == 0 && pcp_has_acl(pcp) && !proxy_userid)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "SET") == 0)
		{
			const char *who=strtok(NULL, " ");

			if (who)
			{
				int flags=0;

				while ((q=strtok(NULL, " ")) != 0)
					flags |= pcp_acl_num(q);

				if (pcp_acl(pcp, who, flags))
				{
					error(0);
					return (0);
				}
				printf("200 Ok\n");
				return (0);
			}
		}
		else if (q && strcasecmp(q, "LIST") == 0)
		{
			listacls(pcp);
			return (0);
		}
	}

	if (strcasecmp(q, "RSET") == 0)
	{
		conflict_flag=0;
		force_flag=0;
		need_rset=0;
		rset(pcp);
		printf("200 Ok.\n");	
		return (0);
	}

	if (need_rset)
	{
		printf("500 RSET required - calendar in an unknown state.\n");
		return (0);
	}

	if (strcasecmp(q, "DELETE") == 0)
	{
		struct PCP_retr r;
		const char *event_id_list[2];

		char *e=strtok(NULL, " ");

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		if (e && deleted_eventid == NULL && new_eventid == NULL)
		{
			if ((deleted_eventid=strdup(e)) == NULL)
			{
				perror("strdup");
				exit(1);
			}
			proxy_list_rset();
			memset(&r, 0, sizeof(r));
			r.callback_retr_participants=open_event_participant;
			event_id_list[0]=deleted_eventid;
			event_id_list[1]=NULL;
			r.event_id_list=event_id_list;
			if (pcp_retr(pcp, &r))
			{
				error(r.errcode);
				proxy_list_rset();
			}
			else
				printf("200 Ok.\n");
			return (0);
		}
	}

	if (strcasecmp(q, "NEW") == 0 && new_eventid == NULL)
	{
		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		new_eventid=readnewevent(pcp);

		if (new_eventid == NULL)
		{
			printf("500 %s\n", strerror(errno));
		}
		else
			printf("109 %s ready to be commited.\n",
			       new_eventid->eventid);
		return (0);
	}

	if (strcasecmp(q, "BOOK") == 0 && new_eventid)
	{
		dobook(pcp);
		return (0);
	}

	if (strcasecmp(q, "CONFLICT") == 0)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "ON") == 0)
		{
			if (check_acl(acl_flags, PCP_ACL_CONFLICT))
				return (0);

			conflict_flag=1;
		}
		else
			conflict_flag=0;
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "FORCE") == 0)
	{
		q=strtok(NULL, " ");
		if (q && strcasecmp(q, "ON") == 0)
		{
			force_flag=1;
		}
		else
			force_flag=0;
		printf("200 Ok.\n");
		return (0);
	}

	if (strcasecmp(q, "COMMIT") == 0)
	{
		if (notbooked)
		{
			printf("500 BOOK required.\n");
		}
		else if (new_eventid && new_commit_times)
		{
			struct proxy_list *pl;

			new_commit.add_conflict_callback=NULL;
			new_commit.add_conflict_callback_ptr=NULL;

			new_commit.flags=
				(conflict_flag ? PCP_OK_CONFLICT:0) |
				(force_flag ? PCP_OK_PROXY_ERRORS:0);

			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (pl->flags & PROXY_IGNORE)
					continue;

				if (pl->flags & PROXY_NEW)
				{
					if (pcp_commit(pl->proxy,
						       pl->newevent,
						       &new_commit))
					{
						syslog(LOG_CRIT,
						       "COMMIT failed for PROXY %s",
						       pl->userid);

						if (!force_flag)
						{
							pl->flags &=
								~PROXY_NEW;
							error(new_commit
							      .errcode);
							return (0);
						}
					}
				}
				else if (pl->old_event_id)
				{
					struct PCP_delete del;

					memset(&del, 0, sizeof(del));

					del.id=pl->old_event_id;

					if (pcp_delete(pl->proxy, &del))
					{
						syslog(LOG_CRIT,
						       "DELETE failed for PROXY %s",
						       pl->userid);
						if (!force_flag)
						{
							error(del.errcode);
							return (0);
						}
						pl->flags |= PROXY_IGNORE;
					}
				}
			}

			if (proxy_userid)
				new_commit.flags |= PCP_BYPROXY;

			if (pcp_commit(pcp, new_eventid, &new_commit))
				error(new_commit.errcode);
			else
			{
				const char *proxy_name=NULL;
				const char *proxy_action=NULL;

				for (pl=proxy_list; pl; pl=pl->next)
				{
					if (proxy_name)
						printf("111-%s %s\n",
						       proxy_action,
						       proxy_name);

					proxy_action=
						!(pl->flags & PROXY_IGNORE)
						&& (pl->flags & PROXY_NEW)
						? "NEW":"DELETE";
					proxy_name=pl->userid;
				}

				if (proxy_name)
					printf("111 %s %s\n",
					       proxy_action,
					       proxy_name);
				else
					printf("200 Ok.\n");
			}	
			rset(pcp);
			return (0);
		}
		else if (!new_eventid && deleted_eventid)
		{
			struct proxy_list *pl;
			struct PCP_delete del;
			const char *proxy_userid;

			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (pl->flags & PROXY_IGNORE)
					continue;

				if (pl->old_event_id)
				{
					memset(&del, 0, sizeof(del));
					del.id=pl->old_event_id;

					if (pcp_delete(pl->proxy, &del))
					{
						syslog(LOG_CRIT,
						       "DELETE failed for PROXY %s",
						       pl->userid);
					}
				}
			}

			memset(&del, 0, sizeof(del));
			del.id=deleted_eventid;

			if (pcp_delete(pcp, &del))
			{
				if (del.errcode != PCP_ERR_EVENTNOTFOUND)
				{
					error(del.errcode);
					return (0);
				}
			}

			proxy_userid=NULL;
			for (pl=proxy_list; pl; pl=pl->next)
			{
				if (proxy_userid)
					printf("111-DELETE %s\n",
					       proxy_userid);

				proxy_userid=pl->userid;
			}

			if (proxy_userid)
				printf("111 DELETE %s\n", proxy_userid);
			else
				printf("200 Ok\n");

			rset(pcp);
			return (0);
		}

		printf("500 There's nothing to commit.\n");
		return (0);
	}

	if (strcasecmp(q, "CANCEL") == 0)
	{
		int errcode;

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		q=strtok(NULL, " ");
		if (!q)
			printf("500 Syntax error\n");
		else if (pcp_cancel(pcp, q, &errcode))
			error(errcode);
		else
			printf("200 Cancelled\n");
		return (0);
	}

	if (strcasecmp(q, "UNCANCEL") == 0)
	{
		struct PCP_uncancel unc;
		struct uncancel_list *list=NULL, **tail= &list;
		struct uncancel_list *p;

		if (check_acl(acl_flags, PCP_ACL_MODIFY))
			return (0);

		memset(&unc, 0, sizeof(unc));
		unc.uncancel_conflict_callback=uncancel_callback;
		unc.uncancel_conflict_callback_ptr=&tail;

		q=strtok(NULL, " ");
		if (!q)
			printf("500 Syntax error\n");
		else if (pcp_uncancel(pcp, q,
				      (conflict_flag ? PCP_OK_CONFLICT:0)|
				      (force_flag ? PCP_OK_PROXY_ERRORS:0),
				      &unc))
		{
			if (unc.errcode == PCP_ERR_CONFLICT && list)
			{
				for (p=list; p; p=p->next)
				{
					char from_buf[15];
					char to_buf[15];

					pcp_gmtimestr(p->from, from_buf);
					pcp_gmtimestr(p->to, to_buf);

					printf("403%c%s %s %s %s conflicts.\n",
					       p->next ? '-':' ',
					       p->addr,
					       from_buf,
					       to_buf,
					       p->id);
				}
			}
			else
				error(unc.errcode);
		}
		else
			printf("200 Uncancelled\n");

		while((p=list) != NULL)
		{
			list=p->next;
			free(p->addr);
			free(p->id);
			free(p);
		}
		return (0);
	}

	printf("500 Syntax error\n");
	return (0);
}
示例#22
0
UMLSceneSize ClassifierWidget::minimumSize()
{
    if (!m_pObject) {
        return UMLWidget::minimumSize();
    }
    if (classifier()->isInterface() && m_drawAsCircle) {
        return calculateAsCircleSize();
    }

    const QFontMetrics &fm = getFontMetrics(UMLWidget::FT_NORMAL);
    const int fontHeight = fm.lineSpacing();
    // width is the width of the longest 'word'
    int width = 0, height = 0;

    // consider stereotype
    if (m_showStereotype && !m_pObject->stereotype().isEmpty()) {
        height += fontHeight;
        // ... width
        const QFontMetrics &bfm = UMLWidget::getFontMetrics(UMLWidget::FT_BOLD);
        const int stereoWidth = bfm.size(0,m_pObject->stereotype(true)).width();
        if (stereoWidth > width)
            width = stereoWidth;
    }

    // consider name
    height += fontHeight;
    // ... width
    QString displayedName;
    if (m_showPackage)
        displayedName = m_pObject->fullyQualifiedName();
    else
        displayedName = m_pObject->name();
    const UMLWidget::FontType nft = (m_pObject->isAbstract() ? FT_BOLD_ITALIC : FT_BOLD);
    const int nameWidth = UMLWidget::getFontMetrics(nft).size(0,displayedName).width();
    if (nameWidth > width)
        width = nameWidth;

    // consider attributes
    const int numAtts = displayedAttributes();
    if (numAtts == 0) {
        height += fontHeight / 2;  // no atts, so just add a bit of space
    } else {
        height += fontHeight * numAtts;
        // calculate width of the attributes
        UMLClassifierListItemList list = classifier()->getFilteredList(UMLObject::ot_Attribute);
        foreach (UMLClassifierListItem *a , list ) {
            if (m_showPublicOnly && a->visibility() != Uml::Visibility::Public)
                continue;
            const int attWidth = fm.size(0,a->toString(m_ShowAttSigs)).width();
            if (attWidth > width)
                width = attWidth;
        }
    }

    // consider operations
    const int numOps = displayedOperations();
    if (numOps == 0) {
        height += fontHeight / 2;  // no ops, so just add a bit of space
    } else {
        height += numOps * fontHeight;
        // ... width
        UMLOperationList list(classifier()->getOpList());
        foreach (UMLOperation* op ,  list) {
                  if (m_showPublicOnly && op->visibility() != Uml::Visibility::Public)
                continue;
            const QString displayedOp = op->toString(m_ShowOpSigs);
            UMLWidget::FontType oft;
            oft = (op->isAbstract() ? UMLWidget::FT_ITALIC : UMLWidget::FT_NORMAL);
            const int w = UMLWidget::getFontMetrics(oft).size(0,displayedOp).width();
            if (w > width)
                width = w;
        }
    }

    // consider template box _as last_ !
    QSize templatesBoxSize = calculateTemplatesBoxSize();
    if (templatesBoxSize.width() != 0) {
        // add width to largest 'word'
        width += templatesBoxSize.width() / 2;
    }
    if (templatesBoxSize.height() != 0) {
        height += templatesBoxSize.height() - MARGIN;
    }


    // allow for height margin
    if (!m_showOperations && !m_showAttributes && !m_showStereotype) {
        height += MARGIN * 2;
    }

    // allow for width margin
    width += MARGIN * 2;

    return UMLSceneSize(width, height);
}
示例#23
0
文件: xar.c 项目: Merturbation/xar
int main(int argc, char *argv[]) {
	int ret;
	char *filename = NULL;
	char command = 0, c;
	char **args;
	const char *tocfile = NULL;
	int arglen, i, err;
	xar_t x;
	int loptind = 0;
	int required_dash_f = 0;  /* This release requires us to use -f */
	struct lnode *tmp;
	long int longtmp;
	struct option o[] = { 
		{"toc-cksum", 1, 0, 1},
		{"dump-toc", 1, 0, 'd'},
		{"compression", 1, 0, 2},
		{"list-subdocs", 0, 0, 3},
		{"help", 0, 0, 'h'},
		{"version", 0, 0, 4},
		{"dump-header", 0, 0, 5},
		{"extract-subdoc", 1, 0, 6},
		{"exclude", 1, 0, 7},
		{"rsize", 1, 0, 8},
		{"coalesce-heap", 0, 0, 9},
		{"link-same", 0, 0, 10},
		{"no-compress", 1, 0, 11},
		{"prop-include", 1, 0, 12},
		{"prop-exclude", 1, 0, 13},
		{"distribution", 0, 0, 14},
		{"keep-existing", 0, 0, 15},
		{"keep-setuid", 0, 0, 16},
		{"compression-args", 1, 0, 17},
		{ 0, 0, 0, 0}
	};

	if( argc < 2 ) {
		usage(argv[0]);
		exit(1);
	}

	while( (c = getopt_long(argc, argv, "axcC:vtjzf:hpPln:s:d:vk", o, &loptind)) != -1 ) {
		switch(c) {
		case  1 : if( !optarg ) {
		          	usage(argv[0]);
		          	exit(1);
		          }
		          if( (strcmp(optarg, XAR_OPT_VAL_NONE) != 0) &&
		              (strcmp(optarg, XAR_OPT_VAL_SHA1) != 0) &&
		              (strcmp(optarg, XAR_OPT_VAL_MD5)  != 0) ) {
		          	usage(argv[0]);
		          	exit(1);
		          }
		          Toccksum = optarg;
		
		          break;
		case  2 : if( !optarg ) {
		          	usage(argv[0]);
		          	exit(1);
		          }
		          if( (strcmp(optarg, XAR_OPT_VAL_NONE) != 0) &&
		              (strcmp(optarg, XAR_OPT_VAL_GZIP) != 0)
#ifdef HAVE_LIBBZ2
		              && (strcmp(optarg, XAR_OPT_VAL_BZIP) != 0)
#endif
#ifdef HAVE_LIBLZMA
		              && (strcmp(optarg, XAR_OPT_VAL_LZMA) != 0)
#endif
#ifdef HAVE_XZ
		              && (strcmp(optarg, XAR_OPT_VAL_XZ) != 0)
#endif
                    ) {
                    fprintf(stderr, "This instance of xar doesn't understand compression type %s\n", optarg);
		          	usage(argv[0]);
		          	exit(1);
		          }
		          Compression = optarg;
		          break;
		case  3 : if( command && (command != 3) ) {
		          	fprintf(stderr, "Conflicting commands specified\n");
				exit(1);
		          }
			  command = 3;
			  break;
		case  4 : print_version();
		          exit(0);
		case 'd':
			if( !optarg ) {
				usage(argv[0]);
				exit(1);
			}
			tocfile = optarg;
			command = 'd';
			break;
		case  5 : command = 5;
		          break;
		case  6 :
			SubdocName = optarg;
			asprintf(&Subdoc, "%s.xml", SubdocName);
			if( !command )
				command = 6;
			break;
		case  7 :
			tmp = malloc(sizeof(struct lnode));
			tmp->str = optarg;
			tmp->next = NULL;
			err = regcomp(&tmp->reg, tmp->str, REG_NOSUB);
			if( err ) {
				char errstr[1024];
				regerror(err, &tmp->reg, errstr, sizeof(errstr));
				printf("Error with regular expression %s: %s\n", tmp->str, errstr);
				exit(1);
			}
			if( Exclude == NULL ) {
				Exclude = tmp;
				Exclude_Tail = tmp;
			} else {
				Exclude_Tail->next = tmp;
				Exclude_Tail = tmp;
			}
			break;
		case  8 :
			if ( !optarg ) {
				usage(argv[0]);
				exit(1);
			}
			longtmp = strtol(optarg, NULL, 10);
			if( (((longtmp == LONG_MIN) || (longtmp == LONG_MAX)) && (errno == ERANGE)) || (longtmp < 1) ) {
				fprintf(stderr, "Invalid rsize value: %s\n", optarg);
				exit(5);
			}
			Rsize = optarg;
			break;
		case  9 : Coalesce = 1; break;
		case 10 : LinkSame = 1; break;
		case 11 :
			tmp = malloc(sizeof(struct lnode));
			tmp->str = optarg;
			tmp->next = NULL;
			err = regcomp(&tmp->reg, tmp->str, REG_NOSUB);
			if( err ) {
				char errstr[1024];
				regerror(err, &tmp->reg, errstr, sizeof(errstr));
				printf("Error with regular expression %s: %s\n", tmp->str, errstr);
				exit(1);
			}
			if( NoCompress == NULL ) {
				NoCompress = tmp;
				NoCompress_Tail = tmp;
			} else {
				NoCompress_Tail->next = tmp;
				NoCompress_Tail = tmp;
			}
			break;
		case 12 :
			tmp = malloc(sizeof(struct lnode));
			tmp->str = optarg;
			tmp->next = NULL;
			if( PropInclude == NULL ) {
				PropInclude = tmp;
				PropInclude_Tail = tmp;
			} else {
				PropInclude_Tail->next = tmp;
				PropInclude_Tail = tmp;
			}
			break;
		case 13 :
			tmp = malloc(sizeof(struct lnode));
			tmp->str = optarg;
			tmp->next = NULL;
			if( PropExclude == NULL ) {
				PropExclude = tmp;
				PropExclude_Tail = tmp;
			} else {
				PropExclude_Tail->next = tmp;
				PropExclude_Tail = tmp;
			}
			break;
		case 14 :
		{
			char *props[] = { "type", "data", "mode", "name" };
			int i;
			for( i = 0; i < 4; i++ ) {
				tmp = malloc(sizeof(struct lnode));
				tmp->str = strdup(props[i]);
				tmp->next = NULL;
				if( PropInclude == NULL ) {
					PropInclude = tmp;
					PropInclude_Tail = tmp;
				} else {
					PropInclude_Tail->next = tmp;
					PropInclude_Tail = tmp;
				}
			}
		}
			break;
		case 'k':
		case 15 :
			NoOverwrite++;
			break;
		case 16 :
			SaveSuid++;
			break;
		case 17 :
			CompressionArg = optarg;
			break;
		case 'C': if( !optarg ) {
		          	usage(argv[0]);
		          	exit(1);
		          }
		          Chdir = optarg;
		          break;
		case 'c':
		case 'x':
		case 't':
			if( command && (command != 's') ) {
				usage(argv[0]);
				fprintf(stderr, "Conflicting command flags: %c and %c specified\n", c, command);
				exit(1);
			}
			if( c == 't' )
				List = 1;
			command = c;
			break;
		case 'a':
			Compression = "lzma";
			break;
		case 'j':
			Compression = "bzip2";
			break;
		case 'z':
			Compression = "gzip";
			break;
		case 'f':
		        required_dash_f = 1;
			filename = optarg;
			break;
		case 'p':
			Perms = SYMBOLIC;
			break;
		case 'P':
			Perms = NUMERIC;
			break;
		case 'l':
			Local = 1;
			break;
		case 'n':
			SubdocName = optarg;
			break;
		case 's':
			Subdoc = optarg;
			if( !command )
				command = 's';
			break;
		case 'v':
			Verbose++;
			break;
		case 'h':
		default:
			usage(argv[0]);
			exit(1);
		}
	}

	if (! required_dash_f)	{
		usage(argv[0]);
		fprintf(stderr, "\n -f option is REQUIRED\n");
		exit(1);
	}

	switch(command) {
		case  5 : 
		        return dump_header(filename);
		case  3 : 
			return list_subdocs(filename);
		case 'c':
			if( optind == argc ) {
				usage(argv[0]);
				fprintf(stderr, "No files to operate on.\n");
				exit(1);
			}
			arglen = argc - optind;
			args = malloc(sizeof(char*) * (arglen+1));
			memset(args, 0, sizeof(char*) * (arglen+1));
			for( i = 0; i < arglen; i++ )
				args[i] = strdup(argv[optind + i]);

			return archive(filename, arglen, args);
		case 'd':
			if( !tocfile ) {
				usage(argv[0]);
				exit(1);
			}
			return dumptoc(filename, tocfile);
		case 'x':
			arglen = argc - optind;
			args = malloc(sizeof(char*) * (arglen+1));
			for( i = 0; i < arglen; i++ )
				args[i] = strdup(argv[optind + i]);
			args[i] = NULL;
			return extract(filename, arglen, args);
		case 't':
			arglen = argc - optind;
			args = calloc(sizeof(char*) * (arglen+1),1);
			for( i = 0; i < arglen; i++ )
				args[i] = strdup(argv[optind + i]);
			ret = list(filename, arglen, args);
			for( i = 0; i < arglen; i++ )
				free(args[i]);
		case  6 :
		case 's':
			x = xar_open(filename, READ);
			if( !x ) {
				fprintf(stderr, "Error opening xar archive: %s\n", filename);
				exit(1);
			}
			xar_register_errhandler(x, err_callback, NULL);
			extract_subdoc(x, SubdocName);
			xar_close(x);
			exit(Err);
			break;
		default:
			usage(argv[0]);
			fprintf(stderr, "Unrecognized command.\n");
			exit(1);
	}

	/* unreached */
	exit(0);
}
示例#24
0
文件: gfgroup.c 项目: ddk50/gfarm_v2
int
main(int argc, char *argv[])
{
	gfarm_error_t e;
	char op = OP_GROUPNAME, *groupname;
	int c;
	const char *path = ".";
	char *realpath = NULL;

	e = gfarm_initialize(&argc, &argv);
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: gfarm_initialize: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}

	while ((c = getopt(argc, argv, "P:cdlm?")) != -1) {
		switch (c) {
		case 'P':
			path = optarg;
			break;
		case OP_CREATE_GROUP:
		case OP_DELETE_GROUP:
		case OP_MODIFY_GROUP:
		case OP_LIST_LONG:
			op = c;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (gfarm_realpath_by_gfarm2fs(path, &realpath) == GFARM_ERR_NO_ERROR)
		path = realpath;
	if ((e = gfm_client_connection_and_process_acquire_by_path(path,
	    &gfm_server)) != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: metadata server for \"%s\": %s\n",
		    program_name, path, gfarm_error_string(e));
		exit(1);
	}
	free(realpath);

	switch (op) {
	case OP_GROUPNAME:
	case OP_LIST_LONG:
		if (argc == 0)
			e = list_all(op);
		else
			e = list(op, argc, argv);
		break;
	case OP_CREATE_GROUP:
	case OP_MODIFY_GROUP:
		if (argc < 1)
			usage();
		groupname = *argv++;
		--argc;
		e = create_group(op, groupname, argc, argv);
		break;
	case OP_DELETE_GROUP:
		if (argc != 1)
			usage();
		e = delete_group(*argv);
		break;
	}
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}

	gfm_client_connection_free(gfm_server);

	e = gfarm_terminate();
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: gfarm_terminate: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}
	exit(0);
}
void dspGLTransactions::sViewDocument()
{
  XSqlQuery dspViewDocument;
  XTreeWidgetItem * item = (XTreeWidgetItem*)list()->currentItem();
  if(0 == item)
    return;

  ParameterList params;
  if(item->rawValue("gltrans_doctype").toString() == "VO")
  {
    dspViewDocument.prepare("SELECT vohead_id, vohead_misc"
              "  FROM vohead"
              " WHERE (vohead_number=:vohead_number)");
    dspViewDocument.bindValue(":vohead_number", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("vohead_id", dspViewDocument.value("vohead_id").toInt());
    params.append("mode", "view");
    
    if(dspViewDocument.value("vohead_misc").toBool())
    {
      miscVoucher *newdlg = new miscVoucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }
    else
    {
      voucher *newdlg = new voucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }

  }
  else if(item->rawValue("gltrans_doctype").toString() == "IN")
  {
    dspViewDocument.prepare("SELECT invchead_id"
              "  FROM invchead"
              " WHERE (invchead_invcnumber=:invchead_invcnumber)");
    dspViewDocument.bindValue(":invchead_invcnumber", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    invoice::viewInvoice(dspViewDocument.value("invchead_id").toInt());
  }
  else if(item->rawValue("gltrans_doctype").toString() == "PO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    dspViewDocument.prepare("SELECT pohead_id"
              "  FROM pohead"
              " WHERE (pohead_number=:docnumber)");
    dspViewDocument.bindValue(":docnumber", docnumber[0]);
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("pohead_id", dspViewDocument.value("pohead_id").toInt());
    params.append("mode", "view");

    purchaseOrder *newdlg = new purchaseOrder();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if(item->rawValue("gltrans_doctype").toString() == "SH")
  {
    dspViewDocument.prepare("SELECT shiphead_id"
              "  FROM shiphead"
              " WHERE (shiphead_number=:shiphead_number)");
    dspViewDocument.bindValue(":shiphead_number", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("shiphead_id", dspViewDocument.value("shiphead_id").toInt());

    dspShipmentsByShipment *newdlg = new dspShipmentsByShipment();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if( (item->rawValue("gltrans_doctype").toString() == "CM") || (item->rawValue("gltrans_doctype").toString() == "DM") )
  {
    if(item->rawValue("gltrans_source").toString() == "A/P")
    {
      dspViewDocument.prepare("SELECT apopen_id"
                "  FROM apopen"
                " WHERE ( (apopen_docnumber=:docnumber) "
                "  AND (apopen_journalnumber=:journalnumber)"
                "  AND (apopen_doctype IN ('C', 'D')) );");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.bindValue(":journalnumber", item->rawValue("gltrans_journalnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("apopen_id", dspViewDocument.value("apopen_id").toInt());
      apOpenItem newdlg(this, "", TRUE);
      newdlg.set(params);
      newdlg.exec();
    }
    else if(item->rawValue("gltrans_source").toString() == "A/R")
    {
      dspViewDocument.prepare("SELECT aropen_id"
                "  FROM aropen"
                " WHERE ((aropen_docnumber=:docnumber) "
                "  AND (aropen_doctype IN ('C', 'D')) );");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("aropen_id", dspViewDocument.value("aropen_id").toInt());
      arOpenItem newdlg(this, "", TRUE);
      newdlg.set(params);
      newdlg.exec();
    }
    else if(item->rawValue("gltrans_source").toString() == "S/O")
    {
      dspViewDocument.prepare("SELECT cmhead_id"
                "  FROM cmhead"
                " WHERE (cmhead_number=:docnumber);");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("cmhead_id", dspViewDocument.value("cmhead_id").toInt());
      creditMemo *newdlg = new creditMemo();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }
  }
  else if(item->rawValue("gltrans_doctype").toString() == "SO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    dspViewDocument.prepare("SELECT cohead_id"
              "  FROM cohead"
              " WHERE (cohead_number=:docnumber)");
    dspViewDocument.bindValue(":docnumber", docnumber[0]);
    dspViewDocument.exec();
    if(dspViewDocument.first())
      salesOrder::viewSalesOrder(dspViewDocument.value("cohead_id").toInt());
  }
  else if(item->rawValue("gltrans_doctype").toString() == "WO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    params.append("wo_number", docnumber[0]);

    dspWoHistoryByNumber *newdlg = new dspWoHistoryByNumber();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if(item->rawValue("gltrans_source").toString() == "I/M")
  {
    dspViewDocument.prepare("SELECT gltrans_misc_id"
              "  FROM gltrans"
              " WHERE (gltrans_id=:gltrans_id)");
    dspViewDocument.bindValue(":gltrans_id", item->id());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("mode", "view");
    params.append("invhist_id", dspViewDocument.value("gltrans_misc_id").toInt());

    transactionInformation newdlg(this, "", TRUE);
    newdlg.set(params);
    newdlg.exec();
  }
}
示例#26
0
文件: init.c 项目: 29decibel/golang
void
fninit(NodeList *n)
{
	int i;
	Node *gatevar;
	Node *a, *b, *fn;
	NodeList *r;
	uint32 h;
	Sym *s, *initsym;

	if(debug['A']) {
		// sys.go or unsafe.go during compiler build
		return;
	}

	n = initfix(n);
	if(!anyinit(n))
		return;

	r = nil;

	// (1)
	snprint(namebuf, sizeof(namebuf), "initdone·");
	gatevar = newname(lookup(namebuf));
	addvar(gatevar, types[TUINT8], PEXTERN);

	// (2)
	maxarg = 0;
	snprint(namebuf, sizeof(namebuf), "init");

	fn = nod(ODCLFUNC, N, N);
	initsym = lookup(namebuf);
	fn->nname = newname(initsym);
	fn->nname->defn = fn;
	fn->nname->ntype = nod(OTFUNC, N, N);
	declare(fn->nname, PFUNC);
	funchdr(fn);

	// (3)
	a = nod(OIF, N, N);
	a->ntest = nod(ONE, gatevar, nodintconst(0));
	r = list(r, a);

	// (4)
	b = nod(OIF, N, N);
	b->ntest = nod(OEQ, gatevar, nodintconst(2));
	b->nbody = list1(nod(ORETURN, N, N));
	a->nbody = list1(b);

	// (5)
	b = syslook("throwinit", 0);
	b = nod(OCALL, b, N);
	a->nbody = list(a->nbody, b);

	// (6)
	a = nod(OAS, gatevar, nodintconst(1));
	r = list(r, a);

	// (7)
	for(h=0; h<NHASH; h++)
	for(s = hash[h]; s != S; s = s->link) {
		if(s->name[0] != 'i' || strcmp(s->name, "init") != 0)
			continue;
		if(s->def == N)
			continue;
		if(s == initsym)
			continue;

		// could check that it is fn of no args/returns
		a = nod(OCALL, s->def, N);
		r = list(r, a);
	}

	// (8)
	r = concat(r, n);

	// (9)
	// could check that it is fn of no args/returns
	for(i=1;; i++) {
		snprint(namebuf, sizeof(namebuf), "init·%d", i);
		s = lookup(namebuf);
		if(s->def == N)
			break;
		a = nod(OCALL, s->def, N);
		r = list(r, a);
	}

	// (10)
	a = nod(OAS, gatevar, nodintconst(2));
	r = list(r, a);

	// (11)
	a = nod(ORETURN, N, N);
	r = list(r, a);
	exportsym(fn->nname);

	fn->nbody = r;
	funcbody(fn);

	curfn = fn;
	typecheck(&fn, Etop);
	typechecklist(r, Etop);
	curfn = nil;
	funccompile(fn, 0);
}
示例#27
0
void dspSubLedger::sViewDocument()
{
  XTreeWidgetItem * item = (XTreeWidgetItem*)list()->currentItem();
  if(0 == item)
    return;

  ParameterList params;
  if(item->rawValue("sltrans_doctype").toString() == "VO")
  {
    q.prepare("SELECT vohead_id, vohead_misc"
              "  FROM vohead"
              " WHERE (vohead_number=:vohead_number)");
    q.bindValue(":vohead_number", item->rawValue("docnumber").toString());
    q.exec();
    if(!q.first())
      return;

    params.append("vohead_id", q.value("vohead_id").toInt());
    params.append("mode", "view");
    
    if(q.value("vohead_misc").toBool())
    {
      miscVoucher *newdlg = new miscVoucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg);
    }
    else
    {
      voucher *newdlg = new voucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg);
    }

  }
  else if(item->rawValue("sltrans_doctype").toString() == "IN")
  {
    q.prepare("SELECT invchead_id"
              "  FROM invchead"
              " WHERE (invchead_invcnumber=:invchead_invcnumber)");
    q.bindValue(":invchead_invcnumber", item->rawValue("docnumber").toString());
    q.exec();
    if(!q.first())
      return;

    invoice::viewInvoice(q.value("invchead_id").toInt());
  }
  else if(item->rawValue("sltrans_doctype").toString() == "PO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    q.prepare("SELECT pohead_id"
              "  FROM pohead"
              " WHERE (pohead_number=:docnumber)");
    q.bindValue(":docnumber", docnumber[0]);
    q.exec();
    if(!q.first())
      return;

    params.append("pohead_id", q.value("pohead_id").toInt());
    params.append("mode", "view");

    purchaseOrder *newdlg = new purchaseOrder();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg);
  }
  else if(item->rawValue("sltrans_doctype").toString() == "SH")
  {
    q.prepare("SELECT shiphead_id"
              "  FROM shiphead"
              " WHERE (shiphead_number=:shiphead_number)");
    q.bindValue(":shiphead_number", item->rawValue("docnumber").toString());
    q.exec();
    if(!q.first())
      return;

    params.append("shiphead_id", q.value("shiphead_id").toInt());

    dspShipmentsByShipment *newdlg = new dspShipmentsByShipment();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg);
  }
  else if( (item->rawValue("sltrans_doctype").toString() == "CM") || (item->rawValue("sltrans_doctype").toString() == "DM") )
  {
    if(item->rawValue("sltrans_source").toString() == "A/P")
    {
      q.prepare("SELECT apopen_id"
                "  FROM apopen"
                " WHERE ((apopen_docnumber=:docnumber) "
                "  AND (apopen_doctype='C'));");
      q.bindValue(":docnumber", item->rawValue("docnumber").toString());
      q.exec();
      if(!q.first())
        return;

      params.append("mode", "view");
      params.append("apopen_id", q.value("apopen_id").toInt());
      apOpenItem newdlg(this, "", true);
      newdlg.set(params);
      newdlg.exec();
    }
    else if(item->rawValue("sltrans_source").toString() == "A/R")
    {
      q.prepare("SELECT aropen_id"
                "  FROM aropen"
                " WHERE ((aropen_docnumber=:docnumber) "
                "  AND (aropen_doctype='C'));");
      q.bindValue(":docnumber", item->rawValue("docnumber").toString());
      q.exec();
      if(!q.first())
        return;

      params.append("mode", "view");
      params.append("aropen_id", q.value("aropen_id").toInt());
      arOpenItem newdlg(this, "", true);
      newdlg.set(params);
      newdlg.exec();
    }
  }
  else if(item->rawValue("sltrans_doctype").toString() == "SO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    q.prepare("SELECT cohead_id"
              "  FROM cohead"
              " WHERE (cohead_number=:docnumber)");
    q.bindValue(":docnumber", docnumber[0]);
    q.exec();
    if(q.first())
      salesOrder::viewSalesOrder(q.value("cohead_id").toInt(), this);
  }
  else if(item->rawValue("sltrans_doctype").toString() == "WO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    params.append("wo_number", docnumber[0]);

    dspWoHistoryByNumber *newdlg = new dspWoHistoryByNumber();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg);
  }
  else if(item->rawValue("sltrans_source").toString() == "I/M")
  {
    q.prepare("SELECT sltrans_misc_id"
              "  FROM sltrans"
              " WHERE (sltrans_id=:sltrans_id)");
    q.bindValue(":sltrans_id", item->id());
    q.exec();
    if(!q.first())
      return;

    params.append("mode", "view");
    params.append("invhist_id", q.value("sltrans_misc_id").toInt());

    transactionInformation newdlg(this, "", true);
    newdlg.set(params);
    newdlg.exec();
  }
}
示例#28
0
文件: sh.c 项目: benhandanyan/shell
int sh( int argc, char **argv, char **envp ) {
	signal(SIGINT, sig_handle);
	signal(SIGTERM, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	char *prompt = calloc(PROMPTMAX, sizeof(char));
	char *commandline = calloc(MAX_CANON, sizeof(char));
	char *command, *arg, *aliashelp, *commandpath, *p, *pwd, *owd;
	/* Use these two save chars for strtok_r on command and alias commands*/
	char *command_save, *alias_save;
	char **args = calloc(MAXARGS, sizeof(char*));
	int uid, i, status, argsct, a, go = 1;
	int background, bg_pid = 0;
	struct passwd *password_entry;
	char *homedir;
	struct pathelement *pathlist, *history;
	struct aliaselement *aliases;
	const char sp[2] = " ";
	extern char **environ;
	glob_t globbuf;
	size_t glc;
	char **gl;
	pthread_t pt_warnload, pt_watchuser;
	
	/* for use with warnload */
	float load = 0.0;
	int load_thread = 1;
	
	/* for use with watchuser */
	static pthread_mutex_t user_lock = PTHREAD_MUTEX_INITIALIZER;
	int user_thread = 1;
	struct userarg *userargs;

	/* for use with file redirection */
	int fid;
	int file_redirect, error_redirect, input_redirect = 0;
	int noclobber = 0;

	/* for use with pipe */
	int ipc = 0;
	int ipc_err = 0;
	int pipefd[2];
	char **pipeargs = calloc(5, sizeof(char*));

	uid = getuid();
	password_entry = getpwuid(uid);               /* get passwd info */
	homedir = getenv("HOME");						/* get homedir */
     
	if ( (pwd = getcwd(NULL, PATH_MAX+1)) == NULL ) {
    	perror("getcwd");
    	exit(2);
	}
	
	owd = calloc(strlen(pwd) + 1, sizeof(char));
	memcpy(owd, pwd, strlen(pwd));
	prompt[0] = ' '; prompt[1] = '\0';

	/* Put PATH into a linked list */
	pathlist = get_path();

	/* By default, we have no history or aliases or users */
	history = NULL;
	aliases = NULL;
	userargs = NULL;

	while ( go ) {

		/* wait on background processes */
		bg_pid = waitpid(-1, &status, WNOHANG);
		if(bg_pid > 0) {
        	printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status));
		}

		/* print prompt */
		printf("\n");
    	printf(prompt);
    	printf(" [");
    	printf(pwd);
    	printf("]> ");

    	i = 0;

		/* get command line and process */
    	while (fgets(commandline, MAX_CANON, stdin) != NULL) {

			/* wait on background processes */
            bg_pid = waitpid(-1, &status, WNOHANG);
            if(bg_pid > 0) {
                printf("Background child [%d] exited with status: %d\n", bg_pid, WEXITSTATUS(status));
            }

			if (commandline[strlen(commandline) - 1] == '\n') {
				commandline[strlen(commandline) - 1] = 0;
			}

			/* Add the command to history */
			history = add_last(history, commandline);

			/* Get the command */	
			command = strtok_r(commandline, sp, &command_save);
			if(command == NULL) {
				break;
			}

			/* Search for aliases */
			a = 0;	
			struct aliaselement *alias = aliases;
			while(alias != NULL) {
				if(strcmp(command, alias->name) == 0) {
					a = 1;
					break;
				}
				alias = alias->next;
			}

			/* If we have an alias */
			i = 0;
			if(a) {
				/* parse alias command */
				arg = calloc(strlen(alias->command) + 1, sizeof(char));
				strcpy(arg, alias->command);
				aliashelp = strtok_r(arg, sp, &alias_save);
				while(aliashelp != NULL) {
					if(i == MAXARGS) {
						strcpy(args[0], "maxargs");
						break;
					}
					args[i] = calloc(strlen(aliashelp) + 1, sizeof(char));
					strcpy(args[i], aliashelp);
					aliashelp = strtok_r(NULL, sp, &alias_save);
					i++;
				}
				command = strtok_r(NULL, sp, &command_save);
				free(arg);
			} 

			/* parse command line or remainder of command line if we have an alias */
			while (command != NULL) {
	    		if(i == MAXARGS) {
					strcpy(args[0], "maxargs");
					break;
				}
	    		args[i] =  calloc(strlen(command) + 1, sizeof(char));
	   			strcpy(args[i], command);
	    		command = strtok_r(NULL, sp, &command_save);
	    		i++;
			}
			
			/* SANITY CHECK: make sure the user passed in something */
			if(args[0] == NULL) {
				break;
			}

			/* Expand wildcard characters */
			glob(args[0], GLOB_NOCHECK, NULL, &globbuf);
			i = 1;	
			while(args[i] != NULL) {
 				glob(args[i], GLOB_APPEND | GLOB_NOCHECK, NULL, &globbuf);
				i++;
			}
		
			/* gl becomes our arguments, it is the expanded version of args */
			gl = globbuf.gl_pathv;
			/* glc is the number of arguments. Use it for checking built in commands */
			glc = globbuf.gl_pathc;

			/* Check for background & at end of last argument */
			char* last_arg = gl[glc - 1];
			char last_char = last_arg[(strlen(last_arg) - 1)];
			if(strcmp(&last_char, "&") == 0) {
				last_arg[(strlen(last_arg) - 1)] = '\0';
				background = 1;
			}

			/* Check for file output redirection (without appending) */
			if(glc > 2 && (strcmp(gl[glc-2], ">") == 0 || strcmp(gl[glc-2], ">&") == 0)) {

				/* Don't overwrite an existing file if noclobber is set */
				if(noclobber) {
					if(access(gl[glc-1], F_OK) == 0) {
						fprintf(stderr, "%s: File exists.\n", gl[glc-1]);
						free_args(args);
						break;
					}
				}

				/* Redirect the output to given file */
				fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(1);
				dup(fid);
				
				/* Redirect error output to the given file */
				if(strcmp(gl[glc-2], ">&") == 0) {
					close(2);
					dup(fid);
					error_redirect = 1;
				}
				close(fid);
				file_redirect = 1;

				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for file output redirection (with appending) */
			if(glc > 2 && (strcmp(gl[glc-2], ">>") == 0 || strcmp(gl[glc-2], ">>&") == 0)) {
				
				/* Don't append to a file that doesn't exist */
				if(noclobber) {
					if(access(gl[glc-1], F_OK) != 0) {
						fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]);
						free_args(args);
						break;
					}
				}

				/* Redirect the output to given file */
				fid = open(gl[glc-1], O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(1);
				dup(fid);
		
				/* Redirect error output to the given file */
				if(strcmp(gl[glc-2], ">>&") == 0) {
					close(2);
					dup(fid);
					error_redirect = 1;
				}
				close(fid);
				file_redirect = 1;
			
				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for file input redirection */
			if(glc > 2 && strcmp(gl[glc-2], "<") == 0) {

				/* Can't take input from a nonexisistent file */
				if(access(gl[glc-1], F_OK) != 0) {
					fprintf(stderr, "%s: No such file or directory.\n", gl[glc-1]);
					free_args(args);
					break;
				}

				/* Open the file to read from */
				fid = open(gl[glc-1], O_RDONLY);
				if(fid == -1) {
					perror(gl[glc-1]);
					free_args(args);
					break;
				}
				close(0);
				dup(fid);
				close(fid);
				input_redirect = 1;

				/* Hide redirection character and filename */
				gl[glc-2] = '\0';
				gl[glc-1] = '\0';
				glc = glc - 2;
			}

			/* Check for inter-process communication */
			if(glc > 2 && (strcmp(gl[1], "|") == 0 || strcmp(gl[1], "|&") == 0)) {
				ipc = 1;
				if(strcmp(gl[1], "|&") == 0) {
					ipc_err = 1;
				}

				/* Create our pipe */
				if(pipe(pipefd) == -1) {
					perror("pipe");
					free_args(args);
					break;
				}

				/* Put the command to the right of the pipe in a second arguments list */
				i = 2;
				int p = 0;
				while(gl[i] != NULL) {
					pipeargs[p] = malloc(strlen(gl[i]) + 1 * sizeof(char));
					pipeargs[p] = gl[i];
					i++; p++;
				}
				gl[1] = '\0';
				glc = 1;
			}

    		/* check for each built in command and implement */

			/* Built in warnload */
			if(strcmp(gl[0], "warnload") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
				char *end;
				if(glc != 2) {
					printf("Usage: warnload LOAD\n");
				} else if (strcmp(gl[1], "0.0") != 0 && (strtof(gl[1], &end) == 0 || strtof(gl[1], &end) < 0)) {
					printf("LOAD must be a positive floating point number\n");
				} else if (strcmp(gl[1], "0.0") == 0) {
					load = 0.0;
					load_thread = 1;
				} else {
					load = strtof(gl[1], &end);
					if(load_thread != 0) {
						load_thread = 0;
						pthread_create(&pt_warnload, NULL, warnload, &load);
					}
				}
			}

			/* Built in watchuser */
			else if(strcmp(gl[0], "watchuser") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "watchuser: Too few arguements.\n");
				} else if(glc > 3) {
					fprintf(stderr, "watchuser: Too many arguments.\n");
				} else if (glc == 3 && strcmp(gl[2], "off") != 0) {
					printf("Usage: watchuser USERNAME [off]\n");
				} else if (glc == 3 && strcmp(gl[2], "off") == 0 ){

					/* remove the given username from watched users list */
					if(user_thread == 0) {
						pthread_mutex_lock(&user_lock);
						userargs->users = remove_user(userargs->users, gl[1]);
						pthread_mutex_unlock(&user_lock);
					} else {
						printf("No watched users have been added yet\n");
					}
				} else {
					
					/* Add the user to the list. Create the watchuser thread if it isn't already created */
					if(user_thread == 1) {
						user_thread = 0;
						userargs = calloc(1, sizeof(struct userarg));	
						userargs->lock = user_lock;
						userargs->users = add_user(NULL, gl[1]);
						pthread_create(&pt_watchuser, NULL, watchuser, userargs);
					} else {
						pthread_mutex_lock(&user_lock);
						userargs->users = add_user(userargs->users, gl[1]);
						pthread_mutex_unlock(&user_lock);
					}
				}
			}

			/* WATCHMAIL NOT IMPLEMENTED */
			else if(strcmp(gl[0], "watchmail") == 0) {
				printf("We were not able to implement watchmail as we could not figure out\nhow to correctly use pthread_cancel(3) to cancel threads\n");
			}

			/* Build in fg */
			else if(strcmp(gl[0], "fg") == 0) {
				printf("Executing build-in [%s]\n", gl[0]);
				/* No arguments, bring a default process into foreground */
				if(glc == 1) {
					kill(0, SIGCONT);
					wait(NULL);
				}
				/* One argument, bring the process with pid into foreground */
				else if(glc == 2) {
					if(atoi(gl[1])) {
						kill(atoi(gl[1]), SIGCONT);
						waitpid(atoi(gl[1]), NULL, 0);
					} else {
						fprintf(stderr, "pid must be an integer\n");
					}
				} else {
					fprintf(stderr, "Usage: fg [pid]\n");
				}
			}

			/* Built in list */
			else if(strcmp(gl[0], "list") == 0) {
	    		printf("Executing built-in [%s]\n", gl[0]);
	    		i = 1;
				/* No arguments, print the current working directory */
	    		if(glc < 2) {
	    			list(pwd);
	    		} else {
					/* list each of the arguments passed in */
	        		while(i < glc) {
	            		list(gl[i]);
		    			printf("\n");
		    			i++;
	        		}
	    		}
    		} 

			/* Built in exit */
			else if (strcmp(gl[0], "exit") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		go = 0;
	    		break;
			} 

			/* Built in prompt */
			else if (strcmp(gl[0], "prompt") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		if(glc < 2) {
					/* user didn't enter a prompt so request one */
					printf("input prompt prefix:");
					fgets(prompt, PROMPTMAX, stdin);
					if(prompt[strlen(prompt) - 1] == '\n') {
		    			prompt[strlen(prompt) - 1] = 0;
					}
	    		} else {
					/* set the prompt to be the first argument */
					strncpy(prompt, gl[1], PROMPTMAX);
	    		}
			} 

			/* Built in pwd */
			else if (strcmp(gl[0], "pwd") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		printf(pwd);
	    		printf("\n");
			} 
			
			/* Built in noclobber */
			else if (strcmp(gl[0], "noclobber") == 0){
				if(noclobber == 0) {
					noclobber = 1;
				} else {
					noclobber = 0;
				}
				printf("noclobber is set to %d\n", noclobber);
			}
			/* Built in pid */
			else if (strcmp(gl[0], "pid") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		printf("%d\n", getpid());
			} 

			/* Built in which */
			else if (strcmp(gl[0], "which") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "which: Too few arguments.\n");
				} else {
					i = 1;
					while(i < glc) {
						char *wh;
						/* call the which function which will check for the command in the path */
	    				wh = which(gl[i], pathlist);
						if(wh == NULL) { 
							fprintf(stderr, "%s: Command not found.\n", gl[i]);
						} else {
							printf("%s\n", wh);
						}
						free(wh);
						i++;
					}
				}	   
			} 

			/* Built in where */
			else if (strcmp(gl[0], "where") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "where: Too few arguments.\n");
				} else {
					i = 1;
					while(i < glc) {
						where(gl[i], pathlist);
						i++;
					}	
				} 
			}

			/* Built in cd */
			else if (strcmp(gl[0], "cd") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc > 2) {
					printf("cd: Too many arguments.\n");
				} else {
	    			char *tmp;	    
					/* tmp will be the new directory or NULL on failure */
	    			tmp = cd(gl[1], homedir, owd);
	    			if(tmp == NULL) {
						break;
	    			} else { 
						free(owd);
						/* set owd to be the old (previous) working directory */
						owd = pwd;
						/* set the new working directory */
						pwd = tmp;
	    			}    
	    			tmp = NULL;
				}
			} 

			/* Built in printenv */
			else if (strcmp(gl[0], "printenv") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
	    		if(glc > 2) {
					fprintf(stderr, "%s: Too many arguments.\n", gl[0]);
	    		} else if (glc > 1) { 
					/* print a particular environmental variable */
					char *tmp;
					tmp = getenv(gl[1]);
					if(tmp == NULL) {
						fprintf(stderr, "%s: Environmental variable not found.\n", gl[1]);
					} else {
						printf("%s\n", tmp);
					}
					tmp = NULL;
	    		} else {
					/* print all environmental variables */
	        		i = 0;
	        		while(environ[i] != NULL) {
		    			printf("%s\n", environ[i]);
		    			i++;
					}
	    		}
			} 

			/* Built in setenv */
			else if (strcmp(gl[0], "setenv") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc > 3) {
					fprintf(stderr, "%s: Too many arguments.\n", gl[0]);
				} else if (glc > 2) {
					/* set an environmental variable to the given value */
					setenv(gl[1], gl[2], 1);
				} else if (glc > 1) {
					/* set an environmental variable to an empty value */
					setenv(gl[1], "", 1);
				} else {
					/* print all environmental variables */
					i = 0;
					while(environ[i] != NULL) {
						printf("%s\n", environ[i]);
						i++;
					}
				}
				/* in case we update the home directory */
				homedir = getenv("HOME");
			} 

			/* Built in history */
			else if (strcmp(gl[0], "history") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				int n = 10;
				/* set how many history records to print */
				if(glc > 1 && atoi(gl[1]) != 0) {
					n = atoi(gl[1]);
				}
				struct pathelement *curr = history;
				/* loop and print past commands */
				while(curr != NULL && n > 0) {
					printf("%s\n", curr->element);
					curr = curr->next;
					n--;
				}
			} 

			/* Built in alias */
			else if (strcmp(gl[0], "alias") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					/* list all aliases */
					struct aliaselement *curr = aliases;
					while(curr != NULL) {
						printf("%s     %s\n", curr->name, curr->command);
						curr = curr->next;
					}
				} else if(glc < 3) {
					/* list a specific alias */
					struct aliaselement *curr = aliases;
					while(curr != NULL) {
						if(strcmp(gl[1], curr->name) == 0) {
							printf("%s\n", curr->command);
						}
						curr = curr->next;
					}
				} else {
					/* add an alias */
					char buf[MAX_CANON];
					snprintf(buf, MAX_CANON, "%s", gl[2]);
					i = 3;
					while(gl[i] != NULL && i < MAXARGS) {
						strcat(buf, " ");
						strcat(buf, gl[i]);
						i++;
					}
					aliases = add_alias(aliases, gl[1], buf);
				}
			} 

			/* Built in kill */
			else if (strcmp(gl[0], "kill") == 0) {
 	    		printf("Executing built-in [%s]\n", gl[0]);
				if(glc < 2) {
					fprintf(stderr, "kill: Too few arguments.\n");
				} else if(glc < 3 || strchr(gl[1], '-') == NULL) {
					/* default kill with SIGINT */
					i = 1;
					while(gl[i] != NULL) {
						kill_process(gl[i]);
						i++;
					}
				} else {
					/* kill with the given signal number */
					char *signal;
					signal = strtok(gl[1], "-");
					i = 2;
					while(gl[i] != NULL) {
						kill_process_signal(gl[i], signal);	
						i++;
					}
				}
			} 

			/* MAXARGS handler */
			else if (strcmp(gl[0], "maxargs") == 0) {
	    		fprintf(stderr, "Error: Too many arguments.\n");
			} 

			/* Absolute/Relative paths */
			else if (strncmp(gl[0], "/", 1) == 0 || strncmp(gl[0], "./", 2) == 0 || strncmp(gl[0], "../", 3) == 0) {
				if(access(gl[0], X_OK) == 0) {
					pid_t pid = fork();
					if(pid == -1) {
						perror("fork");
					} else if(pid == 0) {
						/* print what child is executing and execve it */
 	    				printf("Executing [%s]\n", gl[0]);
						
						/* If we are piping this is the command on the left, set standard output to the pipe output */
						if(ipc) {
							close(1);
							dup(pipefd[1]);
							if(ipc_err) {
								close(2);
								dup(pipefd[1]);
							}
							close(pipefd[0]);
							close(pipefd[1]);
						}

						execve(gl[0], gl, environ);
						/* on exec error */
						perror(gl[0]);
						exit(127);
					} else {
						/* if not a background process, wait */
						if(!background) {
							/* If we are piping this is the command on the right. Wait for the first command to finish */
							if(ipc) {
								waitpid(pid, &status, 0);
								pid_t pid2 = fork();
								if(pid2 == -1) {
									perror("fork");
								} else if (pid2 == 0) {
									/* Set stdin to be the pipe input */
									close(0);
									dup(pipefd[0]);
									close(pipefd[1]);
									close(pipefd[0]);
									
									/* Which command should we run */
									char* wh;
									wh = which(pipeargs[0], pathlist);
									if(wh == NULL) {
										fprintf(stderr, "%s: Command not found", pipeargs[0]);
									} else {
										execve(wh, pipeargs, environ);
									}
								} else {
									close(pipefd[0]);
									close(pipefd[1]);
								}
							} else {
								/* wait for chil process */
								waitpid(pid, &status, 0);
								/* if child exits with non-zero status print it */
								if(WEXITSTATUS(status) != 0) {
									printf("Exit: %d\n", WEXITSTATUS(status));
								}
							}
						}
					}
				} else {
					/* path doens't exist */
					fprintf(stderr,"%s: Command not found.\n", gl[0]);
				}
			} 

			/* Executable */
			else {
				char* wh;
				char* wh2;
				/* figure out which executable to execute */
				wh = which(gl[0], pathlist);
				if(wh == NULL) {
					fprintf(stderr, "%s: Command not found.\n", gl[0]);   
				} else {
					pid_t pid = fork();
					if(pid == -1) {
						perror("fork");
					} else if (pid == 0) {
						/* what we are executing */
 	    				printf("Executing [%s]\n", wh);

						/* If we are piping this is the command on the left, set standard output to be the pipe output*/
                        if(ipc) {
                            close(1);
                            dup(pipefd[1]);
							if(ipc_err) {
								close(2);
								dup(pipefd[1]);
							}
                            close(pipefd[0]);
                            close(pipefd[1]);
                        }

						execve(wh, gl, environ);
						/* on execve error */
						perror(wh);
						exit(127);
					} else {
						/* if not a background process, wait */
						if(!background) {

							/* If we are piping this is the command on the right, wait for command on left to finish */
							if(ipc) {
                                waitpid(pid, &status, 0);
                                pid_t pid2 = fork();
                                if(pid2 == -1) {
                                    perror("fork");
                                } else if (pid2 == 0) {
									/* Set standard input to be pipe input */
                                    close(0);
                                    dup(pipefd[0]);
                                    close(pipefd[1]);
                                    close(pipefd[0]);
									/* Which command should we run */
                                    wh2 = which(pipeargs[0], pathlist);
                                    if(wh2 == NULL) {
                                        fprintf(stderr, "%s: Command not found", pipeargs[0]);
                                    } else {
                                        execve(wh2, pipeargs, environ);
                                    }
                                } else {
                                    close(pipefd[0]);
                                    close(pipefd[1]);
                                }
							} else {
								/* wait for child */
								waitpid(pid, &status, 0);
								/* if child exits with nonzero value print it */
								if(WEXITSTATUS(status) != 0){
									printf("Exit: %d\n", WEXITSTATUS(status));
								}
							}
						}
					}
					free(wh);
				} 
    		}
		
			/* reset background */
			background = 0;

			/* reset glob */
			globfree(&globbuf);

			/* reset args */
			free_args(args);
			free_args(pipeargs);

			/* if we redirected file output, reset it to the screen */
			if(file_redirect == 1) {
				file_redirect = 0;
				fid = open("/dev/tty", O_WRONLY);
				close(1);
				dup(fid);
				if(error_redirect == 1) {
					error_redirect = 0;
					close(2);
					dup(fid);
				}
				close(fid);
			}

			/* if we redirected file input, reset it to the keyboard */
			if(input_redirect == 1) {
				input_redirect = 0;
				fid = open("/dev/tty", O_RDONLY);
				close(0);
				dup(fid);
				close(fid);
			}

			ipc = 0;
			ipc_err = 0;

			sleep(1);

			/* Print prompt again */
			printf(prompt);
			printf(" [");
			printf(pwd);
			printf("]> ");
    	}
	}

	/* free allocated memory */
	free(prompt);
	free(commandline);
	free_args(args);
	free_args(pipeargs);
	free(args);
	free(pipeargs);
	free(owd);
	free(pwd);
	struct pathelement *tmp;
	while(pathlist != NULL) {
    	tmp = pathlist->next;
    	free(pathlist);
    	pathlist = tmp;
	}
	while(history != NULL) {
		tmp = history->next;
		free(history->element);
		free(history);
		history = tmp;
	}
	struct aliaselement *temp;
	while(aliases != NULL) {
		temp = aliases->next;
		free(aliases->name);
		free(aliases->command);
		free(aliases);
		aliases = temp;
	}
	struct userelement *tem;
	while(userargs != NULL && userargs->users != NULL) {
		tem = userargs->users->next;
		free(userargs->users->username);
		free(userargs->users);
		userargs->users = tem;
	}
	if(userargs != NULL) {
		pthread_mutex_destroy(&userargs->lock);
		free(userargs);
	}
	globfree(&globbuf);

	return 0;
} /* sh() */
示例#29
0
bool OptionsDetailed::saveCustomProfile( bool lastUsed )
{
    if( wPlugin && currentPlugin )
    {
        QString profileName;
        if( lastUsed )
        {
            profileName = "soundkonverter_last_used";
        }
        else
        {
            bool ok;
            profileName = KInputDialog::getText( i18n("New profile"), i18n("Enter a name for the new profile:"), "", &ok );
            if( !ok )
                return false;
        }

        if( profileName.isEmpty() )
        {
            KMessageBox::information( this, i18n("You cannot save a profile without a name."), i18n("Profile name is empty") );
            return false;
        }

        QStringList profiles;
        profiles += i18n("Very low");
        profiles += i18n("Low");
        profiles += i18n("Medium");
        profiles += i18n("High");
        profiles += i18n("Very high");
        profiles += i18n("Lossless");
        profiles += i18n("Hybrid");
        profiles += i18n("Last used");
        profiles += "Last used";
        profiles += i18n("User defined");
        if( !lastUsed )
            profiles += "soundkonverter_last_used";

        if( profiles.contains(profileName) )
        {
            KMessageBox::information( this, i18n("You cannot overwrite the built-in profiles."), i18n("Profile already exists") );
            return false;
        }

        QDomDocument list("soundkonverter_profilelist");
        QDomElement root;
        bool profileFound = false;

        QFile listFile( KStandardDirs::locateLocal("data","soundkonverter/profiles.xml") );
        if( listFile.open( QIODevice::ReadOnly ) )
        {
            if( list.setContent( &listFile ) )
            {
                root = list.documentElement();
                if( root.nodeName() == "soundkonverter" && root.attribute("type") == "profilelist" )
                {
                    QDomNodeList conversionOptionsElements = root.elementsByTagName("conversionOptions");
                    for( int i=0; i<conversionOptionsElements.count(); i++ )
                    {
                        if( conversionOptionsElements.at(i).toElement().attribute("profileName") == profileName )
                        {
                            int ret;
                            if( lastUsed )
                                ret = KMessageBox::Yes;
                            else
                                ret = KMessageBox::questionYesNo( this, i18n("A profile with this name already exists.\n\nDo you want to overwrite the existing one?"), i18n("Profile already exists") );

                            if( ret == KMessageBox::Yes )
                            {
                                ConversionOptions *conversionOptions = currentConversionOptions( false );
                                delete config->data.profiles[profileName];
                                config->data.profiles[profileName] = conversionOptions;
                                root.removeChild(conversionOptionsElements.at(i));
                                QDomElement profileElement = conversionOptions->toXml(list);
                                profileElement.setAttribute("profileName",profileName);
                                root.appendChild(profileElement);
                                profileFound = true;
                                break;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
            }
            listFile.close();
        }

        if( listFile.open( QIODevice::WriteOnly ) )
        {
            if( list.childNodes().isEmpty() )
            {
                root = list.createElement("soundkonverter");
                root.setAttribute("type","profilelist");
                list.appendChild(root);
            }

            if( !profileFound )
            {
                ConversionOptions *conversionOptions = currentConversionOptions( false );
                config->data.profiles[profileName] = conversionOptions;
                QDomElement profileElement = conversionOptions->toXml(list);
                profileElement.setAttribute("profileName",profileName);
                root.appendChild(profileElement);
            }

            updateProfiles();
            emit customProfilesEdited();

            QTextStream stream(&listFile);
            stream << list.toString();
            listFile.close();

            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
示例#30
0
OBJECT_PTR id_to_mc_fn(reg_closure_t *cls, OBJECT_PTR val)
{
  return list(2, cls->closed_vals[0], val);
}