Example #1
0
/* static */
wxDllType wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
{
    wxASSERT_MSG( !(flags & wxDL_NOW) || !(flags & wxDL_LAZY),
                  wxT("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );

#ifdef USE_POSIX_DL_FUNCS
    // we need to use either RTLD_NOW or RTLD_LAZY because if we call dlopen()
    // with flags == 0 recent versions of glibc just fail the call, so use
    // RTLD_NOW even if wxDL_NOW was not specified
    int rtldFlags = flags & wxDL_LAZY ? RTLD_LAZY : RTLD_NOW;

    if ( flags & wxDL_GLOBAL )
        rtldFlags |= RTLD_GLOBAL;

    return dlopen(libname.fn_str(), rtldFlags);
#else // !USE_POSIX_DL_FUNCS
    int shlFlags = 0;

    if ( flags & wxDL_LAZY )
    {
        shlFlags |= BIND_DEFERRED;
    }
    else if ( flags & wxDL_NOW )
    {
        shlFlags |= BIND_IMMEDIATE;
    }

    return shl_load(libname.fn_str(), shlFlags, 0);
#endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
}
Example #2
0
bool wxMkdir(const wxString& dir, int perm)
{
#if defined(__WXMAC__) && !defined(__UNIX__)
    if ( mkdir(dir.fn_str(), 0) != 0 )

    // assume mkdir() has 2 args on all platforms
    // for the GNU compiler
#elif (!defined(__WINDOWS__)) || \
      (defined(__GNUWIN32__) && !defined(__MINGW32__)) ||                \
      defined(__WINE__)
    const wxChar *dirname = dir.c_str();
  #if defined(MSVCRT)
    wxUnusedVar(perm);
    if ( mkdir(wxFNCONV(dirname)) != 0 )
  #else
    if ( mkdir(wxFNCONV(dirname), perm) != 0 )
  #endif
#else  // MSW and VC++
    wxUnusedVar(perm);
    if ( wxMkDir(dir.fn_str()) != 0 )
#endif // !MSW/MSW
    {
        wxLogSysError(_("Directory '%s' couldn't be created"), dir);
        return false;
    }

    return true;
}
Example #3
0
bool Mysql::Cambiar_usuario(wxString new_usuario,wxString new_password,wxString new_db){
	if(mysql_change_user(sock,new_usuario.fn_str(),new_password.fn_str(),new_db.fn_str())){
		return false;//No tuvo exito
	}
	else{
		return true;//Tuvo exito la consulta
	}
}
Example #4
0
bool CLocalFileSystem::BeginFindFiles(wxString path, bool dirs_only)
{
	EndFindFiles();

	m_dirs_only = dirs_only;
#ifdef __WXMSW__
	if (path.Last() != '/' && path.Last() != '\\') {
		m_find_path = path + _T("\\");
		path += _T("\\*");
	}
	else {
		m_find_path = path;
		path += '*';
	}

	m_hFind = FindFirstFileEx(path, FindExInfoStandard, &m_find_data, dirs_only ? FindExSearchLimitToDirectories : FindExSearchNameMatch, 0, 0);
	if (m_hFind == INVALID_HANDLE_VALUE) {
		m_found = false;
		return false;
	}

	m_found = true;
	return true;
#else
	if (path != _T("/") && path.Last() == '/')
		path.RemoveLast();

	const wxCharBuffer s = path.fn_str();

	m_dir = opendir(s);
	if (!m_dir)
		return false;

	const wxCharBuffer p = path.fn_str();
	const int len = strlen(p);
	m_raw_path = new char[len + 2048 + 2];
	m_buffer_length = len + 2048 + 2;
	strcpy(m_raw_path, p);
	if (len > 1)
	{
		m_raw_path[len] = '/';
		m_file_part = m_raw_path + len + 1;
	}
	else
		m_file_part = m_raw_path + len;

	return true;
#endif
}
Example #5
0
int Mysql::Obtener_nombre_campos_y_valores(wxGrid *cuadro,wxString consulta){
	if(!mysql_query(sock,consulta.fn_str())){
		if((resultado =  mysql_store_result(sock))) {
			// Obtener el número de registros seleccionados:
			f = (int) mysql_num_rows(resultado);
			// Obtener el número de columnsa por fila:
			c = (int) mysql_num_fields(resultado);
			// Información sobre columnas usando mysql_fetch_field:
			if(c!=cuadro->GetNumberCols()){
				cuadro->AppendCols(c);//agregamos el numero de columnas x resultado
				cuadro->AppendRows(f);//agregamos el numero de filas x resultado
				for(int l = 0; l < c; l++) {
					columna = mysql_fetch_field(resultado);
					cuadro->SetColLabelValue( l,wxString::FromAscii(columna->name));
					cuadro->SetRowLabelValue(l,wxString::Format(wxT("%i"),l+1));
				}
				for(int k=0; k<f;k++){
					fila = mysql_fetch_row(resultado);
					for(int j = 0 ; j < c ; j++){
						cuadro->SetCellValue(k,j,wxString::FromAscii(fila[j]));
					}
				}
			}
		}
		else{
			return 0;
		}
		return 1;
	}
	else{
		mysql_close(sock);
		return 0;
	}
	
}
Example #6
0
wxString CLocalFileSystem::GetSymbolicLinkTarget(wxString const& path)
{
	wxString target;

#ifdef __WXMSW__
	HANDLE hFile = CreateFile(path, FILE_READ_ATTRIBUTES | FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (hFile != INVALID_HANDLE_VALUE) {
		DWORD const size = 1024;
		wxChar out[size];
		DWORD ret = GetFinalPathNameByHandle(hFile, out, size, 0);
		if (ret > 0 && ret < size) {
			target = out;
		}
		CloseHandle(hFile);
	}
#else
	size_t const size = 1024;
	char out[size];

	const wxCharBuffer p = path.fn_str();
	ssize_t res = readlink(static_cast<char const*>(p), out, size);
	if( res > 0 && static_cast<size_t>(res) < size ) {
		out[res] = 0;
		target = wxString(out, *wxConvFileName);
	}
#endif
	return target;
}
Example #7
0
void wxSingleInstanceCheckerImpl::Unlock()
{
    if ( m_fdLock != -1 )
    {
        if ( unlink(m_nameLock.fn_str()) != 0 )
        {
            wxLogSysError(_("Failed to remove lock file '%s'"),
                          m_nameLock.c_str());
        }

        if ( wxLockFile(m_fdLock, UNLOCK) != 0 )
        {
            wxLogSysError(_("Failed to unlock lock file '%s'"),
                          m_nameLock.c_str());
        }

        if ( close(m_fdLock) != 0 )
        {
            wxLogSysError(_("Failed to close lock file '%s'"),
                          m_nameLock.c_str());
        }
    }

    m_pidLocker = 0;
}
Example #8
0
bool MPQFile::exists(wxString filename)
{
	if( useLocalFiles ) {
		wxString fn1 = wxGetCwd()+SLASH+wxT("Import")+SLASH;
		wxString fn2 = fn1;
		wxString fn3 = gamePath;
		fn1.Append(filename);
		fn2.Append(filename.AfterLast(SLASH));
		fn3.Append(filename);

		wxString fns[] = { fn1, fn2, fn3 };
		for(size_t i=0; i<WXSIZEOF(fns); i++) {
			wxString fn = fns[i];
			if (wxFile::Exists(fn))
				return true;
		}
	}

	for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end();++i)
	{
		HANDLE &mpq_a = *i->second;
#ifndef _MINGW
		if( SFileHasFile( mpq_a, filename.fn_str() ) )
#else
		if( SFileHasFile( mpq_a, filename.char_str() ) )
#endif
			return true;
	}

	return false;
}
Example #9
0
wxString MPQFile::getArchive(wxString filename)
{
	if( useLocalFiles ) {
		wxString fn1 = wxGetCwd()+SLASH+wxT("Import")+SLASH;
		wxString fn2 = fn1;
		wxString fn3 = gamePath;
		fn1.Append(filename);
		fn2.Append(filename.AfterLast(SLASH));
		fn3.Append(filename);

		wxString fns[] = { fn1, fn2, fn3 };
		for(size_t i=0; i<WXSIZEOF(fns); i++) {
			wxString fn = fns[i];
			if (wxFile::Exists(fn)) {
				return fn;
			}
		}
	}

	for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end();++i)
	{
		HANDLE &mpq_a = *i->second;
		HANDLE fh;
#ifndef _MINGW
		if( !SFileOpenFileEx( mpq_a, filename.fn_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#else
		if( !SFileOpenFileEx( mpq_a, filename.char_str(), SFILE_OPEN_PATCHED_FILE, &fh ) )
#endif
			continue;

		return i->first;
	}

	return wxT("unknown");
}
Example #10
0
bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
{
#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
    // the case to "char *" is needed for AIX 4.3
    wxStatfs_t fs;
    if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
    {
        wxLogSysError( wxT("Failed to get file system statistics") );

        return false;
    }

    // under Solaris we also have to use f_frsize field instead of f_bsize
    // which is in general a multiple of f_frsize
#ifdef HAVE_STATVFS
    wxDiskspaceSize_t blockSize = fs.f_frsize;
#else // HAVE_STATFS
    wxDiskspaceSize_t blockSize = fs.f_bsize;
#endif // HAVE_STATVFS/HAVE_STATFS

    if ( pTotal )
    {
        *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
    }

    if ( pFree )
    {
        *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
    }

    return true;
#else // !HAVE_STATFS && !HAVE_STATVFS
    return false;
#endif // HAVE_STATFS
}
Example #11
0
bool
SbAccessFilterPolicy::setPath(wxString path)
{
	struct apn_rule *rule;

	rule = getApnRule();
	if ((rule == NULL) || path.IsEmpty()){
		return (false);
	}

	startChange();
	if (rule->rule.sbaccess.path != NULL) {
		free(rule->rule.sbaccess.path);
		rule->rule.sbaccess.path = NULL;
		setModified();
	}

	if (path.Cmp(wxT("any")) != 0) {
		rule->rule.sbaccess.path = strdup(path.fn_str());
		setModified();
	}

	finishChange();
	return (true);
}
Example #12
0
// This form is deprecated
wxPrinterDC::wxPrinterDC(const wxString& driver_name,
                         const wxString& device_name,
                         const wxString& file,
                         bool interactive,
                         wxPrintOrientation orientation)
{
    m_isInteractive = interactive;

    if ( !file.empty() )
        m_printData.SetFilename(file);

#if wxUSE_COMMON_DIALOGS
    if ( interactive )
    {
        PRINTDLG pd;

        pd.lStructSize = sizeof( PRINTDLG );
        pd.hwndOwner = (HWND) NULL;
        pd.hDevMode = (HANDLE)NULL;
        pd.hDevNames = (HANDLE)NULL;
        pd.Flags = PD_RETURNDC | PD_NOSELECTION | PD_NOPAGENUMS;
        pd.nFromPage = 0;
        pd.nToPage = 0;
        pd.nMinPage = 0;
        pd.nMaxPage = 0;
        pd.nCopies = 1;
        pd.hInstance = (HINSTANCE)NULL;

        m_ok = PrintDlg( &pd ) != 0;
        if ( m_ok )
        {
            m_hDC = (WXHDC) pd.hDC;
        }
    }
    else
#endif // wxUSE_COMMON_DIALOGS
    {
        if ( !driver_name.empty() && !device_name.empty() && !file.empty() )
        {
            m_hDC = (WXHDC) CreateDC(driver_name.t_str(),
                                     device_name.t_str(),
                                     file.fn_str(),
                                     NULL);
        }
        else // we don't have all parameters, ask the user
        {
            wxPrintData printData;
            printData.SetOrientation(orientation);
            m_hDC = wxGetPrinterDC(printData);
        }

        m_ok = m_hDC ? true: false;

        // as we created it, we must delete it as well
        m_bOwnsDC = true;
    }

    Init();
}
Example #13
0
void wxDirDialog::SetPath(const wxString& dir)
{
    if (wxDirExists(dir))
    {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(m_widget),
                                            dir.fn_str());
    }
}
Example #14
0
bool wxRemoveFile(const wxString& file)
{
#if defined(__VISUALC__) \
 || defined(__BORLANDC__) \
 || defined(__GNUWIN32__)
    int res = wxRemove(file);
#elif defined(__WXMAC__)
    int res = unlink(file.fn_str());
#else
    int res = unlink(file.fn_str());
#endif
    if ( res )
    {
        wxLogSysError(_("File '%s' couldn't be removed"), file);
    }
    return res == 0;
}
bool CreateHardLink(const wxString &oldpath, const wxString &newpath) {
	wxDynamicLibrary kernel32(_T("kernel32.dll"));

	void *CreateHardLinkFun = kernel32.GetSymbolAorW(_T("CreateHardLink"));

	if(CreateHardLinkFun == NULL) {
		// we are working with Windows 95 family
		return false;
	}
	else {
		// windows NT upwards :-)
		return ((BOOL (WINAPI *)(
  			  LPCTSTR lpFileName,
			  LPCTSTR lpExistingFileName,
			  LPSECURITY_ATTRIBUTES lpSecurityAttributes
			) ) CreateHardLinkFun)(newpath.fn_str(), oldpath.fn_str(), NULL) == TRUE;
	}
}
Example #16
0
wxDirDialog::wxDirDialog(wxWindow* parent,
                         const wxString& title,
                         const wxString& defaultPath,
                         long style,
                         const wxPoint& pos,
                         const wxSize& WXUNUSED(sz),
                         const wxString& WXUNUSED(name))
{
    m_message = title;

    parent = GetParentForModalDialog(parent, style);

    if (!PreCreation(parent, pos, wxDefaultSize) ||
        !CreateBase(parent, wxID_ANY, pos, wxDefaultSize, style,
                wxDefaultValidator, wxT("dirdialog")))
    {
        wxFAIL_MSG( wxT("wxDirDialog creation failed") );
        return;
    }

    GtkWindow* gtk_parent = NULL;
    if (parent)
        gtk_parent = GTK_WINDOW( gtk_widget_get_toplevel(parent->m_widget) );

    m_widget = gtk_file_chooser_dialog_new(
                   wxGTK_CONV(m_message),
                   gtk_parent,
                   GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
                   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                   GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                   NULL);
    g_object_ref(m_widget);

    gtk_dialog_set_default_response(GTK_DIALOG(m_widget), GTK_RESPONSE_ACCEPT);

    // gtk_widget_hide_on_delete is used here to avoid that Gtk automatically destroys
    // the dialog when the user press ESC on the dialog: in that case a second call to
    // ShowModal() would result in a bunch of Gtk-CRITICAL errors...
    g_signal_connect (G_OBJECT(m_widget),
                    "delete_event",
                    G_CALLBACK (gtk_widget_hide_on_delete),
                    (gpointer)this);

    // local-only property could be set to false to allow non-local files to be loaded.
    // In that case get/set_uri(s) should be used instead of get/set_filename(s) everywhere
    // and the GtkFileChooserDialog should probably also be created with a backend,
    // e.g. "gnome-vfs", "default", ... (gtk_file_chooser_dialog_new_with_backend).
    // Currently local-only is kept as the default - true:
    // gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(m_widget), true);

    g_signal_connect (m_widget, "response",
        G_CALLBACK (gtk_dirdialog_response_callback), this);

    if ( !defaultPath.empty() )
        gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(m_widget),
                defaultPath.fn_str() );
}
Example #17
0
int Mysql::Seleccionar_db(wxString db){
	if(mysql_select_db(sock, db.fn_str())){
		//Error al seleccionar la DB
		return 0;
	}
	else{
		return 1;
	}
}
bool IsSymLink(const wxString &filename) {
	struct stat st;

	if(lstat(filename.fn_str(), &st) == 0) {
		return S_ISLNK(st.st_mode) ? true : false;
	}
	else {
		return false;
	}
}
Example #19
0
Status_e FileText::writeStringInFile(wxFile& file, wxString const& str)
{
    uint8_t sizeStr = strlen(str.fn_str());

    //Écriture de la taille du texte.
    if(file.Write(&sizeStr, sizeof sizeStr) != sizeof sizeStr)
        return STATUS_FILE_WRITE_ERROR;

    //Écriture du texte.
    if(!file.Write(str))
        return STATUS_FILE_WRITE_ERROR;

    return STATUS_SUCCESS;
}
Example #20
0
bool wxSetWorkingDirectory(const wxString& d)
{
    bool success = false;
#if defined(__UNIX__) || defined(__WXMAC__)
    success = (chdir(d.fn_str()) == 0);
#elif defined(__WINDOWS__)
    success = (SetCurrentDirectory(d.t_str()) != 0);
#endif
    if ( !success )
    {
       wxLogSysError(_("Could not set current working directory"));
    }
    return success;
}
Example #21
0
bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
{
#if defined(__VMS__)
    return false; //to be changed since rmdir exists in VMS7.x
#else
    if ( wxRmDir(dir.fn_str()) != 0 )
    {
        wxLogSysError(_("Directory '%s' couldn't be deleted"), dir);
        return false;
    }

    return true;
#endif
}
Example #22
0
void wxFileHistory::AddFileToHistory(const wxString& file)
{
    wxFileHistoryBase::AddFileToHistory(file);

#ifdef __WXGTK210__
    const wxString fullPath = wxFileName(file).GetFullPath();
    if ( !gtk_check_version(2,10,0) )
    {
        wxGtkString uri(g_filename_to_uri(fullPath.fn_str(), NULL, NULL));

        if ( uri )
            gtk_recent_manager_add_item(gtk_recent_manager_get_default(), uri);
    }
#endif
}
Example #23
0
// -------------------------------------------------------------------------------- //
bool guSetFileMode( const wxString &filepath, int mode, bool adding )
{
    int m = mode;
    if( adding )
    {
        m |= guGetFileMode( filepath );
    }

    if( chmod( ( const char * ) filepath.fn_str(), mode ) == -1 )
    {
        guLogError( wxT( "Failed to set file permission for '%s'"), filepath.c_str() );
        return false;
    }
    return true;
}
Example #24
0
FitsFname::FitsFname(const wxString& path, bool create, bool clobber)
{
#ifdef __WINDOWS__

    if (create)
    {
        if (!clobber && wxFileExists(path))
        {
            m_str = new char[1];
            *m_str = 0;
            return;
        }

        int fd = wxOpen(path, O_BINARY | O_WRONLY | O_CREAT, wxS_DEFAULT);
        wxClose(fd);
    }

    // use the short DOS 8.3 path name to avoid problems converting UTF-16 filenames to the ANSI filenames expected by CFITTSIO

    DWORD shortlen = GetShortPathNameW(path.wc_str(), 0, 0);

    if (shortlen)
    {
        LPWSTR shortpath = new WCHAR[shortlen];
        GetShortPathNameW(path.wc_str(), shortpath, shortlen);
        int slen = WideCharToMultiByte(CP_OEMCP, WC_NO_BEST_FIT_CHARS, shortpath, shortlen, 0, 0, 0, 0);
        m_str = new char[slen + 1];
        char *str = m_str;
        if (create)
            *str++ = '!';
        WideCharToMultiByte(CP_OEMCP, WC_NO_BEST_FIT_CHARS, shortpath, shortlen, str, slen, 0, 0);
        delete[] shortpath;
    }
    else
    {
        m_str = new char[1];
        *m_str = 0;
    }

#else // __WINDOWS__

    if (clobber)
        m_str = (wxT("!") + path).fn_str();
    else
        m_str = path.fn_str();

#endif // __WINDOWS__
}
Example #25
0
// -------------------------------------------------------------------------------- //
int guGetFileMode( const wxString &filepath )
{
    mode_t mode;
    wxStructStat st;
    if( !filepath.IsEmpty() && stat( ( const char * ) filepath.fn_str(), &st ) == 0 )
    {
        mode = st.st_mode;
    }
    else
    {
        mode_t mask = umask(0777);
        mode = 0666 & ~mask;
        umask(mask);
    }
    return mode;
}
Example #26
0
bool
SbAccessFilterPolicy::setSubjectKey(wxString key)
{
	struct apn_rule *rule;

	rule = getApnRule();
	if (rule == NULL) {
		return (false);
	}

	startChange();
	PolicyUtils::cleanSubject(&rule->rule.sbaccess.cs);

	rule->rule.sbaccess.cs.type = APN_CS_KEY;
	rule->rule.sbaccess.cs.value.keyid = strdup(key.fn_str());

	setModified();
	finishChange();

	return (true);
}
Example #27
0
wxFontInstance::wxFontInstance(float ptSize, bool aa,
                               const wxString& filename)
    : wxFontInstanceBase(ptSize, aa)
{
    // NB: DFB's fract_height value is 32bit integer with the last 6 bit
    //     representing fractional value, hence the multiplication by 64;
    //     1pt=1/72inch, hence "/ 72"
    int pixSize = int(ptSize * wxGetDisplayPPI().y * 64 / 72);

    DFBFontDescription desc;
    desc.flags = (DFBFontDescriptionFlags)(
                    DFDESC_ATTRIBUTES | DFDESC_FRACT_HEIGHT);
    desc.attributes = aa ? DFFA_NONE : DFFA_MONOCHROME;
    desc.fract_height = pixSize;

    if ( filename == BUILTIN_DFB_FONT_FILENAME )
        m_font = wxIDirectFB::Get()->CreateFont(NULL, &desc);
    else
        m_font = wxIDirectFB::Get()->CreateFont(filename.fn_str(), &desc);

    wxASSERT_MSG( m_font, "cannot create font instance" );
}
Example #28
0
static void
setup(void)
{
	ContextAppPolicy	*app;

	fail_if(rule     != NULL, "apn rule already exists @ setup().");
	fail_if(observer != NULL, "observer already exists @ setup().");
	fail_if(policy   != NULL, "Policy already exists @ setup().");

	app = new ContextAppPolicy(NULL, NULL);
	FAIL_IFZERO(app, "Couldn't create ContextAppPolicy.");

	initName = wxT("/usr/bin/test");
	rule = createApnRule(initName.fn_str());
	FAIL_IFZERO(rule, "Couldn't create apn filter rule.");

	policy = new ContextFilterPolicy(app, rule);
	FAIL_IFZERO(policy, "Couldn't create ContextFilterPolicy.");

	observer = new PolicyObserver(policy);
	FAIL_IFZERO(observer, "Couldn't create observer.");
}
Example #29
0
bool wxDIB::Load(const wxString& filename)
{
#ifdef __WXWINCE__
    m_handle = SHLoadDIBitmap(filename);
#else // !__WXWINCE__
    m_handle = (HBITMAP)::LoadImage
                         (
                            wxGetInstance(),
                            filename.fn_str(),
                            IMAGE_BITMAP,
                            0, 0, // don't specify the size
                            LR_CREATEDIBSECTION | LR_LOADFROMFILE
                         );
#endif // __WXWINCE__

    if ( !m_handle )
    {
        wxLogLastError(wxT("Loading DIB from file"));

        return false;
    }

    return true;
}
Example #30
0
bool wxMakeMetafilePlaceable(const wxString& filename, int x1, int y1, int x2, int y2, float scale, bool useOriginAndExtent)
{
    // I'm not sure if this is the correct way of suggesting a scale
    // to the client application, but it's the only way I can find.
    int unitsPerInch = (int)(576/scale);

    mfPLACEABLEHEADER header;
    header.key = 0x9AC6CDD7L;
    header.hmf = 0;
    header.bbox.left = (int)(x1);
    header.bbox.top = (int)(y1);
    header.bbox.right = (int)(x2);
    header.bbox.bottom = (int)(y2);
    header.inch = unitsPerInch;
    header.reserved = 0;

    // Calculate checksum
    WORD *p;
    mfPLACEABLEHEADER *pMFHead = &header;
    for (p =(WORD *)pMFHead,pMFHead -> checksum = 0;
            p < (WORD *)&pMFHead ->checksum; ++p)
        pMFHead ->checksum ^= *p;

    FILE *fd = wxFopen(filename.fn_str(), wxT("rb"));
    if (!fd) return false;

    wxString tempFileBuf = wxFileName::CreateTempFileName(wxT("mf"));
    if (tempFileBuf.empty())
        return false;

    FILE *fHandle = wxFopen(tempFileBuf.fn_str(), wxT("wb"));
    if (!fHandle)
        return false;
    fwrite((void *)&header, sizeof(unsigned char), sizeof(mfPLACEABLEHEADER), fHandle);

    // Calculate origin and extent
    int originX = x1;
    int originY = y1;
    int extentX = x2 - x1;
    int extentY = (y2 - y1);

    // Read metafile header and write
    METAHEADER metaHeader;
    fread((void *)&metaHeader, sizeof(unsigned char), sizeof(metaHeader), fd);

    if (useOriginAndExtent)
        metaHeader.mtSize += 15;
    else
        metaHeader.mtSize += 5;

    fwrite((void *)&metaHeader, sizeof(unsigned char), sizeof(metaHeader), fHandle);

    // Write SetMapMode, SetWindowOrigin and SetWindowExt records
    char modeBuffer[8];
    char originBuffer[10];
    char extentBuffer[10];
    METARECORD *modeRecord = (METARECORD *)&modeBuffer;

    METARECORD *originRecord = (METARECORD *)&originBuffer;
    METARECORD *extentRecord = (METARECORD *)&extentBuffer;

    modeRecord->rdSize = 4;
    modeRecord->rdFunction = META_SETMAPMODE;
    modeRecord->rdParm[0] = MM_ANISOTROPIC;

    originRecord->rdSize = 5;
    originRecord->rdFunction = META_SETWINDOWORG;
    originRecord->rdParm[0] = originY;
    originRecord->rdParm[1] = originX;

    extentRecord->rdSize = 5;
    extentRecord->rdFunction = META_SETWINDOWEXT;
    extentRecord->rdParm[0] = extentY;
    extentRecord->rdParm[1] = extentX;

    fwrite((void *)modeBuffer, sizeof(char), 8, fHandle);

    if (useOriginAndExtent)
    {
        fwrite((void *)originBuffer, sizeof(char), 10, fHandle);
        fwrite((void *)extentBuffer, sizeof(char), 10, fHandle);
    }

    int ch = -2;
    while (ch != EOF)
    {
        ch = getc(fd);
        if (ch != EOF)
        {
            putc(ch, fHandle);
        }
    }
    fclose(fHandle);
    fclose(fd);
    wxRemoveFile(filename);
    wxCopyFile(tempFileBuf, filename);
    wxRemoveFile(tempFileBuf);
    return true;
}