Example #1
0
int main(int argc, char *argv[])
{
    // this should be checked, especially in larger projects
    if(!ttvfs::checkCompat())
    {
        std::cout << "HUH? ttvfs was compiled with different options than this file!" << std::endl;
        return 1;
    }

    // Note: Here, it is really important that all files & subdirs are loaded recursively.
    // In the merge step below, only those files that already exist in the tree will be
    // accessible in their new location.
    vfs.LoadFileSysRoot(true);
    vfs.Prepare();
    
    PrintFile("myfile.txt"); // this is the default file
    PrintFile("patches/myfile.txt"); // this is the patch file

    std::cout << "-- Mounting 'patches' -> ''" << std::endl;

    // merge "patches" into root dir
    //vfs.MountExternalPath("patches"); // this works, but recreates parts of the tree
                                        // that are already existing - possibly error prone!

    vfs.Mount("patches", ""); // <-- this is the better way.
    // all files and subdirs that were in "patches" are now mirrored in "" as well.

    PrintFile("myfile.txt"); // Access the file as before -> it got replaced.

    std::cout << "-- Before mounting 'more/even_more/deep' -> 'far' (should error)" << std::endl;

    PrintFile("far/file.txt"); // not found!

    // remount a directory under a different name
    vfs.Mount("more/even_more/deep", "far");

    std::cout << "-- After mounting 'more/even_more/deep' -> 'far'" << std::endl;

    PrintFile("far/file.txt"); // ... and access this file normally

    // mount an external directory (this could be ~/.MyApp or anything)
    vfs.MountExternalPath("../ttvfs", "ext");

    ttvfs::VFSDir *ext = vfs.GetDir("ext");
    if(ext)
    {
        //VFS_GUARD(ext); // in case this would be called from multiple threads, lock this directory.

        std::cout << "Listing files in 'ext' subdir ..." << std::endl;

        unsigned int c = 0;
        ext->forEachFile(FileCallback, &c);

        std::cout << c << " files in total!" << std::endl;
    }
    
    return 0;
}
Example #2
0
void Tree::PrintFile(ofstream &of, TreeNode *pTree) const{

    if(pTree != nullptr){
        PrintFile(of,pTree->m_left);
        pTree->m_student.writeToFile(of);
        PrintFile(of,pTree->m_right);
    }

}
Example #3
0
void DisplayStage(char s, char *msg, int error)
{
	char *p;
	char buf[MAXLEN];
	if(msg!=NULL && *msg!=0)  {
		if(error) 
			snprintf(DeferMSG,MAXLEN,"<font color=red>错误:%s</font>",msg);
		else 
			snprintf(DeferMSG,MAXLEN,"信息:%s",msg);
	}
	p = user_agent();
	if ( (s<'0') ||  (s>'2') ) 
		s='0';

	if( HtmlHeadOut==0 ) {
		HtmlHead();
	}
	if( p && (strstr(p,"Mobile")) ) {
#ifdef DEBUG
		snprintf(buf,MAXLEN,"/var/www/html/mstage%c.1.html",s);
#else
		snprintf(buf,MAXLEN,"/var/www/html/mstage%c.html",s);
#endif
	} else {
#ifdef DEBUG
		snprintf(buf,MAXLEN,"/var/www/html/stage%c.1.html",s);
#else
		snprintf(buf,MAXLEN,"/var/www/html/stage%c.html",s);
#endif
	}
	PrintFile(buf);
	if ( mysql ) mysql_close(mysql);
	exit(0);
}
Example #4
0
void IPOnline( int timespan )
{
	char buf[MAXLEN];
	char *url;
	setuid(0);
	snprintf(buf,MAXLEN,"/usr/sbin/ipset add -exist user %s,%c%c:%c%c:%c%c:%c%c:%c%c:%c%c timeout %d",
		remote_addr(), MAC[0],MAC[1],MAC[2],MAC[3],MAC[4],MAC[5],MAC[6],MAC[7],MAC[8],MAC[9],MAC[10],MAC[11],
		timespan );
	system(buf);
	snprintf(buf,MAXLEN,"insert into IPMACPhone values('%s', '%s','%s',now(), date_add(now(), interval %d second))",
			remote_addr(),MAC,PHONE,timespan);
	ExecSQL(buf,0);
	url=GetValue("url");
	if(url && (*url) && (strcmp(url,"URL")!=0)) {
		if( HtmlHeadOut==0 ) {
			HtmlHead();
			PrintFile("/var/www/html/redir.html");
		}
		printf("<script language=\"javascript\" type=\"text/javascript\">"
                        "window.location.href=\"%s\";</script>\n", url);
		printf("请继续访问<a href=%s>%s</a><p>",url,url);
		printf("</body></html>\n");
		mysql_close(mysql);
		exit(0);
	}
	DisplayStage('2',"欢迎使用网络",0);
}
Example #5
0
void CLogManager::WriteLog(CLogInfo &oLogInfo, bool bSupportNet)
{
	if(m_bHold)
	{
		GetLogDate(oLogInfo.sDate);
		m_oLogBuffer.Push(oLogInfo);
	}
	else
	{
		CAfcLogAttr& oLogAttr = GetLogAttr(oLogInfo.sModuleName);
		if( (oLogAttr.nMode & FOCP_LOG_SCREEN) || (oLogAttr.nMode & FOCP_LOG_FILE) )
		{
			char sLogInfo[FOCP_LOG_MAXMSG];
			uint32 nLen = GetLogInfo(oLogAttr.nFilter, oLogInfo, sLogInfo);
			if(oLogAttr.nMode & FOCP_LOG_SCREEN)
				PrintScreen(oLogInfo.nLevel, sLogInfo, nLen);
			if(oLogAttr.nMode & FOCP_LOG_FILE)
				PrintFile(sLogInfo, nLen);
		}
		if(bSupportNet && (oLogAttr.nMode & FOCP_LOG_SERVER))
		{
			char sLogInfo[FOCP_LOG_MAXMSG];
			uint32 nLen = CreateLogMsg(oLogInfo, sLogInfo);
			PrintServer(sLogInfo, nLen);
		}
	}
}
Example #6
0
int main(int argc, char *argv[])
{
	char *way_to_file;
	char *parent_catalog = NULL;
	int catalog_counter = 1, file_counter = 0;
	TFile *file_list = NULL;
	
	//check for errors, if found - exit program
	if (CheckErrors(argc, argv))
		return 1;

	//edit parent path(if the last letter = '/' - delete it
	parent_catalog = EditArgv(parent_catalog, argv[1]);
	
	//recursive function of searching file. if file wasn`t found - exit
	if ((file_list = SearchFile(parent_catalog, argv[2], &catalog_counter, &file_counter, file_list)) == NULL) {
		fprintf(stderr, "%s: Such file not found...\n", argv[1]);
		return 0;
	} 
	
	//print the information about file
	PrintFile(way_to_file, argv[2], catalog_counter, file_counter);
	while(file_list != NULL) {
		printf("\n%s\n", file_list->path);
		file_list = file_list->next;
	}
	
	return 0;
}
Example #7
0
int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " [FILENAME]" << std::endl;
        return 1;
    }

    uint32_t rowsCount = 0;
    uint32_t colsCount = 0;
    ReadInputShape(argv[1], &rowsCount, &colsCount);

    std::fstream in(argv[1], std::fstream::in | std::fstream::binary);
    in.seekg(2 * sizeof(rowsCount), in.beg);
    uint8_t data = 0;
    char* dataPtr = (char*)&data;
    for (size_t row = 0; row < rowsCount; ++row) {
        for (size_t col = 0; col < colsCount; ++col) {
            in.read(dataPtr, sizeof(data));
            if (data != (col * rowsCount + row + 1) % 256) {
                PrintFile(argv[1]);
                return 1;
            }
        }
    }
    return 0;
}
Example #8
0
bool PrintFile(const WCHAR *fileName, WCHAR *printerName, bool displayErrors, const WCHAR *settings)
{
    ScopedMem<WCHAR> fileName2(path::Normalize(fileName));
    BaseEngine *engine = EngineManager::CreateEngine(fileName2);
    bool ok = PrintFile(engine, printerName, displayErrors, settings);
    delete engine;
    return ok;
}
Example #9
0
CWebSock::EPageReqResult CWebSock::PrintStaticFile(const CString& sPath, CString& sPageRet, CModule* pModule) {
	SetPaths(pModule);
	CString sFile = m_Template.ExpandFile(sPath.TrimLeft_n("/"));
	DEBUG("About to print [" + sFile+ "]");
	// Either PrintFile() fails and sends an error page or it suceeds and
	// sends a result. In both cases we don't have anything more to do.
	PrintFile(sFile);
	return PAGE_DONE;
}
void VerifyReportPromise(struct Promise *pp)

{ struct Attributes a = {{0}};
  struct CfLock thislock;
  struct Rlist *rp;
  char unique_name[CF_EXPANDSIZE];

a = GetReportsAttributes(pp);

if (strcmp(pp->classes,"any") == 0)
   {
   CfOut(cf_verbose,""," --> Reports promises may not be in class \"any\"");
   return;
   }

snprintf(unique_name,CF_EXPANDSIZE-1,"%s_%d",pp->promiser,pp->lineno);
thislock = AcquireLock(unique_name,VUQNAME,CFSTARTTIME,a,pp,false);

if (thislock.lock == NULL)
   {
   return;
   }

PromiseBanner(pp);

cfPS(cf_verbose,CF_CHG,"",pp,a,"Report: %s", pp->promiser);

if (a.report.to_file)
   {
   CfFOut(a.report.to_file,cf_error,"","%s",pp->promiser);
   }
else
   {
   CfOut(cf_reporting,"","R: %s",pp->promiser);
   }

if (a.report.haveprintfile)
   {
   PrintFile(a,pp);
   }

if (a.report.showstate)
   {
   for (rp = a.report.showstate; rp != NULL; rp=rp->next)
      {
      ShowState(rp->item,a,pp);
      }
   }

if (a.report.havelastseen)
   {
   FriendStatus(a,pp);
   }
    
YieldCurrentLock(thislock);
}
SearchTree
PrintFile( SearchTree TreeNode, FILE *file)
{
	if( TreeNode != NULL) {
		PrintFile(TreeNode->LeftNode,file);

		if(!(strcmp((*TreeNode).strPtr, ""))==0)
		{
			fprintf (file,"(%s,", (*TreeNode).strPtr);
			fprintf (file,"%d) \n", RetrieveWordCount(TreeNode));

			if((*TreeNode).wordCount>MostOccuring)
			{
				MostOccuring = (*TreeNode).wordCount;
				MostNode = (*TreeNode).Element;
				strcpy(MostWord,(*TreeNode).strPtr);
			}
		}

		PrintFile(TreeNode->RightNode,file);
	}
	return 0;
}
Example #12
0
void VerifyReportPromise(Promise *pp)
{
    Attributes a = { {0} };
    CfLock thislock;
    Rlist *rp;
    char unique_name[CF_EXPANDSIZE];

    a = GetReportsAttributes(pp);

    snprintf(unique_name, CF_EXPANDSIZE - 1, "%s_%zu", pp->promiser, pp->offset.line);
    thislock = AcquireLock(unique_name, VUQNAME, CFSTARTTIME, a, pp, false);

    if (thislock.lock == NULL)
    {
        return;
    }

    PromiseBanner(pp);

    cfPS(cf_verbose, CF_CHG, "", pp, a, "Report: %s", pp->promiser);

    if (a.report.to_file)
    {
        CfFOut(a.report.to_file, cf_error, "", "%s", pp->promiser);
    }
    else
    {
        CfOut(cf_reporting, "", "R: %s", pp->promiser);
    }

    if (a.report.haveprintfile)
    {
        PrintFile(a, pp);
    }

    if (a.report.showstate)
    {
        for (rp = a.report.showstate; rp != NULL; rp = rp->next)
        {
            ShowState(rp->item);
        }
    }

    if (a.report.havelastseen)
    {
        /* Do nothing. Deprecated. */
    }

    YieldCurrentLock(thislock);
}
Example #13
0
void __fastcall TEditTiffForm::AppendMenuItemClick(TObject *Sender) {
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
    if (!EditConfig("Добавить")) return;

    if (!PrintFile()) return;

    int pos = tb->GetNPages();
    tb->InsPages(10000);

    tb->SetPage(pos);
    SetupPageComboBox(tb->GetNPages(), tb->GetPage());
    Fog1->Invalidate();
}
Example #14
0
void __fastcall TEditTiffForm::ReplaceMenuItemClick(TObject *Sender) {
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
    if (!EditConfig("Заменить")) return;
    // Application->MessageBox("Якобы заменяет страницы", "Инфо", 0);

    if (!DeleteTicStartEnd()) return;

    if (!PrintFile()) return;

    int pos = tic.Start - 1;
    tb->InsPages(pos);

    tb->SetPage(pos);
    SetupPageComboBox(tb->GetNPages(), tb->GetPage());
    Fog1->Invalidate();

}
Position
writeToFile(SearchTree Tree)
{
	FILE *file;
	file = fopen("output.txt","w");

	//fprintf(file,"%s","This is just an example :)"); /*writes*/
	MostWord = ((char*)malloc(22*sizeof(char)));
	PrintFile(Tree,file);

	//printf("\n Most Occuring = %d",MostOccuring);
	//printf("\n Most Occuring = %d",MostNode);

	printf("\n\n Most Used Word = %s",MostWord);
	fprintf(file,"\n\n Most used word : %s",MostWord);
	fclose(file); /*done!*/
	printf("\n\n File 'output.txt' Created. ");
	//free(MostWord);
	//getchar(); /* pause and wait for key */
	return 0;
}
Example #16
0
int main()
{
    SetWindow();
    Castle ct; // define Castle
    ct.Xstrt = CastleXStrt;
    ct.Ystrt = CastleYStrt;
    ct.W = CastleWidth;
    ct.L = CastleLength;
    int NA = 0, NB = 0, NC = 0, ND = 0;
    int DA = 0, DB = 0, DC = 0, DD = 0;
    int DAL = 0, DBL = 0, DCL = 0, DDL = 0;
    int EnemiesNumber = GetEnemiesNumber(NA, NB, NC, ND);
    Heap *ActiveA=CreateHeap(NA);
    Heap *ActiveB = CreateHeap(NB);
    Heap *ActiveC = CreateHeap(NC);
    Heap *ActiveD = CreateHeap(ND);
    Queue *Inactive = CreateQueue();
    DLL *Dead = CreateDLL();

    Constants C = { 0, 0, 0 };
    if (Read(Inactive, &ct, C))
    {
        int Mode;
        cout << "Please Choose Game Mode: \n1: Interactive Mode\n2: Step-by-step Mode\n3: Silent Mode\n";
        cin >> Mode;
        int Result = 0;
        for (int GameTime = 1; Result == 0; GameTime++)
        {
            Result = SimulateBattle(&ct, Inactive, Dead, ActiveA, ActiveB, ActiveC, ActiveD, GameTime, C, Mode, NA, NB, NC, ND, DA, DB, DC, DD, DAL, DBL, DCL, DDL);
            if (Mode == 1)
                _getch();
            else if (Mode == 2)
                Sleep(1000);
        }
        PrintFile(Dead, &ct,Result,EnemiesNumber);
    }
Example #17
0
CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CString& sPageRet) {
	if (CZNC::Get().GetProtectWebSessions() && GetSession()->GetIP() != GetRemoteIP()) {
		DEBUG("Expected IP: " << GetSession()->GetIP());
		DEBUG("Remote IP:   " << GetRemoteIP());
		PrintErrorPage(403, "Access denied", "This session does not belong to your IP.");
		return PAGE_DONE;
	}

	// Check that they really POSTed from one our forms by checking if they
	// know the "secret" CSRF check value. Don't do this for login since
	// CSRF against the login form makes no sense and the login form does a
	// cookies-enabled check which would break otherwise.
	if (IsPost() && GetParam("_CSRF_Check") != GetCSRFCheck() && sURI != "/login") {
		DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
		DEBUG("Actual _CSRF_Check:   " << GetParam("_CSRF_Check"));
		PrintErrorPage(403, "Access denied", "POST requests need to send "
				"a secret token to prevent cross-site request forgery attacks.");
		return PAGE_DONE;
	}

	SendCookie("SessionId", GetSession()->GetId());

	if (GetSession()->IsLoggedIn()) {
		m_sUser = GetSession()->GetUser()->GetUserName();
		m_bLoggedIn = true;
	}

	// Handle the static pages that don't require a login
	if (sURI == "/") {
		if(!m_bLoggedIn && GetParam("cookie_check", false).ToBool() && GetRequestCookie("SessionId").empty()) {
			GetSession()->AddError("Your browser does not have cookies enabled for this site!");
		}
		return PrintTemplate("index", sPageRet);
	} else if (sURI == "/favicon.ico") {
		return PrintStaticFile("/pub/favicon.ico", sPageRet);
	} else if (sURI == "/robots.txt") {
		return PrintStaticFile("/pub/robots.txt", sPageRet);
	} else if (sURI == "/logout") {
		GetSession()->SetUser(NULL);
		SetLoggedIn(false);
		Redirect("/");

		// We already sent a reply
		return PAGE_DONE;
	} else if (sURI == "/login") {
		if (GetParam("submitted").ToBool()) {
			m_sUser = GetParam("user");
			m_sPass = GetParam("pass");
			m_bLoggedIn = OnLogin(m_sUser, m_sPass);

			// AcceptedLogin()/RefusedLogin() will call Redirect()
			return PAGE_DEFERRED;
		}

		Redirect("/"); // the login form is here
		return PAGE_DONE;
	} else if (sURI.Left(5) == "/pub/") {
		return PrintStaticFile(sURI, sPageRet);
	} else if (sURI.Left(11) == "/skinfiles/") {
		CString sSkinName = sURI.substr(11);
		CString::size_type uPathStart = sSkinName.find("/");
		if (uPathStart != CString::npos) {
			CString sFilePath = sSkinName.substr(uPathStart + 1);
			sSkinName.erase(uPathStart);

			m_Template.ClearPaths();
			m_Template.AppendPath(GetSkinPath(sSkinName) + "pub");

			if (PrintFile(m_Template.ExpandFile(sFilePath))) {
				return PAGE_DONE;
			} else {
				return PAGE_NOTFOUND;
			}
		}
		return PAGE_NOTFOUND;
	} else if (sURI.Left(6) == "/mods/" || sURI.Left(10) == "/modfiles/") {
		ParsePath();
		// Make sure modules are treated as directories
		if (sURI.Right(1) != "/" && sURI.find(".") == CString::npos && sURI.TrimLeft_n("/mods/").TrimLeft_n("/").find("/") == CString::npos) {
			Redirect(sURI + "/");
			return PAGE_DONE;
		}

		CModule *pModule = CZNC::Get().GetModules().FindModule(m_sModName);
		if (!pModule) {
			// Check if GetSession()->GetUser() is NULL and display
			// an error in that case
			if (!ForceLogin())
				return PAGE_DONE;

			pModule = GetSession()->GetUser()->GetModules().FindModule(m_sModName);
		}

		if (!pModule) {
			return PAGE_NOTFOUND;
		} else if (pModule->WebRequiresLogin() && !ForceLogin()) {
			return PAGE_PRINT;
		} else if (pModule->WebRequiresAdmin() && !GetSession()->IsAdmin()) {
			PrintErrorPage(403, "Forbidden", "You need to be an admin to access this module");
			return PAGE_DONE;
		} else if (!pModule->IsGlobal() && pModule->GetUser() != GetSession()->GetUser()) {
			PrintErrorPage(403, "Forbidden", "You must login as " + pModule->GetUser()->GetUserName() + " in order to view this page");
			return PAGE_DONE;
		} else if (pModule->OnWebPreRequest(*this, m_sPage)) {
			return PAGE_DEFERRED;
		}

		VWebSubPages& vSubPages = pModule->GetSubPages();

		for (unsigned int a = 0; a < vSubPages.size(); a++) {
			TWebSubPage& SubPage = vSubPages[a];

			bool bActive = (m_sModName == pModule->GetModName() && m_sPage == SubPage->GetName());

			if (bActive && SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) {
				PrintErrorPage(403, "Forbidden", "You need to be an admin to access this page");
				return PAGE_DONE;
			}
		}

		if (pModule && !pModule->IsGlobal() && (!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) {
			AddModLoop("UserModLoop", *pModule);
		}

		if (sURI.Left(10) == "/modfiles/") {
			m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" + m_sModName + "/files/");
			m_Template.AppendPath(pModule->GetModDataDir() + "/files/");

			if (PrintFile(m_Template.ExpandFile(m_sPage.TrimLeft_n("/")))) {
				return PAGE_PRINT;
			} else {
				return PAGE_NOTFOUND;
			}
		} else {
			SetPaths(pModule, true);

			/* if a module returns false from OnWebRequest, it does not
			   want the template to be printed, usually because it did a redirect. */
			if (pModule->OnWebRequest(*this, m_sPage, m_Template)) {
				// If they already sent a reply, let's assume
				// they did what they wanted to do.
				if (SentHeader()) {
					return PAGE_DONE;
				}
				return PrintTemplate(m_sPage, sPageRet, pModule);
			}

			if (!SentHeader()) {
				PrintErrorPage(404, "Not Implemented", "The requested module does not acknowledge web requests");
			}
			return PAGE_DONE;
		}
	} else {
		CString sPage(sURI.Trim_n("/"));
		if (sPage.length() < 32) {
			for (unsigned int a = 0; a < sPage.length(); a++) {
				unsigned char c = sPage[a];

				if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
					return PAGE_NOTFOUND;
				}
			}

			return PrintTemplate(sPage, sPageRet);
		}
	}

	return PAGE_NOTFOUND;
}
Example #18
0
int main()
{
	FILE *f_teks, *record;
	Tree Teks, nama_f;
	char jawab, judul_f[BUFSIZ], kata[BUFSIZ];

	CreateTree(&Teks);
	CreateTree(&nama_f);
	do
	{
		clrscr();
		gotoxy(17,1);printf ("*=================================================*");
		gotoxy(17,2);printf ("*                    PROGRAM                      *");
		gotoxy(17,3);printf ("*                 STATISTIK KATA                  *");
		gotoxy(17,4);printf ("*=================================================*");
		gotoxy(17,5);printf ("*                  Menu pilihan                   *");
		gotoxy(17,6);printf ("*  1. Tampilkan statistik kata                    *");
		gotoxy(17,7);printf ("*  2. Cari kata yang diinginkan                   *");
		gotoxy(17,8);printf ("*  3. Help                                        *");
		gotoxy(17,9);printf ("*  4. Profil Author                               *");
		gotoxy(17,10);printf("*  5. Exit                                        *");
		gotoxy(17,11);printf("*=================================================*");
		gotoxy(17,12);printf("   Masukkan pilihan Anda ...");
		jawab=getch();
		switch(jawab)
		{
			case '1': clrscr();
						 gotoxy(17,1);printf("*=================================================*");
						 gotoxy(17,2);printf("*                     NAMA FILE                   *");
						 gotoxy(17,3);printf("* (Contoh : sample.txt atau C:\\Folder\\sample.txt) *");
						 gotoxy(17,4);printf("*=================================================*");
						 record = fopen("file", "rb"); //membuka file berisi nama file teks yang pernah dibuka
						 if(record != NULL)
						 {
							printf("\n\t\t   File yang terakhir dibuka :\n");
							while ((fread(&judul_f,sizeof(judul_f),1,record))==1)
							{
								  InsertNode(&nama_f, judul_f);
							}
							PrintfInfo(nama_f);

							printf("\n\t\t*=================================================*");
						 }
						 fclose(record);
						 printf("\n\t\t  Masukkan nama file : "); gets(judul_f);
						 if(!validasifile(judul_f))
						 {
							printf("\n\n\t\t FILE YANG ANDA INPUTKAN BUKAN FILE TEKS");
						 }
						 else
						 {
							f_teks = fopen(judul_f, "r");
							if( f_teks == NULL ) // jika program tidak menemukan file yang ingin dibuka user,
							{
								gotoxy(17,7);printf("  FILE TIDAK DITEMUKAN");
							}
							else
							{
								if(!IsEmptyBTree(Teks))
								{
									Delete(&Teks);
								}
								CreateTree(&Teks);
								clrscr();
								printf("*=============================================================================*\n");
								printf("*                                    ISI FILE                                 *\n");
								printf("*=============================================================================*\n");
								printf("\nNama file : %s\n\n", judul_f);
								PrintFile(judul_f);
								while(!feof(f_teks))
								{
									if(addString(fgetc(f_teks), 0, kata, f_teks)!=0)
									{
										InsertNode(&Teks, kata);
										clear(kata);
									}
								}
								fclose(f_teks);
								record = fopen("file", "ab");  //menyimpan nama file teks yang pernah dibuka ke file
								if(record != NULL)
								{
									fwrite(&judul_f,sizeof(judul_f),1,record);
								}
								fclose(record);
								printf("\n\n\t\t*---------------------------------------------------*");
								printf("\n\t\t Tekan Sembarang Tombol Untuk Melihat Statistik Kata");getch();
								clrscr();
								gotoxy(17,1);printf("*=================================================*");
								gotoxy(17,2);printf("*              STATISTIK KATA                     *");
								gotoxy(17,3);printf("*=================================================*\n\n");
								InOrder(Teks);
							}
						 }
						 break;
			case '2': clrscr();
						 gotoxy(17,1);printf("*=================================================*");
						 gotoxy(17,2);printf("*                  PENCARIAN                      *");
						 gotoxy(17,3);printf("*=================================================*");
						 gotoxy(17,5);printf(" Masukkan kata yang ingin dicari : "); gets(kata);
						 if(IsEmptyBTree(Teks))
						 {
							gotoxy(17,6);printf("  BELUM ADA FILE TEKS YANG DIBUKA");
						 }
						 else
						 {
							Searching(Teks, kata);
						 }
						 break;
			case '3': clrscr(); PrintFile("help.txt"); break;
			case '4': clrscr(); PrintFile("author.txt"); break;
			case '5': clrscr(); gotoxy(34,15); printf("...TERIMA KASIH...");
						 getch();_exit(1);
			default : gotoxy(17,14); printf("   Pilihan yang anda masukkan salah, coba lagi...");
		}

		if (jawab !='5')
			{
				printf("\n\n\n\t\t*-------------------------------------------------*");
				printf("\n\n\t\tTekan Sembarang Tombol Untuk Kembali ke Menu Utama");getch();
			}
	} while(jawab!='5');
	return 0;
}
Example #19
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int retCode = 1;    // by default it's error

#ifdef DEBUG
    // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for
    // regular termination so that leaks aren't checked on exceptions,
    // aborts, etc. where some clean-up might not take place)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
    //_CrtSetBreakAlloc(421);
    TryLoadMemTrace();
#endif

    //BenchMD5();

    DisableDataExecution();
    // ensure that C functions behave consistently under all OS locales
    // (use Win32 functions where localized input or output is desired)
    setlocale(LC_ALL, "C");

    RunUnitTests();

    // don't show system-provided dialog boxes when accessing files on drives
    // that are not mounted (e.g. a: drive without floppy or cd rom drive
    // without a cd).
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
    srand((unsigned int)time(NULL));

    // don't bother sending crash reports when running under Wine
    // as they're not helpful
    if (!RunningUnderWine()) {
        ScopedMem<TCHAR> symDir;
        ScopedMem<TCHAR> tmpDir(path::GetTempPath());
        if (tmpDir)
            symDir.Set(path::Join(tmpDir, _T("SumatraPDF-symbols")));
        else
            symDir.Set(AppGenDataFilename(_T("SumatraPDF-symbols")));
        ScopedMem<TCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME));
        InstallCrashHandler(crashDumpPath, symDir);
    }

    ScopedOle ole;
    InitAllCommonControls();
    ScopedGdiPlus gdiPlus(true);
    mui::Initialize();
    uimsg::Initialize();

    ScopedMem<TCHAR> prefsFilename(GetPrefsFileName());
    if (!file::Exists(prefsFilename)) {
        // guess the ui language on first start
        CurrLangNameSet(Trans::GuessLanguage());
        gFavorites = new Favorites();
    } else {
        assert(gFavorites == NULL);
        Prefs::Load(prefsFilename, gGlobalPrefs, gFileHistory, &gFavorites);
        CurrLangNameSet(gGlobalPrefs.currentLanguage);
    }
    prefsFilename.Set(NULL);

    CommandLineInfo i;
    GetCommandLineInfo(i);

    if (i.showConsole)
        RedirectIOToConsole();
    if (i.makeDefault)
        AssociateExeWithPdfExtension();
    if (i.pathsToBenchmark.Count() > 0) {
        BenchFileOrDir(i.pathsToBenchmark);
        if (i.showConsole)
            system("pause");
    }
    if (i.exitImmediately)
        goto Exit;
    gCrashOnOpen = i.crashOnOpen;

    gGlobalPrefs.bgColor = i.bgColor;
    gGlobalPrefs.fwdSearch.offset = i.fwdSearch.offset;
    gGlobalPrefs.fwdSearch.width = i.fwdSearch.width;
    gGlobalPrefs.fwdSearch.color = i.fwdSearch.color;
    gGlobalPrefs.fwdSearch.permanent = i.fwdSearch.permanent;
    gGlobalPrefs.escToExit = i.escToExit;
    gGlobalPrefs.cbxR2L = i.cbxR2L;
    gPolicyRestrictions = GetPolicies(i.restrictedUse);
    gRenderCache.colorRange[0] = i.colorRange[0];
    gRenderCache.colorRange[1] = i.colorRange[1];
    DebugGdiPlusDevice(gUseGdiRenderer);
    DebugAlternateChmEngine(!gUseEbookUI);

    if (i.inverseSearchCmdLine) {
        str::ReplacePtr(&gGlobalPrefs.inverseSearchCmdLine, i.inverseSearchCmdLine);
        gGlobalPrefs.enableTeXEnhancements = true;
    }
    CurrLangNameSet(i.lang);

    if (!RegisterWinClass(hInstance))
        goto Exit;
    if (!InstanceInit(hInstance, nCmdShow))
        goto Exit;

    if (i.hwndPluginParent) {
        if (!SetupPluginMode(i))
            goto Exit;
    }

    if (i.printerName) {
        // note: this prints all PDF files. Another option would be to
        // print only the first one
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings);
            if (!ok)
                retCode++;
        }
        --retCode; // was 1 if no print failures, turn 1 into 0
        goto Exit;
    }

    if (i.fileNames.Count() == 0 && gGlobalPrefs.rememberOpenedFiles && gGlobalPrefs.showStartPage) {
        // make the shell prepare the image list, so that it's ready when the first window's loaded
        SHFILEINFO sfi;
        SHGetFileInfo(_T(".pdf"), 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    }

    WindowInfo *win = NULL;
    bool isFirstWin = true;

    for (size_t n = 0; n < i.fileNames.Count(); n++) {
        if (i.reuseInstance && !i.printDialog) {
            OpenUsingDde(i.fileNames.At(n), i, isFirstWin);
        } else {
            win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin);
            if (!win) {
                retCode++;
                continue;
            }
            if (i.printDialog)
                OnMenuPrint(win, i.exitOnPrint);
        }
        isFirstWin = false;
    }
    if (i.fileNames.Count() > 0 && isFirstWin) {
        // failed to create any window, even though there
        // were files to load (or show a failure message for)
        goto Exit;
    }

    if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitOnPrint)
        goto Exit;

    if (isFirstWin) {
        win = CreateAndShowWindowInfo();
        if (!win)
            goto Exit;
    }

    UpdateUITextForLanguage(); // needed for RTL languages
    if (isFirstWin)
        UpdateToolbarAndScrollbarState(*win);

    // Make sure that we're still registered as default,
    // if the user has explicitly told us to be
    if (gGlobalPrefs.pdfAssociateShouldAssociate && win)
        RegisterForPdfExtentions(win->hwndFrame);

    if (gGlobalPrefs.enableAutoUpdate && gWindows.Count() > 0)
        AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true);

#ifndef THREAD_BASED_FILEWATCH
    const UINT_PTR timerID = SetTimer(NULL, -1, FILEWATCH_DELAY_IN_MS, NULL);
#endif

    if (i.stressTestPath) {
        gIsStressTesting = true;
        StartStressTest(win, i.stressTestPath, i.stressTestFilter,
                        i.stressTestRanges, i.stressTestCycles, &gRenderCache);
    }

    retCode = RunMessageLoop();

#ifndef THREAD_BASED_FILEWATCH
    KillTimer(NULL, timerID);
#endif

    CleanUpThumbnailCache(gFileHistory);

Exit:
    while (gWindows.Count() > 0) {
        DeleteWindowInfo(gWindows.At(0));
    }
    while (gEbookWindows.Count() > 0) {
        DeleteEbookWindow(gEbookWindows.At(0), true);
    }

#ifndef DEBUG
    // leave all the remaining clean-up to the OS
    // (as recommended for a quick exit)
    ExitProcess(retCode);
#endif

    DeleteObject(gBrushNoDocBg);
    DeleteObject(gBrushLogoBg);
    DeleteObject(gBrushAboutBg);
    DeleteObject(gDefaultGuiFont);
    DeleteBitmap(gBitmapReloadingCue);

    delete gFavorites;

    mui::Destroy();

    DrainUiMsgQueue();
    uimsg::Destroy();

    // it's still possible to crash after this (destructors of static classes,
    // atexit() code etc.) point, but it's very unlikely
    if (!RunningUnderWine())
        UninstallCrashHandler();

#ifdef DEBUG
    // output leaks after all destructors of static objects have run
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

    return retCode;
}
Example #20
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int retCode = 1;    // by default it's error

#ifdef DEBUG
    // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for
    // regular termination so that leaks aren't checked on exceptions,
    // aborts, etc. where some clean-up might not take place)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
    //_CrtSetBreakAlloc(421);
    TryLoadMemTrace();
#endif

    DisableDataExecution();
    // ensure that C functions behave consistently under all OS locales
    // (use Win32 functions where localized input or output is desired)
    setlocale(LC_ALL, "C");
    // don't show system-provided dialog boxes when accessing files on drives
    // that are not mounted (e.g. a: drive without floppy or cd rom drive
    // without a cd).
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(DEBUG) || defined(SVN_PRE_RELEASE_VER)
    if (str::StartsWith(lpCmdLine, "/tester")) {
        extern int TesterMain(); // in Tester.cpp
        return TesterMain();
    }

    if (str::StartsWith(lpCmdLine, "/regress")) {
        extern int RegressMain(); // in Regress.cpp
        return RegressMain();
    }
#endif
#ifdef SUPPORTS_AUTO_UPDATE
    if (str::StartsWith(lpCmdLine, "-autoupdate")) {
        bool quit = AutoUpdateMain();
        if (quit)
            return 0;
    }
#endif

    RunUnitTests();

    srand((unsigned int)time(NULL));

    {
        ScopedMem<WCHAR> symDir;
        ScopedMem<WCHAR> tmpDir(path::GetTempPath());
        if (tmpDir)
            symDir.Set(path::Join(tmpDir, L"SumatraPDF-symbols"));
        else
            symDir.Set(AppGenDataFilename(L"SumatraPDF-symbols"));
        ScopedMem<WCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME));
        InstallCrashHandler(crashDumpPath, symDir);
    }

    ScopedOle ole;
    InitAllCommonControls();
    ScopedGdiPlus gdiPlus(true);
    mui::Initialize();
    uitask::Initialize();

    LoadPrefs();

    CommandLineInfo i;
    GetCommandLineInfo(i);

    SetCurrentLang(i.lang ? i.lang : gGlobalPrefs->currLangCode);

    if (i.showConsole)
        RedirectIOToConsole();
    if (i.makeDefault)
        AssociateExeWithPdfExtension();
    if (i.pathsToBenchmark.Count() > 0) {
        BenchFileOrDir(i.pathsToBenchmark);
        if (i.showConsole)
            system("pause");
    }
    if (i.exitImmediately)
        goto Exit;
    gCrashOnOpen = i.crashOnOpen;

    gUserPrefs->mainWindowBackground = i.bgColor;
    if (gUserPrefs->forwardSearch.highlightColor != i.forwardSearch.highlightColor ||
        gUserPrefs->forwardSearch.highlightOffset != i.forwardSearch.highlightOffset ||
        gUserPrefs->forwardSearch.highlightPermanent != i.forwardSearch.highlightPermanent ||
        gUserPrefs->forwardSearch.highlightWidth != i.forwardSearch.highlightWidth) {
        gGlobalPrefs->enableTeXEnhancements = true;
    }
    gUserPrefs->forwardSearch = i.forwardSearch;
    gUserPrefs->escToExit = i.escToExit;
    gGlobalPrefs->cbxR2L = i.cbxR2L;
    gPolicyRestrictions = GetPolicies(i.restrictedUse);
    gRenderCache.colorRange[0] = i.colorRange[0];
    gRenderCache.colorRange[1] = i.colorRange[1];
    DebugGdiPlusDevice(gUseGdiRenderer);
    DebugAlternateChmEngine(gUserPrefs->ebookUI.traditionalEbookUI);

    if (i.inverseSearchCmdLine) {
        str::ReplacePtr(&gGlobalPrefs->inverseSearchCmdLine, i.inverseSearchCmdLine);
        gGlobalPrefs->enableTeXEnhancements = true;
    }

    if (!RegisterWinClass(hInstance))
        goto Exit;
    if (!InstanceInit(hInstance, nCmdShow))
        goto Exit;

    if (i.hwndPluginParent) {
        if (!SetupPluginMode(i))
            goto Exit;
    }

    if (i.printerName) {
        // note: this prints all PDF files. Another option would be to
        // print only the first one
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings);
            if (!ok)
                retCode++;
        }
        --retCode; // was 1 if no print failures, turn 1 into 0
        goto Exit;
    }

    if (i.fileNames.Count() == 0 && gGlobalPrefs->rememberOpenedFiles && gGlobalPrefs->showStartPage) {
        // make the shell prepare the image list, so that it's ready when the first window's loaded
        SHFILEINFO sfi;
        SHGetFileInfo(L".pdf", 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    }

    if (!i.reuseInstance && gUserPrefs->reuseInstance && FindWindow(FRAME_CLASS_NAME, 0))
        i.reuseInstance = true;

    WindowInfo *win = NULL;
    bool isFirstWin = true;

    for (size_t n = 0; n < i.fileNames.Count(); n++) {
        if (i.reuseInstance && !i.printDialog) {
            OpenUsingDde(i.fileNames.At(n), i, isFirstWin);
        } else {
            win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin);
            if (!win) {
                retCode++;
                continue;
            }
            if (i.printDialog)
                OnMenuPrint(win, i.exitWhenDone);
        }
        isFirstWin = false;
    }
    if (i.fileNames.Count() > 0 && isFirstWin) {
        // failed to create any window, even though there
        // were files to load (or show a failure message for)
        goto Exit;
    }

    if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitWhenDone)
        goto Exit;

    if (isFirstWin) {
        win = CreateAndShowWindowInfo();
        if (!win)
            goto Exit;
    }

    UpdateUITextForLanguage(); // needed for RTL languages
    if (isFirstWin)
        UpdateToolbarAndScrollbarState(*win);

    // Make sure that we're still registered as default,
    // if the user has explicitly told us to be
    if (gGlobalPrefs->pdfAssociateShouldAssociate && win)
        RegisterForPdfExtentions(win->hwndFrame);

    if (gGlobalPrefs->enableAutoUpdate && gWindows.Count() > 0)
        AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true);

    if (i.stressTestPath)
        StartStressTest(&i, win, &gRenderCache);

    if (gFileHistory.Get(0)) {
        gFileExistenceChecker = new FileExistenceChecker();
        gFileExistenceChecker->Start();
    }

    retCode = RunMessageLoop();

    CleanUpThumbnailCache(gFileHistory);

Exit:
    while (gWindows.Count() > 0) {
        DeleteWindowInfo(gWindows.At(0));
    }
    while (gEbookWindows.Count() > 0) {
        DeleteEbookWindow(gEbookWindows.At(0), true);
    }

#ifndef DEBUG

    // leave all the remaining clean-up to the OS
    // (as recommended for a quick exit)
    ExitProcess(retCode);

#else

    CrashIf(gFileExistenceChecker);

    DeleteObject(gBrushNoDocBg);
    DeleteObject(gBrushLogoBg);
    DeleteObject(gBrushAboutBg);
    DeleteObject(gDefaultGuiFont);
    DeleteBitmap(gBitmapReloadingCue);

    gFileHistory.UpdateStatesSource(NULL);
    DeleteGlobalPrefs(gGlobalPrefs);

    mui::Destroy();
    uitask::Destroy();
    trans::Destroy();

    // it's still possible to crash after this (destructors of static classes,
    // atexit() code etc.) point, but it's very unlikely
    UninstallCrashHandler();

    // output leaks after all destructors of static objects have run
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    return retCode;
#endif
}
Example #21
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int retCode = 1;    // by default it's error

#ifdef DEBUG
    // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for
    // regular termination so that leaks aren't checked on exceptions,
    // aborts, etc. where some clean-up might not take place)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
    //_CrtSetBreakAlloc(421);
    TryLoadMemTrace();
#endif

    DisableDataExecution();
    // ensure that C functions behave consistently under all OS locales
    // (use Win32 functions where localized input or output is desired)
    setlocale(LC_ALL, "C");
    // don't show system-provided dialog boxes when accessing files on drives
    // that are not mounted (e.g. a: drive without floppy or cd rom drive
    // without a cd).
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(DEBUG) || defined(SVN_PRE_RELEASE_VER)
    if (str::StartsWith(lpCmdLine, "/tester")) {
        extern int TesterMain(); // in Tester.cpp
        return TesterMain();
    }

    if (str::StartsWith(lpCmdLine, "/regress")) {
        extern int RegressMain(); // in Regress.cpp
        return RegressMain();
    }
#endif
#ifdef SUPPORTS_AUTO_UPDATE
    if (str::StartsWith(lpCmdLine, "-autoupdate")) {
        bool quit = AutoUpdateMain();
        if (quit)
            return 0;
    }
#endif

    srand((unsigned int)time(NULL));

    // load uiautomationcore.dll before installing crash handler (i.e. initializing
    // dbghelp.dll), so that we get function names/offsets in GetCallstack()
    uia::Initialize();
#ifdef DEBUG
    dbghelp::RememberCallstackLogs();
#endif

    SetupCrashHandler();

    ScopedOle ole;
    InitAllCommonControls();
    ScopedGdiPlus gdiPlus(true);
    mui::Initialize();
    uitask::Initialize();

    prefs::Load();

    CommandLineInfo i(GetCommandLine());

    SetCurrentLang(i.lang ? i.lang : gGlobalPrefs->uiLanguage);

    // This allows ad-hoc comparison of gdi, gdi+ and gdi+ quick when used
    // in layout
#if 0
    RedirectIOToConsole();
    BenchEbookLayout(L"C:\\kjk\\downloads\\pg12.mobi");
    system("pause");
    goto Exit;
#endif

    if (i.showConsole) {
        RedirectIOToConsole();
        RedirectDllIOToConsole();
    }
    if (i.makeDefault)
        AssociateExeWithPdfExtension();
    if (i.pathsToBenchmark.Count() > 0) {
        BenchFileOrDir(i.pathsToBenchmark);
        if (i.showConsole)
            system("pause");
    }
    if (i.exitImmediately)
        goto Exit;
    gCrashOnOpen = i.crashOnOpen;

    gPolicyRestrictions = GetPolicies(i.restrictedUse);
    GetFixedPageUiColors(gRenderCache.textColor, gRenderCache.backgroundColor);
    DebugGdiPlusDevice(gUseGdiRenderer);

    if (!RegisterWinClass())
        goto Exit;

    CrashIf(hInstance != GetModuleHandle(NULL));
    if (!InstanceInit(nCmdShow))
        goto Exit;

    if (i.hwndPluginParent) {
        if (!SetupPluginMode(i))
            goto Exit;
    }

    if (i.printerName) {
        // note: this prints all PDF files. Another option would be to
        // print only the first one
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings);
            if (!ok)
                retCode++;
        }
        --retCode; // was 1 if no print failures, turn 1 into 0
        goto Exit;
    }

    bool showStartPage = i.fileNames.Count() == 0 && gGlobalPrefs->rememberOpenedFiles && gGlobalPrefs->showStartPage;
    if (showStartPage) {
        // make the shell prepare the image list, so that it's ready when the first window's loaded
        SHFILEINFO sfi;
        SHGetFileInfo(L".pdf", 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    }

    if (gGlobalPrefs->reopenOnce) {
        WStrVec moreFileNames;
        ParseCmdLine(gGlobalPrefs->reopenOnce, moreFileNames);
        moreFileNames.Reverse();
        for (WCHAR **fileName = moreFileNames.IterStart(); fileName; fileName = moreFileNames.IterNext()) {
            i.fileNames.Append(*fileName);
        }
        moreFileNames.RemoveAt(0, moreFileNames.Count());
        str::ReplacePtr(&gGlobalPrefs->reopenOnce, NULL);
    }

    HANDLE hMutex = NULL;
    HWND hPrevWnd = NULL;
    if (i.printDialog || i.stressTestPath || gPluginMode) {
        // TODO: pass print request through to previous instance?
    }
    else if (i.reuseDdeInstance) {
        hPrevWnd = FindWindow(FRAME_CLASS_NAME, NULL);
    }
    else if (gGlobalPrefs->reuseInstance || gGlobalPrefs->useTabs) {
        hPrevWnd = FindPrevInstWindow(&hMutex);
    }
    if (hPrevWnd) {
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            OpenUsingDde(hPrevWnd, i.fileNames.At(n), i, 0 == n);
        }
        goto Exit;
    }

    WindowInfo *win = NULL;
    for (size_t n = 0; n < i.fileNames.Count(); n++) {
        win = LoadOnStartup(i.fileNames.At(n), i, !win);
        if (!win) {
            retCode++;
            continue;
        }
        if (i.printDialog)
            OnMenuPrint(win, i.exitWhenDone);
    }
    if (i.fileNames.Count() > 0 && !win) {
        // failed to create any window, even though there
        // were files to load (or show a failure message for)
        goto Exit;
    }
    if (i.printDialog && i.exitWhenDone)
        goto Exit;

    if (!win) {
        win = CreateAndShowWindowInfo();
        if (!win)
            goto Exit;
    }

    UpdateUITextForLanguage(); // needed for RTL languages
    if (win->IsAboutWindow()) {
        // TODO: shouldn't CreateAndShowWindowInfo take care of this?
        UpdateToolbarAndScrollbarState(*win);
    }

    // Make sure that we're still registered as default,
    // if the user has explicitly told us to be
    if (gGlobalPrefs->associatedExtensions)
        RegisterForPdfExtentions(win->hwndFrame);

    if (i.stressTestPath) {
        // don't save file history and preference changes
        gPolicyRestrictions = (gPolicyRestrictions | Perm_RestrictedUse) & ~Perm_SavePreferences;
        RebuildMenuBarForWindow(win);
        StartStressTest(&i, win, &gRenderCache);
    }

    if (gGlobalPrefs->checkForUpdates)
        UpdateCheckAsync(win, true);

    // only hide newly missing files when showing the start page on startup
    if (showStartPage && gFileHistory.Get(0)) {
        gFileExistenceChecker = new FileExistenceChecker();
        gFileExistenceChecker->Start();
    }
    // call this once it's clear whether Perm_SavePreferences has been granted
    prefs::RegisterForFileChanges();

    retCode = RunMessageLoop();

    SafeCloseHandle(&hMutex);
    CleanUpThumbnailCache(gFileHistory);

Exit:
    prefs::UnregisterForFileChanges();

    while (gWindows.Count() > 0) {
        DeleteWindowInfo(gWindows.At(0));
    }

#ifndef DEBUG

    // leave all the remaining clean-up to the OS
    // (as recommended for a quick exit)
    ExitProcess(retCode);

#else

    DeleteObject(GetDefaultGuiFont());
    DeleteBitmap(gBitmapReloadingCue);
    DeleteSplitterBrush();

    // wait for FileExistenceChecker to terminate
    // (which should be necessary only very rarely)
    while (gFileExistenceChecker) {
        Sleep(10);
        uitask::DrainQueue();
    }

    mui::Destroy();
    uitask::Destroy();
    trans::Destroy();

    SaveCallstackLogs();
    dbghelp::FreeCallstackLogs();

    // must be after uitask::Destroy() because we might have queued prefs::Reload()
    // which crashes if gGlobalPrefs is freed
    gFileHistory.UpdateStatesSource(NULL);
    DeleteGlobalPrefs(gGlobalPrefs);

    // it's still possible to crash after this (destructors of static classes,
    // atexit() code etc.) point, but it's very unlikely
    UninstallCrashHandler();

    // output leaks after all destructors of static objects have run
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    return retCode;
#endif
}
Example #22
0
void VerifyReportPromise(Promise *pp)
{
    Attributes a = { {0} };
    CfLock thislock;
    Rlist *rp;
    char unique_name[CF_EXPANDSIZE];

    a = GetReportsAttributes(pp);

    snprintf(unique_name, CF_EXPANDSIZE - 1, "%s_%zu", pp->promiser, pp->offset.line);
    thislock = AcquireLock(unique_name, VUQNAME, CFSTARTTIME, a, pp, false);

    // Handle return values before locks, as we always do this

    if (a.report.result)
    {
        // User-unwritable value last-result contains the useresult
        if (strlen(a.report.result) > 0)
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result[%s]", a.report.result);
        }
        else
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result");
        }

        NewScalar(pp->bundle, unique_name, pp->promiser, cf_str);
        return;
    }
       
    // Now do regular human reports
    
    if (thislock.lock == NULL)
    {
        return;
    }

    PromiseBanner(pp);

    cfPS(cf_verbose, CF_CHG, "", pp, a, "Report: %s", pp->promiser);

    if (a.report.to_file)
    {
        CfFOut(a.report.to_file, cf_error, "", "%s", pp->promiser);
    }
    else
    {
        CfOut(cf_reporting, "", "R: %s", pp->promiser);
    }

    if (a.report.haveprintfile)
    {
        PrintFile(a, pp);
    }

    if (a.report.showstate)
    {
        for (rp = a.report.showstate; rp != NULL; rp = rp->next)
        {
            ShowState(rp->item);
        }
    }

    if (a.report.havelastseen)
    {
        /* Do nothing. Deprecated. */
    }

    YieldCurrentLock(thislock);
}
Example #23
0
void VerifyReportPromise(EvalContext *ctx, Promise *pp)
{
    Attributes a = { {0} };
    CfLock thislock;
    char unique_name[CF_EXPANDSIZE];

    a = GetReportsAttributes(ctx, pp);

    snprintf(unique_name, CF_EXPANDSIZE - 1, "%s_%zu", pp->promiser, pp->offset.line);
    thislock = AcquireLock(ctx, unique_name, VUQNAME, CFSTARTTIME, a.transaction, pp, false);

    // Handle return values before locks, as we always do this

    if (a.report.result)
    {
        // User-unwritable value last-result contains the useresult
        if (strlen(a.report.result) > 0)
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result[%s]", a.report.result);
        }
        else
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result");
        }

        VarRef *ref = VarRefParseFromBundle(unique_name, PromiseGetBundle(pp));
        EvalContextVariablePut(ctx, ref, (Rval) {
            pp->promiser, RVAL_TYPE_SCALAR
        }, DATA_TYPE_STRING);
        VarRefDestroy(ref);
        return;
    }

    // Now do regular human reports

    if (thislock.lock == NULL)
    {
        return;
    }

    PromiseBanner(pp);

    if (a.transaction.action == cfa_warn)
    {
        cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_WARN, pp, a, "Need to repair reports promise: %s", pp->promiser);
        YieldCurrentLock(thislock);
        return;
    }

    cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Report: %s", pp->promiser);

    if (a.report.to_file)
    {
        ReportToFile(a.report.to_file, pp->promiser);
    }
    else
    {
        Log(LOG_LEVEL_NOTICE, "R: %s", pp->promiser);
    }

    if (a.report.haveprintfile)
    {
        PrintFile(ctx, a, pp);
    }

    if (a.report.showstate)
    {
        /* Do nothing. Deprecated. */
    }

    if (a.report.havelastseen)
    {
        /* Do nothing. Deprecated. */
    }

    YieldCurrentLock(thislock);
}
Example #24
0
File: Text.c Project: atrniv/CLIPS
static void text_OnCommand(
  HWND hwnd, 
  int id, 
  HWND hctl, 
  UINT codeNotify)
  {	 
   switch (id) 
	 {
      case ID_EDIT_SET_FONT:
        text_OnFont(hwnd);
        return;

      case ID_EDIT_BALANCE:
        Balance(GetDlgItem(hwnd,ID_EDIT_CONTROL));
        return;

      case ID_EDIT_COMMENT:
        DoComment(GetDlgItem(hwnd,ID_EDIT_CONTROL));
        return;

      case ID_EDIT_UNCOMMENT:
        DoUncomment(GetDlgItem(hwnd,ID_EDIT_CONTROL));
        return;
        
      case ID_HELP_COMPLETE:
        EditComplete(GetDlgItem(hwnd,ID_EDIT_CONTROL));
        return;
       
      case ID_EDIT_UNDO:
        FORWARD_WM_UNDO(GetDlgItem(hwnd, ID_EDIT_CONTROL), 
		 						SendMessage);
        return;
        
      case ID_EDIT_CUT:
        FORWARD_WM_CUT(GetDlgItem(hwnd, ID_EDIT_CONTROL), 
		 						SendMessage);
        return;
         
      case ID_EDIT_COPY:
        FORWARD_WM_COPY(GetDlgItem(hwnd, ID_EDIT_CONTROL), 
		 						SendMessage);
        return;
        
      case ID_EDIT_PASTE:
        FORWARD_WM_PASTE(GetDlgItem(hwnd, ID_EDIT_CONTROL), 
		 						SendMessage);
		FixTextLineEndings(GetDlgItem(hwnd, ID_EDIT_CONTROL));
        return;
         
      case ID_EDIT_CLEAR:
        FORWARD_WM_CLEAR(GetDlgItem(hwnd, ID_EDIT_CONTROL), 
		 						SendMessage);
        return;
         
      case ID_EDIT_SELECT_ALL:
        Edit_SetSel(GetDlgItem(hwnd, ID_EDIT_CONTROL), 0, -1);
        return;
                
      case ID_EDIT_CONTROL:
        text_OnEdit(hwnd,id,hctl,codeNotify);
        return;

      case ID_BUFFER_FIND:
	    SetUpSearch(GetDlgItem(hwnd,ID_EDIT_CONTROL),0);
        return;
        
      case ID_BUFFER_REPLACE:
	    SetUpSearch(GetDlgItem(hwnd,ID_EDIT_CONTROL),1);
        return;
        
      case ID_FILE_PRINT:
	    PrintFile(hwnd);
	    return;
	    
      case ID_FILE_SAVE:
        text_Save(hwnd);
        return;

      case  ID_FILE_SAVE_AS:
        text_SaveAs(hwnd);
        return;
        
      case ID_BUFFER_LOAD:
      case ID_BUFFER_BATCH:
      case ID_BUFFER_LOAD_BUFFER:
        LoadBatchBufferSelection(GetDlgItem(hwnd,ID_EDIT_CONTROL),id);
        return;
	 } 
   
   FORWARD_WM_COMMAND(hwnd, id, hctl, codeNotify, DefMDIChildProc);
  }
Example #25
0
int main(int argc, char* argv[])
{
	bool all = false;
	const char* argv0 = argv[0];
	for ( int i = 1; i < argc; i++ )
	{
		const char* arg = argv[i];
		if ( arg[0] != '-' || !arg[1] )
			continue;
		argv[i] = NULL;
		if ( !strcmp(arg, "--") )
			break;
		if ( arg[1] != '-' )
		{
			char c;
			while ( (c = *++arg) ) switch ( c )
			{
			default:
				fprintf(stderr, "%s: unknown option -- '%c'\n", argv0, c);
				help(stderr, argv0);
				exit(1);
			}
		}
		else if ( !strcmp(arg, "--help") )
			help(stdout, argv0), exit(0);
		else if ( !strcmp(arg, "--version") )
			version(stdout, argv0), exit(0);
		else if ( !strcmp(arg, "-a") )
			all = true;
		else
		{
			fprintf(stderr, "%s: unknown option: %s\n", argv0, arg);
			help(stderr, argv0);
			exit(1);
		}
	}

	compact_arguments(&argc, &argv);

	if ( argc == 1 )
		error(1, 0, "No initrd specified");
	const char* initrd = argv[1];
	if ( argc == 2 )
		error(1, 0, "No command specified");
	const char* cmd = argv[2];
	if ( argc == 3 )
		error(1, 0, "No path specified");
	const char* path = argv[3];

	int fd = open(initrd, O_RDONLY);
	if ( fd < 0 ) { error(1, errno, "open: %s", initrd); }

	initrd_superblock_t* sb = GetSuperBlock(fd);
	if ( !sb ) { error(1, errno, "read: %s", initrd); }

	if ( path[0] != '/' ) { error(1, ENOENT, "%s", path); }

	initrd_inode_t* root = GetInode(fd, sb, sb->root);
	if ( !root ) { error(1, errno, "read: %s", initrd); }

	initrd_inode_t* inode = ResolvePath(fd, sb, root, path+1);
	if ( !inode ) { error(1, errno, "%s", path); }

	free(root);

	if ( !strcmp(cmd, "cat") )
	{
		if ( !PrintFile(fd, sb, inode) ) { error(1, errno, "%s", path); }
	}
	else if ( !strcmp(cmd, "ls") )
	{
		initrd_inode_t* dir = inode;
		if ( !ListDirectory(fd, sb, dir, all) ) { error(1, errno, "%s", path); }
	}
	else
	{
		fprintf(stderr, "%s: unrecognized command: %s", argv0, cmd);
		exit(1);
	}

	free(inode);
	free(sb);
	close(fd);

	return 0;
}
Example #26
0
int main(int argc, char* argv[]) {
    if (argc < 2) {
        doHelp(argv[0]);
        return 1;
    }

    OperationMode mode = kModeUpdate;
    std::list<plString> addPaths;
    std::list<plString> delPaths;
    std::list<plString> sumFiles;

    for (int i = 1; i < argc; i++) {
        if (argv[i][0] == '-') {
            if (strcmp(argv[i], "-L") == 0) {
                mode = kModeList;
            } else if (strcmp(argv[i], "-i") == 0) {
                mode = kModeManual;
                if (++i >= argc) {
                    fprintf(stderr, "Error: Expected filename\n");
                    return 1;
                }
                addPaths.push_back(argv[i]);
            } else if (strcmp(argv[i], "-d") == 0) {
                mode = kModeManual;
                if (++i >= argc) {
                    fprintf(stderr, "Error: Expected filename\n");
                    return 1;
                }
                delPaths.push_back(argv[i]);
            } else if (strcmp(argv[i], "-c") == 0) {
                s_createFile = true;
            } else if (strcmp(argv[i], "-y") == 0) {
                s_autoYes = true;
            } else if (strcmp(argv[i], "-old") == 0) {
                s_oldFormat = true;
            } else if (strcmp(argv[i], "--help") == 0) {
                doHelp(argv[0]);
                return 0;
            } else {
                fprintf(stderr, "Error: Unrecognized option %s\n", argv[i]);
                return 1;
            }
        } else {
            sumFiles.push_back(argv[i]);
        }
    }

    if (sumFiles.empty()) {
        fprintf(stderr, "Error: No sum files specified\n");
        return 1;
    }
    if (s_createFile && mode == kModeList) {
        fprintf(stderr, "Error: -c and -L options cannot be combined\n");
        return 1;
    }

    switch (mode) {
    case kModeUpdate:
        for (std::list<plString>::iterator fn = sumFiles.begin(); fn != sumFiles.end(); fn++) {
            if (UpdateSums(*fn))
                printf("Successfully updated %s\n", fn->cstr());
        }
        break;
    case kModeList:
        for (std::list<plString>::iterator fn = sumFiles.begin(); fn != sumFiles.end(); fn++) {
            printf("%s:\n", fn->cstr());
            try {
                plEncryptedStream S;
                if (!S.open(*fn, fmRead, plEncryptedStream::kEncAuto)) {
                    fprintf(stderr, "Could not open file %s\n", fn->cstr());
                    continue;
                }
                SumFile sum;
                sum.read(&S);
                S.close();

                std::vector<SumEntry>::iterator it;
                for (it = sum.fEntries.begin(); it != sum.fEntries.end(); it++)
                    PrintFile(*it, ' ');
                printf("\n");
            } catch (hsException& e) {
                fprintf(stderr, "%s:%ld: %s\n", e.File(), e.Line(), e.what());
                return 1;
            } catch (...) {
                fprintf(stderr, "An unknown error occured\n");
                return 1;
            }
        }
        break;
    case kModeManual:
        if (sumFiles.size() != 1) {
            fprintf(stderr, "Error: You must specify exactly ONE sumfile for\n");
            fprintf(stderr, "-i and -d operations\n");
            return 1;
        }
        try {
            bool isUpdated = false;
            SumFile sum;
            plEncryptedStream S;
            plEncryptedStream::EncryptionType eType = plEncryptedStream::kEncXtea;
            if (!s_createFile) {
                if (!S.open(sumFiles.front(), fmRead, plEncryptedStream::kEncAuto)) {
                    fprintf(stderr, "Could not open file %s\n", sumFiles.front().cstr());
                    return 1;
                }
                eType = S.getEncType();
                sum.read(&S);
                S.close();
            } else {
                isUpdated = true;
            }

            std::list<plString>::iterator pi;
            std::vector<SumEntry>::iterator it;
            for (pi = delPaths.begin(); pi != delPaths.end(); pi++) {
                bool found = false;
                it = sum.fEntries.begin();
                while (it != sum.fEntries.end()) {
                    if (it->fPath == *pi) {
                        PrintFile(*it, '-');
                        it = sum.fEntries.erase(it);
                        found = true;
                        isUpdated = true;
                    } else {
                        ++it;
                    }
                }
                if (!found)
                    fprintf(stderr, "Warning: path '%s' not found\n", pi->cstr());
            }

            for (pi = addPaths.begin(); pi != addPaths.end(); pi++) {
                hsFileStream* IS = FindFilePath(*pi, "");
                if (IS == NULL) {
                    fprintf(stderr, "Warning: path '%s' not found\n", pi->cstr());
                    continue;
                }

                SumEntry ent;
                ent.fPath = GetInternalName(*pi);
                ent.fHash = plMD5::hashStream(IS);
                ent.fTimestamp = IS->getModTime();
                bool found = false;
                it = sum.fEntries.begin();
                while (it != sum.fEntries.end()) {
                    if (it->fPath == *pi) {
                        found = true;
                        if (it->fHash != ent.fHash) {
                            PrintFile(*it, '*');
                            it->fHash = ent.fHash;
                            it->fTimestamp = ent.fTimestamp;
                            isUpdated = true;
                        } else {
                            PrintFile(*it, ' ');
                        }
                    }
                    ++it;
                }
                if (!found) {
                    PrintFile(ent, '+');
                    sum.fEntries.push_back(ent);
                    if (IS != NULL)
                        delete IS;
                    isUpdated = true;
                }
            }

            if (isUpdated) {
                if (!S.open(sumFiles.front(), fmWrite, eType)) {
                    fprintf(stderr, "Error: Could not open %s for writing!\n",
                            sumFiles.front().cstr());
                    return 1;
                }
                sum.write(&S);
                S.close();
                printf("Successfully %s %s\n",
                       s_createFile ? "created" : "updated",
                       sumFiles.front().cstr());
            }
        } catch (hsException& e) {
            fprintf(stderr, "%s:%ld: %s\n", e.File(), e.Line(), e.what());
            return 1;
        } catch (...) {
            fprintf(stderr, "An unknown error occured\n");
            return 1;
        }
        break;
    }

    return 0;
}
Example #27
0
void OnMenuPrint(WindowInfo *win, bool waitForCompletion)
{
    // we remember some printer settings per process
    static ScopedMem<DEVMODE> defaultDevMode;
    static PrintScaleAdv defaultScaleAdv = PrintScaleShrink;
    static bool defaultAsImage = false;

    static bool hasDefaults = false;
    if (!hasDefaults) {
        hasDefaults = true;
        defaultAsImage = gGlobalPrefs->printerDefaults.printAsImage;
        if (str::EqI(gGlobalPrefs->printerDefaults.printScale, "fit"))
            defaultScaleAdv = PrintScaleFit;
        else if (str::EqI(gGlobalPrefs->printerDefaults.printScale, "none"))
            defaultScaleAdv = PrintScaleNone;
    }

    bool printSelection = false;
    Vec<PRINTPAGERANGE> ranges;
    PRINTER_INFO_2 printerInfo = { 0 };

    if (!HasPermission(Perm_PrinterAccess))
        return;

    if (win->AsChm()) {
        // the Print dialog allows access to the file system, so fall back
        // to printing the entire document without dialog if that isn't desired
        bool showUI = HasPermission(Perm_DiskAccess);
        win->AsChm()->PrintCurrentPage(showUI);
        return;
    }
    if (win->AsEbook()) {
        // TODO: use EbookEngine for printing?
        return;
    }

    CrashIf(!win->AsFixed());
    if (!win->AsFixed()) return;
    DisplayModel *dm = win->AsFixed();

#ifndef DISABLE_DOCUMENT_RESTRICTIONS
    if (!dm->engine()->AllowsPrinting())
        return;
#endif

    if (win->printThread) {
        int res = MessageBox(win->hwndFrame, 
                             _TR("Printing is still in progress. Abort and start over?"),
                             _TR("Printing in progress."),
                             MB_ICONEXCLAMATION | MB_YESNO | MbRtlReadingMaybe());
        if (res == IDNO)
            return;
    }
    AbortPrinting(win);

    // the Print dialog allows access to the file system, so fall back
    // to printing the entire document without dialog if that isn't desired
    if (!HasPermission(Perm_DiskAccess)) {
        PrintFile(dm->engine());
        return;
    }

    PRINTDLGEX pd;
    ZeroMemory(&pd, sizeof(PRINTDLGEX));
    pd.lStructSize = sizeof(PRINTDLGEX);
    pd.hwndOwner   = win->hwndFrame;
    pd.Flags       = PD_USEDEVMODECOPIESANDCOLLATE | PD_COLLATE;
    if (!win->selectionOnPage)
        pd.Flags |= PD_NOSELECTION;
    pd.nCopies     = 1;
    /* by default print all pages */
    pd.nPageRanges = 1;
    pd.nMaxPageRanges = MAXPAGERANGES;
    PRINTPAGERANGE *ppr = AllocArray<PRINTPAGERANGE>(MAXPAGERANGES);
    pd.lpPageRanges = ppr;
    ppr->nFromPage = 1;
    ppr->nToPage = dm->PageCount();
    pd.nMinPage = 1;
    pd.nMaxPage = dm->PageCount();
    pd.nStartPage = START_PAGE_GENERAL;

    Print_Advanced_Data advanced(PrintRangeAll, defaultScaleAdv, defaultAsImage);
    ScopedMem<DLGTEMPLATE> dlgTemplate; // needed for RTL languages
    HPROPSHEETPAGE hPsp = CreatePrintAdvancedPropSheet(&advanced, dlgTemplate);
    pd.lphPropertyPages = &hPsp;
    pd.nPropertyPages = 1;

    // restore remembered settings
    if (defaultDevMode) {
        DEVMODE *p = defaultDevMode.Get();
        pd.hDevMode = GlobalMemDup(p, p->dmSize + p->dmDriverExtra);
    }

    if (PrintDlgEx(&pd) != S_OK) {
        if (CommDlgExtendedError() != 0) {
            /* if PrintDlg was cancelled then
               CommDlgExtendedError is zero, otherwise it returns the
               error code, which we could look at here if we wanted.
               for now just warn the user that printing has stopped
               becasue of an error */
            MessageBoxWarning(win->hwndFrame, _TR("Couldn't initialize printer"), 
                              _TR("Printing problem."));
        }
        goto Exit;
    }

    if (pd.dwResultAction == PD_RESULT_PRINT || pd.dwResultAction == PD_RESULT_APPLY) {
        // remember settings for this process
        LPDEVMODE devMode = (LPDEVMODE)GlobalLock(pd.hDevMode);
        if (devMode) {
            defaultDevMode.Set((LPDEVMODE)memdup(devMode, devMode->dmSize + devMode->dmDriverExtra));
            GlobalUnlock(pd.hDevMode);
        }
        defaultScaleAdv = advanced.scale;
        defaultAsImage = advanced.asImage;
    }

    if (pd.dwResultAction != PD_RESULT_PRINT)
        goto Exit;

    if (pd.Flags & PD_CURRENTPAGE) {
        PRINTPAGERANGE pr = { dm->CurrentPageNo(), dm->CurrentPageNo() };
        ranges.Append(pr);
    } else if (win->selectionOnPage && (pd.Flags & PD_SELECTION)) {
        printSelection = true;
    } else if (!(pd.Flags & PD_PAGENUMS)) {
        PRINTPAGERANGE pr = { 1, dm->PageCount() };
        ranges.Append(pr);
    } else {
        assert(pd.nPageRanges > 0);
        for (DWORD i = 0; i < pd.nPageRanges; i++)
            ranges.Append(pd.lpPageRanges[i]);
    }

    LPDEVNAMES devNames = (LPDEVNAMES)GlobalLock(pd.hDevNames);
    LPDEVMODE devMode = (LPDEVMODE)GlobalLock(pd.hDevMode);
    if (devNames) {
        printerInfo.pDriverName = (LPWSTR)devNames + devNames->wDriverOffset;
        printerInfo.pPrinterName = (LPWSTR)devNames + devNames->wDeviceOffset;
        printerInfo.pPortName = (LPWSTR)devNames + devNames->wOutputOffset;
    }
    PrintData *data = new PrintData(dm->engine(), &printerInfo, devMode, ranges, advanced,
                                    dm->GetRotation(), printSelection ? win->selectionOnPage : NULL);
    if (devNames)
        GlobalUnlock(pd.hDevNames);
    if (devMode)
        GlobalUnlock(pd.hDevMode);

    // if a file is missing and the engine can't thus be cloned,
    // we print using the original engine on the main thread
    // so that the document can't be closed and the original engine
    // unexpectedly deleted
    // TODO: instead prevent closing the document so that printing
    // can still happen on a separate thread and be interruptible
    bool failedEngineClone = dm->engine() && !data->engine;
    if (failedEngineClone)
        data->engine = dm->engine();

    if (!waitForCompletion && !failedEngineClone)
        PrintToDeviceOnThread(win, data);
    else {
        PrintToDevice(*data);
        if (failedEngineClone)
            data->engine = NULL;
        delete data;
    }

Exit:
    free(ppr);
    GlobalFree(pd.hDevNames);
    GlobalFree(pd.hDevMode);
}
Example #28
0
PromiseResult VerifyReportPromise(EvalContext *ctx, const Promise *pp)
{
    CfLock thislock;
    char unique_name[CF_EXPANDSIZE];

    Attributes a = GetReportsAttributes(ctx, pp);

    // We let AcquireLock worry about making a unique name
    snprintf(unique_name, CF_EXPANDSIZE - 1, "%s", pp->promiser);
    thislock = AcquireLock(ctx, unique_name, VUQNAME, CFSTARTTIME, a.transaction, pp, false);

    // Handle return values before locks, as we always do this

    if (a.report.result)
    {
        // User-unwritable value last-result contains the useresult
        if (strlen(a.report.result) > 0)
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result[%s]", a.report.result);
        }
        else
        {
            snprintf(unique_name, CF_BUFSIZE, "last-result");
        }

        VarRef *ref = VarRefParseFromBundle(unique_name, PromiseGetBundle(pp));
        EvalContextVariablePut(ctx, ref, pp->promiser, CF_DATA_TYPE_STRING, "source=bundle");
        VarRefDestroy(ref);

        if (thislock.lock)
        {
            YieldCurrentLock(thislock);
        }
        return PROMISE_RESULT_NOOP;
    }

    if (thislock.lock == NULL)
    {
        return PROMISE_RESULT_SKIPPED;
    }

    PromiseBanner(ctx, pp);

    if (a.transaction.action == cfa_warn)
    {
        cfPS(ctx, LOG_LEVEL_WARNING, PROMISE_RESULT_WARN, pp, a, "Need to repair reports promise: %s", pp->promiser);
        YieldCurrentLock(thislock);
        return PROMISE_RESULT_WARN;
    }

    if (a.report.to_file)
    {
        ReportToFile(a.report.to_file, pp->promiser);
    }
    else
    {
        ReportToLog(pp->promiser);
    }

    PromiseResult result = PROMISE_RESULT_NOOP;
    if (a.report.haveprintfile)
    {
        if (!PrintFile(a.report.filename, a.report.numlines))
        {
            result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL);
        }
    }

    YieldCurrentLock(thislock);

    ClassAuditLog(ctx, pp, a, result);
    return result;
}
Example #29
0
/*
 * DoLC - perform LC on a specified directory
 */
void DoLC( char *dir )
{
    int                 i;
    DIR                 *d;
    struct dirent       *nd;
#ifdef __QNX__
    char                tmpname[ _MAX_PATH ];
    char                drive[_MAX_DRIVE],directory[_MAX_DIR];
    char                name[_MAX_FNAME],ext[_MAX_EXT];
#endif

    /*
     * initialize for file scan
     */
    filecnt = 0;
    strcpy(filename,dir);
#ifndef __QNX__
    if( !FNameCompare(dir,"..") ) {
        strcat(filename,"\\*.*");
    } else if( dir[ strlen(dir)-1 ] == '.' ) {
        filename[ strlen(dir)-1 ] = 0;
        strcat(filename,"*.*");
    } else if( dir[ strlen(dir)-1 ] == '\\' ) {
        strcat(filename,"*.*");
    } else {
        strcat(filename,"\\*.*");
    }
#else
    if( filename[0] == 0 ) {
        filename[0] = '.';
        filename[1] = 0;
    }
    _splitpath( filename, drive, directory, name, ext );
#endif
    d = opendir( filename );
    if( d == NULL ) {
        printf( "Directory (%s) not found.\n",filename );
        return;
    }


    /*
     * find all files (except for . and ..)
     */
    while( (nd = readdir( d )) != NULL ) {

#ifndef __QNX__
        if( files_only && nd->d_attr & _A_SUBDIR ) {
            continue;
        }
        if( directories_only && !( nd->d_attr & _A_SUBDIR ) ) {
            continue;
        }
        if( !((nd->d_attr & _A_SUBDIR ) && IsDotOrDotDot( nd->d_name ))) {
#else
        if( files_only && S_ISDIR( nd->d_stat.st_mode ) ) {
            continue;
        }
        if( directories_only && !S_ISDIR( nd->d_stat.st_mode ) ) {
            continue;
        }
        if( !((S_ISDIR( nd->d_stat.st_mode) && IsDotOrDotDot( nd->d_name ) ))) {
#endif
            files = realloc( files, ( filecnt+1 )*sizeof( struct dirent * ) );
            if( files == NULL ) {
                printf( "Out of memory!\n" );
                exit( 1 );
            }
            files[ filecnt ] = malloc( sizeof( struct dirent ) );
            if( files[ filecnt ] == NULL ) {
                break;
            }
#ifndef __QNX__
            FNameLower( nd->d_name );
#else
            if( !(nd->d_stat.st_status & _FILE_USED ) ) {
                _splitpath( nd->d_name, NULL, NULL, name, ext );
                _makepath( tmpname, drive, directory, name, ext );
                stat( tmpname, &nd->d_stat );
            }
#endif
            memcpy( files[filecnt++],nd,sizeof( struct dirent ) );
        }

    }
    closedir( d );
    if( filecnt == 0 ) {
        return;
    }

    /*
     * sort the data.
     */
    qsort( files, filecnt, sizeof(struct dirent *), Compare );

    /*
     * determine if there are files and/or directories
     */
    fileflag = dirflag = read_only_flag = false;
    for( i = 0; i < filecnt; i++ ) {
#ifndef __QNX__
        if( files[i]->d_attr & _A_SUBDIR ) {
            dirflag = true;
        } else if( separate_read_only && files[i]->d_attr & _A_RDONLY ) {
            read_only_flag = true;
        } else {
            fileflag = true;
        }
#else
        if( S_ISDIR( files[i]->d_stat.st_mode ) ) {
            dirflag = true;
        } else {
            fileflag = true;
        }
#endif
        if( fileflag && dirflag && (!separate_read_only || read_only_flag) ) {
            break;
        }
    }

    /*
     * print out results
     */
    if( dirflag ) {
        printf("Directories:\n");
        pass = DIR_PASS;
        linecnt=0;
        for( i = 0; i < filecnt; i++ ) {
            PrintFile( files[i] );
        }
        if( linecnt != 0 ) {
            printf("\n");
        }
    }
    if( fileflag ) {
        if( dirflag ) {
            printf("\n");
        }
        printf("Files:\n");
        pass = FILE_PASS;
        linecnt=0;
        for( i = 0; i < filecnt; i++ ) {
            PrintFile( files[i] );
        }
        if( linecnt != 0 ) {
            printf("\n");
        }
    }
    if( read_only_flag ) {
        if( dirflag || fileflag ) {
            printf("\n");
        }
        printf( "Read-Only Files:\n" );
        pass = READ_ONLY_PASS;
        linecnt = 0;
        for( i = 0; i < filecnt; i++ ) {
            PrintFile( files[i] );
        }
        if( linecnt != 0 ) {
            printf("\n");
        }
    }
} /* DoLC */

/*
 * PrintFile - print a file entry
 */
void PrintFile( struct dirent *file )
{

    size_t      len;
    size_t      num_columns;

#ifndef __QNX__
    if( file->d_attr & _A_SUBDIR ) {
#else
    if( S_ISDIR( file->d_stat.st_mode ) ) {
#endif
        if( pass != DIR_PASS ) {
            return;
        }
    } else {
#ifndef __QNX__
        if( separate_read_only && file->d_attr & _A_RDONLY ) {
            if( pass != READ_ONLY_PASS ) {
                return;
            }
        } else if( pass != FILE_PASS ) {
            return;
        }
#else
        if( pass != FILE_PASS ) {
            return;
        }
#endif
    }

    /* calculate how many columns it will take to print the filename */
    len = strlen( file->d_name ) + ( GUTTER_WIDTH + COLUMN_WIDTH - 1 );
    num_columns = len / COLUMN_WIDTH;
    if( num_columns + linecnt > maxwidth ) {
        printf( "\n" );
        linecnt = 0;
    }
    printf("%-*s", COLUMN_WIDTH * num_columns - GUTTER_WIDTH, file->d_name );
    linecnt += num_columns;
    if( linecnt >= maxwidth ) {
        printf("\n");
        linecnt = 0;
    } else {
        printf( "%*s", GUTTER_WIDTH, "" );
    }

} /* PrintFile */
Example #30
0
bool UpdateSums(const plString& filename) {
    bool isUpdated = false;
    printf("%s:\n", filename.cstr());
    try {
        SumFile sum;
        plEncryptedStream S;
        plEncryptedStream::EncryptionType eType = plEncryptedStream::kEncXtea;
        if (!s_createFile) {
            if (!S.open(filename, fmRead, plEncryptedStream::kEncAuto)) {
                fprintf(stderr, "Could not open file %s\n", filename.cstr());
                return false;
            }
            eType = S.getEncType();
            sum.read(&S);
            S.close();
        }

        std::vector<SumEntry>::iterator it = sum.fEntries.begin();
        while (it != sum.fEntries.end()) {
            hsFileStream* IS = FindFilePath(it->fPath, cdUp(filename));
            if (IS == NULL) {
                if (s_autoYes) {
                    PrintFile(*it, '-');
                    it = sum.fEntries.erase(it);
                    isUpdated = true;
                } else {
                    fprintf(stderr, "File %s not found.  Remove it? [y/N] ",
                            it->fPath.cstr());
                    char buf[256];
                    fgets(buf, 256, stdin);

                    if (strcmp(buf, "y\n") == 0 || strcmp(buf, "Y\n") == 0) {
                        PrintFile(*it, '-');
                        it = sum.fEntries.erase(it);
                        isUpdated = true;
                    } else {
                        PrintFile(*it, '!');
                        ++it;
                    }
                }
                continue;
            }
            plMD5Hash hash = plMD5::hashStream(IS);
            it->fTimestamp = IS->getModTime();
            if (it->fHash != hash) {
                it->fHash = hash;
                PrintFile(*it, '*');
                isUpdated = true;
            } else {
                PrintFile(*it, ' ');
            }
            if (IS != NULL)
                delete IS;
            ++it;
        }

        if (isUpdated) {
            if (!S.open(filename, fmCreate, eType)) {
                fprintf(stderr, "Error: Could not open %s for writing!\n", filename.cstr());
                return false;
            }
            sum.write(&S);
            S.close();
        }
        printf("\n");
    } catch (hsException& e) {
        fprintf(stderr, "%s:%ld: %s\n", e.File(), e.Line(), e.what());
    } catch (...) {
        fprintf(stderr, "An unknown error occured\n");
    }
    return isUpdated;
}