コード例 #1
0
ファイル: OCPNPlatform.cpp プロジェクト: vonwenm/OpenCPN
wxString &OCPNPlatform::GetPrivateDataDir()
{
    if(m_PrivateDataDir.IsEmpty()){
        //      Establish the prefix of the location of user specific data files
        wxStandardPaths& std_path = GetStdPaths();
        
#ifdef __WXMSW__
        m_PrivateDataDir = GetHomeDir();                     // should be {Documents and Settings}\......
#elif defined __WXOSX__
        m_PrivateDataDir = std_path.GetUserConfigDir();     // should be ~/Library/Preferences
        appendOSDirSlash(&m_PrivateDataDir);
        m_PrivateDataDir.Append(_T("opencpn"));
#else
        m_PrivateDataDir = std_path.GetUserDataDir();       // should be ~/.opencpn
#endif
        
        if( g_bportable )
            m_PrivateDataDir = GetHomeDir();
        
#ifdef __OCPN__ANDROID__
        m_PrivateDataDir = androidGetPrivateDir();
#endif
    }
    
    return m_PrivateDataDir;
}
コード例 #2
0
ファイル: GetDflt.c プロジェクト: sheldonrobinson/VcXsrv
static XrmDatabase
InitDefaults(
    Display *dpy)			/* display for defaults.... */
{
    XrmDatabase userdb;
    XrmDatabase xdb;
    char fname[PATH_MAX];               /* longer than any conceivable size */
    char *xenv;

    XrmInitialize();

    /*
     * See lib/Xt/Initialize.c
     *
     * First, get the defaults from the server; if none, then load from
     * ~/.Xdefaults.  Next, if there is an XENVIRONMENT environment variable,
     * then load that file.
     */
     
    if (dpy->xdefaults == NULL) {
	#ifdef _MSC_VER
	const char *slashDotXdefaults = ".Xdefaults";
	#else
	const char *slashDotXdefaults = "/.Xdefaults";
	#endif

	(void) GetHomeDir (fname, PATH_MAX - strlen (slashDotXdefaults) - 1);
	(void) strcat (fname, slashDotXdefaults);
	xdb = XrmGetFileDatabase (fname);
    } else {
	xdb = XrmGetStringDatabase(dpy->xdefaults);
    }

    if (!(xenv = getenv ("XENVIRONMENT"))) {
	#ifdef _MSC_VER
	const char *slashDotXdefaultsDash = ".Xdefaults-";
	#else
	const char *slashDotXdefaultsDash = "/.Xdefaults-";
	#endif
	int len;

	(void) GetHomeDir (fname, PATH_MAX - strlen (slashDotXdefaultsDash) - 1);
	(void) strcat (fname, slashDotXdefaultsDash);
	len = strlen (fname);
	(void) _XGetHostname (fname+len, PATH_MAX-len);
	xenv = fname;
    }
    userdb = XrmGetFileDatabase (xenv);
    XrmMergeDatabases (userdb, &xdb);
    return (xdb);

#ifdef old
    if (fname[0] != '\0') userdb =  XrmGetFileDatabase(fname);
    xdb = XrmGetStringDatabase(dpy->xdefaults);
    XrmMergeDatabases(userdb, &xdb);
    return xdb;
#endif
}
コード例 #3
0
ファイル: Inform.cpp プロジェクト: wyrover/Windows-Inform7
void InformApp::FindExtensions(void)
{
  m_extensions.clear();
  for (int i = 0; i < 2; i++)
  {
    CString path;
    switch (i)
    {
    case 0:
      path.Format("%s\\Internal\\Extensions\\*.*",(LPCSTR)GetAppDir());
      break;
    case 1:
      path.Format("%s\\Inform\\Extensions\\*.*",(LPCSTR)GetHomeDir());
      break;
    default:
      ASSERT(FALSE);
      break;
    }

    CFileFind find;
    BOOL finding = find.FindFile(path);
    while (finding)
    {
      finding = find.FindNextFile();
      if (!find.IsDots() && find.IsDirectory())
      {
        CString author = find.GetFileName();
        if (author == "Reserved")
          continue;
        if ((author.GetLength() > 0) && (author.GetAt(0) == '.'))
          continue;

        path.Format("%s\\*.*",(LPCSTR)find.GetFilePath());
        CFileFind find;
        BOOL finding = find.FindFile(path);
        while (finding)
        {
          finding = find.FindNextFile();
          if (!find.IsDirectory())
          {
            CString ext = ::PathFindExtension(find.GetFilePath());
            if (ext.CompareNoCase(".i7x") == 0)
              m_extensions.push_back(ExtLocation(author,find.GetFileTitle(),(i == 0),find.GetFilePath()));
            else if (ext.IsEmpty() && (i == 1))
            {
              // Rename an old-style extension (with no file extension) to end with ".i7x"
              CString newPath = find.GetFilePath();
              newPath.Append(".i7x");
              if (::MoveFile(find.GetFilePath(),newPath))
                m_extensions.push_back(ExtLocation(author,find.GetFileTitle(),(i == 0),newPath));
            }
          }
        }
        find.Close();
      }
    }
    find.Close();
  }
  std::sort(m_extensions.begin(),m_extensions.end());
}
コード例 #4
0
wxString &OCPNPlatform::GetSharedDataDir()
{
    if(m_SData_Dir.IsEmpty()){
        //      Establish a "shared data" location
        /*  From the wxWidgets documentation...
         * 
         *     wxStandardPaths::GetDataDir
         *     wxString GetDataDir() const
         *     Return the location of the applications global, i.e. not user-specific, data files.
         * Unix: prefix/share/appname
         * Windows: the directory where the executable file is located
         * Mac: appname.app/Contents/SharedSupport bundle subdirectory
         */
        wxStandardPaths& std_path = GetStdPaths();
        m_SData_Dir = std_path.GetDataDir();
        appendOSDirSlash( &m_SData_Dir );
        
#ifdef __OCPN__ANDROID__
        wxFileName fdir = wxFileName::DirName(std_path.GetUserConfigDir());
        
        fdir.RemoveLastDir();
        m_SData_Dir = fdir.GetPath();
        m_SData_Dir += _T("/cache/");
#endif
        
        if( g_bportable )
            m_SData_Dir = GetHomeDir();
    }
    
    return m_SData_Dir;
    
}
コード例 #5
0
ファイル: OCPNPlatform.cpp プロジェクト: vonwenm/OpenCPN
wxString &OCPNPlatform::GetPluginDir()
{
    if(m_PluginsDir.IsEmpty()){

        wxStandardPaths& std_path = GetStdPaths();
        
        //  Get the PlugIns directory location
        m_PluginsDir = std_path.GetPluginsDir();   // linux:   {prefix}/lib/opencpn
        // Mac:     appname.app/Contents/PlugIns
#ifdef __WXMSW__
        m_PluginsDir += _T("\\plugins");             // Windows: {exe dir}/plugins
#endif
        
        if( g_bportable ) {
            m_PluginsDir = GetHomeDir();
            m_PluginsDir += _T("plugins");
        }
        
#ifdef __OCPN__ANDROID__
        // something like: data/data/org.opencpn.opencpn
        wxFileName fdir = wxFileName::DirName(std_path.GetUserConfigDir());
        fdir.RemoveLastDir();
        m_PluginsDir = fdir.GetPath();
        
//        m_PluginsDir = GetHomeDir();
        
//        m_PluginsDir = _T("/data/data/org.opencpn.opencpn/lib")
        
#endif        
        
        
    }
    
    return m_PluginsDir;
}
コード例 #6
0
ファイル: win_main.cpp プロジェクト: kevindqc/utl
bool Sys_GetPath(sysPath_t type, idStr &path) {
    char buf[MAX_OSPATH];
    struct _stat st;
    idStr s;

    switch(type) {
    case PATH_BASE:
        // try <path to exe>/base first
        if (Sys_GetPath(PATH_EXE, path)) {
            path.StripFilename();

            s = path;
            s.AppendPath(BASE_GAMEDIR);
            if (_stat(s.c_str(), &st) != -1 && st.st_mode & _S_IFDIR)
                return true;

            common->Warning("base path '%s' does not exits", s.c_str());
        }

        // fallback to vanilla doom3 cd install
        if (GetRegistryPath(buf, sizeof(buf), L"SOFTWARE\\id\\Doom 3", L"InstallPath") > 0) {
            path = buf;
            return true;
        }

        // fallback to steam doom3 install
        if (GetRegistryPath(buf, sizeof(buf), L"SOFTWARE\\Valve\\Steam", L"InstallPath") > 0) {
            path = buf;
            path.AppendPath("steamapps\\common\\doom 3");

            if (_stat(path.c_str(), &st) != -1 && st.st_mode & _S_IFDIR)
                return true;
        }

        common->Warning("vanilla doom3 path not found");

        return false;

    case PATH_CONFIG:
    case PATH_SAVE:
        if (GetHomeDir(buf, sizeof(buf)) < 1) {
            Sys_Error("ERROR: Couldn't get dir to home path");
            return false;
        }

        path = buf;
        return true;

    case PATH_EXE:
        GetModuleFileName(NULL, buf, sizeof(buf) - 1);
        path = buf;
        path.BackSlashesToSlashes();
        return true;
    }

    return false;
}
コード例 #7
0
ファイル: OCPNPlatform.cpp プロジェクト: vonwenm/OpenCPN
wxString &OCPNPlatform::GetConfigFileName()
{
    if(m_config_file_name.IsEmpty()){
        //      Establish the location of the config file
        wxStandardPaths& std_path = GetStdPaths();
        
#ifdef __WXMSW__
        m_config_file_name = _T("opencpn.ini");
        m_config_file_name.Prepend( GetHomeDir() );
        
#elif defined __WXOSX__
        m_config_file_name = std_path.GetUserConfigDir(); // should be ~/Library/Preferences
        appendOSDirSlash(&m_config_file_name);
        m_config_file_name.Append(_T("opencpn"));
        appendOSDirSlash(&m_config_file_name);
        m_config_file_name.Append(_T("opencpn.ini"));
#else
        m_config_file_name = std_path.GetUserDataDir(); // should be ~/.opencpn
        appendOSDirSlash(&m_config_file_name);
        m_config_file_name.Append(_T("opencpn.conf"));
#endif
        
        if( g_bportable ) {
            m_config_file_name = GetHomeDir();
#ifdef __WXMSW__
            m_config_file_name += _T("opencpn.ini");
#elif defined __WXOSX__
            m_config_file_name +=_T("opencpn.ini");
#else
            m_config_file_name += _T("opencpn.conf");
#endif
            
        }
        
#ifdef __OCPN__ANDROID__
        m_config_file_name = androidGetPrivateDir();
        appendOSDirSlash(&m_config_file_name);
        m_config_file_name += _T("opencpn.conf");
#endif
        
    }
    
    return m_config_file_name;
}
コード例 #8
0
ファイル: paths.c プロジェクト: gsmadhusudan/Balsa
/* ExpandFilename : "expand" the given file/dirname to make it absolute (if `makeAbsolute' is
	TRUE), remove leading ~ terms. Returns a newly allocated string. Cleans up name a bit
	by removing extra slashes and ./'es. NB. filename gets (temporarily) modified so don't
	pass any constant strings in here.  `pwd' contains the current (perceived) working directory.
	Set this to NULL to use the actual cwd. */
char *ExpandFilename (char *filename, gboolean makeAbsolute, char *pwd)
{
    char *root = NULL;
    char *ret;

    if (!g_path_is_absolute (filename))
    {
        if (*filename == '~')
        {                       /* home dir relative */
            if (filename[1] == '\0' || filename[1] == G_DIR_SEPARATOR)
            {
                root = GetHomeDir (g_get_user_name ());
                filename++;
            } else if (isalnum (filename[1]))
            {                   /* ~whoever/a/b/c */
                char savedChar;
                char *endPtr = filename + 1;

                while (isalnum (*endPtr))
                    endPtr++;
                savedChar = *endPtr;
                root = GetHomeDir (filename + 1);
                *endPtr = savedChar;

                filename = endPtr;
            }                   /* else leave the ~ in place, dunno what it means */
        } else if (makeAbsolute) /* starts with ./ (add current dir) or not / */
            root = g_strdup (pwd ? pwd : g_get_current_dir ());
    }
    ret = (char *) g_malloc ((root ? strlen (root) : 0) + strlen (filename) + 2);
    *ret = '\0';
    if (root)
    {
        sprintf (ret, "%s%c", root, G_DIR_SEPARATOR);
        g_free (root);
    }
    strcat (ret, filename);

    CleanUpFilename (ret);
    return ret;
}
コード例 #9
0
ファイル: test_Utils.cpp プロジェクト: dfleury2/Nedit
// --------------------------------------------------------------------------
TEST(UtilsTest, Directory)
{
   const char* currentDir = GetCurrentDir();
   std::string homeDir = GetHomeDir();
   const char* userName = NeGetUserName();
   const char* hostname = GetNameOfHost();
   
   char fullname[256] = "";
   PrependHome("file.txt", fullname, sizeof(fullname));
   ASSERT_EQ(homeDir + "/file.txt", fullname);

   PrependHome("file.txt", fullname, 10);
   ASSERT_STREQ(fullname, "");
}
コード例 #10
0
ファイル: utils.c プロジェクト: JohnArchieMckown/nedit
/*
** Create a path: $HOME/filename
** Return "" if it doesn't fit into the buffer
*/
char 
*PrependHome(const char *filename, char *buf, int buflen)
{
    const char *homedir;
    int home_len, file_len;
    
    homedir=GetHomeDir();
    home_len=strlen(homedir);
    file_len=strlen(filename);
    if ( (home_len+1+file_len)>=buflen ) {
       buf[0]='\0';
    }
    else {
       strcpy(buf, homedir);
       strcat(buf, "/");
       strcat(buf, filename);
    }
    return buf;
}
コード例 #11
0
ファイル: mp4atom.c プロジェクト: dps123/nitrogenS100
static int32_t mp4ff_read_drms(mp4ff_t *f, uint64_t skip)
{
    uint64_t size;
    int32_t i;
    uint8_t atom_type = 0;
    uint8_t header_size = 0;

    f->track[f->total_tracks - 1]->p_drms = drms_alloc( GetHomeDir() );

    for (i = 0; i < 6; i++)
    {
        mp4ff_read_char(f); /* reserved */
    }
    /* data_reference_index */ mp4ff_read_int16(f);

    mp4ff_read_int32(f); /* reserved */
    mp4ff_read_int32(f); /* reserved */

    f->track[f->total_tracks - 1]->channelCount = mp4ff_read_int16(f);
    f->track[f->total_tracks - 1]->sampleSize = mp4ff_read_int16(f);

    mp4ff_read_int16(f);
    mp4ff_read_int16(f);

    f->track[f->total_tracks - 1]->sampleRate = mp4ff_read_int16(f);

    mp4ff_read_int16(f);

    size = mp4ff_atom_read_header(f, &atom_type, &header_size);
    if (atom_type == ATOM_ESDS)
    {
        mp4ff_read_esds(f);
    }
    mp4ff_set_position(f, skip+size+28);

    size = mp4ff_atom_read_header(f, &atom_type, &header_size);
    if (atom_type == ATOM_SINF)
    {
        parse_sub_atoms(f, size-header_size,0);
    }

    return 0;
}
コード例 #12
0
void
InitFileTransfer()
{
	char* userHome = NULL;
	uid_t uid = geteuid();

	if(fileTransferInitted)
		return;
	
	memset(ftproot, 0, sizeof(ftproot));
	
	userHome = GetHomeDir(uid);

	if((userHome != NULL) && (strlen(userHome) != 0)) {
		SetFtpRoot(userHome);
		FreeHomeDir(userHome);
	}
	
	fileTransferEnabled = TRUE;
	fileTransferInitted = TRUE;
}
コード例 #13
0
wxString &OCPNPlatform::GetPluginDir()
{
    if(m_PluginsDir.IsEmpty()){

        wxStandardPaths& std_path = GetStdPaths();
        
        //  Get the PlugIns directory location
        m_PluginsDir = std_path.GetPluginsDir();   // linux:   {prefix}/lib/opencpn
        // Mac:     appname.app/Contents/PlugIns
#ifdef __WXMSW__
        m_PluginsDir += _T("\\plugins");             // Windows: {exe dir}/plugins
#endif
        
        if( g_bportable ) {
            m_PluginsDir = GetHomeDir();
            m_PluginsDir += _T("plugins");
        }
        
    }
    
    return m_PluginsDir;
}
コード例 #14
0
ファイル: config.cpp プロジェクト: pnkfelix/glx-gle
void find_deps(const string& loc, GLEInterface* iface) {
	vector<GLEFindEntry*> tofind;
	vector<string*> result;
	string gle_paths = ";";
	ConfigCollection* collection = iface->getConfig()->getRCFile();
#ifdef __WIN32__
	GLEFindEntry* findGLE = new GLEFindEntry(&gle_paths);
	findGLE->addToFind("gle.exe");
	findGLE->addToFind("gle_ps.exe");
	tofind.push_back(findGLE);
#endif
	// Create GLEFindEntry for each tool (ghostscript, pdflatex, ...)
	ConfigSection* tools = collection->getSection(GLE_CONFIG_TOOLS);
	for (int j = 0; j <= GLE_TOOL_GHOSTSCRIPT_LIB; j++) {
		CmdLineArgString* strarg = (CmdLineArgString*)tools->getOption(j)->getArg(0);
		GLEFindEntry* findTool = new GLEFindEntry(strarg->getValuePtr());
		char_separator separator(",", ";");
		tokenizer<char_separator> tokens(strarg->getDefault(), separator);
		while (tokens.has_more()) {
			const string& toolName = tokens.next_token();
			if (toolName == ";") {
				if (tokens.has_more() && strarg->isDefault()) {
					findTool->setNotFound(tokens.next_token());
				}
				break;
			} else {
				if (!IsAbsPath(toolName)) {
					findTool->addToFind(toolName);
				}
			}
		}
		if (findTool->getNbFind() != 0) tofind.push_back(findTool);
		else delete findTool;
	}
	// Initialize output and progress indicator
	GLEOutputStream* output = iface->getOutput();
	ostringstream out1;
	out1 << "Running GLE -finddeps \"";
	out1 << loc;
	out1 << ("\" to locate installed software (e.g., Ghostscript and LaTeX): ");
	output->println(out1.str().c_str());
	GLEProgressIndicatorInterface progress(iface);
	// Perform search at specified location
	if (loc != "") {
		if (IsDirectory(loc, true)) {
			GLEFindFiles(loc, tofind, &progress);
			for (unsigned int i = 0; i < tofind.size(); i++) {
				tofind[i]->updateResult(false);
			}
		} else {
			// Name of old GLERC file given
			if (try_load_config(loc)) {
				// Override old version number
				collection->setStringValue(GLE_CONFIG_GLE, GLE_CONFIG_GLE_VERSION, GLEVN);
			} else {
				ostringstream err;
				err << "Can't load configuration from '" << loc << "'" << endl;
				output->println(err.str().c_str());
			}
		}
	}
	#ifdef __UNIX__
		// Find programs in search path on Unix
		GLEFindPrograms(tofind, &progress);
	#endif
	#ifdef __MACOS__
		// Search for frameworks on Mac
		GLEFindFiles(string("/Library/Frameworks"), tofind, &progress);
		string home = GetHomeDir();
		if (home != "") {
			home += "Library/Frameworks";
			GLEFindFiles(home, tofind, &progress);
		}
	#endif
	for (unsigned int i = 0; i < tofind.size(); i++) {
		tofind[i]->updateResult(true);
	}
	#ifdef __UNIX__
		// Search for libraries in typical directories and in LD_LIBRARY_PATH
		string gslibloc = GLEFindLibrary("libgs", &progress);
		if (gslibloc != "") {
			CmdLineArgString* gslib_stra = (CmdLineArgString*)tools->getOption(GLE_TOOL_GHOSTSCRIPT_LIB)->getArg(0);
			gslib_stra->setValue(gslibloc.c_str());
		}
	#endif
	output->println();
	// Write installed GLE's to config section
	ConfigSection* gle = collection->getSection(GLE_CONFIG_GLE);
	CmdLineArgSPairList* installs = (CmdLineArgSPairList*)gle->getOption(GLE_CONFIG_GLE_INSTALL)->getArg(0);
	char_separator separator(";", "");
	tokenizer<char_separator> tokens(gle_paths, separator);
	while (tokens.has_more()) {
		string path = tokens.next_token();
		if (path.length() > 0 && !installs->hasValue2(path)) {
			installs->addPair("?", path);
		}
	}
	// Find versions of installed GLEs and set value of gleexe
	ostringstream out;
	string gle_version = GLEVN;
	if (installs->size() > 1) {
		// Only need to find out versions if more than one installed
		// otherwise assume it is "this" version
		for (int i = 0; i < installs->size(); i++) {
			const string& cr_gle = installs->getValue2(i);
			string& version = installs->getValue1(i);
			if (version == "?") {
				get_version_soft(cr_gle, version);
				if (version == "?") {
					// cout << "Use hard method for: " << cr_gle << endl;
					get_version_hard(cr_gle, version);
				}
			}
			if (str_i_equals(version, gle_version)) {
				out << "Found: GLE " << version << " in " << cr_gle << " (*)" << endl;
			} else {
				out << "Found: GLE " << version << " in " << cr_gle << endl;
			}
		}
	} else if (installs->size() == 1) {
		out << "Found: GLE in " << installs->getValue2(0) << endl;
		// Do not need to remember installed GLEs if there is only one
		// because then the "-v" option makes no sense
		installs->reset();
	}
	// Show locations of other tools
	for (int j = 0; j <= GLE_TOOL_GHOSTSCRIPT_LIB; j++) {
		CmdLineOption* opt = tools->getOption(j);
		CmdLineArgString* strarg = (CmdLineArgString*)opt->getArg(0);
		if (strarg->isDefault()) {
			out << "Found: " << opt->getName() << " in '?'" << endl;
		} else {
			out << "Found: " << opt->getName() << " in '" << strarg->getValue() << "'" << endl;
		}
	}
	output->println(out.str().c_str());
	for (unsigned int i = 0; i < tofind.size(); i++) {
		delete tofind[i];
	}
}
コード例 #15
0
ファイル: dirut.cpp プロジェクト: Frankie-666/tomita-parser
bool resolvepath(Stroka &folder, const Stroka &home)
{
    YASSERT(home && home.at(0) == '/');
    if (!folder) {
        return false;
    }
    // may be from windows
    char *ptr = folder.begin();
    while ((ptr = strchr(ptr, '\\')) != 0)
        *ptr = '/';

    if (folder.at(0) == '~') {
        if (folder.length() == 1 || folder.at(1) == '/') {
            folder = GetHomeDir() + (~folder + 1);
        } else {
            char* buf = (char*)alloca(folder.length()+1);
            strcpy(buf, ~folder + 1);
            char* p = strchr(buf, '/');
            if (p)
                *p++ = 0;
            passwd* pw = getpwnam(buf);
            if (pw) {
                folder = pw->pw_dir;
                folder += "/";
                if (p)
                    folder += p;
            } else {
                return false; // unknown user
            }
        }
    }
    int len = folder.length() + home.length() + 1;
    char* path = (char*)alloca(len);
    if (folder.at(0) != '/') {
        strcpy(path, ~home);
        strcpy(strrchr(path, '/')+1, ~folder); // the last char must be '/' if it's a dir
    } else {
        strcpy(path, ~folder);
    }
    len = strlen(path)+1;
    // grabbed from url.cpp
    char *newpath = (char*)alloca(len+2);
    const char **pp = (const char**)alloca(len*sizeof(char*));
    int i = 0;
    for (char* s = path; s;) {
        pp[i++] = s;
        s = strchr(s, '/');
        if (s)
            *s++ = 0;
    }

    for (int j = 1; j < i;) {
        const char*& p = pp[j];
        if (strcmp(p, ".") == 0 || strcmp(p,"") == 0) {
            if (j == i-1) {
                p = "";
                break;
            } else {
                memmove(pp+j, pp+j+1, (i-j-1)*sizeof(p));
                i--;
            }
        } else if (strcmp(p, "..") == 0) {
            if (j == i-1) {
                if (j == 1) {
                    p = "";
                } else {
                    i--;
                    pp[j-1] = "";
                }
                break;
            } else {
                if (j == 1) {
                    memmove(pp+j, pp+j+1, (i-j-1)*sizeof(p));
                    i--;
                } else {
                    memmove(pp+j-1, pp+j+1, (i-j-1)*sizeof(p));
                    i-=2;
                    j--;
                }
            }
        } else
            j++;
    }

    char* s = newpath;
    for (int k = 0; k < i; k++) {
        s = strchr(strcpy(s, pp[k]), 0);
        *s++ = '/';
    }
    *(--s) = 0;
    folder = newpath;
    return true;
}
コード例 #16
0
static int
userauth_pubkey(Authctxt *authctxt)
{
  #ifdef WIN32_FIXME
  
  int loginStat = 1;

  char currentUser[MAX_PATH] = {0};
  
  DWORD currentUserSize = sizeof(currentUser);
  
  int targetIsCurrent = 0;

  # ifdef USE_NTCREATETOKEN
  int doOpenSSHVerify = 1;
  # else
  int doOpenSSHVerify = 0;
  # endif

  #endif
  
	Buffer b;
	Key *key = NULL;
	char *pkalg, *userstyle;
	u_char *pkblob, *sig;
	u_int alen, blen, slen;
	int have_sig, pktype;
	int authenticated = 0;

	if (!authctxt->valid) {
		debug2("userauth_pubkey: disabled because of invalid user");
		return 0;
	}
	have_sig = packet_get_char();
	if (datafellows & SSH_BUG_PKAUTH) {
		debug2("userauth_pubkey: SSH_BUG_PKAUTH");
		/* no explicit pkalg given */
		pkblob = packet_get_string(&blen);
		buffer_init(&b);
		buffer_append(&b, pkblob, blen);
		/* so we have to extract the pkalg from the pkblob */
		pkalg = buffer_get_string(&b, &alen);
		buffer_free(&b);
	} else {
		pkalg = packet_get_string(&alen);
		pkblob = packet_get_string(&blen);
	}
	pktype = key_type_from_name(pkalg);
	if (pktype == KEY_UNSPEC) {
		/* this is perfectly legal */
		logit("userauth_pubkey: unsupported public key algorithm: %s",
		    pkalg);
		goto done;
	}
	key = key_from_blob(pkblob, blen);
	if (key == NULL) {
		error("userauth_pubkey: cannot decode key: %s", pkalg);
		goto done;
	}
	if (key->type != pktype) {
		error("userauth_pubkey: type mismatch for decoded key "
		    "(received %d, expected %d)", key->type, pktype);
		goto done;
	}
	if (key_type_plain(key->type) == KEY_RSA &&
	    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
		logit("Refusing RSA key because client uses unsafe "
		    "signature scheme");
		goto done;
	}
	if (auth2_userkey_already_used(authctxt, key)) {
		logit("refusing previously-used %s key", key_type(key));
		goto done;
	}
	if (match_pattern_list(sshkey_ssh_name(key),
	    options.pubkey_key_types, 0) != 1) {
		logit("%s: key type %s not in PubkeyAcceptedKeyTypes",
		    __func__, sshkey_ssh_name(key));
		goto done;
	}

	if (have_sig) {
		sig = packet_get_string(&slen);
		packet_check_eom();
		buffer_init(&b);
		if (datafellows & SSH_OLD_SESSIONID) {
			buffer_append(&b, session_id2, session_id2_len);
		} else {
			buffer_put_string(&b, session_id2, session_id2_len);
		}
		/* reconstruct packet */
		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
		xasprintf(&userstyle, "%s%s%s", authctxt->user,
		    authctxt->style ? ":" : "",
		    authctxt->style ? authctxt->style : "");
		buffer_put_cstring(&b, userstyle);
		free(userstyle);
		buffer_put_cstring(&b,
		    datafellows & SSH_BUG_PKSERVICE ?
		    "ssh-userauth" :
		    authctxt->service);
		if (datafellows & SSH_BUG_PKAUTH) {
			buffer_put_char(&b, have_sig);
		} else {
			buffer_put_cstring(&b, "publickey");
			buffer_put_char(&b, have_sig);
			buffer_put_cstring(&b, pkalg);
		}
		buffer_put_string(&b, pkblob, blen);
#ifdef DEBUG_PK
		buffer_dump(&b);
#endif
		pubkey_auth_info(authctxt, key, NULL);

		/* test for correct signature */
		authenticated = 0;
   /*
     * On pure win32 try to logon using lsa first.
     */

    #ifdef WIN32_FIXME

    authctxt -> hTokenLsa_ = NULL;
    authctxt -> methoddata = NULL;
 
    /*
     * Retrieve name of current login user (i.e. sshd process owner).
     */
     
    GetUserName(currentUser, &currentUserSize);

    /*
     * Try to get token from lsa, but only if targetUser != currentUser.
     * Owerthise we already have targetUser's token in current thread, so
     * we only need key verify from original OpenSSH code.
     */

    targetIsCurrent = (strcmp(currentUser, authctxt -> user) == 0);
    
    if (targetIsCurrent)
    {
      doOpenSSHVerify = 1;
    }
    else
    {
      loginStat = LsaLogon(&authctxt -> hTokenLsa_, HomeDirLsaW,
                               authctxt -> user, pkblob, blen, sig, slen,
                                 buffer_ptr(&b), buffer_len(&b), datafellows);

      /*
       * If lsa logon process success.
       */
  
      if (loginStat == 0)
      {
        /*
         * And user authorized OK.
         */
    
        if (authctxt -> hTokenLsa_)
        {
          doOpenSSHVerify = 0;
          
          /*
           * This is part of openssh authorization needed for parsing
           * 'options' block in key.
           */
      
          authctxt -> pw -> pw_dir = GetHomeDir(authctxt -> user);
      
          if (PRIVSEP(user_key_allowed(authctxt -> pw, key, 1))) // PRAGMA:TODO
          {
            authenticated = 1;
          }
          else
          {
            authenticated = 0;
          }
          
          buffer_free(&b);

          free(sig);
        }
      }
    }
    
    if (doOpenSSHVerify)
    {
      /*
       * If lsa fails, test for correct signature using openssh code.
       */
      
      authctxt -> pw -> pw_dir = GetHomeDir(authctxt -> user);
  
      if (PRIVSEP(user_key_allowed(authctxt->pw, key, 0))  //PRAGMA:TODO
		  &&
              PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b), buffer_len(&b))) == 1)
    
      {
        authenticated = 1;
      }
    }
    
    /*
     * Original code.
     */

    #else /* #ifdef WIN32_FIXME */

		if (PRIVSEP(user_key_allowed(authctxt->pw, key, 1)) &&
		    PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b),
		    buffer_len(&b))) == 1) {
			authenticated = 1;
			/* Record the successful key to prevent reuse */
			auth2_record_userkey(authctxt, key);
			key = NULL; /* Don't free below */
		}
		buffer_free(&b);
		free(sig);
   #endif /* else #ifdef WIN32_FIXME. */

	} else {
		debug("test whether pkalg/pkblob are acceptable");
		packet_check_eom();

		/* XXX fake reply and always send PK_OK ? */
		/*
		 * XXX this allows testing whether a user is allowed
		 * to login: if you happen to have a valid pubkey this
		 * message is sent. the message is NEVER sent at all
		 * if a user is not allowed to login. is this an
		 * issue? -markus
		 */
		

      #ifndef WIN32_FIXME

     if (PRIVSEP(user_key_allowed(authctxt->pw, key, 0)))  
 
      #endif		
		{
			packet_start(SSH2_MSG_USERAUTH_PK_OK);
			packet_put_string(pkalg, alen);
			packet_put_string(pkblob, blen);
			packet_send();
			packet_write_wait();
			authctxt->postponed = 1;
		}
	}
	if (authenticated != 1)
		auth_clear_options();
done:
	debug2("userauth_pubkey: authenticated %d pkalg %s", authenticated, pkalg);
	if (key != NULL)
		key_free(key);
	free(pkalg);
	free(pkblob);
	return authenticated;
}
コード例 #17
0
ファイル: utils.c プロジェクト: JohnArchieMckown/nedit
/*
**  Returns a pointer to the name of an rc file of the requested type.
**
**  Preconditions:
**      - MAXPATHLEN is set to the max. allowed path length
**      - fullPath points to a buffer of at least MAXPATHLEN
**
**  Returns:
**      - NULL if an error occurs while creating a directory
**      - Pointer to a static array containing the file name
**
*/
const char* GetRCFileName(int type)
{
    static char rcFiles[N_FILE_TYPES][MAXPATHLEN + 1];
    static int namesDetermined = False;

    if (!namesDetermined)
    {
        char* nedit_home;
        int i;

        if ((nedit_home = getenv("NEDIT_HOME")) == NULL)
        {
            /*  No NEDIT_HOME */
#ifdef VMS
            /* This is a default VMS setup */
            for (i = 0; i < N_FILE_TYPES; i++)
            {
                buildFilePath(rcFiles[i], "SYS$LOGIN", hiddenFileNames[i]);
            }
#else /* #ifdef VMS */
            /* Let's try if ~/.nedit is a regular file or not. */
            char legacyFile[MAXPATHLEN + 1];
            buildFilePath(legacyFile, GetHomeDir(), hiddenFileNames[NEDIT_RC]);
            if (isRegFile(legacyFile))
            {
                /* This is a legacy setup with rc files in $HOME */
                for (i = 0; i < N_FILE_TYPES; i++)
                {
                    buildFilePath(rcFiles[i], GetHomeDir(), hiddenFileNames[i]);
                }
            } else
            {
                /* ${HOME}/.nedit does not exist as a regular file. */
                /* FIXME: Devices, sockets and fifos are ignored for now. */
                char defaultNEditHome[MAXPATHLEN + 1];
                buildFilePath(defaultNEditHome, GetHomeDir(), DEFAULT_NEDIT_HOME);
                if (!isDir(defaultNEditHome))
                {
                    /* Create DEFAULT_NEDIT_HOME */
                    if (mkdir(defaultNEditHome, 0777) != 0)
                    {
                        perror("nedit: Error while creating rc file directory"
                                " $HOME/" DEFAULT_NEDIT_HOME "\n"
                                " (Make sure all parent directories exist.)");
                        return NULL;
                    }
                }

                /* All set for DEFAULT_NEDIT_HOME, let's copy the names */
                for (i = 0; i < N_FILE_TYPES; i++)
                {
                    buildFilePath(rcFiles[i], defaultNEditHome, plainFileNames[i]);
                }
            }
#endif /* #ifdef VMS */
        } else
        {
            /*  $NEDIT_HOME is set. */
#ifndef VMS
            /* FIXME: Is this required? Does VMS know stat(), mkdir()? */
            if (!isDir(nedit_home))
            {
                /* Create $NEDIT_HOME */
                if (mkdir(nedit_home, 0777) != 0)
                {
                    perror("nedit: Error while creating rc file directory $NEDIT_HOME\n"
                            "nedit: (Make sure all parent directories exist.)");
                    return NULL;
                }
            }
#endif /* #ifndef VMS */

            /* All set for NEDIT_HOME, let's copy the names */
            for (i = 0; i < N_FILE_TYPES; i++)
            {
                buildFilePath(rcFiles[i], nedit_home, plainFileNames[i]);
            }
        }

        namesDetermined = True;
    }

    return rcFiles[type];
}
コード例 #18
0
bool OCPNPlatform::InitializeLogFile( void )
{
    //      Establish Log File location
    mlog_file = GetHomeDir();
    
#ifdef  __WXOSX__
    
    wxFileName LibPref(mlog_file);          // starts like "~/Library/Preferences"
    LibPref.RemoveLastDir();// takes off "Preferences"
    
    mlog_file = LibPref.GetFullPath();
    appendOSDirSlash(&mlog_file);
    
    mlog_file.Append(_T("Logs/"));// so, on OS X, opencpn.log ends up in ~/Library/Logs
                                   // which makes it accessible to Applications/Utilities/Console....
#endif
    
    // create the opencpn "home" directory if we need to
    wxFileName wxHomeFiledir( GetHomeDir() );
    if( true != wxHomeFiledir.DirExists( wxHomeFiledir.GetPath() ) )
        if( !wxHomeFiledir.Mkdir( wxHomeFiledir.GetPath() ) ) {
            wxASSERT_MSG(false,_T("Cannot create opencpn home directory"));
            return false;
    }
        
        // create the opencpn "log" directory if we need to
    wxFileName wxLogFiledir( mlog_file );
    if( true != wxLogFiledir.DirExists( wxLogFiledir.GetPath() ) ) {
        if( !wxLogFiledir.Mkdir( wxLogFiledir.GetPath() ) ) {
            wxASSERT_MSG(false,_T("Cannot create opencpn log directory"));
            return false;
        }
    }
    
    mlog_file.Append( _T("opencpn.log") );
    wxString logit = mlog_file;
        
        //  Constrain the size of the log file
    if( ::wxFileExists( mlog_file ) ) {
            if( wxFileName::GetSize( mlog_file ) > 1000000 ) {
                wxString oldlog = mlog_file;
                oldlog.Append( _T(".log") );
                //  Defer the showing of this messagebox until the system locale is established.
                large_log_message = ( _("Old log will be moved to opencpn.log.log") );
                ::wxRenameFile( mlog_file, oldlog );
            }
    }
        
#ifdef __OCPN__ANDROID__
        //  Force new logfile for each instance
        // TODO Remove this behaviour on Release
    if( ::wxFileExists( mlog_file ) ){
        ::wxRemoveFile( mlog_file );
    }
#endif
        
    flog = fopen( mlog_file.mb_str(), "a" );
    g_logger = new wxLogStderr( flog );
        
#ifdef __OCPN__ANDROID__
        //  Trouble printing timestamp
    g_logger->SetTimestamp((const char *)NULL);
#endif
        
#if defined(__WXGTK__) || defined(__WXOSX__)
    g_logger->SetTimestamp(_T("%H:%M:%S %Z"));
#endif
        
    m_Oldlogger = wxLog::SetActiveTarget( g_logger );

    return true;
    
}
コード例 #19
0
ファイル: CslApp.cpp プロジェクト: aurhat/cubelister
bool CslApp::OnInit()
{
    SetAppName(wxString(CSL_NAME_SHORT_STR).Lower());

#if defined(__WXMSW__)
    wxCrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

#if CSL_DEBUG < 1
#if wxUSE_DEBUGREPORT && wxUSE_ON_FATAL_EXCEPTION
    ::wxHandleFatalExceptions(true);
#endif
#endif

    wxString ipcCmd;
    const wxString cwd = ::DirName(::wxPathOnly(argv[0]));

    static const wxCmdLineEntryDesc cmdLineDesc[] =
    {
        { wxCMD_LINE_SWITCH, NULL,       wxT_2("version"),   wxTRANSLATE("show version"),   wxCMD_LINE_VAL_NONE,   0                         },
        { wxCMD_LINE_SWITCH, wxT_2("h"), wxT_2("help"),      wxTRANSLATE("show this help"), wxCMD_LINE_VAL_NONE,   wxCMD_LINE_OPTION_HELP    },
        { wxCMD_LINE_OPTION, wxT_2("d"), wxT_2("datadir"),   wxTRANSLATE("add data dir"),   wxCMD_LINE_VAL_STRING, 0                         },
        { wxCMD_LINE_OPTION, wxT_2("p"), wxT_2("plugindir"), wxTRANSLATE("add plugin dir"), wxCMD_LINE_VAL_STRING, 0                         },
        { wxCMD_LINE_OPTION, wxT_2("q"), wxT_2("homedir"),   wxTRANSLATE("set home dir"),   wxCMD_LINE_VAL_STRING, 0                         },
        { wxCMD_LINE_PARAM,  NULL,       NULL,               wxTRANSLATE("IPC command"),    wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
        { wxCMD_LINE_NONE                                                                                                                    }
    };

    wxString sOpt;
    wxCmdLineParser parser(cmdLineDesc, argc, argv);

    switch (parser.Parse())
    {
        case -1: // help
            return true;

        case 0:
            if (parser.Found(wxT("version")))
            {
                wxPrintf(wxT("%s\n"), CSL_VERSION_STR);
                return true;
            }
            if (parser.Found(wxT("q"), &sOpt))
                m_home = ::DirName(sOpt, cwd);
            if (parser.Found(wxT("d"), &sOpt))
                AddDataDir(sOpt, cwd);
            if (parser.Found(wxT("p"), &sOpt))
                AddPluginDir(sOpt, cwd);
            break;

        default: // syntax error
            return true;
    }

    if (parser.GetParamCount())
        ipcCmd = parser.GetParam(0);

    if (m_home.IsEmpty())
        m_home = ::DirName(wxStandardPaths::Get().GetUserDataDir());

    if (!wxFileName::DirExists(m_home))
    {
        if (!wxFileName::Mkdir(m_home, 0700, wxPATH_MKDIR_FULL))
        {
            wxMessageBox(wxString::Format(_("Failed to create the home dir '%s'."),
                                          m_home.c_str()),
                         _("Fatal error!"), wxICON_ERROR);
            return false;
        }
    }
    else if (!wxFileName::IsDirWritable(m_home))
    {
        wxMessageBox(wxString::Format(_("Home dir '%s' isn't writable."),
                                      m_home.c_str()),
                     _("Fatal error!"), wxICON_ERROR);
        return false;
    }

    CSL_LOG_DEBUG("using home dir: %s\n", U2C(m_home));

    AddDataDir(m_home, cwd);
#ifdef PROJECTDIR
    if (::wxDirExists(wxT(PROJECTDIR)))
        AddDataDir(wxT(PROJECTDIR), cwd);
#endif
#ifdef __WXMAC__
    AddDataDir(wxT("../Resources"), cwd);
#else
    AddDataDir(cwd);
#endif
#ifdef DATADIR
    if (cwd!=m_home)
        AddDataDir(wxT(DATADIR), cwd);
#endif

    AddPluginDir(m_home, cwd);
#ifdef __WXMAC__
    AddPluginDir(wxT(".."), cwd);
#else
    AddPluginDir(cwd);
#endif
#ifdef BUILDDIR
    if (::wxDirExists(wxT(BUILDDIR)))
        AddPluginDir(wxT(BUILDDIR), cwd);
#endif
#ifdef PKGLIBDIR
    if (cwd!=m_home)
        AddPluginDir(wxT(PKGLIBDIR));
#endif

    m_locale.Init(wxLANGUAGE_DEFAULT,
#if wxCHECK_VERSION(2, 9, 0)
                  wxLOCALE_LOAD_DEFAULT
#else
                  wxLOCALE_CONV_ENCODING
#endif //wxCHECK_VERSION
                 );

#ifndef LOCALEDIR
#ifdef __WXMSW__
    m_locale.AddCatalogLookupPathPrefix(cwd+wxT("\\locale"));
#else
#ifdef __WXMAC__
    m_locale.AddCatalogLookupPathPrefix(cwd+wxT("../Resources"));
#endif //__WXMAC__
#endif //__WXMSW__
#else
    m_locale.AddCatalogLookupPathPrefix(wxT(LOCALEDIR));
#endif //LOCALEDIR

    if (m_locale.AddCatalog(wxString(CSL_NAME_SHORT_STR).Lower()))
        m_lang=m_locale.GetCanonicalName();

#ifdef __WXMAC__
    wxSystemOptions::SetOption(wxT("mac.listctrl.always_use_generic"), 1);

    // enables Command-H, Command-M and Command-Q at least when not in fullscreen
    wxSetEnv(wxT("SDL_SINGLEDISPLAY"),wxT("1"));
    wxSetEnv(wxT("SDL_ENABLEAPPEVENTS"),wxT("1"));

    // TODO wxApp::SetExitOnFrameDelete(false);

    // register event handler for URI schemes
    AEInstallEventHandler(kInternetEventClass, kAEGetURL,
                          NewAEEventHandlerUPP((AEEventHandlerProcPtr)MacCallbackGetUrl),
                          0, false);
#endif //__WXMAC__

    m_single = new wxSingleInstanceChecker;

    wxString lock = wxString::Format(wxT("%s-%s.%s"), CSL_NAME_SHORT_STR, wxGetUserId().c_str(),
#ifdef __WXMSW__
                                     GetHomeDir(wxPATH_UNIX).c_str()
#else
                                     wxT("lock")
#endif
                                    ).Lower();

    if (m_single->Create(lock, m_home) && m_single->IsAnotherRunning())
    {
        IpcCall(ipcCmd.IsEmpty() ? wxT("show") : ipcCmd);
        return true;
    }

    m_engine = new CslEngine;

    wxInitAllImageHandlers();

    CslFrame* frame = new CslFrame;

    if (m_shutdown!=CSL_SHUTDOWN_NONE)
        return true;

    SetTopWindow(frame);
    frame->Show();

    if (!ipcCmd.IsEmpty())
        IpcCall(ipcCmd, frame);

    return true;
}
コード例 #20
0
ファイル: DocActionPix.cpp プロジェクト: ellysh/notecase
void DocActionPix::Exec(bool bInteractive)
{
	DocumentIterator it(*m_pDoc);

	if(bInteractive)
	{
		FileDialog dlg(true);
		dlg.SetTitle(_("Open picture"));

		//define file filters
		dlg.AddFilter(_("All supported image formats (*.png,*.jpg,*.gif)"), "*.png|*.jpg|*.gif");
		dlg.AddFilter(_("PNG format (*.png)"), "*.png");
		dlg.AddFilter(_("JPG format (*.jpg)"), "*.jpg");
		dlg.AddFilter(_("GIF format (*.gif)"), "*.gif");
		dlg.AddFilter(_("All files (*)"), "*");

		//set initial directory from INI (store last used)
		std::string strDefaultDir;
		std::string strDir;
		g_objIni.GetValue("Cache", "LastPictureDir", strDir, "");
		if(!strDir.empty() && 0 == access(strDir.c_str(), 00))
			strDefaultDir = strDir;
		else
			strDefaultDir = GetHomeDir();

		dlg.SetDirectory(strDefaultDir.c_str());

		if(dlg.DoModal())
		{
			const gchar *filename = dlg.GetFilename();
			strDefaultDir = dlg.GetDirectory();
			dlg.Close();

			//store last open directory
			g_objIni.SetValue("Cache", "LastPictureDir", strDefaultDir.c_str());
			g_objIni.Save();

			GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename, NULL);

			PixPropertiesDlg dlg1;
			dlg1.m_nOrigWidth  = gdk_pixbuf_get_width(pixbuf);
			dlg1.m_nOrigHeight = gdk_pixbuf_get_height(pixbuf);
			dlg1.m_bUsePNG = false;
			dlg1.Create();
			if(GTK_RESPONSE_OK != dlg1.ShowModal()){
				g_object_unref (G_OBJECT (pixbuf));
				return;
			}

			GdkPixbuf *destpix = gdk_pixbuf_scale_simple(pixbuf, dlg1.m_nNewWidth, dlg1.m_nNewHeight, GDK_INTERP_BILINEAR);
			g_object_unref (G_OBJECT (pixbuf));
			pixbuf = destpix;

			UpdateTextFromScreen();

			//search from last result selection (or start)
			int cursor = -1;
			int selection = -1;
			g_text.GetSelectionBounds(cursor, selection);
			if(selection >= 0)
				cursor = selection;

			//get the iterator
			GtkTextBuffer* buffer1 = gtk_text_view_get_buffer((GtkTextView *)g_text.m_pWidget);
			GtkTextIter cursIter;
			gtk_text_buffer_get_iter_at_offset(buffer1, &cursIter, cursor);

			gtk_text_buffer_insert_pixbuf(buffer1, &cursIter, pixbuf);

			//store base name for the picture (with changed extension if required)
			std::string strName = GetBaseName(filename);
			EnsureExtension(strName, dlg1.m_bUsePNG ? ".png" : ".jpg");

			PixInfo info;
			info.bUsePNG = dlg1.m_bUsePNG;
			info.nOffset = cursor;
			info.pixbuf  = pixbuf;
			info.strName = strName;
			g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.push_back(info);
			std::sort(g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.begin(), g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.end());

			m_nOffset = cursor;
			m_pixbuf  = pixbuf;
			m_bUsePNG = dlg1.m_bUsePNG;

			//increment offsets for all formatting marks
			int nSize = g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt.size();
			int i;
			for(i=0; i<nSize; i++){
				if(g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt[i].nOffset >= m_nOffset)
					g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt[i].nOffset ++;
			}

			//increment all the pictures after this one
			nSize = g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.size();
			for(i=0; i<nSize; i++){
				if(g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures[i].nOffset > m_nOffset)
					g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures[i].nOffset ++;
			}
		}
	}
	else
	{
		PixInfo info;
		info.bUsePNG = m_bUsePNG;
		info.nOffset = m_nOffset;
		info.pixbuf  = m_pixbuf;
		g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.push_back(info);

		//increment offsets for all formatting marks
		int nSize = g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt.size();
		int i;
		for(i=0; i<nSize; i++){
			if(g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt[i].nOffset >= m_nOffset)
				g_doc.GetNodeByIdx(m_nNodeIdx).m_lstTxtFmt[i].nOffset ++;
		}

		//increment all the pictures after this one
		nSize = g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures.size();
		for(i=0; i<nSize; i++){
			if(g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures[i].nOffset > m_nOffset)
				g_doc.GetNodeByIdx(m_nNodeIdx).m_lstPictures[i].nOffset ++;
		}

		if(m_nNodeIdx == GetSelectedNodeIdx()){
			//get the iterator
			GtkTextBuffer* buffer1 = gtk_text_view_get_buffer((GtkTextView *)g_text.m_pWidget);
			GtkTextIter cursIter;
			gtk_text_buffer_get_iter_at_offset(buffer1, &cursIter, m_nOffset);
			gtk_text_buffer_insert_pixbuf(buffer1, &cursIter, m_pixbuf);
		}
	}
}
コード例 #21
0
ファイル: utils.cpp プロジェクト: dfleury2/Nedit
// -------------------------------------------------------------------------
//  Returns a pointer to the name of an rc file of the requested type.
//
//  Preconditions:
//      - MAXPATHLEN is set to the max. allowed path length
//      - fullPath points to a buffer of at least MAXPATHLEN
//
//  Returns:
//      - NULL if an error occurs while creating a directory
//      - Pointer to a static array containing the file name
// -------------------------------------------------------------------------
const char* GetRCFileName(FileTypes type)
{
   static std::string rcFiles[N_FILE_TYPES];
   static bool namesDetermined = false;

   if (!namesDetermined)
   {
      std::string nedit_home = GetEnv("NEDIT_HOME");
      if (nedit_home.empty())
      {  //  No NEDIT_HOME
         // Let's try if ~/.nedit is a regular file or not.
         std::string  legacyFile = buildFilePath(GetHomeDir(), hiddenFileNames[NEDIT_RC]);
         if (isRegFile(legacyFile))
         {
            // This is a legacy setup with rc files in $HOME
            for (int i = 0; i < N_FILE_TYPES; i++)
            {
               rcFiles[i] = buildFilePath(GetHomeDir(), hiddenFileNames[i]);
            }
         }
         else
         {
            // ${HOME}/.nedit does not exist as a regular file.
            // FIXME: Devices, sockets and fifos are ignored for now.
            std::string defaultNEditHome = buildFilePath(GetHomeDir(), DEFAULT_NEDIT_HOME);
            if (!isDir(defaultNEditHome))
            {
               /* Create DEFAULT_NEDIT_HOME */
#ifdef WIN32
               if (mkdir(defaultNEditHome.c_str()) != 0)
#else
               if (mkdir(defaultNEditHome.c_str(), 0777) != 0)
#endif
               {
                  perror("nedit: Error while creating rc file directory"
                         " $HOME/" DEFAULT_NEDIT_HOME "\n"
                         " (Make sure all parent directories exist.)");
                  return NULL;
               }
            }

            /* All set for DEFAULT_NEDIT_HOME, let's copy the names */
            for (int i = 0; i < N_FILE_TYPES; i++)
            {
               rcFiles[i] = buildFilePath(defaultNEditHome.c_str(), plainFileNames[i]);
            }
         }
      }
      else
      {  // $NEDIT_HOME is set.
         // FIXME: Is this required? Does VMS know stat(), mkdir()?
         if (!isDir(nedit_home))
         {
            /* Create $NEDIT_HOME */
#ifdef WIN32
            if (mkdir(nedit_home.c_str()) != 0)
#else
            if (mkdir(nedit_home.c_str(), 0777) != 0)
#endif
            {
               perror("nedit: Error while creating rc file directory $NEDIT_HOME\n"
                      "nedit: (Make sure all parent directories exist.)");
               return NULL;
            }
         }

         // All set for NEDIT_HOME, let's copy the names
         for (int i = 0; i < N_FILE_TYPES; i++)
         {
            rcFiles[i] = buildFilePath(nedit_home.c_str(), plainFileNames[i]);
         }
      }

      namesDetermined = true;
   }

   return rcFiles[type].c_str();
}