Пример #1
0
NS_IMETHODIMP
nsFilePicker::Show(PRInt16 *aReturn)
{
  NS_ENSURE_ARG_POINTER(aReturn);

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));

  GtkWindow *parent_widget = get_gtk_window_for_nsiwidget(mParentWidget);

  GtkFileChooserAction action = GetGtkFileChooserAction(mMode);
  const gchar *accept_button = (mMode == GTK_FILE_CHOOSER_ACTION_SAVE)
                               ? GTK_STOCK_SAVE : GTK_STOCK_OPEN;
  GtkWidget *file_chooser =
      _gtk_file_chooser_dialog_new(title, parent_widget, action,
                                   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                   accept_button, GTK_RESPONSE_ACCEPT,
                                   NULL);

  if (parent_widget && parent_widget->group) {
    gtk_window_group_add_window(parent_widget->group, GTK_WINDOW(file_chooser));
  }

  if (mMode == nsIFilePicker::modeOpenMultiple) {
    _gtk_file_chooser_set_select_multiple (GTK_FILE_CHOOSER(file_chooser), TRUE);
  } else if (mMode == nsIFilePicker::modeSave) {
    char *default_filename = ToNewUTF8String(mDefault);
    _gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser),
                                       NS_STATIC_CAST(const gchar*, default_filename));
    nsMemory::Free(default_filename);
  }

  gtk_dialog_set_default_response(GTK_DIALOG(file_chooser), GTK_RESPONSE_ACCEPT);

  nsCAutoString directory;
  if (mDisplayDirectory) {
    mDisplayDirectory->GetNativePath(directory);
  } else if (mPrevDisplayDirectory) {
    mPrevDisplayDirectory->GetNativePath(directory);
  }

  if (!directory.IsEmpty()) {
    _gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(file_chooser),
                                         directory.get());
  }

  PRInt32 count = mFilters.Count();
  for (PRInt32 i = 0; i < count; ++i) {
    // This is fun... the GTK file picker does not accept a list of filters
    // so we need to split out each string, and add it manually.

    char **patterns = g_strsplit(mFilters[i]->get(), ";", -1);
    if (!patterns) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    GtkFileFilter *filter = _gtk_file_filter_new ();
    for (int j = 0; patterns[j] != NULL; ++j) {
      _gtk_file_filter_add_pattern (filter, g_strstrip (patterns[j]));
    }

    g_strfreev(patterns);

    if (!mFilterNames[i]->IsEmpty()) {
      // If we have a name for our filter, let's use that.
      const char *filter_name = mFilterNames[i]->get();
      _gtk_file_filter_set_name (filter, filter_name);
    } else {
      // If we don't have a name, let's just use the filter pattern.
      const char *filter_pattern = mFilters[i]->get();
      _gtk_file_filter_set_name (filter, filter_pattern);
    }

    _gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (file_chooser), filter);

    // Set the initially selected filter
    if (mSelectedType == i) {
      _gtk_file_chooser_set_filter (GTK_FILE_CHOOSER(file_chooser), filter);
    }
  }

  PRBool checkForOverwrite = PR_TRUE;
  if (_gtk_file_chooser_set_do_overwrite_confirmation) {
    checkForOverwrite = PR_FALSE;
    // Only available in GTK 2.8
    _gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(file_chooser), PR_TRUE);
  }

  gint response = gtk_dialog_run (GTK_DIALOG (file_chooser));

  switch (response) {
    case GTK_RESPONSE_ACCEPT:
    ReadValuesFromFileChooser(file_chooser);
    *aReturn = nsIFilePicker::returnOK;
    if (mMode == nsIFilePicker::modeSave) {
      nsCOMPtr<nsILocalFile> file;
      GetFile(getter_AddRefs(file));
      if (file) {
        PRBool exists = PR_FALSE;
        file->Exists(&exists);
        if (exists) {
          PRBool overwrite = !checkForOverwrite ||
            confirm_overwrite_file (file_chooser, file);

          if (overwrite) {
            *aReturn = nsIFilePicker::returnReplace;
          } else {
            *aReturn = nsIFilePicker::returnCancel;
          }
        }
      }
    }
    break;

    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_CLOSE:
    case GTK_RESPONSE_DELETE_EVENT:
    *aReturn = nsIFilePicker::returnCancel;
    break;

    default:
    NS_WARNING("Unexpected response");
    *aReturn = nsIFilePicker::returnCancel;
    break;
  }

  gtk_widget_destroy(file_chooser);

  return NS_OK;
}
Пример #2
0
static void ParseMemory (void)
/* Parse a MEMORY section */
{
    static const IdentTok Attributes [] = {
       	{   "START",  	CFGTOK_START    },
	{   "SIZE", 	CFGTOK_SIZE     },
        {   "TYPE",     CFGTOK_TYPE     },
        {   "FILE",     CFGTOK_FILE     },
        {   "DEFINE",   CFGTOK_DEFINE   },
  	{   "FILL", 	CFGTOK_FILL     },
       	{   "FILLVAL", 	CFGTOK_FILLVAL  },
    };
    static const IdentTok Types [] = {
       	{   "RO",    	CFGTOK_RO       },
       	{   "RW",   	CFGTOK_RW       },
    };

    while (CfgTok == CFGTOK_IDENT) {

	/* Create a new entry on the heap */
       	Memory* M = NewMemory (GetStringId (CfgSVal));

	/* Skip the name and the following colon */
	CfgNextTok ();
	CfgConsumeColon ();

       	/* Read the attributes */
	while (CfgTok == CFGTOK_IDENT) {

	    /* Map the identifier to a token */
	    cfgtok_t AttrTok;
	    CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
	    AttrTok = CfgTok;

	    /* An optional assignment follows */
	    CfgNextTok ();
	    CfgOptionalAssign ();

	    /* Check which attribute was given */
	    switch (AttrTok) {

		case CFGTOK_START:
		    FlagAttr (&M->Attr, MA_START, "START");
                    M->Start = CfgIntExpr ();
		    break;

	      	case CFGTOK_SIZE:
	     	    FlagAttr (&M->Attr, MA_SIZE, "SIZE");
	      	    M->Size = CfgIntExpr ();
		    break;

		case CFGTOK_TYPE:
		    FlagAttr (&M->Attr, MA_TYPE, "TYPE");
      		    CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
		    if (CfgTok == CFGTOK_RO) {
		    	M->Flags |= MF_RO;
		    }
                    CfgNextTok ();
		    break;

	        case CFGTOK_FILE:
		    FlagAttr (&M->Attr, MA_FILE, "FILE");
		    CfgAssureStr ();
       	       	    /* Get the file entry and insert the memory area */
	    	    FileInsert (GetFile (GetStringId (CfgSVal)), M);
                    CfgNextTok ();
		    break;

	        case CFGTOK_DEFINE:
 		    FlagAttr (&M->Attr, MA_DEFINE, "DEFINE");
		    /* Map the token to a boolean */
		    CfgBoolToken ();
		    if (CfgTok == CFGTOK_TRUE) {
	  	    	M->Flags |= MF_DEFINE;
		    }
                    CfgNextTok ();
		    break;

	        case CFGTOK_FILL:
 		    FlagAttr (&M->Attr, MA_FILL, "FILL");
		    /* Map the token to a boolean */
		    CfgBoolToken ();
		    if (CfgTok == CFGTOK_TRUE) {
	  	    	M->Flags |= MF_FILL;
		    }
                    CfgNextTok ();
		    break;

	      	case CFGTOK_FILLVAL:
		    FlagAttr (&M->Attr, MA_FILLVAL, "FILLVAL");
	      	    M->FillVal = (unsigned char) CfgCheckedIntExpr (0, 0xFF);
		    break;

	     	default:
	       	    FAIL ("Unexpected attribute token");

	    }

	    /* Skip an optional comma */
	    CfgOptionalComma ();
	}

	/* Skip the semicolon */
	CfgConsumeSemi ();

	/* Check for mandatory parameters */
       	AttrCheck (M->Attr, MA_START, "START");
	AttrCheck (M->Attr, MA_SIZE, "SIZE");

	/* If we don't have a file name for output given, use the default
	 * file name.
	 */
	if ((M->Attr & MA_FILE) == 0) {
	    FileInsert (GetFile (GetStringId (OutputName)), M);
	}
    }

    /* Remember we had this section */
    SectionsEncountered |= SE_MEMORY;
}
Пример #3
0
void CUpdater::CheckUpdates(CMenus *pMenus)
{
	dbg_msg("autoupdate", "Checking for updates...");
	if (!GetFile(UPDATES_MANIFEST_FILE, UPDATES_MANIFEST_FILE))
	{
		dbg_msg("autoupdate", "Error downloading updates manifest :/");
		return;
	}

    Reset();

    IOHANDLE fileAutoUpdate = io_open(UPDATES_MANIFEST_FILE, IOFLAG_READ);
    io_seek(fileAutoUpdate, 0, IOSEEK_END);
    std::streamsize size = io_tell(fileAutoUpdate);
    io_seek(fileAutoUpdate, 0, IOSEEK_START);

    std::vector<char> buffer(size);
    if (io_read(fileAutoUpdate, buffer.data(), size))
    {
        bool needUpdate = false;

        json_settings JsonSettings;
        mem_zero(&JsonSettings, sizeof(JsonSettings));
        char aError[256];
        json_value *pJsonNodeMain = json_parse_ex(&JsonSettings, buffer.data(), size, aError);
        if (pJsonNodeMain == 0)
        {
            dbg_msg("autoupdate", "Error: %s", aError);
            return;
        }

        int verCode = -1;
        for(int j=pJsonNodeMain->u.object.length-1; j>=0; j--) // Ascendent Search: Manifest has descendant order
        {
            sscanf((const char *)pJsonNodeMain->u.object.values[j].name, "%d", &verCode);
            json_value *pNodeCode = pJsonNodeMain->u.object.values[j].value;

            if (verCode <= HCLIENT_VERSION_CODE)
                continue;

            needUpdate = true;

            const json_value &rVersion = (*pNodeCode)["version"];
            str_copy(m_NewVersion, (const char *)rVersion, sizeof(m_NewVersion));

            // Need update client?
            const json_value &rClient = (*pNodeCode)["client"];
            m_NeedUpdateClient = (rClient.u.boolean);

            // Need update server?
            const json_value &rServer = (*pNodeCode)["server"];
            m_NeedUpdateServer = (rServer.u.boolean);

            // Get files to download
            const json_value &rDownload = (*pNodeCode)["download"];
            for(unsigned k = 0; k < rDownload.u.array.length; k++)
                AddFileToDownload((const char *)rDownload[k]);
            // Get files to remove
            const json_value &rRemove = (*pNodeCode)["remove"];
            for(unsigned k = 0; k < rRemove.u.array.length; k++)
                AddFileToRemove((const char *)rRemove[k]);
        }

        if (needUpdate) pMenus->SetPopup(CMenus::POPUP_UPDATER);
        else m_Updated = true;
    }

    io_close(fileAutoUpdate);
    fs_remove(UPDATES_MANIFEST_FILE);
}
Пример #4
0
bool CXbtFile::Exists(const CURL& url)
{
  CXBTFFile dummy;
  return GetFile(url, dummy);
}
Пример #5
0
nsresult
nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
{
  nsCOMPtr<nsIFile> updRoot;
#if defined(MOZ_WIDGET_GONK)

  nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"),
                                      true,
                                      getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#else
  nsCOMPtr<nsIFile> appFile;
  bool per = false;
  nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = appFile->GetParent(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef XP_WIN

  nsAutoString pathHash;
  bool pathHashResult = false;

  nsAutoString appDirPath;
  if (gAppData->vendor && !getenv("MOZ_UPDATE_NO_HASH_DIR") &&
      SUCCEEDED(updRoot->GetPath(appDirPath))) {

    // Figure out where we should check for a cached hash value
    wchar_t regPath[1024] = { L'\0' };
    swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs",
               gAppData->vendor, MOZ_APP_NAME);

    // If we pre-computed the hash, grab it from the registry.
    pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE,
                                   nsDependentString(regPath), appDirPath,
                                   pathHash);
    if (!pathHashResult) {
      pathHashResult = GetCachedHash(HKEY_CURRENT_USER,
                                     nsDependentString(regPath), appDirPath,
                                     pathHash);
    }
  }

  // Get the local app data directory and if a vendor name exists append it.
  // If only a product name exists, append it.  If neither exist fallback to
  // old handling.  We don't use the product name on purpose because we want a
  // shared update directory for different apps run from the same path (like
  // Metro & Desktop).
  nsCOMPtr<nsIFile> localDir;
  if (pathHashResult && (gAppData->vendor || gAppData->name) &&
      NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) &&
      NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(gAppData->vendor ?
                                          gAppData->vendor : gAppData->name))) &&
      NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) &&
      NS_SUCCEEDED(localDir->Append(pathHash))) {
    NS_ADDREF(*aResult = localDir);
    return NS_OK;
  }

  nsAutoString appPath;
  rv = updRoot->GetPath(appPath);
  NS_ENSURE_SUCCESS(rv, rv);

  // AppDir may be a short path. Convert to long path to make sure
  // the consistency of the update folder location
  nsString longPath;
  wchar_t* buf;

  uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN);
  NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY);

  DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength);

  // Failing GetLongPathName() is not fatal.
  if (len <= 0 || len >= bufLength)
    longPath.Assign(appPath);
  else
    longPath.SetLength(len);

  // Use <UserLocalDataDir>\updates\<relative path to app dir from
  // Program Files> if app dir is under Program Files to avoid the
  // folder virtualization mess on Windows Vista
  nsAutoString programFiles;
  rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles);
  NS_ENSURE_SUCCESS(rv, rv);

  programFiles.AppendLiteral("\\");
  uint32_t programFilesLen = programFiles.Length();

  nsAutoString programName;
  if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) {
    programName = Substring(longPath, programFilesLen);
  } else {
    // We need the update root directory to live outside of the installation
    // directory, because otherwise the updater writing the log file can cause
    // the directory to be locked, which prevents it from being replaced after
    // background updates.
    programName.AssignASCII(MOZ_APP_NAME);
  }

  rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = updRoot->AppendRelativePath(programName);
  NS_ENSURE_SUCCESS(rv, rv);

#endif
#endif
  NS_ADDREF(*aResult = updRoot);
  return NS_OK;
}
 AFILE *
GetF( )
{
 char  *hp;
 uint   key;
 char   PromptString[MAXPROMPTSTRING];
 AFILE *fp;
 uchar *SaveArea;

 static int _iview;
 /****************************************************************************/
 /* - put the title, instructions, and help appropriate for this popup       */
 /*   into the popup structure.                                              */
 /* - save the screen area used by the popup if CUA interface.               */
 /* - get a function name from the user.                                     */
 /* - handle user string and keys.                                           */
 /* - handle errors.                                                         */
 /* - restore the screen save area if CUA interface.                         */
 /*                                                                          */
 /****************************************************************************/
 fp = NULL;
#if defined(MSH)
 if(commandLine.nparms>1) {
    fp=GetFile(commandLine.parms[1]);
    if(fp)
    {
#if defined(SD386LOG)
        SD386Log(STRINGCODE," ");
        SD386Log(STRINGCODE,commandLine.parms[1]);
#endif
        return fp;
    }
 }
#endif
 _iview=iview; iview=0;
 *PromptString = '\0';

 Popup.title = GE_Title;
 Popup.instructions = GE_Instructions;
 Popup.help = GETFILEHELP;

 SaveArea = (uchar *)Talloc(Popup.length * Popup.width * 2);
 GetPopArea(SaveArea);
 DisplayPop( &Popup );

 /****************************************************************************/
 /* loop to handle user entry/errors.                                        */
 /****************************************************************************/
 for(;;)
 {
  hp = GE_Instructions;
  key = PopPrompt( PromptString, hp);

  stripblk(PromptString);

  if( key == ESC )
  {
#if 0
    SD386Log(STRINGCODE," ");
   SD386Log(KEYCODE|key,"");
#endif
   break;
  }
  else if ( key == ENTER )
  {
   if( strlen(PromptString) == 0 )
    continue;
   fp = GetFile(PromptString);
   if( fp )
   {
#if 0
        SD386Log(STRINGCODE," ");
        SD386Log(STRINGCODE,PromptString);
#endif
        break;
   }

   /**************************************************************************/
   /* display an error message and then ask for another name.                */
   /**************************************************************************/
   beep();
   hp = CantFind;
   fmterr( hp);
   continue;
  }
 }

 PutPopArea(SaveArea);
 Tfree(SaveArea );
 iview=_iview;
 return(fp);
}
Пример #7
0
INT_PTR CALLBACK DlgProc(
  _In_ HWND   hDlg,
  _In_ UINT   uMsg,
  _In_ WPARAM wParam,
  _In_ LPARAM lParam
) {
	int wmId, wmEvent;
	static ChromeInfo chromeInfo;
	static TCHAR ltcChromeDetected[MAX_LOADSTRING];
	static TCHAR ltcChromeNotDetected[MAX_LOADSTRING];
	static TCHAR ltcSendSuccess[MAX_LOADSTRING];
	static TCHAR ltcSendFailed[MAX_LOADSTRING];

	static char szVariable[MAX_LOADSTRING];
	static char sRawFilepath[MAX_PATH];
	static char sUrl[MAX_PATH];

	static tstringstream os;

	switch (uMsg)
	{
		case WM_INITDIALOG:
			{
				HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(lParam);
				TCHAR szTemp[MAX_LOADSTRING];
				if (0 != LoadString(hInstance, IDS_APP_TITLE, szTemp, MAX_LOADSTRING)){
					SetWindowText(hDlg, szTemp);
				}
				if (0 != LoadString(hInstance, IDS_BTN_SEND_CAPTION, szTemp, MAX_LOADSTRING)){
					SetDlgItemText(hDlg, IDC_BTN_SEND, szTemp);
				}
				LoadStringOrDefault(hInstance, ltcChromeDetected, MAX_LOADSTRING, IDS_CHROME_DETECTED, g_tcChromeDetected);
				LoadStringOrDefault(hInstance, ltcChromeNotDetected, MAX_LOADSTRING, IDS_CHROME_NOTDETECTED, g_tcChromeNotDetected);

				SetDlgItemText(hDlg, IDC_LBL_CHROME_STATUS, ltcChromeNotDetected);

				LoadStringOrDefault(hInstance, ltcSendFailed, MAX_LOADSTRING, IDS_SEND_FAILED, g_tcSendFailed);
				LoadStringOrDefault(hInstance, ltcSendSuccess, MAX_LOADSTRING, IDS_SEND_SUCCESS, g_tcSendSuccess);

				SetDlgItemText(hDlg, IDC_LBL_SEND_STATUS, TEXT(""));

				if (0 != SetTimer(hDlg,	IDT_REFRESH_CHROME_STATUS, int(1000 / refreshratehz), NULL))
				{
					ShowWindow(GetDlgItem(hDlg, IDC_BTN_REFRESH), SW_HIDE);
				} 
				else 
				{
					if (0 != LoadString(hInstance, IDS_BTN_REFRESH_CAPTION, szTemp, MAX_LOADSTRING)){
						SetDlgItemText(hDlg, IDC_BTN_REFRESH, szTemp);
					}
					ShowWindow(GetDlgItem(hDlg, IDC_BTN_REFRESH), SW_SHOW);
				}
				
				char* pTemp = 0;
				if (AllocAndCopyTCtoMB(&pTemp, g_tcRawFilepath, MAX_PATH)) {
					StringCbCopyA(sRawFilepath, MAX_PATH, pTemp);
					delete[] pTemp;
				}
				pTemp = 0;
				if (AllocAndCopyTCtoMB(&pTemp, g_tcUrl, MAX_PATH)) {
					StringCbCopyA(sUrl, MAX_PATH, pTemp);
					delete[] pTemp;
				}

				StringCbCopyA(szVariable, MAX_LOADSTRING, "filearg");

				UpdateField(hDlg, IDC_EDT_FILEPATH, sRawFilepath, MAX_PATH, true);
				UpdateField(hDlg, IDC_EDT_SEND_URL, sUrl, MAX_PATH, true);
			}
			return TRUE;
		case WM_TIMER: 
			switch (wParam) 
			{ 
				case IDT_REFRESH_CHROME_STATUS: 
					if(DetectChrome(&chromeInfo, g_tcImageName)){
						os.str(TEXT(""));
						os.clear();
						os<<ltcChromeDetected<<" (pid: "<<chromeInfo.dwProcId<<")"<<std::endl;
						SetDlgItemText(hDlg, IDC_LBL_CHROME_STATUS, os.str().c_str());
					} else {
						SetDlgItemText(hDlg, IDC_LBL_CHROME_STATUS, ltcChromeNotDetected);
					}

					return TRUE;
			}
			break;
		case WM_COMMAND:
			wmId    = LOWORD(wParam);
			wmEvent = HIWORD(wParam);
			switch (wmId)
			{
				case IDCANCEL:
						SendMessage(hDlg, WM_CLOSE, 0, 0);
						return TRUE;
				case IDC_BTN_SEND:{
						UpdateField(hDlg, IDC_EDT_FILEPATH, sRawFilepath, MAX_PATH);
						UpdateField(hDlg, IDC_EDT_SEND_URL, sUrl, MAX_PATH);
						TCHAR tcRawFilepath[MAX_PATH];
						TCHAR tcUrl[MAX_PATH];
						TCHAR* pTemp = 0;
						if (AllocAndCopyMBtoTC(&pTemp, sUrl, MAX_PATH)) {
							StringCbCopy(tcUrl, MAX_PATH, pTemp);
							delete[] pTemp;
						} 
						pTemp = 0;
						if (AllocAndCopyMBtoTC(&pTemp, sRawFilepath, MAX_PATH)) {
							StringCbCopy(tcRawFilepath, MAX_PATH, pTemp);
							delete[] pTemp;
						}
						TCHAR tcFullPath[MAX_PATH];
						TCHAR *tcFilenamePart;
						if(CreateFullPath(tcRawFilepath, tcFullPath, sizeof(tcFullPath)/ sizeof(TCHAR), &tcFilenamePart) )
						{
							char* pFilenamePart = 0;
							if (AllocAndCopyTCtoMB(&pFilenamePart, tcFilenamePart, MAX_PATH)) 

							if(SendFile(GetFile(tcFullPath), tcUrl, szVariable, pFilenamePart)) {
								SetDlgItemText(hDlg, IDC_LBL_SEND_STATUS, ltcSendSuccess);
							} else {
								SetDlgItemText(hDlg, IDC_LBL_SEND_STATUS, ltcSendFailed);
							}
							
							if(pFilenamePart) delete[] pFilenamePart;
						}
					}
					return TRUE;	
				case IDC_BTN_REFRESH:
					if(DetectChrome(&chromeInfo, g_tcImageName, true)){
						SetDlgItemText(hDlg, IDC_LBL_CHROME_STATUS, ltcChromeDetected);
					} else {
						SetDlgItemText(hDlg, IDC_LBL_CHROME_STATUS, ltcChromeNotDetected);
					}
					return TRUE;
					
			}
			break;

		case WM_CLOSE:
			KillTimer(hDlg, IDT_REFRESH_CHROME_STATUS);
			DestroyWindow(hDlg);
			return TRUE;
		case WM_DESTROY:
			PostQuitMessage(0);
			return TRUE;
	}

	return FALSE;
}
Пример #8
0
int main(int argc, char **argv)
{

/*

#!/bin/sh
rosrun map_file vector_map_loader <csv files>

# EOF

*/

  ros::init(argc, argv, "sample_vector_map");
  ros::NodeHandle n;
  ros::Publisher pub = n.advertise<visualization_msgs::MarkerArray>("/vector_map", 1000, true);
  ros::Publisher stat_publisher = n.advertise<std_msgs::Bool>("/vmap_stat", 100);;
  std_msgs::Bool vmap_stat_msg;

  ros::Publisher pub_point_class = n.advertise<map_file::PointClassArray>(
	  "/vector_map_info/point_class", 1, true);
  ros::Publisher pub_vector_class = n.advertise<map_file::VectorClassArray>(
	  "/vector_map_info/vector_class", 1, true);
  ros::Publisher pub_line_class = n.advertise<map_file::LineClassArray>(
	  "/vector_map_info/line_class", 1, true);
  ros::Publisher pub_area_class = n.advertise<map_file::AreaClassArray>(
	  "/vector_map_info/area_class", 1, true);
  ros::Publisher pub_pole_class = n.advertise<map_file::PoleClassArray>(
	  "/vector_map_info/pole_class", 1, true);
  ros::Publisher pub_box_class = n.advertise<map_file::BoxClassArray>(
	  "/vector_map_info/box_class", 1, true);

  ros::Publisher pub_dtlane = n.advertise<map_file::DTLaneArray>(
	  "/vector_map_info/dtlane", 1, true);
  ros::Publisher pub_node = n.advertise<map_file::NodeArray>(
	  "/vector_map_info/node", 1, true);
  ros::Publisher pub_lane = n.advertise<map_file::LaneArray>(
	  "/vector_map_info/lane", 1, true);

  ros::Publisher pub_road_edge = n.advertise<map_file::RoadEdgeArray>(
	  "/vector_map_info/road_edge", 1, true);
  ros::Publisher pub_gutter = n.advertise<map_file::GutterArray>(
	  "/vector_map_info/gutter", 1, true);
  ros::Publisher pub_curb = n.advertise<map_file::CurbArray>(
	  "/vector_map_info/curb", 1, true);
  ros::Publisher pub_white_line = n.advertise<map_file::WhiteLineArray>(
	  "/vector_map_info/white_line", 1, true);
  ros::Publisher pub_stop_line = n.advertise<map_file::StopLineArray>(
	  "/vector_map_info/stop_line", 1, true);
  ros::Publisher pub_zebra_zone = n.advertise<map_file::ZebraZoneArray>(
	  "/vector_map_info/zebra_zone", 1, true);
  ros::Publisher pub_cross_walk = n.advertise<map_file::CrossWalkArray>(
	  "/vector_map_info/cross_walk", 1, true);
  ros::Publisher pub_road_mark = n.advertise<map_file::RoadMarkArray>(
	  "/vector_map_info/road_mark", 1, true);
  ros::Publisher pub_pole = n.advertise<map_file::PoleArray>(
	  "/vector_map_info/pole", 1, true);
  ros::Publisher pub_road_sign = n.advertise<map_file::RoadSignArray>(
	  "/vector_map_info/road_sign", 1, true);
  ros::Publisher pub_signal = n.advertise<map_file::SignalArray>(
	  "/vector_map_info/signal", 1, true);
  ros::Publisher pub_street_light = n.advertise<map_file::StreetLightArray>(
	  "/vector_map_info/street_light", 1, true);
  ros::Publisher pub_utility_pole = n.advertise<map_file::UtilityPoleArray>(
	  "/vector_map_info/utility_pole", 1, true);
  ros::Publisher pub_guard_rail = n.advertise<map_file::GuardRailArray>(
	  "/vector_map_info/guard_rail", 1, true);
  ros::Publisher pub_side_walk = n.advertise<map_file::SideWalkArray>(
	  "/vector_map_info/side_walk", 1, true);
  ros::Publisher pub_cross_road = n.advertise<map_file::CrossRoadArray>(
	  "/vector_map_info/cross_road", 1, true);

  std::vector<PointClass> pointclasses;
  std::vector<PoleClass> poleclasses;
  std::vector<VectorClass> vectorclasses;
  std::vector<AreaClass> areaclasses;
  std::vector<LineClass> lines;

  std::vector<Pole> poles;
  std::vector<Signal> signals;
  std::vector<RoadSign> roadsigns;
  std::vector<DTLane> dtlanes;
  std::vector<Node> nodes;
  std::vector<Lane> lanes;
  std::vector<WhiteLine> whitelines;
  std::vector<ZebraZone> zebrazones;
  std::vector<CrossWalk> crosswalks;
  std::vector<RoadEdge> roadedges;
  std::vector<RoadMark> roadmarks;
  std::vector<StopLine> stoplines;
  std::vector<CrossRoad> crossroads;
  std::vector<SideWalk> sidewalks;
  std::vector<Gutter> gutters;
  std::vector<Curb> curbs;
  std::vector<StreetLight> streetlights;
  std::vector<UtilityPole> utilitypoles;


  if(argc >= 3){
    std::string host_name = argv[1];
    int port = std::atoi(argv[2]);
    gf = GetFile(host_name, port);
  } else {
    gf = GetFile();
  }

  struct stat st;
  std::string dirname = "/data/map/japan/aichi/nagoya/moriyama/vector";
  std::string tmp_dir = "/tmp" + dirname;
  if(stat(tmp_dir.c_str(), &st) != 0) {
    std::istringstream ss(dirname);
    std::string column;
    std::getline(ss, column, '/');
    tmp_dir = "/tmp";
    while (std::getline(ss, column, '/')) {
      tmp_dir += "/" + column;
      errno = 0;
      int ret = mkdir(tmp_dir.c_str(), 0755);
      if(ret < 0 && errno != EEXIST) perror("mkdir");
    }
    std::cerr << "mkdir " << tmp_dir << std::endl;
  }

  for(auto x: vmap_csv_list) {
    std::cerr << "start get file = " <<dirname << "/" << x << " ... ";
    if(gf.GetHTTPFile(dirname+"/"+x) == 0) {
      vmap_file_list.push_back("/tmp"+dirname+"/"+x);
      std::cerr << " download done" << std::endl;
    } else {
      std::cerr << " download failed" << std::endl;
    }
  }

  std::cerr << "Load csv files" << std::endl;

  for(auto x: vmap_file_list) {
    std::string name(basename((char *)x.c_str()));

    if(name == "point.csv") {
      pointclasses = read_pointclass(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", pointclasses.size()=" <<  pointclasses.size() << std::endl;
      pub_point_class.publish(pack_point_class_array(pointclasses));
    } else if(name == "pole.csv") {
      poleclasses = read_poleclass(x.c_str());
      std::cerr << "  load " << x.c_str()
		<< ", poleclasses.size()=" <<  poleclasses.size() << std::endl;
      pub_pole_class.publish(pack_pole_class_array(poleclasses));
    } else if(name == "vector.csv") {
      vectorclasses = read_vectorclass(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", vectorclasses.size()" << vectorclasses.size() << std::endl;
      pub_vector_class.publish(pack_vector_class_array(vectorclasses));
    } else if(name == "area.csv") {
      areaclasses = read_areaclass(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", areaclasses.size()=" << areaclasses.size() << std::endl;
      pub_area_class.publish(pack_area_class_array(areaclasses));
    } else if(name == "line.csv") {
      lines = read_lineclass(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", lines.size()=" << lines.size() << std::endl;
      pub_line_class.publish(pack_line_class_array(lines));
    } else if(name == "poledata.csv") {
      poles = read_pole(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", poles.size()=" << poles.size() << std::endl;
      pub_pole.publish(pack_pole_array(poles));
    } else if(name == "signaldata.csv") {
      signals = read_signal(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", signals.size()=" << signals.size() << std::endl;
      pub_signal.publish(pack_signal_array(signals));
    } else if(name == "roadsign.csv") {
      roadsigns = read_roadsign(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", roadsigns.size()=" << roadsigns.size() << std::endl;
      pub_road_sign.publish(pack_roadsign_array(roadsigns));
    } else if(name == "dtlane.csv") {
      dtlanes = read_dtlane(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", dtlanes.size()=" << dtlanes.size() << std::endl;
      pub_dtlane.publish(pack_dtlane_array(dtlanes));
    } else if(name == "node.csv") {
      nodes = read_node(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", nodes.size()=" << nodes.size() << std::endl;
      pub_node.publish(pack_node_array(nodes));
    } else if(name == "lane.csv") {
      lanes = read_lane(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", lanes.size()=" << lanes.size() << std::endl;
      pub_lane.publish(pack_lane_array(lanes));
    } else if(name == "whiteline.csv") {
      whitelines = read_whiteline(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", whitelines.size()=" << whitelines.size() << std::endl;
      pub_white_line.publish(pack_whiteline_array(whitelines));
    } else if(name == "zebrazone.csv") {
      zebrazones = read_zebrazone(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", zebrazones.size()=" << zebrazones.size() << std::endl;
      pub_zebra_zone.publish(pack_zebrazone_array(zebrazones));
    } else if(name == "crosswalk.csv") {
      crosswalks = read_crosswalk(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", crosswalks.size()=" << crosswalks.size() << std::endl;
      pub_cross_walk.publish(pack_crosswalk_array(crosswalks));
    } else if(name == "roadedge.csv") {
      roadedges = read_roadedge(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", roadedges.size()=" << roadedges.size() << std::endl;
      pub_road_edge.publish(pack_roadedge_array(roadedges));
    } else if(name == "road_surface_mark.csv") {
      roadmarks = read_roadmark(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", roadmarks.size()=" << roadmarks.size() << std::endl;
      pub_road_mark.publish(pack_roadmark_array(roadmarks));
    } else if(name == "stopline.csv") {
      stoplines = read_stopline(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", stoplines.size()=" << stoplines.size() << std::endl;
      pub_stop_line.publish(pack_stopline_array(stoplines));
    } else if(name == "crossroads.csv") {
      crossroads = read_crossroad(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", crossroads.size()=" << crossroads.size() << std::endl;
      pub_cross_road.publish(pack_crossroad_array(crossroads));
    } else if(name == "sidewalk.csv") {
      sidewalks = read_sidewalk(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", sidewalks.size()=" << sidewalks.size() << std::endl;
      pub_side_walk.publish(pack_sidewalk_array(sidewalks));
    } else if(name == "gutter.csv") {
      gutters = read_gutter(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", gutters.size()=" << gutters.size() << std::endl;
      pub_gutter.publish(pack_gutter_array(gutters));
    } else if(name == "curb.csv") {
      curbs = read_curb(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", curb.size()=" << curbs.size() << std::endl;
      pub_curb.publish(pack_curb_array(curbs));
    } else if(name == "streetlight.csv") {
      streetlights = read_streetlight(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", streetlights.size()=" << streetlights.size() << std::endl;
      pub_street_light.publish(pack_streetlight_array(streetlights));
    } else if(name == "utilitypole.csv") {
      utilitypoles = read_utilitypole(x.c_str());
      std::cerr << "  load " << x.c_str() 
		<< ", utilitypoles.size()=" << utilitypoles.size() << std::endl;
      pub_utility_pole.publish(pack_utilitypole_array(utilitypoles));
    }
  }

  std::cerr << "finished load files" << std::endl;

  if(pointclasses.size() <= 0) {
    std::cerr << "Usage: vector_map_loader csv_file\n"
	      << "\tpoint.csv is not loaded"
              << std::endl;
    std::exit(1);
  }


  visualization_msgs::MarkerArray marker_array;
  visualization_msgs::Marker marker;
  marker.header.frame_id = "/map";
  marker.header.stamp = ros::Time();
  marker.ns = "vector_map";
  marker.action = visualization_msgs::Marker::ADD;
  marker.lifetime = ros::Duration();
  marker.frame_locked = true;
  marker.type = visualization_msgs::Marker::CYLINDER;

  size_t i;

  std::cerr << "start publish vector map" << std::endl;

  marker.id = 0;

  // road data
  if(lanes.size() > 0 && dtlanes.size() <= 0) {
    std::cerr << "error: dtlane.csv is not loaded.\n"
	      << "\tlane.csv needs dtlane.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "lane";
  for (i=0; i<lanes.size(); i++) {
    if (lanes[i].lnid <= 0) {
      continue;
    }
    int did = lanes[i].did;
    int pid = dtlanes[did].pid;
    double ox, oy, oz, ow;

    marker.type = visualization_msgs::Marker::CUBE;

    ox = 0.0;
    oy = 0.0;
    oz = sin(dtlanes[did].dir / 2);
    ow = cos(dtlanes[did].dir / 2);

    if((lanes[i].span == 0 || (dtlanes[did].lw + dtlanes[did].rw) == 0)) continue;
    set_marker_data(&marker,
		    pointclasses[pid].bx - lanes[i].span/2, pointclasses[pid].ly - (dtlanes[did].lw + dtlanes[did].rw)/2, pointclasses[pid].h,
		    ox, oy, oz, ow,
		    lanes[i].span, dtlanes[did].lw + dtlanes[did].rw, 0.1,
		    0.5, 0, 0, 0.3);
    
    push_marker(&marker, &marker_array);
  }

  // pole
  if(poles.size() > 0 && (poleclasses.size() <= 0 || vectorclasses.size() <= 0)) {
    std::cerr << "error: pole.csv or vector.csv is not loaded \n"
	      << "\tpoledata.csv needs pole.csv and vector.csv "
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "pole";
  for (i=0; i<poles.size(); i++) {
    if (poles[i].id <= 0) {
      continue;
    }
    int plid = poles[i].plid;
    set_poleclass_data(poleclasses[plid], 
		       1, 1, 1, 1,
		       vectorclasses,
		       pointclasses,
		       &marker, &marker_array);
  }

  // signal
  if(signals.size() > 0 && (poleclasses.size() <= 0 || vectorclasses.size() <= 0)) {
    std::cerr << "error: pole.csv or vector.csv is not loaded.\n"
	      << "\tsignaldata.csv needs pole.csv and vector.csv "
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "signal";
  for (i=0; i<signals.size(); i++) {
    if (signals[i].id <= 0) {
      continue;
    }
    int vid = signals[i].vid;
    int pid = vectorclasses[vid].pid;

    marker.type = visualization_msgs::Marker::SPHERE;

    double ox, oy, oz, ow;
    calc_ang_to_xyzw(vectorclasses[vid].vang, vectorclasses[vid].hang,
		     &ox, &oy, &oz, &ow);

    double r = 0, g = 0, b = 0, a = 1;
    switch (signals[i].type) {
    case 1:
      r = 1;
      break;
    case 2:
      b = 1;
      break;
    case 3:
      r = 1;
      g = 1;
      break;
    case 4:
      marker.type = visualization_msgs::Marker::CUBE;
      r = 1;
      break;
    case 5:
      marker.type = visualization_msgs::Marker::CUBE;
      b = 1;
      break;
    default:
      break;
    }

    set_marker_data(&marker,
		    pointclasses[pid].bx, 
		    pointclasses[pid].ly, 
		    pointclasses[pid].h,
		    ox, oy, oz, ow,
		    0.5, 0.5, 0.5,
		    r, g, b, a);
    push_marker(&marker, &marker_array);


    // signal pole
    if (signals[i].type == 2) { // blue
      int plid = signals[i].plid;

      if (plid > 0) {
	set_poleclass_data(poleclasses[plid],
			   0.5, 0.5, 0.5, 1,
			   vectorclasses,
			   pointclasses,
			   &marker, &marker_array);
      }
    }
  }

  // roadsigns
  if(roadsigns.size() > 0 && (poleclasses.size() <= 0 || vectorclasses.size() <= 0)) {
    std::cerr << "error: pole.csv or vector.csv is not loaded\n"
	      << "\troadsign.csv needs pole.csv and vector.csv "
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "road sign";
  for (i=0; i<roadsigns.size(); i++) {
    if (roadsigns[i].id <= 0) {
      continue;
    }
    int vid = roadsigns[i].vid;
    int pid = vectorclasses[vid].pid;

    marker.type = visualization_msgs::Marker::SPHERE;

    double ox, oy, oz, ow;
    calc_ang_to_xyzw(vectorclasses[vid].vang, vectorclasses[vid].hang,
		     &ox, &oy, &oz, &ow);

    set_marker_data(&marker,
		    pointclasses[pid].bx, 
		    pointclasses[pid].ly, 
		    pointclasses[pid].h,
		    ox, oy, oz, ow,
		    1.0, 0.1, 1.0,
		    1, 1, 1, 1);
    push_marker(&marker, &marker_array);

    // road sign pole
    int plid = roadsigns[i].plid;
    set_poleclass_data(poleclasses[plid],
		       1, 1, 1, 1,
		       vectorclasses,
		       pointclasses,
		       &marker, &marker_array);
  }

  // cross walk
  if(crosswalks.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\tcrosswalk.csv needs area.csv and line.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "cross walk";
  for (i=0; i<crosswalks.size(); i++) {
    if (crosswalks[i].id <= 0) {
      continue;
    }
    int aid = crosswalks[i].aid;
    int slid = areaclasses[aid].slid;
    int elid = areaclasses[aid].elid;

    marker.type = visualization_msgs::Marker::LINE_STRIP;

    set_marker_data(&marker,
		    0, 0, 0,
		    0, 0, 0, 1,
		    0.1, 0, 0,
		    1, 1, 1, 1);
    
    marker.points.clear();
    for(int lid = slid; ; lid = lines[lid].flid) {
      int pid = lines[lid].bpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);
      if (lid == elid) {
	pid = lines[lid].fpid;
	add_marker_points_pointclass(&marker, pointclasses[pid]);
	break;
      }
    }

    push_marker(&marker, &marker_array);
  }

  // zebrazone
  if(zebrazones.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\tzebrazone.csv needs area.csv and line.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "zebrazone";
  marker.type = visualization_msgs::Marker::LINE_STRIP;
  set_areaclass_data(zebrazones, 0.1,
		     1, 1, 1, 1,
		     areaclasses,
		     lines,
		     pointclasses,
		     &marker, &marker_array);


  // white line
  if(whitelines.size() > 0 && lines.size() <= 0) {
    std::cerr << "err: line.csv is not loaded.\n"
	      << "\twhiteline.csv needs line.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "white line";
  marker.type = visualization_msgs::Marker::LINE_STRIP;
  for (i=0; i<whitelines.size(); i++) {
    if (whitelines[i].id <= 0) {
      continue;
    }
    int lid = whitelines[i].lid;
    if(lines[lid].blid == 0) {
      double r = 1.0, g = 1.0, b = 1.0;
      if(whitelines[i].color == 'Y') {
	g = 0.5;
	b = 0.0;
      }
      set_marker_data(&marker,
		      0, 0, 0,
		      0, 0, 0, 1,
		      whitelines[i].width, 0, 0,
		      r, g, b, 1);
    
      marker.points.clear();
    }

    int pid = lines[lid].bpid;
    add_marker_points_pointclass(&marker, pointclasses[pid]);
    if(lines[lid].flid == 0) {
      pid = lines[lid].fpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);

      push_marker(&marker, &marker_array);
    }
  }


  // roadedge
  if(roadedges.size() > 0 && (lines.size() <= 0)) {
    std::cerr << "error: line.csv is not loaded.\n"
	      << "\troadedge.csv needs line.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "road edge";
  marker.type = visualization_msgs::Marker::LINE_STRIP;
  for (i=0; i<roadedges.size(); i++) {
    if (roadedges[i].id <= 0) continue;
    int lid = roadedges[i].lid;
    if(lines[lid].blid == 0) {
      set_marker_data(&marker,
		      0, 0, 0,
		      0, 0, 0, 1,
		      0.1, 0, 0,
		      0.5, 0.5, 0.5, 1);		// grey @@@@
    
      marker.points.clear();
    }

    int pid = lines[lid].bpid;
    add_marker_points_pointclass(&marker, pointclasses[pid]);
    if(lines[lid].flid == 0) {
      pid = lines[lid].fpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);

      push_marker(&marker, &marker_array);
    }
  }


  // road_surface_mark
  if(roadmarks.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\troad_surface_mark.csv needs area.csv and line.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "road surface mark";
  for (i=0; i<roadmarks.size(); i++) {
    if (roadmarks[i].id <= 0) {
      continue;
    }
    int aid = roadmarks[i].aid;
    int slid = areaclasses[aid].slid;
    int elid = areaclasses[aid].elid;
    double w = 0.2;

    marker.type = visualization_msgs::Marker::LINE_STRIP;
    set_marker_data(&marker,
		    0, 0, 0,
		    0, 0, 0, 1,
		    w, 0, 0,
		    1, 1, 1, 1);
    marker.points.clear();
    for(int lid = slid; ; lid = lines[lid].flid) {
      int pid = lines[lid].bpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);
      if (lid == elid) {
	pid = lines[lid].fpid;
	add_marker_points_pointclass(&marker, pointclasses[pid]);
	break;
      }
    }

    push_marker(&marker, &marker_array);
  }

  // stop line
  if(stoplines.size() > 0 && lines.size() <= 0) {
    std::cerr << "error: line.csv is not loaded.\n"
	      << "\tstoplines.csv needs line.csv"
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "stop line";
  for (i=0; i<stoplines.size(); i++) {
    if (stoplines[i].id <= 0) {
      continue;
    }
    int lid = stoplines[i].lid;
    double r = 1.0, g = 1.0, b = 1.0;
    if(lines[lid].blid == 0) {
      set_marker_data(&marker,
		      0, 0, 0,
		      0, 0, 0, 1,
		      0.4, 0, 0,
		      r, g, b, 1);
    
      marker.points.clear();
    }
    int pid = lines[lid].bpid;
    add_marker_points_pointclass(&marker, pointclasses[pid]);
    if(lines[lid].flid == 0) {
      pid = lines[lid].fpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);

      push_marker(&marker, &marker_array);
    }
  }

  // cross road
  if(crossroads.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\tcrossroad.csv needs area.csv and line.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "cross road";
  marker.type = visualization_msgs::Marker::LINE_STRIP;
  set_areaclass_data(crossroads, 0.1,
		     1, 1, 1, 1,
		     areaclasses,
		     lines,
		     pointclasses,
		     &marker, &marker_array);


  // side walk (hodou) 
  if(sidewalks.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\tsidewalk.csv needs area.csv and line.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "side walk";
  marker.type = visualization_msgs::Marker::LINE_STRIP;
  set_areaclass_data(sidewalks, 0.1,
		     1, 1, 1, 1,
		     areaclasses,
		     lines,
		     pointclasses,
		     &marker, &marker_array);

  // gutter
  if(gutters.size() > 0 && (areaclasses.size() <= 0 || lines.size() <= 0)) {
    std::cerr << "error: area.csv or line.csv is not loaded.\n"
	      << "\tgutter.csv needs area.csv and line.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "gutter";
  marker.type = visualization_msgs::Marker::LINE_STRIP;

  for (i=0; i<gutters.size(); i++) {
    if (gutters[i].id <= 0) {
      continue;
    }
    int aid = gutters[i].aid;
    int slid = areaclasses[aid].slid;
    int elid = areaclasses[aid].elid;
    double r, g, b;

    switch(gutters[i].type) {
    case 0:
      r = 0.7, g = 0.7, b = 0.7;
      break;
    case 1:
      r = 0.8, g = 0.8, b = 0.8;
      break;
    case 2:
      r = 0.5, g = 0.5, b = 0.5;
      break;
    default:
      r = 1.0, g = 1.0, b = 1.0;
      break;
    }

    set_marker_data(&marker,
		    0, 0, 0,
		    0, 0, 0, 1,
		    0.2, 0, 0,
		    r, g, b, 1);
    marker.points.clear();
    for(int lid = slid; ; lid = lines[lid].flid) {
      int pid = lines[lid].bpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);
      if (lid == elid) {
	pid = lines[lid].fpid;
	add_marker_points_pointclass(&marker, pointclasses[pid]);
	break;
      }
    }

    push_marker(&marker, &marker_array);
  }

  // curb
  if(curbs.size() > 0 && lines.size() <= 0) {
    std::cerr << "error: line.csv is not loaded.\n"
	      << "\tcurb.csv needs line.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "curb";
  marker.type = visualization_msgs::Marker::LINE_STRIP;

  for (i=0; i<curbs.size(); i++) {
    if (curbs[i].id <= 0) {
      continue;
    }

    int lid = curbs[i].lid;
    if(lines[lid].blid == 0) {
      set_marker_data(&marker,
		      0, 0, 0,
		      0, 0, 0, 1,
		      curbs[i].width, 0, curbs[i].height,
		      0.7, 0.7, 0.7, 1);
    
      marker.points.clear();
    }

    int pid = lines[lid].bpid;
    add_marker_points_pointclass(&marker, pointclasses[pid]);
    if(lines[lid].flid == 0) {
      pid = lines[lid].fpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);

      push_marker(&marker, &marker_array);
    }
  }


  // streetlight
  if(streetlights.size() > 0 && (lines.size() <= 0 || poleclasses.size() <= 0 || vectorclasses.size() <= 0)) {
    std::cerr << "error: line.csv or pole.csv or vector.csv is not loaded.\n"
	      << "\tcurb.csv needs line.csv, pole.csv and vector.csv."
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "streetlight";

  for (i=0; i<streetlights.size(); i++) {
    if (streetlights[i].id <= 0) {
      continue;
    }

    marker.type = visualization_msgs::Marker::LINE_STRIP;
    int lid = streetlights[i].lid;
    if(lines[lid].blid == 0) {
      set_marker_data(&marker,
		      0, 0, 0,
		      0, 0, 0, 1,
		      0.2, 0, 0,
		      1, 1, 1, 1);
      marker.points.clear();
    }

    int pid = lines[lid].bpid;
    add_marker_points_pointclass(&marker, pointclasses[pid]);
    if(lines[lid].flid == 0) {
      pid = lines[lid].fpid;
      add_marker_points_pointclass(&marker, pointclasses[pid]);

      push_marker(&marker, &marker_array);
    }

    // streetlight pole
    int plid = streetlights[i].plid;
    if(plid <= 0) continue;
    set_poleclass_data(poleclasses[plid],
		       1, 1, 1, 1,
		       vectorclasses,
		       pointclasses,
		       &marker, &marker_array);
  }

  // utilitypole
  if(utilitypoles.size() > 0 && (poleclasses.size() <= 0 || vectorclasses.size() <= 0)) {
    std::cerr << "error: pole.csv or vector.csv is not loaded \n"
	      << "\tutilitypole.csv needs pole.csv and vector.csv "
	      << std::endl;
    std::exit(1);
  }
  marker.ns = "utilitypole";
  for (i=0; i<utilitypoles.size(); i++) {
  if (utilitypoles[i].id <= 0) continue;
  int plid = utilitypoles[i].plid;
  set_poleclass_data(poleclasses[plid], 
			0.5, 0.5, 0.5, 1,
			vectorclasses,
			pointclasses,
			&marker, &marker_array);
  }

  pub.publish(marker_array);

  vmap_stat_msg.data = true;
  stat_publisher.publish(vmap_stat_msg);

#ifdef DEBUG_PRINT
  std::cerr << "publish end" << std::endl;
#endif

  ros::spin();

  return 0;
}
Пример #9
0
bool GetFile(char *url, TCHAR *temp_folder, char *plugin_name, char *version, bool dlls_only, int recurse_count /*=0*/) {
	if(recurse_count > MAX_REDIRECT_RECURSE) {
		NLog("GetFile: error, too many redirects");
		return false;
	}

	TCHAR save_file[MAX_PATH];

	if(url == 0 || temp_folder == 0 || plugin_name == 0)
		return false;

	// ensure temp_folder exists
	if(!CreatePath(options.temp_folder)) {
		NLogF("GetFile: error creating temp folder, code %u", GetLastError());
		return false;
	}

	// ensure zip_folder exists, if necessary
	if(options.save_zips && !CreatePath(options.zip_folder)) {
		NLogF("GetFile: error creating zip folder, code %u", GetLastError());
		return false;
	}

	TCHAR *temp_str = GetTString(plugin_name);
	mir_sntprintf(save_file, SIZEOF(save_file), _T("%s\\%s"), temp_folder, temp_str);
	mir_free(temp_str);
	if (version) 
	{
		temp_str = GetTString(version);
		_tcscat(save_file, _T("_"));
		_tcscat(save_file, temp_str);
		mir_free(temp_str);
	}
	// copt extension from url
	char *ext = strrchr(url, '.');
	if(ext && *ext && strcmp(ext, ".dll") == 0) {
		_tcscat(save_file, _T(".dll"));
	} else { // default to zip extension (e.g. miranda fl)
		_tcscat(save_file, _T(".zip"));
		ext = ".zip";
	}

	// replace version text in URL
	char tmp_url[1024];
	if (version != NULL) {
		char *p;
		size_t pos = 0;
		size_t version_len = strlen(version);
		while ((p = strstr(url, "%VERSION%")) != NULL && (p - url + version_len < sizeof(tmp_url) - 1)) {
			strncpy(&tmp_url[pos], url, p - url);
			pos += p - url;
			strcpy(&tmp_url[pos], version);
			pos += version_len;
			url += p - url + 9; // 9 == strlen("%VERSION%")
		}
		if (strlen(url) < sizeof(tmp_url) - 1) {
			strcpy(&tmp_url[pos], url);
			pos += strlen(url);
		}
		tmp_url[pos] = 0;
		url = tmp_url;
	}


	NETLIBHTTPREQUEST req = {0};

	req.cbSize = sizeof(req);
	req.requestType = REQUEST_GET;
	req.szUrl = url;
	req.flags = NLHRF_NODUMP | NLHRF_HTTP11;
	req.nlc = hNetlibHttp;

	if (CallService(MS_SYSTEM_GETVERSION, 0, 0) >= PLUGIN_MAKE_VERSION(0,9,0,5))
		req.flags |= NLHRF_PERSISTENT | NLHRF_REDIRECT;

	NETLIBHTTPREQUEST *resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&req);

	if (resp) 
	{
		hNetlibHttp = resp->nlc;
		if (resp->resultCode == 200) 
		{
			if (ext && *ext && _stricmp(ext, ".zip") == 0) 
			{
				if (!options.no_unzip) 
					unzip_mem(resp->pData, resp->dataLength, temp_folder); 
										
				if (options.save_zips) 
				{
					TCHAR save_archive[MAX_PATH];
					mir_sntprintf(save_archive, SIZEOF(save_archive), _T("%s%s"), options.zip_folder, _tcsrchr(save_file, '\\'));

					HANDLE hSaveFile = CreateFile(save_archive, GENERIC_WRITE, FILE_SHARE_WRITE, 0, 
						CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
					if (hSaveFile != INVALID_HANDLE_VALUE) 
					{
						unsigned long bytes_written;
						WriteFile(hSaveFile, resp->pData, resp->dataLength, &bytes_written, NULL); 
						CloseHandle(hSaveFile);
					}
					else
						NLogF("GetFile: error creating file, code %u", GetLastError());
				} 
				
				if(dlls_only) 
				{
					NLog("Deleting non-dlls");
					DeleteNonDlls(temp_folder);
				}

			}
			else
			{
				HANDLE hSaveFile = CreateFile(save_file, GENERIC_WRITE, FILE_SHARE_WRITE, 0, 
					CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
				if (hSaveFile != INVALID_HANDLE_VALUE) 
				{
					unsigned long bytes_written;
					WriteFile(hSaveFile, resp->pData, resp->dataLength, &bytes_written, NULL); 
					CloseHandle(hSaveFile);
				}
				else
					NLogF("GetFile: error creating file, code %u", GetLastError());
			}

			CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
			return true;
		} 
		else if (resp->resultCode >= 300 && resp->resultCode < 400) 
		{
			// get new location
			bool ret = false;
			for (int i = 0; i < resp->headersCount; i++) 
			{
				if (_stricmp(resp->headers[i].szName, "Location") == 0) 
				{
					ret = GetFile(resp->headers[i].szValue, temp_folder, plugin_name, version, dlls_only, recurse_count + 1);
					break;
				}
			}
			CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
			return ret;
		} 
		else 
		{
			TCHAR buff[1024], *tmp;
			mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download \"%s\" - Invalid response, code %d"), (tmp = mir_a2t(plugin_name)), resp->resultCode);
			ShowError(buff);
			mir_free(tmp);
		}
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
	} 
	else 
	{
		hNetlibHttp = NULL;
		int err = GetLastError();
		if (err && !Miranda_Terminated()) 
		{
			TCHAR buff[1024], *tmp;
			int len = mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download \"%s\": "), (tmp = mir_a2t(plugin_name)));
			FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, buff + len, 512 - len, 0);
			ShowError(buff);
			mir_free(tmp);
		}
	}

	return false;
}
Пример #10
0
/*
 * Stage all files in the stream.
 */
static void
copyStream()
{
	int rval;
	FileInfo_t *file;
	int dcache;
	boolean_t reject;

	StageInit(Stream->vsn);

	/* Set loading flag for this stream. */
	PthreadMutexLock(&Stream->mutex);
	SET_FLAG(Stream->flags, SR_LOADING);
	PthreadMutexUnlock(&Stream->mutex);

	rval = LoadVolume();

	/* Reject if mount/open failed. */
	if (rval != 0) {
		PthreadMutexLock(&Stream->mutex);
		removeDcachedFile(Stream, rval);

		if (rval == ENODEV) {
			Stream->context = 0;
			PthreadMutexUnlock(&Stream->mutex);
			rejectRequest(0, B_TRUE);
			SET_FLAG(Instance->ci_flags, CI_shutdown);
		} else {
			PthreadMutexUnlock(&Stream->mutex);
			SendCustMsg(HERE, 19017, Stream->vsn);
			rejectRequest(rval, B_TRUE);
		}

		StageEnd();
		return;
	}

	/* VSN load has completed. */
	checkBuffers(Stream->vsn);

	PthreadMutexLock(&Stream->mutex);
	CLEAR_FLAG(Stream->flags, SR_LOADING);

	Instance->ci_seqnum = Stream->seqnum;
	reject = B_FALSE;

	/*
	 * Copy all files in stage stream request.  The files have
	 * been ordered to eliminate backward media positioning.
	 */

	while (STREAM_IS_VALID() && reject == B_FALSE) {

		/* Stop staging if parent died. */
		if (getppid() == 1) {
			SetErrno = 0;		/* set for trace */
			Trace(TR_ERR, "Detected stager daemon exit");

			Stream->first = EOS;
			SET_FLAG(Instance->ci_flags, CI_shutdown);
			break;
		}

		file = GetFile(Stream->first);

		PthreadMutexLock(&file->mutex);
		PthreadMutexUnlock(&Stream->mutex);

		/*
		 * If the first vsn, clear bytes read count.
		 * And if multivolume and stage -n set, initialize
		 * residual length.
		 */
		if (file->vsn_cnt == 0) {
			file->read = 0;
			if (GET_FLAG(file->flags, FI_MULTIVOL) &&
			    GET_FLAG(file->flags, FI_STAGE_NEVER)) {
				file->residlen = file->len;
			} else {
				file->residlen = 0;
			}
		}

		SET_FLAG(file->flags, FI_ACTIVE);

		PthreadMutexUnlock(&file->mutex);

		/* Set file in io control structure for archive read thread. */
		setIoThread(file);

		/* Log stage start. */
		file->eq = IoThread->io_drive;
		LogIt(LOG_STAGE_START, file);

		/*
		 * Check if last request was canceled.  If the last request
		 * was canceled, invalidate i/o buffers and clear cancel
		 * flag in the control structure.
		 */
		if (GET_FLAG(IoThread->io_flags, IO_cancel)) {
			ResetBuffers();
			CLEAR_FLAG(IoThread->io_flags, IO_cancel);
		}

		/*
		 * Next archive file.  If disk archive, we may be opening
		 * a disk archive tarball.
		 */
		if ((rval = NextArchiveFile()) == 0) {
			/* Prepare filesystem to receive staged file. */
			dcache = DiskCacheOpen(file);

		} else {
			/* Unable to open disk archive.  Error request. */
			Trace(TR_ERR, "Unable to open disk archive "
			    "copy: %d inode: %d.%d errno: %d",
			    file->copy + 1, file->id.ino, file->id.gen, errno);
			dcache = -1;
			file->error = errno;
			SendErrorResponse(file);
		}

		if (dcache >= 0 && rval == 0) {
			/*
			 * Notify reader thread that next file in stream
			 * is ready to be staged.
			 */
			ThreadStatePost(&IoThread->io_readReady);

			/* Write data to disk cache. */
			rval = DiskCacheWrite(file, dcache);

			if (rval != 0) {
				SendErrorResponse(file);

				/* Check if number of stream errors exceeded. */
				reject = ifMaxStreamErrors(file);
			}

			ThreadStateWait(&IoThread->io_readDone);

		} else if (rval != 0 && dcache >= 0) {
			/* Setup for error handling. */
			SetFileError(file, dcache, 0, EIO);
			SendErrorResponse(file);
		}

		EndArchiveFile();

		/* Remove file from stream before marking it as done. */
		PthreadMutexLock(&Stream->mutex);
		Stream->first = file->next;

		/* Device not available. */
		if (file->error == ENODEV) {
			SetErrno = 0;	/* set for trace */
			Trace(TR_ERR, "No device available");

			reject = B_TRUE;
			if (NumOpenFiles <= 0 && Instance->ci_first == NULL) {
				SET_FLAG(Instance->ci_flags, CI_shutdown);
				Instance->ci_busy = B_TRUE;
			}
		}

		/* Mark file staging as done. */
		SetStageDone(file);
		Stream->count--;

		if (Stream->first == EOS) {
			Stream->last = EOS;
		}

	}

	/* Reject rest of stages in this stream. */
	if (reject == B_TRUE) {
		if (Stream->first > EOS) {
			removeDcachedFile(Stream, ENODEV);
		}
		PthreadMutexUnlock(&Stream->mutex);
		rejectRequest(ENODEV, B_FALSE);
		PthreadMutexLock(&Stream->mutex);
	}

	/* Remove copy request, no one is waiting on it. */
	RemoveMapFile(copyRequestPath, Request, sizeof (CopyRequestInfo_t));
	Request = NULL;

	/* Ready to unload.  Mark stream as done. */
	SET_FLAG(Stream->flags, SR_DONE);
	PthreadMutexUnlock(&Stream->mutex);

	UnloadVolume();

	/*
	 * Unmap pages of memory.  Stream's memory
	 * mapped file is removed in parent.
	 */
	UnMapFile(Stream, sizeof (StreamInfo_t));
	Stream = NULL;

	StageEnd();
}
Пример #11
0
nsresult
nsFileChannel::OpenContentStream(bool async, nsIInputStream **result,
                                 nsIChannel** channel)
{
  // NOTE: the resulting file is a clone, so it is safe to pass it to the
  //       file input stream which will be read on a background thread.
  nsCOMPtr<nsIFile> file;
  nsresult rv = GetFile(getter_AddRefs(file));
  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIFileProtocolHandler> fileHandler;
  rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler));
  if (NS_FAILED(rv))
    return rv;
    
  nsCOMPtr<nsIURI> newURI;
  rv = fileHandler->ReadURLFile(file, getter_AddRefs(newURI));
  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIChannel> newChannel;
    rv = NS_NewChannel(getter_AddRefs(newChannel), newURI);
    if (NS_FAILED(rv))
      return rv;

    *result = nsnull;
    newChannel.forget(channel);
    return NS_OK;
  }

  nsCOMPtr<nsIInputStream> stream;

  if (mUploadStream) {
    // Pass back a nsFileUploadContentStream instance that knows how to perform
    // the file copy when "read" (the resulting stream in this case does not
    // actually return any data).

    nsCOMPtr<nsIOutputStream> fileStream;
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileStream), file,
                                     PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                                     PR_IRUSR | PR_IWUSR);
    if (NS_FAILED(rv))
      return rv;

    nsFileUploadContentStream *uploadStream =
        new nsFileUploadContentStream(async, fileStream, mUploadStream,
                                      mUploadLength, this);
    if (!uploadStream || !uploadStream->IsInitialized()) {
      delete uploadStream;
      return NS_ERROR_OUT_OF_MEMORY;
    }
    stream = uploadStream;

    SetContentLength64(0);

    // Since there isn't any content to speak of we just set the content-type
    // to something other than "unknown" to avoid triggering the content-type
    // sniffer code in nsBaseChannel.
    // However, don't override explicitly set types.
    if (!HasContentTypeHint())
      SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM));
  } else {
    nsCAutoString contentType;
    rv = MakeFileInputStream(file, stream, contentType);
    if (NS_FAILED(rv))
      return rv;

    EnableSynthesizedProgressEvents(true);

    // fixup content length and type
    if (ContentLength64() < 0) {
      PRInt64 size;
      rv = file->GetFileSize(&size);
      if (NS_FAILED(rv))
        return rv;
      SetContentLength64(size);
    }
    if (!contentType.IsEmpty())
      SetContentType(contentType);
  }

  *result = nsnull;
  stream.swap(*result);
  return NS_OK;
}
Пример #12
0
void AbstractBTGenerator::Run(HANDLE hThread, bool bFaultingThread)
{
    assert(m_process.IsValid());
    assert(hThread);

    if (!Init())
    {
        assert(false);
        return;
    }

    if (bFaultingThread)
    {
        const QString threadInfo = QString("Faulting thread (%1)").arg( reinterpret_cast<quintptr>(hThread) );
        emit DebugLine(threadInfo);
    }
    else
    {
        const QString threadInfo = QString("Thread %1").arg( reinterpret_cast<quintptr>(hThread) );
        emit DebugLine(threadInfo);
    }

    //HANDLE hFile = CreateFile(L"C:\\test\\test.dmp", FILE_ALL_ACCESS, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
    //if (!MiniDumpWriteDump(m_process.GetHandle(), m_process.GetId(), hFile,
    //    MiniDumpNormal, NULL, NULL, NULL))
    //{
    //    HRESULT hres = (HRESULT) GetLastError();
    //    printf("%08X\n\n", hres);
    //}
    //SafeCloseHandle(hFile);

    DWORD dw = SuspendThread(hThread);
    assert(dw != DWORD(-1));
    if (dw == DWORD(-1))
    {
        qCritical() << "SuspendThread() failed: " << GetLastError();
        return;
    }

    CONTEXT context;
    ZeroMemory(&context, sizeof(context));
    if (!bFaultingThread)
    {
        // if it's not the faulting thread, get its context
        context.ContextFlags = CONTEXT_FULL;
        if (!GetThreadContext(hThread, &context))
        {
            ResumeThread(hThread);
            assert(false);
            qCritical() << "GetThreadContext() failed: " << GetLastError();
            return;
        }
    }
    else
    {
        // if it is, get it from KCrash
        HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, sharedMemoryName);
        if (hMapFile == NULL)
        {
            qCritical() << "OpenFileMapping() failed: " << GetLastError();
            return;
        }
        CONTEXT *othercontext = (CONTEXT*) MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CONTEXT));
        if (othercontext == NULL)
        {
            qCritical() << "MapViewOfFile() failed: " << GetLastError();
            SafeCloseHandle(hMapFile);
            return;
        }
        CopyMemory(&context, othercontext, sizeof(CONTEXT));
        UnmapViewOfFile(othercontext); // continue even if it fails
        SafeCloseHandle(hMapFile);
    }

    // some of this stuff is taken from StackWalker
    ZeroMemory(&m_currentFrame, sizeof(m_currentFrame));
    DWORD machineType = IMAGE_FILE_MACHINE_UNKNOWN;
#if defined(_M_IX86)
    machineType = IMAGE_FILE_MACHINE_I386;
    m_currentFrame.AddrPC.Offset = context.Eip;
    m_currentFrame.AddrFrame.Offset = context.Ebp;
    m_currentFrame.AddrStack.Offset = context.Esp;
#elif defined(_M_X64)
    machineType = IMAGE_FILE_MACHINE_AMD64;
    m_currentFrame.AddrPC.Offset = context.Rip;
    m_currentFrame.AddrFrame.Offset = context.Rbp;
    m_currentFrame.AddrStack.Offset = context.Rsp;
#else
# error This architecture is not supported.
#endif
    m_currentFrame.AddrPC.Mode = AddrModeFlat;
    m_currentFrame.AddrFrame.Mode = AddrModeFlat;
    m_currentFrame.AddrStack.Mode = AddrModeFlat;

    SymSetOptions(SymGetOptions() | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
    SymInitialize(m_process.GetHandle(), NULL, FALSE);

    LoadSymbols();

    for (int i = 0; /*nothing*/; i++)
    {
        SetLastError(0);

        if (!StackWalk64(
            machineType,
            m_process.GetHandle(),
            hThread,
            &m_currentFrame,
            &context,
            &Callbacks::ReadProcessMemory,
            &Callbacks::SymFunctionTableAccess64,
            &Callbacks::SymGetModuleBase64,
            NULL))
        {
            emit Finished();
            qDebug() << "Stackwalk finished; GetLastError=" << GetLastError();
            break;
        }
        
        FrameChanged();

        QString modulename = GetModuleName();
        QString functionname = GetFunctionName();
        QString file = GetFile();
        int line = GetLine();
        QString address = QString::number(m_currentFrame.AddrPC.Offset, 16);

        QString debugLine = QString::fromLatin1(BACKTRACE_FORMAT).
            arg(modulename).arg(functionname).arg(file).arg(line).arg(address);
        
        emit DebugLine(debugLine);
    }

    // Resume the target thread now, or else the crashing process will not
    // be terminated
    ResumeThread(hThread);

    SymCleanup(m_process.GetHandle());

    emit DebugLine(QString());
}
Пример #13
0
HRESULT CPatch::GetFtpFiles(VOID)	// 여기에서 File List를 분석해서 GetFile을 계속 돌려줄것  return -1l : Error  0: End 1: Continue
{
	static int		Pos=0;
	char			szTemp[MAX_PATH];
	char			szDirStr[MAX_PATH];
	char			szFileName[MAX_PATH];

	UnCompressedFileNode* FileNode;
// 여기에서 Last Patch Date를 얻어야 한다.
	if(m_bEndPatch != TRUE)
	{
		if(m_PatchState == 3)
		{
			m_bEndPatch = TRUE;
			return 0l;
		}
		else
		{
			if((m_PatchState == 2) || (m_PatchState == 0)) 
			{
				Pos ++;
				if(m_PatchState == 2)
				{
					if(m_hFile != NULL)   
					{
						CloseHandle(m_hFile);
						m_hFile = NULL;
					}

	  				if(m_HFileFtp != NULL) 
					{
						InternetCloseHandle(m_HFileFtp);
						m_HFileFtp=NULL;
					}

					if(Pos > m_FACount)
					{
						m_PatchState = 0;
						m_bPatched   = TRUE;
						m_bEndPatch  = TRUE;
						return 0l;
					}
				}

				FileNode = GetFileNode(Pos - 1);
				ZeroMemory(szFileName, MAX_PATH);
				ZeroMemory(szTemp, MAX_PATH);

				DWORD dwErrNum;
				ZeroMemory(szDirStr, MAX_PATH);

				if(strcmp(FileNode->szFileName, "Mir2Patch.exe") == 0)	// Patch 화일 일 경우
				{
					DeleteFile(FileNode->szFileName);
					if(!jRegGetKey(_T(DEFAULT_REG_PATH), _T("setup path"), (LPBYTE)szDirStr))
					{
						ZeroMemory(szDirStr, MAX_PATH);
						GetCurrentDirectory(MAX_PATH, szDirStr);
						szDirStr[strlen(szDirStr)] ='\\';
						szDirStr[strlen(szDirStr)] = NULL;
					}
					for ( INT nCnt = strlen(szDirStr); nCnt >= 0; nCnt--)
					{
						if ( szDirStr[nCnt] == '\\' )
						{
							szDirStr[nCnt+1] = NULL;
							break;
						}
					}					
				}
				else
				{
					strcpy(szDirStr, m_UpdatePath);
				}

				strcpy(szFileName, FileNode->szFileName);
				strcpy(szTemp, szDirStr);
				strcat(szTemp, szFileName);
					
				m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
				if((dwErrNum=GetLastError()) == ERROR_FILE_EXISTS)
				{
					// 화일이 이미 존재 할 경우 그 화일의 크기를 확인
					// 업데이트 하려는 화일보다 작은 화일의 경우
					// 재대로 업데이트 되지 않은 화일 이므로 다시 업데이트를 받는다.
					m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
					DWORD High_FileSize;
					DWORD Low_FileSize;
					High_FileSize = 0;
					Low_FileSize = 0;
					Low_FileSize = GetFileSize(m_hFile, &High_FileSize);
					CloseHandle(m_hFile);
					m_hFile = NULL;
					if(Low_FileSize <= (DWORD)FileNode->lFileSize)
					{
						BOOL bResult = DeleteFile(szTemp);
						if (bResult)
						{
							//	Success
			//					MessageBox(NULL,"File Delete & ReCreate","Message",MB_OK); 
							m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
						}
						else
						{
			//					MessageBox(NULL,"File Delete Fail","Message",MB_OK); 
							//	Fail 
							return -1l;
						}
					}
				}
				strcpy(szTemp, m_szPatchDate);
				strcat(szTemp, "\\");
				strcat(szTemp, szFileName);
				m_HFileFtp = FtpOpenFile(m_HFtp, szTemp, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0);
			}
			else
			{
				FileNode = GetFileNode(Pos - 1);
			}
			strcpy(szTemp, m_szPatchDate);
			strcat(szTemp, "\\");
			strcat(szTemp, szFileName);
			GetFile(szTemp);		// 화일 계속 받기 ^^;
		}
	}
	else
	{
		// End Patch
		if(m_HFileFtp != NULL) 
		{
			InternetCloseHandle(m_HFileFtp);
			m_HFileFtp = NULL;
		}
		m_bPatched = TRUE;
		return 0l;
	}
	return 1l;
}
Пример #14
0
void						ReloadEmulator			(const std::string& aFileName)
{
    std::string filename = aFileName.empty() ? GetFile() : aFileName;

    if(!filename.empty())
    {
        //Load file as an archive
        ArchiveList* archive = new ArchiveList(Area(10, 10, 80, 80), filename);
        Summerface sface("Archive", archive);

        //If there are no items we are lost
        if(archive->IsValid())
        {
            //If there is more than one file, run a list to get the specific file
            if(archive->GetItemCount() > 1)
            {
                sface.Do();

                if(archive->WasCanceled())
                {
                    //HACK: If we do this too much we will get a stack overflow, but oh well. Beats a goto anyway
                    ReloadEmulator("");
                    return;
                }
            }

            //Get the size of the selected file
            uint32_t size = archive->GetSelectedSize();

            //We can only load files up to 64 megabytes, for CD's you should load cue files not BIN files
            if(size)
            {
                void* data = malloc(size);
                if(data)
                {
                    if(archive->GetSelectedData(size, data))
                    {
                        //Clean up the filename, if we are loading a file from an archive replace the name of the zip file with the name of the file inside
                        if(ArchiveList::IsArchive(filename) && filename.rfind('/') != std::string::npos)
                        {
                            filename = filename.substr(0, filename.rfind('/') + 1);
                            filename += archive->GetSelectedFileName();
                        }
                        else
                        {
                            filename = archive->GetSelectedFileName();
                        }

                        //Load the game into mednafen
                        MednafenEmu::CloseGame();
                        if(!MednafenEmu::LoadGame(filename.c_str(), data, size))
                        {
                            ReloadEmulator("");
                            return;
                        }
                    }
                    else
                    {
                        free(data);

                        LibES::Error(_("Could not read file. [Failed to extract]"));
                        ReloadEmulator("");
                        return;
                    }
                }
                else
                {
                    LibES::Error(_("Could not allocate enough memory to load file. All CD games must be loaded through cue files. [File size too large]"));
                    ReloadEmulator("");
                    return;
                }
            }
            else
            {
                LibES::Error(_("Could not read file. [File empty]"));
                ReloadEmulator("");
                return;
            }
        }
        else
        {
            LibES::Error(_("Could not read file. [File not accessible]"));
            ReloadEmulator("");
            return;
        }
    }
    else if(!MednafenEmu::IsGameLoaded())
    {
        Exit();
    }
}
Пример #15
0
bool BaseMediaDocument::Process() {
	double startTime = 0;
	double endTime = 0;
	GETCLOCKS(startTime, double);

	//1. Compute the names
	_mediaFilePath = _metadata.mediaFullPath();
	_metaFilePath = _metadata.metaFileFullPath();
	_seekFilePath = _metadata.seekFileFullPath();
	_keyframeSeek = _metadata.storage().keyframeSeek();
	_seekGranularity = _metadata.storage().seekGranularity();

	//1. Open the media file
	if (!GetFile(_mediaFilePath, 4 * 1024 * 1024, _mediaFile)) {
		FATAL("Unable to open media file: %s", STR(_mediaFilePath));
		return false;
	}

	//4. Read the document
	if (!ParseDocument()) {
		FATAL("Unable to parse document");
		return false;
	}

	//5. Build the frames
	if (!BuildFrames()) {
		FATAL("Unable to build frames");
		return false;
	}

	//6. Save the seek file
	if (!SaveSeekFile()) {
		FATAL("Unable to save seeking file");
		return false;
	}

	//7. Build the meta
	if (!SaveMetaFile()) {
		FATAL("Unable to save meta file");
		return false;
	}

	GETCLOCKS(endTime, double);

	uint64_t framesCount = _audioSamplesCount + _videoSamplesCount;
	if (framesCount == 0)
		framesCount = (uint64_t) _frames.size();

	INFO("%"PRIu64" frames computed in %.2f seconds at a speed of %.2f FPS",
			framesCount,
			(endTime - startTime) / (double) CLOCKS_PER_SECOND,
			(double) framesCount / ((endTime - startTime) / (double) CLOCKS_PER_SECOND));
	if (_frames.size() != 0) {
		uint32_t totalSeconds = (uint32_t) (((uint32_t) _frames[_frames.size() - 1].dts) / 1000);
		uint32_t hours = totalSeconds / 3600;
		uint32_t minutes = (totalSeconds - hours * 3600) / 60;
		uint32_t seconds = (totalSeconds - hours * 3600 - minutes * 60);
		INFO("File size: %"PRIu64" bytes; Duration: %u:%u:%u (%u sec); Optimal bandwidth: %.2f kB/s",
				_mediaFile.Size(),
				hours, minutes, seconds,
				totalSeconds,
				(double) _streamCapabilities.GetTransferRate() / 8192);
	}

	moveFile(_seekFilePath + ".tmp", _seekFilePath);
	moveFile(_metaFilePath + ".tmp", _metaFilePath);

	chmod(STR(_seekFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	chmod(STR(_metaFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	return true;
}
Пример #16
0
NS_IMETHODIMP
nsFilePicker::Show(PRInt16 *aReturn)
{
  NS_ENSURE_ARG_POINTER(aReturn);

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));

  GtkWindow *parent_widget = get_gtk_window_for_nsiwidget(mParentWidget);

  GtkFileChooserAction action = GetGtkFileChooserAction(mMode);
  const gchar *accept_button = (action == GTK_FILE_CHOOSER_ACTION_SAVE)
                               ? GTK_STOCK_SAVE : GTK_STOCK_OPEN;
#if (MOZ_PLATFORM_MAEMO == 5)
  GtkWidget *file_chooser =
    hildon_file_chooser_dialog_new_with_properties(parent_widget,
                                                   "action", action,
                                                   "open-button-text", accept_button,
                                                   NULL);
  gtk_window_set_title(GTK_WINDOW(file_chooser), title);
#else
  GtkWidget *file_chooser =
      gtk_file_chooser_dialog_new(title, parent_widget, action,
                                  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                  accept_button, GTK_RESPONSE_ACCEPT,
                                  NULL);
  gtk_dialog_set_alternative_button_order(GTK_DIALOG(file_chooser),
                                          GTK_RESPONSE_ACCEPT,
                                          GTK_RESPONSE_CANCEL,
                                          -1);
  if (mAllowURLs) {
    gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(file_chooser), FALSE);
  }
#endif

  if (action == GTK_FILE_CHOOSER_ACTION_OPEN || action == GTK_FILE_CHOOSER_ACTION_SAVE) {
    GtkWidget *img_preview = gtk_image_new();
    gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(file_chooser), img_preview);
    g_signal_connect(file_chooser, "update-preview", G_CALLBACK(UpdateFilePreviewWidget), img_preview);
  }

  if (parent_widget && parent_widget->group) {
    gtk_window_group_add_window(parent_widget->group, GTK_WINDOW(file_chooser));
  }

  NS_ConvertUTF16toUTF8 defaultName(mDefault);
  switch (mMode) {
    case nsIFilePicker::modeOpenMultiple:
      gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(file_chooser), TRUE);
      break;
    case nsIFilePicker::modeSave:
      gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_chooser),
                                        defaultName.get());
      break;
  }

  nsCOMPtr<nsIFile> defaultPath;
  if (mDisplayDirectory) {
    mDisplayDirectory->Clone(getter_AddRefs(defaultPath));
  } else if (mPrevDisplayDirectory) {
    mPrevDisplayDirectory->Clone(getter_AddRefs(defaultPath));
  }

  if (defaultPath) {
    if (!defaultName.IsEmpty() && mMode != nsIFilePicker::modeSave) {
      // Try to select the intended file. Even if it doesn't exist, GTK still switches
      // directories.
      defaultPath->AppendNative(defaultName);
      nsCAutoString path;
      defaultPath->GetNativePath(path);
      gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(file_chooser), path.get());
    } else {
      nsCAutoString directory;
      defaultPath->GetNativePath(directory);
      gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(file_chooser),
                                          directory.get());
    }
  }

  gtk_dialog_set_default_response(GTK_DIALOG(file_chooser), GTK_RESPONSE_ACCEPT);

  PRInt32 count = mFilters.Length();
  for (PRInt32 i = 0; i < count; ++i) {
    // This is fun... the GTK file picker does not accept a list of filters
    // so we need to split out each string, and add it manually.

    char **patterns = g_strsplit(mFilters[i].get(), ";", -1);
    if (!patterns) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    GtkFileFilter *filter = gtk_file_filter_new();
    for (int j = 0; patterns[j] != NULL; ++j) {
      nsCAutoString caseInsensitiveFilter = MakeCaseInsensitiveShellGlob(g_strstrip(patterns[j]));
      gtk_file_filter_add_pattern(filter, caseInsensitiveFilter.get());
    }

    g_strfreev(patterns);

    if (!mFilterNames[i].IsEmpty()) {
      // If we have a name for our filter, let's use that.
      const char *filter_name = mFilterNames[i].get();
      gtk_file_filter_set_name(filter, filter_name);
    } else {
      // If we don't have a name, let's just use the filter pattern.
      const char *filter_pattern = mFilters[i].get();
      gtk_file_filter_set_name(filter, filter_pattern);
    }

    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(file_chooser), filter);

    // Set the initially selected filter
    if (mSelectedType == i) {
      gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(file_chooser), filter);
    }
  }

  gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(file_chooser), PR_TRUE);
  gint response = RunDialog(GTK_DIALOG(file_chooser));

  switch (response) {
    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_ACCEPT:
    ReadValuesFromFileChooser(file_chooser);
    *aReturn = nsIFilePicker::returnOK;
    if (mMode == nsIFilePicker::modeSave) {
      nsCOMPtr<nsILocalFile> file;
      GetFile(getter_AddRefs(file));
      if (file) {
        PRBool exists = PR_FALSE;
        file->Exists(&exists);
        if (exists)
          *aReturn = nsIFilePicker::returnReplace;
      }
    }
    break;

    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_CLOSE:
    case GTK_RESPONSE_DELETE_EVENT:
    *aReturn = nsIFilePicker::returnCancel;
    break;

    default:
    NS_WARNING("Unexpected response");
    *aReturn = nsIFilePicker::returnCancel;
    break;
  }

  gtk_widget_destroy(file_chooser);

  return NS_OK;
}
Пример #17
0
trpgrAppFile *trpgrAppFileCache::GetFile(trpgEndian ness,int id)
{
    return GetFile(ness,id,-1,-1);
}
Пример #18
0
NS_IMETHODIMP
nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent,
			  nsIFile** aFile)
{
  nsresult rv;

  bool gettingProfile = false;

  if (!strcmp(aProperty, NS_APP_USER_PROFILE_LOCAL_50_DIR)) {
    // If XRE_NotifyProfile hasn't been called, don't fall through to
    // mAppProvider on the profile keys.
    if (!mProfileNotified)
      return NS_ERROR_FAILURE;

    if (mProfileLocalDir)
      return mProfileLocalDir->Clone(aFile);

    if (mAppProvider)
      return mAppProvider->GetFile(aProperty, aPersistent, aFile);

    // This falls through to the case below
    gettingProfile = true;
  }
  if (!strcmp(aProperty, NS_APP_USER_PROFILE_50_DIR) || gettingProfile) {
    if (!mProfileNotified)
      return NS_ERROR_FAILURE;

    if (mProfileDir)
      return mProfileDir->Clone(aFile);

    if (mAppProvider)
      return mAppProvider->GetFile(aProperty, aPersistent, aFile);

    // If we don't succeed here, bail early so that we aren't reentrant
    // through the "GetProfileDir" call below.
    return NS_ERROR_FAILURE;
  }

  if (mAppProvider) {
    rv = mAppProvider->GetFile(aProperty, aPersistent, aFile);
    if (NS_SUCCEEDED(rv) && *aFile)
      return rv;
  }

  *aPersistent = true;

  if (!strcmp(aProperty, NS_GRE_DIR)) {
    return mGREDir->Clone(aFile);
  }
  else if (!strcmp(aProperty, NS_OS_CURRENT_PROCESS_DIR) ||
      !strcmp(aProperty, NS_APP_INSTALL_CLEANUP_DIR)) {
    return GetAppDir()->Clone(aFile);
  }

  rv = NS_ERROR_FAILURE;
  nsCOMPtr<nsIFile> file;

  if (!strcmp(aProperty, NS_APP_PROFILE_DEFAULTS_50_DIR) ||
           !strcmp(aProperty, NS_APP_PROFILE_DEFAULTS_NLOC_50_DIR)) {
    return GetProfileDefaultsDir(aFile);
  }
  else if (!strcmp(aProperty, NS_APP_PREF_DEFAULTS_50_DIR))
  {
    // return the GRE default prefs directory here, and the app default prefs
    // directory (if applicable) in NS_APP_PREFS_DEFAULTS_DIR_LIST.
    rv = mGREDir->Clone(getter_AddRefs(file));
    if (NS_SUCCEEDED(rv)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("defaults"));
      if (NS_SUCCEEDED(rv))
        rv = file->AppendNative(NS_LITERAL_CSTRING("pref"));
    }
  }
  else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_DIR) ||
           !strcmp(aProperty, XRE_USER_APP_DATA_DIR)) {
    rv = GetUserAppDataDirectory(getter_AddRefs(file));
  }
  else if (!strcmp(aProperty, XRE_UPDATE_ROOT_DIR)) {
    rv = GetUpdateRootDir(getter_AddRefs(file));
  }
  else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_FILE)) {
    rv = GetUserAppDataDirectory(getter_AddRefs(file));
    if (NS_SUCCEEDED(rv))
      rv = file->AppendNative(NS_LITERAL_CSTRING(APP_REGISTRY_NAME));
  }
  else if (!strcmp(aProperty, NS_APP_USER_PROFILES_ROOT_DIR)) {
    rv = GetUserProfilesRootDir(getter_AddRefs(file), nullptr, nullptr, nullptr);
  }
  else if (!strcmp(aProperty, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR)) {
    rv = GetUserProfilesLocalDir(getter_AddRefs(file), nullptr, nullptr, nullptr);
  }
  else if (!strcmp(aProperty, XRE_EXECUTABLE_FILE) && gArgv[0]) {
    nsCOMPtr<nsIFile> lf;
    rv = XRE_GetBinaryPath(gArgv[0], getter_AddRefs(lf));
    if (NS_SUCCEEDED(rv))
      file = lf;
  }

  else if (!strcmp(aProperty, NS_APP_PROFILE_DIR_STARTUP) && mProfileDir) {
    return mProfileDir->Clone(aFile);
  }
  else if (!strcmp(aProperty, NS_APP_PROFILE_LOCAL_DIR_STARTUP)) {
    if (mProfileLocalDir)
      return mProfileLocalDir->Clone(aFile);

    if (mProfileDir)
      return mProfileDir->Clone(aFile);

    if (mAppProvider)
      return mAppProvider->GetFile(NS_APP_PROFILE_DIR_STARTUP, aPersistent,
                                   aFile);
  }
#if defined(XP_UNIX) || defined(XP_MACOSX)
  else if (!strcmp(aProperty, XRE_SYS_LOCAL_EXTENSION_PARENT_DIR)) {
#ifdef ENABLE_SYSTEM_EXTENSION_DIRS
    return GetSystemExtensionsDirectory(aFile);
#else
    return NS_ERROR_FAILURE;
#endif
  }
#endif
#if defined(XP_UNIX) && !defined(XP_MACOSX)
  else if (!strcmp(aProperty, XRE_SYS_SHARE_EXTENSION_PARENT_DIR)) {
#ifdef ENABLE_SYSTEM_EXTENSION_DIRS
#if defined(__OpenBSD__) || defined(__FreeBSD__)
    static const char *const sysLExtDir = "/usr/local/share/mozilla/extensions";
#else
    static const char *const sysLExtDir = "/usr/share/mozilla/extensions";
#endif
    return NS_NewNativeLocalFile(nsDependentCString(sysLExtDir),
                                 false, aFile);
#else
    return NS_ERROR_FAILURE;
#endif
  }
#endif
  else if (!strcmp(aProperty, XRE_USER_SYS_EXTENSION_DIR)) {
#ifdef ENABLE_SYSTEM_EXTENSION_DIRS
    return GetSysUserExtensionsDirectory(aFile);
#else
    return NS_ERROR_FAILURE;
#endif
  }
  else if (!strcmp(aProperty, XRE_APP_DISTRIBUTION_DIR)) {
    bool persistent = false;
    rv = GetFile(XRE_EXECUTABLE_FILE, &persistent, getter_AddRefs(file));
    if (NS_SUCCEEDED(rv))
      rv = file->SetNativeLeafName(NS_LITERAL_CSTRING("distribution"));
  }
  else if (NS_SUCCEEDED(GetProfileStartupDir(getter_AddRefs(file)))) {
    // We need to allow component, xpt, and chrome registration to
    // occur prior to the profile-after-change notification.
    if (!strcmp(aProperty, NS_APP_USER_CHROME_DIR)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("chrome"));
    }
  }

  if (NS_SUCCEEDED(rv) && file) {
    NS_ADDREF(*aFile = file);
    return NS_OK;
  }

  bool ensureFilePermissions = false;

  if (NS_SUCCEEDED(GetProfileDir(getter_AddRefs(file)))) {
    if (!strcmp(aProperty, NS_APP_PREFS_50_DIR)) {
      rv = NS_OK;
    }
    else if (!strcmp(aProperty, NS_APP_PREFS_50_FILE)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("prefs.js"));
    }
    else if (!strcmp(aProperty, NS_METRO_APP_PREFS_50_FILE)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("metro-prefs.js"));
    }
    else if (!strcmp(aProperty, NS_LOCALSTORE_UNSAFE_FILE)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("localstore.rdf"));
    }
    else if (!strcmp(aProperty, NS_APP_LOCALSTORE_50_FILE)) {
      if (gSafeMode) {
        rv = file->AppendNative(NS_LITERAL_CSTRING("localstore-safe.rdf"));
        file->Remove(false);
      }
      else {
        rv = file->AppendNative(NS_LITERAL_CSTRING("localstore.rdf"));
        EnsureProfileFileExists(file);
        ensureFilePermissions = true;
      }
    }
    else if (!strcmp(aProperty, NS_APP_USER_MIMETYPES_50_FILE)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("mimeTypes.rdf"));
      EnsureProfileFileExists(file);
      ensureFilePermissions = true;
    }
    else if (!strcmp(aProperty, NS_APP_DOWNLOADS_50_FILE)) {
      rv = file->AppendNative(NS_LITERAL_CSTRING("downloads.rdf"));
    }
    else if (!strcmp(aProperty, NS_APP_PREFS_OVERRIDE_DIR)) {
      rv = mProfileDir->Clone(getter_AddRefs(file));
      nsresult tmp = file->AppendNative(NS_LITERAL_CSTRING(PREF_OVERRIDE_DIRNAME));
      if (NS_FAILED(tmp)) {
        rv = tmp;
      }
      tmp = EnsureDirectoryExists(file);
      if (NS_FAILED(tmp)) {
        rv = tmp;
      }
    }
  }
  if (NS_FAILED(rv) || !file)
    return NS_ERROR_FAILURE;

  if (ensureFilePermissions) {
    bool fileToEnsureExists;
    bool isWritable;
    if (NS_SUCCEEDED(file->Exists(&fileToEnsureExists)) && fileToEnsureExists
        && NS_SUCCEEDED(file->IsWritable(&isWritable)) && !isWritable) {
      uint32_t permissions;
      if (NS_SUCCEEDED(file->GetPermissions(&permissions))) {
        rv = file->SetPermissions(permissions | 0600);
        NS_ASSERTION(NS_SUCCEEDED(rv), "failed to ensure file permissions");
      }
    }
  }

  NS_ADDREF(*aFile = file);
  return NS_OK;
}
Пример #19
0
void CUpdater::DoUpdates(CMenus *pMenus)
{
    bool noErrors = true;

    // Remove Files
    for (int i=0; i<m_vToRemove.size(); i++)
        if (fs_is_file(m_vToRemove[i].c_str()) && fs_remove(m_vToRemove[i].c_str()) != 0) noErrors = false;
    m_vToRemove.clear();

    // Download Files
    for (int i=0; i<m_vToDownload.size(); i++)
        if (!GetFile(m_vToDownload[i].c_str(), m_vToDownload[i].c_str())) noErrors = false;
    m_vToDownload.clear();

    if (m_NeedUpdateClient)
    {
        #ifdef CONF_FAMILY_WINDOWS
            #ifdef CONF_PLATFORM_WIN64
                if (!GetFile("teeworlds64.exe", "tw_tmp"))
            #else
                if (!GetFile("teeworlds.exe", "tw_tmp"))
            #endif
        #elif defined(CONF_FAMILY_UNIX)
            #ifdef CONF_PLATFORM_MACOSX
                if (!GetFile("teeworlds_mac", "tw_tmp"))
            #elif defined(CONF_ARCH_IA64) || defined(CONF_ARCH_AMD64)
                if (!GetFile("teeworlds64", "tw_tmp"))
            #else
                if (!GetFile("teeworlds", "tw_tmp"))
            #endif
        #endif
        {
            noErrors = false;
        }
    }

    if (m_NeedUpdateServer)
    {
        #ifdef CONF_FAMILY_WINDOWS
            #ifdef CONF_PLATFORM_WIN64
                if (!GetFile("teeworlds_srv64.exe", "teeworlds_srv.exe"))
            #else
                if (!GetFile("teeworlds_srv.exe", "teeworlds_srv.exe"))
            #endif
        #elif defined(CONF_FAMILY_UNIX)
            #ifdef CONF_PLATFORM_MACOSX
                if (!GetFile("teeworlds_srv_mac", "teeworlds_srv"))
            #elif defined(CONF_ARCH_IA64) || defined(CONF_ARCH_AMD64)
                if (!GetFile("teeworlds_srv64", "teeworlds_srv"))
            #else
                if (!GetFile("teeworlds_srv", "teeworlds_srv"))
            #endif
        #endif
        {
            noErrors = false;
        }
    }

    if (noErrors)
        m_Updated = true;

    pMenus->SetPopup(CMenus::POPUP_UPDATER_RESULT);
}
Пример #20
0
/// Accepts an incoming connection on a server pipe.
///
/// @param[in] timeout maximum time to wait for a client in milliseconds
/// @return this end of a pipe connected to the client, or NULL if none was available
CNamedPipe *CNamedPipe::Accept (unsigned long timeout) {
	assert (IsServer ());
#ifdef _WIN32
	if (!ConnectNamedPipe (GetFile (), GetOverlapped ())) {
		if (GetLastError () != ERROR_PIPE_CONNECTED) {
			if (!WaitOnOverlapped (timeout)) {
				DWORD dwError = GetLastError ();
				LOGWARN (TEXT ("Overlapped result not available, error ") << dwError);
				SetLastError (dwError);
				return NULL;
			}
		}
	}
	HANDLE handle = _CreatePipe (GetName (), IsServer (), false, IsReader ());
	if (!handle) {
		DWORD dwError = GetLastError ();
		LOGWARN (TEXT ("Couldn't create replacement pipe for server, error ") << dwError);
		SetLastError (dwError);
		return NULL;
	}
	CNamedPipe *poClient = new CNamedPipe (GetFile (), GetName (), false, IsReader ());
	SetFile (handle);
	return poClient;
#else
failedOperation:
	struct sockaddr_un addr;
	bool bLazyWait = false;
	if (IsLazyClosing ()) {
		bLazyWait = true;
		timeout = IsLazyClosing ();
	}
timeoutOperation:
	int sock;
	if (BeginOverlapped (timeout, true)) {
		socklen_t len = sizeof (addr);
		sock = accept (GetFile (), (struct sockaddr*)&addr, &len);
		EndOverlapped ();
	} else {
		sock = -1;
	}
	if (sock < 0) {
		int ec = GetLastError ();
		if (ec == EINTR) {
			LOGDEBUG (TEXT ("Accept interrupted"));
			if (IsLazyClosing ()) {
				if (bLazyWait) {
					LOGINFO (TEXT ("Closing file on idle timeout"));
					Close ();
				}
			}
			if (!IsClosed () && !bLazyWait) {
				bLazyWait = true;
				timeout = IsLazyClosing ();
				LOGDEBUG (TEXT ("Resuming operation with idle timeout of ") << timeout << TEXT ("ms"));
				goto timeoutOperation;
			}
		}
		LOGWARN (TEXT ("Couldn't accept client, error ") << ec);
		SetLastError (ec);
		return NULL;
	}
	LOGINFO (TEXT ("Connection accepted on ") << GetName ());
	if (!_SetDefaultSocketOptions (sock)) {
		int ec = GetLastError ();
		close (sock);
		LOGWARN (TEXT ("Couldn't set default socket options, error ") << ec);
		SetLastError (ec);
		return NULL;
	}
	if ((send (sock, "!", 1, 0) != 1) || fcntl (sock, F_SETFL, O_NONBLOCK)) {
		int ec = GetLastError ();
		close (sock);
		if (ec == EPIPE) {
			LOGWARN (TEXT ("Client disconnected before receiving handshake"));
			goto failedOperation;
		}
		LOGWARN (TEXT ("Couldn't send handshake message, error ") << ec);
		SetLastError (ec);
		return NULL;
	} else {
		LOGDEBUG (TEXT ("Handshake message written"));
	}
	return new CNamedPipe (sock, GetName (), false, IsReader ());
#endif
}
Пример #21
0
int main() {
     File f = GetFile();  // сейчас не сработает - конструктор копирования запрещён!
     // ...
}