Exemplo n.º 1
0
static bool test_unsorted_table() {
    emit_test("Test UNSORTED_TOKENER_TABLE");

	MyString msg;

	for (size_t ii = 0; ii < TestTbl.cItems; ++ii) {
		const char * key = TestTbl.pTable[ii].key;
		const TestTableItem * tti = UnTestTbl.lookup(key);
		if ( ! tti) {
			emit_step_failure(__LINE__, msg.formatstr("lookup('%s') returned NULL", key));
			continue;
		}
		if (tti->id != TestTbl.pTable[ii].id) {
			emit_step_failure(__LINE__, msg.formatstr("lookup('%s') returned '%s'", key, tti->key));
		}

		tokener toke(key); toke.next();
		tti = UnTestTbl.lookup_token(toke);
		if ( ! tti) {
			emit_step_failure(__LINE__, msg.formatstr("lookup_token('%s') returned NULL", key));
			continue;
		}
		if (tti->id != TestTbl.pTable[ii].id) {
			emit_step_failure(__LINE__, msg.formatstr("lookup_token('%s') returned '%s'", key, tti->key));
		}
	}

	return REQUIRED_RESULT();
}
Exemplo n.º 2
0
static bool test_tokener_parse_regex() {
    emit_test("Test tokener regex parsing");

	MyString msg;
	int fl;
	std::string temp;
	tokener toke("/(.*)/i");

	REQUIRE(toke.next() && toke.is_regex());
	REQUIRE(toke.copy_regex(temp,fl) && temp=="(.*)");
	if (fl != 1) {
		emit_step_failure(__LINE__, msg.formatstr("toke.copy_regex() returned pcre_flags==%d, should be 1", fl));
	}

	toke.set(" /([\\d]*)/i ");
	REQUIRE(toke.next() && toke.is_regex());
	REQUIRE(toke.copy_regex(temp,fl) && temp=="([\\d]*)");
	if (fl != 1) {
		emit_step_failure(__LINE__, msg.formatstr("toke.copy_regex() returned pcre_flags==%d, should be 1", fl));
	}

	toke.set(" /^Now is the|Time$/ ");
	REQUIRE(toke.next() && toke.is_regex());
	REQUIRE(toke.copy_regex(temp,fl) && temp=="^Now is the|Time$");
	if (fl != 0) {
		emit_step_failure(__LINE__, msg.formatstr("toke.copy_regex() returned pcre_flags==%d, should be 1", fl));
	}

	return REQUIRED_RESULT();
}
Exemplo n.º 3
0
static bool test_nocase_sorted_table() {
    emit_test("Test NOCASE SORTED_TOKENER_TABLE");

	MyString msg;

	// test the case sensitive sorted table
	for (size_t ii = 0; ii < UnTestTbl.cItems; ++ii) {
		const char * key = UnTestTbl.pTable[ii].key;
		int id = UnTestTbl.pTable[ii].id;
		if (id == item_aaa) { id = item_AAA; } //  This table has only the AAA item, not the aaa item.
		const TestTableItem * tti = NcTestTbl.lookup(key);
		if ( ! tti) {
			emit_step_failure(__LINE__, msg.formatstr("lookup('%s') returned NULL", key));
			continue;
		}
		if (tti->id != id) {
			emit_step_failure(__LINE__, msg.formatstr("lookup('%s') returned '%s'", key, tti->key));
		}

		tokener toke(key); toke.next();
		tti = NcTestTbl.lookup_token(toke);
		if ( ! tti) {
			emit_step_failure(__LINE__, msg.formatstr("lookup_token('%s') returned NULL", key));
			continue;
		}
		if (tti->id != id) {
			emit_step_failure(__LINE__, msg.formatstr("lookup_token('%s') returned '%s'", key, tti->key));
		}
	}

	return REQUIRED_RESULT();
}
Exemplo n.º 4
0
int wxFileDialog::ShowModal()
{
    HWND hWnd = 0;
    if (m_parent) hWnd = (HWND) m_parent->GetHWND();
    if (!hWnd && wxTheApp->GetTopWindow())
        hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();

    static wxChar fileNameBuffer [ wxMAXPATH ];           // the file-name
    wxChar        titleBuffer    [ wxMAXFILE+1+wxMAXEXT ];  // the file-name, without path

    *fileNameBuffer = wxT('\0');
    *titleBuffer    = wxT('\0');

    long msw_flags = OFN_HIDEREADONLY;

    if ( HasFdFlag(wxFD_FILE_MUST_EXIST) )
        msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    /*
        If the window has been moved the programmer is probably
        trying to center or position it.  Thus we set the callback
        or hook function so that we can actually adjust the position.
        Without moving or centering the dlg, it will just stay
        in the upper left of the frame, it does not center
        automatically.
    */
    if (m_bMovedWindow || HasExtraControlCreator()) // we need these flags.
    {
        msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK;
#ifndef __WXWINCE__
        msw_flags |= OFN_ENABLESIZING;
#endif
    }

    if ( HasFdFlag(wxFD_MULTIPLE) )
    {
        // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
        msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
    }

    // if wxFD_CHANGE_DIR flag is not given we shouldn't change the CWD which the
    // standard dialog does by default (notice that under NT it does it anyhow,
    // OFN_NOCHANGEDIR or not, see below)
    if ( !HasFdFlag(wxFD_CHANGE_DIR) )
    {
        msw_flags |= OFN_NOCHANGEDIR;
    }

    if ( HasFdFlag(wxFD_OVERWRITE_PROMPT) )
    {
        msw_flags |= OFN_OVERWRITEPROMPT;
    }

    wxOPENFILENAME of;
    wxZeroMemory(of);

    of.lStructSize       = gs_ofStructSize;
    of.hwndOwner         = hWnd;
    of.lpstrTitle        = m_message.wx_str();
    of.lpstrFileTitle    = titleBuffer;
    of.nMaxFileTitle     = wxMAXFILE + 1 + wxMAXEXT;

#ifndef __WXWINCE__
    GlobalPtr hgbl;
    if ( HasExtraControlCreator() )
    {
        msw_flags |= OFN_ENABLETEMPLATEHANDLE;

        hgbl.Init(256, GMEM_ZEROINIT);
        GlobalPtrLock hgblLock(hgbl);
        LPDLGTEMPLATE lpdt = static_cast<LPDLGTEMPLATE>(hgblLock.Get());

        // Define a dialog box.

        lpdt->style = DS_CONTROL | WS_CHILD | WS_CLIPSIBLINGS;
        lpdt->cdit = 0;         // Number of controls
        lpdt->x = 0;
        lpdt->y = 0;

        // convert the size of the extra controls to the dialog units
        const wxSize extraSize = GetExtraControlSize();
        const LONG baseUnits = ::GetDialogBaseUnits();
        lpdt->cx = ::MulDiv(extraSize.x, 4, LOWORD(baseUnits));
        lpdt->cy = ::MulDiv(extraSize.y, 8, HIWORD(baseUnits));

        // after the DLGTEMPLATE there are 3 additional WORDs for dialog menu,
        // class and title, all three set to zeros.

        of.hInstance = (HINSTANCE)lpdt;
    }
#endif // __WXWINCE__

    // Convert forward slashes to backslashes (file selector doesn't like
    // forward slashes) and also squeeze multiple consecutive slashes into one
    // as it doesn't like two backslashes in a row neither

    wxString  dir;
    size_t    i, len = m_dir.length();
    dir.reserve(len);
    for ( i = 0; i < len; i++ )
    {
        wxChar ch = m_dir[i];
        switch ( ch )
        {
            case wxT('/'):
                // convert to backslash
                ch = wxT('\\');

                // fall through

            case wxT('\\'):
                while ( i < len - 1 )
                {
                    wxChar chNext = m_dir[i + 1];
                    if ( chNext != wxT('\\') && chNext != wxT('/') )
                        break;

                    // ignore the next one, unless it is at the start of a UNC path
                    if (i > 0)
                        i++;
                    else
                        break;
                }
                // fall through

            default:
                // normal char
                dir += ch;
        }
    }

    of.lpstrInitialDir   = dir.c_str();

    of.Flags             = msw_flags;
    of.lpfnHook          = wxFileDialogHookFunction;
    of.lCustData         = (LPARAM)this;

    wxArrayString wildDescriptions, wildFilters;

    size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, wildFilters);

    wxASSERT_MSG( items > 0 , wxT("empty wildcard list") );

    wxString filterBuffer;

    for (i = 0; i < items ; i++)
    {
        filterBuffer += wildDescriptions[i];
        filterBuffer += wxT("|");
        filterBuffer += wildFilters[i];
        filterBuffer += wxT("|");
    }

    // Replace | with \0
    for (i = 0; i < filterBuffer.length(); i++ ) {
        if ( filterBuffer.GetChar(i) == wxT('|') ) {
            filterBuffer[i] = wxT('\0');
        }
    }

    of.lpstrFilter  = (LPTSTR)filterBuffer.wx_str();
    of.nFilterIndex = m_filterIndex + 1;

    //=== Setting defaultFileName >>=========================================

    wxStrlcpy(fileNameBuffer, m_fileName.c_str(), WXSIZEOF(fileNameBuffer));

    of.lpstrFile = fileNameBuffer;  // holds returned filename
    of.nMaxFile  = wxMAXPATH;

    // we must set the default extension because otherwise Windows would check
    // for the existing of a wrong file with wxFD_OVERWRITE_PROMPT (i.e. if the
    // user types "foo" and the default extension is ".bar" we should force it
    // to check for "foo.bar" existence and not "foo")
    wxString defextBuffer; // we need it to be alive until GetSaveFileName()!
    if (HasFdFlag(wxFD_SAVE))
    {
        const wxChar* extension = filterBuffer.wx_str();
        int maxFilter = (int)(of.nFilterIndex*2L) - 1;

        for( int i = 0; i < maxFilter; i++ )           // get extension
            extension = extension + wxStrlen( extension ) + 1;

        // use dummy name a to avoid assert in AppendExtension
        defextBuffer = AppendExtension(wxT("a"), extension);
        if (defextBuffer.StartsWith(wxT("a.")))
        {
            defextBuffer = defextBuffer.Mid(2); // remove "a."
            of.lpstrDefExt = defextBuffer.c_str();
        }
    }

    // store off before the standard windows dialog can possibly change it
    const wxString cwdOrig = wxGetCwd();

    //== Execute FileDialog >>=================================================

    if ( !ShowCommFileDialog(&of, m_windowStyle) )
        return wxID_CANCEL;

    // GetOpenFileName will always change the current working directory on
    // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag
    // OFN_NOCHANGEDIR has no effect.  If the user did not specify
    // wxFD_CHANGE_DIR let's restore the current working directory to what it
    // was before the dialog was shown.
    if ( msw_flags & OFN_NOCHANGEDIR )
    {
        wxSetWorkingDirectory(cwdOrig);
    }

    m_fileNames.Empty();

    if ( ( HasFdFlag(wxFD_MULTIPLE) ) &&
#if defined(OFN_EXPLORER)
         ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') )
#else
         ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') )
#endif // OFN_EXPLORER
       )
    {
#if defined(OFN_EXPLORER)
        m_dir = fileNameBuffer;
        i = of.nFileOffset;
        m_fileName = &fileNameBuffer[i];
        m_fileNames.Add(m_fileName);
        i += m_fileName.length() + 1;

        while (fileNameBuffer[i] != wxT('\0'))
        {
            m_fileNames.Add(&fileNameBuffer[i]);
            i += wxStrlen(&fileNameBuffer[i]) + 1;
        }
#else
        wxStringTokenizer toke(fileNameBuffer, wxT(" \t\r\n"));
        m_dir = toke.GetNextToken();
        m_fileName = toke.GetNextToken();
        m_fileNames.Add(m_fileName);

        while (toke.HasMoreTokens())
            m_fileNames.Add(toke.GetNextToken());
#endif // OFN_EXPLORER

        wxString dir(m_dir);
        if ( m_dir.Last() != wxT('\\') )
            dir += wxT('\\');

        m_path = dir + m_fileName;
        m_filterIndex = (int)of.nFilterIndex - 1;
    }
    else
    {
        //=== Adding the correct extension >>=================================

        m_filterIndex = (int)of.nFilterIndex - 1;

        if ( !of.nFileExtension ||
             (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
        {
            // User has typed a filename without an extension:
            const wxChar* extension = filterBuffer.wx_str();
            int   maxFilter = (int)(of.nFilterIndex*2L) - 1;

            for( int i = 0; i < maxFilter; i++ )           // get extension
                extension = extension + wxStrlen( extension ) + 1;

            m_fileName = AppendExtension(fileNameBuffer, extension);
            wxStrlcpy(fileNameBuffer, m_fileName.c_str(), WXSIZEOF(fileNameBuffer));
        }

        m_path = fileNameBuffer;
        m_fileName = wxFileNameFromPath(fileNameBuffer);
        m_fileNames.Add(m_fileName);
        m_dir = wxPathOnly(fileNameBuffer);
        }

    return wxID_OK;

}
Exemplo n.º 5
0
// Read a stream a line at a time, and parse it to fill out the print mask,
// header, group_by, where expression, and projection attributes.
//
int SetAttrListPrintMaskFromStream (
	SimpleInputStream & stream, // in: fetch lines from this stream until nextline() returns NULL
	const CustomFormatFnTable & FnTable, // in: table of custom output functions for SELECT
	AttrListPrintMask & mask, // out: columns and headers set in SELECT
	printmask_headerfooter_t & headfoot, // out: header and footer flags set in SELECT or SUMMARY
	printmask_aggregation_t & aggregate, // out: aggregation mode in SELECT
	std::vector<GroupByKeyInfo> & group_by, // out: ordered set of attributes/expressions in GROUP BY
	std::string & where_expression, // out: classad expression from WHERE
	StringList & attrs, // out ClassAd attributes referenced in mask or group_by outputs
	std::string & error_message) // out, if return is non-zero, this will be an error message
{
	ClassAd ad; // so we can GetExprReferences
	enum section_t { NOWHERE=0, SELECT, SUMMARY, WHERE, GROUP};
	enum cust_t { PRINTAS_STRING, PRINTAS_INT, PRINTAS_FLOAT };

	bool label_fields = false;
	const char * labelsep = " = ";
	const char * prowpre = NULL;
	const char * pcolpre = " ";
	const char * pcolsux = NULL;
	const char * prowsux = "\n";
	mask.SetAutoSep(prowpre, pcolpre, pcolsux, prowsux);

	error_message.clear();
	aggregate = PR_NO_AGGREGATION;

	printmask_headerfooter_t usingHeadFoot = (printmask_headerfooter_t)(HF_CUSTOM | HF_NOSUMMARY);
	section_t sect = SELECT;
	tokener toke("");
	while (toke.set(stream.nextline())) {
		if ( ! toke.next())
			continue;

		if (toke.matches("#")) continue;

		if (toke.matches("SELECT"))	{
			while (toke.next()) {
				if (toke.matches("FROM")) {
					if (toke.next()) {
						if (toke.matches("AUTOCLUSTER")) {
							aggregate = PR_FROM_AUTOCLUSTER;
						} else {
							std::string aa; toke.copy_token(aa);
							formatstr_cat(error_message, "Warning: Unknown header argument %s for SELECT FROM\n", aa.c_str());
						}
					}
				} else if (toke.matches("UNIQUE")) {
					aggregate = PR_COUNT_UNIQUE;
				} else if (toke.matches("BARE")) {
					usingHeadFoot = HF_BARE;
				} else if (toke.matches("NOTITLE")) {
					usingHeadFoot = (printmask_headerfooter_t)(usingHeadFoot | HF_NOTITLE);
				} else if (toke.matches("NOHEADER")) {
					usingHeadFoot = (printmask_headerfooter_t)(usingHeadFoot | HF_NOHEADER);
				} else if (toke.matches("NOSUMMARY")) {
					usingHeadFoot = (printmask_headerfooter_t)(usingHeadFoot | HF_NOSUMMARY);
				} else if (toke.matches("LABEL")) {
					label_fields = true;
				} else if (label_fields && toke.matches("SEPARATOR")) {
					if (toke.next()) { std::string tmp; toke.copy_token(tmp); collapse_escapes(tmp); labelsep = mask.store(tmp.c_str()); }
				} else if (toke.matches("RECORDPREFIX")) {
					if (toke.next()) { std::string tmp; toke.copy_token(tmp); collapse_escapes(tmp); prowpre = mask.store(tmp.c_str()); }
				} else if (toke.matches("RECORDSUFFIX")) {
					if (toke.next()) { std::string tmp; toke.copy_token(tmp); collapse_escapes(tmp); prowsux = mask.store(tmp.c_str()); }
				} else if (toke.matches("FIELDPREFIX")) {
					if (toke.next()) { std::string tmp; toke.copy_token(tmp); collapse_escapes(tmp); pcolpre = mask.store(tmp.c_str()); }
				} else if (toke.matches("FIELDSUFFIX")) {
					if (toke.next()) { std::string tmp; toke.copy_token(tmp); collapse_escapes(tmp); pcolsux = mask.store(tmp.c_str()); }
				} else {
					std::string aa; toke.copy_token(aa);
					formatstr_cat(error_message, "Warning: Unknown header argument %s for SELECT\n", aa.c_str());
				}
			}
			mask.SetAutoSep(prowpre, pcolpre, pcolsux, prowsux);
			sect = SELECT;
			continue;
		} else if (toke.matches("WHERE")) {
			sect = WHERE;
			if ( ! toke.next()) continue;
		} else if (toke.matches("GROUP")) {
			sect = GROUP;
			if ( ! toke.next() || (toke.matches("BY") && ! toke.next())) continue;
		} else if (toke.matches("SUMMARY")) {
			usingHeadFoot = (printmask_headerfooter_t)(usingHeadFoot & ~HF_NOSUMMARY);
			while (toke.next()) {
				if (toke.matches("STANDARD")) {
					// attrs.insert(ATTR_JOB_STATUS);
				} else if (toke.matches("NONE")) {
					usingHeadFoot = (printmask_headerfooter_t)(usingHeadFoot | HF_NOSUMMARY);
				} else {
					std::string aa; toke.copy_token(aa);
					formatstr_cat(error_message, "Unknown argument %s for SELECT\n", aa.c_str());
				}
			}
			sect = SUMMARY;
			continue;
		}

		switch (sect) {
		case SELECT: {
			toke.mark();
			std::string attr;
			std::string name;
			int opts = FormatOptionAutoWidth | FormatOptionNoTruncate;
			const char * fmt = "%v";
			int wid = 0;
			CustomFormatFn cust;

			bool got_attr = false;
			while (toke.next()) {
				const Keyword * pkw = SelectKeywords.find_match(toke);
				if ( ! pkw)
					continue;

				// next token is a keyword, if we havent set the attribute yet
				// it's everything up to the current token.
				int kw = pkw->value;
				if ( ! got_attr) {
					toke.copy_marked(attr);
					got_attr = true;
				}

				switch (kw) {
				case kw_AS: {
					if (toke.next()) {
						toke.copy_token(name);
						if (toke.is_quoted_string()) { collapse_escapes(name); }
					} else {
						expected_token(error_message, "column name after AS", "SELECT", stream, toke);
					}
					toke.mark_after();
				} break;
				case kw_PRINTF: {
					if (toke.next()) {
						std::string val; toke.copy_token(val);
						fmt = mask.store(val.c_str());
					} else {
						expected_token(error_message, "format after PRINTF", "SELECT", stream, toke);
					}
				} break;
				case kw_PRINTAS: {
					if (toke.next()) {
						const CustomFormatFnTableItem * pcffi = FnTable.find_match(toke);
						if (pcffi) {
							cust = pcffi->cust;
							//cust_type = pcffi->cust;
							const char * pszz = pcffi->extra_attribs;
							if (pszz) {
								size_t cch = strlen(pszz);
								while (cch > 0) { attrs.insert(pszz); pszz += cch+1; cch = strlen(pszz); }
							}
						} else {
							std::string aa; toke.copy_token(aa);
							formatstr_cat(error_message, "Unknown argument %s for PRINTAS\n", aa.c_str());
						}
					} else {
						expected_token(error_message, "function name after PRINTAS", "SELECT", stream, toke);
					}
				} break;
				case kw_NOSUFFIX: {
					opts |= FormatOptionNoSuffix;
				} break;
				case kw_NOPREFIX: {
					opts |= FormatOptionNoPrefix;
				} break;
				case kw_LEFT: {
					opts |= FormatOptionLeftAlign;
				} break;
				case kw_RIGHT: {
					opts &= ~FormatOptionLeftAlign;
				} break;
				case kw_TRUNCATE: {
					opts &= ~FormatOptionNoTruncate;
				} break;
				case kw_WIDTH: {
					if (toke.next()) {
						std::string val; toke.copy_token(val);
						if (toke.matches("AUTO")) {
							opts |= FormatOptionAutoWidth;
						} else {
							wid = atoi(val.c_str());
							//if (wid) opts &= ~FormatOptionAutoWidth;
							//PRAGMA_REMIND("TJ: decide how LEFT & RIGHT interact with pos and neg widths."
						}
					} else {
						expected_token(error_message, "number or AUTO after WIDTH", "SELECT", stream, toke);
					}
				} break;
				default:
					unexpected_token(error_message, "SELECT", stream, toke);
				break;
				} // switch
			} // while

			if ( ! got_attr) { attr = toke.content(); }
			trim(attr);
			if (attr.empty() || attr[0] == '#') continue;

			const char * lbl = name.empty() ? attr.c_str() : name.c_str();
			if (label_fields) {
				// build a format string that contains the label
				std::string label(lbl);
				if (labelsep) { label += labelsep; }
				if (fmt) { label += fmt; } 
				else {
					label += "%";
					if (wid) {
						if (opts & FormatOptionNoTruncate)
							formatstr_cat(label, "%d", wid);
						else
							formatstr_cat(label, "%d.%d", wid, wid < 0 ? -wid : wid);
					}
					label += cust ? "s" : "v";
				}
				lbl = mask.store(label.c_str());
				fmt = lbl;
				wid = 0;
			} else {
				if ( ! wid) { wid = 0 - (int)strlen(lbl); }
				mask.set_heading(lbl);
				lbl = NULL;
			}
			if (cust) {
				mask.registerFormat (lbl, wid, opts, cust, attr.c_str());
			} else {
				mask.registerFormat(fmt, wid, opts, attr.c_str());
			}
			ad.GetExprReferences(attr.c_str(), NULL, &attrs);
		}
		break;

		case WHERE: {
			toke.copy_to_end(where_expression);
			trim(where_expression);
		}
		break;

		case SUMMARY: {
		}
		break;

		case GROUP: {
			toke.mark();
			GroupByKeyInfo key;

			// in case we end up finding no keywords, copy the remainder of the line now as the expression
			toke.copy_to_end(key.expr);
			bool got_expr = false;

			while (toke.next()) {
				const Keyword * pgw = GroupKeywords.find_match(toke);
				if ( ! pgw)
					continue;

				// got a keyword
				int gw = pgw->value;
				if ( ! got_expr) {
					toke.copy_marked(key.expr);
					got_expr = true;
				}

				switch (gw) {
				case gw_AS: {
					if (toke.next()) { toke.copy_token(key.name); }
					toke.mark_after();
				} break;
				case gw_DECENDING: {
					key.decending = true;
					toke.mark_after();
				} break;
				case gw_ASCENDING: {
					key.decending = false;
					toke.mark_after();
				} break;
				default:
					unexpected_token(error_message, "GROUP BY", stream, toke);
				break;
				} // switch
			} // while toke.next

			trim(key.expr);
			if (key.expr.empty() || key.expr[0] == '#')
				continue;

			if ( ! ad.GetExprReferences(key.expr.c_str(), NULL, &attrs)) {
				formatstr_cat(error_message, "GROUP BY expression is not valid: %s\n", key.expr.c_str());
			} else {
				group_by.push_back(key);
			}
		}
		break;

		default:
		break;
		}
	}

	headfoot = usingHeadFoot;

	return 0;
}
Exemplo n.º 6
0
int wxFileDialog::ShowModal()
{
    HWND hWnd = 0;
    if (m_parent) hWnd = (HWND) m_parent->GetHWND();
    if (!hWnd && wxTheApp->GetTopWindow())
        hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();

    static wxChar fileNameBuffer [ wxMAXPATH ];           // the file-name
    wxChar        titleBuffer    [ wxMAXFILE+1+wxMAXEXT ];  // the file-name, without path

    *fileNameBuffer = wxT('\0');
    *titleBuffer    = wxT('\0');

#if WXWIN_COMPATIBILITY_2_4
    long msw_flags = 0;
    if ( HasFdFlag(wxHIDE_READONLY) || HasFdFlag(wxFD_SAVE) )
        msw_flags |= OFN_HIDEREADONLY;
#else
    long msw_flags = OFN_HIDEREADONLY;
#endif

    if ( HasFdFlag(wxFD_FILE_MUST_EXIST) )
        msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    /*
        If the window has been moved the programmer is probably
        trying to center or position it.  Thus we set the callback
        or hook function so that we can actually adjust the position.
        Without moving or centering the dlg, it will just stay
        in the upper left of the frame, it does not center
        automatically.
    */
    if (m_bMovedWindow) // we need these flags.
    {
        msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK;
#ifndef __WXWINCE__
        msw_flags |= OFN_ENABLESIZING;
#endif
    }

    if ( HasFdFlag(wxFD_MULTIPLE) )
    {
        // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
        msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
    }

    // if wxFD_CHANGE_DIR flag is not given we shouldn't change the CWD which the
    // standard dialog does by default (notice that under NT it does it anyhow,
    // OFN_NOCHANGEDIR or not, see below)
    if ( !HasFdFlag(wxFD_CHANGE_DIR) )
    {
        msw_flags |= OFN_NOCHANGEDIR;
    }

    if ( HasFdFlag(wxFD_OVERWRITE_PROMPT) )
    {
        msw_flags |= OFN_OVERWRITEPROMPT;
    }

    wxOPENFILENAME of;
    wxZeroMemory(of);

    of.lStructSize       = gs_ofStructSize;
    of.hwndOwner         = hWnd;
    of.lpstrTitle        = WXSTRINGCAST m_message;
    of.lpstrFileTitle    = titleBuffer;
    of.nMaxFileTitle     = wxMAXFILE + 1 + wxMAXEXT;

    // Convert forward slashes to backslashes (file selector doesn't like
    // forward slashes) and also squeeze multiple consecutive slashes into one
    // as it doesn't like two backslashes in a row neither

    wxString  dir;
    size_t    i, len = m_dir.length();
    dir.reserve(len);
    for ( i = 0; i < len; i++ )
    {
        wxChar ch = m_dir[i];
        switch ( ch )
        {
            case _T('/'):
                // convert to backslash
                ch = _T('\\');

                // fall through

            case _T('\\'):
                while ( i < len - 1 )
                {
                    wxChar chNext = m_dir[i + 1];
                    if ( chNext != _T('\\') && chNext != _T('/') )
                        break;

                    // ignore the next one, unless it is at the start of a UNC path
                    if (i > 0)
                        i++;
                    else
                        break;
                }
                // fall through

            default:
                // normal char
                dir += ch;
        }
    }

    of.lpstrInitialDir   = dir.c_str();

    of.Flags             = msw_flags;
    of.lpfnHook          = wxFileDialogHookFunction;

    wxArrayString wildDescriptions, wildFilters;

    size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, wildFilters);

    wxASSERT_MSG( items > 0 , _T("empty wildcard list") );

    wxString filterBuffer;

    for (i = 0; i < items ; i++)
    {
        filterBuffer += wildDescriptions[i];
        filterBuffer += wxT("|");
        filterBuffer += wildFilters[i];
        filterBuffer += wxT("|");
    }

    // Replace | with \0
    for (i = 0; i < filterBuffer.length(); i++ ) {
        if ( filterBuffer.GetChar(i) == wxT('|') ) {
            filterBuffer[i] = wxT('\0');
        }
    }

    of.lpstrFilter  = (LPTSTR)filterBuffer.c_str();
    of.nFilterIndex = m_filterIndex + 1;

    //=== Setting defaultFileName >>=========================================

    wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
    fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');

    of.lpstrFile = fileNameBuffer;  // holds returned filename
    of.nMaxFile  = wxMAXPATH;

    // we must set the default extension because otherwise Windows would check
    // for the existing of a wrong file with wxFD_OVERWRITE_PROMPT (i.e. if the
    // user types "foo" and the default extension is ".bar" we should force it
    // to check for "foo.bar" existence and not "foo")
    wxString defextBuffer; // we need it to be alive until GetSaveFileName()!
    if (HasFdFlag(wxFD_SAVE))
    {
        const wxChar* extension = filterBuffer;
        int maxFilter = (int)(of.nFilterIndex*2L) - 1;

        for( int i = 0; i < maxFilter; i++ )           // get extension
            extension = extension + wxStrlen( extension ) + 1;

        // use dummy name a to avoid assert in AppendExtension
        defextBuffer = AppendExtension(wxT("a"), extension);
        if (defextBuffer.StartsWith(wxT("a.")))
        {
            defextBuffer = defextBuffer.Mid(2); // remove "a."
            of.lpstrDefExt = defextBuffer.c_str();
        }
    }

    // store off before the standard windows dialog can possibly change it
    const wxString cwdOrig = wxGetCwd();

    //== Execute FileDialog >>=================================================

    DWORD errCode;
    bool success = DoShowCommFileDialog(&of, m_windowStyle, &errCode);

#ifdef wxTRY_SMALLER_OPENFILENAME
    // the system might be too old to support the new version file dialog
    // boxes, try with the old size
    if ( !success && errCode == CDERR_STRUCTSIZE &&
            of.lStructSize != wxOPENFILENAME_V4_SIZE )
    {
        of.lStructSize = wxOPENFILENAME_V4_SIZE;

        success = DoShowCommFileDialog(&of, m_windowStyle, &errCode);

        if ( success || !errCode )
        {
            // use this struct size for subsequent dialogs
            gs_ofStructSize = of.lStructSize;
        }
    }
#endif // wxTRY_SMALLER_OPENFILENAME

    if ( success )
    {
        // GetOpenFileName will always change the current working directory on
        // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag
        // OFN_NOCHANGEDIR has no effect.  If the user did not specify
        // wxFD_CHANGE_DIR let's restore the current working directory to what it
        // was before the dialog was shown.
        if ( msw_flags & OFN_NOCHANGEDIR )
        {
            wxSetWorkingDirectory(cwdOrig);
        }

        m_fileNames.Empty();

        if ( ( HasFdFlag(wxFD_MULTIPLE) ) &&
#if defined(OFN_EXPLORER)
             ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') )
#else
             ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') )
#endif // OFN_EXPLORER
           )
        {
#if defined(OFN_EXPLORER)
            m_dir = fileNameBuffer;
            i = of.nFileOffset;
            m_fileName = &fileNameBuffer[i];
            m_fileNames.Add(m_fileName);
            i += m_fileName.length() + 1;

            while (fileNameBuffer[i] != wxT('\0'))
            {
                m_fileNames.Add(&fileNameBuffer[i]);
                i += wxStrlen(&fileNameBuffer[i]) + 1;
            }
#else
            wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n"));
            m_dir = toke.GetNextToken();
            m_fileName = toke.GetNextToken();
            m_fileNames.Add(m_fileName);

            while (toke.HasMoreTokens())
                m_fileNames.Add(toke.GetNextToken());
#endif // OFN_EXPLORER

            wxString dir(m_dir);
            if ( m_dir.Last() != _T('\\') )
                dir += _T('\\');

            m_path = dir + m_fileName;
            m_filterIndex = (int)of.nFilterIndex - 1;
        }
        else
        {
            //=== Adding the correct extension >>=================================

            m_filterIndex = (int)of.nFilterIndex - 1;

            if ( !of.nFileExtension ||
                 (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
            {
                // User has typed a filename without an extension:
                const wxChar* extension = filterBuffer;
                int   maxFilter = (int)(of.nFilterIndex*2L) - 1;

                for( int i = 0; i < maxFilter; i++ )           // get extension
                    extension = extension + wxStrlen( extension ) + 1;

                m_fileName = AppendExtension(fileNameBuffer, extension);
                wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.length(), wxMAXPATH-1));
                fileNameBuffer[wxMin(m_fileName.length(), wxMAXPATH-1)] = wxT('\0');
            }

            m_path = fileNameBuffer;
            m_fileName = wxFileNameFromPath(fileNameBuffer);
            m_fileNames.Add(m_fileName);
            m_dir = wxPathOnly(fileNameBuffer);
        }
    }
#ifdef __WXDEBUG__
    else
    {
        // common dialog failed - why?
        if ( errCode != 0 )
        {
            // this msg is only for developers so don't translate it
            wxLogError(wxT("Common dialog failed with error code %0lx."),
                       errCode);
        }
        //else: it was just cancelled
    }
#endif // __WXDEBUG__

    return success ? wxID_OK : wxID_CANCEL;

}
Exemplo n.º 7
0
int FileDialog::ShowModal()
{
   HWND hWnd = 0;
   if (m_parent) hWnd = (HWND) m_parent->GetHWND();
   if (!hWnd && wxTheApp->GetTopWindow())
      hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
   
   static wxChar fileNameBuffer [ wxMAXPATH ];           // the file-name
   wxChar        titleBuffer    [ wxMAXFILE+1+wxMAXEXT ];  // the file-name, without path
   
   *fileNameBuffer = wxT('\0');
   *titleBuffer    = wxT('\0');
   
#if WXWIN_COMPATIBILITY_2_4
   long msw_flags = 0;
   if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
      msw_flags |= OFN_HIDEREADONLY;
#else
   long msw_flags = OFN_HIDEREADONLY;
#endif
   
   if ( m_dialogStyle & wxFILE_MUST_EXIST )
      msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
   /*
    If the window has been moved the programmer is probably
    trying to center or position it.  Thus we set the callback
    or hook function so that we can actually adjust the position.
    Without moving or centering the dlg, it will just stay
    in the upper left of the frame, it does not center
    automatically..  One additional note, when the hook is
    enabled, the PLACES BAR in the dlg (shown on later versions
    of windows (2000 and XP) will automatically be turned off
    according to the MSDN docs.  This is normal.  If the
    programmer needs the PLACES BAR (left side of dlg) they
    just shouldn't move or center the dlg.
    */
   if (m_bMovedWindow) // we need these flags.
   {
      msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK;
#ifndef __WXWINCE__
      msw_flags |= OFN_ENABLESIZING;
#endif
   }
   
   if (m_dialogStyle & wxMULTIPLE )
   {
      // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
      msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
   }
   
   // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the
   // standard dialog does by default (notice that under NT it does it anyhow, 
   // OFN_NOCHANGEDIR or not, see below)
   if ( !(m_dialogStyle & wxCHANGE_DIR) )
   {
      msw_flags |= OFN_NOCHANGEDIR;
   }
   
   if ( m_dialogStyle & wxOVERWRITE_PROMPT )
   {
      msw_flags |= OFN_OVERWRITEPROMPT;
   }
   
   if ( m_dialogStyle & wxRESIZE_BORDER )
   {
      msw_flags |= OFN_ENABLESIZING;
   }
   
   if ( m_callback != NULL )
   {
      msw_flags |= OFN_SHOWHELP | OFN_EXPLORER | OFN_ENABLEHOOK;
   }
   
   // We always need EXPLORER and ENABLEHOOK to use our filtering code
   msw_flags |= OFN_EXPLORER | OFN_ENABLEHOOK;
   
   OPENFILENAME of;
   wxZeroMemory(of);
   
   // Allow Places bar to show on supported platforms
   if ( wxGetOsVersion() == wxWINDOWS_NT )
   {
      of.lStructSize       = sizeof(OPENFILENAME);
   }
   else
   {
      of.lStructSize       = OPENFILENAME_SIZE_VERSION_400;
   }
   
   of.hwndOwner         = hWnd;
   of.lpstrTitle        = WXSTRINGCAST m_message;
   of.lpstrFileTitle    = titleBuffer;
   of.nMaxFileTitle     = wxMAXFILE + 1 + wxMAXEXT;    // Windows 3.0 and 3.1
   of.lCustData         = (LPARAM) this;
   
   // Convert forward slashes to backslashes (file selector doesn't like
   // forward slashes) and also squeeze multiple consecutive slashes into one
   // as it doesn't like two backslashes in a row neither
   
   wxString  dir;
   size_t    i, len = m_dir.length();
   dir.reserve(len);
   for ( i = 0; i < len; i++ )
   {
      wxChar ch = m_dir[i];
      switch ( ch )
      {
         case _T('/'):
            // convert to backslash
            ch = _T('\\');
            
            // fall through
            
         case _T('\\'):
            while ( i < len - 1 )
            {
               wxChar chNext = m_dir[i + 1];
               if ( chNext != _T('\\') && chNext != _T('/') )
                  break;
               
               // ignore the next one, unless it is at the start of a UNC path
               if (i > 0)
                  i++;
               else
                  break;
            }
            // fall through
            
            default:
            // normal char
            dir += ch;
      }
   }
   
   of.lpstrInitialDir   = dir.c_str();
   
   of.Flags             = msw_flags;
   of.lpfnHook          = FileDialogHookFunction;
   
   wxArrayString wildDescriptions;
   
   size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, m_FilterGroups);
   
   wxASSERT_MSG( items > 0 , _T("empty wildcard list") );
   
   wxString filterBuffer;
   
   for (i = 0; i < items ; i++)
   {
      filterBuffer += wildDescriptions[i];
      filterBuffer += wxT("|");
      filterBuffer += wxT("*.*");
      filterBuffer += wxT("|");
   }
   
   // Replace | with \0
   for (i = 0; i < filterBuffer.Len(); i++ )
   {
      if ( filterBuffer.GetChar(i) == wxT('|') )
      {
         filterBuffer[i] = wxT('\0');
      }
   }
   
   of.lpstrFilter  = (LPTSTR)filterBuffer.c_str();
   of.nFilterIndex = m_filterIndex + 1;
   
   ParseFilter(of.nFilterIndex);
   
   //=== Setting defaultFileName >>=========================================
   
   wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
   fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
   
   of.lpstrFile = fileNameBuffer;  // holds returned filename
   of.nMaxFile  = wxMAXPATH;
   
   // we must set the default extension because otherwise Windows would check
   // for the existing of a wrong file with wxOVERWRITE_PROMPT (i.e. if the
   // user types "foo" and the default extension is ".bar" we should force it
   // to check for "foo.bar" existence and not "foo")
   wxString defextBuffer; // we need it to be alive until GetSaveFileName()!
   if (m_dialogStyle & wxSAVE && m_dialogStyle & wxOVERWRITE_PROMPT)
   {
      const wxChar* extension = filterBuffer;
      int maxFilter = (int)(of.nFilterIndex*2L) - 1;
      
      for( int i = 0; i < maxFilter; i++ )           // get extension
         extension = extension + wxStrlen( extension ) + 1;
      
      // use dummy name a to avoid assert in AppendExtension
      defextBuffer = AppendExtension(wxT("a"), extension);
      if (defextBuffer.StartsWith(wxT("a.")))
      {
         defextBuffer.Mid(2);
         of.lpstrDefExt = defextBuffer.c_str();
      }
   }
   
   // store off before the standard windows dialog can possibly change it 
   const wxString cwdOrig = wxGetCwd(); 
   
   //== Execute FileDialog >>=================================================
   
   bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of)
                   : GetOpenFileName(&of)) != 0;
   
#ifdef __WXWINCE__
   DWORD errCode = GetLastError();
#else
   DWORD errCode = CommDlgExtendedError();
   
   // GetOpenFileName will always change the current working directory on 
   // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag 
   // OFN_NOCHANGEDIR has no effect.  If the user did not specify wxCHANGE_DIR 
   // let's restore the current working directory to what it was before the 
   // dialog was shown (assuming this behavior extends to Windows Server 2003 
   // seems safe). 
   if ( success && 
       (msw_flags & OFN_NOCHANGEDIR) && 
       wxGetOsVersion() == wxWINDOWS_NT ) 
   { 
      wxSetWorkingDirectory(cwdOrig); 
   } 
   
#ifdef __WIN32__
   if (!success && (errCode == CDERR_STRUCTSIZE))
   {
      // The struct size has changed so try a smaller or bigger size
      
      int oldStructSize = of.lStructSize;
      of.lStructSize       = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
      success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
      : (GetOpenFileName(&of) != 0);
      errCode = CommDlgExtendedError();
      
      if (!success && (errCode == CDERR_STRUCTSIZE))
      {
         of.lStructSize       = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
         success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
         : (GetOpenFileName(&of) != 0);
      }
   }
#endif // __WIN32__
#endif // __WXWINCE__
   
   if ( success )
   {
      m_fileNames.Empty();
      
      if ( ( m_dialogStyle & wxMULTIPLE ) &&
#if defined(OFN_EXPLORER)
          ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') )
#else
          ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') )
#endif // OFN_EXPLORER
          )
      {
#if defined(OFN_EXPLORER)
         m_dir = fileNameBuffer;
         i = of.nFileOffset;
         m_fileName = &fileNameBuffer[i];
         m_fileNames.Add(m_fileName);
         i += m_fileName.Len() + 1;
         
         while (fileNameBuffer[i] != wxT('\0'))
         {
            m_fileNames.Add(&fileNameBuffer[i]);
            i += wxStrlen(&fileNameBuffer[i]) + 1;
         }
#else
         wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n"));
         m_dir = toke.GetNextToken();
         m_fileName = toke.GetNextToken();
         m_fileNames.Add(m_fileName);
         
         while (toke.HasMoreTokens())
            m_fileNames.Add(toke.GetNextToken());
#endif // OFN_EXPLORER
         
         wxString dir(m_dir);
         if ( m_dir.Last() != _T('\\') )
            dir += _T('\\');
         
         m_path = dir + m_fileName;
         m_filterIndex = (int)of.nFilterIndex - 1;
      }
      else
      {
         //=== Adding the correct extension >>=================================
         m_filterIndex = (int)of.nFilterIndex - 1;
         
#if 0
         // LLL:  Removed to prevent adding extension during Export
         //       processing.
         
         if ( !of.nFileExtension ||
             (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
         {
            // User has typed a filename without an extension:
            const wxChar* extension = filterBuffer;
            int   maxFilter = (int)(of.nFilterIndex*2L) - 1;
            
            for( int i = 0; i < maxFilter; i++ )           // get extension
               extension = extension + wxStrlen( extension ) + 1;
            
            m_fileName = AppendExtension(fileNameBuffer, extension);
            wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.Len(), wxMAXPATH-1));
            fileNameBuffer[wxMin(m_fileName.Len(), wxMAXPATH-1)] = wxT('\0');
         }
#endif
         m_path = fileNameBuffer;
         m_fileName = wxFileNameFromPath(fileNameBuffer);
         m_fileNames.Add(m_fileName);
         m_dir = wxPathOnly(fileNameBuffer);
      }
   }
   else
   {
      // common dialog failed - why?
#ifdef __WXDEBUG__
#ifdef __WXWINCE__
      if (errCode == 0)
      {
         // OK, user cancelled the dialog
      }
      else if (errCode == ERROR_INVALID_PARAMETER)
      {
         wxLogError(wxT("Invalid parameter passed to file dialog function."));
      }
      else if (errCode == ERROR_OUTOFMEMORY)
      {
         wxLogError(wxT("Out of memory when calling file dialog function."));
      }
      else if (errCode == ERROR_CALL_NOT_IMPLEMENTED)
      {
         wxLogError(wxT("Call not implemented when calling file dialog function."));
      }
      else
      {
         wxLogError(wxT("Unknown error %d when calling file dialog function."), errCode);
      }
#else
      DWORD dwErr = CommDlgExtendedError();
      if ( dwErr != 0 )
      {
         // this msg is only for developers
         wxLogError(wxT("Common dialog failed with error code %0lx."),
                    dwErr);
      }
      //else: it was just cancelled
#endif
#endif
   }
   
   return success ? wxID_OK : wxID_CANCEL;
   
}
Exemplo n.º 8
0
Arquivo: Shell.c Projeto: Lutes/McGill
int getcmd(char *prompt, char *args[], int *background){
	int length, i = 0;
	char *token, *loc;
	char *line;
	size_t linecap = 0;

	printf("%s", prompt);
	length = getline(&line, &linecap, stdin);
   
	if (length <= 0) {
        	exit(-1);
    	}
    	// Check if background is specified..
    	addHistory(line);
	printf("%s",history[1]);
    	if ((loc = index(line, '&')) != NULL) {
		*background = 1;
		*loc = ' ';
    		bh[c] = line;
		c++;
	
	}	 
	
	else
  	      *background = 0;

	char *temp = malloc(sizeof(line));
	strtok(line, "\n");
	strcpy (temp, line);

	while ((token = strsep(&temp, " \t\n")) != NULL) {
        	int j = 0;
		for (j < strlen(token); j++;)
            		if (token[j] <= 32)
                token[j] = '\0';
        	if (strlen(token) > 0)
            		args[i++] = token;
	    	args[i] = NULL;
	}

	free(temp);

	//if blank, place new prompt
	if (args[0] == NULL)
		return -1;

	//history command
	if (strcmp(args[0],"r") == 0){
        char *key = args[1];
	
	//If there is no history tell user
	if ((args[1] == NULL)&&(count == 2)){
		printf("You have yet to enter history, YOU FOOOL! \n");
		return  -1;
	}
	
	//if there is history and no args, run most recent
	if ((args[1] == NULL)&&(count != 2)){
		printf("run:%s", history[count - 2]);
		toke(args,history[count-2]);
	}

	//if there is an arg, cycle through 10 items.
	int i = 0;
        if (args[1]!= NULL){
		while ( (i < 10)&&((count - i)>0)){
        		if (key[0] == (history[count - i][0])){
				printf("run:%s", history[count-i]);
                		toke(args,history[(count-i)]);
                		break;
       			}
        	//if arg doesnt occur in array report
		if ((i == 9) || ((count - i == 1)))
                printf("No history match found, try again...");
        	
		i++;
        	}
     	}
	}    

	// change directory
	if (strcmp(args[0],"cd") == 0){
		
		//Checks for path
		if (args[1] == NULL){
			printf("no path specified \n");
			return -1;
		}
        	
		//Checks for too many args
        	if (args[2] != NULL){
			printf("Only one arg required \n");
			return -1;
		}
        	
		//Looks for real path
		if (chdir(args[1]) !=-1){ 
			return -1;
		}
		else {
			printf("Path failure");
			return -1;
		}	
	}

	//shows working dir
	if(strcmp(args[0], "pwd") == 0){
		//makes sure no args
		if (args[1] != NULL){
			printf("too may args");
			return -1;
		}
		
		printf("%s", getcwd(NULL, 0));	
	}

	//reads background processes and prints the ones that are running 
	if(strcmp(args[0],"jobs")==0){
		if(args[1] != NULL){
			printf("Too many args\n");
			return -1;
		}
		
		int offset = 0;
		int k = 0;
		int p = c;	
		
		//Checks for background procceses that are no longer running.
		while(k < p){

			if( 0 != (waitpid(bpid[k],0,WNOHANG))){ 
				int i = k;
				while (i < c){
					strcpy(bh[i] , bh[i + 1]);
                			bpid[i] = bpid[i+1];
					i++;
				}
				offset++;
			}	
			k++;
		}	
		c = c - offset;
	        	
		//Print running background jobs
		printf("# :: CMD  \n");
		int w = 0;
		while (w < c){ 
			printf("%d :: %s \n", w, bh[w]);	
			w++;	
		}


		return -1;
	}	
	
	//fg command
	if(strcmp(args[0],"fg") == 0){
		if ((args[1] == NULL)){
			printf("You need to enter an arg\n");
			return -1;
		}
		//wait for specified function
		int f = atoi(args[1]);
		waitpid(bpid[f], 0, NULL);
	}


	//Print history
	if(strcmp(args[0], "history") == 0){
		if (args[1] != NULL){
			printf("too many args\n");
			return -1;
		}

		int i = 1;
		while(i < count){
			printf("%d -- %s \n",i, history[i]);	
			i++;
		}
	}
	
	return i;
}
Exemplo n.º 9
0
static bool test_tokener_parse_realistic() {
    emit_test("Test realistic tokener parsing functions");

	MyString msg;
	std::string temp;
	std::set<std::string> attrs;
	std::set<std::string> labels;
	std::set<std::string> formats;

	StringLiteralInputStream lines(
		"# blackhole.cpf\n"
		"# show static slots with high job churn\n"
		"SELECT\n"
		"   Machine WIDTH -24 \n"
		"   splitslotname(Name)[0] AS Slot WIDTH -8\n"
		"   Strcat(Arch,\"_\",IfThenElse(OpSys==\"WINDOWS\",OpSysShortName,OpSysName)) AS Platform\n"
		"   Cpus AS CPU\n"
		"   Memory     PRINTF \"%6d\"     AS Mem\n"
		"   Strcat(State,\"/\",Activity) AS Status WIDTH -14 TRUNCATE\n"
		"   EnteredCurrentActivity AS '  StatusTime'  PRINTAS ACTIVITY_TIME NOPREFIX\n"
		"   IfThenElse(JobId isnt undefined, JobId, \"no\") AS JobId WIDTH -11\n"
		"   RecentJobStarts/20.0 AS J/Min PRINTF %.2f\n"
		"WHERE RecentJobStarts >= 1 && PartitionableSlot =!= true && DynamicSlot =!= true\n"
		"SUMMARY \n"
	);

	tokener toke("");
	int state = 0;
	while (toke.set(lines.nextline())) {
		REQUIRE(toke.next());
		if (toke.starts_with("#")) {
			REQUIRE(toke.next() && (toke.matches("blackhole.cpf") || toke.matches("show")));
			continue;
		}
		const TestTableItem * ti = Keywords.lookup_token(toke);
		if (ti) {
			if (ti->id == item_SELECT) { REQUIRE(state == 0 && ! toke.next()); state = ti->id; continue; }
			else if (ti->id == item_WHERE) { REQUIRE(state == item_SELECT); }
			else if (ti->id == item_SUMMARY) { REQUIRE(state == item_WHERE); }
			else {
				emit_step_failure(__LINE__, "invalid transition");
			}
			state = ti->id;
		}
		switch (state) {
		default:
			emit_step_failure(__LINE__, "invalid state");
			break;
		case item_WHERE:
			REQUIRE(toke.next());
			toke.copy_to_end(temp);
			REQUIRE(temp == "RecentJobStarts >= 1 && PartitionableSlot =!= true && DynamicSlot =!= true");
			break;
		case item_SUMMARY:
			REQUIRE(!toke.next());
			break;
		case item_SELECT:
			toke.mark();
			bool got_attr = false;
			while (toke.next()) {
				ti = Keywords.lookup_token(toke);
				REQUIRE(!ti || ti->index > 1);
				if (ti && ! got_attr) {
					toke.copy_marked(temp);
					trim(temp);
					attrs.insert(temp);
					got_attr = true;
				} else if ( ! ti && got_attr) {
					msg = "invalid token at: ";
					msg += (toke.content().c_str() + toke.offset());
					emit_step_failure(__LINE__, msg.c_str());
				}
				if ( ! ti) continue;
				switch (ti->id) {
				case item_AS:
					REQUIRE(toke.next()); toke.copy_token(temp);
					labels.insert(temp);
					toke.mark_after();
					break;
				case item_PRINTF:
				case item_PRINTAS:
				case item_WIDTH:
					REQUIRE(toke.next()); toke.copy_token(temp);
					formats.insert(temp);
					break;
				}
			}
			break;
		}
	}

	std::set<std::string>::const_iterator it;
	it = attrs.begin();
	REQUIRE(*it++ == "Cpus");
	REQUIRE(*it++ == "EnteredCurrentActivity");
	REQUIRE(*it++ == "IfThenElse(JobId isnt undefined, JobId, \"no\")");
	REQUIRE(*it++ == "Machine");
	REQUIRE(*it++ == "Memory");
	REQUIRE(*it++ == "RecentJobStarts/20.0");
	REQUIRE(*it++ == "Strcat(Arch,\"_\",IfThenElse(OpSys==\"WINDOWS\",OpSysShortName,OpSysName))");
	REQUIRE(*it++ == "Strcat(State,\"/\",Activity)");
	REQUIRE(*it++ == "splitslotname(Name)[0]");
	REQUIRE(it == attrs.end());

	it = labels.begin();
	REQUIRE(*it++ == "  StatusTime");
	REQUIRE(*it++ == "CPU");
	REQUIRE(*it++ == "J/Min");
	REQUIRE(*it++ == "JobId");
	REQUIRE(*it++ == "Mem");
	REQUIRE(*it++ == "Platform");
	REQUIRE(*it++ == "Slot");
	REQUIRE(*it++ == "Status");
	REQUIRE(it == labels.end());

	it = formats.begin();
	REQUIRE(*it++ == "%.2f");
	REQUIRE(*it++ == "%6d");
	REQUIRE(*it++ == "-11");
	REQUIRE(*it++ == "-14");
	REQUIRE(*it++ == "-24");
	REQUIRE(*it++ == "-8");
	REQUIRE(*it++ == "ACTIVITY_TIME");
	REQUIRE(it == formats.end());
	/*
	for (it = attrs.begin(); it != attrs.end(); ++it) {
		emit_comment(msg.formatstr("attr: '%s'", it->c_str()));
	}
	for (it = labels.begin(); it != labels.end(); ++it) {
		emit_comment(msg.formatstr("label: '%s'", it->c_str()));
	}
	for (it = formats.begin(); it != formats.end(); ++it) {
		emit_comment(msg.formatstr("format: '%s'", it->c_str()));
	}
	*/

	return REQUIRED_RESULT();
}
Exemplo n.º 10
0
static bool test_tokener_parse_basic() {
    emit_test("Test basic tokener parsing functions");

	MyString msg;
	std::string temp;
	tokener toke("now is the time");

	REQUIRE (toke.content() == "now is the time");

	REQUIRE(toke.next() && toke.matches("now"));
	toke.copy_token(temp);
	REQUIRE(temp == "now");
	REQUIRE(toke.compare_nocase("NAW") > 0);
	REQUIRE(toke.compare_nocase("NoW") == 0);
	REQUIRE(toke.compare_nocase("pow") < 0);

	REQUIRE(toke.next() && toke.matches("is"));
	REQUIRE(toke.next() && toke.matches("the"));
	REQUIRE(toke.next() && toke.matches("time"));
	REQUIRE( ! toke.next());

	REQUIRE (toke.content() == "now is the time");

	toke.set("this is 'the end', really");
	REQUIRE(toke.next() && toke.matches("this"));
	REQUIRE(toke.next() && toke.matches("is"));
	REQUIRE( ! toke.is_quoted_string());
	REQUIRE( ! toke.is_regex());

	REQUIRE(toke.next() && toke.matches("the end"));
	REQUIRE(toke.is_quoted_string());
	REQUIRE( ! toke.is_regex());
	REQUIRE(toke.starts_with("the "));

	REQUIRE(toke.next() && toke.matches(","));
	REQUIRE( ! toke.is_quoted_string());
	REQUIRE( ! toke.is_regex());

	REQUIRE(toke.next() && toke.matches("really"));
	REQUIRE( ! toke.starts_with("the"));

	REQUIRE(toke.at_end());
	REQUIRE( ! toke.next());

	toke.rewind();
	REQUIRE(toke.next() && toke.matches("this"));
	toke.copy_to_end(temp);
	REQUIRE(temp == "this is 'the end', really");
	toke.mark_after();
	toke.next();
	REQUIRE(toke.next() && toke.matches("the end"));
	toke.next();
	toke.copy_marked(temp);
	if (temp != " is 'the end'") {
		emit_step_failure(__LINE__, msg.formatstr("toke.copy_marked() returned |%s| should be | is 'the end'|", temp.c_str()));
	}
	toke.copy_to_end(temp);
	if (temp != ", really") {
		emit_step_failure(__LINE__, msg.formatstr("toke.copy_marked() returned |%s| should be |, really|", temp.c_str()));
	}


	return REQUIRED_RESULT();
}