コード例 #1
0
ファイル: Search.cpp プロジェクト: Jshauk/sumatrapdf
// Synchronization command format:
// [<DDECOMMAND_SYNC>(["<pdffile>",]"<srcfile>",<line>,<col>[,<newwindow>,<setfocus>])]
static const WCHAR *HandleSyncCmd(const WCHAR *cmd, DDEACK& ack)
{
    ScopedMem<WCHAR> pdfFile, srcFile;
    BOOL line = 0, col = 0, newWindow = 0, setFocus = 0;
    const WCHAR *next = str::Parse(cmd, L"[" DDECOMMAND_SYNC L"(\"%S\",%? \"%S\",%u,%u)]",
                                   &pdfFile, &srcFile, &line, &col);
    if (!next)
        next = str::Parse(cmd, L"[" DDECOMMAND_SYNC L"(\"%S\",%? \"%S\",%u,%u,%u,%u)]",
                          &pdfFile, &srcFile, &line, &col, &newWindow, &setFocus);
    // allow to omit the pdffile path, so that editors don't have to know about
    // multi-file projects (requires that the PDF has already been opened)
    if (!next) {
        pdfFile.Set(NULL);
        next = str::Parse(cmd, L"[" DDECOMMAND_SYNC L"(\"%S\",%u,%u)]",
                          &srcFile, &line, &col);
        if (!next)
            next = str::Parse(cmd, L"[" DDECOMMAND_SYNC L"(\"%S\",%u,%u,%u,%u)]",
                              &srcFile, &line, &col, &newWindow, &setFocus);
    }

    if (!next)
        return NULL;

    WindowInfo *win = NULL;
    if (pdfFile) {
        // check if the PDF is already opened
        win = FindWindowInfoByFile(pdfFile);
        // if not then open it
        if (newWindow || !win) {
            LoadArgs args(pdfFile, !newWindow ? win : NULL);
            win = LoadDocument(args);
        } else if (win && !win->IsDocLoaded()) {
            ReloadDocument(win);
        }
    }
    else {
        // check if any opened PDF has sync information for the source file
        win = FindWindowInfoBySyncFile(srcFile);
        if (newWindow) {
            LoadArgs args(win->loadedFilePath);
            win = LoadDocument(args);
        }
    }

    if (!win || !win->IsDocLoaded())
        return next;
    if (!win->pdfsync)
        return next;

    ack.fAck = 1;
    assert(win->IsDocLoaded());
    UINT page;
    Vec<RectI> rects;
    int ret = win->pdfsync->SourceToDoc(srcFile, line, col, &page, rects);
    ShowForwardSearchResult(win, srcFile, line, col, ret, page, rects);
    if (setFocus)
        win->Focus();

    return next;
}
コード例 #2
0
ファイル: Search.cpp プロジェクト: Jshauk/sumatrapdf
// Open file DDE command, format:
// [<DDECOMMAND_OPEN>("<pdffilepath>"[,<newwindow>,<setfocus>,<forcerefresh>])]
static const WCHAR *HandleOpenCmd(const WCHAR *cmd, DDEACK& ack)
{
    ScopedMem<WCHAR> pdfFile;
    BOOL newWindow = 0, setFocus = 0, forceRefresh = 0;
    const WCHAR *next = str::Parse(cmd, L"[" DDECOMMAND_OPEN L"(\"%S\")]", &pdfFile);
    if (!next)
        next = str::Parse(cmd, L"[" DDECOMMAND_OPEN L"(\"%S\",%u,%u,%u)]",
                          &pdfFile, &newWindow, &setFocus, &forceRefresh);
    if (!next)
        return NULL;

    WindowInfo *win = FindWindowInfoByFile(pdfFile);
    if (newWindow || !win) {
        LoadArgs args(pdfFile, !newWindow ? win : NULL);
        win = LoadDocument(args);
    } else if (win && !win->IsDocLoaded()) {
        ReloadDocument(win);
        forceRefresh = 0;
    }

    assert(!win || !win->IsAboutWindow());
    if (!win)
        return next;

    ack.fAck = 1;
    if (forceRefresh)
        ReloadDocument(win, true);
    if (setFocus)
        win->Focus();

    return next;
}
コード例 #3
0
      /// <summary>Reads the entire language file</summary>
      /// <param name="path">Full path</param>
      /// <returns>New language file</returns>
      /// <exception cref="Logic::ComException">COM Error</exception>
      /// <exception cref="Logic::FileFormatException">Corrupt XML / Missing elements / missing attributes</exception>
      /// <exception cref="Logic::InvalidValueException">Invalid languageID or pageID</exception>
      /// <exception cref="Logic::IOException">An I/O error occurred</exception>
      LanguageFile LanguageFileReader::ReadFile(Path path)
      {
         try
         {
            LanguageFile file(path);

            // Parse document
            LoadDocument();

            // Get root (as node)
            XmlNodePtr languageNode(Document->documentElement);

            // Read fileID + language tag
            file.ID = LanguageFilenameReader(path.FileName).FileID;
            file.Language = ReadLanguageTag(languageNode);

            // Read pages
            for (int i = 0; i < languageNode->childNodes->length; i++)
            {
               XmlNodePtr n = languageNode->childNodes->item[i];

               if (n->nodeType == Xml::NODE_ELEMENT)
                  file.Pages.Add( ReadPage(n) );
            }

            return file;
         }
         catch (_com_error& ex) {
            throw ComException(HERE, ex);
         }
      }
コード例 #4
0
ファイル: Favorites.cpp プロジェクト: wyrover/sumatrapdf
// Going to a bookmark within current file scrolls to a given page.
// Going to a bookmark in another file, loads the file and scrolls to a page
// (similar to how invoking one of the recently opened files works)
static void GoToFavorite(WindowInfo* win, DisplayState* f, Favorite* fn) {
    CrashIf(!f || !fn);
    if (!f || !fn) {
        return;
    }

    WindowInfo* existingWin = FindWindowInfoByFile(f->filePath, true);
    if (existingWin) {
        int pageNo = fn->pageNo;
        uitask::Post([=] { GoToFavorite(existingWin, pageNo); });
        return;
    }

    if (!HasPermission(Perm_DiskAccess)) {
        return;
    }

    // When loading a new document, go directly to selected page instead of
    // first showing last seen page stored in file history
    // A hacky solution because I don't want to add even more parameters to
    // LoadDocument() and LoadDocumentInto()
    int pageNo = fn->pageNo;
    DisplayState* ds = gFileHistory.Find(f->filePath);
    if (ds && !ds->useDefaultState && gGlobalPrefs->rememberStatePerDocument) {
        ds->pageNo = fn->pageNo;
        ds->scrollPos = PointI(-1, -1); // don't scroll the page
        pageNo = -1;
    }

    LoadArgs args(f->filePath, win);
    win = LoadDocument(args);
    if (win) {
        uitask::Post([=] { (win, pageNo); });
    }
}
コード例 #5
0
ファイル: WindowInfo.cpp プロジェクト: jounghyun/sumatrapdf
void LinkHandler::LaunchFile(const WCHAR *path, PageDestination *link)
{
    // for safety, only handle relative paths and only open them in SumatraPDF
    // (unless they're of an allowed perceived type) and never launch any external
    // file in plugin mode (where documents are supposed to be self-contained)
    WCHAR drive;
    if (str::StartsWith(path, L"\\") || str::Parse(path, L"%c:\\", &drive) || gPluginMode) {
        return;
    }

    ScopedMem<WCHAR> fullPath(path::GetDir(owner->dm->FilePath()));
    fullPath.Set(path::Join(fullPath, path));
    fullPath.Set(path::Normalize(fullPath));
    // TODO: respect link->ld.gotor.new_window for PDF documents ?
    WindowInfo *newWin = FindWindowInfoByFile(fullPath);
    // TODO: don't show window until it's certain that there was no error
    if (!newWin) {
        LoadArgs args(fullPath, owner);
        newWin = LoadDocument(args);
        if (!newWin)
            return;
    }

    if (!newWin->IsDocLoaded()) {
        CloseWindow(newWin, true);
        // OpenFileExternally rejects files we'd otherwise
        // have to show a notification to be sure (which we
        // consider bad UI and thus simply don't)
        bool ok = OpenFileExternally(fullPath);
        if (!ok) {
            ScopedMem<WCHAR> msg(str::Format(_TR("Error loading %s"), fullPath));
            ShowNotification(owner, msg, true /* autoDismiss */, true /* highlight */);
        }
        return;
    }

    newWin->Focus();
    if (!link)
        return;

    ScopedMem<WCHAR> name(link->GetDestName());
    if (!name)
        newWin->linkHandler->ScrollTo(link);
    else {
        PageDestination *dest = newWin->dm->engine->GetNamedDest(name);
        if (dest) {
            newWin->linkHandler->ScrollTo(dest);
            delete dest;
        }
    }
}
コード例 #6
0
ファイル: assetmanager.cpp プロジェクト: Dracophoenix1/ares
bool AssetManager::LoadFile (const char* filename)
{
  NewProject ();

  csRef<iDocument> doc;
  csRef<iString> error = LoadDocument (object_reg, doc, 0, filename);
  if (!doc && !error)
  {
    error.AttachNew (new scfString ());
    error->Format ("ERROR reading file '%s'", filename);
  }
  else
    return LoadDoc (doc);

  printf ("%s\n", error->GetData ());
  return false;
}
コード例 #7
0
ファイル: SumatraStartup.cpp プロジェクト: Nargesf/Sumatrapdf
static WindowInfo *LoadOnStartup(const WCHAR *filePath, CommandLineInfo& i, bool isFirstWin)
{
    LoadArgs args(filePath);
    args.showWin = !(i.printDialog && i.exitWhenDone) && !gPluginMode;
    WindowInfo *win = LoadDocument(args);
    if (!win)
        return win;

    if (win->IsDocLoaded() && i.destName && isFirstWin) {
        win->linkHandler->GotoNamedDest(i.destName);
    } else if (win->IsDocLoaded() && i.pageNumber > 0 && isFirstWin) {
        if (win->ctrl->ValidPageNo(i.pageNumber))
            win->ctrl->GoToPage(i.pageNumber, false);
    }
    if (i.hwndPluginParent)
        MakePluginWindow(*win, i.hwndPluginParent);
    if (!win->IsDocLoaded() || !isFirstWin)
        return win;

    if (i.enterPresentation || i.enterFullScreen) {
        if (i.enterPresentation && win->isFullScreen || i.enterFullScreen && win->presentation)
            ExitFullScreen(*win);
        EnterFullScreen(*win, i.enterPresentation);
    }
    if (i.startView != DM_AUTOMATIC)
        SwitchToDisplayMode(win, i.startView);
    if (i.startZoom != INVALID_ZOOM)
        ZoomToSelection(win, i.startZoom);
    if ((i.startScroll.x != -1 || i.startScroll.y != -1) && win->AsFixed()) {
        DisplayModel *dm = win->AsFixed();
        ScrollState ss = dm->GetScrollState();
        ss.x = i.startScroll.x;
        ss.y = i.startScroll.y;
        dm->SetScrollState(ss);
    }
    if (i.forwardSearchOrigin && i.forwardSearchLine && win->AsFixed() && win->AsFixed()->pdfSync) {
        UINT page;
        Vec<RectI> rects;
            ScopedMem<WCHAR> sourcePath(path::Normalize(i.forwardSearchOrigin));
        int ret = win->AsFixed()->pdfSync->SourceToDoc(sourcePath, i.forwardSearchLine, 0, &page, rects);
        ShowForwardSearchResult(win, sourcePath, i.forwardSearchLine, 0, ret, page, rects);
    }
    return win;
}
コード例 #8
0
ファイル: LTVUtil.Test.cpp プロジェクト: codeboost/libertv
	HRESULT LoadFile(const char* pszFileName)
	{
		HRESULT hr = E_FAIL; 
		hr = m_pDoc.CoCreateInstance(CLSID_DOMDocument30, NULL, CLSCTX_INPROC_SERVER); 
		if (SUCCEEDED(hr))
		{
			m_pDoc->put_async(VARIANT_FALSE); 
			m_pDoc->put_validateOnParse(VARIANT_FALSE); 
			VARIANT_BOOL bSuccessful; 
			hr = m_pDoc->load(CComVariant(pszFileName), &bSuccessful); 
			if (SUCCEEDED(hr) && bSuccessful)
			{
				hr = LoadDocument();
				if (SUCCEEDED(hr))
				{
					hr = m_pDoc->save(CComVariant("E:\\Temp\\out.xml")); 
				}
			}
		}
		return hr; 
	}
コード例 #9
0
ファイル: WindowInfo.cpp プロジェクト: jra101/sumatrapdf
void LinkHandler::GotoLink(PageDestination *link)
{
    CrashIf(!owner || owner->linkHandler != this);
    if (!link || !owner->IsDocLoaded())
        return;

    ScopedMem<WCHAR> path(link->GetDestValue());
    PageDestType type = link->GetDestType();
    if (Dest_ScrollTo == type) {
        // TODO: respect link->ld.gotor.new_window for PDF documents ?
        ScrollTo(link);
    }
    else if (Dest_LaunchURL == type) {
        if (!path)
            /* ignore missing URLs */;
        else {
            WCHAR *colon = str::FindChar(path, ':');
            WCHAR *hash = str::FindChar(path, '#');
            if (!colon || (hash && colon > hash)) {
                // treat relative URIs as file paths (without fragment identifier)
                if (hash)
                    *hash = '\0';
                // LaunchFile will reject unsupported file types
                LaunchFile(path, NULL);
            }
            else {
                // LaunchBrowser will reject unsupported URI schemes
                LaunchBrowser(path);
            }
        }
    }
    else if (Dest_LaunchEmbedded == type) {
        // open embedded PDF documents in a new window
        if (path && str::StartsWith(path.Get(), owner->ctrl->FilePath())) {
            WindowInfo *newWin = FindWindowInfoByFile(path, true);
            if (!newWin) {
                LoadArgs args(path, owner);
                newWin = LoadDocument(args);
            }
            if (newWin)
                newWin->Focus();
        }
        // offer to save other attachments to a file
        else {
            LinkSaver linkSaverTmp(*owner, path);
            link->SaveEmbedded(linkSaverTmp);
        }
    }
    else if (Dest_LaunchFile == type) {
        if (path) {
            // LaunchFile only opens files inside SumatraPDF
            // (except for allowed perceived file types)
            LaunchFile(path, link);
        }
    }
    // predefined named actions
    else if (Dest_NextPage == type)
        owner->ctrl->GoToNextPage();
    else if (Dest_PrevPage == type)
        owner->ctrl->GoToPrevPage();
    else if (Dest_FirstPage == type)
        owner->ctrl->GoToFirstPage();
    else if (Dest_LastPage == type)
        owner->ctrl->GoToLastPage();
    // Adobe Reader extensions to the spec, cf. http://www.tug.org/applications/hyperref/manual.html
    else if (Dest_FindDialog == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_FIND_FIRST, 0);
    else if (Dest_FullScreen == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_VIEW_PRESENTATION_MODE, 0);
    else if (Dest_GoBack == type)
        owner->ctrl->Navigate(-1);
    else if (Dest_GoForward == type)
        owner->ctrl->Navigate(1);
    else if (Dest_GoToPageDialog == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_GOTO_PAGE, 0);
    else if (Dest_PrintDialog == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_PRINT, 0);
    else if (Dest_SaveAsDialog == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_SAVEAS, 0);
    else if (Dest_ZoomToDialog == type)
        PostMessage(owner->hwndFrame, WM_COMMAND, IDM_ZOOM_CUSTOM, 0);
    else
        CrashIf(Dest_None != type);
}
コード例 #10
0
bool StressTest::OpenFile(const TCHAR *fileName)
{
    bool reuse = rand() % 3 != 1;
    _tprintf(_T("%s\n"), fileName);
    fflush(stdout);
    LoadArgs args(fileName, NULL, true /* show */, reuse);
    WindowInfo *w = LoadDocument(args);
    if (!w)
        return false;

    if (w == win) { // WindowInfo reused
        if (!win->dm)
            return false;
    } else if (!w->dm) { // new WindowInfo
        CloseWindow(w, false, true);
        return false;
    }

    // transfer ownership of stressTest object to a new window and close the
    // current one
    assert(this == win->stressTest);
    if (w != win) {
        if (win->IsDocLoaded()) {
            // try to provoke a crash in RenderCache cleanup code
            ClientRect rect(win->hwndFrame);
            rect.Inflate(rand() % 10, rand() % 10);
            SendMessage(win->hwndFrame, WM_SIZE, 0, MAKELONG(rect.dx, rect.dy));
            win->RenderPage(1);
            win->RepaintAsync();
        }

        WindowInfo *toClose = win;
        w->stressTest = win->stressTest;
        win->stressTest = NULL;
        win = w;
        CloseWindow(toClose, false, false);
    }
    if (!win->dm)
        return false;

    win->dm->ChangeDisplayMode(DM_CONTINUOUS);
    win->dm->ZoomTo(ZOOM_FIT_PAGE);
    win->dm->GoToFirstPage();
    if (win->tocVisible || gGlobalPrefs.favVisible)
        SetSidebarVisibility(win, win->tocVisible, gGlobalPrefs.favVisible);

    currPage = pageRanges.At(0).start;
    win->dm->GoToPage(currPage, 0);
    currPageRenderTime.Start();
    ++filesCount;

    pageForSearchStart = (rand() % win->dm->PageCount()) + 1;
    // search immediately in single page documents
    if (1 == pageForSearchStart) {
        // use text that is unlikely to be found, so that we search all pages
        win::SetText(win->hwndFindBox, _T("!z_yt"));
        FindTextOnThread(win);
    }

    int secs = SecsSinceSystemTime(stressStartTime);
    ScopedMem<TCHAR> tm(FormatTime(secs));
    ScopedMem<TCHAR> s(str::Format(_T("File %d: %s, time: %s"), filesCount, fileName, tm));
    ShowNotification(win, s, false, false, NG_STRESS_TEST_SUMMARY);

    return true;
}
コード例 #11
0
void TestPPTAttachedDocument::TestDiscoverHyperLinks()
{
	CStdString documentFileName = CreateTestResultDocument(GetDiscoverDocumentFileName(), _T(__FUNCTION__));
	LPCTSTR expectedFileName = GetDiscoverExpectedXMLFileName();
	LPCTSTR metadataNode = _T("HyperLinks");
	LPCTSTR metadataElement = MWE_FIELDS;

	DocumentManager spPresentation(documentFileName.c_str(), g_spPPTInstanceManager);

	CStdString sTestDocumentFileName = documentFileName;	

	IMWMetadataElementsPtr spElements(__uuidof(CMetadataElements));
	IMWDocumentsPtr spDocuments = m_spApplication->Documents;
	IMWDocumentPtr spDocument = spDocuments->Open(spPresentation);		

	spElements->SelectNoElements();
	spElements->Item[metadataElement]->Enabled = VARIANT_TRUE;

	MSXML2::IXMLDOMDocumentPtr spActualMetadataDocument = spDocument->DiscoverMetadata(spElements);	
	CStdString sFileName = GetTestResultFileName(expectedFileName, _T(__FUNCTION__));

	ResetAuthorPathToBlank(spActualMetadataDocument);
	WriteXmlNodeToFile(sFileName, spActualMetadataDocument);

	// Reload the actual xml into the dom to remove any empty nodes that may exist. This is only for the test
	// and should not effect any other area of the system.
	spActualMetadataDocument = LoadDocument(sFileName, GetXMLErrorFileName(_T(__FUNCTION__)));

	MSXML2::IXMLDOMDocumentPtr spExpectedMetadataDocument = LoadDocument(expectedFileName, GetXMLErrorFileName(_T(__FUNCTION__)));

	// Because we are working with a copy of the document, we must inject that name into the DOM otherwise
	// our tests will fail.
	IDispatchPtr spElement = spExpectedMetadataDocument->selectSingleNode(_T("/Metadata/Documents/Document"));
	if(spElement == 0)
		throw Workshare::Exception(_T("Failed to obtain the /Metadata/Documents/Document node from the document"));

	MSXML2::IXMLDOMElementPtr spDocumentElement = spElement;
	if(spDocumentElement == 0)
		throw Workshare::Exception(_T("MSXML2::IXMLDOMElement is not implemented by the node returned from \"/Metadata/Documents/Document\""));

	spDocumentElement->setAttribute(_T("Name"), documentFileName.c_str());

	CStdString sBaseNodeName(_T("/Metadata/Documents/Document/"));	
	CStdString sXmlNode(sBaseNodeName);
	sXmlNode += metadataNode;

	MSXML2::IXMLDOMNodePtr spExpectedNode = spExpectedMetadataDocument->selectSingleNode(sXmlNode.c_str());
	MSXML2::IXMLDOMNodePtr spActualNode = spActualMetadataDocument->selectSingleNode(sXmlNode.c_str());

	assertMessage(spExpectedNode != 0, _T("The expected xml node should not be zero"));
	assertMessage(spActualNode != 0, _T("The actual xml node should not be zero"));

	assertXmlEqual(spExpectedNode, spActualNode);

	for(long nIndex = 1; nIndex <= spElements->Count; nIndex++)
	{
		IMWMetadataElementPtr spElement = spElements->Item[nIndex];
		// Only those elements selected should be discovered, so ignore the selected one
		if(0 != lstrcmpi(spElement->Name, metadataElement))
		{
			sXmlNode = sBaseNodeName;
			sXmlNode += static_cast<const TCHAR*>(spElement->Name);

			MSXML2::IXMLDOMNodePtr spNode = spActualMetadataDocument->selectSingleNode(sXmlNode.c_str());

			CStdString sMessage;
			sMessage.Format(_T("\"%s\" was discovered and was not set."), static_cast<const TCHAR*>(spElement->Name));
			assertMessage(spNode == 0, sMessage)
		}
	}
コード例 #12
0
ファイル: umcframework.cpp プロジェクト: Jared-Prime/UniMRCP
bool UmcFramework::LoadScenarios()
{
	apr_xml_doc* pDoc = LoadDocument();
	if(!pDoc)
		return false;

	const apr_xml_attr* pAttr;
	const apr_xml_elem* pElem;
	const apr_xml_elem* pRoot = pDoc->root;
	if(!pRoot || strcasecmp(pRoot->name,"umcscenarios") != 0)
	{
		apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"Unknown Document");
		return FALSE;
	}
	for(pElem = pRoot->first_child; pElem; pElem = pElem->next)
	{
		if(strcasecmp(pElem->name,"scenario") != 0)
		{
			apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"Unknown Element <%s>",pElem->name);
			continue;
		}
		
		const char* pName = NULL;
		const char* pClass = NULL;
		const char* pMrcpProfile = NULL;
		for(pAttr = pElem->attr; pAttr; pAttr = pAttr->next) 
		{
			if(strcasecmp(pAttr->name,"name") == 0) 
			{
				pName = pAttr->value;
			}
			else if(strcasecmp(pAttr->name,"class") == 0) 
			{
				pClass = pAttr->value;
			}
			else if(strcasecmp(pAttr->name,"profile") == 0) 
			{
				pMrcpProfile = pAttr->value;
			}
		}

		if(pName && pClass)
		{
			apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Load Scenario name [%s] class [%s]",pName,pClass);
			UmcScenario* pScenario = CreateScenario(pClass);
			if(pScenario)
			{
				pScenario->SetDirLayout(m_pDirLayout);
				pScenario->SetName(pName);
				pScenario->SetMrcpProfile(pMrcpProfile);
				if(pScenario->Load(pElem,m_pPool))
					apr_hash_set(m_pScenarioTable,pScenario->GetName(),APR_HASH_KEY_STRING,pScenario);
				else
					delete pScenario;
			}
			else
			{
				apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"No such scenario <%s>",pClass);
			}
		}
		else
		{
			apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"Missing either name or class of the scenario");
		}
	}
	return true;
}
コード例 #13
0
int main (int argc, char **argv) {

	/* Check Arguments */
	if (!CheckArguments(argc, argv)) {
		exit(-1);
	}

	/* Make variables for all things needed for indexer and indexer testing */
	char *page_directory;
	char *index_filename;
	char *read_index_filename;
	char *new_index_filename;
	// If argument count is 3 initialize only 2 variables else initialize all
	page_directory = argv[1];
	index_filename = argv[2];

	// Initialize hashtable, word node, and document node
	HashTable *index_hashtable = calloc(1, sizeof(HashTable));

	/*Make array to hold filenames (just document numbers) and use GetFilenamesInDir to grab all names */
	char **filename_array;
	int number_of_files;
	if ((number_of_files = GetFilenamesInDir(page_directory, &filename_array)) < 0) {
		fprintf(stderr, "Could not get filenames in page directory. Exiting Now.\n");
		exit(-1);
	}


	/* Add page_directory to the front of the filenames */
	for (int i = 0; i < number_of_files; i++) {
		// Make pointe to current string in filename_array
		char *previous_string = filename_array[i];
		// Get length of full string and initialize element of filename_array to that size
		int len = strlen(page_directory) + strlen(previous_string) + 1;
		char *new_string = calloc(len, sizeof(char));
		// Make new string and free previous string
		strcpy(new_string, page_directory);
		strcat(new_string, previous_string);
		if (previous_string)
			free(previous_string);		

		filename_array[i] = new_string;
	}

	/* Populate the index data structure from the words on each doc
	 * Then Save to an index file                     
	 */
	for (int i = 0; i < number_of_files; i++) {

		/* Check that the filenames are digits */
		int continue_flag = 0;
		char *digit_string = filename_array[i] + strlen(page_directory);
		// Check that every character in the filename is a digit
		for (int j = 0; j < strlen(digit_string); j++) {
			if (!isdigit(digit_string[j])) {
				fprintf(stderr, "This file %s contains something other than a digit \n", filename_array[i]);
				continue_flag = 1;
			}
		}
		if (continue_flag ==1)
			continue;

		// Check that each file in the filename array is a good file
		char *file_name = filename_array[i];
		if (!IsFile(file_name)) {
			fprintf(stderr, "not file\n");	
			continue;
		}

		// Get contents of file into a string
		char *document = LoadDocument(file_name);
		if (document == NULL) {
			continue;
		}

		// Get DocumentID of file (check if bad)
		int document_id = GetDocumentId(file_name, page_directory);
		if (document_id < 0) {
			fprintf(stderr, "Error when converting document id char to integer\n");
			continue;
		}

		// Use GetNext word, with pos variable and buffer, to get every word and add the word to the data structure
		int pos = 0;
		char *word_buffer;
		while ((pos = GetNextWord(document, pos, &word_buffer)) > 0) {
			// Update the index for each word
			// Normalize word then update index with that word
			NormalizeWord(word_buffer);
			UpdateIndex(word_buffer, document_id, index_hashtable);
			free(word_buffer);
		}
		// free the string containing the html and the word in filenamearray
		free(document);
	}

	/* Save to index file, and check that it actually went well */
	if (!SaveIndexToFile(index_hashtable, index_filename)) {
		fprintf(stderr, "Could not save index hashtable to file\n");
		exit(-1);
	}

	for (int i = 0; i < number_of_files; i++) {
		free(filename_array[i]);
	}
	free(filename_array);
	FreeHashTable(index_hashtable);

	if (argc == 3) {
		;
	}
	/* Read index file into data strucutres and save to new index file */
 	else {
 		// Assign 2 filenames
 		read_index_filename = argv[3];
		new_index_filename = argv[4];
		// Read index file into data structures 
		HashTable *read_index = ReadFile(read_index_filename);
		if (read_index == NULL) {
			fprintf(stderr, "Error when reading index file into data structures.\n");
			exit(-1);
		}
		// Save index data structures into new file
		if (!SaveIndexToFile(read_index, new_index_filename)) {
			fprintf(stderr, "Could not save read index file into new index file\n");
			exit(-1);
		}
		
		FreeHashTable(read_index);
    }

	return 0;
}
コード例 #14
0
void TestWSChangeInterface::setUp()
{
	LoadDocument();	
}
コード例 #15
0
ファイル: indexer.c プロジェクト: jlee9595/TinySearchEngine
int main(int argc, char* argv[]) {
	//check argument number
	if (argc < 3 || argc > 4) {
		printf("too many or too little arguments, please try again");
		exit(0);
	}
	
	//check directory validity
	if (!IsDir(argv[1])) {
		printf("invalid directory, please try again");
		exit(0);
	}
	
	//Initialize variables and index
	int docId;
	int pos;
	char *doc;
	char **filenames = NULL;
	int num_files = 0;
	HashTable *WordsFound = calloc(1, sizeof(HashTable));
	num_files = GetFilenamesInDir(argv[1], &filenames);

	//check whether the folder has files
	if (num_files < 0) {
		printf("failed to get any filenames");
		exit(0);
	}

	//iterate through each file in the directory
	for (int i = 0; i < num_files; i++) {
		
		//check that the file is in the correct format (title is a number)
		int filechecker = 0;
		for (int c = 0; c < strlen(filenames[i]); c++) {
			if (!isdigit(filenames[i][c])) {
				filechecker = 1;
			}
		}
		if (filechecker == 1) {
			continue;
		}

		//Load the document
		char *word;
		char file[100];
		strcpy(file, argv[1]);
		strcat(file, filenames[i]);
		doc = LoadDocument(file);
		docId = GetDocumentId(filenames[i]);
		free(filenames[i]);
		
		pos = 0;
		//Iterate through each word in the html file (doc)
		while ((pos = GetNextWord(doc, pos, &word)) > 0) {
			NormalizeWord(word);
			if (InHashTable(word, WordsFound) == 0) {
				AddToHashTable(word, WordsFound);
				UpdateHashTable(word, docId, WordsFound);
			}
			else {
				UpdateHashTable(word, docId, WordsFound);
				free(word);
			}
		}
		free(doc);
	}	
	free(filenames);
	SaveIndexToFile(argv[2], WordsFound);				//Save the index to the file specified
	FreeHashTable(WordsFound);

	//only proceed if there was a third argument specified. If so, reload the index form the file you just created
	if (argc == 4) {
		HashTable *ReloadedIndex = ReadFile(argv[2]);
		SaveIndexToFile(argv[3], ReloadedIndex);
		FreeHashTable(ReloadedIndex);
	}
	return 0;
}
コード例 #16
0
bool StressTest::OpenFile(const WCHAR* fileName) {
    wprintf(L"%s\n", fileName);
    fflush(stdout);

    LoadArgs args(fileName);
    args.forceReuse = rand() % 3 != 1;
    WindowInfo* w = LoadDocument(args);
    if (!w)
        return false;

    if (w == win) { // WindowInfo reused
        if (!win->IsDocLoaded())
            return false;
    } else if (!w->IsDocLoaded()) { // new WindowInfo
        CloseWindow(w, false);
        return false;
    }

    // transfer ownership of stressTest object to a new window and close the
    // current one
    AssertCrash(this == win->stressTest);
    if (w != win) {
        if (win->IsDocLoaded()) {
            // try to provoke a crash in RenderCache cleanup code
            ClientRect rect(win->hwndFrame);
            rect.Inflate(rand() % 10, rand() % 10);
            SendMessage(win->hwndFrame, WM_SIZE, 0, MAKELONG(rect.dx, rect.dy));
            if (win->AsFixed())
                win->cbHandler->RequestRendering(1);
            win->RepaintAsync();
        }

        WindowInfo* toClose = win;
        w->stressTest = win->stressTest;
        win->stressTest = nullptr;
        win = w;
        CloseWindow(toClose, false);
    }
    if (!win->IsDocLoaded())
        return false;

    win->ctrl->SetDisplayMode(DM_CONTINUOUS);
    win->ctrl->SetZoomVirtual(ZOOM_FIT_PAGE, nullptr);
    win->ctrl->GoToFirstPage();
    if (win->tocVisible || gGlobalPrefs->showFavorites)
        SetSidebarVisibility(win, win->tocVisible, gGlobalPrefs->showFavorites);

    currPage = pageRanges.at(0).start;
    win->ctrl->GoToPage(currPage, false);
    currPageRenderTime.Start();
    ++filesCount;

    pageForSearchStart = (rand() % win->ctrl->PageCount()) + 1;
    // search immediately in single page documents
    if (1 == pageForSearchStart) {
        // use text that is unlikely to be found, so that we search all pages
        win::SetText(win->hwndFindBox, L"!z_yt");
        FindTextOnThread(win, TextSearchDirection::Forward, true);
    }

    int secs = SecsSinceSystemTime(stressStartTime);
    AutoFreeW tm(FormatTime(secs));
    AutoFreeW s(str::Format(L"File %d: %s, time: %s", filesCount, fileName, tm));
    win->ShowNotification(s, NOS_PERSIST, NG_STRESS_TEST_SUMMARY);

    return true;
}